Advertisement
Guest User

Untitled

a guest
Feb 21st, 2017
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 18.15 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Diagnostics;
  6. using System.Linq;
  7. using System.ServiceProcess;
  8. using System.Text;
  9. using System.Runtime.InteropServices;
  10. using System.IO;
  11. using System.Threading;
  12.  
  13. namespace UsbService
  14. {
  15. public partial class EntredaUsbService : ServiceBase
  16. {
  17. public static string log_path = AppDomain.CurrentDomain.BaseDirectory.ToString() + "\Usbservice.log";
  18. static string deviceid = "";
  19. static string path = "";
  20. static long oldstamp;
  21. static long oldstamp1;
  22. static string create;
  23. public static long usbval = 0;
  24. public static string drivecaption = "";
  25. public static long setdrive = 0;
  26. private IntPtr deviceNotifyHandle;
  27. private IntPtr deviceEventHandle;
  28. private IntPtr directoryHandle;
  29. public static int prev_control = 0;
  30. public static int prev_eventtype = 0;
  31. private Win32.ServiceControlHandlerEx myCallback;
  32.  
  33. private int ServiceControlHandler(int control, int eventType, IntPtr eventData, IntPtr context)
  34. {
  35. File.AppendAllText(log_path, "Entered into ServiceControlHandler" + Environment.NewLine);
  36. File.AppendAllText(log_path, "Control is : " + control + "event type is :" + eventType + "event data is :" + eventData + "context is : " + context + Environment.NewLine);
  37.  
  38. while (eventType != prev_eventtype)
  39. {
  40. prev_eventtype = eventType;
  41. prev_control = control;
  42. if (control == Win32.SERVICE_CONTROL_STOP || control == Win32.SERVICE_CONTROL_SHUTDOWN)
  43. {
  44. UnregisterHandles();
  45. Win32.UnregisterDeviceNotification(deviceEventHandle);
  46. File.AppendAllText(log_path, "Stopping or shutdown the service" + Environment.NewLine);
  47. base.Stop();
  48. }
  49. else if (control == Win32.SERVICE_CONTROL_DEVICEEVENT)
  50. {
  51. FileSystemWatcher fileSystemWatcher = new FileSystemWatcher();
  52. File.AppendAllText(log_path, "Control is : " + control + "event type is before switch :" + eventType);
  53.  
  54. switch (eventType)
  55. {
  56. case Win32.DBT_DEVICEQUERYREMOVE:
  57. File.AppendAllText(log_path, "Eventtype is DBT_DEVICEQUERYREMOVE" + Environment.NewLine);
  58. fileSystemWatcher.EnableRaisingEvents = false;
  59. // fileSystemWatcher.Dispose();
  60. UnregisterHandles();
  61. File.AppendAllText(log_path, "fswatcher raising events are :" + fileSystemWatcher.EnableRaisingEvents + Environment.NewLine);
  62. break;
  63.  
  64. case Win32.DBT_DEVICEREMOVECOMPLETE:
  65. File.AppendAllText(log_path, "Eventtype is DBT_DEVICEREMOVECOMPLETE" + Environment.NewLine);
  66. break;
  67.  
  68. case Win32.DBT_DEVICEARRIVAL:
  69. string driveLetter = "";
  70. File.AppendAllText(log_path, "Entered into DBT_DEVICEARRIVAL" + Environment.NewLine);
  71. Win32.DEV_BROADCAST_HDR hdr;
  72. hdr = (Win32.DEV_BROADCAST_HDR)
  73. Marshal.PtrToStructure(eventData, typeof(Win32.DEV_BROADCAST_HDR));
  74.  
  75. if (hdr.dbcc_devicetype == Win32.DBT_DEVTYP_DEVICEINTERFACE)
  76. {
  77. File.AppendAllText(log_path, "Hdr.dbcc_devicetype is :" + hdr.dbcc_devicetype + Environment.NewLine);
  78. Win32.DEV_BROADCAST_DEVICEINTERFACE deviceInterface;
  79. deviceInterface = (Win32.DEV_BROADCAST_DEVICEINTERFACE)
  80. Marshal.PtrToStructure(eventData, typeof(Win32.DEV_BROADCAST_DEVICEINTERFACE));
  81. var usbdrives = DriveInfo.GetDrives();
  82. foreach (var usbdrive in usbdrives)
  83. {
  84. if (usbdrive.DriveType == DriveType.Removable)
  85. {
  86. // string drivepah = usbdrive.Name;
  87. driveLetter = usbdrive.Name;
  88. File.AppendAllText(log_path, "Drive letter is : " + driveLetter + Environment.NewLine);
  89. }
  90. }
  91. /*
  92. if (!Win32.GetVolumePathNamesForVolumeNameW(stringBuilder.ToString(), driveLetter, stringReturnLength, ref stringReturnLength))
  93. {
  94. File.AppendAllText(log_path, "getvolume is null" + Environment.NewLine);
  95. }
  96. */
  97. RegisterForHandle(driveLetter[0]);
  98. // usbdrives = DriveInfo.GetDrives();
  99. // foreach (var usbdrive in usbdrives)
  100. {
  101. // if (usbdrive.DriveType == DriveType.Removable)
  102. {
  103.  
  104. // File.AppendAllText(log_path, "USBDrive:" + usbdrive.Name);
  105. // string drivepath = usbdrive.Name;
  106. fileSystemWatcher.Path = driveLetter;
  107. File.AppendAllText(log_path, "Drive path is :" + driveLetter + Environment.NewLine);
  108. fileSystemWatcher.NotifyFilter = NotifyFilters.Size | NotifyFilters.FileName | NotifyFilters.DirectoryName;
  109. fileSystemWatcher.IncludeSubdirectories = true;
  110. fileSystemWatcher.Filter = "*.*";
  111. fileSystemWatcher.InternalBufferSize = 1321440;
  112. fileSystemWatcher.Created += new System.IO.FileSystemEventHandler(fileSystemWatcher_Created);
  113. fileSystemWatcher.Deleted += new System.IO.FileSystemEventHandler(fileSystemWatcher_Deleted);
  114. fileSystemWatcher.Changed += new System.IO.FileSystemEventHandler(fileSystemWatcher_Changed);
  115. fileSystemWatcher.Renamed += new System.IO.RenamedEventHandler(fileSystemWatcher_Renamed);
  116. fileSystemWatcher.EnableRaisingEvents = true;
  117. File.AppendAllText(log_path, "fswatcher raising events are: " + fileSystemWatcher.EnableRaisingEvents + Environment.NewLine);
  118. }
  119. }
  120. }
  121. break;
  122. }
  123. }
  124.  
  125. }
  126. return 0;
  127. }
  128. private void UnregisterHandles()
  129. {
  130. File.AppendAllText(log_path, "Entered into UnregisterHandles" + Environment.NewLine);
  131. File.AppendAllText(log_path, "directory handle : " + directoryHandle + " devicenotifyhandle : " + deviceNotifyHandle + Environment.NewLine);
  132. if (directoryHandle != IntPtr.Zero)
  133. {
  134. bool k = Win32.CloseHandle(directoryHandle);
  135. File.AppendAllText(log_path, "Close handle return : " + k + Environment.NewLine);
  136. directoryHandle = IntPtr.Zero;
  137. }
  138. if (deviceNotifyHandle != IntPtr.Zero)
  139. {
  140. uint k = Win32.UnregisterDeviceNotification(deviceNotifyHandle);
  141. File.AppendAllText(log_path, "UnregisterDeviceNotification return : " + k + Environment.NewLine);
  142. deviceNotifyHandle = IntPtr.Zero;
  143. }
  144. }
  145.  
  146. private void RegisterForHandle(char c)
  147. {
  148. File.AppendAllText(log_path, "Register to handle and char c is :" + c + Environment.NewLine);
  149. Win32.DEV_BROADCAST_HANDLE deviceHandle = new Win32.DEV_BROADCAST_HANDLE();
  150. File.AppendAllText(log_path, "Device handle is : " + deviceHandle + Environment.NewLine);
  151. int size = Marshal.SizeOf(deviceHandle);
  152. deviceHandle.dbch_size = size;
  153. deviceHandle.dbch_devicetype = Win32.DBT_DEVTYP_HANDLE;
  154. directoryHandle = CreateFileHandle(c + ":\");
  155. File.AppendAllText(log_path, "Directory handle : " + directoryHandle + Environment.NewLine);
  156. deviceHandle.dbch_handle = directoryHandle;
  157. IntPtr buffer = Marshal.AllocHGlobal(size);
  158. Marshal.StructureToPtr(deviceHandle, buffer, true);
  159. deviceNotifyHandle = Win32.RegisterDeviceNotification(this.ServiceHandle, buffer, Win32.DEVICE_NOTIFY_SERVICE_HANDLE);
  160. if (deviceNotifyHandle == IntPtr.Zero)
  161. {
  162. File.AppendAllText(log_path, "DeviceNotifyhandle is null" + Environment.NewLine);
  163. }
  164. else
  165. {
  166. File.AppendAllText(log_path, "DeviceNotifyHandle is : " + deviceNotifyHandle + Environment.NewLine);
  167. }
  168. }
  169.  
  170. private void RegisterDeviceNotification(string logpath)
  171. {
  172. File.AppendAllText(logpath, "Entered into RegisterDeviceNotification" + Environment.NewLine);
  173. // while (true)
  174. {
  175. myCallback = new Win32.ServiceControlHandlerEx(ServiceControlHandler);
  176. IntPtr m = Win32.RegisterServiceCtrlHandlerEx(this.ServiceName, myCallback, IntPtr.Zero);
  177. File.AppendAllText(logpath, "Register m value : " + m + Environment.NewLine);
  178. }
  179.  
  180. if (this.ServiceHandle == IntPtr.Zero)
  181. {
  182. File.AppendAllText(logpath, "Service Handle is null" + Environment.NewLine);
  183. }
  184. else
  185. {
  186. File.AppendAllText(logpath, "Service handle is :" + this.ServiceHandle + Environment.NewLine);
  187. }
  188.  
  189. Win32.DEV_BROADCAST_DEVICEINTERFACE deviceInterface = new Win32.DEV_BROADCAST_DEVICEINTERFACE();
  190. File.AppendAllText(logpath, "Device Interface is :" + deviceInterface + Environment.NewLine);
  191. int size = Marshal.SizeOf(deviceInterface);
  192. deviceInterface.dbcc_size = size;
  193. deviceInterface.dbcc_devicetype = Win32.DBT_DEVTYP_DEVICEINTERFACE;
  194. IntPtr buffer = default(IntPtr);
  195. buffer = Marshal.AllocHGlobal(size);
  196.  
  197. Marshal.StructureToPtr(deviceInterface, buffer, true);
  198. deviceEventHandle = Win32.RegisterDeviceNotification(this.ServiceHandle, buffer, Win32.DEVICE_NOTIFY_SERVICE_HANDLE | Win32.DEVICE_NOTIFY_ALL_INTERFACE_CLASSES);
  199. if (deviceEventHandle == IntPtr.Zero)
  200. {
  201. File.AppendAllText(logpath, "DeviceEventHandle is null" + Environment.NewLine);
  202. }
  203. else
  204. {
  205. File.AppendAllText(logpath, "DeviceEventHandle is : " + deviceEventHandle + Environment.NewLine);
  206. }
  207. }
  208.  
  209.  
  210. public EntredaUsbService()
  211. {
  212. InitializeComponent();
  213. }
  214. void fileSystemWatcher_Created(object sender, System.IO.FileSystemEventArgs e)
  215. {
  216. File.AppendAllText(log_path, "Entered into fswatcher_created" + Environment.NewLine);
  217. }
  218.  
  219. void fileSystemWatcher_Renamed(object sender, System.IO.RenamedEventArgs e)
  220. {
  221. File.AppendAllText(log_path, "Entered into fswatcher_renamed" + Environment.NewLine);
  222. }
  223.  
  224. void fileSystemWatcher_Changed(object sender, System.IO.FileSystemEventArgs e)
  225. {
  226. File.AppendAllText(log_path, "Entered into fswatcher_changed" + Environment.NewLine);
  227. }
  228.  
  229. void fileSystemWatcher_Deleted(object sender, System.IO.FileSystemEventArgs e)
  230. {
  231. File.AppendAllText(log_path, "Entered into fswatcher_deleted" + Environment.NewLine);
  232. }
  233.  
  234. public static IntPtr CreateFileHandle(string driveLetter)
  235. {
  236. // open the existing file for reading
  237. IntPtr handle = Win32.CreateFile(
  238. driveLetter,
  239. Win32.GENERIC_READ,
  240. Win32.FILE_SHARE_READ | Win32.FILE_SHARE_WRITE,
  241. 0,
  242. Win32.OPEN_EXISTING,
  243. Win32.FILE_FLAG_BACKUP_SEMANTICS | Win32.FILE_ATTRIBUTE_NORMAL,
  244. 0);
  245.  
  246. if (handle == Win32.INVALID_HANDLE_VALUE)
  247. {
  248. File.AppendAllText(log_path, "Return handle is null" + Environment.NewLine);
  249. return IntPtr.Zero;
  250. }
  251. else
  252. {
  253. File.AppendAllText(log_path, "Return handle is :" + handle + Environment.NewLine);
  254. return handle;
  255. }
  256. }
  257.  
  258. protected override void OnStart(string[] args)
  259. {
  260. base.OnStart(args);
  261.  
  262. //while (true)
  263. {
  264. File.WriteAllText(log_path, "Just entered to onstart for usbservice" + Environment.NewLine);
  265. RegisterDeviceNotification(log_path);
  266. File.AppendAllText(log_path, "Register Device Notification is ended" + Environment.NewLine);
  267. Win32.ServiceControlHandlerEx mycall = new Win32.ServiceControlHandlerEx(ServiceControlHandler);
  268. Win32.RegisterServiceCtrlHandlerEx(this.ServiceName, mycall, IntPtr.Zero);
  269. File.AppendAllText(log_path, "End" + Environment.NewLine);
  270. }
  271. }
  272. public class Win32
  273. {
  274. public const int DEVICE_NOTIFY_SERVICE_HANDLE = 1;
  275. public const int DEVICE_NOTIFY_ALL_INTERFACE_CLASSES = 4;
  276.  
  277. public const int SERVICE_CONTROL_STOP = 1;
  278. public const int SERVICE_CONTROL_DEVICEEVENT = 11;
  279. public const int SERVICE_CONTROL_SHUTDOWN = 5;
  280.  
  281. public const uint GENERIC_READ = 0x80000000;
  282. public const uint OPEN_EXISTING = 3;
  283. public const uint FILE_SHARE_READ = 1;
  284. public const uint FILE_SHARE_WRITE = 2;
  285. public const uint FILE_SHARE_DELETE = 4;
  286. public const uint FILE_ATTRIBUTE_NORMAL = 128;
  287. public const uint FILE_FLAG_BACKUP_SEMANTICS = 0x02000000;
  288. public static readonly IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1);
  289.  
  290. public const int DBT_DEVTYP_DEVICEINTERFACE = 5;
  291. public const int DBT_DEVTYP_HANDLE = 6;
  292.  
  293. public const int DBT_DEVICEARRIVAL = 0x8000;
  294. public const int DBT_DEVICEQUERYREMOVE = 0x8001;
  295. public const int DBT_DEVICEREMOVECOMPLETE = 0x8004;
  296.  
  297. public const int WM_DEVICECHANGE = 0x219;
  298.  
  299. public delegate int ServiceControlHandlerEx(int control, int eventType, IntPtr eventData, IntPtr context);
  300.  
  301. [DllImport("advapi32.dll", SetLastError = true)]
  302. public static extern IntPtr RegisterServiceCtrlHandlerEx(string lpServiceName, ServiceControlHandlerEx cbex, IntPtr context);
  303.  
  304. [DllImport("kernel32.dll", SetLastError = true)]
  305. [return: MarshalAs(UnmanagedType.Bool)]
  306. public static extern bool GetVolumePathNamesForVolumeNameW(
  307. [MarshalAs(UnmanagedType.LPWStr)]
  308. string lpszVolumeName,
  309. [MarshalAs(UnmanagedType.LPWStr)]
  310. string lpszVolumePathNames,
  311. uint cchBuferLength,
  312. ref UInt32 lpcchReturnLength);
  313.  
  314. [DllImport("kernel32.dll")]
  315. public static extern bool GetVolumeNameForVolumeMountPoint(string
  316. lpszVolumeMountPoint, [Out] StringBuilder lpszVolumeName,
  317. uint cchBufferLength);
  318.  
  319. [DllImport("user32.dll", SetLastError = true)]
  320. public static extern IntPtr RegisterDeviceNotification(IntPtr IntPtr, IntPtr NotificationFilter, Int32 Flags);
  321.  
  322. [DllImport("user32.dll", CharSet = CharSet.Auto)]
  323. public static extern uint UnregisterDeviceNotification(IntPtr hHandle);
  324.  
  325. [DllImport("kernel32.dll", SetLastError = true)]
  326. public static extern IntPtr CreateFile(
  327. string FileName, // file name
  328. uint DesiredAccess, // access mode
  329. uint ShareMode, // share mode
  330. uint SecurityAttributes, // Security Attributes
  331. uint CreationDisposition, // how to create
  332. uint FlagsAndAttributes, // file attributes
  333. int hTemplateFile // handle to template file
  334. );
  335.  
  336. [DllImport("kernel32.dll", SetLastError = true)]
  337. public static extern bool CloseHandle(IntPtr hObject);
  338.  
  339. [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
  340. public struct DEV_BROADCAST_DEVICEINTERFACE
  341. {
  342. public int dbcc_size;
  343. public int dbcc_devicetype;
  344. public int dbcc_reserved;
  345. [MarshalAs(UnmanagedType.ByValArray, ArraySubType = UnmanagedType.U1, SizeConst = 16)]
  346. public byte[] dbcc_classguid;
  347. [MarshalAs(UnmanagedType.ByValArray, SizeConst = 128)]
  348. public char[] dbcc_name;
  349. }
  350.  
  351. [StructLayout(LayoutKind.Sequential)]
  352. public struct DEV_BROADCAST_HDR
  353. {
  354. public int dbcc_size;
  355. public int dbcc_devicetype;
  356. public int dbcc_reserved;
  357. }
  358.  
  359. [StructLayout(LayoutKind.Sequential)]
  360. public struct DEV_BROADCAST_HANDLE
  361. {
  362. public int dbch_size;
  363. public int dbch_devicetype;
  364. public int dbch_reserved;
  365. public IntPtr dbch_handle;
  366. public IntPtr dbch_hdevnotify;
  367. public Guid dbch_eventguid;
  368. public long dbch_nameoffset;
  369. public byte dbch_data;
  370. public byte dbch_data1;
  371. }
  372. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement