VirtualBox

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

Last change on this file since 103882 was 98103, checked in by vboxsync, 17 months ago

Copyright year updates by scm.

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

© 2023 Oracle
ContactPrivacy policyTerms of Use