1 | /* $Id: tcp.cpp 932 2007-02-15 18:25:10Z vboxsync $ */
|
---|
2 | /** @file
|
---|
3 | * InnoTek Portable Runtime - TCP/IP.
|
---|
4 | */
|
---|
5 |
|
---|
6 | /*
|
---|
7 | * Copyright (C) 2006 InnoTek Systemberatung 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 | inline 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 | inline 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 | inline 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 | {
|
---|
444 | shutdown(Sock, SHUT_RDWR);
|
---|
445 | }
|
---|
446 | return rtTcpClose(Sock, pszMsg);
|
---|
447 | }
|
---|
448 |
|
---|
449 |
|
---|
450 | /**
|
---|
451 | * Internal worker common for RTTcpServerListen and the thread created by RTTcpServerCreate().
|
---|
452 | */
|
---|
453 | static int rtTcpServerListen(PRTTCPSERVER pServer)
|
---|
454 | {
|
---|
455 | /*
|
---|
456 | * Accept connection loop.
|
---|
457 | */
|
---|
458 | int rc = VINF_SUCCESS;
|
---|
459 | for (;;)
|
---|
460 | {
|
---|
461 | /*
|
---|
462 | * Change state.
|
---|
463 | */
|
---|
464 | RTTCPSERVERSTATE enmState = pServer->enmState;
|
---|
465 | if ( enmState != RTTCPSERVERSTATE_ACCEPTING
|
---|
466 | && enmState != RTTCPSERVERSTATE_SERVING)
|
---|
467 | break;
|
---|
468 | if (!rtTcpServerSetState(pServer, RTTCPSERVERSTATE_ACCEPTING, enmState))
|
---|
469 | continue;
|
---|
470 |
|
---|
471 | /*
|
---|
472 | * Accept connection.
|
---|
473 | */
|
---|
474 | struct sockaddr_in RemoteAddr = {0};
|
---|
475 | socklen_t Len = sizeof(RemoteAddr);
|
---|
476 | RTSOCKET Socket = accept(pServer->SockServer, (struct sockaddr *)&RemoteAddr, &Len);
|
---|
477 | if (Socket == -1)
|
---|
478 | {
|
---|
479 | #ifndef __WIN__
|
---|
480 | /* These are typical for what can happen during destruction. */
|
---|
481 | if (errno == EBADF || errno == EINVAL || errno == ENOTSOCK)
|
---|
482 | break;
|
---|
483 | #endif
|
---|
484 | continue;
|
---|
485 | }
|
---|
486 |
|
---|
487 | /*
|
---|
488 | * Run a pfnServe callback.
|
---|
489 | */
|
---|
490 | if (!rtTcpServerSetState(pServer, RTTCPSERVERSTATE_SERVING, RTTCPSERVERSTATE_ACCEPTING))
|
---|
491 | break;
|
---|
492 | rtTcpAtomicXchgSock(&pServer->SockClient, Socket);
|
---|
493 | rc = pServer->pfnServe(Socket, pServer->pvUser);
|
---|
494 | rtTcpServerDestroyClientSock(&pServer->SockClient, "Listener: client");
|
---|
495 |
|
---|
496 | /*
|
---|
497 | * Stop the server?
|
---|
498 | */
|
---|
499 | if (rc == VERR_TCP_SERVER_STOP)
|
---|
500 | {
|
---|
501 | if (rtTcpServerSetState(pServer, RTTCPSERVERSTATE_STOPPING, RTTCPSERVERSTATE_SERVING))
|
---|
502 | {
|
---|
503 | /*
|
---|
504 | * Reset the server socket and change the state to stopped. After that state change
|
---|
505 | * we cannot safely access the handle so we'll have to return here.
|
---|
506 | */
|
---|
507 | RTSOCKET SockServer = rtTcpAtomicXchgSock(&pServer->SockServer, NIL_RTSOCKET);
|
---|
508 | rtTcpServerSetState(pServer, RTTCPSERVERSTATE_STOPPED, RTTCPSERVERSTATE_STOPPING);
|
---|
509 | rtTcpClose(SockServer, "Listener: server stopped");
|
---|
510 | return rc;
|
---|
511 | }
|
---|
512 | break;
|
---|
513 | }
|
---|
514 | }
|
---|
515 |
|
---|
516 | /*
|
---|
517 | * Perform any pending clean and be gone.
|
---|
518 | */
|
---|
519 | rcTcpServerListenCleanup(pServer);
|
---|
520 | return rc;
|
---|
521 | }
|
---|
522 |
|
---|
523 |
|
---|
524 | /**
|
---|
525 | * Clean up after listener.
|
---|
526 | */
|
---|
527 | static void rcTcpServerListenCleanup(PRTTCPSERVER pServer)
|
---|
528 | {
|
---|
529 | /*
|
---|
530 | * Wait for any destroyers to finish signaling us.
|
---|
531 | */
|
---|
532 | for (unsigned cTries = 99; cTries > 0; cTries--)
|
---|
533 | {
|
---|
534 | RTTCPSERVERSTATE enmState = pServer->enmState;
|
---|
535 | switch (enmState)
|
---|
536 | {
|
---|
537 | /*
|
---|
538 | * Intermediate state while the destroyer closes the client socket.
|
---|
539 | */
|
---|
540 | case RTTCPSERVERSTATE_SIGNALING:
|
---|
541 | if (!RTThreadYield())
|
---|
542 | RTThreadSleep(1);
|
---|
543 | break;
|
---|
544 |
|
---|
545 | /*
|
---|
546 | * Free the handle.
|
---|
547 | */
|
---|
548 | case RTTCPSERVERSTATE_DESTROYING:
|
---|
549 | {
|
---|
550 | rtTcpClose(rtTcpAtomicXchgSock(&pServer->SockServer, NIL_RTSOCKET), "Listener-cleanup: server");
|
---|
551 | rtTcpServerSetState(pServer, RTTCPSERVERSTATE_FREED, RTTCPSERVERSTATE_DESTROYING);
|
---|
552 | RTMemFree(pServer);
|
---|
553 | return;
|
---|
554 | }
|
---|
555 |
|
---|
556 | /*
|
---|
557 | * Everything else means failure.
|
---|
558 | */
|
---|
559 | default:
|
---|
560 | AssertMsgFailed(("pServer=%p enmState=%d\n", pServer, enmState));
|
---|
561 | return;
|
---|
562 | }
|
---|
563 | }
|
---|
564 | AssertMsgFailed(("Timed out when trying to clean up after listener. pServer=%p enmState=%d\n", pServer, pServer->enmState));
|
---|
565 | }
|
---|
566 |
|
---|
567 |
|
---|
568 | /**
|
---|
569 | * Terminate the open connection to the server.
|
---|
570 | *
|
---|
571 | * @returns iprt status code.
|
---|
572 | * @param pServer Handle to the server.
|
---|
573 | */
|
---|
574 | RTR3DECL(int) RTTcpServerDisconnectClient(PRTTCPSERVER pServer)
|
---|
575 | {
|
---|
576 | /*
|
---|
577 | * Validate input.
|
---|
578 | */
|
---|
579 | if ( !pServer
|
---|
580 | || pServer->enmState <= RTTCPSERVERSTATE_INVALID
|
---|
581 | || pServer->enmState >= RTTCPSERVERSTATE_FREED)
|
---|
582 | {
|
---|
583 | AssertMsgFailed(("Invalid parameter!\n"));
|
---|
584 | return VERR_INVALID_PARAMETER;
|
---|
585 | }
|
---|
586 |
|
---|
587 | return rtTcpServerDestroyClientSock(&pServer->SockClient, "DisconnectClient: client");
|
---|
588 | }
|
---|
589 |
|
---|
590 |
|
---|
591 | /**
|
---|
592 | * Closes down and frees a TCP Server.
|
---|
593 | * This will also terminate any open connections to the server.
|
---|
594 | *
|
---|
595 | * @returns iprt status code.
|
---|
596 | * @param pServer Handle to the server.
|
---|
597 | */
|
---|
598 | RTR3DECL(int) RTTcpServerDestroy(PRTTCPSERVER pServer)
|
---|
599 | {
|
---|
600 | /*
|
---|
601 | * Validate input.
|
---|
602 | */
|
---|
603 | if ( !pServer
|
---|
604 | || pServer->enmState <= RTTCPSERVERSTATE_INVALID
|
---|
605 | || pServer->enmState >= RTTCPSERVERSTATE_FREED)
|
---|
606 | {
|
---|
607 | AssertMsgFailed(("Invalid parameter!\n"));
|
---|
608 | return VERR_INVALID_PARAMETER;
|
---|
609 | }
|
---|
610 |
|
---|
611 | /** @todo r=bird: Some of this horrible code can probably be exchanged with a RTThreadWait(). (It didn't exist when this code was written.) */
|
---|
612 |
|
---|
613 | /*
|
---|
614 | * Move it to the destroying state.
|
---|
615 | */
|
---|
616 | RTSOCKET SockServer = rtTcpAtomicXchgSock(&pServer->SockServer, NIL_RTSOCKET);
|
---|
617 | for (unsigned cTries = 99; cTries > 0; cTries--)
|
---|
618 | {
|
---|
619 | RTTCPSERVERSTATE enmState = pServer->enmState;
|
---|
620 | switch (enmState)
|
---|
621 | {
|
---|
622 | /*
|
---|
623 | * Try move it to the destroying state.
|
---|
624 | */
|
---|
625 | case RTTCPSERVERSTATE_STARTING:
|
---|
626 | case RTTCPSERVERSTATE_ACCEPTING:
|
---|
627 | case RTTCPSERVERSTATE_SERVING:
|
---|
628 | {
|
---|
629 | if (rtTcpServerSetState(pServer, RTTCPSERVERSTATE_SIGNALING, enmState))
|
---|
630 | {
|
---|
631 | /* client */
|
---|
632 | rtTcpServerDestroyClientSock(&pServer->SockClient, "Destroyer: client");
|
---|
633 |
|
---|
634 | bool fRc = rtTcpServerSetState(pServer, RTTCPSERVERSTATE_DESTROYING, RTTCPSERVERSTATE_SIGNALING);
|
---|
635 | Assert(fRc); NOREF(fRc);
|
---|
636 |
|
---|
637 | /* server */
|
---|
638 | rtTcpServerDestroyServerSock(SockServer, "Destroyer: server destroying");
|
---|
639 | RTThreadYield();
|
---|
640 |
|
---|
641 | return VINF_SUCCESS;
|
---|
642 | }
|
---|
643 | break;
|
---|
644 | }
|
---|
645 |
|
---|
646 |
|
---|
647 | /*
|
---|
648 | * Intermediate state.
|
---|
649 | */
|
---|
650 | case RTTCPSERVERSTATE_STOPPING:
|
---|
651 | if (!RTThreadYield())
|
---|
652 | RTThreadSleep(1);
|
---|
653 | break;
|
---|
654 |
|
---|
655 | /*
|
---|
656 | * Just release the handle.
|
---|
657 | */
|
---|
658 | case RTTCPSERVERSTATE_CREATED:
|
---|
659 | case RTTCPSERVERSTATE_STOPPED:
|
---|
660 | if (rtTcpServerSetState(pServer, RTTCPSERVERSTATE_FREED, enmState))
|
---|
661 | {
|
---|
662 | rtTcpServerDestroyServerSock(SockServer, "Destroyer: server freeing");
|
---|
663 | RTMemFree(pServer);
|
---|
664 | return VINF_TCP_SERVER_STOP;
|
---|
665 | }
|
---|
666 | break;
|
---|
667 |
|
---|
668 | /*
|
---|
669 | * Everything else means failure.
|
---|
670 | */
|
---|
671 | default:
|
---|
672 | AssertMsgFailed(("pServer=%p enmState=%d\n", pServer, enmState));
|
---|
673 | return VERR_INTERNAL_ERROR;
|
---|
674 | }
|
---|
675 | }
|
---|
676 |
|
---|
677 | AssertMsgFailed(("Giving up! pServer=%p enmState=%d\n", pServer, pServer->enmState));
|
---|
678 | rtTcpServerDestroyServerSock(SockServer, "Destroyer: server timeout");
|
---|
679 | return VERR_INTERNAL_ERROR;
|
---|
680 | }
|
---|
681 |
|
---|
682 |
|
---|
683 | /**
|
---|
684 | * Shutdowns the server socket.
|
---|
685 | */
|
---|
686 | static void rtTcpServerDestroyServerSock(RTSOCKET SockServer, const char *pszMsg)
|
---|
687 | {
|
---|
688 | if (SockServer == NIL_RTSOCKET)
|
---|
689 | return;
|
---|
690 | shutdown(SockServer, SHUT_RDWR);
|
---|
691 | rtTcpClose(SockServer, "Destroyer: server destroying");
|
---|
692 | }
|
---|
693 |
|
---|
694 |
|
---|
695 |
|
---|
696 | RTR3DECL(int) RTTcpRead(RTSOCKET Sock, void *pvBuffer, size_t cbBuffer, size_t *pcbRead)
|
---|
697 | {
|
---|
698 | /*
|
---|
699 | * Do params checking
|
---|
700 | */
|
---|
701 | if (!pvBuffer || !cbBuffer)
|
---|
702 | {
|
---|
703 | AssertMsgFailed(("Invalid params\n"));
|
---|
704 | return VERR_INVALID_PARAMETER;
|
---|
705 | }
|
---|
706 |
|
---|
707 | /*
|
---|
708 | * Read loop.
|
---|
709 | * If pcbRead is NULL we have to fill the entire buffer!
|
---|
710 | */
|
---|
711 | size_t cbRead = 0;
|
---|
712 | size_t cbToRead = cbBuffer;
|
---|
713 | for (;;)
|
---|
714 | {
|
---|
715 | ssize_t cbBytesRead = recv(Sock, (char *)pvBuffer + cbRead, cbToRead, MSG_NOSIGNAL);
|
---|
716 | if (cbBytesRead < 0)
|
---|
717 | return rtTcpError();
|
---|
718 | if (cbBytesRead == 0 && rtTcpError())
|
---|
719 | return rtTcpError();
|
---|
720 | if (pcbRead)
|
---|
721 | {
|
---|
722 | /* return partial data */
|
---|
723 | *pcbRead = cbBytesRead;
|
---|
724 | break;
|
---|
725 | }
|
---|
726 |
|
---|
727 | /* read more? */
|
---|
728 | cbRead += cbBytesRead;
|
---|
729 | if (cbRead == cbBuffer)
|
---|
730 | break;
|
---|
731 |
|
---|
732 | /* next */
|
---|
733 | cbToRead = cbBuffer - cbRead;
|
---|
734 | }
|
---|
735 |
|
---|
736 | return VINF_SUCCESS;
|
---|
737 | }
|
---|
738 |
|
---|
739 |
|
---|
740 | RTR3DECL(int) RTTcpWrite(RTSOCKET Sock, const void *pvBuffer, size_t cbBuffer)
|
---|
741 | {
|
---|
742 | do
|
---|
743 | {
|
---|
744 | ssize_t cbWritten = send(Sock, (const char *)pvBuffer, cbBuffer, MSG_NOSIGNAL);
|
---|
745 | if (cbWritten < 0)
|
---|
746 | return rtTcpError();
|
---|
747 | AssertMsg(cbBuffer >= (size_t)cbWritten, ("Wrote more than we requested!!! cbWritten=%d cbBuffer=%d rtTcpError()=%d\n",
|
---|
748 | cbWritten, cbBuffer, rtTcpError()));
|
---|
749 | cbBuffer -= cbWritten;
|
---|
750 | pvBuffer = (char *)pvBuffer + cbWritten;
|
---|
751 | } while (cbBuffer);
|
---|
752 |
|
---|
753 | return VINF_SUCCESS;
|
---|
754 | }
|
---|
755 |
|
---|
756 |
|
---|
757 | RTR3DECL(int) RTTcpFlush(RTSOCKET Sock)
|
---|
758 | {
|
---|
759 | int fFlag = 1;
|
---|
760 | setsockopt(Sock, IPPROTO_TCP, TCP_NODELAY, (const char *)&fFlag, sizeof(fFlag));
|
---|
761 | fFlag = 0;
|
---|
762 | setsockopt(Sock, IPPROTO_TCP, TCP_NODELAY, (const char *)&fFlag, sizeof(fFlag));
|
---|
763 |
|
---|
764 | return VINF_SUCCESS;
|
---|
765 | }
|
---|
766 |
|
---|
767 |
|
---|
768 | RTR3DECL(int) RTTcpSelectOne(RTSOCKET Sock, unsigned cMillies)
|
---|
769 | {
|
---|
770 | fd_set fdsetR;
|
---|
771 | FD_ZERO(&fdsetR);
|
---|
772 | FD_SET(Sock, &fdsetR);
|
---|
773 |
|
---|
774 | fd_set fdsetE = fdsetR;
|
---|
775 |
|
---|
776 | int rc;
|
---|
777 | if (cMillies == RT_INDEFINITE_WAIT)
|
---|
778 | rc = select(FD_SETSIZE, &fdsetR, NULL, &fdsetE, NULL);
|
---|
779 | else
|
---|
780 | {
|
---|
781 | struct timeval timeout;
|
---|
782 | timeout.tv_sec = cMillies / 1000;
|
---|
783 | timeout.tv_usec = (cMillies % 1000) * 1000;
|
---|
784 | rc = select(FD_SETSIZE, &fdsetR, NULL, &fdsetE, &timeout);
|
---|
785 | }
|
---|
786 | if (rc > 0)
|
---|
787 | return VINF_SUCCESS;
|
---|
788 | if (rc == 0)
|
---|
789 | return VERR_TIMEOUT;
|
---|
790 | return rtTcpError();
|
---|
791 | }
|
---|
792 |
|
---|
793 |
|
---|
794 | RTR3DECL(int) RTTcpClientConnect(const char *pszAddress, uint32_t uPort, PRTSOCKET pSock)
|
---|
795 | {
|
---|
796 | int rc;
|
---|
797 |
|
---|
798 | /*
|
---|
799 | * Do params checking
|
---|
800 | */
|
---|
801 | AssertReturn(uPort, VERR_INVALID_PARAMETER);
|
---|
802 | AssertReturn(VALID_PTR(pszAddress), VERR_INVALID_PARAMETER);
|
---|
803 |
|
---|
804 | #ifdef __WIN__
|
---|
805 | /*
|
---|
806 | * Initialize WinSock and check version.
|
---|
807 | */
|
---|
808 | WORD wVersionRequested = MAKEWORD(1, 1);
|
---|
809 | WSADATA wsaData;
|
---|
810 | rc = WSAStartup(wVersionRequested, &wsaData);
|
---|
811 | if (wsaData.wVersion != wVersionRequested)
|
---|
812 | {
|
---|
813 | AssertMsgFailed(("Wrong winsock version\n"));
|
---|
814 | return VERR_NOT_SUPPORTED;
|
---|
815 | }
|
---|
816 | #endif
|
---|
817 |
|
---|
818 | /*
|
---|
819 | * Resolve the address.
|
---|
820 | */
|
---|
821 | struct hostent *pHostEnt = NULL;
|
---|
822 | pHostEnt = gethostbyname(pszAddress);
|
---|
823 | if (!pHostEnt)
|
---|
824 | {
|
---|
825 | struct in_addr InAddr;
|
---|
826 | InAddr.s_addr = inet_addr(pszAddress);
|
---|
827 | pHostEnt = gethostbyaddr((char *)&InAddr, 4, AF_INET);
|
---|
828 | if (!pHostEnt)
|
---|
829 | {
|
---|
830 | rc = rtTcpError();
|
---|
831 | AssertMsgFailed(("Could not resolve '%s', rc=%Vrc\n", pszAddress, rc));
|
---|
832 | return rc;
|
---|
833 | }
|
---|
834 | }
|
---|
835 |
|
---|
836 | /*
|
---|
837 | * Create the socket and connect.
|
---|
838 | */
|
---|
839 | RTSOCKET Sock = socket(AF_INET, SOCK_STREAM, 0);
|
---|
840 | if (Sock != -1)
|
---|
841 | {
|
---|
842 | struct sockaddr_in InAddr = {0};
|
---|
843 | InAddr.sin_family = AF_INET;
|
---|
844 | InAddr.sin_port = htons(uPort);
|
---|
845 | InAddr.sin_addr = *((struct in_addr *)pHostEnt->h_addr);
|
---|
846 | if (!connect(Sock, (struct sockaddr *)&InAddr, sizeof(InAddr)))
|
---|
847 | {
|
---|
848 | *pSock = Sock;
|
---|
849 | return VINF_SUCCESS;
|
---|
850 | }
|
---|
851 | rc = rtTcpError();
|
---|
852 | rtTcpClose(Sock, "RTTcpClientConnect");
|
---|
853 | }
|
---|
854 | else
|
---|
855 | rc = rtTcpError();
|
---|
856 | return rc;
|
---|
857 | }
|
---|
858 |
|
---|
859 |
|
---|
860 | RTR3DECL(int) RTTcpClientClose(RTSOCKET Sock)
|
---|
861 | {
|
---|
862 | return rtTcpClose(Sock, "RTTcpClientClose");
|
---|
863 | }
|
---|
864 |
|
---|
865 |
|
---|
866 | /**
|
---|
867 | * Internal close function which does all the proper bitching.
|
---|
868 | */
|
---|
869 | static int rtTcpClose(RTSOCKET Sock, const char *pszMsg)
|
---|
870 | {
|
---|
871 | /* ignore nil handles. */
|
---|
872 | if (Sock == NIL_RTSOCKET)
|
---|
873 | return VINF_SUCCESS;
|
---|
874 |
|
---|
875 | /*
|
---|
876 | * Attempt to close it.
|
---|
877 | */
|
---|
878 | #ifdef __WIN__
|
---|
879 | int rc = closesocket(Sock);
|
---|
880 | #else
|
---|
881 | int rc = close(Sock);
|
---|
882 | #endif
|
---|
883 | if (!rc)
|
---|
884 | return VINF_SUCCESS;
|
---|
885 | rc = rtTcpError();
|
---|
886 | AssertMsgFailed(("\"%s\": close(%d) -> %Vrc\n", pszMsg, Sock, rc));
|
---|
887 | return rc;
|
---|
888 | }
|
---|
889 |
|
---|