1 | /* $Id: tcp.cpp 2981 2007-06-01 16:01:28Z vboxsync $ */
|
---|
2 | /** @file
|
---|
3 | * innotek Portable Runtime - TCP/IP.
|
---|
4 | */
|
---|
5 |
|
---|
6 | /*
|
---|
7 | * Copyright (C) 2006-2007 innotek GmbH
|
---|
8 | *
|
---|
9 | * This file is part of VirtualBox Open Source Edition (OSE), as
|
---|
10 | * available from http://www.virtualbox.org. This file is free software;
|
---|
11 | * you can redistribute it and/or modify it under the terms of the GNU
|
---|
12 | * General Public License as published by the Free Software Foundation,
|
---|
13 | * in version 2 as it comes in the "COPYING" file of the VirtualBox OSE
|
---|
14 | * distribution. VirtualBox OSE is distributed in the hope that it will
|
---|
15 | * be useful, but WITHOUT ANY WARRANTY of any kind.
|
---|
16 | *
|
---|
17 | * If you received this file as part of a commercial VirtualBox
|
---|
18 | * distribution, then only the terms of your commercial VirtualBox
|
---|
19 | * license agreement apply instead of the previous paragraph.
|
---|
20 | */
|
---|
21 |
|
---|
22 |
|
---|
23 | /*******************************************************************************
|
---|
24 | * Header Files *
|
---|
25 | *******************************************************************************/
|
---|
26 | #ifdef __WIN__
|
---|
27 | #include <winsock.h>
|
---|
28 | #else /* !__WIN__ */
|
---|
29 | #include <errno.h>
|
---|
30 | #include <sys/stat.h>
|
---|
31 | #include <sys/socket.h>
|
---|
32 | #include <netinet/in.h>
|
---|
33 | #include <netinet/tcp.h>
|
---|
34 | #include <arpa/inet.h>
|
---|
35 | #include <sys/un.h>
|
---|
36 | #include <netdb.h>
|
---|
37 | #include <unistd.h>
|
---|
38 | #endif /* !__WIN__ */
|
---|
39 |
|
---|
40 | #include <iprt/tcp.h>
|
---|
41 | #include <iprt/thread.h>
|
---|
42 | #include <iprt/alloc.h>
|
---|
43 | #include <iprt/assert.h>
|
---|
44 | #include <iprt/asm.h>
|
---|
45 | #include <iprt/err.h>
|
---|
46 | #include <iprt/string.h>
|
---|
47 |
|
---|
48 |
|
---|
49 | /* non-standard linux stuff (it seems). */
|
---|
50 | #ifndef MSG_NOSIGNAL
|
---|
51 | # define MSG_NOSIGNAL 0
|
---|
52 | #endif
|
---|
53 | #ifndef SHUT_RDWR
|
---|
54 | # ifdef SD_BOTH
|
---|
55 | # define SHUT_RDWR SD_BOTH
|
---|
56 | # else
|
---|
57 | # define SHUT_RDWR 2
|
---|
58 | # endif
|
---|
59 | #endif
|
---|
60 |
|
---|
61 | /* fixup backlevel OSes. */
|
---|
62 | #if defined(__OS2__) || defined(__WIN__)
|
---|
63 | # define socklen_t int
|
---|
64 | #endif
|
---|
65 |
|
---|
66 |
|
---|
67 | /*******************************************************************************
|
---|
68 | * Defined Constants And Macros *
|
---|
69 | *******************************************************************************/
|
---|
70 | #define BACKLOG 10 /* how many pending connections queue will hold */
|
---|
71 |
|
---|
72 |
|
---|
73 | /*******************************************************************************
|
---|
74 | * Structures and Typedefs *
|
---|
75 | *******************************************************************************/
|
---|
76 | /**
|
---|
77 | * TCP Server state.
|
---|
78 | */
|
---|
79 | typedef enum RTTCPSERVERSTATE
|
---|
80 | {
|
---|
81 | /** Invalid. */
|
---|
82 | RTTCPSERVERSTATE_INVALID = 0,
|
---|
83 | /** Created. */
|
---|
84 | RTTCPSERVERSTATE_CREATED,
|
---|
85 | /** Listener thread is starting up. */
|
---|
86 | RTTCPSERVERSTATE_STARTING,
|
---|
87 | /** Accepting client connections. */
|
---|
88 | RTTCPSERVERSTATE_ACCEPTING,
|
---|
89 | /** Serving a client. */
|
---|
90 | RTTCPSERVERSTATE_SERVING,
|
---|
91 | /** Listener terminating. */
|
---|
92 | RTTCPSERVERSTATE_STOPPING,
|
---|
93 | /** Listener terminated. */
|
---|
94 | RTTCPSERVERSTATE_STOPPED,
|
---|
95 | /** Destroying signaling to the listener, listener will wait. */
|
---|
96 | RTTCPSERVERSTATE_SIGNALING,
|
---|
97 | /** Listener cleans up. */
|
---|
98 | RTTCPSERVERSTATE_DESTROYING,
|
---|
99 | /** Freed. */
|
---|
100 | RTTCPSERVERSTATE_FREED
|
---|
101 | } RTTCPSERVERSTATE;
|
---|
102 |
|
---|
103 | /*
|
---|
104 | * Internal representation of the TCP Server handle.
|
---|
105 | */
|
---|
106 | typedef struct RTTCPSERVER
|
---|
107 | {
|
---|
108 | /** The server state. */
|
---|
109 | RTTCPSERVERSTATE volatile enmState;
|
---|
110 | /** The server thread. */
|
---|
111 | RTTHREAD Thread;
|
---|
112 | /** The server socket. */
|
---|
113 | RTSOCKET volatile SockServer;
|
---|
114 | /** The socket to the client currently being serviced.
|
---|
115 | * This is NIL_RTSOCKET when no client is serviced. */
|
---|
116 | RTSOCKET volatile SockClient;
|
---|
117 | /** The connection function. */
|
---|
118 | PFNRTTCPSERVE pfnServe;
|
---|
119 | /** Argument to pfnServer. */
|
---|
120 | void *pvUser;
|
---|
121 | } RTTCPSERVER;
|
---|
122 |
|
---|
123 |
|
---|
124 | /*******************************************************************************
|
---|
125 | * Internal Functions *
|
---|
126 | *******************************************************************************/
|
---|
127 | static DECLCALLBACK(int) rtTcpServerThread(RTTHREAD ThreadSelf, void *pvServer);
|
---|
128 | static int rtTcpServerListen(PRTTCPSERVER pServer);
|
---|
129 | static void rcTcpServerListenCleanup(PRTTCPSERVER pServer);
|
---|
130 | static void rtTcpServerDestroyServerSock(RTSOCKET SockServer, const char *pszMsg);
|
---|
131 | static int rtTcpClose(RTSOCKET Sock, const char *pszMsg);
|
---|
132 |
|
---|
133 |
|
---|
134 |
|
---|
135 | /**
|
---|
136 | * Get the last error as an iprt status code.
|
---|
137 | * @returns iprt status code.
|
---|
138 | */
|
---|
139 | DECLINLINE(int) rtTcpError(void)
|
---|
140 | {
|
---|
141 | #ifdef __WIN__
|
---|
142 | return RTErrConvertFromWin32(WSAGetLastError());
|
---|
143 | #else
|
---|
144 | return RTErrConvertFromErrno(errno);
|
---|
145 | #endif
|
---|
146 | }
|
---|
147 |
|
---|
148 |
|
---|
149 | /**
|
---|
150 | * Atomicly updates a socket variable.
|
---|
151 | * @returns The old value.
|
---|
152 | * @param pSock The socket variable to update.
|
---|
153 | * @param Sock The new value.
|
---|
154 | */
|
---|
155 | DECLINLINE(RTSOCKET) rtTcpAtomicXchgSock(RTSOCKET volatile *pSock, const RTSOCKET Sock)
|
---|
156 | {
|
---|
157 | switch (sizeof(RTSOCKET))
|
---|
158 | {
|
---|
159 | case 4: return (RTSOCKET)ASMAtomicXchgS32((int32_t volatile *)pSock, (int32_t)Sock);
|
---|
160 | default:
|
---|
161 | AssertReleaseFailed();
|
---|
162 | return NIL_RTSOCKET;
|
---|
163 | }
|
---|
164 | }
|
---|
165 |
|
---|
166 |
|
---|
167 | /**
|
---|
168 | * Changes the TCP server state.
|
---|
169 | */
|
---|
170 | DECLINLINE(bool) rtTcpServerSetState(PRTTCPSERVER pServer, RTTCPSERVERSTATE enmStateNew, RTTCPSERVERSTATE enmStateOld)
|
---|
171 | {
|
---|
172 | bool fRc;
|
---|
173 | ASMAtomicCmpXchgSize(&pServer->enmState, enmStateNew, enmStateOld, fRc);
|
---|
174 | return fRc;
|
---|
175 | }
|
---|
176 |
|
---|
177 |
|
---|
178 | /**
|
---|
179 | * Create single connection at a time TCP Server in a separate thread.
|
---|
180 | *
|
---|
181 | * The thread will loop accepting connections and call pfnServe for
|
---|
182 | * each of the incoming connections in turn. The pfnServe function can
|
---|
183 | * return VERR_TCP_SERVER_STOP too terminate this loop. RTTcpServerDestroy()
|
---|
184 | * should be used to terminate the server.
|
---|
185 | *
|
---|
186 | * @returns iprt status code.
|
---|
187 | * @param pszAddress The address for creating a listening socket.
|
---|
188 | * If NULL or empty string the server is bound to all interfaces.
|
---|
189 | * @param uPort The port for creating a listening socket.
|
---|
190 | * @param enmType The thread type.
|
---|
191 | * @param pszThrdName The name of the worker thread.
|
---|
192 | * @param pfnServe The function which will serve a new client connection.
|
---|
193 | * @param pvUser User argument passed to pfnServe.
|
---|
194 | * @param ppServer Where to store the serverhandle.
|
---|
195 | */
|
---|
196 | RTR3DECL(int) RTTcpServerCreate(const char *pszAddress, unsigned uPort, RTTHREADTYPE enmType, const char *pszThrdName,
|
---|
197 | PFNRTTCPSERVE pfnServe, void *pvUser, PPRTTCPSERVER ppServer)
|
---|
198 | {
|
---|
199 | /*
|
---|
200 | * Do params checking
|
---|
201 | */
|
---|
202 | if (!uPort || !pfnServe || !pszThrdName || !ppServer)
|
---|
203 | {
|
---|
204 | AssertMsgFailed(("Invalid params\n"));
|
---|
205 | return VERR_INVALID_PARAMETER;
|
---|
206 | }
|
---|
207 |
|
---|
208 | /*
|
---|
209 | * Create the server.
|
---|
210 | */
|
---|
211 | PRTTCPSERVER pServer;
|
---|
212 | int rc = RTTcpServerCreateEx(pszAddress, uPort, &pServer);
|
---|
213 | if (RT_SUCCESS(rc))
|
---|
214 | {
|
---|
215 | /*
|
---|
216 | * Create the listener thread.
|
---|
217 | */
|
---|
218 | pServer->enmState = RTTCPSERVERSTATE_STARTING;
|
---|
219 | pServer->pvUser = pvUser;
|
---|
220 | pServer->pfnServe = pfnServe;
|
---|
221 | rc = RTThreadCreate(&pServer->Thread, rtTcpServerThread, pServer, 0, enmType, /*RTTHREADFLAGS_WAITABLE*/0, pszThrdName);
|
---|
222 | if (RT_SUCCESS(rc))
|
---|
223 | {
|
---|
224 | /* done */
|
---|
225 | if (ppServer)
|
---|
226 | *ppServer = pServer;
|
---|
227 | return rc;
|
---|
228 | }
|
---|
229 |
|
---|
230 | /*
|
---|
231 | * Destroy the server.
|
---|
232 | */
|
---|
233 | rtTcpServerSetState(pServer, RTTCPSERVERSTATE_CREATED, RTTCPSERVERSTATE_STARTING);
|
---|
234 | RTTcpServerDestroy(pServer);
|
---|
235 | }
|
---|
236 |
|
---|
237 | return rc;
|
---|
238 | }
|
---|
239 |
|
---|
240 |
|
---|
241 | /**
|
---|
242 | * Server thread, loops accepting connections until it's terminated.
|
---|
243 | *
|
---|
244 | * @returns iprt status code. (ignored).
|
---|
245 | * @param ThreadSelf Thread handle.
|
---|
246 | * @param pvServer Server handle.
|
---|
247 | */
|
---|
248 | static DECLCALLBACK(int) rtTcpServerThread(RTTHREAD ThreadSelf, void *pvServer)
|
---|
249 | {
|
---|
250 | PRTTCPSERVER pServer = (PRTTCPSERVER)pvServer;
|
---|
251 | if (rtTcpServerSetState(pServer, RTTCPSERVERSTATE_ACCEPTING, RTTCPSERVERSTATE_STARTING))
|
---|
252 | return rtTcpServerListen(pServer);
|
---|
253 | rcTcpServerListenCleanup(pServer);
|
---|
254 | NOREF(ThreadSelf);
|
---|
255 | return VINF_SUCCESS;
|
---|
256 | }
|
---|
257 |
|
---|
258 |
|
---|
259 | /**
|
---|
260 | * Create single connection at a time TCP Server.
|
---|
261 | * The caller must call RTTcpServerListen() to actually start the server.
|
---|
262 | *
|
---|
263 | * @returns iprt status code.
|
---|
264 | * @param pszAddress The address for creating a listening socket.
|
---|
265 | * If NULL the server is bound to all interfaces.
|
---|
266 | * @param uPort The port for creating a listening socket.
|
---|
267 | * @param ppServer Where to store the serverhandle.
|
---|
268 | */
|
---|
269 | RTR3DECL(int) RTTcpServerCreateEx(const char *pszAddress, uint32_t uPort, PPRTTCPSERVER ppServer)
|
---|
270 | {
|
---|
271 | int rc;
|
---|
272 |
|
---|
273 | /*
|
---|
274 | * Do params checking
|
---|
275 | */
|
---|
276 | if (!uPort || !ppServer)
|
---|
277 | {
|
---|
278 | AssertMsgFailed(("Invalid params\n"));
|
---|
279 | return VERR_INVALID_PARAMETER;
|
---|
280 | }
|
---|
281 |
|
---|
282 | #ifdef __WIN__
|
---|
283 | /*
|
---|
284 | * Initialize WinSock and check version.
|
---|
285 | */
|
---|
286 | WORD wVersionRequested = MAKEWORD(1, 1);
|
---|
287 | WSADATA wsaData;
|
---|
288 | rc = WSAStartup(wVersionRequested, &wsaData);
|
---|
289 | if (wsaData.wVersion != wVersionRequested)
|
---|
290 | {
|
---|
291 | AssertMsgFailed(("Wrong winsock version\n"));
|
---|
292 | return VERR_NOT_SUPPORTED;
|
---|
293 | }
|
---|
294 | #endif
|
---|
295 |
|
---|
296 | /*
|
---|
297 | * Get host listening address.
|
---|
298 | */
|
---|
299 | struct hostent *pHostEnt = NULL;
|
---|
300 | if (pszAddress != NULL && *pszAddress)
|
---|
301 | {
|
---|
302 | pHostEnt = gethostbyname(pszAddress);
|
---|
303 | if (!pHostEnt)
|
---|
304 | {
|
---|
305 | struct in_addr InAddr;
|
---|
306 | InAddr.s_addr = inet_addr(pszAddress);
|
---|
307 | pHostEnt = gethostbyaddr((char *)&InAddr, 4, AF_INET);
|
---|
308 | if (!pHostEnt)
|
---|
309 | {
|
---|
310 | rc = rtTcpError();
|
---|
311 | AssertMsgFailed(("Could not get host address rc=%Vrc\n", rc));
|
---|
312 | return rc;
|
---|
313 | }
|
---|
314 | }
|
---|
315 | }
|
---|
316 |
|
---|
317 | /*
|
---|
318 | * Setting up socket.
|
---|
319 | */
|
---|
320 | RTSOCKET WaitSock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
|
---|
321 | if (WaitSock != -1)
|
---|
322 | {
|
---|
323 | /*
|
---|
324 | * Set socket options.
|
---|
325 | */
|
---|
326 | int fFlag = 1;
|
---|
327 | if (!setsockopt(WaitSock, SOL_SOCKET, SO_REUSEADDR, (const char *)&fFlag, sizeof(fFlag)))
|
---|
328 | {
|
---|
329 | /*
|
---|
330 | * Set socket family, address and port.
|
---|
331 | */
|
---|
332 | struct sockaddr_in LocalAddr = {0};
|
---|
333 | LocalAddr.sin_family = AF_INET;
|
---|
334 | LocalAddr.sin_port = htons(uPort);
|
---|
335 | /* if address not specified, use INADDR_ANY. */
|
---|
336 | if (!pHostEnt)
|
---|
337 | LocalAddr.sin_addr.s_addr = INADDR_ANY;
|
---|
338 | else
|
---|
339 | LocalAddr.sin_addr = *((struct in_addr *)pHostEnt->h_addr);
|
---|
340 |
|
---|
341 | /*
|
---|
342 | * Bind a name to a socket.
|
---|
343 | */
|
---|
344 | if (bind(WaitSock, (struct sockaddr *)&LocalAddr, sizeof(LocalAddr)) != -1)
|
---|
345 | {
|
---|
346 | /*
|
---|
347 | * Listen for connections on a socket.
|
---|
348 | */
|
---|
349 | if (listen(WaitSock, BACKLOG) != -1)
|
---|
350 | {
|
---|
351 | /*
|
---|
352 | * Create the server handle.
|
---|
353 | */
|
---|
354 | PRTTCPSERVER pServer = (PRTTCPSERVER)RTMemAllocZ(sizeof(*pServer));
|
---|
355 | if (pServer)
|
---|
356 | {
|
---|
357 | pServer->SockServer = WaitSock;
|
---|
358 | pServer->SockClient = NIL_RTSOCKET;
|
---|
359 | pServer->Thread = NIL_RTTHREAD;
|
---|
360 | pServer->enmState = RTTCPSERVERSTATE_CREATED;
|
---|
361 | *ppServer = pServer;
|
---|
362 | return VINF_SUCCESS;
|
---|
363 | }
|
---|
364 | else
|
---|
365 | rc = VERR_NO_MEMORY;
|
---|
366 | }
|
---|
367 | else
|
---|
368 | {
|
---|
369 | rc = rtTcpError();
|
---|
370 | AssertMsgFailed(("listen() %Vrc\n", rc));
|
---|
371 | }
|
---|
372 | }
|
---|
373 | else
|
---|
374 | {
|
---|
375 | rc = rtTcpError();
|
---|
376 | }
|
---|
377 | }
|
---|
378 | else
|
---|
379 | {
|
---|
380 | rc = rtTcpError();
|
---|
381 | AssertMsgFailed(("setsockopt() %Vrc\n", rc));
|
---|
382 | }
|
---|
383 | rtTcpClose(WaitSock, "RTServerCreateEx");
|
---|
384 | }
|
---|
385 | else
|
---|
386 | {
|
---|
387 | rc = rtTcpError();
|
---|
388 | AssertMsgFailed(("socket() %Vrc\n", rc));
|
---|
389 | }
|
---|
390 |
|
---|
391 | return rc;
|
---|
392 | }
|
---|
393 |
|
---|
394 |
|
---|
395 | /**
|
---|
396 | * Listen for incoming connections.
|
---|
397 | *
|
---|
398 | * The function will loop accepting connections and call pfnServe for
|
---|
399 | * each of the incoming connections in turn. The pfnServe function can
|
---|
400 | * return VERR_TCP_SERVER_STOP too terminate this loop. A stopped server
|
---|
401 | * can only be destroyed.
|
---|
402 | *
|
---|
403 | * @returns iprt status code.
|
---|
404 | * @param pServer The server handle as returned from RTTcpServerCreateEx().
|
---|
405 | * @param pfnServe The function which will serve a new client connection.
|
---|
406 | * @param pvUser User argument passed to pfnServe.
|
---|
407 | */
|
---|
408 | RTR3DECL(int) RTTcpServerListen(PRTTCPSERVER pServer, PFNRTTCPSERVE pfnServe, void *pvUser)
|
---|
409 | {
|
---|
410 | /*
|
---|
411 | * Validate input.
|
---|
412 | */
|
---|
413 | if (!pfnServe || !pServer)
|
---|
414 | {
|
---|
415 | AssertMsgFailed(("pfnServer=%p pServer=%p\n", pfnServe, pServer));
|
---|
416 | return VERR_INVALID_PARAMETER;
|
---|
417 | }
|
---|
418 | if (rtTcpServerSetState(pServer, RTTCPSERVERSTATE_ACCEPTING, RTTCPSERVERSTATE_CREATED))
|
---|
419 | {
|
---|
420 | Assert(!pServer->pfnServe);
|
---|
421 | Assert(!pServer->pvUser);
|
---|
422 | Assert(pServer->Thread == NIL_RTTHREAD);
|
---|
423 | Assert(pServer->SockClient == NIL_RTSOCKET);
|
---|
424 |
|
---|
425 | pServer->pfnServe = pfnServe;
|
---|
426 | pServer->pvUser = pvUser;
|
---|
427 | pServer->Thread = RTThreadSelf();
|
---|
428 | Assert(pServer->Thread != NIL_RTTHREAD);
|
---|
429 | return rtTcpServerListen(pServer);
|
---|
430 | }
|
---|
431 | AssertMsgFailed(("pServer->enmState=%d\n", pServer->enmState));
|
---|
432 | return VERR_INVALID_PARAMETER;
|
---|
433 | }
|
---|
434 |
|
---|
435 |
|
---|
436 | /**
|
---|
437 | * Closes the client socket.
|
---|
438 | */
|
---|
439 | static int rtTcpServerDestroyClientSock(RTSOCKET volatile *pSock, const char *pszMsg)
|
---|
440 | {
|
---|
441 | RTSOCKET Sock = rtTcpAtomicXchgSock(pSock, NIL_RTSOCKET);
|
---|
442 | if (Sock != NIL_RTSOCKET)
|
---|
443 | shutdown(Sock, SHUT_RDWR);
|
---|
444 | return rtTcpClose(Sock, pszMsg);
|
---|
445 | }
|
---|
446 |
|
---|
447 |
|
---|
448 | /**
|
---|
449 | * Internal worker common for RTTcpServerListen and the thread created by RTTcpServerCreate().
|
---|
450 | */
|
---|
451 | static int rtTcpServerListen(PRTTCPSERVER pServer)
|
---|
452 | {
|
---|
453 | /*
|
---|
454 | * Accept connection loop.
|
---|
455 | */
|
---|
456 | int rc = VINF_SUCCESS;
|
---|
457 | for (;;)
|
---|
458 | {
|
---|
459 | /*
|
---|
460 | * Change state.
|
---|
461 | */
|
---|
462 | RTTCPSERVERSTATE enmState = pServer->enmState;
|
---|
463 | if ( enmState != RTTCPSERVERSTATE_ACCEPTING
|
---|
464 | && enmState != RTTCPSERVERSTATE_SERVING)
|
---|
465 | break;
|
---|
466 | if (!rtTcpServerSetState(pServer, RTTCPSERVERSTATE_ACCEPTING, enmState))
|
---|
467 | continue;
|
---|
468 |
|
---|
469 | /*
|
---|
470 | * Accept connection.
|
---|
471 | */
|
---|
472 | struct sockaddr_in RemoteAddr = {0};
|
---|
473 | socklen_t Len = sizeof(RemoteAddr);
|
---|
474 | RTSOCKET Socket = accept(pServer->SockServer, (struct sockaddr *)&RemoteAddr, &Len);
|
---|
475 | if (Socket == -1)
|
---|
476 | {
|
---|
477 | #ifndef __WIN__
|
---|
478 | /* These are typical for what can happen during destruction. */
|
---|
479 | if (errno == EBADF || errno == EINVAL || errno == ENOTSOCK)
|
---|
480 | break;
|
---|
481 | #endif
|
---|
482 | continue;
|
---|
483 | }
|
---|
484 |
|
---|
485 | /*
|
---|
486 | * Run a pfnServe callback.
|
---|
487 | */
|
---|
488 | if (!rtTcpServerSetState(pServer, RTTCPSERVERSTATE_SERVING, RTTCPSERVERSTATE_ACCEPTING))
|
---|
489 | break;
|
---|
490 | rtTcpAtomicXchgSock(&pServer->SockClient, Socket);
|
---|
491 | rc = pServer->pfnServe(Socket, pServer->pvUser);
|
---|
492 | rtTcpServerDestroyClientSock(&pServer->SockClient, "Listener: client");
|
---|
493 |
|
---|
494 | /*
|
---|
495 | * Stop the server?
|
---|
496 | */
|
---|
497 | if (rc == VERR_TCP_SERVER_STOP)
|
---|
498 | {
|
---|
499 | if (rtTcpServerSetState(pServer, RTTCPSERVERSTATE_STOPPING, RTTCPSERVERSTATE_SERVING))
|
---|
500 | {
|
---|
501 | /*
|
---|
502 | * Reset the server socket and change the state to stopped. After that state change
|
---|
503 | * we cannot safely access the handle so we'll have to return here.
|
---|
504 | */
|
---|
505 | RTSOCKET SockServer = rtTcpAtomicXchgSock(&pServer->SockServer, NIL_RTSOCKET);
|
---|
506 | rtTcpServerSetState(pServer, RTTCPSERVERSTATE_STOPPED, RTTCPSERVERSTATE_STOPPING);
|
---|
507 | rtTcpClose(SockServer, "Listener: server stopped");
|
---|
508 | return rc;
|
---|
509 | }
|
---|
510 | break;
|
---|
511 | }
|
---|
512 | }
|
---|
513 |
|
---|
514 | /*
|
---|
515 | * Perform any pending clean and be gone.
|
---|
516 | */
|
---|
517 | rcTcpServerListenCleanup(pServer);
|
---|
518 | return rc;
|
---|
519 | }
|
---|
520 |
|
---|
521 |
|
---|
522 | /**
|
---|
523 | * Clean up after listener.
|
---|
524 | */
|
---|
525 | static void rcTcpServerListenCleanup(PRTTCPSERVER pServer)
|
---|
526 | {
|
---|
527 | /*
|
---|
528 | * Wait for any destroyers to finish signaling us.
|
---|
529 | */
|
---|
530 | for (unsigned cTries = 99; cTries > 0; cTries--)
|
---|
531 | {
|
---|
532 | RTTCPSERVERSTATE enmState = pServer->enmState;
|
---|
533 | switch (enmState)
|
---|
534 | {
|
---|
535 | /*
|
---|
536 | * Intermediate state while the destroyer closes the client socket.
|
---|
537 | */
|
---|
538 | case RTTCPSERVERSTATE_SIGNALING:
|
---|
539 | if (!RTThreadYield())
|
---|
540 | RTThreadSleep(1);
|
---|
541 | break;
|
---|
542 |
|
---|
543 | /*
|
---|
544 | * Free the handle.
|
---|
545 | */
|
---|
546 | case RTTCPSERVERSTATE_DESTROYING:
|
---|
547 | {
|
---|
548 | rtTcpClose(rtTcpAtomicXchgSock(&pServer->SockServer, NIL_RTSOCKET), "Listener-cleanup: server");
|
---|
549 | rtTcpServerSetState(pServer, RTTCPSERVERSTATE_FREED, RTTCPSERVERSTATE_DESTROYING);
|
---|
550 | RTMemFree(pServer);
|
---|
551 | return;
|
---|
552 | }
|
---|
553 |
|
---|
554 | /*
|
---|
555 | * Everything else means failure.
|
---|
556 | */
|
---|
557 | default:
|
---|
558 | AssertMsgFailed(("pServer=%p enmState=%d\n", pServer, enmState));
|
---|
559 | return;
|
---|
560 | }
|
---|
561 | }
|
---|
562 | AssertMsgFailed(("Timed out when trying to clean up after listener. pServer=%p enmState=%d\n", pServer, pServer->enmState));
|
---|
563 | }
|
---|
564 |
|
---|
565 |
|
---|
566 | /**
|
---|
567 | * Terminate the open connection to the server.
|
---|
568 | *
|
---|
569 | * @returns iprt status code.
|
---|
570 | * @param pServer Handle to the server.
|
---|
571 | */
|
---|
572 | RTR3DECL(int) RTTcpServerDisconnectClient(PRTTCPSERVER pServer)
|
---|
573 | {
|
---|
574 | /*
|
---|
575 | * Validate input.
|
---|
576 | */
|
---|
577 | if ( !pServer
|
---|
578 | || pServer->enmState <= RTTCPSERVERSTATE_INVALID
|
---|
579 | || pServer->enmState >= RTTCPSERVERSTATE_FREED)
|
---|
580 | {
|
---|
581 | AssertMsgFailed(("Invalid parameter!\n"));
|
---|
582 | return VERR_INVALID_PARAMETER;
|
---|
583 | }
|
---|
584 |
|
---|
585 | return rtTcpServerDestroyClientSock(&pServer->SockClient, "DisconnectClient: client");
|
---|
586 | }
|
---|
587 |
|
---|
588 |
|
---|
589 | /**
|
---|
590 | * Closes down and frees a TCP Server.
|
---|
591 | * This will also terminate any open connections to the server.
|
---|
592 | *
|
---|
593 | * @returns iprt status code.
|
---|
594 | * @param pServer Handle to the server.
|
---|
595 | */
|
---|
596 | RTR3DECL(int) RTTcpServerDestroy(PRTTCPSERVER pServer)
|
---|
597 | {
|
---|
598 | /*
|
---|
599 | * Validate input.
|
---|
600 | */
|
---|
601 | if ( !pServer
|
---|
602 | || pServer->enmState <= RTTCPSERVERSTATE_INVALID
|
---|
603 | || pServer->enmState >= RTTCPSERVERSTATE_FREED)
|
---|
604 | {
|
---|
605 | AssertMsgFailed(("Invalid parameter!\n"));
|
---|
606 | return VERR_INVALID_PARAMETER;
|
---|
607 | }
|
---|
608 |
|
---|
609 | /** @todo r=bird: Some of this horrible code can probably be exchanged with a RTThreadWait(). (It didn't exist when this code was written.) */
|
---|
610 |
|
---|
611 | /*
|
---|
612 | * Move it to the destroying state.
|
---|
613 | */
|
---|
614 | RTSOCKET SockServer = rtTcpAtomicXchgSock(&pServer->SockServer, NIL_RTSOCKET);
|
---|
615 | for (unsigned cTries = 99; cTries > 0; cTries--)
|
---|
616 | {
|
---|
617 | RTTCPSERVERSTATE enmState = pServer->enmState;
|
---|
618 | switch (enmState)
|
---|
619 | {
|
---|
620 | /*
|
---|
621 | * Try move it to the destroying state.
|
---|
622 | */
|
---|
623 | case RTTCPSERVERSTATE_STARTING:
|
---|
624 | case RTTCPSERVERSTATE_ACCEPTING:
|
---|
625 | case RTTCPSERVERSTATE_SERVING:
|
---|
626 | {
|
---|
627 | if (rtTcpServerSetState(pServer, RTTCPSERVERSTATE_SIGNALING, enmState))
|
---|
628 | {
|
---|
629 | /* client */
|
---|
630 | rtTcpServerDestroyClientSock(&pServer->SockClient, "Destroyer: client");
|
---|
631 |
|
---|
632 | bool fRc = rtTcpServerSetState(pServer, RTTCPSERVERSTATE_DESTROYING, RTTCPSERVERSTATE_SIGNALING);
|
---|
633 | Assert(fRc); NOREF(fRc);
|
---|
634 |
|
---|
635 | /* server */
|
---|
636 | rtTcpServerDestroyServerSock(SockServer, "Destroyer: server destroying");
|
---|
637 | RTThreadYield();
|
---|
638 |
|
---|
639 | return VINF_SUCCESS;
|
---|
640 | }
|
---|
641 | break;
|
---|
642 | }
|
---|
643 |
|
---|
644 |
|
---|
645 | /*
|
---|
646 | * Intermediate state.
|
---|
647 | */
|
---|
648 | case RTTCPSERVERSTATE_STOPPING:
|
---|
649 | if (!RTThreadYield())
|
---|
650 | RTThreadSleep(1);
|
---|
651 | break;
|
---|
652 |
|
---|
653 | /*
|
---|
654 | * Just release the handle.
|
---|
655 | */
|
---|
656 | case RTTCPSERVERSTATE_CREATED:
|
---|
657 | case RTTCPSERVERSTATE_STOPPED:
|
---|
658 | if (rtTcpServerSetState(pServer, RTTCPSERVERSTATE_FREED, enmState))
|
---|
659 | {
|
---|
660 | rtTcpServerDestroyServerSock(SockServer, "Destroyer: server freeing");
|
---|
661 | RTMemFree(pServer);
|
---|
662 | return VINF_TCP_SERVER_STOP;
|
---|
663 | }
|
---|
664 | break;
|
---|
665 |
|
---|
666 | /*
|
---|
667 | * Everything else means failure.
|
---|
668 | */
|
---|
669 | default:
|
---|
670 | AssertMsgFailed(("pServer=%p enmState=%d\n", pServer, enmState));
|
---|
671 | return VERR_INTERNAL_ERROR;
|
---|
672 | }
|
---|
673 | }
|
---|
674 |
|
---|
675 | AssertMsgFailed(("Giving up! pServer=%p enmState=%d\n", pServer, pServer->enmState));
|
---|
676 | rtTcpServerDestroyServerSock(SockServer, "Destroyer: server timeout");
|
---|
677 | return VERR_INTERNAL_ERROR;
|
---|
678 | }
|
---|
679 |
|
---|
680 |
|
---|
681 | /**
|
---|
682 | * Shutdowns the server socket.
|
---|
683 | */
|
---|
684 | static void rtTcpServerDestroyServerSock(RTSOCKET SockServer, const char *pszMsg)
|
---|
685 | {
|
---|
686 | if (SockServer == NIL_RTSOCKET)
|
---|
687 | return;
|
---|
688 | shutdown(SockServer, SHUT_RDWR);
|
---|
689 | rtTcpClose(SockServer, "Destroyer: server destroying");
|
---|
690 | }
|
---|
691 |
|
---|
692 |
|
---|
693 |
|
---|
694 | RTR3DECL(int) RTTcpRead(RTSOCKET Sock, void *pvBuffer, size_t cbBuffer, size_t *pcbRead)
|
---|
695 | {
|
---|
696 | /*
|
---|
697 | * Do params checking
|
---|
698 | */
|
---|
699 | if (!pvBuffer || !cbBuffer)
|
---|
700 | {
|
---|
701 | AssertMsgFailed(("Invalid params\n"));
|
---|
702 | return VERR_INVALID_PARAMETER;
|
---|
703 | }
|
---|
704 |
|
---|
705 | /*
|
---|
706 | * Read loop.
|
---|
707 | * If pcbRead is NULL we have to fill the entire buffer!
|
---|
708 | */
|
---|
709 | size_t cbRead = 0;
|
---|
710 | size_t cbToRead = cbBuffer;
|
---|
711 | for (;;)
|
---|
712 | {
|
---|
713 | ssize_t cbBytesRead = recv(Sock, (char *)pvBuffer + cbRead, cbToRead, MSG_NOSIGNAL);
|
---|
714 | if (cbBytesRead < 0)
|
---|
715 | return rtTcpError();
|
---|
716 | if (cbBytesRead == 0 && rtTcpError())
|
---|
717 | return rtTcpError();
|
---|
718 | if (pcbRead)
|
---|
719 | {
|
---|
720 | /* return partial data */
|
---|
721 | *pcbRead = cbBytesRead;
|
---|
722 | break;
|
---|
723 | }
|
---|
724 |
|
---|
725 | /* read more? */
|
---|
726 | cbRead += cbBytesRead;
|
---|
727 | if (cbRead == cbBuffer)
|
---|
728 | break;
|
---|
729 |
|
---|
730 | /* next */
|
---|
731 | cbToRead = cbBuffer - cbRead;
|
---|
732 | }
|
---|
733 |
|
---|
734 | return VINF_SUCCESS;
|
---|
735 | }
|
---|
736 |
|
---|
737 |
|
---|
738 | RTR3DECL(int) RTTcpWrite(RTSOCKET Sock, const void *pvBuffer, size_t cbBuffer)
|
---|
739 | {
|
---|
740 | do
|
---|
741 | {
|
---|
742 | ssize_t cbWritten = send(Sock, (const char *)pvBuffer, cbBuffer, MSG_NOSIGNAL);
|
---|
743 | if (cbWritten < 0)
|
---|
744 | return rtTcpError();
|
---|
745 | AssertMsg(cbBuffer >= (size_t)cbWritten, ("Wrote more than we requested!!! cbWritten=%d cbBuffer=%d rtTcpError()=%d\n",
|
---|
746 | cbWritten, cbBuffer, rtTcpError()));
|
---|
747 | cbBuffer -= cbWritten;
|
---|
748 | pvBuffer = (char *)pvBuffer + cbWritten;
|
---|
749 | } while (cbBuffer);
|
---|
750 |
|
---|
751 | return VINF_SUCCESS;
|
---|
752 | }
|
---|
753 |
|
---|
754 |
|
---|
755 | RTR3DECL(int) RTTcpFlush(RTSOCKET Sock)
|
---|
756 | {
|
---|
757 | int fFlag = 1;
|
---|
758 | setsockopt(Sock, IPPROTO_TCP, TCP_NODELAY, (const char *)&fFlag, sizeof(fFlag));
|
---|
759 | fFlag = 0;
|
---|
760 | setsockopt(Sock, IPPROTO_TCP, TCP_NODELAY, (const char *)&fFlag, sizeof(fFlag));
|
---|
761 |
|
---|
762 | return VINF_SUCCESS;
|
---|
763 | }
|
---|
764 |
|
---|
765 |
|
---|
766 | RTR3DECL(int) RTTcpSelectOne(RTSOCKET Sock, unsigned cMillies)
|
---|
767 | {
|
---|
768 | fd_set fdsetR;
|
---|
769 | FD_ZERO(&fdsetR);
|
---|
770 | FD_SET(Sock, &fdsetR);
|
---|
771 |
|
---|
772 | fd_set fdsetE = fdsetR;
|
---|
773 |
|
---|
774 | int rc;
|
---|
775 | if (cMillies == RT_INDEFINITE_WAIT)
|
---|
776 | rc = select(FD_SETSIZE, &fdsetR, NULL, &fdsetE, NULL);
|
---|
777 | else
|
---|
778 | {
|
---|
779 | struct timeval timeout;
|
---|
780 | timeout.tv_sec = cMillies / 1000;
|
---|
781 | timeout.tv_usec = (cMillies % 1000) * 1000;
|
---|
782 | rc = select(FD_SETSIZE, &fdsetR, NULL, &fdsetE, &timeout);
|
---|
783 | }
|
---|
784 | if (rc > 0)
|
---|
785 | return VINF_SUCCESS;
|
---|
786 | if (rc == 0)
|
---|
787 | return VERR_TIMEOUT;
|
---|
788 | return rtTcpError();
|
---|
789 | }
|
---|
790 |
|
---|
791 |
|
---|
792 | RTR3DECL(int) RTTcpClientConnect(const char *pszAddress, uint32_t uPort, PRTSOCKET pSock)
|
---|
793 | {
|
---|
794 | int rc;
|
---|
795 |
|
---|
796 | /*
|
---|
797 | * Do params checking
|
---|
798 | */
|
---|
799 | AssertReturn(uPort, VERR_INVALID_PARAMETER);
|
---|
800 | AssertReturn(VALID_PTR(pszAddress), VERR_INVALID_PARAMETER);
|
---|
801 |
|
---|
802 | #ifdef __WIN__
|
---|
803 | /*
|
---|
804 | * Initialize WinSock and check version.
|
---|
805 | */
|
---|
806 | WORD wVersionRequested = MAKEWORD(1, 1);
|
---|
807 | WSADATA wsaData;
|
---|
808 | rc = WSAStartup(wVersionRequested, &wsaData);
|
---|
809 | if (wsaData.wVersion != wVersionRequested)
|
---|
810 | {
|
---|
811 | AssertMsgFailed(("Wrong winsock version\n"));
|
---|
812 | return VERR_NOT_SUPPORTED;
|
---|
813 | }
|
---|
814 | #endif
|
---|
815 |
|
---|
816 | /*
|
---|
817 | * Resolve the address.
|
---|
818 | */
|
---|
819 | struct hostent *pHostEnt = NULL;
|
---|
820 | pHostEnt = gethostbyname(pszAddress);
|
---|
821 | if (!pHostEnt)
|
---|
822 | {
|
---|
823 | struct in_addr InAddr;
|
---|
824 | InAddr.s_addr = inet_addr(pszAddress);
|
---|
825 | pHostEnt = gethostbyaddr((char *)&InAddr, 4, AF_INET);
|
---|
826 | if (!pHostEnt)
|
---|
827 | {
|
---|
828 | rc = rtTcpError();
|
---|
829 | AssertMsgFailed(("Could not resolve '%s', rc=%Vrc\n", pszAddress, rc));
|
---|
830 | return rc;
|
---|
831 | }
|
---|
832 | }
|
---|
833 |
|
---|
834 | /*
|
---|
835 | * Create the socket and connect.
|
---|
836 | */
|
---|
837 | RTSOCKET Sock = socket(AF_INET, SOCK_STREAM, 0);
|
---|
838 | if (Sock != -1)
|
---|
839 | {
|
---|
840 | struct sockaddr_in InAddr = {0};
|
---|
841 | InAddr.sin_family = AF_INET;
|
---|
842 | InAddr.sin_port = htons(uPort);
|
---|
843 | InAddr.sin_addr = *((struct in_addr *)pHostEnt->h_addr);
|
---|
844 | if (!connect(Sock, (struct sockaddr *)&InAddr, sizeof(InAddr)))
|
---|
845 | {
|
---|
846 | *pSock = Sock;
|
---|
847 | return VINF_SUCCESS;
|
---|
848 | }
|
---|
849 | rc = rtTcpError();
|
---|
850 | rtTcpClose(Sock, "RTTcpClientConnect");
|
---|
851 | }
|
---|
852 | else
|
---|
853 | rc = rtTcpError();
|
---|
854 | return rc;
|
---|
855 | }
|
---|
856 |
|
---|
857 |
|
---|
858 | RTR3DECL(int) RTTcpClientClose(RTSOCKET Sock)
|
---|
859 | {
|
---|
860 | return rtTcpClose(Sock, "RTTcpClientClose");
|
---|
861 | }
|
---|
862 |
|
---|
863 |
|
---|
864 | /**
|
---|
865 | * Internal close function which does all the proper bitching.
|
---|
866 | */
|
---|
867 | static int rtTcpClose(RTSOCKET Sock, const char *pszMsg)
|
---|
868 | {
|
---|
869 | /* ignore nil handles. */
|
---|
870 | if (Sock == NIL_RTSOCKET)
|
---|
871 | return VINF_SUCCESS;
|
---|
872 |
|
---|
873 | /*
|
---|
874 | * Attempt to close it.
|
---|
875 | */
|
---|
876 | #ifdef __WIN__
|
---|
877 | int rc = closesocket(Sock);
|
---|
878 | #else
|
---|
879 | int rc = close(Sock);
|
---|
880 | #endif
|
---|
881 | if (!rc)
|
---|
882 | return VINF_SUCCESS;
|
---|
883 | rc = rtTcpError();
|
---|
884 | AssertMsgFailed(("\"%s\": close(%d) -> %Vrc\n", pszMsg, Sock, rc));
|
---|
885 | return rc;
|
---|
886 | }
|
---|
887 |
|
---|