forked from bloones/SyncThingWin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Program.cs
364 lines (347 loc) · 11 KB
/
Program.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
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceProcess;
using System.Windows.Forms;
using System.Configuration.Install;
using System.Collections;
using Microsoft.Win32;
using System.IO;
using System.Security.Principal;
using System.Diagnostics;
using System.Reflection;
using System.Xml;
namespace SyncThingTray
{
static class Program
{
public const string SERVICENAME = "SyncThingService";
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] Args)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
if (Args.Length > 0)
{
if (Args[0].ToLower() == "install")
{
if (!IsUserAdministrator) { RunAsAdministrator(Args); return; }
InstallService();
return;
}
else if (Args[0].ToLower() == "uninstall")
{
if (!IsUserAdministrator) { RunAsAdministrator(Args); return; }
UninstallService();
return;
}
else if (Args[0].ToLower() == "start")
{
if (!IsUserAdministrator) { RunAsAdministrator(Args); return; }
StartService();
return;
}
else if (Args[0].ToLower() == "stop")
{
if (!IsUserAdministrator) { RunAsAdministrator(Args); return; }
StopService();
return;
}
else if (Args[0].ToLower() == "configure")
{
if (!IsUserAdministrator) { RunAsAdministrator(Args); return; }
var f = new frmInstall();
f.SetForm();
Application.Run(f);
return;
}
else if (Args[0].ToLower() == "shutdown")
{
if (IsConfigured)
{
string res = ReadConfiguration();
if (res != null)
Application.Run(new frmMessage(res));
else
{
res = API.CallAPIPostSync("shutdown", 2000, "Tineout occured: No response was received from syncthing");
if (res != null)
Application.Run(new frmMessage(res));
}
return;
}
}
else if (Args[0].ToLower() == "restart")
{
if (IsConfigured)
{
string res = ReadConfiguration();
if (res != null)
Application.Run(new frmMessage(res));
else
{
res = API.CallAPIPostSync("restart", 2000, "Tineout occured: No response was received from syncthing");
if (res != null)
Application.Run(new frmMessage(res));
}
return;
}
}
else if (Args[0].ToLower() == "upgrade")
{
if (IsConfigured)
{
string res = ReadConfiguration();
if (res != null)
Application.Run(new frmMessage(res));
else
{
res = API.CallAPIPostSync("upgrade", 2000, "Tineout occured: No response was received from syncthing");
if (res != null)
Application.Run(new frmMessage(res));
}
return;
}
}
}
if (Environment.UserInteractive)
Application.Run(new frmMain());
else
ServiceBase.Run(new SyngThingService());
}
public static bool IsInstalled { get { using (ServiceController s = new ServiceController(SERVICENAME)) return GetIsInstalled(s); } }
public static bool GetIsInstalled(ServiceController Controller)
{
try { var status = Controller.Status; }
catch { return false; }
return true;
}
public static bool IsRunning { get { using (ServiceController s = new ServiceController(SERVICENAME)) return GetIsRunning(s); } }
public static bool GetIsRunning(ServiceController Controller)
{
if (!GetIsInstalled(Controller)) return false;
return Controller.Status == ServiceControllerStatus.Running;
}
public static void InstallService()
{
InstallService(ServiceStartMode.Automatic, false, ServiceAccount.LocalSystem, null, null);
}
public static void InstallService(ServiceStartMode StartMode, bool DelayedStart, ServiceAccount Account, string UserName, string Password)
{
if (IsInstalled) return;
try
{
string path = "/assemblypath=" + Assembly.GetEntryAssembly().Location;
using (var iGbl = new TransactedInstaller())
using (var iSP = new System.ServiceProcess.ServiceProcessInstaller())
using (var iS = new System.ServiceProcess.ServiceInstaller())
{
iSP.Account = Account;
iSP.Password = Password;
iSP.Username = UserName;
iS.Description = "Start the SyncThing executable in the background and allow monitoring";
iS.DisplayName = "SyncThing synchronization launcher";
iS.ServiceName = "SyncThingService";
iS.StartType = StartMode;
iS.DelayedAutoStart = DelayedStart;
iGbl.Installers.AddRange(new System.Configuration.Install.Installer[] { iSP, iS });
iGbl.Context = new InstallContext(null, new[] { path });
iGbl.Install(new Hashtable());
}
}
catch { throw; }
}
public static void UninstallService()
{
if (!IsInstalled) return;
try
{
string path = "/assemblypath=" + Assembly.GetEntryAssembly().Location;
using (var iGbl = new TransactedInstaller())
using (var iSP = new System.ServiceProcess.ServiceProcessInstaller())
using (var iS = new System.ServiceProcess.ServiceInstaller())
{
iS.ServiceName = "SyncThingService";
iGbl.Installers.AddRange(new System.Configuration.Install.Installer[] { iSP, iS });
iGbl.Context = new InstallContext(null, new[] { path });
iGbl.Uninstall(null);
}
}
catch { throw; }
}
public static void StartService()
{
if (!IsUserAdministrator) { RunAsAdministrator("start"); return; }
using (ServiceController controller =
new ServiceController(SERVICENAME))
{
if (!GetIsInstalled(controller)) return;
try
{
if (controller.Status != ServiceControllerStatus.Running)
{
controller.Start();
controller.WaitForStatus(ServiceControllerStatus.Running,
TimeSpan.FromSeconds(10));
}
}
catch { throw; }
}
}
public static void StopService()
{
if (!IsUserAdministrator) { RunAsAdministrator("stop"); return; }
using (ServiceController controller =
new ServiceController(SERVICENAME))
{
if (!GetIsInstalled(controller)) return;
try
{
if (controller.Status != ServiceControllerStatus.Stopped)
{
controller.Stop();
controller.WaitForStatus(ServiceControllerStatus.Stopped,
TimeSpan.FromSeconds(10));
}
}
catch { throw; }
}
}
public static bool IsUserAdministrator
{
get
{
try
{
WindowsIdentity user = WindowsIdentity.GetCurrent();
WindowsPrincipal principal = new WindowsPrincipal(user);
return principal.IsInRole(WindowsBuiltInRole.Administrator);
}
catch (UnauthorizedAccessException) { return false; }
catch (Exception) { return false; }
}
}
public static void RunAsAdministrator()
{
ProcessStartInfo sinfo = new ProcessStartInfo(Application.ExecutablePath);
sinfo.Verb = "runas";
Process.Start(sinfo);
}
public static void RunAsAdministrator(params string[] Params)
{
ProcessStartInfo sinfo = new ProcessStartInfo(Application.ExecutablePath, "\"" + string.Join("\" \"", Params) + "\"");
sinfo.Verb = "runas";
Process.Start(sinfo);
}
public static string MonitorFile { get; private set; }
public static string SyncExePath { get; private set; }
public static string SyncConfigPath { get; private set; }
public static ProcessPriorityClass SyncPriority { get; private set; }
public static bool AutoRestart { get; private set; }
public static int AutoRestartCount { get; private set; }
public static TimeSpan AutoRestartPeriod { get; private set; }
public static bool IsConfigured
{
get
{
MonitorFile = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData, Environment.SpecialFolderOption.Create);
MonitorFile = Path.Combine(MonitorFile, "Syncthing Service");
if (!Directory.Exists(MonitorFile)) Directory.CreateDirectory(MonitorFile);
MonitorFile = Path.Combine(MonitorFile, "Std.out");
// Check the configuration
RegistryKey klm = Registry.LocalMachine;
if (klm == null) return false;
using (RegistryKey ksoft = klm.OpenSubKey("SOFTWARE"))
{
if (ksoft == null) return false;
using (RegistryKey ksync = ksoft.OpenSubKey("Syncthing Service"))
{
if (ksync == null) return false;
SyncExePath = ksync.GetValue("Executable", "") as string;
SyncConfigPath = ksync.GetValue("Configuration", "") as string;
string priority = ksync.GetValue("Priority", "") as string;
switch (priority)
{
case "Real Time": SyncPriority = ProcessPriorityClass.RealTime; break;
case "High": SyncPriority = ProcessPriorityClass.High; break;
case "Above Normal": SyncPriority = ProcessPriorityClass.AboveNormal; break;
case "Normal": SyncPriority = ProcessPriorityClass.Normal; break;
case "Below Normal": SyncPriority = ProcessPriorityClass.BelowNormal; break;
case "Idle": SyncPriority = ProcessPriorityClass.Idle; break;
default: SyncPriority = ProcessPriorityClass.Normal; break;
}
string[] autos = (ksync.GetValue("Autorestart", "") as string).Split(new char[] { ':' }, 2);
if ((autos.Length < 2) || (autos[0] != "Yes"))
AutoRestart = false;
else if (autos[1] == "unlimited")
{
AutoRestart = true;
AutoRestartCount = 0;
AutoRestartPeriod = TimeSpan.Zero;
}
else
{
string[] opts = autos[1].Split(',');
int t; TimeSpan d;
if (!int.TryParse(opts[0], out t))
t = 0;
if ((opts.Length<2)|| !TimeSpan.TryParse(opts[1], out d))
d = TimeSpan.Zero;
if ((t == 0) || (d == TimeSpan.Zero))
{
AutoRestart = false;
}
else
{
AutoRestart = true;
AutoRestartCount = t;
AutoRestartPeriod = d;
}
}
return !string.IsNullOrEmpty(SyncExePath) && !string.IsNullOrEmpty(SyncConfigPath);
}
}
}
}
public static string GuiUrl { get; private set; }
public static string APIUrl { get; private set; }
public static string APIKey { get; private set; }
public static string ReadConfiguration()
{
string cfgpath = Path.Combine(Program.SyncConfigPath, "config.xml");
if (File.Exists(cfgpath))
{
XmlDocument xml = new XmlDocument();
xml.Load(cfgpath);
XmlElement xr = xml.DocumentElement;
var xgs = xr.GetElementsByTagName("gui");
if (xgs.Count == 1)
{
XmlElement xg = (XmlElement)xgs[0];
string tls = xg.GetAttribute("tls");
var xas = xg.GetElementsByTagName("address");
if (xas.Count == 1)
{
GuiUrl = (tls == "true" ? "https://" : "http://") + xas[0].InnerText;
APIUrl = "http://" + xas[0].InnerText;
}
else
return "The http address of Syncthing could not be found in the configuration";
xas = xg.GetElementsByTagName("apikey");
if (xas.Count == 1)
APIKey = xas[0].InnerText;
else
return "Could not find the API Key in the configuration: Ensure that an API key was generated in the syncthing GUI";
return null;
}
else
return "The Syncthing configuration cannot be retreived as the gui element could not be found";
}
else
return "The configuration file could not be found: " + cfgpath;
}
}
}