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
|
/*
KeePass Password Safe - The Open-Source Password Manager
Copyright (C) 2003-2024 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.Text;
using System.Threading;
using KeePassLib.Cryptography;
using KeePassLib.Resources;
using KeePassLib.Utility;
namespace KeePassLib.Serialization
{
public sealed class FileLockException : Exception
{
private readonly string m_strMsg;
public override string Message
{
get { return m_strMsg; }
}
public FileLockException(string strBaseFile, string strUser)
{
StringBuilder sb = new StringBuilder();
if(!string.IsNullOrEmpty(strBaseFile))
{
sb.Append(strBaseFile);
sb.Append(MessageService.NewParagraph);
}
sb.Append(KLRes.FileLockedWrite);
sb.Append(MessageService.NewLine);
if(!string.IsNullOrEmpty(strUser)) sb.Append(strUser);
else sb.Append("?");
sb.Append(MessageService.NewParagraph);
sb.Append(KLRes.TryAgainSecs);
m_strMsg = sb.ToString();
}
}
public sealed class FileLock : IDisposable
{
private const string LockFileExt = ".lock";
private const string LockFileHeader = "KeePass Lock File";
private IOConnectionInfo m_iocLockFile;
private sealed class LockFileInfo
{
public readonly string ID;
public readonly DateTime Time;
public readonly string UserName;
public readonly string Machine;
public readonly string Domain;
private LockFileInfo(string strID, string strTime, string strUserName,
string strMachine, string strDomain)
{
this.ID = (strID ?? string.Empty).Trim();
DateTime dt;
if(TimeUtil.TryDeserializeUtc(strTime.Trim(), out dt))
this.Time = dt;
else
{
Debug.Assert(false);
this.Time = DateTime.UtcNow;
}
this.UserName = (strUserName ?? string.Empty).Trim();
this.Machine = (strMachine ?? string.Empty).Trim();
this.Domain = (strDomain ?? string.Empty).Trim();
if(this.Domain.Equals(this.Machine, StrUtil.CaseIgnoreCmp))
this.Domain = string.Empty;
}
public string GetOwner()
{
StringBuilder sb = new StringBuilder();
sb.Append((this.UserName.Length > 0) ? this.UserName : "?");
bool bMachine = (this.Machine.Length > 0);
bool bDomain = (this.Domain.Length > 0);
if(bMachine || bDomain)
{
sb.Append(" (");
sb.Append(this.Machine);
if(bMachine && bDomain) sb.Append(" @ ");
sb.Append(this.Domain);
sb.Append(")");
}
return sb.ToString();
}
public static LockFileInfo Load(IOConnectionInfo iocLockFile)
{
Stream s = null;
try
{
s = IOConnection.OpenRead(iocLockFile);
if(s == null) return null;
string str;
using(StreamReader sr = new StreamReader(s, StrUtil.Utf8))
{
str = sr.ReadToEnd();
}
if(str == null) { Debug.Assert(false); return null; }
str = StrUtil.NormalizeNewLines(str, false);
string[] v = str.Split('\n');
if((v == null) || (v.Length < 6)) { Debug.Assert(false); return null; }
if(!v[0].StartsWith(LockFileHeader)) { Debug.Assert(false); return null; }
return new LockFileInfo(v[1], v[2], v[3], v[4], v[5]);
}
catch(FileNotFoundException) { }
catch(Exception) { Debug.Assert(false); }
finally { if(s != null) s.Close(); }
return null;
}
// Throws on error
public static LockFileInfo Create(IOConnectionInfo iocLockFile)
{
LockFileInfo lfi;
Stream s = null;
try
{
byte[] pbID = CryptoRandom.Instance.GetRandomBytes(16);
string strTime = TimeUtil.SerializeUtc(DateTime.UtcNow);
lfi = new LockFileInfo(Convert.ToBase64String(pbID), strTime,
#if KeePassUAP
EnvironmentExt.UserName, EnvironmentExt.MachineName,
EnvironmentExt.UserDomainName);
#elif KeePassLibSD
string.Empty, string.Empty, string.Empty);
#else
Environment.UserName, Environment.MachineName,
Environment.UserDomainName);
#endif
StringBuilder sb = new StringBuilder();
#if !KeePassLibSD
sb.AppendLine(LockFileHeader);
sb.AppendLine(lfi.ID);
sb.AppendLine(strTime);
sb.AppendLine(lfi.UserName);
sb.AppendLine(lfi.Machine);
sb.AppendLine(lfi.Domain);
#else
sb.Append(LockFileHeader + MessageService.NewLine);
sb.Append(lfi.ID + MessageService.NewLine);
sb.Append(strTime + MessageService.NewLine);
sb.Append(lfi.UserName + MessageService.NewLine);
sb.Append(lfi.Machine + MessageService.NewLine);
sb.Append(lfi.Domain + MessageService.NewLine);
#endif
byte[] pbFile = StrUtil.Utf8.GetBytes(sb.ToString());
s = IOConnection.OpenWrite(iocLockFile);
if(s == null) throw new IOException(iocLockFile.GetDisplayName());
s.Write(pbFile, 0, pbFile.Length);
}
finally { if(s != null) s.Close(); }
return lfi;
}
}
public FileLock(IOConnectionInfo iocBaseFile)
{
if(iocBaseFile == null) throw new ArgumentNullException("strBaseFile");
m_iocLockFile = iocBaseFile.CloneDeep();
m_iocLockFile.Path += LockFileExt;
LockFileInfo lfiEx = LockFileInfo.Load(m_iocLockFile);
if(lfiEx != null)
{
m_iocLockFile = null; // Otherwise Dispose deletes the existing one
throw new FileLockException(iocBaseFile.GetDisplayName(),
lfiEx.GetOwner());
}
LockFileInfo.Create(m_iocLockFile);
}
~FileLock()
{
Dispose(false);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private void Dispose(bool bDisposing)
{
if(m_iocLockFile == null) return;
bool bFileDeleted = false;
for(int r = 0; r < 5; ++r)
{
// if(!OwnLockFile()) { bFileDeleted = true; break; }
try
{
IOConnection.DeleteFile(m_iocLockFile);
bFileDeleted = true;
}
catch(Exception) { Debug.Assert(false); }
if(bFileDeleted) break;
if(bDisposing) Thread.Sleep(50);
}
// if(bDisposing && !bFileDeleted)
// IOConnection.DeleteFile(m_iocLockFile); // Possibly with exception
m_iocLockFile = null;
}
// private bool OwnLockFile()
// {
// if(m_iocLockFile == null) { Debug.Assert(false); return false; }
// if(m_strLockID == null) { Debug.Assert(false); return false; }
// LockFileInfo lfi = LockFileInfo.Load(m_iocLockFile);
// if(lfi == null) return false;
// return m_strLockID.Equals(lfi.ID);
// }
}
}
|