1 // TortoiseGit - a Windows shell extension for easy version control
3 // Copyright (C) 2013 - TortoiseGit
4 // External Cache Copyright (C) 2007-2012 - TortoiseSVN
6 // This program is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU General Public License
8 // as published by the Free Software Foundation; either version 2
9 // of the License, or (at your option) any later version.
11 // This program is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 // GNU General Public License for more details.
16 // You should have received a copy of the GNU General Public License
17 // along with this program; if not, write to the Free Software Foundation,
18 // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
22 #include "PathWatcher.h"
24 CPathWatcher::CPathWatcher(void) : m_hCompPort(NULL
)
26 , m_bLimitReached(false)
28 // enable the required privileges for this process
29 LPCTSTR arPrivelegeNames
[] = { SE_BACKUP_NAME
,
34 for (int i
=0; i
<(sizeof(arPrivelegeNames
)/sizeof(LPCTSTR
)); ++i
)
36 CAutoGeneralHandle hToken
;
37 if (OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES
, hToken
.GetPointer()))
39 TOKEN_PRIVILEGES tp
= { 1 };
41 if (LookupPrivilegeValue(NULL
, arPrivelegeNames
[i
], &tp
.Privileges
[0].Luid
))
43 tp
.Privileges
[0].Attributes
= SE_PRIVILEGE_ENABLED
;
45 AdjustTokenPrivileges(hToken
, FALSE
, &tp
, sizeof(tp
), NULL
, NULL
);
50 unsigned int threadId
= 0;
51 m_hThread
= (HANDLE
)_beginthreadex(NULL
,0,ThreadEntry
,this,0,&threadId
);
54 CPathWatcher::~CPathWatcher(void)
57 AutoLocker
lock(m_critSec
);
61 void CPathWatcher::Stop()
63 InterlockedExchange(&m_bRunning
, FALSE
);
66 PostQueuedCompletionStatus(m_hCompPort
, 0, NULL
, NULL
);
67 m_hCompPort
.CloseHandle();
72 // the background thread sleeps for 200ms,
73 // so lets wait for it to finish for 1000 ms.
75 WaitForSingleObject(m_hThread
, 1000);
76 m_hThread
.CloseHandle();
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 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": add path to watch %s\n"), newroot
.GetWinPath());
167 watchedPaths
.AddPath(newroot
);
168 watchedPaths
.RemoveChildren();
169 m_hCompPort
.CloseHandle();
172 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": add path to watch %s\n"), path
.GetWinPath());
173 watchedPaths
.AddPath(path
);
174 m_hCompPort
.CloseHandle();
179 unsigned int CPathWatcher::ThreadEntry(void* pContext
)
181 ((CPathWatcher
*)pContext
)->WorkerThread();
185 void CPathWatcher::WorkerThread()
188 CDirWatchInfo
* pdi
= NULL
;
189 LPOVERLAPPED lpOverlapped
;
190 const int bufferSize
= MAX_PATH
* 4;
191 TCHAR buf
[bufferSize
] = {0};
194 if (!watchedPaths
.IsEmpty())
196 if (!m_hCompPort
|| !GetQueuedCompletionStatus(m_hCompPort
,
202 // Error retrieving changes
203 // Clear the list of watched objects and recreate that list
207 AutoLocker
lock(m_critSec
);
210 DWORD lasterr
= GetLastError();
211 if ((m_hCompPort
)&&(lasterr
!=ERROR_SUCCESS
)&&(lasterr
!=ERROR_INVALID_HANDLE
))
213 m_hCompPort
.CloseHandle();
215 for (int i
=0; i
<watchedPaths
.GetCount(); ++i
)
217 CAutoFile hDir
= CreateFile(watchedPaths
[i
].GetWinPath(),
219 FILE_SHARE_READ
| FILE_SHARE_WRITE
| FILE_SHARE_DELETE
,
220 NULL
, //security attributes
222 FILE_FLAG_BACKUP_SEMANTICS
| //required privileges: SE_BACKUP_NAME and SE_RESTORE_NAME.
223 FILE_FLAG_OVERLAPPED
,
227 // this could happen if a watched folder has been removed/renamed
228 m_hCompPort
.CloseHandle();
229 AutoLocker
lock(m_critSec
);
230 watchedPaths
.RemovePath(watchedPaths
[i
]);
235 CDirWatchInfo
* pDirInfo
= new CDirWatchInfo(hDir
, watchedPaths
[i
]);
236 hDir
.Detach(); // the new CDirWatchInfo object owns the handle now
237 m_hCompPort
= CreateIoCompletionPort(pDirInfo
->m_hDir
, m_hCompPort
, (ULONG_PTR
)pDirInfo
, 0);
238 if (m_hCompPort
== NULL
)
240 AutoLocker
lock(m_critSec
);
244 watchedPaths
.RemovePath(watchedPaths
[i
]);
248 if (!ReadDirectoryChangesW(pDirInfo
->m_hDir
,
252 FILE_NOTIFY_CHANGE_FILE_NAME
| FILE_NOTIFY_CHANGE_DIR_NAME
| FILE_NOTIFY_CHANGE_LAST_WRITE
,
253 &numBytes
,// not used
254 &pDirInfo
->m_Overlapped
,
255 NULL
)) //no completion routine!
257 AutoLocker
lock(m_critSec
);
261 watchedPaths
.RemovePath(watchedPaths
[i
]);
265 AutoLocker
lock(m_critSec
);
266 watchInfoMap
[pDirInfo
->m_hDir
] = pDirInfo
;
267 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": watching path %s\n"), pDirInfo
->m_DirName
.GetWinPath());
274 // NOTE: the longer this code takes to execute until ReadDirectoryChangesW
275 // is called again, the higher the chance that we miss some
276 // changes in the file system!
281 goto continuewatching
;
283 PFILE_NOTIFY_INFORMATION pnotify
= (PFILE_NOTIFY_INFORMATION
)pdi
->m_Buffer
;
284 if ((ULONG_PTR
)pnotify
- (ULONG_PTR
)pdi
->m_Buffer
> bufferSize
)
285 goto continuewatching
;
286 DWORD nOffset
= pnotify
->NextEntryOffset
;
289 nOffset
= pnotify
->NextEntryOffset
;
290 SecureZeroMemory(buf
, bufferSize
*sizeof(TCHAR
));
291 _tcsncpy_s(buf
, bufferSize
, pdi
->m_DirPath
, bufferSize
);
292 errno_t err
= _tcsncat_s(buf
+pdi
->m_DirPath
.GetLength(), bufferSize
-pdi
->m_DirPath
.GetLength(), pnotify
->FileName
, min(bufferSize
-pdi
->m_DirPath
.GetLength(), pnotify
->FileNameLength
/sizeof(TCHAR
)));
293 if (err
== STRUNCATE
)
295 pnotify
= (PFILE_NOTIFY_INFORMATION
)((LPBYTE
)pnotify
+ nOffset
);
298 buf
[min(bufferSize
-1, pdi
->m_DirPath
.GetLength()+(pnotify
->FileNameLength
/sizeof(WCHAR
)))] = 0;
299 pnotify
= (PFILE_NOTIFY_INFORMATION
)((LPBYTE
)pnotify
+ nOffset
);
300 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": change notification: %s\n"), buf
);
302 AutoLocker
lock(m_critSec
);
303 if (m_changedPaths
.GetCount() < MAX_CHANGED_PATHS
)
304 m_changedPaths
.AddPath(CTGitPath(buf
));
306 m_bLimitReached
= true;
308 if ((ULONG_PTR
)pnotify
- (ULONG_PTR
)pdi
->m_Buffer
> bufferSize
)
313 AutoLocker
lock(m_critSec
);
314 m_changedPaths
.RemoveDuplicates();
316 SecureZeroMemory(pdi
->m_Buffer
, sizeof(pdi
->m_Buffer
));
317 SecureZeroMemory(&pdi
->m_Overlapped
, sizeof(OVERLAPPED
));
318 if (!ReadDirectoryChangesW(pdi
->m_hDir
,
322 FILE_NOTIFY_CHANGE_FILE_NAME
| FILE_NOTIFY_CHANGE_DIR_NAME
| FILE_NOTIFY_CHANGE_LAST_WRITE
,
323 &numBytes
,// not used
325 NULL
)) //no completion routine!
327 // Since the call to ReadDirectoryChangesW failed, just
328 // wait a while. We don't want to have this thread
329 // running using 100% CPU if something goes completely
335 }// if (!watchedPaths.IsEmpty())
338 }// while (m_bRunning)
341 void CPathWatcher::ClearInfoMap()
343 if (!watchInfoMap
.empty())
345 AutoLocker
lock(m_critSec
);
346 for (std::map
<HANDLE
, CDirWatchInfo
*>::iterator I
= watchInfoMap
.begin(); I
!= watchInfoMap
.end(); ++I
)
348 CPathWatcher::CDirWatchInfo
* info
= I
->second
;
353 watchInfoMap
.clear();
354 m_hCompPort
.CloseHandle();
357 CPathWatcher::CDirWatchInfo::CDirWatchInfo(HANDLE hDir
, const CTGitPath
& DirectoryName
)
359 , m_DirName(DirectoryName
)
361 ATLASSERT( hDir
&& !DirectoryName
.IsEmpty());
363 memset(&m_Overlapped
, 0, sizeof(m_Overlapped
));
364 m_DirPath
= m_DirName
.GetWinPathString();
365 if (m_DirPath
.GetAt(m_DirPath
.GetLength()-1) != '\\')
366 m_DirPath
+= _T("\\");
369 CPathWatcher::CDirWatchInfo::~CDirWatchInfo()
371 CloseDirectoryHandle();
374 bool CPathWatcher::CDirWatchInfo::CloseDirectoryHandle()
376 return m_hDir
.CloseHandle();