TortoiseGitSetup: Added ElevationShield image to install button
[TortoiseGit.git] / src / Utils / PathWatcher.cpp
blobf16142b96acbc23bdb03091be96f9bb3a9d72147
1 // TortoiseGit - a Windows shell extension for easy version control
3 // External Cache Copyright (C) 2007 - 2007 - Stefan Kueng
5 // This program is free software; you can redistribute it and/or
6 // modify it under the terms of the GNU General Public License
7 // as published by the Free Software Foundation; either version 2
8 // of the License, or (at your option) any later version.
10 // This program is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with this program; if not, write to the Free Software Foundation,
17 // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19 #include "StdAfx.h"
20 #include "Dbt.h"
21 #include "PathWatcher.h"
23 CPathWatcher::CPathWatcher(void) : m_hCompPort(NULL)
24 , m_bRunning(TRUE)
26 // enable the required privileges for this process
27 LPCTSTR arPrivelegeNames[] = { SE_BACKUP_NAME,
28 SE_RESTORE_NAME,
29 SE_CHANGE_NOTIFY_NAME
32 for (int i=0; i<(sizeof(arPrivelegeNames)/sizeof(LPCTSTR)); ++i)
34 CAutoGeneralHandle hToken;
35 if (OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES, hToken.GetPointer()))
37 TOKEN_PRIVILEGES tp = { 1 };
39 if (LookupPrivilegeValue(NULL, arPrivelegeNames[i], &tp.Privileges[0].Luid))
41 tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
43 AdjustTokenPrivileges(hToken, FALSE, &tp, sizeof(tp), NULL, NULL);
48 unsigned int threadId;
49 m_hThread = (HANDLE)_beginthreadex(NULL,0,ThreadEntry,this,0,&threadId);
52 CPathWatcher::~CPathWatcher(void)
54 InterlockedExchange(&m_bRunning, FALSE);
55 m_hThread.CloseHandle();
56 AutoLocker lock(m_critSec);
57 ClearInfoMap();
60 void CPathWatcher::Stop()
62 InterlockedExchange(&m_bRunning, FALSE);
63 if (m_hCompPort)
65 PostQueuedCompletionStatus(m_hCompPort, 0, NULL, NULL);
66 m_hCompPort.CloseHandle();
69 if (m_hThread)
71 if( WaitForSingleObject(m_hThread, 1000) != WAIT_OBJECT_0 )
73 TerminateThread(m_hThread, (DWORD)-1);
75 m_hThread.CloseHandle();
79 bool CPathWatcher::RemovePathAndChildren(const CTGitPath& path)
81 bool bRemoved = false;
82 AutoLocker lock(m_critSec);
83 repeat:
84 for (int i=0; i<watchedPaths.GetCount(); ++i)
86 if (path.IsAncestorOf(watchedPaths[i]))
88 watchedPaths.RemovePath(watchedPaths[i]);
89 bRemoved = true;
90 goto repeat;
93 return bRemoved;
96 bool CPathWatcher::AddPath(const CTGitPath& path)
98 AutoLocker lock(m_critSec);
99 for (int i=0; i<watchedPaths.GetCount(); ++i)
101 if (watchedPaths[i].IsAncestorOf(path))
102 return false; // already watched (recursively)
105 // now check if with the new path we might have a new root
106 CTGitPath newroot;
107 for (int i=0; i<watchedPaths.GetCount(); ++i)
109 const CString& watched = watchedPaths[i].GetWinPathString();
110 const CString& sPath = path.GetWinPathString();
111 int minlen = min(sPath.GetLength(), watched.GetLength());
112 int len = 0;
113 for (len = 0; len < minlen; ++len)
115 if (watched.GetAt(len) != sPath.GetAt(len))
117 if ((len > 1)&&(len < minlen))
119 if (sPath.GetAt(len)=='\\')
121 newroot = CTGitPath(sPath.Left(len));
123 else if (watched.GetAt(len)=='\\')
125 newroot = CTGitPath(watched.Left(len));
128 break;
131 if (len == minlen)
133 if (sPath.GetLength() == minlen)
135 if (watched.GetLength() > minlen)
137 if (watched.GetAt(len)=='\\')
139 newroot = path;
141 else if (sPath.GetLength() == 3 && sPath[1] == ':')
143 newroot = path;
147 else
149 if (sPath.GetLength() > minlen)
151 if (sPath.GetAt(len)=='\\')
153 newroot = CTGitPath(watched);
155 else if (watched.GetLength() == 3 && watched[1] == ':')
157 newroot = CTGitPath(watched);
163 if (!newroot.IsEmpty())
165 ATLTRACE(_T("add path to watch %s\n"), newroot.GetWinPath());
166 watchedPaths.AddPath(newroot);
167 watchedPaths.RemoveChildren();
168 m_hCompPort.CloseHandle();
169 return true;
171 ATLTRACE(_T("add path to watch %s\n"), path.GetWinPath());
172 watchedPaths.AddPath(path);
173 m_hCompPort.CloseHandle();
174 return true;
178 unsigned int CPathWatcher::ThreadEntry(void* pContext)
180 ((CPathWatcher*)pContext)->WorkerThread();
181 return 0;
184 void CPathWatcher::WorkerThread()
186 DWORD numBytes;
187 CDirWatchInfo * pdi = NULL;
188 LPOVERLAPPED lpOverlapped;
189 WCHAR buf[MAX_PATH*4] = {0};
190 while (m_bRunning)
192 if (watchedPaths.GetCount())
194 if (!m_hCompPort || !GetQueuedCompletionStatus(m_hCompPort,
195 &numBytes,
196 (PULONG_PTR) &pdi,
197 &lpOverlapped,
198 INFINITE))
200 // Error retrieving changes
201 // Clear the list of watched objects and recreate that list
202 if (!m_bRunning)
203 return;
205 AutoLocker lock(m_critSec);
206 ClearInfoMap();
208 DWORD lasterr = GetLastError();
209 if ((m_hCompPort)&&(lasterr!=ERROR_SUCCESS)&&(lasterr!=ERROR_INVALID_HANDLE))
211 m_hCompPort.CloseHandle();
213 // Since we pass m_hCompPort to CreateIoCompletionPort, we
214 // have to set this to NULL to have that API create a new
215 // handle.
216 m_hCompPort = NULL;
217 for (int i=0; i<watchedPaths.GetCount(); ++i)
219 CAutoFile hDir = CreateFile(watchedPaths[i].GetWinPath(),
220 FILE_LIST_DIRECTORY,
221 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
222 NULL, //security attributes
223 OPEN_EXISTING,
224 FILE_FLAG_BACKUP_SEMANTICS | //required privileges: SE_BACKUP_NAME and SE_RESTORE_NAME.
225 FILE_FLAG_OVERLAPPED,
226 NULL);
227 if (!hDir)
229 // this could happen if a watched folder has been removed/renamed
230 m_hCompPort.CloseHandle();
231 AutoLocker lock(m_critSec);
232 watchedPaths.RemovePath(watchedPaths[i]);
233 i--; if (i<0) i=0;
234 break;
237 CDirWatchInfo * pDirInfo = new CDirWatchInfo(hDir, watchedPaths[i]);
238 hDir.Detach(); // the new CDirWatchInfo object owns the handle now
239 m_hCompPort = CreateIoCompletionPort(pDirInfo->m_hDir, m_hCompPort, (ULONG_PTR)pDirInfo, 0);
240 if (m_hCompPort == NULL)
242 AutoLocker lock(m_critSec);
243 ClearInfoMap();
244 delete pDirInfo;
245 pDirInfo = NULL;
246 watchedPaths.RemovePath(watchedPaths[i]);
247 i--; if (i<0) i=0;
248 break;
250 if (!ReadDirectoryChangesW(pDirInfo->m_hDir,
251 pDirInfo->m_Buffer,
252 READ_DIR_CHANGE_BUFFER_SIZE,
253 TRUE,
254 FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_DIR_NAME | FILE_NOTIFY_CHANGE_LAST_WRITE,
255 &numBytes,// not used
256 &pDirInfo->m_Overlapped,
257 NULL)) //no completion routine!
259 AutoLocker lock(m_critSec);
260 ClearInfoMap();
261 delete pDirInfo;
262 pDirInfo = NULL;
263 watchedPaths.RemovePath(watchedPaths[i]);
264 i--; if (i<0) i=0;
265 break;
267 AutoLocker lock(m_critSec);
268 watchInfoMap[pDirInfo->m_hDir] = pDirInfo;
269 ATLTRACE(_T("watching path %s\n"), pDirInfo->m_DirName.GetWinPath());
272 else
274 if (!m_bRunning)
275 return;
276 // NOTE: the longer this code takes to execute until ReadDirectoryChangesW
277 // is called again, the higher the chance that we miss some
278 // changes in the file system!
279 if (pdi)
281 if (numBytes == 0)
283 goto continuewatching;
285 PFILE_NOTIFY_INFORMATION pnotify = (PFILE_NOTIFY_INFORMATION)pdi->m_Buffer;
286 if ((ULONG_PTR)pnotify - (ULONG_PTR)pdi->m_Buffer > READ_DIR_CHANGE_BUFFER_SIZE)
287 goto continuewatching;
288 DWORD nOffset = pnotify->NextEntryOffset;
291 nOffset = pnotify->NextEntryOffset;
292 SecureZeroMemory(buf, MAX_PATH*4*sizeof(TCHAR));
293 _tcsncpy_s(buf, MAX_PATH*4, pdi->m_DirPath, MAX_PATH*4);
294 errno_t err = _tcsncat_s(buf+pdi->m_DirPath.GetLength(), (MAX_PATH*4)-pdi->m_DirPath.GetLength(), pnotify->FileName, _TRUNCATE);
295 if (err == STRUNCATE)
297 pnotify = (PFILE_NOTIFY_INFORMATION)((LPBYTE)pnotify + nOffset);
298 continue;
300 buf[min(MAX_PATH*4-1, pdi->m_DirPath.GetLength()+(pnotify->FileNameLength/sizeof(WCHAR)))] = 0;
301 pnotify = (PFILE_NOTIFY_INFORMATION)((LPBYTE)pnotify + nOffset);
302 ATLTRACE(_T("change notification: %s\n"), buf);
303 m_changedPaths.AddPath(CTGitPath(buf));
304 if ((ULONG_PTR)pnotify - (ULONG_PTR)pdi->m_Buffer > READ_DIR_CHANGE_BUFFER_SIZE)
305 break;
306 } while (nOffset);
307 continuewatching:
308 SecureZeroMemory(pdi->m_Buffer, sizeof(pdi->m_Buffer));
309 SecureZeroMemory(&pdi->m_Overlapped, sizeof(OVERLAPPED));
310 if (!ReadDirectoryChangesW(pdi->m_hDir,
311 pdi->m_Buffer,
312 READ_DIR_CHANGE_BUFFER_SIZE,
313 TRUE,
314 FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_DIR_NAME | FILE_NOTIFY_CHANGE_LAST_WRITE,
315 &numBytes,// not used
316 &pdi->m_Overlapped,
317 NULL)) //no completion routine!
319 // Since the call to ReadDirectoryChangesW failed, just
320 // wait a while. We don't want to have this thread
321 // running using 100% CPU if something goes completely
322 // wrong.
323 Sleep(200);
327 }// if (watchedPaths.GetCount())
328 else
329 Sleep(200);
330 }// while (m_bRunning)
333 void CPathWatcher::ClearInfoMap()
335 if (watchInfoMap.size()!=0)
337 AutoLocker lock(m_critSec);
338 for (std::map<HANDLE, CDirWatchInfo *>::iterator I = watchInfoMap.begin(); I != watchInfoMap.end(); ++I)
340 CPathWatcher::CDirWatchInfo * info = I->second;
341 delete info;
342 info = NULL;
345 watchInfoMap.clear();
346 m_hCompPort.CloseHandle();
349 CPathWatcher::CDirWatchInfo::CDirWatchInfo(HANDLE hDir, const CTGitPath& DirectoryName) :
350 m_hDir(hDir),
351 m_DirName(DirectoryName)
353 ATLASSERT( hDir && !DirectoryName.IsEmpty());
354 m_Buffer[0] = 0;
355 memset(&m_Overlapped, 0, sizeof(m_Overlapped));
356 m_DirPath = m_DirName.GetWinPathString();
357 if (m_DirPath.GetAt(m_DirPath.GetLength()-1) != '\\')
358 m_DirPath += _T("\\");
361 CPathWatcher::CDirWatchInfo::~CDirWatchInfo()
363 CloseDirectoryHandle();
366 bool CPathWatcher::CDirWatchInfo::CloseDirectoryHandle()
368 return m_hDir.CloseHandle();