VirtualBox

source: vbox/trunk/src/VBox/Runtime/tools/RTFTPServer.cpp@ 82841

最後變更 在這個檔案從82841是 82841,由 vboxsync 提交於 5 年 前

IPRT/FTP: Implemented support for directory traversing. bugref:9646

  • 屬性 svn:eol-style 設為 native
  • 屬性 svn:keywords 設為 Author Date Id Revision
檔案大小: 18.9 KB
 
1/* $Id: RTFTPServer.cpp 82841 2020-01-23 10:02:26Z vboxsync $ */
2/** @file
3 * IPRT - Utility for running a (simple) FTP server.
4 */
5
6/*
7 * Copyright (C) 2020 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.alldomusa.eu.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 * The contents of this file may alternatively be used under the terms
18 * of the Common Development and Distribution License Version 1.0
19 * (CDDL) only, as it comes in the "COPYING.CDDL" file of the
20 * VirtualBox OSE distribution, in which case the provisions of the
21 * CDDL are applicable instead of those of the GPL.
22 *
23 * You may elect to license modified versions of this file under the
24 * terms and conditions of either the GPL or the CDDL or both.
25 */
26
27/*
28 * Use this setup to best see what's going on:
29 *
30 * VBOX_LOG=rt_ftp=~0
31 * VBOX_LOG_DEST="nofile stderr"
32 * VBOX_LOG_FLAGS="unbuffered enabled thread msprog"
33 *
34 */
35
36
37/*********************************************************************************************************************************
38* Header Files *
39*********************************************************************************************************************************/
40#include <signal.h>
41
42#include <iprt/ftp.h>
43
44#include <iprt/net.h> /* To make use of IPv4Addr in RTGETOPTUNION. */
45
46#include <iprt/asm.h>
47#include <iprt/assert.h>
48#include <iprt/ctype.h>
49#include <iprt/err.h>
50#include <iprt/file.h>
51#include <iprt/getopt.h>
52#include <iprt/initterm.h>
53#include <iprt/mem.h>
54#include <iprt/message.h>
55#include <iprt/path.h>
56#include <iprt/stream.h>
57#include <iprt/string.h>
58#include <iprt/thread.h>
59#include <iprt/vfs.h>
60
61#ifdef RT_OS_WINDOWS
62# include <iprt/win/windows.h>
63#endif
64
65
66/*********************************************************************************************************************************
67* Definitations *
68*********************************************************************************************************************************/
69typedef struct FTPSERVERDATA
70{
71 /** The absolute path of the FTP server's root directory. */
72 char szPathRootAbs[RTPATH_MAX];
73 /** The relative current working directory (CWD) to szRootDir. */
74 char szCWD[RTPATH_MAX];
75 RTFILE hFile;
76} FTPSERVERDATA;
77typedef FTPSERVERDATA *PFTPSERVERDATA;
78
79typedef struct FTPDIRHANDLE
80{
81 /** The VFS (chain) handle to use for this directory. */
82 RTVFSDIR hVfsDir;
83} FTPDIRHANDLE;
84typedef FTPDIRHANDLE *PFTPDIRHANDLE;
85
86
87/*********************************************************************************************************************************
88* Global Variables *
89*********************************************************************************************************************************/
90/** Set by the signal handler when the FTP server shall be terminated. */
91static volatile bool g_fCanceled = false;
92static FTPSERVERDATA g_FTPServerData;
93
94
95#ifdef RT_OS_WINDOWS
96static BOOL WINAPI signalHandler(DWORD dwCtrlType)
97{
98 bool fEventHandled = FALSE;
99 switch (dwCtrlType)
100 {
101 /* User pressed CTRL+C or CTRL+BREAK or an external event was sent
102 * via GenerateConsoleCtrlEvent(). */
103 case CTRL_BREAK_EVENT:
104 case CTRL_CLOSE_EVENT:
105 case CTRL_C_EVENT:
106 ASMAtomicWriteBool(&g_fCanceled, true);
107 fEventHandled = TRUE;
108 break;
109 default:
110 break;
111 /** @todo Add other events here. */
112 }
113
114 return fEventHandled;
115}
116#else /* !RT_OS_WINDOWS */
117/**
118 * Signal handler that sets g_fCanceled.
119 *
120 * This can be executed on any thread in the process, on Windows it may even be
121 * a thread dedicated to delivering this signal. Don't do anything
122 * unnecessary here.
123 */
124static void signalHandler(int iSignal)
125{
126 NOREF(iSignal);
127 ASMAtomicWriteBool(&g_fCanceled, true);
128}
129#endif
130
131/**
132 * Installs a custom signal handler to get notified
133 * whenever the user wants to intercept the program.
134 *
135 * @todo Make this handler available for all VBoxManage modules?
136 */
137static int signalHandlerInstall(void)
138{
139 g_fCanceled = false;
140
141 int rc = VINF_SUCCESS;
142#ifdef RT_OS_WINDOWS
143 if (!SetConsoleCtrlHandler((PHANDLER_ROUTINE)signalHandler, TRUE /* Add handler */))
144 {
145 rc = RTErrConvertFromWin32(GetLastError());
146 RTMsgError("Unable to install console control handler, rc=%Rrc\n", rc);
147 }
148#else
149 signal(SIGINT, signalHandler);
150 signal(SIGTERM, signalHandler);
151# ifdef SIGBREAK
152 signal(SIGBREAK, signalHandler);
153# endif
154#endif
155 return rc;
156}
157
158/**
159 * Uninstalls a previously installed signal handler.
160 */
161static int signalHandlerUninstall(void)
162{
163 int rc = VINF_SUCCESS;
164#ifdef RT_OS_WINDOWS
165 if (!SetConsoleCtrlHandler((PHANDLER_ROUTINE)NULL, FALSE /* Remove handler */))
166 {
167 rc = RTErrConvertFromWin32(GetLastError());
168 RTMsgError("Unable to uninstall console control handler, rc=%Rrc\n", rc);
169 }
170#else
171 signal(SIGINT, SIG_DFL);
172 signal(SIGTERM, SIG_DFL);
173# ifdef SIGBREAK
174 signal(SIGBREAK, SIG_DFL);
175# endif
176#endif
177 return rc;
178}
179
180static DECLCALLBACK(int) onUserConnect(PRTFTPCALLBACKDATA pData, const char *pcszUser)
181{
182 RT_NOREF(pData, pcszUser);
183
184 RTPrintf("User '%s' connected\n", pcszUser);
185
186 return VINF_SUCCESS;
187}
188
189static DECLCALLBACK(int) onUserAuthenticate(PRTFTPCALLBACKDATA pData, const char *pcszUser, const char *pcszPassword)
190{
191 RT_NOREF(pData, pcszUser, pcszPassword);
192
193 RTPrintf("Authenticating user '%s' ...\n", pcszUser);
194
195 return VINF_SUCCESS;
196}
197
198static DECLCALLBACK(int) onUserDisonnect(PRTFTPCALLBACKDATA pData, const char *pcszUser)
199{
200 RT_NOREF(pData);
201
202 RTPrintf("User '%s' disconnected\n", pcszUser);
203
204 return VINF_SUCCESS;
205}
206
207static DECLCALLBACK(int) onFileOpen(PRTFTPCALLBACKDATA pData, const char *pcszPath, uint32_t fMode, void **ppvHandle)
208{
209 RT_NOREF(ppvHandle);
210
211 PFTPSERVERDATA pThis = (PFTPSERVERDATA)pData->pvUser;
212 Assert(pData->cbUser == sizeof(FTPSERVERDATA));
213
214 return RTFileOpen(&pThis->hFile, pcszPath, fMode);
215}
216
217static DECLCALLBACK(int) onFileRead(PRTFTPCALLBACKDATA pData, void *pvHandle, void *pvBuf, size_t cbToRead, size_t *pcbRead)
218{
219 RT_NOREF(pvHandle);
220
221 PFTPSERVERDATA pThis = (PFTPSERVERDATA)pData->pvUser;
222 Assert(pData->cbUser == sizeof(FTPSERVERDATA));
223
224 return RTFileRead(pThis->hFile, pvBuf, cbToRead, pcbRead);
225}
226
227static DECLCALLBACK(int) onFileClose(PRTFTPCALLBACKDATA pData, void *pvHandle)
228{
229 RT_NOREF(pvHandle);
230
231 PFTPSERVERDATA pThis = (PFTPSERVERDATA)pData->pvUser;
232 Assert(pData->cbUser == sizeof(FTPSERVERDATA));
233
234 int rc = RTFileClose(pThis->hFile);
235 if (RT_SUCCESS(rc))
236 {
237 pThis->hFile = NIL_RTFILE;
238 }
239
240 return rc;
241}
242
243static DECLCALLBACK(int) onFileGetSize(PRTFTPCALLBACKDATA pData, const char *pcszPath, uint64_t *puSize)
244{
245 PFTPSERVERDATA pThis = (PFTPSERVERDATA)pData->pvUser;
246 Assert(pData->cbUser == sizeof(FTPSERVERDATA));
247
248 char *pszStat = NULL;
249 if (RTStrAPrintf(&pszStat, "%s/%s", pThis->szPathRootAbs, pcszPath) <= 0)
250 return VERR_NO_MEMORY;
251
252 RTPrintf("Retrieving file size for '%s' ...\n", pcszPath);
253
254 RTFILE hFile;
255 int rc = RTFileOpen(&hFile, pcszPath,
256 RTFILE_O_READ | RTFILE_O_OPEN | RTFILE_O_DENY_WRITE);
257 if (RT_SUCCESS(rc))
258 {
259 rc = RTFileQuerySize(hFile, puSize);
260 if (RT_SUCCESS(rc))
261 RTPrintf("File size is: %RU64\n", *puSize);
262 RTFileClose(hFile);
263 }
264
265 RTStrFree(pszStat);
266
267 return rc;
268}
269
270static DECLCALLBACK(int) onFileStat(PRTFTPCALLBACKDATA pData, const char *pcszPath, PRTFSOBJINFO pFsObjInfo)
271{
272 PFTPSERVERDATA pThis = (PFTPSERVERDATA)pData->pvUser;
273 Assert(pData->cbUser == sizeof(FTPSERVERDATA));
274
275 char *pszStat = NULL;
276 if (RTStrAPrintf(&pszStat, "%s/%s", pThis->szPathRootAbs, pcszPath) <= 0)
277 return VERR_NO_MEMORY;
278
279 RTPrintf("Stat for '%s'\n", pszStat);
280
281 RTFILE hFile;
282 int rc = RTFileOpen(&hFile, pszStat,
283 RTFILE_O_READ | RTFILE_O_OPEN | RTFILE_O_DENY_WRITE);
284 if (RT_SUCCESS(rc))
285 {
286 RTFSOBJINFO fsObjInfo;
287 rc = RTFileQueryInfo(hFile, &fsObjInfo, RTFSOBJATTRADD_NOTHING);
288 if (RT_SUCCESS(rc))
289 {
290 if (pFsObjInfo)
291 *pFsObjInfo = fsObjInfo;
292 }
293
294 RTFileClose(hFile);
295 }
296
297 RTStrFree(pszStat);
298
299 return rc;
300}
301
302static DECLCALLBACK(int) onPathSetCurrent(PRTFTPCALLBACKDATA pData, const char *pcszCWD)
303{
304 PFTPSERVERDATA pThis = (PFTPSERVERDATA)pData->pvUser;
305 Assert(pData->cbUser == sizeof(FTPSERVERDATA));
306
307 RTPrintf("Setting current directory to '%s'\n", pcszCWD);
308
309 /** @todo BUGBUG Santiy checks! */
310
311 return RTStrCopy(pThis->szCWD, sizeof(pThis->szCWD), pcszCWD);
312}
313
314static DECLCALLBACK(int) onPathGetCurrent(PRTFTPCALLBACKDATA pData, char *pszPWD, size_t cbPWD)
315{
316 PFTPSERVERDATA pThis = (PFTPSERVERDATA)pData->pvUser;
317 Assert(pData->cbUser == sizeof(FTPSERVERDATA));
318
319 RTPrintf("Current directory is: '%s'\n", pThis->szCWD);
320
321 return RTStrCopy(pszPWD, cbPWD, pThis->szCWD);
322}
323
324static DECLCALLBACK(int) onPathUp(PRTFTPCALLBACKDATA pData)
325{
326 RT_NOREF(pData);
327
328 return VINF_SUCCESS;
329}
330
331static DECLCALLBACK(int) onDirOpen(PRTFTPCALLBACKDATA pData, const char *pcszPath, void **ppvHandle)
332{
333 PFTPSERVERDATA pThis = (PFTPSERVERDATA)pData->pvUser;
334 Assert(pData->cbUser == sizeof(FTPSERVERDATA));
335
336 PFTPDIRHANDLE pHandle = (PFTPDIRHANDLE)RTMemAllocZ(sizeof(FTPDIRHANDLE));
337 if (!pHandle)
338 return VERR_NO_MEMORY;
339
340 /* Construct absolute path. */
341 char *pszPathAbs = NULL;
342 if (RTStrAPrintf(&pszPathAbs, "%s/%s", pThis->szPathRootAbs, pcszPath) <= 0)
343 return VERR_NO_MEMORY;
344
345 RTPrintf("Opening directory '%s'\n", pszPathAbs);
346
347 int rc = RTVfsChainOpenDir(pszPathAbs, 0 /*fFlags*/, &pHandle->hVfsDir, NULL /* poffError */, NULL /* pErrInfo */);
348 if (RT_SUCCESS(rc))
349 {
350 *ppvHandle = pHandle;
351 }
352 else
353 {
354 RTMemFree(pHandle);
355 }
356
357 RTStrFree(pszPathAbs);
358
359 return rc;
360}
361
362static DECLCALLBACK(int) onDirClose(PRTFTPCALLBACKDATA pData, void *pvHandle)
363{
364 RT_NOREF(pData);
365
366 PFTPDIRHANDLE pHandle = (PFTPDIRHANDLE)pvHandle;
367 AssertPtrReturn(pHandle, VERR_INVALID_POINTER);
368
369 RTVfsDirRelease(pHandle->hVfsDir);
370
371 RTMemFree(pHandle);
372 pHandle = NULL;
373
374 return VINF_SUCCESS;
375}
376
377static DECLCALLBACK(int) onDirRead(PRTFTPCALLBACKDATA pData, void *pvHandle, char **ppszEntry,
378 PRTFSOBJINFO pInfo, char **ppszOwner, char **ppszGroup, char **ppszTarget)
379{
380 RT_NOREF(pData);
381 RT_NOREF(ppszTarget); /* No symlinks yet */
382
383 PFTPDIRHANDLE pHandle = (PFTPDIRHANDLE)pvHandle;
384 AssertPtrReturn(pHandle, VERR_INVALID_POINTER);
385
386 size_t cbDirEntryAlloced = sizeof(RTDIRENTRYEX);
387 PRTDIRENTRYEX pDirEntry = (PRTDIRENTRYEX)RTMemTmpAlloc(cbDirEntryAlloced);
388 if (!pDirEntry)
389 return VERR_NO_MEMORY;
390
391 int rc;
392
393 for (;;)
394 {
395 size_t cbDirEntry = cbDirEntryAlloced;
396 rc = RTVfsDirReadEx(pHandle->hVfsDir, pDirEntry, &cbDirEntry, RTFSOBJATTRADD_UNIX);
397 if (RT_FAILURE(rc))
398 {
399 if (rc == VERR_BUFFER_OVERFLOW)
400 {
401 RTMemTmpFree(pDirEntry);
402 cbDirEntryAlloced = RT_ALIGN_Z(RT_MIN(cbDirEntry, cbDirEntryAlloced) + 64, 64);
403 pDirEntry = (PRTDIRENTRYEX)RTMemTmpAlloc(cbDirEntryAlloced);
404 if (pDirEntry)
405 continue;
406 }
407 else if (rc != VERR_NO_MORE_FILES)
408 break;
409 }
410
411 if (RT_SUCCESS(rc))
412 {
413 if (pDirEntry->Info.Attr.u.Unix.uid != NIL_RTUID)
414 {
415 RTFSOBJINFO OwnerInfo;
416 rc = RTVfsDirQueryPathInfo(pHandle->hVfsDir,
417 pDirEntry->szName, &OwnerInfo, RTFSOBJATTRADD_UNIX_OWNER, RTPATH_F_ON_LINK);
418 if ( RT_SUCCESS(rc)
419 && OwnerInfo.Attr.u.UnixOwner.szName[0])
420 {
421 *ppszOwner = RTStrDup(&OwnerInfo.Attr.u.UnixOwner.szName[0]);
422 if (!*ppszOwner)
423 rc = VERR_NO_MEMORY;
424 }
425 }
426
427 if ( RT_SUCCESS(rc)
428 && pDirEntry->Info.Attr.u.Unix.gid != NIL_RTGID)
429 {
430 RTFSOBJINFO GroupInfo;
431 rc = RTVfsDirQueryPathInfo(pHandle->hVfsDir,
432 pDirEntry->szName, &GroupInfo, RTFSOBJATTRADD_UNIX_GROUP, RTPATH_F_ON_LINK);
433 if ( RT_SUCCESS(rc)
434 && GroupInfo.Attr.u.UnixGroup.szName[0])
435 {
436 *ppszGroup = RTStrDup(&GroupInfo.Attr.u.UnixGroup.szName[0]);
437 if (!*ppszGroup)
438 rc = VERR_NO_MEMORY;
439 }
440 }
441 }
442
443 *ppszEntry = RTStrDup(pDirEntry->szName);
444 AssertPtrReturn(*ppszEntry, VERR_NO_MEMORY);
445
446 *pInfo = pDirEntry->Info;
447
448 break;
449
450 } /* for */
451
452 RTMemTmpFree(pDirEntry);
453 pDirEntry = NULL;
454
455 return rc;
456}
457
458int main(int argc, char **argv)
459{
460 int rc = RTR3InitExe(argc, &argv, 0);
461 if (RT_FAILURE(rc))
462 return RTMsgInitFailure(rc);
463
464 /* Use some sane defaults. */
465 char szAddress[64] = "localhost";
466 uint16_t uPort = 2121;
467
468 RT_ZERO(g_FTPServerData);
469
470 /*
471 * Parse arguments.
472 */
473 static const RTGETOPTDEF s_aOptions[] =
474 {
475 { "--address", 'a', RTGETOPT_REQ_IPV4ADDR }, /** @todo Use a string for DNS hostnames? */
476 /** @todo Implement IPv6 support? */
477 { "--port", 'p', RTGETOPT_REQ_UINT16 },
478 { "--root-dir", 'r', RTGETOPT_REQ_STRING },
479 { "--verbose", 'v', RTGETOPT_REQ_NOTHING }
480 };
481
482 RTEXITCODE rcExit = RTEXITCODE_SUCCESS;
483 unsigned uVerbosityLevel = 1;
484
485 RTGETOPTUNION ValueUnion;
486 RTGETOPTSTATE GetState;
487 RTGetOptInit(&GetState, argc, argv, s_aOptions, RT_ELEMENTS(s_aOptions), 1, RTGETOPTINIT_FLAGS_OPTS_FIRST);
488 while ((rc = RTGetOpt(&GetState, &ValueUnion)))
489 {
490 switch (rc)
491 {
492 case 'a':
493 RTStrPrintf2(szAddress, sizeof(szAddress), "%RU8.%RU8.%RU8.%RU8", /** @todo Improve this. */
494 ValueUnion.IPv4Addr.au8[0], ValueUnion.IPv4Addr.au8[1], ValueUnion.IPv4Addr.au8[2], ValueUnion.IPv4Addr.au8[3]);
495 break;
496
497 case 'p':
498 uPort = ValueUnion.u16;
499 break;
500
501 case 'r':
502 RTStrCopy(g_FTPServerData.szPathRootAbs, sizeof(g_FTPServerData.szPathRootAbs), ValueUnion.psz);
503 break;
504
505 case 'v':
506 uVerbosityLevel++;
507 break;
508
509 case 'h':
510 RTPrintf("Usage: %s [options]\n"
511 "\n"
512 "Options:\n"
513 " -a, --address (default: localhost)\n"
514 " Specifies the address to use for listening.\n"
515 " -p, --port (default: 2121)\n"
516 " Specifies the port to use for listening.\n"
517 " -r, --root-dir (default: current dir)\n"
518 " Specifies the root directory being served.\n"
519 " -v, --verbose\n"
520 " Controls the verbosity level.\n"
521 " -h, -?, --help\n"
522 " Display this help text and exit successfully.\n"
523 " -V, --version\n"
524 " Display the revision and exit successfully.\n"
525 , RTPathFilename(argv[0]));
526 return RTEXITCODE_SUCCESS;
527
528 case 'V':
529 RTPrintf("$Revision: 82841 $\n");
530 return RTEXITCODE_SUCCESS;
531
532 default:
533 return RTGetOptPrintError(rc, &ValueUnion);
534 }
535 }
536
537 if (!strlen(g_FTPServerData.szPathRootAbs))
538 {
539 /* By default use the current directory as serving root directory. */
540 rc = RTPathGetCurrent(g_FTPServerData.szPathRootAbs, sizeof(g_FTPServerData.szPathRootAbs));
541 if (RT_FAILURE(rc))
542 return RTMsgErrorExit(RTEXITCODE_FAILURE, "Retrieving current directory failed: %Rrc", rc);
543 }
544
545 /* Initialize CWD. */
546 RTStrPrintf2(g_FTPServerData.szCWD, sizeof(g_FTPServerData.szCWD), "/");
547
548 /* Install signal handler. */
549 rc = signalHandlerInstall();
550 if (RT_SUCCESS(rc))
551 {
552 /*
553 * Create the FTP server instance.
554 */
555 RTFTPSERVERCALLBACKS Callbacks;
556 RT_ZERO(Callbacks);
557
558 Callbacks.pfnOnUserConnect = onUserConnect;
559 Callbacks.pfnOnUserAuthenticate = onUserAuthenticate;
560 Callbacks.pfnOnUserDisconnect = onUserDisonnect;
561 Callbacks.pfnOnFileOpen = onFileOpen;
562 Callbacks.pfnOnFileRead = onFileRead;
563 Callbacks.pfnOnFileClose = onFileClose;
564 Callbacks.pfnOnFileGetSize = onFileGetSize;
565 Callbacks.pfnOnFileStat = onFileStat;
566 Callbacks.pfnOnPathSetCurrent = onPathSetCurrent;
567 Callbacks.pfnOnPathGetCurrent = onPathGetCurrent;
568 Callbacks.pfnOnPathUp = onPathUp;
569 Callbacks.pfnOnDirOpen = onDirOpen;
570 Callbacks.pfnOnDirClose = onDirClose;
571 Callbacks.pfnOnDirRead = onDirRead;
572
573 RTFTPSERVER hFTPServer;
574 rc = RTFtpServerCreate(&hFTPServer, szAddress, uPort, &Callbacks,
575 &g_FTPServerData, sizeof(g_FTPServerData));
576 if (RT_SUCCESS(rc))
577 {
578 RTPrintf("Starting FTP server at %s:%RU16 ...\n", szAddress, uPort);
579 RTPrintf("Root directory is '%s'\n", g_FTPServerData.szPathRootAbs);
580
581 RTPrintf("Running FTP server ...\n");
582
583 for (;;)
584 {
585 RTThreadSleep(200);
586
587 if (g_fCanceled)
588 break;
589 }
590
591 RTPrintf("Stopping FTP server ...\n");
592
593 int rc2 = RTFtpServerDestroy(hFTPServer);
594 if (RT_SUCCESS(rc))
595 rc = rc2;
596
597 RTPrintf("Stopped FTP server\n");
598 }
599 else
600 rcExit = RTMsgErrorExit(RTEXITCODE_FAILURE, "RTFTPServerCreate failed: %Rrc", rc);
601
602 int rc2 = signalHandlerUninstall();
603 if (RT_SUCCESS(rc))
604 rc = rc2;
605 }
606
607 /* Set rcExit on failure in case we forgot to do so before. */
608 if (RT_FAILURE(rc))
609 rcExit = RTEXITCODE_FAILURE;
610
611 return rcExit;
612}
613
注意: 瀏覽 TracBrowser 來幫助您使用儲存庫瀏覽器

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