1 // TortoiseSVN - 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.
21 #include "PathWatcher.h"
23 CPathWatcher::CPathWatcher(void) : m_hCompPort(NULL
)
26 // enable the required privileges for this process
28 LPCTSTR arPrivelegeNames
[] = { SE_BACKUP_NAME
,
33 for (int i
=0; i
<(sizeof(arPrivelegeNames
)/sizeof(LPCTSTR
)); ++i
)
36 if (OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES
, &hToken
))
38 TOKEN_PRIVILEGES tp
= { 1 };
40 if (LookupPrivilegeValue(NULL
, arPrivelegeNames
[i
], &tp
.Privileges
[0].Luid
))
42 tp
.Privileges
[0].Attributes
= SE_PRIVILEGE_ENABLED
;
44 AdjustTokenPrivileges(hToken
, FALSE
, &tp
, sizeof(tp
), NULL
, NULL
);
50 unsigned int threadId
;
51 m_hThread
= (HANDLE
)_beginthreadex(NULL
,0,ThreadEntry
,this,0,&threadId
);
54 CPathWatcher::~CPathWatcher(void)
56 InterlockedExchange(&m_bRunning
, FALSE
);
57 if (m_hThread
!= INVALID_HANDLE_VALUE
)
59 CloseHandle(m_hThread
);
60 m_hThread
= INVALID_HANDLE_VALUE
;
62 AutoLocker
lock(m_critSec
);
66 void CPathWatcher::Stop()
68 InterlockedExchange(&m_bRunning
, FALSE
);
69 if (m_hCompPort
!= INVALID_HANDLE_VALUE
)
71 PostQueuedCompletionStatus(m_hCompPort
, 0, NULL
, NULL
);
73 if (m_hThread
!= INVALID_HANDLE_VALUE
)
74 CloseHandle(m_hThread
);
76 m_hThread
= INVALID_HANDLE_VALUE
;
77 m_hCompPort
= INVALID_HANDLE_VALUE
;
80 bool CPathWatcher::RemovePathAndChildren(const CTGitPath
& path
)
82 bool bRemoved
= false;
83 AutoLocker
lock(m_critSec
);
85 for (int i
=0; i
<watchedPaths
.GetCount(); ++i
)
87 if (path
.IsAncestorOf(watchedPaths
[i
]))
89 watchedPaths
.RemovePath(watchedPaths
[i
]);
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
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());
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
));
134 if (sPath
.GetLength() == minlen
)
136 if (watched
.GetLength() > minlen
)
138 if (watched
.GetAt(len
)=='\\')
142 else if (sPath
.GetLength() == 3 && sPath
[1] == ':')
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 ATLTRACE(_T("add path to watch %s\n"), newroot
.GetWinPath());
167 watchedPaths
.AddPath(newroot
);
168 watchedPaths
.RemoveChildren();
169 m_hCompPort
= INVALID_HANDLE_VALUE
;
172 ATLTRACE(_T("add path to watch %s\n"), path
.GetWinPath());
173 watchedPaths
.AddPath(path
);
174 m_hCompPort
= INVALID_HANDLE_VALUE
;
179 unsigned int CPathWatcher::ThreadEntry(void* pContext
)
181 ((CPathWatcher
*)pContext
)->WorkerThread();
185 void CPathWatcher::WorkerThread()
188 CDirWatchInfo
* pdi
= NULL
;
189 LPOVERLAPPED lpOverlapped
;
190 WCHAR buf
[MAX_PATH
*4] = {0};
193 if (watchedPaths
.GetCount())
195 if (!GetQueuedCompletionStatus(m_hCompPort
,
201 // Error retrieving changes
202 // Clear the list of watched objects and recreate that list
206 AutoLocker
lock(m_critSec
);
209 DWORD lasterr
= GetLastError();
210 if ((m_hCompPort
!= INVALID_HANDLE_VALUE
)&&(lasterr
!=ERROR_SUCCESS
)&&(lasterr
!=ERROR_INVALID_HANDLE
))
212 CloseHandle(m_hCompPort
);
213 m_hCompPort
= INVALID_HANDLE_VALUE
;
215 // Since we pass m_hCompPort to CreateIoCompletionPort, we
216 // have to set this to NULL to have that API create a new
219 for (int i
=0; i
<watchedPaths
.GetCount(); ++i
)
221 HANDLE hDir
= CreateFile(watchedPaths
[i
].GetWinPath(),
223 FILE_SHARE_READ
| FILE_SHARE_WRITE
| FILE_SHARE_DELETE
,
224 NULL
, //security attributes
226 FILE_FLAG_BACKUP_SEMANTICS
| //required privileges: SE_BACKUP_NAME and SE_RESTORE_NAME.
227 FILE_FLAG_OVERLAPPED
,
229 if (hDir
== INVALID_HANDLE_VALUE
)
231 // this could happen if a watched folder has been removed/renamed
232 CloseHandle(m_hCompPort
);
233 m_hCompPort
= INVALID_HANDLE_VALUE
;
234 AutoLocker
lock(m_critSec
);
235 watchedPaths
.RemovePath(watchedPaths
[i
]);
240 CDirWatchInfo
* pDirInfo
= new CDirWatchInfo(hDir
, watchedPaths
[i
]);
241 m_hCompPort
= CreateIoCompletionPort(hDir
, m_hCompPort
, (ULONG_PTR
)pDirInfo
, 0);
242 if (m_hCompPort
== NULL
)
244 AutoLocker
lock(m_critSec
);
248 watchedPaths
.RemovePath(watchedPaths
[i
]);
252 if (!ReadDirectoryChangesW(pDirInfo
->m_hDir
,
254 READ_DIR_CHANGE_BUFFER_SIZE
,
256 FILE_NOTIFY_CHANGE_FILE_NAME
| FILE_NOTIFY_CHANGE_DIR_NAME
| FILE_NOTIFY_CHANGE_LAST_WRITE
,
257 &numBytes
,// not used
258 &pDirInfo
->m_Overlapped
,
259 NULL
)) //no completion routine!
261 AutoLocker
lock(m_critSec
);
265 watchedPaths
.RemovePath(watchedPaths
[i
]);
269 AutoLocker
lock(m_critSec
);
270 watchInfoMap
[pDirInfo
->m_hDir
] = pDirInfo
;
271 ATLTRACE(_T("watching path %s\n"), pDirInfo
->m_DirName
.GetWinPath());
278 // NOTE: the longer this code takes to execute until ReadDirectoryChangesW
279 // is called again, the higher the chance that we miss some
280 // changes in the file system!
285 goto continuewatching
;
287 PFILE_NOTIFY_INFORMATION pnotify
= (PFILE_NOTIFY_INFORMATION
)pdi
->m_Buffer
;
288 if ((ULONG_PTR
)pnotify
- (ULONG_PTR
)pdi
->m_Buffer
> READ_DIR_CHANGE_BUFFER_SIZE
)
289 goto continuewatching
;
290 DWORD nOffset
= pnotify
->NextEntryOffset
;
293 nOffset
= pnotify
->NextEntryOffset
;
294 SecureZeroMemory(buf
, MAX_PATH
*4*sizeof(TCHAR
));
295 _tcsncpy_s(buf
, MAX_PATH
*4, pdi
->m_DirPath
, MAX_PATH
*4);
296 errno_t err
= _tcsncat_s(buf
+pdi
->m_DirPath
.GetLength(), (MAX_PATH
*4)-pdi
->m_DirPath
.GetLength(), pnotify
->FileName
, _TRUNCATE
);
297 if (err
== STRUNCATE
)
299 pnotify
= (PFILE_NOTIFY_INFORMATION
)((LPBYTE
)pnotify
+ nOffset
);
302 buf
[min(MAX_PATH
*4-1, pdi
->m_DirPath
.GetLength()+(pnotify
->FileNameLength
/sizeof(WCHAR
)))] = 0;
303 pnotify
= (PFILE_NOTIFY_INFORMATION
)((LPBYTE
)pnotify
+ nOffset
);
304 ATLTRACE(_T("change notification: %s\n"), buf
);
305 m_changedPaths
.AddPath(CTGitPath(buf
));
306 if ((ULONG_PTR
)pnotify
- (ULONG_PTR
)pdi
->m_Buffer
> READ_DIR_CHANGE_BUFFER_SIZE
)
310 SecureZeroMemory(pdi
->m_Buffer
, sizeof(pdi
->m_Buffer
));
311 SecureZeroMemory(&pdi
->m_Overlapped
, sizeof(OVERLAPPED
));
312 if (!ReadDirectoryChangesW(pdi
->m_hDir
,
314 READ_DIR_CHANGE_BUFFER_SIZE
,
316 FILE_NOTIFY_CHANGE_FILE_NAME
| FILE_NOTIFY_CHANGE_DIR_NAME
| FILE_NOTIFY_CHANGE_LAST_WRITE
,
317 &numBytes
,// not used
319 NULL
)) //no completion routine!
321 // Since the call to ReadDirectoryChangesW failed, just
322 // wait a while. We don't want to have this thread
323 // running using 100% CPU if something goes completely
329 }// if (watchedPaths.GetCount())
332 }// while (m_bRunning)
335 void CPathWatcher::ClearInfoMap()
337 if (watchInfoMap
.size()!=0)
339 AutoLocker
lock(m_critSec
);
340 for (std::map
<HANDLE
, CDirWatchInfo
*>::iterator I
= watchInfoMap
.begin(); I
!= watchInfoMap
.end(); ++I
)
342 CPathWatcher::CDirWatchInfo
* info
= I
->second
;
347 watchInfoMap
.clear();
348 if (m_hCompPort
!= INVALID_HANDLE_VALUE
)
349 CloseHandle(m_hCompPort
);
350 m_hCompPort
= INVALID_HANDLE_VALUE
;
353 CPathWatcher::CDirWatchInfo::CDirWatchInfo(HANDLE hDir
, const CTGitPath
& DirectoryName
) :
355 m_DirName(DirectoryName
)
357 ATLASSERT( hDir
!= INVALID_HANDLE_VALUE
358 && !DirectoryName
.IsEmpty());
359 memset(&m_Overlapped
, 0, sizeof(m_Overlapped
));
360 m_DirPath
= m_DirName
.GetWinPathString();
361 if (m_DirPath
.GetAt(m_DirPath
.GetLength()-1) != '\\')
362 m_DirPath
+= _T("\\");
365 CPathWatcher::CDirWatchInfo::~CDirWatchInfo()
367 CloseDirectoryHandle();
370 bool CPathWatcher::CDirWatchInfo::CloseDirectoryHandle()
373 if( m_hDir
!= INVALID_HANDLE_VALUE
)
375 b
= !!CloseHandle(m_hDir
);
376 m_hDir
= INVALID_HANDLE_VALUE
;