Source code of Windows XP (NT5)
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

787 lines
22 KiB

  1. /*++
  2. Copyright (c) 1989-1999 Microsoft Corporation
  3. Module Name:
  4. fspyUser.c
  5. Abstract:
  6. This file contains the implementation for the main function of the
  7. user application piece of FileSpy. This function is responsible for
  8. controlling the command mode available to the user to control the
  9. kernel mode driver.
  10. Environment:
  11. User mode
  12. // @@BEGIN_DDKSPLIT
  13. Author:
  14. George Jenkins (GeorgeJe)
  15. Revision History:
  16. Molly Brown (MollyBro) 21-Apr-1999
  17. Broke out the logging code and added command mode functionality.
  18. Neal Christiansen (nealch) 06-Jul-2001
  19. Updated cash statistics for use with contexts
  20. // @@END_DDKSPLIT
  21. --*/
  22. #include <windows.h>
  23. #include <stdlib.h>
  24. #include <stdio.h>
  25. #include <winioctl.h>
  26. #include <string.h>
  27. #include <crtdbg.h>
  28. #include "filespy.h"
  29. #include "fspyLog.h"
  30. #include "filespyLib.h"
  31. #define SUCCESS 0
  32. #define USAGE_ERROR 1
  33. #define EXIT_INTERPRETER 2
  34. #define EXIT_PROGRAM 4
  35. #define INTERPRETER_EXIT_COMMAND1 "go"
  36. #define INTERPRETER_EXIT_COMMAND2 "g"
  37. #define PROGRAM_EXIT_COMMAND "exit"
  38. #define ToggleFlag(V, F) (V = (((V) & (F)) ? (V & (~F)) : (V | F)))
  39. DWORD
  40. InterpretCommand(
  41. int argc,
  42. char *argv[],
  43. PLOG_CONTEXT Context
  44. );
  45. BOOL
  46. ListDevices(
  47. PLOG_CONTEXT Context
  48. );
  49. BOOL
  50. ListHashStats(
  51. PLOG_CONTEXT Context
  52. );
  53. VOID
  54. DisplayError (
  55. DWORD Code
  56. );
  57. int _cdecl main(int argc, char *argv[])
  58. {
  59. SC_HANDLE hSCManager = NULL;
  60. SC_HANDLE hService = NULL;
  61. SERVICE_STATUS_PROCESS serviceInfo;
  62. DWORD bytesNeeded;
  63. HANDLE hDevice = NULL;
  64. BOOL bResult;
  65. DWORD result;
  66. ULONG threadId;
  67. HANDLE thread = NULL;
  68. LOG_CONTEXT context;
  69. INT inputChar;
  70. //
  71. // Initialize handle in case of error
  72. //
  73. context.ShutDown = NULL;
  74. context.VerbosityFlags = 0;
  75. //
  76. // Start the kernel mode driver through the service manager
  77. //
  78. hSCManager = OpenSCManager (NULL, NULL, SC_MANAGER_ALL_ACCESS) ;
  79. if (NULL == hSCManager) {
  80. result = GetLastError();
  81. printf("ERROR opening Service Manager...\n");
  82. DisplayError( result );
  83. goto Main_Continue;
  84. }
  85. hService = OpenService( hSCManager,
  86. FILESPY_SERVICE_NAME,
  87. FILESPY_SERVICE_ACCESS);
  88. if (NULL == hService) {
  89. result = GetLastError();
  90. printf("ERROR opening FileSpy Service...\n");
  91. DisplayError( result );
  92. goto Main_Continue;
  93. }
  94. if (!QueryServiceStatusEx( hService,
  95. SC_STATUS_PROCESS_INFO,
  96. (UCHAR *)&serviceInfo,
  97. sizeof(serviceInfo),
  98. &bytesNeeded))
  99. {
  100. result = GetLastError();
  101. printf("ERROR querrying status of FileSpy Service...\n");
  102. DisplayError( result );
  103. goto Main_Continue;
  104. }
  105. if(serviceInfo.dwCurrentState != SERVICE_RUNNING) {
  106. //
  107. // Service hasn't been started yet, so try to start service
  108. //
  109. if (!StartService(hService, 0, NULL)) {
  110. result = GetLastError();
  111. printf("ERROR starting FileSpy service...\n");
  112. DisplayError( result );
  113. goto Main_Continue;
  114. }
  115. }
  116. Main_Continue:
  117. printf("Hit [Enter] to begin command mode...\n");
  118. //
  119. // Open the device that is used to talk to FileSpy.
  120. //
  121. printf("FileSpy: Opening device...\n");
  122. hDevice = CreateFile( FILESPY_W32_DEVICE_NAME,
  123. GENERIC_READ | GENERIC_WRITE,
  124. 0,
  125. NULL,
  126. OPEN_EXISTING,
  127. FILE_ATTRIBUTE_NORMAL,
  128. NULL);
  129. if (hDevice == INVALID_HANDLE_VALUE) {
  130. result = GetLastError();
  131. printf("ERROR opening device...\n");
  132. DisplayError( result );
  133. goto Main_Exit;
  134. }
  135. //
  136. // Initialize the fields of the LOG_CONTEXT.
  137. //
  138. context.Device = hDevice;
  139. context.ShutDown = CreateSemaphore(
  140. NULL,
  141. 0,
  142. 1,
  143. L"FileSpy shutdown");
  144. context.CleaningUp = FALSE;
  145. context.LogToScreen = context.NextLogToScreen = TRUE;
  146. context.LogToFile = FALSE;
  147. context.OutputFile = NULL;
  148. //
  149. // Check the valid parameters for startup
  150. //
  151. if (argc > 1) {
  152. if (InterpretCommand(argc - 1, &(argv[1]), &context) == USAGE_ERROR) {
  153. goto Main_Exit;
  154. }
  155. }
  156. //
  157. // Propagate the /s switch to the variable that the logging
  158. // thread checks.
  159. //
  160. context.LogToScreen = context.NextLogToScreen;
  161. //
  162. // Check to see what devices we are attached to from
  163. // previous runs of this program.
  164. //
  165. bResult = ListDevices(&context);
  166. if (!bResult) {
  167. result = GetLastError();
  168. printf("ERROR listing devices...\n");
  169. DisplayError( result );
  170. }
  171. //
  172. // Create the thread to read the log records that are gathered
  173. // by filespy.sys.
  174. //
  175. printf("FileSpy: Creating logging thread...\n");
  176. thread = CreateThread(
  177. NULL,
  178. 0,
  179. RetrieveLogRecords,
  180. (LPVOID)&context,
  181. 0,
  182. &threadId);
  183. if (!thread) {
  184. result = GetLastError();
  185. printf("ERROR creating logging thread...\n");
  186. DisplayError( result );
  187. goto Main_Exit;
  188. }
  189. while (inputChar = getchar()) {
  190. CHAR commandLine[81];
  191. INT parmCount, count, ch;
  192. CHAR **parms;
  193. BOOLEAN newParm;
  194. DWORD returnValue = SUCCESS;
  195. if (inputChar == '\n') {
  196. //
  197. // Start command interpreter. First we must turn off logging
  198. // to screen if we are. Also, remember the state of logging
  199. // to the screen, so that we can reinstate that when command
  200. // interpreter is finished.
  201. //
  202. context.NextLogToScreen = context.LogToScreen;
  203. context.LogToScreen = FALSE;
  204. while (returnValue != EXIT_INTERPRETER) {
  205. //
  206. // Print prompt
  207. //
  208. printf(">");
  209. //
  210. // Read in next line, keeping track of the number of parameters
  211. // as you go
  212. //
  213. parmCount = 1;
  214. for (count = 0;
  215. (count < 80) && ((ch = getchar())!= '\n');
  216. count++) {
  217. commandLine[count] = (CHAR)ch;
  218. if (ch == ' ') {
  219. parmCount ++;
  220. }
  221. }
  222. commandLine[count] = '\0';
  223. parms = (CHAR **)malloc(parmCount * sizeof(CHAR *));
  224. parmCount = 0;
  225. newParm = TRUE;
  226. for (count = 0; commandLine[count] != '\0'; count++) {
  227. if (newParm) {
  228. parms[parmCount] = &(commandLine[count]);
  229. parmCount ++;
  230. }
  231. if (commandLine[count] == ' ' ) {
  232. newParm = TRUE;
  233. } else {
  234. newParm = FALSE;
  235. }
  236. }
  237. //
  238. // We've got our parameter count and parameter list, so
  239. // send it off to be interpreted.
  240. //
  241. returnValue = InterpretCommand(parmCount, parms, &context);
  242. free(parms);
  243. if (returnValue == EXIT_PROGRAM) {
  244. // Time to stop the program
  245. goto Main_Cleanup;
  246. }
  247. }
  248. // Set LogToScreen appropriately based on any commands seen
  249. context.LogToScreen = context.NextLogToScreen;
  250. if (context.LogToScreen) {
  251. printf("Should be logging to screen...\n");
  252. }
  253. }
  254. }
  255. Main_Cleanup:
  256. //
  257. // Clean up the threads, then fall through to Main_Exit
  258. //
  259. printf("FileSpy: Cleaning up...\n");
  260. //
  261. // Set the Cleaning up flag to TRUE to notify other threads
  262. // that we are cleaning up
  263. //
  264. context.CleaningUp = TRUE;
  265. //
  266. // Wait for everyone to shut down
  267. //
  268. WaitForSingleObject(context.ShutDown, INFINITE);
  269. if (context.LogToFile) {
  270. fclose(context.OutputFile);
  271. }
  272. Main_Exit:
  273. //
  274. // Clean up the data that is always around and exit
  275. //
  276. if(context.ShutDown) {
  277. CloseHandle(context.ShutDown);
  278. }
  279. if (thread) {
  280. CloseHandle(thread);
  281. }
  282. if(hSCManager) {
  283. CloseServiceHandle(hSCManager);
  284. }
  285. if(hService) {
  286. CloseServiceHandle(hService);
  287. }
  288. if (hDevice) {
  289. CloseHandle(hDevice);
  290. }
  291. printf("FileSpy: All done\n");
  292. return 0;
  293. }
  294. DWORD
  295. InterpretCommand(
  296. int argc,
  297. char *argv[],
  298. PLOG_CONTEXT Context
  299. )
  300. {
  301. int parmIndex;
  302. CHAR *parm;
  303. BOOL bResult;
  304. DWORD result;
  305. DWORD returnValue = SUCCESS;
  306. CHAR buffer[BUFFER_SIZE];
  307. DWORD bufferLength;
  308. DWORD bytesReturned;
  309. //
  310. // Interpret the command line parameters
  311. //
  312. for (parmIndex = 0; parmIndex < argc; parmIndex++) {
  313. parm = argv[parmIndex];
  314. if (parm[0] == '/') {
  315. //
  316. // Have the beginning of a switch
  317. //
  318. switch (parm[1]) {
  319. case 'a':
  320. case 'A':
  321. //
  322. // Attach to the specified drive letter
  323. //
  324. parmIndex++;
  325. if (parmIndex >= argc) {
  326. //
  327. // Not enough parameters
  328. //
  329. goto InterpretCommand_Usage;
  330. }
  331. parm = argv[parmIndex];
  332. printf("\tAttaching to %s\n", parm);
  333. bufferLength = MultiByteToWideChar(
  334. CP_ACP,
  335. MB_ERR_INVALID_CHARS,
  336. parm,
  337. -1,
  338. (LPWSTR)buffer,
  339. BUFFER_SIZE/sizeof(WCHAR));
  340. bResult = DeviceIoControl(
  341. Context->Device,
  342. FILESPY_StartLoggingDevice,
  343. buffer,
  344. bufferLength * sizeof(WCHAR),
  345. NULL,
  346. 0,
  347. &bytesReturned,
  348. NULL);
  349. if (!bResult) {
  350. result = GetLastError();
  351. printf("ERROR attaching to device...\n");
  352. DisplayError( result );
  353. }
  354. break;
  355. case 'd':
  356. case 'D':
  357. //
  358. // Detach to the specified drive letter
  359. //
  360. parmIndex++;
  361. if (parmIndex >= argc) {
  362. //
  363. // Not enough parameters
  364. //
  365. goto InterpretCommand_Usage;
  366. }
  367. parm = argv[parmIndex];
  368. printf("\tDetaching from %s\n", parm);
  369. bufferLength = MultiByteToWideChar(
  370. CP_ACP,
  371. MB_ERR_INVALID_CHARS,
  372. parm,
  373. -1,
  374. (LPWSTR)buffer,
  375. BUFFER_SIZE/sizeof(WCHAR));
  376. bResult = DeviceIoControl(
  377. Context->Device,
  378. FILESPY_StopLoggingDevice,
  379. buffer,
  380. bufferLength * sizeof(WCHAR),
  381. NULL,
  382. 0,
  383. &bytesReturned,
  384. NULL);
  385. if (!bResult) {
  386. result = GetLastError();
  387. printf("ERROR detaching to device...\n");
  388. DisplayError( result );
  389. }
  390. break;
  391. case 'h':
  392. case 'H':
  393. ListHashStats(Context);
  394. break;
  395. case 'l':
  396. case 'L':
  397. //
  398. // List all devices that are currently being monitored
  399. //
  400. bResult = ListDevices(Context);
  401. if (!bResult) {
  402. result = GetLastError();
  403. printf("ERROR listing devices...\n");
  404. DisplayError( result );
  405. }
  406. break;
  407. case 's':
  408. case 'S':
  409. //
  410. // Output logging results to screen, save new value to
  411. // instate when command interpreter is exited.
  412. //
  413. if (Context->NextLogToScreen) {
  414. printf("\tTurning off logging to screen\n");
  415. } else {
  416. printf("\tTurning on logging to screen\n");
  417. }
  418. Context->NextLogToScreen = !Context->NextLogToScreen;
  419. break;
  420. case 'f':
  421. case 'F':
  422. //
  423. // Output logging results to file
  424. //
  425. if (Context->LogToFile) {
  426. printf("\tStop logging to file \n");
  427. Context->LogToFile = FALSE;
  428. _ASSERT(Context->OutputFile);
  429. fclose(Context->OutputFile);
  430. Context->OutputFile = NULL;
  431. } else {
  432. parmIndex++;
  433. if (parmIndex >= argc) {
  434. // Not enough parameters
  435. goto InterpretCommand_Usage;
  436. }
  437. parm = argv[parmIndex];
  438. Context->OutputFile = fopen(parm, "w");
  439. if (Context->OutputFile == NULL) {
  440. result = GetLastError();
  441. printf("\nERROR opening \"%s\"...\n",parm);
  442. DisplayError( result );
  443. exit(1);
  444. }
  445. Context->LogToFile = TRUE;
  446. printf("\tLog to file %s\n", parm);
  447. }
  448. break;
  449. case 'v':
  450. case 'V':
  451. //
  452. // Toggle the specified verbosity flag.
  453. //
  454. parmIndex++;
  455. if (parmIndex >= argc) {
  456. //
  457. // Not enough parameters
  458. //
  459. goto InterpretCommand_Usage;
  460. }
  461. parm = argv[parmIndex];
  462. switch(parm[0]) {
  463. case 'p':
  464. case 'P':
  465. ToggleFlag( Context->VerbosityFlags, FS_VF_DUMP_PARAMETERS );
  466. break;
  467. default:
  468. //
  469. // Invalid switch, goto usage
  470. //
  471. goto InterpretCommand_Usage;
  472. }
  473. break;
  474. default:
  475. //
  476. // Invalid switch, goto usage
  477. //
  478. goto InterpretCommand_Usage;
  479. }
  480. } else {
  481. //
  482. // Look for "go" or "g" to see if we should exit interpreter
  483. //
  484. if (!_strnicmp(
  485. parm,
  486. INTERPRETER_EXIT_COMMAND1,
  487. sizeof(INTERPRETER_EXIT_COMMAND1))) {
  488. returnValue = EXIT_INTERPRETER;
  489. goto InterpretCommand_Exit;
  490. }
  491. if (!_strnicmp(
  492. parm,
  493. INTERPRETER_EXIT_COMMAND2,
  494. sizeof(INTERPRETER_EXIT_COMMAND2))) {
  495. returnValue = EXIT_INTERPRETER;
  496. goto InterpretCommand_Exit;
  497. }
  498. //
  499. // Look for "exit" to see if we should exit program
  500. //
  501. if (!_strnicmp(
  502. parm,
  503. PROGRAM_EXIT_COMMAND,
  504. sizeof(PROGRAM_EXIT_COMMAND))) {
  505. returnValue = EXIT_PROGRAM;
  506. goto InterpretCommand_Exit;
  507. }
  508. //
  509. // Invalid parameter
  510. //
  511. goto InterpretCommand_Usage;
  512. }
  513. }
  514. InterpretCommand_Exit:
  515. return returnValue;
  516. InterpretCommand_Usage:
  517. printf("Valid switches: [/a <drive>] [/d <drive>] [/h] [/l] [/s] [/f [<file name>] [/v <flag>]]\n"
  518. "\t[/a <drive>] attaches monitor to <drive>\n"
  519. "\t[/d <drive>] detaches monitor from <drive>\n"
  520. "\t[/h] print filename hash statistics\n"
  521. "\t[/l] lists all the drives the monitor is currently attached to\n"
  522. "\t[/s] turns on and off showing logging output on the screen\n"
  523. "\t[/f [<file name>]] turns on and off logging to the specified file\n"
  524. "\t[/v <flag>] toggles a verbosity flag. Valid verbosity flags are:\n"
  525. "\t\tp (dump irp parameters)\n"
  526. "If you are in command mode,\n"
  527. "\t[go|g] will exit command mode\n"
  528. "\t[exit] will terminate this program\n"
  529. );
  530. returnValue = USAGE_ERROR;
  531. goto InterpretCommand_Exit;
  532. }
  533. BOOL
  534. ListHashStats(
  535. PLOG_CONTEXT Context
  536. )
  537. {
  538. ULONG bytesReturned;
  539. BOOL returnValue;
  540. FILESPY_STATISTICS stats;
  541. returnValue = DeviceIoControl( Context->Device,
  542. FILESPY_GetStats,
  543. NULL,
  544. 0,
  545. (CHAR *) &stats,
  546. BUFFER_SIZE,
  547. &bytesReturned,
  548. NULL );
  549. if (returnValue) {
  550. printf(" STATISTICS\n");
  551. printf("---------------------------------\n");
  552. printf("%-40s %8d\n",
  553. "Name lookups",
  554. stats.TotalContextSearches);
  555. printf("%-40s %8d\n",
  556. "Name lookup hits",
  557. stats.TotalContextFound);
  558. if (stats.TotalContextSearches) {
  559. printf(
  560. "%-40s %8.2f%%\n",
  561. "Hit ratio",
  562. ((FLOAT) stats.TotalContextFound / (FLOAT) stats.TotalContextSearches) * 100.);
  563. }
  564. printf("%-40s %8d\n",
  565. "Names created",
  566. stats.TotalContextCreated);
  567. printf("%-40s %8d\n",
  568. "Temporary Names created",
  569. stats.TotalContextTemporary);
  570. printf("%-40s %8d\n",
  571. "Duplicate names created",
  572. stats.TotalContextDuplicateFrees);
  573. printf("%-40s %8d\n",
  574. "Context callback frees",
  575. stats.TotalContextCtxCallbackFrees);
  576. printf("%-40s %8d\n",
  577. "NonDeferred context frees",
  578. stats.TotalContextNonDeferredFrees);
  579. printf("%-40s %8d\n",
  580. "Deferred context frees",
  581. stats.TotalContextDeferredFrees);
  582. printf("%-40s %8d\n",
  583. "Delete all contexts",
  584. stats.TotalContextDeleteAlls);
  585. printf("%-40s %8d\n",
  586. "Contexts not supported",
  587. stats.TotalContextsNotSupported);
  588. printf("%-40s %8d\n",
  589. "Contexts not found attached to stream",
  590. stats.TotalContextsNotFoundInStreamList);
  591. }
  592. return returnValue;
  593. }
  594. BOOL
  595. ListDevices(
  596. PLOG_CONTEXT Context
  597. )
  598. {
  599. CHAR buffer[BUFFER_SIZE];
  600. ULONG bytesReturned;
  601. BOOL returnValue;
  602. returnValue = DeviceIoControl(
  603. Context->Device,
  604. FILESPY_ListDevices,
  605. NULL,
  606. 0,
  607. buffer,
  608. BUFFER_SIZE,
  609. &bytesReturned,
  610. NULL);
  611. if (returnValue) {
  612. PATTACHED_DEVICE device = (PATTACHED_DEVICE) buffer;
  613. printf("DEVICE NAME | LOGGING STATUS\n");
  614. printf("------------------------------------------------------\n");
  615. if (bytesReturned == 0) {
  616. printf("No devices attached\n");
  617. } else {
  618. while ((BYTE *)device < buffer + bytesReturned) {
  619. printf(
  620. "%-38S| %s\n",
  621. device->DeviceNames,
  622. (device->LoggingOn)?"ON":"OFF");
  623. device ++;
  624. }
  625. }
  626. }
  627. return returnValue;
  628. }
  629. VOID
  630. DisplayError (
  631. DWORD Code
  632. )
  633. /*++
  634. Routine Description:
  635. This routine will display an error message based off of the Win32 error
  636. code that is passed in. This allows the user to see an understandable
  637. error message instead of just the code.
  638. Arguments:
  639. Code - The error code to be translated.
  640. Return Value:
  641. None.
  642. --*/
  643. {
  644. WCHAR buffer[80] ;
  645. DWORD count ;
  646. //
  647. // Translate the Win32 error code into a useful message.
  648. //
  649. count = FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM,
  650. NULL,
  651. Code,
  652. 0,
  653. buffer,
  654. sizeof( buffer )/sizeof( WCHAR ),
  655. NULL) ;
  656. //
  657. // Make sure that the message could be translated.
  658. //
  659. if (count == 0) {
  660. printf("\nError could not be translated.\n Code: %d\n", Code) ;
  661. return;
  662. }
  663. else {
  664. //
  665. // Display the translated error.
  666. //
  667. printf("%S\n", buffer) ;
  668. return;
  669. }
  670. }