Welcome to mirror list, hosted at ThFree Co, Russian Federation.

KeventWatcher.cs « System.IO « System « class « mcs - github.com/mono/mono.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: f3cc7dcc183200a81a8ca409b3ab9e49f936f7ec (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
// 
// System.IO.KeventWatcher.cs: interface with osx kevent
//
// Authors:
//	Geoff Norton (gnorton@customerdna.com)
//	Cody Russell (cody@xamarin.com)
//	Alexis Christoforides (lexas@xamarin.com)
//
// (c) 2004 Geoff Norton
// Copyright 2014 Xamarin Inc
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
// 
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//

using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Reflection;

namespace System.IO {

        [Flags]
        enum EventFlags : ushort {
                Add         = 0x0001,
                Delete      = 0x0002,
                Enable      = 0x0004,
                Disable     = 0x0008,
                OneShot     = 0x0010,
                Clear       = 0x0020,
                Receipt     = 0x0040,
                Dispatch    = 0x0080,

                Flag0       = 0x1000,
                Flag1       = 0x2000,
                SystemFlags = unchecked (0xf000),
                        
                // Return values.
                EOF         = 0x8000,
                Error       = 0x4000,
        }
        
        enum EventFilter : short {
                Read = -1,
                Write = -2,
                Aio = -3,
                Vnode = -4,
                Proc = -5,
                Signal = -6,
                Timer = -7,
                MachPort = -8,
                FS = -9,
                User = -10,
                VM = -11
        }

	[Flags]
	enum FilterFlags : uint {
                ReadPoll          = EventFlags.Flag0,
                ReadOutOfBand     = EventFlags.Flag1,
                ReadLowWaterMark  = 0x00000001,

                WriteLowWaterMark = ReadLowWaterMark,

                NoteTrigger       = 0x01000000,
                NoteFFNop         = 0x00000000,
                NoteFFAnd         = 0x40000000,
                NoteFFOr          = 0x80000000,
                NoteFFCopy        = 0xc0000000,
                NoteFFCtrlMask    = 0xc0000000,
                NoteFFlagsMask    = 0x00ffffff,
                                  
                VNodeDelete       = 0x00000001,
                VNodeWrite        = 0x00000002,
                VNodeExtend       = 0x00000004,
                VNodeAttrib       = 0x00000008,
                VNodeLink         = 0x00000010,
                VNodeRename       = 0x00000020,
                VNodeRevoke       = 0x00000040,
                VNodeNone         = 0x00000080,
                                  
                ProcExit          = 0x80000000,
                ProcFork          = 0x40000000,
                ProcExec          = 0x20000000,
                ProcReap          = 0x10000000,
                ProcSignal        = 0x08000000,
                ProcExitStatus    = 0x04000000,
                ProcResourceEnd   = 0x02000000,

                // iOS only
                ProcAppactive     = 0x00800000,
                ProcAppBackground = 0x00400000,
                ProcAppNonUI      = 0x00200000,
                ProcAppInactive   = 0x00100000,
                ProcAppAllStates  = 0x00f00000,

                // Masks
                ProcPDataMask     = 0x000fffff,
                ProcControlMask   = 0xfff00000,

                VMPressure        = 0x80000000,
                VMPressureTerminate = 0x40000000,
                VMPressureSuddenTerminate = 0x20000000,
                VMError           = 0x10000000,
                TimerSeconds      =    0x00000001,
                TimerMicroSeconds =   0x00000002,
                TimerNanoSeconds  =   0x00000004,
                TimerAbsolute     =   0x00000008,
        }

	[StructLayout(LayoutKind.Sequential)]
	struct kevent : IDisposable {
		public UIntPtr ident;
		public EventFilter filter;
		public EventFlags flags;
		public FilterFlags fflags;
		public IntPtr data;
		public IntPtr udata;

		public void Dispose ()
		{
			if (udata != IntPtr.Zero)
				Marshal.FreeHGlobal (udata);
		}


	}

	[StructLayout(LayoutKind.Sequential)]
	struct timespec {
		public IntPtr tv_sec;
		public IntPtr tv_usec;
	}

	class PathData
	{
		public string Path;
		public bool IsDirectory;
		public int Fd;
	}

	class KqueueMonitor : IDisposable
	{
		public int Connection
		{
			get { return conn; }
		}

		public KqueueMonitor (FileSystemWatcher fsw)
		{
			this.fsw = fsw;
			this.conn = -1;
		}

		public void Dispose ()
		{
			CleanUp ();
		}

		public void Start ()
		{
			lock (stateLock) {
				if (started)
					return;

				conn = kqueue ();

				if (conn == -1)
					throw new IOException (String.Format (
						"kqueue() error at init, error code = '{0}'", Marshal.GetLastWin32Error ()));
					
				thread = new Thread (() => DoMonitor ());
				thread.IsBackground = true;
				thread.Start ();

				startedEvent.WaitOne ();

				if (failedInit) {
					thread.Join ();
					CleanUp ();
					throw new IOException ("Monitor thread failed while initializing.");
				}
				else 
					started = true;
			}
		}

		public void Stop ()
		{
			lock (stateLock) {
				if (!started)
					return;
					
				requestStop = true;
				thread.Join ();
				requestStop = false;

				CleanUp ();
				started = false;
			}
		}

		void CleanUp ()
		{
			if (conn != -1)
				close (conn);

			conn = -1;

			foreach (int fd in fdsDict.Keys)
				close (fd); 

			fdsDict.Clear ();
			pathsDict.Clear ();
		}

		void DoMonitor ()
		{
			Exception exc = null;
			failedInit = false;

			try {
				Setup ();
			} catch (Exception e) {
				failedInit = true;
				exc = e;
			} finally {
				startedEvent.Set ();
			}

			if (failedInit) {
				fsw.OnError (new ErrorEventArgs (exc));
				return;
			}

			try {
				Monitor ();
			} catch (Exception e) {
				exc = e;
			} finally {
				if (!requestStop) { // failure
					CleanUp ();
					started = false;
				}
				if (exc != null)
					fsw.OnError (new ErrorEventArgs (exc));
			}
		}

		void Setup ()
		{	
			var initialFds = new List<int> ();

			// GetFilenameFromFd() returns the *realpath* which can be different than fsw.FullPath because symlinks.
			// If so, introduce a fixup step.
			int fd = open (fsw.FullPath, O_EVTONLY, 0);
			var resolvedFullPath = GetFilenameFromFd (fd);
			close (fd);

			if (resolvedFullPath != fsw.FullPath)
				fixupPath = resolvedFullPath;
			else
				fixupPath = null;

			Scan (fsw.FullPath, false, ref initialFds);

			var immediate_timeout = new timespec { tv_sec = (IntPtr)0, tv_usec = (IntPtr)0 };
			var eventBuffer = new kevent[0]; // we don't want to take any events from the queue at this point
			var changes = CreateChangeList (ref initialFds);

			int numEvents = kevent (conn, changes, changes.Length, eventBuffer, eventBuffer.Length, ref immediate_timeout);

			if (numEvents == -1) {
				var errMsg = String.Format ("kevent() error at initial event registration, error code = '{0}'", Marshal.GetLastWin32Error ());
				throw new IOException (errMsg);
			}
		}

		kevent[] CreateChangeList (ref List<int> FdList)
		{
			if (FdList.Count == 0)
				return emptyEventList;

			var changes = new List<kevent> ();
			foreach (int fd in FdList) {
				var change = new kevent {

					ident = (UIntPtr)fd,
					filter = EventFilter.Vnode,
					flags = EventFlags.Add | EventFlags.Enable | EventFlags.Clear,
					fflags = FilterFlags.VNodeDelete | FilterFlags.VNodeExtend |
						FilterFlags.VNodeRename | FilterFlags.VNodeAttrib |
						FilterFlags.VNodeLink | FilterFlags.VNodeRevoke |
						FilterFlags.VNodeWrite,
					data = IntPtr.Zero,
					udata = IntPtr.Zero
				};

				changes.Add (change);
			}
			FdList.Clear ();

			return changes.ToArray ();
		}

		void Monitor ()
		{
			var timeout = new timespec { tv_sec = (IntPtr)0, tv_usec = (IntPtr)500000000 };
			var eventBuffer = new kevent[32];
			var newFds = new List<int> ();
			List<PathData> removeQueue = new List<PathData> ();
			List<string> rescanQueue = new List<string> ();

			while (!requestStop) {
				var changes = CreateChangeList (ref newFds);

				int numEvents = kevent (conn, changes, changes.Length, eventBuffer, eventBuffer.Length, ref timeout);

				if (numEvents == -1) {
					var errMsg = String.Format ("kevent() error, error code = '{0}'", Marshal.GetLastWin32Error ());
					fsw.OnError (new ErrorEventArgs (new IOException (errMsg)));
				}

				if (numEvents == 0)
					continue;

				for (var i = 0; i < numEvents; i++) {
					var kevt = eventBuffer [i];
					var pathData = fdsDict [(int)kevt.ident];

					if ((kevt.flags & EventFlags.Error) == EventFlags.Error) {
						var errMsg = String.Format ("kevent() error watching path '{0}', error code = '{1}'", pathData.Path, kevt.data);
						fsw.OnError (new ErrorEventArgs (new IOException (errMsg)));
						continue;
					}

					if ((kevt.fflags & FilterFlags.VNodeDelete) == FilterFlags.VNodeDelete || (kevt.fflags & FilterFlags.VNodeRevoke) == FilterFlags.VNodeRevoke)
						removeQueue.Add (pathData);

					else if ((kevt.fflags & FilterFlags.VNodeWrite) == FilterFlags.VNodeWrite) {
						if (pathData.IsDirectory)
							rescanQueue.Add (pathData.Path);
						else
							PostEvent (FileAction.Modified, pathData.Path);
					} 

					else if ((kevt.fflags & FilterFlags.VNodeRename) == FilterFlags.VNodeRename) {
						var newFilename = GetFilenameFromFd (pathData.Fd);

						if (newFilename.StartsWith (fsw.FullPath))
							Rename (pathData, newFilename);
						else //moved outside of our watched dir so stop watching
								RemoveTree (pathData);
					} 

					else if ((kevt.fflags & FilterFlags.VNodeAttrib) == FilterFlags.VNodeAttrib || (kevt.fflags & FilterFlags.VNodeExtend) == FilterFlags.VNodeExtend)
						PostEvent (FileAction.Modified, pathData.Path);
				}

				removeQueue.ForEach (Remove);
				removeQueue.Clear ();

				rescanQueue.ForEach (path => {
					Scan (path, true, ref newFds);
				});
				rescanQueue.Clear ();
			}
		}

		PathData Add (string path, bool postEvents, ref List<int> fds)
		{
			PathData pathData;
			pathsDict.TryGetValue (path, out pathData);

			if (pathData != null)
				return pathData;

			var fd = open (path, O_EVTONLY, 0);

			if (fd == -1) {
				fsw.OnError (new ErrorEventArgs (new IOException (String.Format (
					"open() error while attempting to process path '{0}', error code = '{1}'", path, Marshal.GetLastWin32Error ()))));
				return null;
			}

			try {
				fds.Add (fd);

				var attrs = File.GetAttributes (path);

				pathData = new PathData {
					Path = path,
					Fd = fd,
					IsDirectory = (attrs & FileAttributes.Directory) == FileAttributes.Directory
				};
				
				pathsDict.Add (path, pathData);
				fdsDict.Add (fd, pathData);

				if (postEvents)
					PostEvent (FileAction.Added, path);

				return pathData;
			} catch (Exception e) {
				close (fd);
				fsw.OnError (new ErrorEventArgs (e));
				return null;
			}

		}

		void Remove (PathData pathData)
		{
			fdsDict.Remove (pathData.Fd);
			pathsDict.Remove (pathData.Path);
			close (pathData.Fd);
			PostEvent (FileAction.Removed, pathData.Path);
		}

		void RemoveTree (PathData pathData)
		{
			var toRemove = new List<PathData> ();

			toRemove.Add (pathData);

			if (pathData.IsDirectory) {
				var prefix = pathData.Path + Path.DirectorySeparatorChar;
				foreach (var path in pathsDict.Keys)
					if (path.StartsWith (prefix)) {
						toRemove.Add (pathsDict [path]);
					}
			}
			toRemove.ForEach (Remove);
		}

		void Rename (PathData pathData, string newRoot)
		{
			var toRename = new List<PathData> ();
			var oldRoot = pathData.Path;

			toRename.Add (pathData);
															
			if (pathData.IsDirectory) {
				var prefix = oldRoot + Path.DirectorySeparatorChar;
				foreach (var path in pathsDict.Keys)
					if (path.StartsWith (prefix))
						toRename.Add (pathsDict [path]);
			}

			toRename.ForEach ((pd) => { 
				var oldPath = pd.Path;
				var newPath = newRoot + oldPath.Substring (oldRoot.Length);
				pd.Path = newPath;
				pathsDict.Remove (oldPath);
				pathsDict.Add (newPath, pd);
			});

			PostEvent (FileAction.RenamedNewName, oldRoot, newRoot);
		}

		void Scan (string path, bool postEvents, ref List<int> fds)
		{
			if (requestStop)
				return;
				
			var pathData = Add (path, postEvents, ref fds);

			if (pathData == null)
				return;
				
			if (!pathData.IsDirectory)
				return;

			var dirsToProcess = new List<string> ();
			dirsToProcess.Add (path);

			while (dirsToProcess.Count > 0) {
				var tmp = dirsToProcess [0];
				dirsToProcess.RemoveAt (0);

				var info = new DirectoryInfo (tmp);
				FileSystemInfo[] fsInfos = null;
				try {
					fsInfos = info.GetFileSystemInfos ();
						
				} catch (IOException) {
					// this can happen if the directory has been deleted already.
					// that's okay, just keep processing the other dirs.
					fsInfos = new FileSystemInfo[0];
				}

				foreach (var fsi in fsInfos) {
					if ((fsi.Attributes & FileAttributes.Directory) == FileAttributes.Directory && !fsw.IncludeSubdirectories)
						continue;

					if ((fsi.Attributes & FileAttributes.Directory) != FileAttributes.Directory && !fsw.Pattern.IsMatch (fsi.FullName))
						continue;

					var currentPathData = Add (fsi.FullName, postEvents, ref fds);

					if (currentPathData != null && currentPathData.IsDirectory)
						dirsToProcess.Add (fsi.FullName);
				}
			}
		}
			
		void PostEvent (FileAction action, string path, string newPath = null)
		{
			RenamedEventArgs renamed = null;

			if (action == 0)
				return;

			// only post events that match filter pattern. check both old and new paths for renames
			if (!fsw.Pattern.IsMatch (path) && (newPath == null || !fsw.Pattern.IsMatch (newPath))) 
				return;
				
			if (action == FileAction.RenamedNewName)
				renamed = new RenamedEventArgs (WatcherChangeTypes.Renamed, "", newPath, path);

			lock (fsw) {
				fsw.DispatchEvents (action, path, ref renamed);

				if (fsw.Waiting) {
					fsw.Waiting = false;
					System.Threading.Monitor.PulseAll (fsw);
				}
			}
		}

		private string GetFilenameFromFd (int fd)
		{
			var sb = new StringBuilder (__DARWIN_MAXPATHLEN);

			if (fcntl (fd, F_GETPATH, sb) != -1) {
				if (fixupPath != null)
					sb.Replace (fixupPath, fsw.FullPath, 0, fixupPath.Length); // see Setup()
				return sb.ToString ();
			} else {
				fsw.OnError (new ErrorEventArgs (new IOException (String.Format (
					"fcntl() error while attempting to get path for fd '{0}', error code = '{1}'", fd, Marshal.GetLastWin32Error ()))));
				return String.Empty;
			}
		}

		const int O_EVTONLY = 0x8000;
		const int F_GETPATH = 50;
		const int __DARWIN_MAXPATHLEN = 1024;
		static readonly kevent[] emptyEventList = new System.IO.kevent[0];

		FileSystemWatcher fsw;
		int conn;
		Thread thread;
		volatile bool requestStop = false;
		AutoResetEvent startedEvent = new AutoResetEvent (false);
		bool started = false;
		bool failedInit = false;
		object stateLock = new object ();

		readonly Dictionary<string, PathData> pathsDict = new Dictionary<string, PathData> ();
		readonly Dictionary<int, PathData> fdsDict = new Dictionary<int, PathData> ();
		string fixupPath = null;

		[DllImport ("libc", EntryPoint="fcntl", CharSet=CharSet.Auto, SetLastError=true)]
		static extern int fcntl (int file_names_by_descriptor, int cmd, StringBuilder sb);

		[DllImport ("libc")]
		extern static int open (string path, int flags, int mode_t);

		[DllImport ("libc")]
		extern static int close (int fd);

		[DllImport ("libc")]
		extern static int kqueue ();

		[DllImport ("libc")]
		extern static int kevent (int kq, [In]kevent[] ev, int nchanges, [Out]kevent[] evtlist, int nevents, [In] ref timespec time);
	}

	class KeventWatcher : IFileWatcher
	{
		static bool failed;
		static KeventWatcher instance;
		static Hashtable watches;  // <FileSystemWatcher, KqueueMonitor>

		private KeventWatcher ()
		{
		}

		// Locked by caller
		public static bool GetInstance (out IFileWatcher watcher)
		{
			if (failed == true) {
				watcher = null;
				return false;
			}

			if (instance != null) {
				watcher = instance;
				return true;
			}

			watches = Hashtable.Synchronized (new Hashtable ());
			var conn = kqueue();
			if (conn == -1) {
				failed = true;
				watcher = null;
				return false;
			}
			close (conn);

			instance = new KeventWatcher ();
			watcher = instance;
			return true;
		}

		public void StartDispatching (FileSystemWatcher fsw)
		{
			KqueueMonitor monitor;

			if (watches.ContainsKey (fsw)) {
				monitor = (KqueueMonitor)watches [fsw];
			} else {
				monitor = new KqueueMonitor (fsw);
				watches.Add (fsw, monitor);
			}
				
			monitor.Start ();
		}

		public void StopDispatching (FileSystemWatcher fsw)
		{
			KqueueMonitor monitor = (KqueueMonitor)watches [fsw];
			if (monitor == null)
				return;

			monitor.Stop ();
		}
			
		[DllImport ("libc")]
		extern static int close (int fd);

		[DllImport ("libc")]
		extern static int kqueue ();
	}
}