Subversion Repositories HomeAutomation

Rev

Rev 1033 | Rev 1122 | Go to most recent revision | Only display areas with differences | Regard whitespace | Details | Blame | Last modification | View Log | SVN | RSS feed

Rev 1033 Rev 1036
1
/***************************************************************************
1
/***************************************************************************
2
 *  Copyright (C) December 6, 2008 by Mattias Runge               *
2
 *  Copyright (C) December 6, 2008 by Mattias Runge               *
3
 *  mattias@runge.se                           *
3
 *  mattias@runge.se                           *
4
 *  asyncsocket.cpp                      *
4
 *  asyncsocket.cpp                      *
5
 *                                     *
5
 *                                     *
6
 *  This program is free software; you can redistribute it and/or modify *
6
 *  This program is free software; you can redistribute it and/or modify *
7
 *  it under the terms of the GNU General Public License as published by *
7
 *  it under the terms of the GNU General Public License as published by *
8
 *  the Free Software Foundation; either version 2 of the License, or   *
8
 *  the Free Software Foundation; either version 2 of the License, or   *
9
 *  (at your option) any later version.                  *
9
 *  (at your option) any later version.                  *
10
 *                                     *
10
 *                                     *
11
 *  This program is distributed in the hope that it will be useful,    *
11
 *  This program is distributed in the hope that it will be useful,    *
12
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of    *
12
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of    *
13
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the     *
13
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the     *
14
 *  GNU General Public License for more details.             *
14
 *  GNU General Public License for more details.             *
15
 *                                     *
15
 *                                     *
16
 *  You should have received a copy of the GNU General Public License   *
16
 *  You should have received a copy of the GNU General Public License   *
17
 *  along with this program; if not, write to the             *
17
 *  along with this program; if not, write to the             *
18
 *  Free Software Foundation, Inc.,                    *
18
 *  Free Software Foundation, Inc.,                    *
19
 *  59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.       *
19
 *  59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.       *
20
 ***************************************************************************/
20
 ***************************************************************************/
21
 
21
 
22
#include "socketeventcallback.h"
22
#include "socketeventcallback.h"
23
 
23
 
24
 
24
 
25
#include "asyncsocket.h"
25
#include "asyncsocket.h"
26
 
26
 
27
int socketCount = 1;
27
int socketCount = 1;
28
 
28
 
29
AsyncSocket::AsyncSocket()
29
AsyncSocket::AsyncSocket()
30
{
30
{
31
    myId = socketCount++;
31
    myId = socketCount++;
32
    mySocket = -1;
32
    mySocket = -1;
33
    myReconnectTimeout = 0;
33
    myReconnectTimeout = 0;
34
    myForceReconnect = false;
34
    myForceReconnect = false;
35
    myEventCallback = NULL;
35
    myEventCallback = NULL;
36
}
36
}
37
 
37
 
38
AsyncSocket::~AsyncSocket()
38
AsyncSocket::~AsyncSocket()
39
{
39
{
40
    stop();
40
    stop();
41
    silentClose();
41
    silentClose();
42
}
42
}
43
 
43
 
44
void AsyncSocket::run()
44
void AsyncSocket::run()
45
{
45
{
46
    // If connection is already up then we should not connect again
46
    // If connection is already up then we should not connect again
47
    if (!isConnected())
47
    if (!isConnected())
48
    {
48
    {
49
        // If we have choosen to not use automatic reconnect do not start reconnect loop
49
        // If we have choosen to not use automatic reconnect do not start reconnect loop
50
        if (myReconnectTimeout == 0)
50
        if (myReconnectTimeout == 0)
51
        {
51
        {
52
            // Connect to somewhere
52
            // Connect to somewhere
53
            connect();
53
            connect();
54
        }
54
        }
55
        else
55
        else
56
        {
56
        {
57
            // Start the reconnect loop
57
            // Start the reconnect loop
58
            reconnectLoop();
58
            reconnectLoop();
59
        }
59
        }
60
    }
60
    }
61
 
61
 
62
    bool loop = true;
62
    bool loop = true;
63
    try
63
    try
64
    {
64
    {
65
        while (loop)
65
        while (loop)
66
        {
66
        {
67
            // If we have triggered a forced reconnect do it here
67
            // If we have triggered a forced reconnect do it here
68
            if (myForceReconnect)
68
            if (myForceReconnect)
69
            {
69
            {
70
                myForceReconnect = false;
70
                myForceReconnect = false;
71
                reconnectLoop();
71
                reconnectLoop();
72
            }
72
            }
73
 
73
 
74
            // Receive data
74
            // Receive data
75
            loop = receiveData();
75
            loop = receiveData();
76
        }
76
        }
77
    }
77
    }
78
    catch (SocketException *e)
78
    catch (SocketException *e)
79
    {
79
    {
80
        // Something bad happend and we can not continue
80
        // Something bad happend and we can not continue
81
        eventAdd(SocketEvent::TYPE_CONNECTION_DIED, e->getDescription());
81
        eventAdd(SocketEvent::TYPE_CONNECTION_DIED, e->getDescription());
82
    }
82
    }
83
 
83
 
84
    // Clean up socket if we would want to restart
84
    // Clean up socket if we would want to restart
85
    silentClose();
85
    silentClose();
86
}
86
}
87
 
87
 
88
bool AsyncSocket::receiveData()
88
bool AsyncSocket::receiveData()
89
{
89
{
90
    char buffer[MAXBUFFER + 1];
90
    char buffer[MAXBUFFER + 1];
91
    memset(buffer, 0, MAXBUFFER + 1);
91
    memset(buffer, 0, MAXBUFFER + 1);
92
 
92
 
93
    int status = ::recv(mySocket, buffer, MAXBUFFER, 0);
93
    int status = ::recv(mySocket, buffer, MAXBUFFER, 0);
94
 
94
 
95
    if (status == -1)
95
    if (status == -1)
96
    {
96
    {
97
        switch (errno)
97
        switch (errno)
98
        {
98
        {
99
            case EAGAIN:
99
            case EAGAIN:
100
            throw new SocketException("The socket is marked non-blocking and the receive operation would block, or a receive timeout had been set and the timeout expired before data was received.");
100
            throw new SocketException("The socket is marked non-blocking and the receive operation would block, or a receive timeout had been set and the timeout expired before data was received.");
101
 
101
 
102
            case EBADF:
102
            case EBADF:
103
            throw new SocketException("The argument s is an invalid descriptor.");
103
            throw new SocketException("The argument s is an invalid descriptor.");
104
 
104
 
105
            case ECONNREFUSED:
105
            case ECONNREFUSED:
106
            throw new SocketException("A remote host refused to allow the network connection (typically because it is not running the requested service).");
106
            throw new SocketException("A remote host refused to allow the network connection (typically because it is not running the requested service).");
107
 
107
 
108
            case EFAULT:
108
            case EFAULT:
109
            throw new SocketException("The receive buffer pointer(s) point outside the process's address space.");
109
            throw new SocketException("The receive buffer pointer(s) point outside the process's address space.");
110
 
110
 
111
            case EINTR:
111
            case EINTR:
112
            throw new SocketException("The receive was interrupted by delivery of a signal before any data were available; see signal(7).");
112
            throw new SocketException("The receive was interrupted by delivery of a signal before any data were available; see signal(7).");
113
 
113
 
114
            case EINVAL:
114
            case EINVAL:
115
            throw new SocketException("Invalid argument passed.");
115
            throw new SocketException("Invalid argument passed.");
116
 
116
 
117
            case ENOMEM:
117
            case ENOMEM:
118
            throw new SocketException("Could not allocate memory for recvmsg().");
118
            throw new SocketException("Could not allocate memory for recvmsg().");
119
 
119
 
120
            case ENOTCONN:
120
            case ENOTCONN:
121
            throw new SocketException("The socket is associated with a connection-oriented protocol and has not been connected (see connect(2) and accept(2)).");
121
            throw new SocketException("The socket is associated with a connection-oriented protocol and has not been connected (see connect(2) and accept(2)).");
122
 
122
 
123
            case ENOTSOCK:
123
            case ENOTSOCK:
124
            throw new SocketException("The argument s does not refer to a socket.");
124
            throw new SocketException("The argument s does not refer to a socket.");
125
 
125
 
126
            case ECONNRESET:
126
            case ECONNRESET:
127
            eventAdd(SocketEvent::TYPE_CONNECTION_RESET);
127
            eventAdd(SocketEvent::TYPE_CONNECTION_RESET);
128
 
128
 
129
            // If we have automatic reconnect we want to start it now
129
            // If we have automatic reconnect we want to start it now
130
            if (myReconnectTimeout == 0)
130
            if (myReconnectTimeout == 0)
131
            {
131
            {
132
                reconnectLoop();
132
                reconnectLoop();
133
            }
133
            }
134
            else
134
            else
135
            {
135
            {
136
                // Otherwise we would like to end the main loop
136
                // Otherwise we would like to end the main loop
137
                return false;
137
                return false;
138
            }
138
            }
139
            break;
139
            break;
140
 
140
 
141
            default:
141
            default:
142
            throw new SocketException("Unknow exception: " + itos(errno));
142
            throw new SocketException("Unknow exception: " + itos(errno));
143
            break;
143
            break;
144
        }
144
        }
145
    }
145
    }
146
    else if (status == 0)
146
    else if (status == 0)
147
    {
147
    {
148
        // Remote host have done a normal shutdown
148
        // Remote host have done a normal shutdown
149
        eventAdd(SocketEvent::TYPE_CONNECTION_CLOSED);
149
        eventAdd(SocketEvent::TYPE_CONNECTION_CLOSED);
150
 
150
 
151
        if (myReconnectTimeout > 0)
151
        if (myReconnectTimeout > 0)
152
        {
152
        {
153
            reconnectLoop();
153
            reconnectLoop();
154
        }
154
        }
155
        else
155
        else
156
        {
156
        {
157
            return false;
157
            return false;
158
        }
158
        }
159
    }
159
    }
160
    else if (status > 0)
160
    else if (status > 0)
161
    {
161
    {
162
        // We have received data
162
        // We have received data
163
        eventAdd(SocketEvent::TYPE_DATA, buffer);
163
        eventAdd(SocketEvent::TYPE_DATA, buffer);
164
    }
164
    }
165
 
165
 
166
    return true;
166
    return true;
167
}
167
}
168
 
168
 
169
void AsyncSocket::silentClose()
169
void AsyncSocket::silentClose()
170
{
170
{
171
    if (mySocket != -1)
171
    if (mySocket != -1)
172
    {
172
    {
173
        ::close(mySocket);
173
        ::close(mySocket);
174
        mySocket = -1;
174
        mySocket = -1;
175
    }
175
    }
176
}
176
}
177
 
177
 
178
void AsyncSocket::close()
178
void AsyncSocket::close()
179
{
179
{
180
    silentClose();
180
    silentClose();
181
    eventAdd(SocketEvent::TYPE_CONNECTION_CLOSED);
181
    eventAdd(SocketEvent::TYPE_CONNECTION_CLOSED);
182
}
182
}
183
 
183
 
184
void AsyncSocket::reconnectLoop()
184
void AsyncSocket::reconnectLoop()
185
{
185
{
186
    while (true)
186
    while (true)
187
    {
187
    {
188
        try
188
        try
189
        {
189
        {
190
            connect();
190
            connect();
191
            return;
191
            return;
192
        }
192
        }
193
        catch (SocketException *e)
193
        catch (SocketException *e)
194
        {
194
        {
195
            eventAdd(SocketEvent::TYPE_CONNECTION_FAILED, e->getDescription());
195
            eventAdd(SocketEvent::TYPE_CONNECTION_FAILED, e->getDescription());
196
            eventAdd(SocketEvent::TYPE_WAITING_RECONNECT);
196
            eventAdd(SocketEvent::TYPE_WAITING_RECONNECT);
197
            sleep(myReconnectTimeout);
197
            sleep(myReconnectTimeout);
198
        }
198
        }
199
    }
199
    }
200
}
200
}
201
 
201
 
202
void AsyncSocket::create()
202
void AsyncSocket::create()
203
{
203
{
204
    silentClose();
204
    silentClose();
205
 
205
 
206
    mySocket = ::socket(AF_INET, SOCK_STREAM, 0);
206
    mySocket = ::socket(AF_INET, SOCK_STREAM, 0);
207
 
207
 
208
    int on = 1;
208
    int on = 1;
209
    int status = setsockopt(mySocket, SOL_SOCKET, SO_REUSEADDR, (const char*)&on, sizeof(on));
209
    int status = setsockopt(mySocket, SOL_SOCKET, SO_REUSEADDR, (const char*)&on, sizeof(on));
210
    if (status == -1)
210
    if (status == -1)
211
    {
211
    {
212
        silentClose();
212
        silentClose();
213
        throw new SocketException("Create:Reuseaddress: " + itos(errno));
213
        throw new SocketException("Create:Reuseaddress: " + itos(errno));
214
    }
214
    }
215
}
215
}
216
 
216
 
217
void AsyncSocket::startListen()
217
void AsyncSocket::startListen()
218
{
218
{
219
    create();
219
    create();
220
 
220
 
221
    myAddressStruct.sin_family = AF_INET;
221
    myAddressStruct.sin_family = AF_INET;
222
    myAddressStruct.sin_addr.s_addr = INADDR_ANY;
222
    myAddressStruct.sin_addr.s_addr = INADDR_ANY;
223
    myAddressStruct.sin_port = htons(myPort);
223
    myAddressStruct.sin_port = htons(myPort);
224
 
224
 
225
    int status = ::bind(mySocket, (struct sockaddr *)&myAddressStruct, sizeof(myAddressStruct));
225
    int status = ::bind(mySocket, (struct sockaddr *)&myAddressStruct, sizeof(myAddressStruct));
226
 
226
 
227
    if (status == -1)
227
    if (status == -1)
228
    {
228
    {
229
        silentClose();
229
        silentClose();
230
        switch (errno)
230
        switch (errno)
231
        {
231
        {
232
            case EACCES:
232
            case EACCES:
233
            throw new SocketException("The address is protected, and the user is not the superuser.");
233
            throw new SocketException("The address is protected, and the user is not the superuser.");
234
 
234
 
235
            case EADDRINUSE:
235
            case EADDRINUSE:
236
            throw new SocketException("The given address is already in use.");
236
            throw new SocketException("The given address is already in use.");
237
 
237
 
238
            case EBADF:
238
            case EBADF:
239
            throw new SocketException("sockfd is not a valid descriptor.");
239
            throw new SocketException("sockfd is not a valid descriptor.");
240
 
240
 
241
            case EINVAL:
241
            case EINVAL:
242
            throw new SocketException("The socket is already bound to an address.");
242
            throw new SocketException("The socket is already bound to an address.");
243
 
243
 
244
            case ENOTSOCK:
244
            case ENOTSOCK:
245
            throw new SocketException("sockfd is a descriptor for a file, not a socket.");
245
            throw new SocketException("sockfd is a descriptor for a file, not a socket.");
246
 
246
 
247
            //case EACCES:
247
            //case EACCES:
248
            //throw new SocketException("Search permission is denied on a component of the path prefix. (See also path_resolution(7).)");
248
            //throw new SocketException("Search permission is denied on a component of the path prefix. (See also path_resolution(7).)");
249
 
249
 
250
            case EADDRNOTAVAIL:
250
            case EADDRNOTAVAIL:
251
            throw new SocketException("A nonexistent interface was requested or the requested address was not local.");
251
            throw new SocketException("A nonexistent interface was requested or the requested address was not local.");
252
 
252
 
253
            case EFAULT:
253
            case EFAULT:
254
            throw new SocketException("addr points outside the user's accessible address space.");
254
            throw new SocketException("addr points outside the user's accessible address space.");
255
 
255
 
256
            //case EINVAL:
256
            //case EINVAL:
257
            //throw new SocketException("The addrlen is wrong, or the socket was not in the AF_UNIX family.");
257
            //throw new SocketException("The addrlen is wrong, or the socket was not in the AF_UNIX family.");
258
 
258
 
259
            case ELOOP:
259
            case ELOOP:
260
            throw new SocketException("Too many symbolic links were encountered in resolving addr.");
260
            throw new SocketException("Too many symbolic links were encountered in resolving addr.");
261
 
261
 
262
            case ENAMETOOLONG:
262
            case ENAMETOOLONG:
263
            throw new SocketException("addr is too long.");
263
            throw new SocketException("addr is too long.");
264
 
264
 
265
            case ENOENT:
265
            case ENOENT:
266
            throw new SocketException("The file does not exist.");
266
            throw new SocketException("The file does not exist.");
267
 
267
 
268
            case ENOMEM:
268
            case ENOMEM:
269
            throw new SocketException("Insufficient kernel memory was available.");
269
            throw new SocketException("Insufficient kernel memory was available.");
270
 
270
 
271
            case ENOTDIR:
271
            case ENOTDIR:
272
            throw new SocketException("A component of the path prefix is not a directory.");
272
            throw new SocketException("A component of the path prefix is not a directory.");
273
 
273
 
274
            case EROFS:
274
            case EROFS:
275
            throw new SocketException("The socket inode would reside on a read-only file system.");
275
            throw new SocketException("The socket inode would reside on a read-only file system.");
276
 
276
 
277
            default:
277
            default:
278
            throw new SocketException("Unknow exception: " + itos(errno));
278
            throw new SocketException("Unknow exception: " + itos(errno));
279
            break;
279
            break;
280
        }
280
        }
281
    }
281
    }
282
 
282
 
283
    status = ::listen(mySocket, MAXCONNECTIONS);
283
    status = ::listen(mySocket, MAXCONNECTIONS);
284
 
284
 
285
    if (status == -1)
285
    if (status == -1)
286
    {
286
    {
287
        silentClose();
287
        silentClose();
288
        switch (errno)
288
        switch (errno)
289
        {
289
        {
290
            case EADDRINUSE:
290
            case EADDRINUSE:
291
            throw new SocketException("Another socket is already listening on the same port.");
291
            throw new SocketException("Another socket is already listening on the same port.");
292
 
292
 
293
            case EBADF:
293
            case EBADF:
294
            throw new SocketException("The argument sockfd is not a valid descriptor.");
294
            throw new SocketException("The argument sockfd is not a valid descriptor.");
295
 
295
 
296
            case ENOTSOCK:
296
            case ENOTSOCK:
297
            throw new SocketException("The argument sockfd is not a socket.");
297
            throw new SocketException("The argument sockfd is not a socket.");
298
 
298
 
299
            case EOPNOTSUPP:
299
            case EOPNOTSUPP:
300
            throw new SocketException("The socket is not of a type that supports the listen() operation.");
300
            throw new SocketException("The socket is not of a type that supports the listen() operation.");
301
 
301
 
302
            default:
302
            default:
303
            throw new SocketException("Unknow exception: " + itos(errno));
303
            throw new SocketException("Unknow exception: " + itos(errno));
304
            break;
304
            break;
305
        }
305
        }
306
    }
306
    }
307
}
307
}
308
 
308
 
309
bool AsyncSocket::accept(AsyncSocket* newSocket)
309
bool AsyncSocket::accept(AsyncSocket* newSocket)
310
{
310
{
311
    int addr_length = sizeof(myAddressStruct);
311
    int addr_length = sizeof(myAddressStruct);
312
    int socket = ::accept(mySocket, (sockaddr*)&myAddressStruct, (socklen_t*)&addr_length);
312
    int socket = ::accept(mySocket, (sockaddr*)&myAddressStruct, (socklen_t*)&addr_length);
313
 
313
 
314
    if (socket > 0)
314
    if (socket > 0)
315
    {
315
    {
316
        newSocket->setSocket(socket);
316
        newSocket->setSocket(socket);
317
        return true;
317
        return true;
318
    }
318
    }
319
 
319
 
320
    return false;
320
    return false;
321
}
321
}
322
 
322
 
323
void AsyncSocket::connect()
323
void AsyncSocket::connect()
324
{
324
{
325
    eventAdd(SocketEvent::TYPE_CONNECTING);
325
    eventAdd(SocketEvent::TYPE_CONNECTING);
326
 
326
 
327
    create();
327
    create();
328
 
328
 
329
    memset(&myAddressStruct, 0, sizeof(myAddressStruct));
329
    memset(&myAddressStruct, 0, sizeof(myAddressStruct));
330
 
330
 
331
    myAddressStruct.sin_family = AF_INET;
331
    myAddressStruct.sin_family = AF_INET;
332
    myAddressStruct.sin_port = htons(myPort);
332
    myAddressStruct.sin_port = htons(myPort);
333
 
333
 
334
    struct hostent *hptr = gethostbyname(myAddress.c_str());
334
    struct hostent *hptr = gethostbyname(myAddress.c_str());
335
    if (hptr == NULL)
335
    if (hptr == NULL)
336
    {
336
    {
337
        silentClose();
337
        silentClose();
338
        throw new SocketException("Connect: Could not resolv ip address");
338
        throw new SocketException("Connect: Could not resolv ip address");
339
    }
339
    }
340
 
340
 
341
    memcpy(&myAddressStruct.sin_addr, hptr->h_addr, hptr->h_length);
341
    memcpy(&myAddressStruct.sin_addr, hptr->h_addr, hptr->h_length);
342
 
342
 
343
    int status = ::connect(mySocket, (sockaddr*)&myAddressStruct, sizeof(myAddressStruct));
343
    int status = ::connect(mySocket, (sockaddr*)&myAddressStruct, sizeof(myAddressStruct));
344
 
344
 
345
    if (status == -1)
345
    if (status == -1)
346
    {
346
    {
347
        silentClose();
347
        silentClose();
348
        switch (errno)
348
        switch (errno)
349
        {
349
        {
350
            case EACCES:
350
            case EACCES:
351
            throw new SocketException("For Unix domain sockets, which are identified by pathname: Write permission is denied on the socket file, or search per- mission is denied for one of the directories in the path prefix. (See also path_resolution(7).)");
351
            throw new SocketException("For Unix domain sockets, which are identified by pathname: Write permission is denied on the socket file, or search per- mission is denied for one of the directories in the path prefix. (See also path_resolution(7).)");
352
 
352
 
353
            case EPERM:
353
            case EPERM:
354
            throw new SocketException("The user tried to connect to a broadcast address without having the socket broadcast flag enabled or the connection request failed because of a local firewall rule.");
354
            throw new SocketException("The user tried to connect to a broadcast address without having the socket broadcast flag enabled or the connection request failed because of a local firewall rule.");
355
 
355
 
356
            case EADDRINUSE:
356
            case EADDRINUSE:
357
            throw new SocketException("Local address is already in use.");
357
            throw new SocketException("Local address is already in use.");
358
 
358
 
359
            case EAFNOSUPPORT:
359
            case EAFNOSUPPORT:
360
            throw new SocketException("The passed address didn't have the correct address family in its sa_family field.");
360
            throw new SocketException("The passed address didn't have the correct address family in its sa_family field.");
361
 
361
 
362
            case EAGAIN:
362
            case EAGAIN:
363
            throw new SocketException("No more free local ports or insufficient entries in the routing cache. For AF_INET see the net.ipv4.ip_local_port_range sysctl in ip(7) on how to increase the number of local ports.");
363
            throw new SocketException("No more free local ports or insufficient entries in the routing cache. For AF_INET see the net.ipv4.ip_local_port_range sysctl in ip(7) on how to increase the number of local ports.");
364
 
364
 
365
            case EALREADY:
365
            case EALREADY:
366
            throw new SocketException("The socket is non-blocking and a previous connection attempt has not yet been completed.");
366
            throw new SocketException("The socket is non-blocking and a previous connection attempt has not yet been completed.");
367
 
367
 
368
            case EBADF:
368
            case EBADF:
369
            throw new SocketException("The file descriptor is not a valid index in the descriptor table.");
369
            throw new SocketException("The file descriptor is not a valid index in the descriptor table.");
370
 
370
 
371
            case ECONNREFUSED:
371
            case ECONNREFUSED:
372
            throw new SocketException("No-one listening on the remote address.");
372
            throw new SocketException("No-one listening on the remote address.");
373
 
373
 
374
            case EFAULT:
374
            case EFAULT:
375
            throw new SocketException("The socket structure address is outside the user's address space.");
375
            throw new SocketException("The socket structure address is outside the user's address space.");
376
 
376
 
377
            case EINPROGRESS:
377
            case EINPROGRESS:
378
            throw new SocketException("The socket is non-blocking and the connection cannot be completed immediately. It is possible to select(2) or poll(2) for completion by selecting the socket for writing. After select(2) indicates writability, use getsockopt(2) to read the SO_ERROR option at level SOL_SOCKET to determine whether connect() completed successfully (SO_ERROR is zero) or unsuccessfully (SO_ERROR is one of the usual error codes listed here, explaining the reason for the failure).");
378
            throw new SocketException("The socket is non-blocking and the connection cannot be completed immediately. It is possible to select(2) or poll(2) for completion by selecting the socket for writing. After select(2) indicates writability, use getsockopt(2) to read the SO_ERROR option at level SOL_SOCKET to determine whether connect() completed successfully (SO_ERROR is zero) or unsuccessfully (SO_ERROR is one of the usual error codes listed here, explaining the reason for the failure).");
379
 
379
 
380
            case EINTR:
380
            case EINTR:
381
            throw new SocketException("The system call was interrupted by a signal that was caught; see signal(7).");
381
            throw new SocketException("The system call was interrupted by a signal that was caught; see signal(7).");
382
 
382
 
383
            case EISCONN:
383
            case EISCONN:
384
            throw new SocketException("The socket is already connected.");
384
            throw new SocketException("The socket is already connected.");
385
 
385
 
386
            case ENETUNREACH:
386
            case ENETUNREACH:
387
            throw new SocketException("Network is unreachable.");
387
            throw new SocketException("Network is unreachable.");
388
 
388
 
389
            case ENOTSOCK:
389
            case ENOTSOCK:
390
            throw new SocketException("The file descriptor is not associated with a socket.");
390
            throw new SocketException("The file descriptor is not associated with a socket.");
391
 
391
 
392
            case ETIMEDOUT:
392
            case ETIMEDOUT:
393
            throw new SocketException("Timeout while attempting connection. The server may be too busy to accept new connections. Note that for IP sockets the timeout may be very long when syncookies are enabled on the server.");
393
            throw new SocketException("Timeout while attempting connection. The server may be too busy to accept new connections. Note that for IP sockets the timeout may be very long when syncookies are enabled on the server.");
394
 
394
 
395
            default:
395
            default:
396
            throw new SocketException("Other errors may be generated by the underlying protocol modules. : " + itos(errno));
396
            throw new SocketException("Other errors may be generated by the underlying protocol modules. : " + itos(errno));
397
        }
397
        }
398
    }
398
    }
399
 
399
 
400
    eventAdd(SocketEvent::TYPE_CONNECTED);
400
    eventAdd(SocketEvent::TYPE_CONNECTED);
401
}
401
}
402
 
402
 
403
void AsyncSocket::sendData(string data)
403
void AsyncSocket::sendData(string data)
404
{
404
{
405
    mySendMutex.lock();
405
    mySendMutex.lock();
406
 
406
 
407
    int status = ::send(mySocket, data.c_str(), data.size(), 0);
407
    int status = ::send(mySocket, data.c_str(), data.size(), 0);
408
 
408
 
409
    mySendMutex.unlock();
409
    mySendMutex.unlock();
410
 
410
 
411
    Logger &log = Logger::getInstance();
411
    //Logger &log = Logger::getInstance();
412
    log.add("Sent: \"" + data + "\" status was " + itos(status) + "\n");
412
    //log.add("Sent: \"" + data + "\" status was " + itos(status) + "\n");
413
 
413
 
414
    if (status == -1)
414
    if (status == -1)
415
    {
415
    {
416
        switch (errno)
416
        switch (errno)
417
        {
417
        {
418
            case EACCES:
418
            case EACCES:
419
            throw new SocketException("(For Unix domain sockets, which are identified by pathname) Write permission is denied on the destination socket file, or search permission is denied for one of the directories the path prefix. (See path_resolution(7).)");
419
            throw new SocketException("(For Unix domain sockets, which are identified by pathname) Write permission is denied on the destination socket file, or search permission is denied for one of the directories the path prefix. (See path_resolution(7).)");
420
 
420
 
421
            case EAGAIN:
421
            case EAGAIN:
422
            throw new SocketException("The socket is marked non-blocking and the requested operation would block.");
422
            throw new SocketException("The socket is marked non-blocking and the requested operation would block.");
423
 
423
 
424
            case EBADF:
424
            case EBADF:
425
            throw new SocketException("An invalid descriptor was specified.");
425
            throw new SocketException("An invalid descriptor was specified.");
426
 
426
 
427
            case ECONNRESET:
427
            case ECONNRESET:
428
            throw new SocketException("Connection reset by peer.");
428
            throw new SocketException("Connection reset by peer.");
429
 
429
 
430
            case EDESTADDRREQ:
430
            case EDESTADDRREQ:
431
            throw new SocketException("The socket is not connection-mode, and no peer address is set.");
431
            throw new SocketException("The socket is not connection-mode, and no peer address is set.");
432
 
432
 
433
            case EFAULT:
433
            case EFAULT:
434
            throw new SocketException("An invalid user space address was specified for an argument.");
434
            throw new SocketException("An invalid user space address was specified for an argument.");
435
 
435
 
436
            case EINTR:
436
            case EINTR:
437
            throw new SocketException("A signal occurred before any data was transmitted; see signal(7).");
437
            throw new SocketException("A signal occurred before any data was transmitted; see signal(7).");
438
 
438
 
439
            case EINVAL:
439
            case EINVAL:
440
            throw new SocketException("1Invalid argument passed.");
440
            throw new SocketException("1Invalid argument passed.");
441
 
441
 
442
            case EISCONN:
442
            case EISCONN:
443
            throw new SocketException("The connection-mode socket was connected already but a recipient was specified. (Now either this error is returned, or the recipient specification is ignored.)");
443
            throw new SocketException("The connection-mode socket was connected already but a recipient was specified. (Now either this error is returned, or the recipient specification is ignored.)");
444
 
444
 
445
            case EMSGSIZE:
445
            case EMSGSIZE:
446
            throw new SocketException("The socket type requires that message be sent atomically, and the size of the message to be sent made this impossible.");
446
            throw new SocketException("The socket type requires that message be sent atomically, and the size of the message to be sent made this impossible.");
447
 
447
 
448
            case ENOBUFS:
448
            case ENOBUFS:
449
            throw new SocketException("The output queue for a network interface was full. This generally indicates that the interface has stopped sending, but may be caused by transient congestion. (Normally, this does not occur in Linux. Packets are just silently dropped when a device queue overflows.)");
449
            throw new SocketException("The output queue for a network interface was full. This generally indicates that the interface has stopped sending, but may be caused by transient congestion. (Normally, this does not occur in Linux. Packets are just silently dropped when a device queue overflows.)");
450
 
450
 
451
            case ENOMEM:
451
            case ENOMEM:
452
            throw new SocketException("No memory available.");
452
            throw new SocketException("No memory available.");
453
 
453
 
454
            case ENOTCONN:
454
            case ENOTCONN:
455
            throw new SocketException("The socket is not connected, and no target has been given.");
455
            throw new SocketException("The socket is not connected, and no target has been given.");
456
 
456
 
457
            case ENOTSOCK:
457
            case ENOTSOCK:
458
            throw new SocketException("The argument s is not a socket.");
458
            throw new SocketException("The argument s is not a socket.");
459
 
459
 
460
            case EOPNOTSUPP:
460
            case EOPNOTSUPP:
461
            throw new SocketException("Some bit in the flags argument is inappropriate for the socket type.");
461
            throw new SocketException("Some bit in the flags argument is inappropriate for the socket type.");
462
 
462
 
463
            case EPIPE:
463
            case EPIPE:
464
            throw new SocketException("The local end has been shut down on a connection oriented socket. In this case the process will also receive a SIGPIPE unless MSG_NOSIGNAL is set.");
464
            throw new SocketException("The local end has been shut down on a connection oriented socket. In this case the process will also receive a SIGPIPE unless MSG_NOSIGNAL is set.");
465
 
465
 
466
            default:
466
            default:
467
            throw new SocketException("Unknow exception: " + itos(errno));
467
            throw new SocketException("Unknow exception: " + itos(errno));
468
        }
468
        }
469
    }
469
    }
470
}
470
}
471
 
471
 
472
void AsyncSocket::eventAdd(unsigned int eventType)
472
void AsyncSocket::eventAdd(unsigned int eventType)
473
{
473
{
474
    eventAdd(eventType, "");
474
    eventAdd(eventType, "");
475
}
475
}
476
 
476
 
477
void AsyncSocket::eventAdd(unsigned int eventType, string eventData)
477
void AsyncSocket::eventAdd(unsigned int eventType, string eventData)
478
{
478
{
479
    SocketEvent socketEvent(eventType, eventData);
479
    SocketEvent socketEvent(eventType, eventData);
480
 
480
 
481
    if (myEventCallback == NULL)
481
    if (myEventCallback == NULL)
482
    {
482
    {
483
        myEventQueue.push(socketEvent);
483
        myEventQueue.push(socketEvent);
484
        myEventSemaphore.broadcast();
484
        myEventSemaphore.broadcast();
485
    }
485
    }
486
    else
486
    else
487
    {
487
    {
488
        myEventCallback->handleEvent(myId, socketEvent);
488
        myEventCallback->handleEvent(myId, socketEvent);
489
    }
489
    }
490
}
490
}
491
 
491
 
492
void AsyncSocket::eventSetCallback(SocketEventCallback* eventCallback)
492
void AsyncSocket::eventSetCallback(SocketEventCallback* eventCallback)
493
{
493
{
494
    myEventCallback = eventCallback;
494
    myEventCallback = eventCallback;
495
}
495
}
496
 
496