Merge branch 'master' of git://github.com/Jopie64/tortoisegit
[TortoiseGit.git] / src / TGitCache / DirectoryWatcher.cpp
bloba2cdfb2d608b190415d6b5c85296445e23944680
1 // TortoiseSVN - a Windows shell extension for easy version control
3 // External Cache Copyright (C) 2005 - 2007 - TortoiseSVN
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 "GitStatusCache.h"
22 #include ".\directorywatcher.h"
24 extern HWND hWnd;
26 CDirectoryWatcher::CDirectoryWatcher(void) : m_hCompPort(NULL)
27 , m_bRunning(TRUE)
28 , m_FolderCrawler(NULL)
29 , blockTickCount(0)
31 // enable the required privileges for this process
33 LPCTSTR arPrivelegeNames[] = { SE_BACKUP_NAME,
34 SE_RESTORE_NAME,
35 SE_CHANGE_NOTIFY_NAME
38 for (int i=0; i<(sizeof(arPrivelegeNames)/sizeof(LPCTSTR)); ++i)
40 HANDLE hToken;
41 if (OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES, &hToken))
43 TOKEN_PRIVILEGES tp = { 1 };
45 if (LookupPrivilegeValue(NULL, arPrivelegeNames[i], &tp.Privileges[0].Luid))
47 tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
49 AdjustTokenPrivileges(hToken, FALSE, &tp, sizeof(tp), NULL, NULL);
51 CloseHandle(hToken);
55 unsigned int threadId;
56 m_hThread = (HANDLE)_beginthreadex(NULL,0,ThreadEntry,this,0,&threadId);
59 CDirectoryWatcher::~CDirectoryWatcher(void)
61 InterlockedExchange(&m_bRunning, FALSE);
62 if (m_hThread != INVALID_HANDLE_VALUE)
64 CloseHandle(m_hThread);
65 m_hThread = INVALID_HANDLE_VALUE;
67 AutoLocker lock(m_critSec);
68 ClearInfoMap();
71 void CDirectoryWatcher::Stop()
73 InterlockedExchange(&m_bRunning, FALSE);
74 if (m_hThread != INVALID_HANDLE_VALUE)
75 CloseHandle(m_hThread);
76 m_hThread = INVALID_HANDLE_VALUE;
77 if (m_hCompPort != INVALID_HANDLE_VALUE)
78 CloseHandle(m_hCompPort);
79 m_hCompPort = INVALID_HANDLE_VALUE;
82 void CDirectoryWatcher::SetFolderCrawler(CFolderCrawler * crawler)
84 m_FolderCrawler = crawler;
87 bool CDirectoryWatcher::RemovePathAndChildren(const CTGitPath& path)
89 bool bRemoved = false;
90 AutoLocker lock(m_critSec);
91 repeat:
92 for (int i=0; i<watchedPaths.GetCount(); ++i)
94 if (path.IsAncestorOf(watchedPaths[i]))
96 watchedPaths.RemovePath(watchedPaths[i]);
97 bRemoved = true;
98 goto repeat;
101 return bRemoved;
104 void CDirectoryWatcher::BlockPath(const CTGitPath& path)
106 blockedPath = path;
107 // block the path from being watched for 4 seconds
108 blockTickCount = GetTickCount()+4000;
109 ATLTRACE(_T("Blocking path: %s\n"), path.GetWinPath());
112 bool CDirectoryWatcher::AddPath(const CTGitPath& path)
114 if (!CGitStatusCache::Instance().IsPathAllowed(path))
115 return false;
116 if ((!blockedPath.IsEmpty())&&(blockedPath.IsAncestorOf(path)))
118 if (GetTickCount() < blockTickCount)
120 ATLTRACE(_T("Path %s prevented from being watched\n"), path.GetWinPath());
121 return false;
124 AutoLocker lock(m_critSec);
125 for (int i=0; i<watchedPaths.GetCount(); ++i)
127 if (watchedPaths[i].IsAncestorOf(path))
128 return false; // already watched (recursively)
131 // now check if with the new path we might have a new root
132 CTGitPath newroot;
133 for (int i=0; i<watchedPaths.GetCount(); ++i)
135 const CString& watched = watchedPaths[i].GetWinPathString();
136 const CString& sPath = path.GetWinPathString();
137 int minlen = min(sPath.GetLength(), watched.GetLength());
138 int len = 0;
139 for (len = 0; len < minlen; ++len)
141 if (watched.GetAt(len) != sPath.GetAt(len))
143 if ((len > 1)&&(len < minlen))
145 if (sPath.GetAt(len)=='\\')
147 newroot = CTGitPath(sPath.Left(len));
149 else if (watched.GetAt(len)=='\\')
151 newroot = CTGitPath(watched.Left(len));
154 break;
157 if (len == minlen)
159 if (sPath.GetLength() == minlen)
161 if (watched.GetLength() > minlen)
163 if (watched.GetAt(len)=='\\')
165 newroot = path;
167 else if (sPath.GetLength() == 3 && sPath[1] == ':')
169 newroot = path;
173 else
175 if (sPath.GetLength() > minlen)
177 if (sPath.GetAt(len)=='\\')
179 newroot = CTGitPath(watched);
181 else if (watched.GetLength() == 3 && watched[1] == ':')
183 newroot = CTGitPath(watched);
189 if (!newroot.IsEmpty())
191 ATLTRACE(_T("add path to watch %s\n"), newroot.GetWinPath());
192 watchedPaths.AddPath(newroot);
193 watchedPaths.RemoveChildren();
194 CloseInfoMap();
195 m_hCompPort = INVALID_HANDLE_VALUE;
196 return true;
198 ATLTRACE(_T("add path to watch %s\n"), path.GetWinPath());
199 watchedPaths.AddPath(path);
200 CloseInfoMap();
201 m_hCompPort = INVALID_HANDLE_VALUE;
202 return true;
205 bool CDirectoryWatcher::IsPathWatched(const CTGitPath& path)
207 for (int i=0; i<watchedPaths.GetCount(); ++i)
209 if (watchedPaths[i].IsAncestorOf(path))
210 return true;
212 return false;
215 unsigned int CDirectoryWatcher::ThreadEntry(void* pContext)
217 ((CDirectoryWatcher*)pContext)->WorkerThread();
218 return 0;
221 void CDirectoryWatcher::WorkerThread()
223 DWORD numBytes;
224 CDirWatchInfo * pdi = NULL;
225 LPOVERLAPPED lpOverlapped;
226 WCHAR buf[READ_DIR_CHANGE_BUFFER_SIZE] = {0};
227 WCHAR * pFound = NULL;
228 while (m_bRunning)
230 if (watchedPaths.GetCount())
232 if (!GetQueuedCompletionStatus(m_hCompPort,
233 &numBytes,
234 (PULONG_PTR) &pdi,
235 &lpOverlapped,
236 INFINITE))
238 // Error retrieving changes
239 // Clear the list of watched objects and recreate that list
240 if (!m_bRunning)
241 return;
243 AutoLocker lock(m_critSec);
244 ClearInfoMap();
246 DWORD lasterr = GetLastError();
247 if ((m_hCompPort != INVALID_HANDLE_VALUE)&&(lasterr!=ERROR_SUCCESS)&&(lasterr!=ERROR_INVALID_HANDLE))
249 CloseHandle(m_hCompPort);
250 m_hCompPort = INVALID_HANDLE_VALUE;
252 // Since we pass m_hCompPort to CreateIoCompletionPort, we
253 // have to set this to NULL to have that API create a new
254 // handle.
255 m_hCompPort = NULL;
256 for (int i=0; i<watchedPaths.GetCount(); ++i)
258 CTGitPath watchedPath = watchedPaths[i];
260 HANDLE hDir = CreateFile(watchedPath.GetWinPath(),
261 FILE_LIST_DIRECTORY,
262 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
263 NULL, //security attributes
264 OPEN_EXISTING,
265 FILE_FLAG_BACKUP_SEMANTICS | //required privileges: SE_BACKUP_NAME and SE_RESTORE_NAME.
266 FILE_FLAG_OVERLAPPED,
267 NULL);
268 if (hDir == INVALID_HANDLE_VALUE)
270 // this could happen if a watched folder has been removed/renamed
271 ATLTRACE(_T("CDirectoryWatcher: CreateFile failed. Can't watch directory %s\n"), watchedPaths[i].GetWinPath());
272 CloseHandle(m_hCompPort);
273 m_hCompPort = INVALID_HANDLE_VALUE;
274 AutoLocker lock(m_critSec);
275 watchedPaths.RemovePath(watchedPath);
276 i--; if (i<0) i=0;
277 break;
280 DEV_BROADCAST_HANDLE NotificationFilter;
281 SecureZeroMemory(&NotificationFilter, sizeof(NotificationFilter));
282 NotificationFilter.dbch_size = sizeof(DEV_BROADCAST_HANDLE);
283 NotificationFilter.dbch_devicetype = DBT_DEVTYP_HANDLE;
284 NotificationFilter.dbch_handle = hDir;
285 NotificationFilter.dbch_hdevnotify = RegisterDeviceNotification(hWnd, &NotificationFilter, DEVICE_NOTIFY_WINDOW_HANDLE);
287 CDirWatchInfo * pDirInfo = new CDirWatchInfo(hDir, watchedPath);
288 pDirInfo->m_hDevNotify = NotificationFilter.dbch_hdevnotify;
289 m_hCompPort = CreateIoCompletionPort(hDir, m_hCompPort, (ULONG_PTR)pDirInfo, 0);
290 if (m_hCompPort == NULL)
292 ATLTRACE(_T("CDirectoryWatcher: CreateIoCompletionPort failed. Can't watch directory %s\n"), watchedPath.GetWinPath());
293 AutoLocker lock(m_critSec);
294 ClearInfoMap();
295 delete pDirInfo;
296 pDirInfo = NULL;
297 watchedPaths.RemovePath(watchedPath);
298 i--; if (i<0) i=0;
299 break;
301 if (!ReadDirectoryChangesW(pDirInfo->m_hDir,
302 pDirInfo->m_Buffer,
303 READ_DIR_CHANGE_BUFFER_SIZE,
304 TRUE,
305 FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_DIR_NAME | FILE_NOTIFY_CHANGE_LAST_WRITE,
306 &numBytes,// not used
307 &pDirInfo->m_Overlapped,
308 NULL)) //no completion routine!
310 ATLTRACE(_T("CDirectoryWatcher: ReadDirectoryChangesW failed. Can't watch directory %s\n"), watchedPath.GetWinPath());
311 AutoLocker lock(m_critSec);
312 ClearInfoMap();
313 delete pDirInfo;
314 pDirInfo = NULL;
315 watchedPaths.RemovePath(watchedPath);
316 i--; if (i<0) i=0;
317 break;
319 AutoLocker lock(m_critSec);
320 watchInfoMap[pDirInfo->m_hDir] = pDirInfo;
321 ATLTRACE(_T("watching path %s\n"), pDirInfo->m_DirName.GetWinPath());
324 else
326 if (!m_bRunning)
327 return;
328 // NOTE: the longer this code takes to execute until ReadDirectoryChangesW
329 // is called again, the higher the chance that we miss some
330 // changes in the file system!
331 if (pdi)
333 if (numBytes == 0)
335 goto continuewatching;
337 PFILE_NOTIFY_INFORMATION pnotify = (PFILE_NOTIFY_INFORMATION)pdi->m_Buffer;
338 if ((ULONG_PTR)pnotify - (ULONG_PTR)pdi->m_Buffer > READ_DIR_CHANGE_BUFFER_SIZE)
339 goto continuewatching;
340 DWORD nOffset = pnotify->NextEntryOffset;
343 nOffset = pnotify->NextEntryOffset;
344 if (pnotify->FileNameLength >= (READ_DIR_CHANGE_BUFFER_SIZE*sizeof(TCHAR)))
345 continue;
346 SecureZeroMemory(buf, READ_DIR_CHANGE_BUFFER_SIZE*sizeof(TCHAR));
347 _tcsncpy_s(buf, READ_DIR_CHANGE_BUFFER_SIZE, pdi->m_DirPath, READ_DIR_CHANGE_BUFFER_SIZE);
348 errno_t err = _tcsncat_s(buf+pdi->m_DirPath.GetLength(), READ_DIR_CHANGE_BUFFER_SIZE-pdi->m_DirPath.GetLength(), pnotify->FileName, _TRUNCATE);
349 if (err == STRUNCATE)
351 pnotify = (PFILE_NOTIFY_INFORMATION)((LPBYTE)pnotify + nOffset);
352 continue;
354 buf[(pnotify->FileNameLength/sizeof(TCHAR))+pdi->m_DirPath.GetLength()] = 0;
355 pnotify = (PFILE_NOTIFY_INFORMATION)((LPBYTE)pnotify + nOffset);
356 if (m_FolderCrawler)
358 if ((pFound = wcsstr(buf, L"\\tmp"))!=NULL)
360 pFound += 4;
361 if (((*pFound)=='\\')||((*pFound)=='\0'))
363 if ((ULONG_PTR)pnotify - (ULONG_PTR)pdi->m_Buffer > READ_DIR_CHANGE_BUFFER_SIZE)
364 break;
365 continue;
368 if ((pFound = wcsstr(buf, L":\\RECYCLER\\"))!=NULL)
370 if ((pFound-buf) < 5)
372 // a notification for the recycle bin - ignore it
373 if ((ULONG_PTR)pnotify - (ULONG_PTR)pdi->m_Buffer > READ_DIR_CHANGE_BUFFER_SIZE)
374 break;
375 continue;
378 if ((pFound = wcsstr(buf, L":\\$Recycle.Bin\\"))!=NULL)
380 if ((pFound-buf) < 5)
382 // a notification for the recycle bin - ignore it
383 if ((ULONG_PTR)pnotify - (ULONG_PTR)pdi->m_Buffer > READ_DIR_CHANGE_BUFFER_SIZE)
384 break;
385 continue;
388 if ((pFound = wcsstr(buf, L".tmp"))!=NULL)
390 // assume files with a .tmp extension are not versioned and interesting,
391 // so ignore them.
392 if ((ULONG_PTR)pnotify - (ULONG_PTR)pdi->m_Buffer > READ_DIR_CHANGE_BUFFER_SIZE)
393 break;
394 continue;
396 ATLTRACE(_T("change notification: %s\n"), buf);
397 m_FolderCrawler->AddPathForUpdate(CTGitPath(buf));
399 if ((ULONG_PTR)pnotify - (ULONG_PTR)pdi->m_Buffer > READ_DIR_CHANGE_BUFFER_SIZE)
400 break;
401 } while (nOffset);
402 continuewatching:
403 SecureZeroMemory(pdi->m_Buffer, sizeof(pdi->m_Buffer));
404 SecureZeroMemory(&pdi->m_Overlapped, sizeof(OVERLAPPED));
405 if (!ReadDirectoryChangesW(pdi->m_hDir,
406 pdi->m_Buffer,
407 READ_DIR_CHANGE_BUFFER_SIZE,
408 TRUE,
409 FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_DIR_NAME | FILE_NOTIFY_CHANGE_LAST_WRITE,
410 &numBytes,// not used
411 &pdi->m_Overlapped,
412 NULL)) //no completion routine!
414 // Since the call to ReadDirectoryChangesW failed, just
415 // wait a while. We don't want to have this thread
416 // running using 100% CPU if something goes completely
417 // wrong.
418 Sleep(200);
422 }// if (watchedPaths.GetCount())
423 else
424 Sleep(200);
425 }// while (m_bRunning)
428 void CDirectoryWatcher::ClearInfoMap()
430 if (watchInfoMap.size()!=0)
432 AutoLocker lock(m_critSec);
433 for (std::map<HANDLE, CDirWatchInfo *>::iterator I = watchInfoMap.begin(); I != watchInfoMap.end(); ++I)
435 CDirectoryWatcher::CDirWatchInfo * info = I->second;
436 delete info;
437 info = NULL;
440 watchInfoMap.clear();
441 if (m_hCompPort != INVALID_HANDLE_VALUE)
442 CloseHandle(m_hCompPort);
443 m_hCompPort = INVALID_HANDLE_VALUE;
446 CTGitPath CDirectoryWatcher::CloseInfoMap(HDEVNOTIFY hdev)
448 CTGitPath path;
449 if (watchInfoMap.size() == 0)
450 return path;
451 AutoLocker lock(m_critSec);
452 for (std::map<HANDLE, CDirWatchInfo *>::iterator I = watchInfoMap.begin(); I != watchInfoMap.end(); ++I)
454 CDirectoryWatcher::CDirWatchInfo * info = I->second;
455 if (info->m_hDevNotify == hdev)
457 path = info->m_DirName;
458 RemovePathAndChildren(path);
459 BlockPath(path);
461 info->CloseDirectoryHandle();
463 watchInfoMap.clear();
464 if (m_hCompPort != INVALID_HANDLE_VALUE)
465 CloseHandle(m_hCompPort);
466 m_hCompPort = INVALID_HANDLE_VALUE;
467 return path;
470 bool CDirectoryWatcher::CloseHandlesForPath(const CTGitPath& path)
472 if (watchInfoMap.size() == 0)
473 return false;
474 AutoLocker lock(m_critSec);
475 for (std::map<HANDLE, CDirWatchInfo *>::iterator I = watchInfoMap.begin(); I != watchInfoMap.end(); ++I)
477 CDirectoryWatcher::CDirWatchInfo * info = I->second;
478 CTGitPath p = CTGitPath(info->m_DirPath);
479 if (path.IsAncestorOf(p))
481 RemovePathAndChildren(p);
482 BlockPath(p);
484 info->CloseDirectoryHandle();
486 watchInfoMap.clear();
487 if (m_hCompPort != INVALID_HANDLE_VALUE)
488 CloseHandle(m_hCompPort);
489 m_hCompPort = INVALID_HANDLE_VALUE;
490 return true;
493 CDirectoryWatcher::CDirWatchInfo::CDirWatchInfo(HANDLE hDir, const CTGitPath& DirectoryName) :
494 m_hDir(hDir),
495 m_DirName(DirectoryName)
497 ATLASSERT( hDir != INVALID_HANDLE_VALUE
498 && !DirectoryName.IsEmpty());
499 memset(&m_Overlapped, 0, sizeof(m_Overlapped));
500 m_DirPath = m_DirName.GetWinPathString();
501 if (m_DirPath.GetAt(m_DirPath.GetLength()-1) != '\\')
502 m_DirPath += _T("\\");
503 m_hDevNotify = INVALID_HANDLE_VALUE;
506 CDirectoryWatcher::CDirWatchInfo::~CDirWatchInfo()
508 CloseDirectoryHandle();
511 bool CDirectoryWatcher::CDirWatchInfo::CloseDirectoryHandle()
513 bool b = TRUE;
514 if( m_hDir != INVALID_HANDLE_VALUE )
516 b = !!CloseHandle(m_hDir);
517 m_hDir = INVALID_HANDLE_VALUE;
519 if (m_hDevNotify != INVALID_HANDLE_VALUE)
521 UnregisterDeviceNotification(m_hDevNotify);
523 return b;