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.
21 #include "GitStatusCache.h"
22 #include ".\directorywatcher.h"
26 CDirectoryWatcher::CDirectoryWatcher(void) : m_hCompPort(NULL
)
28 , m_FolderCrawler(NULL
)
31 // enable the required privileges for this process
33 LPCTSTR arPrivelegeNames
[] = { SE_BACKUP_NAME
,
38 for (int i
=0; i
<(sizeof(arPrivelegeNames
)/sizeof(LPCTSTR
)); ++i
)
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
);
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
);
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
);
92 for (int i
=0; i
<watchedPaths
.GetCount(); ++i
)
94 if (path
.IsAncestorOf(watchedPaths
[i
]))
96 watchedPaths
.RemovePath(watchedPaths
[i
]);
104 void CDirectoryWatcher::BlockPath(const CTGitPath
& 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
))
116 if ((!blockedPath
.IsEmpty())&&(blockedPath
.IsAncestorOf(path
)))
118 if (GetTickCount() < blockTickCount
)
120 ATLTRACE(_T("Path %s prevented from being watched\n"), path
.GetWinPath());
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
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());
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
));
159 if (sPath
.GetLength() == minlen
)
161 if (watched
.GetLength() > minlen
)
163 if (watched
.GetAt(len
)=='\\')
167 else if (sPath
.GetLength() == 3 && sPath
[1] == ':')
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();
195 m_hCompPort
= INVALID_HANDLE_VALUE
;
198 ATLTRACE(_T("add path to watch %s\n"), path
.GetWinPath());
199 watchedPaths
.AddPath(path
);
201 m_hCompPort
= INVALID_HANDLE_VALUE
;
205 bool CDirectoryWatcher::IsPathWatched(const CTGitPath
& path
)
207 for (int i
=0; i
<watchedPaths
.GetCount(); ++i
)
209 if (watchedPaths
[i
].IsAncestorOf(path
))
215 unsigned int CDirectoryWatcher::ThreadEntry(void* pContext
)
217 ((CDirectoryWatcher
*)pContext
)->WorkerThread();
221 void CDirectoryWatcher::WorkerThread()
224 CDirWatchInfo
* pdi
= NULL
;
225 LPOVERLAPPED lpOverlapped
;
226 WCHAR buf
[READ_DIR_CHANGE_BUFFER_SIZE
] = {0};
227 WCHAR
* pFound
= NULL
;
230 if (watchedPaths
.GetCount())
232 if (!GetQueuedCompletionStatus(m_hCompPort
,
238 // Error retrieving changes
239 // Clear the list of watched objects and recreate that list
243 AutoLocker
lock(m_critSec
);
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
256 for (int i
=0; i
<watchedPaths
.GetCount(); ++i
)
258 CTGitPath watchedPath
= watchedPaths
[i
];
260 HANDLE hDir
= CreateFile(watchedPath
.GetWinPath(),
262 FILE_SHARE_READ
| FILE_SHARE_WRITE
| FILE_SHARE_DELETE
,
263 NULL
, //security attributes
265 FILE_FLAG_BACKUP_SEMANTICS
| //required privileges: SE_BACKUP_NAME and SE_RESTORE_NAME.
266 FILE_FLAG_OVERLAPPED
,
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
);
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
);
297 watchedPaths
.RemovePath(watchedPath
);
301 if (!ReadDirectoryChangesW(pDirInfo
->m_hDir
,
303 READ_DIR_CHANGE_BUFFER_SIZE
,
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
);
315 watchedPaths
.RemovePath(watchedPath
);
319 AutoLocker
lock(m_critSec
);
320 watchInfoMap
[pDirInfo
->m_hDir
] = pDirInfo
;
321 ATLTRACE(_T("watching path %s\n"), pDirInfo
->m_DirName
.GetWinPath());
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!
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
)))
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
);
354 buf
[(pnotify
->FileNameLength
/sizeof(TCHAR
))+pdi
->m_DirPath
.GetLength()] = 0;
355 pnotify
= (PFILE_NOTIFY_INFORMATION
)((LPBYTE
)pnotify
+ nOffset
);
358 if ((pFound
= wcsstr(buf
, L
"\\tmp"))!=NULL
)
361 if (((*pFound
)=='\\')||((*pFound
)=='\0'))
363 if ((ULONG_PTR
)pnotify
- (ULONG_PTR
)pdi
->m_Buffer
> READ_DIR_CHANGE_BUFFER_SIZE
)
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
)
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
)
388 if ((pFound
= wcsstr(buf
, L
".tmp"))!=NULL
)
390 // assume files with a .tmp extension are not versioned and interesting,
392 if ((ULONG_PTR
)pnotify
- (ULONG_PTR
)pdi
->m_Buffer
> READ_DIR_CHANGE_BUFFER_SIZE
)
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
)
403 SecureZeroMemory(pdi
->m_Buffer
, sizeof(pdi
->m_Buffer
));
404 SecureZeroMemory(&pdi
->m_Overlapped
, sizeof(OVERLAPPED
));
405 if (!ReadDirectoryChangesW(pdi
->m_hDir
,
407 READ_DIR_CHANGE_BUFFER_SIZE
,
409 FILE_NOTIFY_CHANGE_FILE_NAME
| FILE_NOTIFY_CHANGE_DIR_NAME
| FILE_NOTIFY_CHANGE_LAST_WRITE
,
410 &numBytes
,// not used
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
422 }// if (watchedPaths.GetCount())
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
;
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
)
449 if (watchInfoMap
.size() == 0)
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
);
461 info
->CloseDirectoryHandle();
463 watchInfoMap
.clear();
464 if (m_hCompPort
!= INVALID_HANDLE_VALUE
)
465 CloseHandle(m_hCompPort
);
466 m_hCompPort
= INVALID_HANDLE_VALUE
;
470 bool CDirectoryWatcher::CloseHandlesForPath(const CTGitPath
& path
)
472 if (watchInfoMap
.size() == 0)
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
);
484 info
->CloseDirectoryHandle();
486 watchInfoMap
.clear();
487 if (m_hCompPort
!= INVALID_HANDLE_VALUE
)
488 CloseHandle(m_hCompPort
);
489 m_hCompPort
= INVALID_HANDLE_VALUE
;
493 CDirectoryWatcher::CDirWatchInfo::CDirWatchInfo(HANDLE hDir
, const CTGitPath
& DirectoryName
) :
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()
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
);