Minor cleanup
[TortoiseGit.git] / src / Utils / PathWatcher.cpp
blob8022122cdb7999ae5d1e31c8e9d8c2799c13fd2a
1 // TortoiseGit - a Windows shell extension for easy version control
3 // Copyright (C) 2013 - TortoiseGit
4 // External Cache Copyright (C) 2007-2012 - TortoiseSVN
6 // This program is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU General Public License
8 // as published by the Free Software Foundation; either version 2
9 // of the License, or (at your option) any later version.
11 // This program is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 // GNU General Public License for more details.
16 // You should have received a copy of the GNU General Public License
17 // along with this program; if not, write to the Free Software Foundation,
18 // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20 #include "stdafx.h"
21 #include "Dbt.h"
22 #include "PathWatcher.h"
24 CPathWatcher::CPathWatcher(void) : m_hCompPort(NULL)
25 , m_bRunning(TRUE)
26 , m_bLimitReached(false)
28 // enable the required privileges for this process
29 LPCTSTR arPrivelegeNames[] = { SE_BACKUP_NAME,
30 SE_RESTORE_NAME,
31 SE_CHANGE_NOTIFY_NAME
34 for (int i=0; i<(sizeof(arPrivelegeNames)/sizeof(LPCTSTR)); ++i)
36 CAutoGeneralHandle hToken;
37 if (OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES, hToken.GetPointer()))
39 TOKEN_PRIVILEGES tp = { 1 };
41 if (LookupPrivilegeValue(NULL, arPrivelegeNames[i], &tp.Privileges[0].Luid))
43 tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
45 AdjustTokenPrivileges(hToken, FALSE, &tp, sizeof(tp), NULL, NULL);
50 unsigned int threadId = 0;
51 m_hThread = (HANDLE)_beginthreadex(NULL,0,ThreadEntry,this,0,&threadId);
54 CPathWatcher::~CPathWatcher(void)
56 Stop();
57 AutoLocker lock(m_critSec);
58 ClearInfoMap();
61 void CPathWatcher::Stop()
63 InterlockedExchange(&m_bRunning, FALSE);
64 if (m_hCompPort)
66 PostQueuedCompletionStatus(m_hCompPort, 0, NULL, NULL);
67 m_hCompPort.CloseHandle();
70 if (m_hThread)
72 // the background thread sleeps for 200ms,
73 // so lets wait for it to finish for 1000 ms.
75 WaitForSingleObject(m_hThread, 1000);
76 m_hThread.CloseHandle();
80 bool CPathWatcher::RemovePathAndChildren(const CTGitPath& path)
82 bool bRemoved = false;
83 AutoLocker lock(m_critSec);
84 repeat:
85 for (int i=0; i<watchedPaths.GetCount(); ++i)
87 if (path.IsAncestorOf(watchedPaths[i]))
89 watchedPaths.RemovePath(watchedPaths[i]);
90 bRemoved = true;
91 goto repeat;
94 return bRemoved;
97 bool CPathWatcher::AddPath(const CTGitPath& path)
99 AutoLocker lock(m_critSec);
100 for (int i=0; i<watchedPaths.GetCount(); ++i)
102 if (watchedPaths[i].IsAncestorOf(path))
103 return false; // already watched (recursively)
106 // now check if with the new path we might have a new root
107 CTGitPath newroot;
108 for (int i=0; i<watchedPaths.GetCount(); ++i)
110 const CString& watched = watchedPaths[i].GetWinPathString();
111 const CString& sPath = path.GetWinPathString();
112 int minlen = min(sPath.GetLength(), watched.GetLength());
113 int len = 0;
114 for (len = 0; len < minlen; ++len)
116 if (watched.GetAt(len) != sPath.GetAt(len))
118 if ((len > 1)&&(len < minlen))
120 if (sPath.GetAt(len)=='\\')
122 newroot = CTGitPath(sPath.Left(len));
124 else if (watched.GetAt(len)=='\\')
126 newroot = CTGitPath(watched.Left(len));
129 break;
132 if (len == minlen)
134 if (sPath.GetLength() == minlen)
136 if (watched.GetLength() > minlen)
138 if (watched.GetAt(len)=='\\')
140 newroot = path;
142 else if (sPath.GetLength() == 3 && sPath[1] == ':')
144 newroot = path;
148 else
150 if (sPath.GetLength() > minlen)
152 if (sPath.GetAt(len)=='\\')
154 newroot = CTGitPath(watched);
156 else if (watched.GetLength() == 3 && watched[1] == ':')
158 newroot = CTGitPath(watched);
164 if (!newroot.IsEmpty())
166 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": add path to watch %s\n"), newroot.GetWinPath());
167 watchedPaths.AddPath(newroot);
168 watchedPaths.RemoveChildren();
169 m_hCompPort.CloseHandle();
170 return true;
172 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": add path to watch %s\n"), path.GetWinPath());
173 watchedPaths.AddPath(path);
174 m_hCompPort.CloseHandle();
175 return true;
179 unsigned int CPathWatcher::ThreadEntry(void* pContext)
181 ((CPathWatcher*)pContext)->WorkerThread();
182 return 0;
185 void CPathWatcher::WorkerThread()
187 DWORD numBytes;
188 CDirWatchInfo * pdi = NULL;
189 LPOVERLAPPED lpOverlapped;
190 const int bufferSize = MAX_PATH * 4;
191 TCHAR buf[bufferSize] = {0};
192 while (m_bRunning)
194 if (!watchedPaths.IsEmpty())
196 if (!m_hCompPort || !GetQueuedCompletionStatus(m_hCompPort,
197 &numBytes,
198 (PULONG_PTR) &pdi,
199 &lpOverlapped,
200 INFINITE))
202 // Error retrieving changes
203 // Clear the list of watched objects and recreate that list
204 if (!m_bRunning)
205 return;
207 AutoLocker lock(m_critSec);
208 ClearInfoMap();
210 DWORD lasterr = GetLastError();
211 if ((m_hCompPort)&&(lasterr!=ERROR_SUCCESS)&&(lasterr!=ERROR_INVALID_HANDLE))
213 m_hCompPort.CloseHandle();
215 for (int i=0; i<watchedPaths.GetCount(); ++i)
217 CAutoFile hDir = CreateFile(watchedPaths[i].GetWinPath(),
218 FILE_LIST_DIRECTORY,
219 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
220 NULL, //security attributes
221 OPEN_EXISTING,
222 FILE_FLAG_BACKUP_SEMANTICS | //required privileges: SE_BACKUP_NAME and SE_RESTORE_NAME.
223 FILE_FLAG_OVERLAPPED,
224 NULL);
225 if (!hDir)
227 // this could happen if a watched folder has been removed/renamed
228 m_hCompPort.CloseHandle();
229 AutoLocker lock(m_critSec);
230 watchedPaths.RemovePath(watchedPaths[i]);
231 i--; if (i<0) i=0;
232 break;
235 CDirWatchInfo * pDirInfo = new CDirWatchInfo(hDir, watchedPaths[i]);
236 hDir.Detach(); // the new CDirWatchInfo object owns the handle now
237 m_hCompPort = CreateIoCompletionPort(pDirInfo->m_hDir, m_hCompPort, (ULONG_PTR)pDirInfo, 0);
238 if (m_hCompPort == NULL)
240 AutoLocker lock(m_critSec);
241 ClearInfoMap();
242 delete pDirInfo;
243 pDirInfo = NULL;
244 watchedPaths.RemovePath(watchedPaths[i]);
245 i--; if (i<0) i=0;
246 break;
248 if (!ReadDirectoryChangesW(pDirInfo->m_hDir,
249 pDirInfo->m_Buffer,
250 bufferSize,
251 TRUE,
252 FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_DIR_NAME | FILE_NOTIFY_CHANGE_LAST_WRITE,
253 &numBytes,// not used
254 &pDirInfo->m_Overlapped,
255 NULL)) //no completion routine!
257 AutoLocker lock(m_critSec);
258 ClearInfoMap();
259 delete pDirInfo;
260 pDirInfo = NULL;
261 watchedPaths.RemovePath(watchedPaths[i]);
262 i--; if (i<0) i=0;
263 break;
265 AutoLocker lock(m_critSec);
266 watchInfoMap[pDirInfo->m_hDir] = pDirInfo;
267 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": watching path %s\n"), pDirInfo->m_DirName.GetWinPath());
270 else
272 if (!m_bRunning)
273 return;
274 // NOTE: the longer this code takes to execute until ReadDirectoryChangesW
275 // is called again, the higher the chance that we miss some
276 // changes in the file system!
277 if (pdi)
279 if (numBytes == 0)
281 goto continuewatching;
283 PFILE_NOTIFY_INFORMATION pnotify = (PFILE_NOTIFY_INFORMATION)pdi->m_Buffer;
284 if ((ULONG_PTR)pnotify - (ULONG_PTR)pdi->m_Buffer > bufferSize)
285 goto continuewatching;
286 DWORD nOffset = pnotify->NextEntryOffset;
289 nOffset = pnotify->NextEntryOffset;
290 SecureZeroMemory(buf, bufferSize*sizeof(TCHAR));
291 _tcsncpy_s(buf, bufferSize, pdi->m_DirPath, bufferSize);
292 errno_t err = _tcsncat_s(buf+pdi->m_DirPath.GetLength(), bufferSize-pdi->m_DirPath.GetLength(), pnotify->FileName, min(bufferSize-pdi->m_DirPath.GetLength(), pnotify->FileNameLength/sizeof(TCHAR)));
293 if (err == STRUNCATE)
295 pnotify = (PFILE_NOTIFY_INFORMATION)((LPBYTE)pnotify + nOffset);
296 continue;
298 buf[min(bufferSize-1, pdi->m_DirPath.GetLength()+(pnotify->FileNameLength/sizeof(WCHAR)))] = 0;
299 pnotify = (PFILE_NOTIFY_INFORMATION)((LPBYTE)pnotify + nOffset);
300 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": change notification: %s\n"), buf);
302 AutoLocker lock(m_critSec);
303 if (m_changedPaths.GetCount() < MAX_CHANGED_PATHS)
304 m_changedPaths.AddPath(CTGitPath(buf));
305 else
306 m_bLimitReached = true;
308 if ((ULONG_PTR)pnotify - (ULONG_PTR)pdi->m_Buffer > bufferSize)
309 break;
310 } while (nOffset);
311 continuewatching:
313 AutoLocker lock(m_critSec);
314 m_changedPaths.RemoveDuplicates();
316 SecureZeroMemory(pdi->m_Buffer, sizeof(pdi->m_Buffer));
317 SecureZeroMemory(&pdi->m_Overlapped, sizeof(OVERLAPPED));
318 if (!ReadDirectoryChangesW(pdi->m_hDir,
319 pdi->m_Buffer,
320 bufferSize,
321 TRUE,
322 FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_DIR_NAME | FILE_NOTIFY_CHANGE_LAST_WRITE,
323 &numBytes,// not used
324 &pdi->m_Overlapped,
325 NULL)) //no completion routine!
327 // Since the call to ReadDirectoryChangesW failed, just
328 // wait a while. We don't want to have this thread
329 // running using 100% CPU if something goes completely
330 // wrong.
331 Sleep(200);
335 }// if (!watchedPaths.IsEmpty())
336 else
337 Sleep(200);
338 }// while (m_bRunning)
341 void CPathWatcher::ClearInfoMap()
343 if (!watchInfoMap.empty())
345 AutoLocker lock(m_critSec);
346 for (std::map<HANDLE, CDirWatchInfo *>::iterator I = watchInfoMap.begin(); I != watchInfoMap.end(); ++I)
348 CPathWatcher::CDirWatchInfo * info = I->second;
349 delete info;
350 info = NULL;
353 watchInfoMap.clear();
354 m_hCompPort.CloseHandle();
357 CPathWatcher::CDirWatchInfo::CDirWatchInfo(HANDLE hDir, const CTGitPath& DirectoryName)
358 : m_hDir(hDir)
359 , m_DirName(DirectoryName)
361 ATLASSERT( hDir && !DirectoryName.IsEmpty());
362 m_Buffer[0] = 0;
363 memset(&m_Overlapped, 0, sizeof(m_Overlapped));
364 m_DirPath = m_DirName.GetWinPathString();
365 if (m_DirPath.GetAt(m_DirPath.GetLength()-1) != '\\')
366 m_DirPath += _T("\\");
369 CPathWatcher::CDirWatchInfo::~CDirWatchInfo()
371 CloseDirectoryHandle();
374 bool CPathWatcher::CDirWatchInfo::CloseDirectoryHandle()
376 return m_hDir.CloseHandle();