-
Notifications
You must be signed in to change notification settings - Fork 41
/
Service.cs
381 lines (339 loc) · 14.2 KB
/
Service.cs
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Win32;
using System.IO;
using System.Diagnostics;
using System.ServiceProcess;
namespace OpenVpn
{
class OpenVpnService : System.ServiceProcess.ServiceBase
{
public static string DefaultServiceName = "OpenVpnService";
public const string Package = "openvpn";
private List<OpenVpnChild> Subprocesses;
public OpenVpnService()
{
this.ServiceName = DefaultServiceName;
this.CanStop = true;
this.CanPauseAndContinue = false;
// N.B. if OpenVPN always dies when suspending, then this is unnecessary
// However if there is some kind of stuck state where OpenVPN.exe hangs
// after resuming, then this will help
this.CanHandlePowerEvent = false;
this.AutoLog = true;
this.Subprocesses = new List<OpenVpnChild>();
}
protected override void OnStop()
{
RequestAdditionalTime(3000);
foreach (var child in Subprocesses)
{
child.StopProcess();
}
}
private RegistryKey GetRegistrySubkey(RegistryView rView)
{
try
{
return RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, rView)
.OpenSubKey("Software\\OpenVPN");
}
catch (ArgumentException)
{
return null;
}
catch (NullReferenceException)
{
return null;
}
}
protected override void OnStart(string[] args)
{
try
{
List<RegistryKey> rkOvpns = new List<RegistryKey>();
// Search 64-bit registry, then 32-bit registry for OpenVpn
var key = GetRegistrySubkey(RegistryView.Registry64);
if (key != null) rkOvpns.Add(key);
key = GetRegistrySubkey(RegistryView.Registry32);
if (key != null) rkOvpns.Add(key);
if (rkOvpns.Count() == 0)
throw new Exception("Registry key missing");
var configDirsConsidered = new HashSet<string>();
foreach (var rkOvpn in rkOvpns)
{
try {
bool append = false;
{
var logAppend = (string)rkOvpn.GetValue("log_append");
if (logAppend[0] == '0' || logAppend[0] == '1')
append = logAppend[0] == '1';
else
throw new Exception("Log file append flag must be 1 or 0");
}
var config = new OpenVpnServiceConfiguration()
{
exePath = (string)rkOvpn.GetValue("exe_path"),
configDir = (string)rkOvpn.GetValue("config_dir"),
configExt = "." + (string)rkOvpn.GetValue("config_ext"),
logDir = (string)rkOvpn.GetValue("log_dir"),
logAppend = append,
priorityClass = GetPriorityClass((string)rkOvpn.GetValue("priority")),
eventLog = EventLog,
};
if (configDirsConsidered.Contains(config.configDir)) {
continue;
}
configDirsConsidered.Add(config.configDir);
/// Only attempt to start the service
/// if openvpn.exe is present. This should help if there are old files
/// and registry settings left behind from a previous OpenVPN 32-bit installation
/// on a 64-bit system.
if (!File.Exists(config.exePath))
{
EventLog.WriteEntry("OpenVPN binary does not exist at " + config.exePath);
continue;
}
foreach (var configFilename in Directory.EnumerateFiles(config.configDir,
"*" + config.configExt,
System.IO.SearchOption.AllDirectories))
{
try {
var child = new OpenVpnChild(config, configFilename);
Subprocesses.Add(child);
child.Start();
}
catch (Exception e)
{
EventLog.WriteEntry("Caught exception " + e.Message + " when starting openvpn for "
+ configFilename);
}
}
}
catch (NullReferenceException e) /* e.g. missing registry values */
{
EventLog.WriteEntry("Registry values are incomplete for " + rkOvpn.View.ToString() + e.StackTrace);
}
}
}
catch (Exception e)
{
EventLog.WriteEntry("Exception occured during OpenVPN service start: " + e.Message + e.StackTrace);
throw e;
}
}
private System.Diagnostics.ProcessPriorityClass GetPriorityClass(string priorityString)
{
if (String.Equals(priorityString, "IDLE_PRIORITY_CLASS", StringComparison.InvariantCultureIgnoreCase)) {
return System.Diagnostics.ProcessPriorityClass.Idle;
}
else if (String.Equals(priorityString, "BELOW_NORMAL_PRIORITY_CLASS", StringComparison.InvariantCultureIgnoreCase))
{
return System.Diagnostics.ProcessPriorityClass.BelowNormal;
}
else if (String.Equals(priorityString, "NORMAL_PRIORITY_CLASS", StringComparison.InvariantCultureIgnoreCase))
{
return System.Diagnostics.ProcessPriorityClass.Normal;
}
else if (String.Equals(priorityString, "ABOVE_NORMAL_PRIORITY_CLASS", StringComparison.InvariantCultureIgnoreCase))
{
return System.Diagnostics.ProcessPriorityClass.AboveNormal;
}
else if (String.Equals(priorityString, "HIGH_PRIORITY_CLASS", StringComparison.InvariantCultureIgnoreCase))
{
return System.Diagnostics.ProcessPriorityClass.High;
}
else {
throw new Exception("Unknown priority name: " + priorityString);
}
}
public static int Main(string[] args)
{
if (args.Length == 0)
{
Run(new OpenVpnService());
}
else if (args[0] == "-install")
{
try
{
ProjectInstaller.Install();
}
catch (Exception e)
{
Console.Error.WriteLine(e.Message);
Console.Error.WriteLine(e.StackTrace);
return 1;
}
}
else if (args[0] == "-remove")
{
try
{
ProjectInstaller.Stop();
ProjectInstaller.Uninstall();
}
catch (Exception e)
{
Console.Error.WriteLine(e.Message);
Console.Error.WriteLine(e.StackTrace);
return 1;
}
}
else
{
Console.Error.WriteLine("Unknown command: " + args[0]);
return 1;
}
return 0;
}
}
class OpenVpnServiceConfiguration {
public string exePath {get;set;}
public string configExt {get;set;}
public string configDir {get;set;}
public string logDir {get;set;}
public bool logAppend {get;set;}
public System.Diagnostics.ProcessPriorityClass priorityClass {get;set;}
public EventLog eventLog {get;set;}
}
class OpenVpnChild {
StreamWriter logFile;
Process process;
ProcessStartInfo startInfo;
System.Timers.Timer restartTimer;
OpenVpnServiceConfiguration config;
string configFile;
public OpenVpnChild(OpenVpnServiceConfiguration config, string configFile) {
this.config = config;
/// SET UP LOG FILES
/* Because we will be using the filenames in our closures,
* so make sure we are working on a copy */
this.configFile = String.Copy(configFile);
var justFilename = System.IO.Path.GetFileName(configFile);
var logFilename = config.logDir + "\\" +
justFilename.Substring(0, justFilename.Length - config.configExt.Length) + ".log";
// FIXME: if (!init_security_attributes_allow_all (&sa))
//{
// MSG (M_SYSERR, "InitializeSecurityDescriptor start_" PACKAGE " failed");
// goto finish;
//}
logFile = new StreamWriter(File.Open(logFilename,
config.logAppend ? FileMode.Append : FileMode.Create,
FileAccess.Write,
FileShare.Read), new UTF8Encoding(false));
/// SET UP PROCESS START INFO
string[] procArgs = {
"--config",
"\"" + configFile + "\""
};
this.startInfo = new System.Diagnostics.ProcessStartInfo()
{
RedirectStandardInput = true,
RedirectStandardOutput = true,
RedirectStandardError = true,
WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden,
FileName = config.exePath,
Arguments = String.Join(" ", procArgs),
WorkingDirectory = config.configDir,
UseShellExecute = false,
/* create_new_console is not exposed -- but we probably don't need it?*/
};
/// SET UP FLUSH TIMER
/** .NET has a very annoying habit of taking a very long time to flush
output streams **/
var flushTimer = new System.Timers.Timer(60000);
flushTimer.AutoReset = true;
flushTimer.Elapsed += (object source, System.Timers.ElapsedEventArgs e) =>
{
logFile.Flush();
};
flushTimer.Start();
}
public void StopProcess() {
if (restartTimer != null) {
restartTimer.Stop();
}
try
{
if (!process.HasExited)
{
process.Exited -= Watchdog; // Don't restart the process after kill
process.Kill();
}
}
catch (InvalidOperationException) { }
}
public void Wait() {
process.WaitForExit();
logFile.Close();
}
public void Restart() {
if (restartTimer != null) {
restartTimer.Stop();
}
/* try-catch... because there could be a concurrency issue (write-after-read) here? */
if (!process.HasExited)
{
process.Exited -= Watchdog;
process.Exited += FastRestart; // Restart the process after kill
try
{
process.Kill();
}
catch (InvalidOperationException)
{
Start();
}
}
else
{
Start();
}
}
private void WriteToLog(object sendingProcess, DataReceivedEventArgs e) {
if (e != null)
logFile.WriteLine(e.Data);
}
/// Restart after 10 seconds
/// For use with unexpected terminations
private void Watchdog(object sender, EventArgs e)
{
config.eventLog.WriteEntry("Process for " + configFile + " exited. Restarting in 10 sec.");
restartTimer = new System.Timers.Timer(10000);
restartTimer.AutoReset = false;
restartTimer.Elapsed += (object source, System.Timers.ElapsedEventArgs ev) =>
{
Start();
};
restartTimer.Start();
}
/// Restart after 3 seconds
/// For use with Restart() (e.g. after a resume)
private void FastRestart(object sender, EventArgs e)
{
config.eventLog.WriteEntry("Process for " + configFile + " restarting in 3 sec");
restartTimer = new System.Timers.Timer(3000);
restartTimer.AutoReset = false;
restartTimer.Elapsed += (object source, System.Timers.ElapsedEventArgs ev) =>
{
Start();
};
restartTimer.Start();
}
public void Start() {
process = new System.Diagnostics.Process();
process.StartInfo = startInfo;
process.EnableRaisingEvents = true;
process.OutputDataReceived += WriteToLog;
process.ErrorDataReceived += WriteToLog;
process.Exited += Watchdog;
process.Start();
process.BeginErrorReadLine();
process.BeginOutputReadLine();
process.PriorityClass = config.priorityClass;
}
}
}