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

InotifyWatcher.cs « System.IO « System « class « mcs - github.com/mono/mono.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: e636da2b30ec01d59ca0ec3d72f0767a68f2f8d2 (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
// 
// System.IO.Inotify.cs: interface with inotify
//
// Authors:
//	Gonzalo Paniagua (gonzalo@novell.com)
//	Anders Rune Jensen (anders@iola.dk)
//
// (c) 2006 Novell, Inc. (http://www.novell.com)

//
// 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.ComponentModel;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;

namespace System.IO {

	[Flags]
	enum InotifyMask : uint {
		Access = 1 << 0,
		Modify = 1 << 1,
		Attrib = 1 << 2,
		CloseWrite = 1 << 3,
		CloseNoWrite = 1 << 4,
		Open = 1 << 5,
		MovedFrom = 1 << 6,
		MovedTo = 1 << 7,
		Create = 1 << 8,
		Delete = 1 << 9,
		DeleteSelf = 1 << 10,
		MoveSelf = 1 << 11,
		BaseEvents = 0x00000fff,
		// Can be sent at any time
		Umount = 0x0002000,
		Overflow = 0x0004000,
		Ignored = 0x0008000,

		// Special flags.
		OnlyDir = 0x01000000,
		DontFollow = 0x02000000,
		AddMask = 0x20000000,
		Directory = 0x40000000,
		OneShot = 0x80000000
	}

	struct InotifyEvent { // Our internal representation for the data returned by the kernel
		public static readonly InotifyEvent Default = new InotifyEvent ();
		public int WatchDescriptor;
		public InotifyMask Mask;
		public string Name;

		public override string ToString ()
		{
			return String.Format ("[Descriptor: {0} Mask: {1} Name: {2}]", WatchDescriptor, Mask, Name);
		}
	}

	class ParentInotifyData
	{
		public bool IncludeSubdirs;
		public bool Enabled;
	        public ArrayList children; // InotifyData
	        public InotifyData data;
	}

	class InotifyData {
		public FileSystemWatcher FSW;
		public string Directory;
		public int Watch;
	}

	class InotifyWatcher : IFileWatcher
	{
		static bool failed;
		static InotifyWatcher instance;
		static Hashtable watches; // FSW to ParentInotifyData
		static Hashtable requests; // FSW to InotifyData
		static IntPtr FD;
		static Thread thread;
		static bool stop;
		
		private InotifyWatcher ()
		{
		}
		
		// Locked by caller
		public static bool GetInstance (out IFileWatcher watcher, bool gamin)
		{
			if (failed == true) {
				watcher = null;
				return false;
			}

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

			FD = GetInotifyInstance ();
			if ((long) FD == -1) {
				failed = true;
				watcher = null;
				return false;
			}

			watches = Hashtable.Synchronized (new Hashtable ());
			requests = Hashtable.Synchronized (new Hashtable ());
			instance = new InotifyWatcher ();
			watcher = instance;
			return true;
		}
		
		public void StartDispatching (FileSystemWatcher fsw)
		{
			ParentInotifyData parent;
			lock (this) {
				if ((long) FD == -1)
					FD = GetInotifyInstance ();

				if (thread == null) {
					thread = new Thread (new ThreadStart (Monitor));
					thread.IsBackground = true;
					thread.Start ();
				}

				parent = (ParentInotifyData) watches [fsw];
			}

			if (parent == null) {
				InotifyData data = new InotifyData ();
				data.FSW = fsw;
				data.Directory = fsw.FullPath;

				parent = new ParentInotifyData();
				parent.IncludeSubdirs = fsw.IncludeSubdirectories;
				parent.Enabled = true;
				parent.children = new ArrayList();
				parent.data = data;

				watches [fsw] = parent;

				try {
					StartMonitoringDirectory (data, false);
					lock (this) {
						AppendRequestData (data);
						stop = false;
					}
				} catch {} // ignore the directory if StartMonitoringDirectory fails.
			}
		}
		
		static void AppendRequestData (InotifyData data)
		{
			int wd = data.Watch;

			object obj = requests [wd];
			ArrayList list = null;
			if (obj == null) {
				requests [data.Watch] = data;
			} else if (obj is InotifyData) {
				list = new ArrayList ();
				list.Add (obj);
				list.Add (data);
				requests [data.Watch] = list;
			} else {
				list = (ArrayList) obj;
				list.Add (data);
			}
		}

		static bool RemoveRequestData (InotifyData data)
		{
			int wd = data.Watch;
			object obj = requests [wd];
			if (obj == null)
				return true;

			if (obj is InotifyData) {
				if (obj == data) {
					requests.Remove (wd);
					return true;
				}
				return false;
			}

			ArrayList list = (ArrayList) obj;
			list.Remove (data);
			if (list.Count == 0) {
				requests.Remove (wd);
				return true;
			}
			return false;
		}

		// Attempt to match MS and linux behavior.
		static InotifyMask GetMaskFromFilters (NotifyFilters filters)
		{
			InotifyMask mask = InotifyMask.Create | InotifyMask.Delete | InotifyMask.DeleteSelf | InotifyMask.AddMask;
			if ((filters & NotifyFilters.Attributes) != 0)
				mask |= InotifyMask.Attrib;

			if ((filters & NotifyFilters.Security) != 0)
				mask |= InotifyMask.Attrib;

			if ((filters & NotifyFilters.Size) != 0) {
				mask |= InotifyMask.Attrib;
				mask |= InotifyMask.Modify;
			}

			if ((filters & NotifyFilters.LastAccess) != 0) {
				mask |= InotifyMask.Attrib;
				mask |= InotifyMask.Access;
				mask |= InotifyMask.Modify;
			}

			if ((filters & NotifyFilters.LastWrite) != 0) {
				mask |= InotifyMask.Attrib;
				mask |= InotifyMask.Modify;
			}

			if ((filters & NotifyFilters.FileName) != 0) {
				mask |= InotifyMask.MovedFrom;
				mask |= InotifyMask.MovedTo;
			}

			if ((filters & NotifyFilters.DirectoryName) != 0) {
				mask |= InotifyMask.MovedFrom;
				mask |= InotifyMask.MovedTo;
			}

			return mask;
		}

		static void StartMonitoringDirectory (InotifyData data, bool justcreated)
		{
			InotifyMask mask = GetMaskFromFilters (data.FSW.NotifyFilter);
			int wd = AddDirectoryWatch (FD, data.Directory, mask);
			if (wd == -1) {
				int error = Marshal.GetLastWin32Error ();
				if (error == 4) { // Too many open watches
					string nr_watches = "(unknown)";
					try {
						using (StreamReader reader = new StreamReader ("/proc/sys/fs/inotify/max_user_watches")) {
							nr_watches = reader.ReadLine ();
						}
					} catch {}

					string msg = String.Format ("The per-user inotify watches limit of {0} has been reached. " +
								"If you're experiencing problems with your application, increase that limit " +
								"in /proc/sys/fs/inotify/max_user_watches.", nr_watches);
					
					throw new Win32Exception (error, msg);
				}
				throw new Win32Exception (error);
			}

			FileSystemWatcher fsw = data.FSW;
			data.Watch = wd;

			ParentInotifyData parent = (ParentInotifyData) watches[fsw];

			if (parent.IncludeSubdirs) {
				foreach (string directory in Directory.GetDirectories (data.Directory)) {
					InotifyData fd = new InotifyData ();
					fd.FSW = fsw;
					fd.Directory = directory;

					if (justcreated) {
						lock (fsw) {
							RenamedEventArgs renamed = null;
							if (fsw.Pattern.IsMatch (directory)) {
								fsw.DispatchEvents (FileAction.Added, directory, ref renamed);
								if (fsw.Waiting) {
									fsw.Waiting = false;
									System.Threading.Monitor.PulseAll (fsw);
								}
							}
						}
					}

					try {
						StartMonitoringDirectory (fd, justcreated);
						AppendRequestData (fd);
					        parent.children.Add(fd);
					} catch {} // ignore errors and don't add directory.
				}
			}

			if (justcreated) {
				foreach (string filename in Directory.GetFiles (data.Directory)) {
					lock (fsw) {
						RenamedEventArgs renamed = null;
						if (fsw.Pattern.IsMatch (filename)) {
							fsw.DispatchEvents (FileAction.Added, filename, ref renamed);
							/* If a file has been created, then it has been written to */
							fsw.DispatchEvents (FileAction.Modified, filename, ref renamed);

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

		public void StopDispatching (FileSystemWatcher fsw)
		{
			ParentInotifyData parent;
			lock (this) {
				parent = (ParentInotifyData) watches [fsw];
				if (parent == null)
					return;

				if (RemoveRequestData (parent.data)) {
					StopMonitoringDirectory (parent.data);
				}
				watches.Remove (fsw);
				if (watches.Count == 0) {
					stop = true;
					IntPtr fd = FD;
					FD = (IntPtr) (-1);
					Close (fd);
				}

				if (!parent.IncludeSubdirs)
					return;

				foreach (InotifyData idata in parent.children)
				{
				    if (RemoveRequestData (idata)) {
					StopMonitoringDirectory (idata);
				    }
				}
			}
		}

		static void StopMonitoringDirectory (InotifyData data)
		{
			RemoveWatch (FD, data.Watch);
		}

		void Monitor ()
		{
			byte [] buffer = new byte [4096];
			int nread;
			while (!stop) {
				nread = ReadFromFD (FD, buffer, (IntPtr) buffer.Length);
				if (nread == -1)
					continue;

				lock (this) {
					ProcessEvents (buffer, nread);

				}
			}

			lock (this) {
				thread = null;
				stop = false;
			}
		}
		/*
		struct inotify_event {
			__s32           wd;
			__u32           mask;
			__u32           cookie;
			__u32           len;		// Includes any trailing null in 'name'
			char            name[0];
		};
		*/

		static int ReadEvent (byte [] source, int off, int size, out InotifyEvent evt)
		{
			evt = new InotifyEvent ();
			if (size <= 0 || off > size - 16) {
				return -1;
			}

			int len;
			if (BitConverter.IsLittleEndian) {
				evt.WatchDescriptor = source [off] + (source [off + 1] << 8) +
							(source [off + 2] << 16) + (source [off + 3] << 24);
				evt.Mask = (InotifyMask) (source [off + 4] + (source [off + 5] << 8) +
							(source [off + 6] << 16) + (source [off + 7] << 24));
				// Ignore Cookie -> +4
				len = source [off + 12] + (source [off + 13] << 8) +
					(source [off + 14] << 16) + (source [off + 15] << 24);
			} else {
				evt.WatchDescriptor = source [off + 3] + (source [off + 2] << 8) +
							(source [off + 1] << 16) + (source [off] << 24);
				evt.Mask = (InotifyMask) (source [off + 7] + (source [off + 6] << 8) +
							(source [off + 5] << 16) + (source [off + 4] << 24));
				// Ignore Cookie -> +4
				len = source [off + 15] + (source [off + 14] << 8) +
					(source [off + 13] << 16) + (source [off + 12] << 24);
			}

			if (len > 0) {
				if (off > size - 16 - len)
					return -1;
				string name = Encoding.UTF8.GetString (source, off + 16, len);
				evt.Name = name.Trim ('\0');
			} else {
				evt.Name = null;
			}

			return 16 + len;
		}

		static IEnumerable GetEnumerator (object source)
		{
			if (source == null)
				yield break;

			if (source is InotifyData)
				yield return source;

			if (source is ArrayList) {
				ArrayList list = (ArrayList) source;
				for (int i = 0; i < list.Count; i++)
					yield return list [i];
			}
		}

		/* Interesting events:
			* Modify
			* Attrib
			* MovedFrom
			* MovedTo
			* Create
			* Delete
			* DeleteSelf
		*/
		static InotifyMask Interesting = InotifyMask.Modify | InotifyMask.Attrib | InotifyMask.MovedFrom |
							InotifyMask.MovedTo | InotifyMask.Create | InotifyMask.Delete |
							InotifyMask.DeleteSelf;

		void ProcessEvents (byte [] buffer, int length)
		{
			ArrayList newdirs = null;
			InotifyEvent evt;
			int nread = 0;
			bool new_name_needed = false;
			RenamedEventArgs renamed = null;
			while (length > nread) {
				int bytes_read = ReadEvent (buffer, nread, length, out evt);
				if (bytes_read <= 0)
					break;

				nread += bytes_read;

				InotifyMask mask = evt.Mask;
				bool is_directory = (mask & InotifyMask.Directory) != 0;
				mask = (mask & Interesting); // Clear out all the bits that we don't need
				if (mask == 0)
					continue;

				foreach (InotifyData data in GetEnumerator (requests [evt.WatchDescriptor])) {
				        ParentInotifyData parent = (ParentInotifyData) watches[data.FSW];

					if (data == null || parent.Enabled == false)
						continue;

					string directory = data.Directory;
					string filename = evt.Name;
					if (filename == null)
						filename = directory;

					FileSystemWatcher fsw = data.FSW;
					FileAction action = 0;
					if ((mask & (InotifyMask.Modify | InotifyMask.Attrib)) != 0) {
						action = FileAction.Modified;
					} else if ((mask & InotifyMask.Create) != 0) {
						action = FileAction.Added;
					} else if ((mask & InotifyMask.Delete) != 0) {
						action = FileAction.Removed;
					} else if ((mask & InotifyMask.DeleteSelf) != 0) {
						action = FileAction.Removed;
					} else if ((mask & InotifyMask.MoveSelf) != 0) {
						//action = FileAction.Removed;
						continue; // Ignore this one
					} else if ((mask & InotifyMask.MovedFrom) != 0) {
						InotifyEvent to;
						int i = ReadEvent (buffer, nread, length, out to);
						if (i == -1 || (to.Mask & InotifyMask.MovedTo) == 0) {
							action = FileAction.Removed;
						} else {
							nread += i;
							action = FileAction.RenamedNewName;
							renamed = new RenamedEventArgs (WatcherChangeTypes.Renamed, data.Directory, to.Name, evt.Name);
							if (evt.Name != data.Directory && !fsw.Pattern.IsMatch (evt.Name))
								filename = to.Name;
						}
					} else if ((mask & InotifyMask.MovedTo) != 0) {
						action = (new_name_needed) ? FileAction.RenamedNewName : FileAction.Added;
						new_name_needed = false;
					}

					if (fsw.IncludeSubdirectories) {
						string full = fsw.FullPath;
						string datadir = data.Directory;
						if (datadir != full) {
							int len = full.Length;
							int slash = 1;
							if (len > 1 && full [len - 1] == Path.DirectorySeparatorChar)
								slash = 0;
							string reldir = datadir.Substring (full.Length + slash);
							datadir = Path.Combine (datadir, filename);
							filename = Path.Combine (reldir, filename);
						} else {
							datadir = Path.Combine (full, filename);
						}

						if (action == FileAction.Added && is_directory) {
							if (newdirs == null)
								newdirs = new ArrayList (2);

							InotifyData fd = new InotifyData ();
							fd.FSW = fsw;
							fd.Directory = datadir;
							newdirs.Add (fd);
						}
					}

					if (filename != data.Directory && !fsw.Pattern.IsMatch (filename)) {
						continue;
					}

					lock (fsw) {
						fsw.DispatchEvents (action, filename, ref renamed);
						if (action == FileAction.RenamedNewName)
							renamed = null;
						if (fsw.Waiting) {
							fsw.Waiting = false;
							System.Threading.Monitor.PulseAll (fsw);
						}
					}
				}
			}

			if (newdirs != null) {
			        foreach (InotifyData newdir in newdirs) {
					try {
						StartMonitoringDirectory (newdir, true);
						AppendRequestData (newdir);
					        ((ParentInotifyData) watches[newdir.FSW]).children.Add(newdir);
					} catch {} // ignore the given directory
				}
				newdirs.Clear ();
			}
		}

		static int AddDirectoryWatch (IntPtr fd, string directory, InotifyMask mask)
		{
			mask |= InotifyMask.Directory;
			return AddWatch (fd, directory, mask);
		}

		[DllImport ("libc", EntryPoint="close")]
		internal extern static int Close (IntPtr fd);

		[DllImport ("libc", EntryPoint = "read")]
		extern static int ReadFromFD (IntPtr fd, byte [] buffer, IntPtr length);

		[MethodImplAttribute(MethodImplOptions.InternalCall)]
		extern static IntPtr GetInotifyInstance ();

		[MethodImplAttribute(MethodImplOptions.InternalCall)]
		extern static int AddWatch (IntPtr fd, string name, InotifyMask mask);

		[MethodImplAttribute(MethodImplOptions.InternalCall)]
		extern static IntPtr RemoveWatch (IntPtr fd, int wd);
	}
}