VirtualBox

source: vbox/trunk/src/VBox/Devices/Serial/DrvNamedPipe.cpp@ 69500

Last change on this file since 69500 was 69500, checked in by vboxsync, 7 years ago

*: scm --update-copyright-year

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 38.1 KB
Line 
1 /* $Id: DrvNamedPipe.cpp 69500 2017-10-28 15:14:05Z vboxsync $ */
2/** @file
3 * Named pipe / local socket stream driver.
4 */
5
6/*
7 * Copyright (C) 2006-2017 Oracle Corporation
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 (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 */
17
18
19/*********************************************************************************************************************************
20* Header Files *
21*********************************************************************************************************************************/
22#define LOG_GROUP LOG_GROUP_DRV_NAMEDPIPE
23#include <VBox/vmm/pdmdrv.h>
24#include <iprt/assert.h>
25#include <iprt/file.h>
26#include <iprt/stream.h>
27#include <iprt/alloc.h>
28#include <iprt/pipe.h>
29#include <iprt/poll.h>
30#include <iprt/string.h>
31#include <iprt/semaphore.h>
32#include <iprt/socket.h>
33#include <iprt/uuid.h>
34
35#include "VBoxDD.h"
36
37#ifdef RT_OS_WINDOWS
38# include <iprt/win/windows.h>
39#else /* !RT_OS_WINDOWS */
40# include <errno.h>
41# include <unistd.h>
42# include <sys/types.h>
43# include <sys/socket.h>
44# include <sys/un.h>
45# ifndef SHUT_RDWR /* OS/2 */
46# define SHUT_RDWR 3
47# endif
48#endif /* !RT_OS_WINDOWS */
49
50
51/*********************************************************************************************************************************
52* Defined Constants And Macros *
53*********************************************************************************************************************************/
54
55#ifndef RT_OS_WINDOWS
56# define DRVNAMEDPIPE_POLLSET_ID_SOCKET 0
57# define DRVNAMEDPIPE_POLLSET_ID_WAKEUP 1
58#endif
59
60# define DRVNAMEDPIPE_WAKEUP_REASON_EXTERNAL 0
61# define DRVNAMEDPIPE_WAKEUP_REASON_NEW_CONNECTION 1
62
63
64/*********************************************************************************************************************************
65* Structures and Typedefs *
66*********************************************************************************************************************************/
67/**
68 * Named pipe driver instance data.
69 *
70 * @implements PDMISTREAM
71 */
72typedef struct DRVNAMEDPIPE
73{
74 /** The stream interface. */
75 PDMISTREAM IStream;
76 /** Pointer to the driver instance. */
77 PPDMDRVINS pDrvIns;
78 /** Pointer to the named pipe file name. (Freed by MM) */
79 char *pszLocation;
80 /** Flag whether VirtualBox represents the server or client side. */
81 bool fIsServer;
82#ifdef RT_OS_WINDOWS
83 /** File handle of the named pipe. */
84 HANDLE NamedPipe;
85 /** The wake event handle. */
86 HANDLE hEvtWake;
87 /** Overlapped structure for writes. */
88 OVERLAPPED OverlappedWrite;
89 /** Overlapped structure for reads. */
90 OVERLAPPED OverlappedRead;
91 /** Listen thread wakeup semaphore */
92 RTSEMEVENTMULTI ListenSem;
93 /** Read buffer. */
94 uint8_t abBufRead[32];
95 /** Write buffer. */
96 uint8_t abBufWrite[32];
97 /** Read buffer currently used. */
98 size_t cbReadBufUsed;
99 /** Size of the write buffer used. */
100 size_t cbWriteBufUsed;
101 /** Flag whether a wake operation was caused by an external trigger. */
102 volatile bool fWakeExternal;
103 /** Flag whether a read was started. */
104 bool fReadPending;
105#else /* !RT_OS_WINDOWS */
106 /** Poll set used to wait for I/O events. */
107 RTPOLLSET hPollSet;
108 /** Reading end of the wakeup pipe. */
109 RTPIPE hPipeWakeR;
110 /** Writing end of the wakeup pipe. */
111 RTPIPE hPipeWakeW;
112 /** Socket handle. */
113 RTSOCKET hSock;
114 /** Flag whether the socket is in the pollset. */
115 bool fSockInPollSet;
116 /** Socket handle of the local socket for server. */
117 int LocalSocketServer;
118#endif /* !RT_OS_WINDOWS */
119 /** Thread for listening for new connections. */
120 RTTHREAD ListenThread;
121 /** Flag to signal listening thread to shut down. */
122 bool volatile fShutdown;
123} DRVNAMEDPIPE, *PDRVNAMEDPIPE;
124
125
126/*********************************************************************************************************************************
127* Internal Functions *
128*********************************************************************************************************************************/
129
130
131/**
132 * Kicks any possibly polling thread to get informed about changes.
133 *
134 * @returns VBOx status code.
135 * @param pThis The named pipe driver instance.
136 * @param bReason The reason code to handle.
137 */
138static int drvNamedPipePollerKick(PDRVNAMEDPIPE pThis, uint8_t bReason)
139{
140#ifdef RT_OS_WINDOWS
141 if (bReason == DRVNAMEDPIPE_WAKEUP_REASON_EXTERNAL)
142 ASMAtomicXchgBool(&pThis->fWakeExternal, true);
143 if (!SetEvent(pThis->hEvtWake))
144 return RTErrConvertFromWin32(GetLastError());
145
146 return VINF_SUCCESS;
147#else
148 size_t cbWritten = 0;
149 return RTPipeWrite(pThis->hPipeWakeW, &bReason, 1, &cbWritten);
150#endif
151}
152
153
154/** @interface_method_impl{PDMISTREAM,pfnPoll} */
155static DECLCALLBACK(int) drvNamedPipePoll(PPDMISTREAM pInterface, uint32_t fEvts, uint32_t *pfEvts, RTMSINTERVAL cMillies)
156{
157 int rc = VINF_SUCCESS;
158 PDRVNAMEDPIPE pThis = RT_FROM_MEMBER(pInterface, DRVNAMEDPIPE, IStream);
159
160 LogFlowFunc(("pInterface=%#p fEvts=%#x pfEvts=%#p cMillies=%u\n", pInterface, fEvts, pfEvts, cMillies));
161
162#ifdef RT_OS_WINDOWS
163 /* Immediately return if there is something to read or no write pending and the respective events are set. */
164 *pfEvts = 0;
165 if ( (fEvts & RTPOLL_EVT_READ)
166 && pThis->cbReadBufUsed > 0)
167 *pfEvts |= RTPOLL_EVT_READ;
168 if ( (fEvts & RTPOLL_EVT_WRITE)
169 && !pThis->cbWriteBufUsed)
170 *pfEvts |= RTPOLL_EVT_WRITE;
171
172 if (*pfEvts)
173 return VINF_SUCCESS;
174
175 while (RT_SUCCESS(rc))
176 {
177 /* Set up the waiting handles. */
178 HANDLE ahEvts[3];
179 unsigned cEvts = 0;
180
181 ahEvts[cEvts++] = pThis->hEvtWake;
182 if (fEvts & RTPOLL_EVT_WRITE)
183 {
184 Assert(pThis->cbWriteBufUsed);
185 ahEvts[cEvts++] = pThis->OverlappedWrite.hEvent;
186 }
187 if ( (fEvts & RTPOLL_EVT_READ)
188 && pThis->NamedPipe != INVALID_HANDLE_VALUE
189 && !pThis->fReadPending)
190 {
191 Assert(!pThis->cbReadBufUsed);
192
193 DWORD cbReallyRead;
194 pThis->OverlappedRead.Offset = 0;
195 pThis->OverlappedRead.OffsetHigh = 0;
196 if (!ReadFile(pThis->NamedPipe, &pThis->abBufRead[0], sizeof(pThis->abBufRead), &cbReallyRead, &pThis->OverlappedRead))
197 {
198 DWORD uError = GetLastError();
199
200 if (uError == ERROR_IO_PENDING)
201 {
202 uError = 0;
203 pThis->fReadPending = true;
204 }
205
206 if ( uError == ERROR_PIPE_LISTENING
207 || uError == ERROR_PIPE_NOT_CONNECTED)
208 {
209 /* No connection yet/anymore */
210 cbReallyRead = 0;
211 }
212 else
213 {
214 rc = RTErrConvertFromWin32(uError);
215 Log(("drvNamedPipePoll: ReadFile returned %d (%Rrc)\n", uError, rc));
216 }
217 }
218 else
219 {
220 LogFlowFunc(("Read completed: cbReallyRead=%u\n", cbReallyRead));
221 pThis->fReadPending = false;
222 *pfEvts |= RTPOLL_EVT_READ;
223 return VINF_SUCCESS;
224 }
225
226 if (RT_FAILURE(rc))
227 {
228 Log(("drvNamedPipePoll: FileRead returned %Rrc fShutdown=%d\n", rc, pThis->fShutdown));
229 if ( !pThis->fShutdown
230 && ( rc == VERR_EOF
231 || rc == VERR_BROKEN_PIPE
232 )
233 )
234 {
235 FlushFileBuffers(pThis->NamedPipe);
236 DisconnectNamedPipe(pThis->NamedPipe);
237 if (!pThis->fIsServer)
238 {
239 CloseHandle(pThis->NamedPipe);
240 pThis->NamedPipe = INVALID_HANDLE_VALUE;
241 }
242 /* pretend success */
243 rc = VINF_SUCCESS;
244 }
245 cbReallyRead = 0;
246 }
247 }
248
249 if (pThis->fReadPending)
250 ahEvts[cEvts++] = pThis->OverlappedRead.hEvent;
251
252 DWORD dwMillies = cMillies == RT_INDEFINITE_WAIT ? INFINITE : cMillies;
253 DWORD uErr = WaitForMultipleObjects(cEvts, &ahEvts[0], FALSE /* bWaitAll */, dwMillies);
254 if (uErr == WAIT_TIMEOUT)
255 rc = VERR_TIMEOUT;
256 else if (uErr == WAIT_FAILED)
257 rc = RTErrConvertFromWin32(GetLastError());
258 else
259 {
260 /* Something triggered. */
261 unsigned idxEvt = uErr - WAIT_OBJECT_0;
262 Assert(idxEvt < cEvts);
263
264 LogFlowFunc(("Interrupted by pipe activity: idxEvt=%u\n", idxEvt));
265
266 if (idxEvt == 0)
267 {
268 /* The wakeup triggered. */
269 if (ASMAtomicXchgBool(&pThis->fWakeExternal, false))
270 rc = VERR_INTERRUPTED;
271 else
272 {
273 /*
274 * Internal event because there was a new connection from the listener thread,
275 * restart everything.
276 */
277 rc = VINF_SUCCESS;
278 }
279 }
280 else if (ahEvts[idxEvt] == pThis->OverlappedWrite.hEvent)
281 {
282 LogFlowFunc(("Write completed\n"));
283 /* Fetch the result of the write. */
284 DWORD cbWritten = 0;
285 if (GetOverlappedResult(pThis->NamedPipe, &pThis->OverlappedWrite, &cbWritten, TRUE) == FALSE)
286 {
287 uErr = GetLastError();
288 rc = RTErrConvertFromWin32(uErr);
289 Log(("drvNamedPipePoll: Write completed with %d (%Rrc)\n", uErr, rc));
290
291 if (RT_FAILURE(rc))
292 {
293 /** @todo WriteFile(pipe) has been observed to return ERROR_NO_DATA
294 * (VERR_NO_DATA) instead of ERROR_BROKEN_PIPE, when the pipe is
295 * disconnected. */
296 if ( rc == VERR_EOF
297 || rc == VERR_BROKEN_PIPE)
298 {
299 FlushFileBuffers(pThis->NamedPipe);
300 DisconnectNamedPipe(pThis->NamedPipe);
301 if (!pThis->fIsServer)
302 {
303 CloseHandle(pThis->NamedPipe);
304 pThis->NamedPipe = INVALID_HANDLE_VALUE;
305 }
306 /* pretend success */
307 rc = VINF_SUCCESS;
308 }
309 cbWritten = (DWORD)pThis->cbWriteBufUsed;
310 }
311 }
312
313 pThis->cbWriteBufUsed -= cbWritten;
314 if (!pThis->cbWriteBufUsed && (fEvts & RTPOLL_EVT_WRITE))
315 {
316 *pfEvts |= RTPOLL_EVT_WRITE;
317 break;
318 }
319 }
320 else
321 {
322 Assert(ahEvts[idxEvt] == pThis->OverlappedRead.hEvent);
323
324 DWORD cbRead = 0;
325 if (GetOverlappedResult(pThis->NamedPipe, &pThis->OverlappedRead, &cbRead, TRUE) == FALSE)
326 {
327 uErr = GetLastError();
328 rc = RTErrConvertFromWin32(uErr);
329 Log(("drvNamedPipePoll: Read completed with %d (%Rrc)\n", uErr, rc));
330
331 if (RT_FAILURE(rc))
332 {
333 /** @todo WriteFile(pipe) has been observed to return ERROR_NO_DATA
334 * (VERR_NO_DATA) instead of ERROR_BROKEN_PIPE, when the pipe is
335 * disconnected. */
336 if ( rc == VERR_EOF
337 || rc == VERR_BROKEN_PIPE)
338 {
339 FlushFileBuffers(pThis->NamedPipe);
340 DisconnectNamedPipe(pThis->NamedPipe);
341 if (!pThis->fIsServer)
342 {
343 CloseHandle(pThis->NamedPipe);
344 pThis->NamedPipe = INVALID_HANDLE_VALUE;
345 }
346 /* pretend success */
347 rc = VINF_SUCCESS;
348 }
349 cbRead = 0;
350 }
351 }
352
353 LogFlowFunc(("Read completed with cbRead=%u\n", cbRead));
354 pThis->fReadPending = false;
355 pThis->cbReadBufUsed = cbRead;
356 if (pThis->cbReadBufUsed && (fEvts & RTPOLL_EVT_READ))
357 {
358 *pfEvts |= RTPOLL_EVT_READ;
359 break;
360 }
361 }
362 }
363 }
364#else
365 if (pThis->hSock != NIL_RTSOCKET)
366 {
367 if (!pThis->fSockInPollSet)
368 {
369 rc = RTPollSetAddSocket(pThis->hPollSet, pThis->hSock,
370 fEvts, DRVNAMEDPIPE_POLLSET_ID_SOCKET);
371 if (RT_SUCCESS(rc))
372 pThis->fSockInPollSet = true;
373 }
374 else
375 {
376 /* Always include error event. */
377 fEvts |= RTPOLL_EVT_ERROR;
378 rc = RTPollSetEventsChange(pThis->hPollSet, DRVNAMEDPIPE_POLLSET_ID_SOCKET, fEvts);
379 AssertRC(rc);
380 }
381 }
382
383 while (RT_SUCCESS(rc))
384 {
385 uint32_t fEvtsRecv = 0;
386 uint32_t idHnd = 0;
387
388 rc = RTPoll(pThis->hPollSet, cMillies, &fEvtsRecv, &idHnd);
389 if (RT_SUCCESS(rc))
390 {
391 if (idHnd == DRVNAMEDPIPE_POLLSET_ID_WAKEUP)
392 {
393 /* We got woken up, drain the pipe and return. */
394 uint8_t bReason;
395 size_t cbRead = 0;
396 rc = RTPipeRead(pThis->hPipeWakeR, &bReason, 1, &cbRead);
397 AssertRC(rc);
398
399 if (bReason == DRVNAMEDPIPE_WAKEUP_REASON_EXTERNAL)
400 rc = VERR_INTERRUPTED;
401 else if (bReason == DRVNAMEDPIPE_WAKEUP_REASON_NEW_CONNECTION)
402 {
403 Assert(!pThis->fSockInPollSet);
404 rc = RTPollSetAddSocket(pThis->hPollSet, pThis->hSock,
405 fEvts, DRVNAMEDPIPE_POLLSET_ID_SOCKET);
406 if (RT_SUCCESS(rc))
407 pThis->fSockInPollSet = true;
408 }
409 else
410 AssertMsgFailed(("Unknown wakeup reason in pipe %u\n", bReason));
411 }
412 else
413 {
414 Assert(idHnd == DRVNAMEDPIPE_POLLSET_ID_SOCKET);
415
416 /* On error we close the socket here. */
417 if (fEvtsRecv & RTPOLL_EVT_ERROR)
418 {
419 rc = RTPollSetRemove(pThis->hPollSet, DRVNAMEDPIPE_POLLSET_ID_SOCKET);
420 AssertRC(rc);
421
422 RTSocketClose(pThis->hSock);
423 pThis->hSock = NIL_RTSOCKET;
424 pThis->fSockInPollSet = false;
425 /* Continue with polling. */
426 }
427 else
428 {
429 *pfEvts = fEvtsRecv;
430 break;
431 }
432 }
433 }
434 }
435#endif
436
437 LogFlowFunc(("returns %Rrc\n", rc));
438 return rc;
439}
440
441
442/** @interface_method_impl{PDMISTREAM,pfnPollInterrupt} */
443static DECLCALLBACK(int) drvNamedPipePollInterrupt(PPDMISTREAM pInterface)
444{
445 PDRVNAMEDPIPE pThis = RT_FROM_MEMBER(pInterface, DRVNAMEDPIPE, IStream);
446 return drvNamedPipePollerKick(pThis, DRVNAMEDPIPE_WAKEUP_REASON_EXTERNAL);
447}
448
449
450/** @interface_method_impl{PDMISTREAM,pfnRead} */
451static DECLCALLBACK(int) drvNamedPipeRead(PPDMISTREAM pInterface, void *pvBuf, size_t *pcbRead)
452{
453 int rc = VINF_SUCCESS;
454 PDRVNAMEDPIPE pThis = RT_FROM_MEMBER(pInterface, DRVNAMEDPIPE, IStream);
455 LogFlow(("%s: pvBuf=%p *pcbRead=%#x (%s)\n", __FUNCTION__, pvBuf, *pcbRead, pThis->pszLocation));
456
457 Assert(pvBuf);
458#ifdef RT_OS_WINDOWS
459 if (pThis->NamedPipe != INVALID_HANDLE_VALUE)
460 {
461 /* Check if there is something in the read buffer and return as much as we can. */
462 if (pThis->cbReadBufUsed)
463 {
464 size_t cbRead = RT_MIN(*pcbRead, pThis->cbReadBufUsed);
465
466 memcpy(pvBuf, &pThis->abBufRead[0], cbRead);
467 if (cbRead < pThis->cbReadBufUsed)
468 memmove(&pThis->abBufRead[0], &pThis->abBufRead[cbRead], pThis->cbReadBufUsed - cbRead);
469 pThis->cbReadBufUsed -= cbRead;
470 *pcbRead = cbRead;
471 }
472 else
473 *pcbRead = 0;
474 }
475#else /* !RT_OS_WINDOWS */
476 if (pThis->hSock != NIL_RTSOCKET)
477 {
478 size_t cbRead;
479 size_t cbBuf = *pcbRead;
480 rc = RTSocketReadNB(pThis->hSock, pvBuf, cbBuf, &cbRead);
481 if (RT_SUCCESS(rc))
482 {
483 if (!cbRead && rc != VINF_TRY_AGAIN)
484 {
485 rc = RTPollSetRemove(pThis->hPollSet, DRVNAMEDPIPE_POLLSET_ID_SOCKET);
486 AssertRC(rc);
487
488 RTSocketClose(pThis->hSock);
489 pThis->hSock = NIL_RTSOCKET;
490 pThis->fSockInPollSet = false;
491 rc = VINF_SUCCESS;
492 }
493 *pcbRead = cbRead;
494 }
495 }
496#endif /* !RT_OS_WINDOWS */
497 else
498 {
499 RTThreadSleep(100);
500 *pcbRead = 0;
501 }
502
503 LogFlow(("%s: *pcbRead=%zu returns %Rrc\n", __FUNCTION__, *pcbRead, rc));
504 return rc;
505}
506
507
508/** @interface_method_impl{PDMISTREAM,pfnWrite} */
509static DECLCALLBACK(int) drvNamedPipeWrite(PPDMISTREAM pInterface, const void *pvBuf, size_t *pcbWrite)
510{
511 int rc = VINF_SUCCESS;
512 PDRVNAMEDPIPE pThis = RT_FROM_MEMBER(pInterface, DRVNAMEDPIPE, IStream);
513 LogFlow(("%s: pvBuf=%p *pcbWrite=%#x (%s)\n", __FUNCTION__, pvBuf, *pcbWrite, pThis->pszLocation));
514
515 Assert(pvBuf);
516#ifdef RT_OS_WINDOWS
517 if (pThis->NamedPipe != INVALID_HANDLE_VALUE)
518 {
519 /* Accept the data in case the write buffer is empty. */
520 if (!pThis->cbWriteBufUsed)
521 {
522 size_t cbWrite = RT_MIN(*pcbWrite, sizeof(pThis->cbWriteBufUsed));
523
524 memcpy(&pThis->abBufWrite[0], pvBuf, cbWrite);
525 pThis->cbWriteBufUsed += cbWrite;
526
527 /* Initiate the write. */
528 pThis->OverlappedWrite.Offset = 0;
529 pThis->OverlappedWrite.OffsetHigh = 0;
530 if (!WriteFile(pThis->NamedPipe, pvBuf, (DWORD)cbWrite, NULL, &pThis->OverlappedWrite))
531 {
532 DWORD uError = GetLastError();
533
534 if ( uError == ERROR_PIPE_LISTENING
535 || uError == ERROR_PIPE_NOT_CONNECTED)
536 {
537 /* No connection yet/anymore; just discard the write (pretending everything was written). */
538 pThis->cbWriteBufUsed = 0;
539 cbWrite = *pcbWrite;
540 }
541 else if (uError != ERROR_IO_PENDING) /* We wait for the write to complete in the poll callback. */
542 {
543 rc = RTErrConvertFromWin32(uError);
544 Log(("drvNamedPipeWrite: WriteFile returned %d (%Rrc)\n", uError, rc));
545 cbWrite = 0;
546 }
547 }
548
549 if (RT_FAILURE(rc))
550 {
551 /** @todo WriteFile(pipe) has been observed to return ERROR_NO_DATA
552 * (VERR_NO_DATA) instead of ERROR_BROKEN_PIPE, when the pipe is
553 * disconnected. */
554 if ( rc == VERR_EOF
555 || rc == VERR_BROKEN_PIPE)
556 {
557 FlushFileBuffers(pThis->NamedPipe);
558 DisconnectNamedPipe(pThis->NamedPipe);
559 if (!pThis->fIsServer)
560 {
561 CloseHandle(pThis->NamedPipe);
562 pThis->NamedPipe = INVALID_HANDLE_VALUE;
563 }
564 /* pretend success */
565 rc = VINF_SUCCESS;
566 }
567 cbWrite = 0;
568 }
569
570 *pcbWrite = cbWrite;
571 }
572 else
573 *pcbWrite = 0;
574 }
575#else /* !RT_OS_WINDOWS */
576 if (pThis->hSock != NIL_RTSOCKET)
577 {
578 size_t cbBuf = *pcbWrite;
579 rc = RTSocketWriteNB(pThis->hSock, pvBuf, cbBuf, pcbWrite);
580 }
581 else
582 *pcbWrite = 0;
583#endif /* !RT_OS_WINDOWS */
584
585 LogFlow(("%s: returns %Rrc\n", __FUNCTION__, rc));
586 return rc;
587}
588
589
590/**
591 * @interface_method_impl{PDMIBASE,pfnQueryInterface}
592 */
593static DECLCALLBACK(void *) drvNamedPipeQueryInterface(PPDMIBASE pInterface, const char *pszIID)
594{
595 PPDMDRVINS pDrvIns = PDMIBASE_2_PDMDRV(pInterface);
596 PDRVNAMEDPIPE pThis = PDMINS_2_DATA(pDrvIns, PDRVNAMEDPIPE);
597 PDMIBASE_RETURN_INTERFACE(pszIID, PDMIBASE, &pDrvIns->IBase);
598 PDMIBASE_RETURN_INTERFACE(pszIID, PDMISTREAM, &pThis->IStream);
599 return NULL;
600}
601
602
603/* -=-=-=-=- listen thread -=-=-=-=- */
604
605/**
606 * Receive thread loop.
607 *
608 * @returns 0 on success.
609 * @param hThreadSelf Thread handle to this thread.
610 * @param pvUser User argument.
611 */
612static DECLCALLBACK(int) drvNamedPipeListenLoop(RTTHREAD hThreadSelf, void *pvUser)
613{
614 RT_NOREF(hThreadSelf);
615 PDRVNAMEDPIPE pThis = (PDRVNAMEDPIPE)pvUser;
616 int rc = VINF_SUCCESS;
617#ifdef RT_OS_WINDOWS
618 HANDLE NamedPipe = pThis->NamedPipe;
619 HANDLE hEvent = CreateEvent(NULL, TRUE, FALSE, 0);
620#endif
621
622 while (RT_LIKELY(!pThis->fShutdown))
623 {
624#ifdef RT_OS_WINDOWS
625 OVERLAPPED overlapped;
626
627 memset(&overlapped, 0, sizeof(overlapped));
628 overlapped.hEvent = hEvent;
629
630 BOOL fConnected = ConnectNamedPipe(NamedPipe, &overlapped);
631 if ( !fConnected
632 && !pThis->fShutdown)
633 {
634 DWORD hrc = GetLastError();
635
636 if (hrc == ERROR_IO_PENDING)
637 {
638 DWORD dummy;
639
640 hrc = 0;
641 if (GetOverlappedResult(pThis->NamedPipe, &overlapped, &dummy, TRUE) == FALSE)
642 hrc = GetLastError();
643 else
644 drvNamedPipePollerKick(pThis, DRVNAMEDPIPE_WAKEUP_REASON_NEW_CONNECTION);
645 }
646
647 if (pThis->fShutdown)
648 break;
649
650 if (hrc == ERROR_PIPE_CONNECTED)
651 {
652 RTSemEventMultiWait(pThis->ListenSem, 250);
653 }
654 else if (hrc != ERROR_SUCCESS)
655 {
656 rc = RTErrConvertFromWin32(hrc);
657 LogRel(("NamedPipe%d: ConnectNamedPipe failed, rc=%Rrc\n", pThis->pDrvIns->iInstance, rc));
658 break;
659 }
660 }
661#else /* !RT_OS_WINDOWS */
662 if (listen(pThis->LocalSocketServer, 0) == -1)
663 {
664 rc = RTErrConvertFromErrno(errno);
665 LogRel(("NamedPipe%d: listen failed, rc=%Rrc\n", pThis->pDrvIns->iInstance, rc));
666 break;
667 }
668 int s = accept(pThis->LocalSocketServer, NULL, NULL);
669 if (s == -1)
670 {
671 rc = RTErrConvertFromErrno(errno);
672 LogRel(("NamedPipe%d: accept failed, rc=%Rrc\n", pThis->pDrvIns->iInstance, rc));
673 break;
674 }
675 if (pThis->hSock != NIL_RTSOCKET)
676 {
677 LogRel(("NamedPipe%d: only single connection supported\n", pThis->pDrvIns->iInstance));
678 close(s);
679 }
680 else
681 {
682 RTSOCKET hSockNew = NIL_RTSOCKET;
683 rc = RTSocketFromNative(&hSockNew, s);
684 if (RT_SUCCESS(rc))
685 {
686 pThis->hSock = hSockNew;
687 /* Inform the poller about the new socket. */
688 drvNamedPipePollerKick(pThis, DRVNAMEDPIPE_WAKEUP_REASON_NEW_CONNECTION);
689 }
690 else
691 {
692 LogRel(("NamedPipe%d: Failed to wrap socket with %Rrc\n", pThis->pDrvIns->iInstance, rc));
693 close(s);
694 }
695 }
696#endif /* !RT_OS_WINDOWS */
697 }
698
699#ifdef RT_OS_WINDOWS
700 CloseHandle(hEvent);
701#endif
702 return VINF_SUCCESS;
703}
704
705/* -=-=-=-=- PDMDRVREG -=-=-=-=- */
706
707/**
708 * Common worker for drvNamedPipePowerOff and drvNamedPipeDestructor.
709 *
710 * @param pThis The instance data.
711 */
712static void drvNamedPipeShutdownListener(PDRVNAMEDPIPE pThis)
713{
714 /*
715 * Signal shutdown of the listener thread.
716 */
717 pThis->fShutdown = true;
718#ifdef RT_OS_WINDOWS
719 if ( pThis->fIsServer
720 && pThis->NamedPipe != INVALID_HANDLE_VALUE)
721 {
722 FlushFileBuffers(pThis->NamedPipe);
723 DisconnectNamedPipe(pThis->NamedPipe);
724
725 BOOL fRc = CloseHandle(pThis->NamedPipe);
726 Assert(fRc); NOREF(fRc);
727 pThis->NamedPipe = INVALID_HANDLE_VALUE;
728
729 /* Wake up listen thread */
730 if (pThis->ListenSem != NIL_RTSEMEVENT)
731 RTSemEventMultiSignal(pThis->ListenSem);
732 }
733#else
734 if ( pThis->fIsServer
735 && pThis->LocalSocketServer != -1)
736 {
737 int rc = shutdown(pThis->LocalSocketServer, SHUT_RDWR);
738 AssertRC(rc == 0); NOREF(rc);
739
740 rc = close(pThis->LocalSocketServer);
741 AssertRC(rc == 0);
742 pThis->LocalSocketServer = -1;
743 }
744#endif
745}
746
747
748/**
749 * Power off a named pipe stream driver instance.
750 *
751 * This does most of the destruction work, to avoid ordering dependencies.
752 *
753 * @param pDrvIns The driver instance data.
754 */
755static DECLCALLBACK(void) drvNamedPipePowerOff(PPDMDRVINS pDrvIns)
756{
757 PDRVNAMEDPIPE pThis = PDMINS_2_DATA(pDrvIns, PDRVNAMEDPIPE);
758 LogFlow(("%s: %s\n", __FUNCTION__, pThis->pszLocation));
759
760 drvNamedPipeShutdownListener(pThis);
761}
762
763
764/**
765 * Destruct a named pipe stream driver instance.
766 *
767 * Most VM resources are freed by the VM. This callback is provided so that
768 * any non-VM resources can be freed correctly.
769 *
770 * @param pDrvIns The driver instance data.
771 */
772static DECLCALLBACK(void) drvNamedPipeDestruct(PPDMDRVINS pDrvIns)
773{
774 PDRVNAMEDPIPE pThis = PDMINS_2_DATA(pDrvIns, PDRVNAMEDPIPE);
775 LogFlow(("%s: %s\n", __FUNCTION__, pThis->pszLocation));
776 PDMDRV_CHECK_VERSIONS_RETURN_VOID(pDrvIns);
777
778 drvNamedPipeShutdownListener(pThis);
779
780 /*
781 * While the thread exits, clean up as much as we can.
782 */
783#ifdef RT_OS_WINDOWS
784 if (pThis->NamedPipe != INVALID_HANDLE_VALUE)
785 {
786 CloseHandle(pThis->NamedPipe);
787 pThis->NamedPipe = INVALID_HANDLE_VALUE;
788 }
789 if (pThis->OverlappedRead.hEvent != NULL)
790 {
791 CloseHandle(pThis->OverlappedRead.hEvent);
792 pThis->OverlappedRead.hEvent = NULL;
793 }
794 if (pThis->OverlappedWrite.hEvent != NULL)
795 {
796 CloseHandle(pThis->OverlappedWrite.hEvent);
797 pThis->OverlappedWrite.hEvent = NULL;
798 }
799 if (pThis->hEvtWake != NULL)
800 {
801 CloseHandle(pThis->hEvtWake);
802 pThis->hEvtWake = NULL;
803 }
804#else /* !RT_OS_WINDOWS */
805 Assert(pThis->LocalSocketServer == -1);
806
807 if (pThis->hSock != NIL_RTSOCKET)
808 {
809 int rc = RTPollSetRemove(pThis->hPollSet, DRVNAMEDPIPE_POLLSET_ID_SOCKET);
810 AssertRC(rc);
811
812 rc = RTSocketShutdown(pThis->hSock, true /* fRead */, true /* fWrite */);
813 AssertRC(rc);
814
815 rc = RTSocketClose(pThis->hSock);
816 AssertRC(rc); RT_NOREF(rc);
817
818 pThis->hSock = NIL_RTSOCKET;
819 }
820
821 if (pThis->hPipeWakeR != NIL_RTPIPE)
822 {
823 int rc = RTPipeClose(pThis->hPipeWakeR);
824 AssertRC(rc);
825
826 pThis->hPipeWakeR = NIL_RTPIPE;
827 }
828
829 if (pThis->hPipeWakeW != NIL_RTPIPE)
830 {
831 int rc = RTPipeClose(pThis->hPipeWakeW);
832 AssertRC(rc);
833
834 pThis->hPipeWakeW = NIL_RTPIPE;
835 }
836
837 if (pThis->hPollSet != NIL_RTPOLLSET)
838 {
839 int rc = RTPollSetDestroy(pThis->hPollSet);
840 AssertRC(rc);
841
842 pThis->hPollSet = NIL_RTPOLLSET;
843 }
844
845 if ( pThis->fIsServer
846 && pThis->pszLocation)
847 RTFileDelete(pThis->pszLocation);
848#endif /* !RT_OS_WINDOWS */
849
850 MMR3HeapFree(pThis->pszLocation);
851 pThis->pszLocation = NULL;
852
853 /*
854 * Wait for the thread.
855 */
856 if (pThis->ListenThread != NIL_RTTHREAD)
857 {
858 int rc = RTThreadWait(pThis->ListenThread, 30000, NULL);
859 if (RT_SUCCESS(rc))
860 pThis->ListenThread = NIL_RTTHREAD;
861 else
862 LogRel(("NamedPipe%d: listen thread did not terminate (%Rrc)\n", pDrvIns->iInstance, rc));
863 }
864
865 /*
866 * The last bits of cleanup.
867 */
868#ifdef RT_OS_WINDOWS
869 if (pThis->ListenSem != NIL_RTSEMEVENT)
870 {
871 RTSemEventMultiDestroy(pThis->ListenSem);
872 pThis->ListenSem = NIL_RTSEMEVENT;
873 }
874#endif
875}
876
877
878/**
879 * Construct a named pipe stream driver instance.
880 *
881 * @copydoc FNPDMDRVCONSTRUCT
882 */
883static DECLCALLBACK(int) drvNamedPipeConstruct(PPDMDRVINS pDrvIns, PCFGMNODE pCfg, uint32_t fFlags)
884{
885 RT_NOREF(fFlags);
886 PDMDRV_CHECK_VERSIONS_RETURN(pDrvIns);
887 PDRVNAMEDPIPE pThis = PDMINS_2_DATA(pDrvIns, PDRVNAMEDPIPE);
888
889 /*
890 * Init the static parts.
891 */
892 pThis->pDrvIns = pDrvIns;
893 pThis->pszLocation = NULL;
894 pThis->fIsServer = false;
895#ifdef RT_OS_WINDOWS
896 pThis->NamedPipe = INVALID_HANDLE_VALUE;
897 pThis->ListenSem = NIL_RTSEMEVENTMULTI;
898 pThis->OverlappedWrite.hEvent = NULL;
899 pThis->OverlappedRead.hEvent = NULL;
900 pThis->hEvtWake = NULL;
901#else /* !RT_OS_WINDOWS */
902 pThis->LocalSocketServer = -1;
903 pThis->hSock = NIL_RTSOCKET;
904
905 pThis->hPollSet = NIL_RTPOLLSET;
906 pThis->hPipeWakeR = NIL_RTPIPE;
907 pThis->hPipeWakeW = NIL_RTPIPE;
908 pThis->fSockInPollSet = false;
909#endif /* !RT_OS_WINDOWS */
910 pThis->ListenThread = NIL_RTTHREAD;
911 pThis->fShutdown = false;
912 /* IBase */
913 pDrvIns->IBase.pfnQueryInterface = drvNamedPipeQueryInterface;
914 /* IStream */
915 pThis->IStream.pfnPoll = drvNamedPipePoll;
916 pThis->IStream.pfnPollInterrupt = drvNamedPipePollInterrupt;
917 pThis->IStream.pfnRead = drvNamedPipeRead;
918 pThis->IStream.pfnWrite = drvNamedPipeWrite;
919
920 /*
921 * Validate and read the configuration.
922 */
923 PDMDRV_VALIDATE_CONFIG_RETURN(pDrvIns, "Location|IsServer", "");
924
925 int rc = CFGMR3QueryStringAlloc(pCfg, "Location", &pThis->pszLocation);
926 if (RT_FAILURE(rc))
927 return PDMDrvHlpVMSetError(pDrvIns, rc, RT_SRC_POS,
928 N_("Configuration error: querying \"Location\" resulted in %Rrc"), rc);
929 rc = CFGMR3QueryBool(pCfg, "IsServer", &pThis->fIsServer);
930 if (RT_FAILURE(rc))
931 return PDMDrvHlpVMSetError(pDrvIns, rc, RT_SRC_POS,
932 N_("Configuration error: querying \"IsServer\" resulted in %Rrc"), rc);
933
934 /*
935 * Create/Open the pipe.
936 */
937#ifdef RT_OS_WINDOWS
938 if (pThis->fIsServer)
939 {
940 pThis->NamedPipe = CreateNamedPipe(pThis->pszLocation,
941 PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
942 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT,
943 1, /*nMaxInstances*/
944 32, /*nOutBufferSize*/
945 32, /*nOutBufferSize*/
946 10000, /*nDefaultTimeOut*/
947 NULL); /* lpSecurityAttributes*/
948 if (pThis->NamedPipe == INVALID_HANDLE_VALUE)
949 {
950 rc = RTErrConvertFromWin32(GetLastError());
951 LogRel(("NamedPipe%d: CreateNamedPipe failed rc=%Rrc\n", pThis->pDrvIns->iInstance));
952 return PDMDrvHlpVMSetError(pDrvIns, rc, RT_SRC_POS, N_("NamedPipe#%d failed to create named pipe %s"),
953 pDrvIns->iInstance, pThis->pszLocation);
954 }
955
956 rc = RTSemEventMultiCreate(&pThis->ListenSem);
957 AssertRCReturn(rc, rc);
958
959 rc = RTThreadCreate(&pThis->ListenThread, drvNamedPipeListenLoop, (void *)pThis, 0,
960 RTTHREADTYPE_IO, RTTHREADFLAGS_WAITABLE, "SerPipe");
961 if (RT_FAILURE(rc))
962 return PDMDrvHlpVMSetError(pDrvIns, rc, RT_SRC_POS, N_("NamedPipe#%d failed to create listening thread"),
963 pDrvIns->iInstance);
964
965 }
966 else
967 {
968 /* Connect to the named pipe. */
969 pThis->NamedPipe = CreateFile(pThis->pszLocation, GENERIC_READ | GENERIC_WRITE, 0, NULL,
970 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL);
971 if (pThis->NamedPipe == INVALID_HANDLE_VALUE)
972 {
973 rc = RTErrConvertFromWin32(GetLastError());
974 LogRel(("NamedPipe%d: CreateFile failed rc=%Rrc\n", pThis->pDrvIns->iInstance));
975 return PDMDrvHlpVMSetError(pDrvIns, rc, RT_SRC_POS, N_("NamedPipe#%d failed to connect to named pipe %s"),
976 pDrvIns->iInstance, pThis->pszLocation);
977 }
978 }
979
980 memset(&pThis->OverlappedWrite, 0, sizeof(pThis->OverlappedWrite));
981 pThis->OverlappedWrite.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
982 AssertReturn(pThis->OverlappedWrite.hEvent != NULL, VERR_OUT_OF_RESOURCES);
983
984 memset(&pThis->OverlappedRead, 0, sizeof(pThis->OverlappedRead));
985 pThis->OverlappedRead.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
986 AssertReturn(pThis->OverlappedRead.hEvent != NULL, VERR_OUT_OF_RESOURCES);
987
988 pThis->hEvtWake = CreateEvent(NULL, FALSE, FALSE, NULL);
989 AssertReturn(pThis->hEvtWake != NULL, VERR_OUT_OF_RESOURCES);
990
991#else /* !RT_OS_WINDOWS */
992 rc = RTPipeCreate(&pThis->hPipeWakeR, &pThis->hPipeWakeW, 0 /* fFlags */);
993 if (RT_FAILURE(rc))
994 return PDMDrvHlpVMSetError(pDrvIns, rc, RT_SRC_POS,
995 N_("DrvTCP#%d: Failed to create wake pipe"), pDrvIns->iInstance);
996
997 rc = RTPollSetCreate(&pThis->hPollSet);
998 if (RT_FAILURE(rc))
999 return PDMDrvHlpVMSetError(pDrvIns, rc, RT_SRC_POS,
1000 N_("DrvTCP#%d: Failed to create poll set"), pDrvIns->iInstance);
1001
1002 rc = RTPollSetAddPipe(pThis->hPollSet, pThis->hPipeWakeR,
1003 RTPOLL_EVT_READ | RTPOLL_EVT_ERROR,
1004 DRVNAMEDPIPE_POLLSET_ID_WAKEUP);
1005 if (RT_FAILURE(rc))
1006 return PDMDrvHlpVMSetError(pDrvIns, rc, RT_SRC_POS,
1007 N_("DrvTCP#%d failed to add wakeup pipe for %s to poll set"),
1008 pDrvIns->iInstance, pThis->pszLocation);
1009
1010 int s = socket(PF_UNIX, SOCK_STREAM, 0);
1011 if (s == -1)
1012 return PDMDrvHlpVMSetError(pDrvIns, RTErrConvertFromErrno(errno), RT_SRC_POS,
1013 N_("NamedPipe#%d failed to create local socket"), pDrvIns->iInstance);
1014
1015 struct sockaddr_un addr;
1016 memset(&addr, 0, sizeof(addr));
1017 addr.sun_family = AF_UNIX;
1018 strncpy(addr.sun_path, pThis->pszLocation, sizeof(addr.sun_path) - 1);
1019
1020 if (pThis->fIsServer)
1021 {
1022 /* Bind address to the local socket. */
1023 pThis->LocalSocketServer = s;
1024 RTFileDelete(pThis->pszLocation);
1025 if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) == -1)
1026 return PDMDrvHlpVMSetError(pDrvIns, RTErrConvertFromErrno(errno), RT_SRC_POS,
1027 N_("NamedPipe#%d failed to bind to local socket %s"),
1028 pDrvIns->iInstance, pThis->pszLocation);
1029 rc = RTThreadCreate(&pThis->ListenThread, drvNamedPipeListenLoop, (void *)pThis, 0,
1030 RTTHREADTYPE_IO, RTTHREADFLAGS_WAITABLE, "SerPipe");
1031 if (RT_FAILURE(rc))
1032 return PDMDrvHlpVMSetError(pDrvIns, rc, RT_SRC_POS,
1033 N_("NamedPipe#%d failed to create listening thread"), pDrvIns->iInstance);
1034 }
1035 else
1036 {
1037 /* Connect to the local socket. */
1038 if (connect(s, (struct sockaddr *)&addr, sizeof(addr)) == -1)
1039 return PDMDrvHlpVMSetError(pDrvIns, RTErrConvertFromErrno(errno), RT_SRC_POS,
1040 N_("NamedPipe#%d failed to connect to local socket %s"),
1041 pDrvIns->iInstance, pThis->pszLocation);
1042
1043 rc = RTSocketFromNative(&pThis->hSock, s);
1044 if (RT_FAILURE(rc))
1045 {
1046 close(s);
1047 return PDMDrvHlpVMSetError(pDrvIns, rc, RT_SRC_POS,
1048 N_("NamedPipe#%d failed to wrap socket %Rrc"),
1049 pDrvIns->iInstance, pThis->pszLocation);
1050 }
1051 }
1052#endif /* !RT_OS_WINDOWS */
1053
1054 LogRel(("NamedPipe: location %s, %s\n", pThis->pszLocation, pThis->fIsServer ? "server" : "client"));
1055 return VINF_SUCCESS;
1056}
1057
1058
1059/**
1060 * Named pipe driver registration record.
1061 */
1062const PDMDRVREG g_DrvNamedPipe =
1063{
1064 /* u32Version */
1065 PDM_DRVREG_VERSION,
1066 /* szName */
1067 "NamedPipe",
1068 /* szRCMod */
1069 "",
1070 /* szR0Mod */
1071 "",
1072 /* pszDescription */
1073 "Named Pipe stream driver.",
1074 /* fFlags */
1075 PDM_DRVREG_FLAGS_HOST_BITS_DEFAULT,
1076 /* fClass. */
1077 PDM_DRVREG_CLASS_STREAM,
1078 /* cMaxInstances */
1079 ~0U,
1080 /* cbInstance */
1081 sizeof(DRVNAMEDPIPE),
1082 /* pfnConstruct */
1083 drvNamedPipeConstruct,
1084 /* pfnDestruct */
1085 drvNamedPipeDestruct,
1086 /* pfnRelocate */
1087 NULL,
1088 /* pfnIOCtl */
1089 NULL,
1090 /* pfnPowerOn */
1091 NULL,
1092 /* pfnReset */
1093 NULL,
1094 /* pfnSuspend */
1095 NULL,
1096 /* pfnResume */
1097 NULL,
1098 /* pfnAttach */
1099 NULL,
1100 /* pfnDetach */
1101 NULL,
1102 /* pfnPowerOff */
1103 drvNamedPipePowerOff,
1104 /* pfnSoftReset */
1105 NULL,
1106 /* u32EndVersion */
1107 PDM_DRVREG_VERSION
1108};
1109
Note: See TracBrowser for help on using the repository browser.

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette