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.
21 #include "PathWatcher.h"
23 CPathWatcher::CPathWatcher(void) : m_hCompPort(NULL
)
26 // enable the required privileges for this process
27 LPCTSTR arPrivelegeNames
[] = { SE_BACKUP_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
);
60 void CPathWatcher::Stop()
62 InterlockedExchange(&m_bRunning
, FALSE
);
65 PostQueuedCompletionStatus(m_hCompPort
, 0, NULL
, NULL
);
66 m_hCompPort
.CloseHandle();
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
);
84 for (int i
=0; i
<watchedPaths
.GetCount(); ++i
)
86 if (path
.IsAncestorOf(watchedPaths
[i
]))
88 watchedPaths
.RemovePath(watchedPaths
[i
]);
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
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());
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
));
133 if (sPath
.GetLength() == minlen
)
135 if (watched
.GetLength() > minlen
)
137 if (watched
.GetAt(len
)=='\\')
141 else if (sPath
.GetLength() == 3 && sPath
[1] == ':')
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();
171 ATLTRACE(_T("add path to watch %s\n"), path
.GetWinPath());
172 watchedPaths
.AddPath(path
);
173 m_hCompPort
.CloseHandle();
178 unsigned int CPathWatcher::ThreadEntry(void* pContext
)
180 ((CPathWatcher
*)pContext
)->WorkerThread();
184 void CPathWatcher::WorkerThread()
187 CDirWatchInfo
* pdi
= NULL
;
188 LPOVERLAPPED lpOverlapped
;
189 WCHAR buf
[MAX_PATH
*4] = {0};
192 if (watchedPaths
.GetCount())
194 if (!m_hCompPort
|| !GetQueuedCompletionStatus(m_hCompPort
,
200 // Error retrieving changes
201 // Clear the list of watched objects and recreate that list
205 AutoLocker
lock(m_critSec
);
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
217 for (int i
=0; i
<watchedPaths
.GetCount(); ++i
)
219 CAutoFile hDir
= CreateFile(watchedPaths
[i
].GetWinPath(),
221 FILE_SHARE_READ
| FILE_SHARE_WRITE
| FILE_SHARE_DELETE
,
222 NULL
, //security attributes
224 FILE_FLAG_BACKUP_SEMANTICS
| //required privileges: SE_BACKUP_NAME and SE_RESTORE_NAME.
225 FILE_FLAG_OVERLAPPED
,
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
]);
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
);
246 watchedPaths
.RemovePath(watchedPaths
[i
]);
250 if (!ReadDirectoryChangesW(pDirInfo
->m_hDir
,
252 READ_DIR_CHANGE_BUFFER_SIZE
,
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
);
263 watchedPaths
.RemovePath(watchedPaths
[i
]);
267 AutoLocker
lock(m_critSec
);
268 watchInfoMap
[pDirInfo
->m_hDir
] = pDirInfo
;
269 ATLTRACE(_T("watching path %s\n"), pDirInfo
->m_DirName
.GetWinPath());
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!
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
);
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
)
308 SecureZeroMemory(pdi
->m_Buffer
, sizeof(pdi
->m_Buffer
));
309 SecureZeroMemory(&pdi
->m_Overlapped
, sizeof(OVERLAPPED
));
310 if (!ReadDirectoryChangesW(pdi
->m_hDir
,
312 READ_DIR_CHANGE_BUFFER_SIZE
,
314 FILE_NOTIFY_CHANGE_FILE_NAME
| FILE_NOTIFY_CHANGE_DIR_NAME
| FILE_NOTIFY_CHANGE_LAST_WRITE
,
315 &numBytes
,// not used
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
327 }// if (watchedPaths.GetCount())
330 }// while (m_bRunning)
333 void CPathWatcher::ClearInfoMap()
335 if (!watchInfoMap
.empty())
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
;
345 watchInfoMap
.clear();
346 m_hCompPort
.CloseHandle();
349 CPathWatcher::CDirWatchInfo::CDirWatchInfo(HANDLE hDir
, const CTGitPath
& DirectoryName
) :
351 m_DirName(DirectoryName
)
353 ATLASSERT( hDir
&& !DirectoryName
.IsEmpty());
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();