File: UpdateCheckEx.cs

package info (click to toggle)
keepass2 2.60%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 14,892 kB
  • sloc: cs: 119,878; xml: 6,087; ansic: 2,033; cpp: 738; sh: 50; makefile: 42
file content (623 lines) | stat: -rw-r--r-- 17,610 bytes parent folder | download
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
/*
  KeePass Password Safe - The Open-Source Password Manager
  Copyright (C) 2003-2025 Dominik Reichl <dominik.reichl@t-online.de>

  This program is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation; either version 2 of the License, or
  (at your option) any later version.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program; if not, write to the Free Software
  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
*/

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Windows.Forms;

using KeePass.App;
using KeePass.Forms;
using KeePass.Plugins;
using KeePass.Resources;
using KeePass.UI;

using KeePassLib;
using KeePassLib.Interfaces;
using KeePassLib.Serialization;
using KeePassLib.Utility;

namespace KeePass.Util
{
	public enum UpdateComponentStatus
	{
		Unknown = 0,
		UpToDate,
		NewVerAvailable,
		PreRelease,
		DownloadFailed
	}

	public sealed class UpdateComponentInfo
	{
		private readonly string m_strName; // Never null
		public string Name
		{
			get { return m_strName; }
		}

		private readonly ulong m_uVerInstalled;
		public ulong VerInstalled
		{
			get { return m_uVerInstalled; }
		}

		private ulong m_uVerAvailable = 0;
		public ulong VerAvailable
		{
			get { return m_uVerAvailable; }
			set { m_uVerAvailable = value; }
		}

		private UpdateComponentStatus m_status = UpdateComponentStatus.Unknown;
		public UpdateComponentStatus Status
		{
			get { return m_status; }
			set { m_status = value; }
		}

		private readonly string m_strUpdateUrl; // Never null
		public string UpdateUrl
		{
			get { return m_strUpdateUrl; }
		}

		private readonly string m_strCat; // Never null
		public string Category
		{
			get { return m_strCat; }
		}

		public UpdateComponentInfo(string strName, ulong uVerInstalled,
			string strUpdateUrl, string strCategory)
		{
			if(strName == null) throw new ArgumentNullException("strName");
			if(strUpdateUrl == null) throw new ArgumentNullException("strUpdateUrl");
			if(strCategory == null) throw new ArgumentNullException("strCategory");

			m_strName = strName;
			m_uVerInstalled = uVerInstalled;
			m_strUpdateUrl = strUpdateUrl;
			m_strCat = strCategory;
		}
	}

	public static class UpdateCheckEx
	{
		private static readonly Dictionary<string, string> g_dFileSigKeys =
			new Dictionary<string, string>();

		private static readonly string CompMain = PwDefs.ShortProductName;

		private sealed class UpdateCheckParams
		{
			public readonly bool ForceUI;
			public readonly Form Parent; // May be null

			public UpdateCheckParams(bool bForceUI, Form fOptParent)
			{
				this.ForceUI = bForceUI;
				this.Parent = fOptParent;
			}
		}

		public static void Run(bool bForceUI, Form fOptParent)
		{
			DateTime dtNow = DateTime.UtcNow, dtLast;
			string strLast = Program.Config.Application.LastUpdateCheck;
			if(!bForceUI && (strLast.Length > 0) && TimeUtil.TryDeserializeUtc(
				strLast, out dtLast))
			{
				if(CompareDates(dtLast, dtNow) == 0) return; // Checked today already
			}
			Program.Config.Application.LastUpdateCheck = TimeUtil.SerializeUtc(dtNow);

			UpdateCheckParams p = new UpdateCheckParams(bForceUI, fOptParent);
			if(!bForceUI) // Async
			{
				// // Local, but thread will continue to run anyway
				// Thread th = new Thread(new ParameterizedThreadStart(
				//	UpdateCheckEx.RunPriv));
				// th.Start(p);

				try
				{
					ThreadPool.QueueUserWorkItem(new WaitCallback(
						UpdateCheckEx.RunPriv), p);
				}
				catch(Exception) { Debug.Assert(false); }
			}
			else RunPriv(p);
		}

		private static int CompareDates(DateTime a, DateTime b)
		{
			Debug.Assert(a.Kind == b.Kind);
			if(a.Year != b.Year) return ((a.Year < b.Year) ? -1 : 1);
			if(a.Month != b.Month) return ((a.Month < b.Month) ? -1 : 1);
			if(a.Day != b.Day) return ((a.Day < b.Day) ? -1 : 1);
			return 0;
		}

		private static void RunPriv(object o)
		{
			UpdateCheckParams p = (o as UpdateCheckParams);
			if(p == null) { Debug.Assert(false); return; }

			IStatusLogger sl = null;
			try
			{
				if(p.ForceUI)
				{
					Form fStatusDialog;
					sl = StatusUtil.CreateStatusDialog(p.Parent, out fStatusDialog,
						KPRes.UpdateCheck, KPRes.CheckingForUpd + "...", true, true);
				}

				List<UpdateComponentInfo> lInst = GetInstalledComponents();
				List<string> lUrls = GetUrls(lInst);
				Dictionary<string, List<UpdateComponentInfo>> dictAvail =
					DownloadInfoFiles(lUrls, sl);
				if(dictAvail == null) return; // User cancelled

				MergeInfo(lInst, dictAvail);

				bool bUpdAvail = false;
				foreach(UpdateComponentInfo uc in lInst)
				{
					if(uc.Status == UpdateComponentStatus.NewVerAvailable)
					{
						bUpdAvail = true;
						break;
					}
				}

				if(sl != null) { sl.EndLogging(); sl = null; }

				if(bUpdAvail || p.ForceUI)
					ShowUpdateDialogAsync(lInst, p.ForceUI);
			}
			catch(Exception) { Debug.Assert(false); }
			finally
			{
				try { if(sl != null) sl.EndLogging(); }
				catch(Exception) { Debug.Assert(false); }
			}
		}

		private static void ShowUpdateDialogAsync(List<UpdateComponentInfo> lInst,
			bool bModal)
		{
			try
			{
				MainForm mf = Program.MainForm;
				if((mf != null) && mf.InvokeRequired)
					mf.BeginInvoke(new UceShDlgDelegate(ShowUpdateDialogPriv),
						lInst, bModal);
				else ShowUpdateDialogPriv(lInst, bModal);
			}
			catch(Exception) { Debug.Assert(false); }
		}

		private delegate void UceShDlgDelegate(List<UpdateComponentInfo> lInst,
			bool bModal);
		private static void ShowUpdateDialogPriv(List<UpdateComponentInfo> lInst,
			bool bModal)
		{
			try
			{
				// Do not show the update dialog while auto-typing;
				// https://sourceforge.net/p/keepass/bugs/1265/
				if(SendInputEx.IsSending) return;

				UpdateCheckForm dlg = new UpdateCheckForm();
				dlg.InitEx(lInst, bModal);
				UIUtil.ShowDialogAndDestroy(dlg);
			}
			catch(Exception) { Debug.Assert(false); }
		}

		private sealed class UpdateDownloadInfo
		{
			public readonly string Url; // Never null
			public readonly object SyncObj = new object();
			public bool Ready = false;
			public List<UpdateComponentInfo> ComponentInfo = null;

			public UpdateDownloadInfo(string strUrl)
			{
				if(strUrl == null) throw new ArgumentNullException("strUrl");

				this.Url = strUrl;
			}
		}

		private static Dictionary<string, List<UpdateComponentInfo>>
			DownloadInfoFiles(List<string> lUrls, IStatusLogger sl)
		{
			List<UpdateDownloadInfo> lDl = new List<UpdateDownloadInfo>();
			foreach(string strUrl in lUrls)
			{
				if(string.IsNullOrEmpty(strUrl)) { Debug.Assert(false); continue; }

				UpdateDownloadInfo dl = new UpdateDownloadInfo(strUrl);
				lDl.Add(dl);

				ThreadPool.QueueUserWorkItem(new WaitCallback(
					UpdateCheckEx.DownloadInfoFile), dl);
			}

			while(true)
			{
				bool bReady = true;
				foreach(UpdateDownloadInfo dl in lDl)
				{
					lock(dl.SyncObj) { bReady &= dl.Ready; }
				}

				if(bReady) break;
				Thread.Sleep(40);

				if(sl != null)
				{
					if(!sl.ContinueWork()) return null;
				}
			}

			Dictionary<string, List<UpdateComponentInfo>> dict =
				new Dictionary<string, List<UpdateComponentInfo>>();
			foreach(UpdateDownloadInfo dl in lDl)
			{
				dict[dl.Url.ToLower()] = dl.ComponentInfo;
			}
			return dict;
		}

		private static void DownloadInfoFile(object o)
		{
			UpdateDownloadInfo dl = (o as UpdateDownloadInfo);
			if(dl == null) { Debug.Assert(false); return; }

			dl.ComponentInfo = LoadInfoFile(dl.Url);
			lock(dl.SyncObj) { dl.Ready = true; }
		}

		private static List<string> GetUrls(List<UpdateComponentInfo> l)
		{
			List<string> lUrls = new List<string>();
			foreach(UpdateComponentInfo uc in l)
			{
				string strUrl = uc.UpdateUrl;
				if(string.IsNullOrEmpty(strUrl)) continue;

				bool bFound = false;
				for(int i = 0; i < lUrls.Count; ++i)
				{
					if(lUrls[i].Equals(strUrl, StrUtil.CaseIgnoreCmp))
					{
						bFound = true;
						break;
					}
				}

				if(!bFound) lUrls.Add(strUrl);
			}

			return lUrls;
		}

		private static List<UpdateComponentInfo> LoadInfoFile(string strUrl)
		{
			try
			{
				IOConnectionInfo ioc = IOConnectionInfo.FromPath(strUrl.Trim());

				byte[] pb;
				using(Stream s = IOConnection.OpenRead(ioc))
				{
					pb = MemUtil.Read(s);
				}

				if(ioc.Path.EndsWith(".gz", StrUtil.CaseIgnoreCmp))
				{
					// Decompress in try-catch, because some web filters
					// incorrectly pre-decompress the returned data
					// https://sourceforge.net/projects/keepass/forums/forum/329221/topic/4915083
					try
					{
						byte[] pbDec = MemUtil.Decompress(pb);
						List<UpdateComponentInfo> l = LoadInfoFilePriv(pbDec, ioc);
						if(l != null) return l;
					}
					catch(Exception) { }
				}

				return LoadInfoFilePriv(pb, ioc);
			}
			catch(Exception) { }

			return null;
		}

		private static List<UpdateComponentInfo> LoadInfoFilePriv(byte[] pbData,
			IOConnectionInfo iocSource)
		{
			if((pbData == null) || (pbData.Length == 0)) return null;

			int iOffset = 0;
			StrEncodingInfo sei = StrUtil.GetEncoding(StrEncodingType.Utf8);
			byte[] pbBom = sei.StartSignature;
			if((pbData.Length >= pbBom.Length) && MemUtil.ArraysEqual(pbBom,
				MemUtil.Mid(pbData, 0, pbBom.Length)))
				iOffset += pbBom.Length;

			string strData = sei.Encoding.GetString(pbData, iOffset, pbData.Length - iOffset);
			strData = StrUtil.NormalizeNewLines(strData, false);
			string[] vLines = strData.Split('\n');

			string strSigKey;
			g_dFileSigKeys.TryGetValue(iocSource.Path.ToLowerInvariant(), out strSigKey);
			string strLdSig = null;
			StringBuilder sbToVerify = ((strSigKey != null) ? new StringBuilder() : null);

			List<UpdateComponentInfo> l = new List<UpdateComponentInfo>();
			bool bHeader = true, bFooterFound = false;
			char chSep = ':'; // Modified by header
			for(int i = 0; i < vLines.Length; ++i)
			{
				string str = vLines[i].Trim();
				if(str.Length == 0) continue;

				if(bHeader)
				{
					chSep = str[0];
					bHeader = false;

					string[] vHdr = str.Split(chSep);
					if(vHdr.Length >= 2) strLdSig = vHdr[1];
				}
				else if(str[0] == chSep)
				{
					bFooterFound = true;
					break;
				}
				else // Component info
				{
					if(sbToVerify != null)
					{
						sbToVerify.Append(str);
						sbToVerify.Append('\n');
					}

					string[] vInfo = str.Split(chSep);
					if(vInfo.Length >= 2)
					{
						UpdateComponentInfo c = new UpdateComponentInfo(
							vInfo[0].Trim(), 0, iocSource.Path, string.Empty);
						c.VerAvailable = StrUtil.ParseVersion(vInfo[1]);

						AddComponent(l, c);
					}
				}
			}
			if(!bFooterFound) { Debug.Assert(false); return null; }

			if(sbToVerify != null)
			{
				if(!VerifySignature(sbToVerify.ToString(), strLdSig, strSigKey))
					return null;
			}

			return l;
		}

		private static void AddComponent(List<UpdateComponentInfo> l,
			UpdateComponentInfo c)
		{
			if((l == null) || (c == null)) { Debug.Assert(false); return; }

			for(int i = l.Count - 1; i >= 0; --i)
			{
				if(l[i].Name.Equals(c.Name, StrUtil.CaseIgnoreCmp))
					l.RemoveAt(i);
			}

			l.Add(c);
		}

		private static List<UpdateComponentInfo> GetInstalledComponents()
		{
			List<UpdateComponentInfo> l = new List<UpdateComponentInfo>();

			foreach(PluginInfo pi in Program.MainForm.PluginManager)
			{
				Plugin p = pi.Interface;
				string strUrl = ((p != null) ? (p.UpdateUrl ?? string.Empty) :
					string.Empty);

				AddComponent(l, new UpdateComponentInfo(pi.Name.Trim(),
					StrUtil.ParseVersion(pi.FileVersion), strUrl.Trim(),
					KPRes.Plugins));
			}

			// Add KeePass at the end to override any buggy plugin names
			AddComponent(l, new UpdateComponentInfo(CompMain, PwDefs.FileVersion64,
				PwDefs.VersionUrl, PwDefs.ShortProductName));

			l.Sort(UpdateCheckEx.CompareComponents);
			return l;
		}

		private static int CompareComponents(UpdateComponentInfo a,
			UpdateComponentInfo b)
		{
			if(a.Name == b.Name) return 0;
			if(a.Name == CompMain) return -1;
			if(b.Name == CompMain) return 1;

			return a.Name.CompareTo(b.Name);
		}

		private static void MergeInfo(List<UpdateComponentInfo> lInst,
			Dictionary<string, List<UpdateComponentInfo>> dictAvail)
		{
			string strOvrId = PwDefs.VersionUrl.ToLower();
			List<UpdateComponentInfo> lOvr;
			dictAvail.TryGetValue(strOvrId, out lOvr);

			foreach(UpdateComponentInfo uc in lInst)
			{
				string strUrlId = uc.UpdateUrl.ToLower();
				List<UpdateComponentInfo> lAvail;
				dictAvail.TryGetValue(strUrlId, out lAvail);

				if(SetComponentAvail(uc, lOvr)) { }
				else if(SetComponentAvail(uc, lAvail)) { }
				else if((strUrlId.Length > 0) && (lAvail == null))
					uc.Status = UpdateComponentStatus.DownloadFailed;
				else uc.Status = UpdateComponentStatus.Unknown;
			}
		}

		private static bool SetComponentAvail(UpdateComponentInfo uc,
			List<UpdateComponentInfo> lAvail)
		{
			if(uc == null) { Debug.Assert(false); return false; }
			if(lAvail == null) return false; // No assert

			if((uc.Name == CompMain) && WinUtil.IsAppX)
			{
				// The user's AppX may be old; do not claim it's up-to-date
				// uc.VerAvailable = uc.VerInstalled;
				// uc.Status = UpdateComponentStatus.UpToDate;
				uc.Status = UpdateComponentStatus.Unknown;
				return true;
			}

			foreach(UpdateComponentInfo ucAvail in lAvail)
			{
				if(ucAvail.Name.Equals(uc.Name, StrUtil.CaseIgnoreCmp))
				{
					uc.VerAvailable = ucAvail.VerAvailable;

					if(uc.VerInstalled == uc.VerAvailable)
						uc.Status = UpdateComponentStatus.UpToDate;
					else if(uc.VerInstalled < uc.VerAvailable)
						uc.Status = UpdateComponentStatus.NewVerAvailable;
					else uc.Status = UpdateComponentStatus.PreRelease;

					return true;
				}
			}

			return false;
		}

		private static bool VerifySignature(string strContent, string strSig,
			string strKey)
		{
			if(string.IsNullOrEmpty(strSig)) { Debug.Assert(false); return false; }

			try
			{
				byte[] pbMsg = StrUtil.Utf8.GetBytes(strContent);
				byte[] pbSig = Convert.FromBase64String(strSig);

				using(SHA512Managed sha = new SHA512Managed())
				{
					using(RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
					{
						// Watching this code in the debugger may result in a
						// CryptographicException when disposing the object
						rsa.PersistKeyInCsp = false; // Default key
						rsa.FromXmlString(strKey);
						rsa.PersistKeyInCsp = false; // Loaded key

						if(!rsa.VerifyData(pbMsg, sha, pbSig))
						{
							Debug.Assert(false);
							return false;
						}

						rsa.PersistKeyInCsp = false;
					}
				}
			}
			catch(Exception) { Debug.Assert(false); return false; }

			return true;
		}

		public static void SetFileSigKey(string strUrl, string strKey)
		{
			if(string.IsNullOrEmpty(strUrl)) { Debug.Assert(false); return; }
			if(string.IsNullOrEmpty(strKey)) { Debug.Assert(false); return; }

			g_dFileSigKeys[strUrl.ToLowerInvariant()] = strKey;
		}

		public static void EnsureConfigured(Form fParent)
		{
			SetFileSigKey(PwDefs.VersionUrl, AppDefs.Rsa4096PublicKeyXml);

			if(Program.Config.Application.Start.CheckForUpdateConfigured) return;

			// If the user has manually enabled the automatic update check
			// before, there's no need to ask him again
			if(!Program.Config.Application.Start.CheckForUpdate &&
				!Program.IsDevelopmentSnapshot())
			{
				string strHdr = KPRes.UpdateCheckInfo;
				string strSub = KPRes.UpdateCheckInfoRes + MessageService.NewParagraph +
					KPRes.UpdateCheckInfoPriv;

				VistaTaskDialog dlg = new VistaTaskDialog();
				dlg.CommandLinks = true;
				dlg.Content = strHdr;
				dlg.MainInstruction = KPRes.UpdateCheckEnableQ;
				dlg.WindowTitle = PwDefs.ShortProductName;
				dlg.AddButton((int)DialogResult.Yes, KPRes.Enable +
					" (" + KPRes.Recommended + ")", null);
				dlg.AddButton((int)DialogResult.No, KPRes.Disable, null);
				dlg.SetIcon(VtdCustomIcon.Question);
				dlg.FooterText = strSub;
				dlg.SetFooterIcon(VtdIcon.Information);

				int iResult;
				if(dlg.ShowDialog(fParent)) iResult = dlg.Result;
				else
				{
					string strMain = strHdr + MessageService.NewParagraph + strSub;
					iResult = (MessageService.AskYesNo(strMain +
						MessageService.NewParagraph + KPRes.UpdateCheckEnableQ) ?
						(int)DialogResult.Yes : (int)DialogResult.No);
				}

				Program.Config.Application.Start.CheckForUpdate = ((iResult ==
					(int)DialogResult.OK) || (iResult == (int)DialogResult.Yes));
			}

			Program.Config.Application.Start.CheckForUpdateConfigured = true;
		}
	}
}