chr
2026-04-05 fe750b791d5b517cc4e9bc8e99a9a75139a0cfba
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
using System;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading;
 
namespace OpenTap
{
    internal interface IFileLock : IDisposable
    {
        bool WaitOne();
        bool WaitOne(TimeSpan timeout);
        bool WaitOne(int ms);
        WaitHandle WaitHandle { get; }
        void Release();
    }
 
    internal static class FileLock
    {
        public static IFileLock Create(string file)
        {
            if (OperatingSystem.Current == OperatingSystem.Windows) return new Win32FileLock(file);
            if (OperatingSystem.Current == OperatingSystem.MacOS) return new MacOSFileLock(file);
            return new PosixFileLock(file);
        }
    }
 
    /// <summary>
    /// Note that this implementation is not thread-safe, unlike the other implementations
    /// </summary>
    class MacOSFileLock : IFileLock
    {
        private readonly ManualResetEvent _waitHandle;
        private readonly string name;
 
        public MacOSFileLock(string file)
        {
            _waitHandle = new ManualResetEvent(false);
            name = file;
        }
 
        public void Dispose()
        {
            Release();
        }
 
        public bool WaitOne()
        {
            while (true)
            {
                // Keep retrying waiting with a timeout until it succeeds
                if (WaitOne(1000)) return true;
            }
        }
 
        public bool WaitOne(TimeSpan timeout)
        {
            // If the fileLock is not null, we are already holding this mutex.
            if (fileLock != null) return true;
            var sw = Stopwatch.StartNew();
            do
            {
                // File exists -- the named mutex is locked
                if (File.Exists(name))
                {
                    var remaining = timeout - sw.Elapsed;
                    if (remaining.TotalMilliseconds > 1)
                        Thread.Sleep(1);
                    else Thread.Yield();
                }
                // Otherwise, create the file, thereby claiming the mutex
                else
                {
                    fileLock = File.Create(name, 0, FileOptions.DeleteOnClose);
                    _waitHandle.Set();
                    return true;
                }
            } while (sw.Elapsed < timeout);
 
            return false;
        }
 
        public bool WaitOne(int ms)
        {
            return WaitOne(TimeSpan.FromMilliseconds(ms));
        }
 
        public WaitHandle WaitHandle => _waitHandle;
        public FileStream fileLock { get; set; }
 
        public void Release()
        {
            try
            {
                fileLock.Dispose();
                fileLock = null;
                _waitHandle.Reset();
            }
            catch
            {
                // this is okay
            }
        }
    }
 
    /// <summary> Locks a file using flock on linux. This essentially works as a named mutex.  </summary>
    class PosixFileLock : IFileLock
    {
        int fileDescriptor;
        string fileName;
        private readonly ManualResetEvent _waitHandle;
 
        public PosixFileLock(string file)
        {
            this.fileName = file;
            // Open 'file' in read/write + append mode. If the file does not exist it will be created with the
            // most permissive access settings possible
            fileDescriptor =
                PosixNative.open(file, PosixNative.O_RDONLY | PosixNative.O_APPEND | PosixNative.O_CREAT, PosixNative.ALL_READ_WRITE);
 
            if (fileDescriptor == -1) throw new IOException($"Failed create file lock on {file}");
            _waitHandle = new ManualResetEvent(false);
        }
 
        /// <summary>
        /// Request an exclusive lock on the open file handle
        /// This call wil block until the lock is acquired
        /// </summary>
        private void Take()
        {
            PosixNative.flock(fileDescriptor, PosixNative.LOCK_EX);
        }
 
        public void Release()
        {
            if (fileDescriptor >= 0)
            {
                PosixNative.flock(fileDescriptor, PosixNative.LOCK_UN);
                _waitHandle.Reset();
            }
        }
 
        public void Dispose()
        {
            if (fileDescriptor >= 0 && _waitHandle.WaitOne(0))
            {
                Release();
            }
 
            PosixNative.close(fileDescriptor);
            fileDescriptor = -1;
            try 
            {
                File.Delete(this.fileName);
            }
            catch
            {
                // suppress
            }
        }
 
        public bool WaitOne()
        {
            Take();
            _waitHandle.Set();
            return true;
        }
 
        public bool WaitOne(TimeSpan timeout)
        {
            var sw = Stopwatch.StartNew();
            do
            {
                var @lock = PosixNative.flock(fileDescriptor, PosixNative.LOCK_NB | PosixNative.LOCK_EX);
                if (@lock == 0)
                {
                    _waitHandle.Set();
                    return true;
                }
 
                var remaining = timeout - sw.Elapsed;
                if (remaining.TotalMilliseconds > 1)
                    Thread.Sleep(1);
                else Thread.Yield();
            } while (sw.Elapsed < timeout);
 
            return false;
        }
 
        public bool WaitOne(int ms) => WaitOne(TimeSpan.FromMilliseconds(ms));
        public WaitHandle WaitHandle => _waitHandle;
    }
 
    class Win32FileLock : IFileLock
    {
        private Mutex _mutex;
 
        public Win32FileLock(string name)
        {
            // Having backslashes in the mutex name seems to cause issues for some reason. Replace them with slashes.
            _mutex = new Mutex(false, name.Replace("\\", "/") + "_opentap_named_mutex_");
        }
 
        public void Dispose()
        {
            try
            {
                if (_mutex?.WaitOne(0) == true)
                    _mutex?.ReleaseMutex();
            }
            catch (AbandonedMutexException)
            {
                // this is fine
            }
 
            _mutex?.Dispose();
            _mutex = null;
        }
 
        public bool WaitOne() => _mutex.WaitOne();
        public bool WaitOne(TimeSpan timeout) => _mutex.WaitOne(timeout);
        public bool WaitOne(int ms) => _mutex.WaitOne(ms);
 
        public WaitHandle WaitHandle => _mutex;
        public void Release() => _mutex.ReleaseMutex();
    }
 
    static class PosixNative
    {
        [DllImport("libc")]
        public static extern int open(string pathname, int flags, int mode);
 
        [DllImport("libc")]
        public static extern int close(int fd);
 
        [DllImport("libc")]
        public static extern int flock(int fd, int operation);
 
        public const int O_CREAT = 64; //00000100;
        public const int O_TRUNC = 512; //00001000;
        public const int O_APPEND = 1024; //00002000;
 
        public const int O_RDONLY = 0; //00000000;
        public const int O_RDWR = 2; //00000002;
        /// <summary>
        /// Place a shared lock. More than one process may hold a shared lock for a given file at a given time. 
        /// </summary>
        public const int LOCK_SH = 1;
        /// <summary>
        /// Place an exclusive lock. Only one process may hold an exclusive lock for a given file at a given time. 
        /// </summary>
        public const int LOCK_EX = 2;
        /// <summary>
        /// Return an error instead of blocking when the lock is taken
        /// </summary>
        public const int LOCK_NB = 4;
        /// <summary>
        /// Release the lock
        /// </summary>
        public const int LOCK_UN = 8;
 
        public const int S_IRUSR = 256; //00000400
        public const int S_IWUSR = 128; //00000200
 
        public const int S_IRGRP = 32; //00000040
        public const int S_IWGRP = 16; //00000020
 
        public const int S_IROTH = 4; //00000004
        public const int S_IWOTH = 2; //00000002
 
        public const int ALL_READ_WRITE = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH;
    }
}