11 #include "afsd_init.h"
12 #include "lanahelper.h"
16 #include <WINNT\afsreg.h>
28 //#define REGISTER_POWER_NOTIFICATIONS 1
29 #include "afsd_flushvol.h"
31 extern void afsi_log(char *pattern, ...);
33 static SERVICE_STATUS ServiceStatus;
34 static SERVICE_STATUS_HANDLE StatusHandle;
36 HANDLE hAFSDMainThread = NULL;
38 HANDLE hAFSDWorkerThread[WORKER_THREADS];
41 HANDLE WaitToTerminate;
43 static int GlobalStatus;
46 unsigned int MainThreadId;
50 extern int traceOnPanic;
51 extern HANDLE afsi_file;
53 static int powerEventsRegistered = 0;
54 extern int powerStateSuspended = 0;
57 * Notifier function for use by osi_panic
59 static void afsd_notifier(char *msgp, char *filep, long line)
66 LogEvent(EVENTLOG_ERROR_TYPE, MSG_SERVICE_ERROR_STOP_WITH_MSG_AND_LOCATION,
69 LogEvent(EVENTLOG_ERROR_TYPE, MSG_SERVICE_ERROR_STOP_WITH_MSG, msgp);
73 osi_LogEnable(afsd_logp);
75 afsd_ForceTrace(TRUE);
78 afsi_log("--- begin dump ---");
79 cm_DumpCells(afsi_file, "a", 0);
80 cm_DumpVolumes(afsi_file, "a", 0);
81 cm_DumpSCache(afsi_file, "a", 0);
83 cm_dnlcDump(afsi_file, "a");
85 cm_DumpBufHashTable(afsi_file, "a", 0);
86 smb_DumpVCP(afsi_file, "a", 0);
87 afsi_log("--- end dump ---");
90 if (IsDebuggerPresent())
94 SetEvent(WaitToTerminate);
96 WaitForMultipleObjects(WORKER_THREADS, hAFSDWorkerThread, TRUE, INFINITE);
97 for (i = 0; i < WORKER_THREADS; i++)
98 CloseHandle(hAFSDWorkerThread[i]);
102 if (GetCurrentThreadId() == MainThreadId)
103 longjmp(notifier_jmp, 1);
106 ServiceStatus.dwCurrentState = SERVICE_STOPPED;
107 ServiceStatus.dwWin32ExitCode = NO_ERROR;
108 ServiceStatus.dwCheckPoint = 0;
109 ServiceStatus.dwWaitHint = 0;
110 ServiceStatus.dwControlsAccepted = 0;
111 SetServiceStatus(StatusHandle, &ServiceStatus);
117 * For use miscellaneously in smb.c; need to do better
119 static int _stdcall DummyMessageBox(HWND h, LPCTSTR l1, LPCTSTR l2, UINT ui)
125 afsd_ServiceFlushVolume(DWORD dwlpEventData)
127 DWORD dwRet = ERROR_NETWORK_BUSY; /* or NO_ERROR */
130 ** If UI bit is not set, user interaction is not possible
131 ** BUT, since we are a NON-interactive service, and therefore
132 ** have NO user I/O, it doesn't much matter.
133 ** This benign code left here as example of how to find this out
135 BOOL bUI = (dwlpEventData & 1);
138 if ( PowerNotificationThreadNotify() )
144 /* flush was unsuccessful, or timeout - deny shutdown */
145 dwRet = ERROR_NETWORK_BUSY;
148 /* to deny hibernate, simply return
149 // any value besides NO_ERROR.
151 // dwRet = ERROR_NETWORK_BUSY;
158 /* service control handler used in nt4 only for backward compat. */
160 afsd_ServiceControlHandler(DWORD ctrlCode)
163 DWORD dummyLen, doTrace;
167 case SERVICE_CONTROL_SHUTDOWN:
168 case SERVICE_CONTROL_STOP:
169 ServiceStatus.dwCurrentState = SERVICE_STOP_PENDING;
170 ServiceStatus.dwWin32ExitCode = NO_ERROR;
171 ServiceStatus.dwCheckPoint = 1;
172 ServiceStatus.dwWaitHint = 30000;
173 ServiceStatus.dwControlsAccepted = 0;
174 SetServiceStatus(StatusHandle, &ServiceStatus);
176 if (ctrlCode == SERVICE_CONTROL_STOP)
177 afsi_log("SERVICE_CONTROL_STOP");
179 afsi_log("SERVICE_CONTROL_SHUTDOWN");
181 /* Write all dirty buffers back to server */
182 if ( !lana_OnlyLoopback() )
185 /* Force trace if requested */
186 code = RegOpenKeyEx(HKEY_LOCAL_MACHINE,
187 AFSREG_CLT_SVC_PARAM_SUBKEY,
188 0, KEY_QUERY_VALUE, &parmKey);
189 if (code != ERROR_SUCCESS)
192 dummyLen = sizeof(doTrace);
193 code = RegQueryValueEx(parmKey, "TraceOnShutdown",
195 (BYTE *) &doTrace, &dummyLen);
196 RegCloseKey (parmKey);
197 if (code != ERROR_SUCCESS)
200 afsd_ForceTrace(FALSE);
201 buf_ForceTrace(FALSE);
205 SetEvent(WaitToTerminate);
208 case SERVICE_CONTROL_INTERROGATE:
209 ServiceStatus.dwCurrentState = SERVICE_RUNNING;
210 ServiceStatus.dwWin32ExitCode = NO_ERROR;
211 ServiceStatus.dwCheckPoint = 0;
212 ServiceStatus.dwWaitHint = 0;
213 ServiceStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;
214 SetServiceStatus(StatusHandle, &ServiceStatus);
216 /* XXX handle system shutdown */
217 /* XXX handle pause & continue */
223 ** Extended ServiceControlHandler that provides Event types
224 ** for monitoring Power events, for example.
227 afsd_ServiceControlHandlerEx(
235 DWORD dummyLen, doTrace;
237 DWORD dwRet = ERROR_CALL_NOT_IMPLEMENTED;
238 OSVERSIONINFO osVersion;
240 /* Get the version of Windows */
241 memset(&osVersion, 0x00, sizeof(osVersion));
242 osVersion.dwOSVersionInfoSize = sizeof(osVersion);
243 GetVersionEx(&osVersion);
247 case SERVICE_CONTROL_SHUTDOWN:
248 case SERVICE_CONTROL_STOP:
249 ServiceStatus.dwCurrentState = SERVICE_STOP_PENDING;
250 ServiceStatus.dwWin32ExitCode = NO_ERROR;
251 ServiceStatus.dwCheckPoint = 1;
252 ServiceStatus.dwWaitHint = 30000;
253 ServiceStatus.dwControlsAccepted = 0;
254 SetServiceStatus(StatusHandle, &ServiceStatus);
256 /* Write all dirty buffers back to server */
257 if ( !lana_OnlyLoopback() )
260 /* Force trace if requested */
261 code = RegOpenKeyEx(HKEY_LOCAL_MACHINE,
262 AFSREG_CLT_SVC_PARAM_SUBKEY,
263 0, KEY_QUERY_VALUE, &parmKey);
264 if (code != ERROR_SUCCESS)
267 dummyLen = sizeof(doTrace);
268 code = RegQueryValueEx(parmKey, "TraceOnShutdown",
270 (BYTE *) &doTrace, &dummyLen);
271 RegCloseKey (parmKey);
272 if (code != ERROR_SUCCESS)
275 afsd_ForceTrace(FALSE);
276 buf_ForceTrace(FALSE);
280 SetEvent(WaitToTerminate);
284 case SERVICE_CONTROL_INTERROGATE:
285 ServiceStatus.dwCurrentState = SERVICE_RUNNING;
286 ServiceStatus.dwWin32ExitCode = NO_ERROR;
287 ServiceStatus.dwCheckPoint = 0;
288 ServiceStatus.dwWaitHint = 0;
289 ServiceStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN | SERVICE_ACCEPT_POWEREVENT;
290 SetServiceStatus(StatusHandle, &ServiceStatus);
291 afsi_log("SERVICE_CONTROL_INTERROGATE");
295 /* XXX handle system shutdown */
296 /* XXX handle pause & continue */
297 case SERVICE_CONTROL_POWEREVENT:
300 afsi_log("SERVICE_CONTROL_POWEREVENT");
303 ** dwEventType of this notification == WPARAM of WM_POWERBROADCAST
304 ** Return NO_ERROR == return TRUE for that message, i.e. accept request
305 ** Return any error code to deny request,
306 ** i.e. as if returning BROADCAST_QUERY_DENY
308 if (powerEventsRegistered) {
309 switch((int) dwEventType)
311 case PBT_APMQUERYSUSPEND:
312 afsi_log("SERVICE_CONTROL_APMQUERYSUSPEND");
313 /* Write all dirty buffers back to server */
314 if ( !lana_OnlyLoopback() ) {
318 afsi_log("SERVICE_CONTROL_APMQUERYSUSPEND buf_CleanAndReset complete");
321 case PBT_APMQUERYSTANDBY:
322 afsi_log("SERVICE_CONTROL_APMQUERYSTANDBY");
323 /* Write all dirty buffers back to server */
324 if ( !lana_OnlyLoopback() ) {
328 afsi_log("SERVICE_CONTROL_APMQUERYSTANDBY buf_CleanAndReset complete");
332 /* allow remaining case PBT_WhatEver */
334 afsi_log("SERVICE_CONTROL_APMSUSPEND");
335 powerStateSuspended = 1;
336 if (osVersion.dwMajorVersion >= 6) {
343 afsi_log("SERVICE_CONTROL_APMSTANDBY");
344 powerStateSuspended = 1;
345 if (osVersion.dwMajorVersion >= 6) {
351 case PBT_APMRESUMECRITICAL:
352 afsi_log("SERVICE_CONTROL_APMRESUMECRITICAL");
353 if (osVersion.dwMajorVersion >= 6)
354 smb_RestartListeners();
357 case PBT_APMRESUMESUSPEND:
358 /* User logged in after suspend */
359 afsi_log("SERVICE_CONTROL_APMRESUMESUSPEND");
362 case PBT_APMRESUMESTANDBY:
363 /* User logged in after standby */
364 afsi_log("SERVICE_CONTROL_APMRESUMESTANDBY");
367 case PBT_APMBATTERYLOW:
368 afsi_log("SERVICE_CONTROL_APMBATTERYLOW");
371 case PBT_APMPOWERSTATUSCHANGE:
373 afsi_log("SERVICE_CONTROL_APMPOWERSTATUSCHANGE");
377 case PBT_APMOEMEVENT:
379 afsi_log("SERVICE_CONTROL_APMOEMEVENT");
383 case PBT_APMRESUMEAUTOMATIC:
384 /* This is the message delivered once all devices are up */
385 afsi_log("SERVICE_CONTROL_APMRESUMEAUTOMATIC");
386 powerStateSuspended = 0;
387 if (osVersion.dwMajorVersion >= 6)
388 smb_RestartListeners();
392 afsi_log("SERVICE_CONTROL_unknown");
398 case SERVICE_CONTROL_CUSTOM_DUMP:
400 afsi_log("SERVICE_CONTROL_CUSTOM_DUMP");
401 GenerateMiniDump(NULL);
405 } /* end switch(ctrlCode) */
409 /* There is similar code in client_config\drivemap.cpp GlobalMountDrive()
411 * Mount a drive into AFS if there global mapping
413 /* DEE Could check first if we are run as SYSTEM */
414 #define MAX_RETRIES 10
415 #define MAX_DRIVES 23
416 static DWORD __stdcall MountGlobalDrivesThread(void * notUsed)
419 char szAfsPath[_MAX_PATH];
421 char szDriveToMapTo[5];
425 DWORD dwIndex = 0, dwRetry = 0;
427 DWORD dwSubMountSize;
428 char szSubMount[256];
431 sprintf(szKeyName, "%s\\GlobalAutoMapper", AFSREG_CLT_SVC_PARAM_SUBKEY);
433 dwResult = RegOpenKeyEx(HKEY_LOCAL_MACHINE, szKeyName, 0, KEY_QUERY_VALUE, &hKey);
434 if (dwResult != ERROR_SUCCESS)
437 while (dwIndex < MAX_DRIVES) {
438 dwDriveSize = sizeof(szDriveToMapTo);
439 dwSubMountSize = sizeof(szSubMount);
440 dwResult = RegEnumValue(hKey, dwIndex++, szDriveToMapTo, &dwDriveSize, 0, &dwType, szSubMount, &dwSubMountSize);
441 if (dwResult != ERROR_MORE_DATA) {
442 if (dwResult != ERROR_SUCCESS) {
443 if (dwResult != ERROR_NO_MORE_ITEMS)
444 afsi_log("Failed to read GlobalAutoMapper values: %d\n", dwResult);
450 for (dwRetry = 0 ; dwRetry < MAX_RETRIES; dwRetry++)
453 memset (&nr, 0x00, sizeof(NETRESOURCE));
455 sprintf(szAfsPath,"\\\\%s\\%s",cm_NetbiosName,szSubMount);
457 nr.dwScope = RESOURCE_GLOBALNET; /* ignored parameter */
458 nr.dwType=RESOURCETYPE_DISK;
459 nr.lpLocalName=szDriveToMapTo;
460 nr.lpRemoteName=szAfsPath;
461 nr.dwDisplayType = RESOURCEDISPLAYTYPE_SHARE; /* ignored parameter */
462 nr.dwUsage = RESOURCEUSAGE_CONNECTABLE; /* ignored parameter */
464 dwResult = WNetAddConnection2(&nr,NULL,NULL,0);
465 afsi_log("GlobalAutoMap of %s to %s %s (%d)", szDriveToMapTo, szSubMount,
466 (dwResult == NO_ERROR) ? "succeeded" : "failed", dwResult);
467 if (dwResult == NO_ERROR) {
470 /* wait for smb server to come up */
471 Sleep((DWORD)1000 /* miliseconds */);
473 /* Disconnect any previous mappings */
474 dwResult = WNetCancelConnection2(szDriveToMapTo, 0, TRUE);
477 /* FIXFIX: implement */
478 afsi_log("GlobalAutoMap of %s to %s not implemented", szDriveToMapTo, szSubMount);
486 static HANDLE hThreadMountGlobalDrives = NULL;
488 static void MountGlobalDrives()
492 hThreadMountGlobalDrives = CreateThread(NULL, 0, MountGlobalDrivesThread, 0, 0, &tid);
494 if ( hThreadMountGlobalDrives ) {
495 DWORD rc = WaitForSingleObject( hThreadMountGlobalDrives, 15000 );
496 if (rc == WAIT_TIMEOUT) {
497 afsi_log("GlobalAutoMap thread failed to complete after 15 seconds");
498 } else if (rc == WAIT_OBJECT_0) {
499 afsi_log("GlobalAutoMap thread completed");
500 CloseHandle( hThreadMountGlobalDrives );
501 hThreadMountGlobalDrives = NULL;
506 static void DismountGlobalDrives()
509 char szAfsPath[_MAX_PATH];
510 char szDriveToMapTo[5];
512 DWORD dwSubMountSize;
513 char szSubMount[256];
521 if ( hThreadMountGlobalDrives ) {
522 DWORD rc = WaitForSingleObject(hThreadMountGlobalDrives, 0);
524 if (rc == WAIT_TIMEOUT) {
525 afsi_log("GlobalAutoMap thread failed to complete before service shutdown");
527 else if (rc == WAIT_OBJECT_0) {
528 afsi_log("GlobalAutoMap thread completed");
529 CloseHandle( hThreadMountGlobalDrives );
530 hThreadMountGlobalDrives = NULL;
534 sprintf(szKeyName, "%s\\GlobalAutoMapper", AFSREG_CLT_SVC_PARAM_SUBKEY);
536 dwResult = RegOpenKeyEx(HKEY_LOCAL_MACHINE, szKeyName, 0, KEY_QUERY_VALUE, &hKey);
537 if (dwResult != ERROR_SUCCESS)
541 /* FIXFIX: implement */
543 while (dwIndex < MAX_DRIVES) {
544 dwDriveSize = sizeof(szDriveToMapTo);
545 dwSubMountSize = sizeof(szSubMount);
546 dwResult = RegEnumValue(hKey, dwIndex++, szDriveToMapTo, &dwDriveSize, 0, &dwType, szSubMount, &dwSubMountSize);
547 if (dwResult != ERROR_MORE_DATA) {
548 if (dwResult != ERROR_SUCCESS) {
549 if (dwResult != ERROR_NO_MORE_ITEMS)
550 afsi_log("Failed to read GlobalAutoMapper values: %d\n", dwResult);
555 sprintf(szAfsPath,"\\\\%s\\%s",cm_NetbiosName,szSubMount);
557 dwResult = WNetCancelConnection2(szDriveToMapTo, 0, TRUE);
558 dwResult = WNetCancelConnection(szAfsPath, TRUE);
560 afsi_log("Disconnect from GlobalAutoMap of %s to %s %s", szDriveToMapTo, szSubMount, dwResult ? "succeeded" : "failed");
568 GetVersionInfo( CHAR * filename, CHAR * szOutput, DWORD dwOutput )
570 DWORD dwVersionHandle;
571 LPVOID pVersionInfo = 0;
573 LPDWORD pLangInfo = 0;
574 LPTSTR szVersion = 0;
576 TCHAR szVerQ[] = TEXT("\\StringFileInfo\\12345678\\FileVersion");
577 DWORD size = GetFileVersionInfoSize(filename, &dwVersionHandle);
580 afsi_log("GetFileVersionInfoSize failed");
581 return GetLastError();
584 pVersionInfo = malloc(size);
586 afsi_log("out of memory 1");
587 return ERROR_NOT_ENOUGH_MEMORY;
590 GetFileVersionInfo(filename, dwVersionHandle, size, pVersionInfo);
591 if (retval = GetLastError())
593 afsi_log("GetFileVersionInfo failed: %d", retval);
597 VerQueryValue(pVersionInfo, TEXT("\\VarFileInfo\\Translation"),
598 (LPVOID*)&pLangInfo, &len);
599 if (retval = GetLastError())
601 afsi_log("VerQueryValue 1 failed: %d", retval);
606 TEXT("\\StringFileInfo\\%04x%04x\\FileVersion"),
607 LOWORD(*pLangInfo), HIWORD(*pLangInfo));
609 VerQueryValue(pVersionInfo, szVerQ, (LPVOID*)&szVersion, &len);
610 if (retval = GetLastError())
612 /* try again with language 409 since the old binaries were tagged wrong */
614 TEXT("\\StringFileInfo\\0409%04x\\FileVersion"),
617 VerQueryValue(pVersionInfo, szVerQ, (LPVOID*)&szVersion, &len);
618 if (retval = GetLastError()) {
619 afsi_log("VerQueryValue 2 failed: [%s] %d", szVerQ, retval);
623 snprintf(szOutput, dwOutput, TEXT("%s"), szVersion);
624 szOutput[dwOutput - 1] = 0;
633 static HINSTANCE hCrypt32;
634 static DWORD (WINAPI *pCertGetNameString)(PCCERT_CONTEXT pCertContext, DWORD dwType, DWORD dwFlags,
635 void* pvTypePara, LPTSTR pszNameString, DWORD cchNameString);
636 static BOOL (WINAPI *pCryptQueryObject)(DWORD dwObjectType, const void* pvObject, DWORD dwExpectedContentTypeFlags,
637 DWORD dwExpectedFormatTypeFlags, DWORD dwFlags,
638 DWORD* pdwMsgAndCertEncodingType, DWORD* pdwContentType,
639 DWORD* pdwFormatType, HCERTSTORE* phCertStore,
640 HCRYPTMSG* phMsg, const void** ppvContext);
641 static BOOL (WINAPI *pCryptMsgGetParam)(HCRYPTMSG hCryptMsg, DWORD dwParamType, DWORD dwIndex,
642 void* pvData, DWORD* pcbData);
643 static PCCERT_CONTEXT (WINAPI *pCertFindCertificateInStore)(HCERTSTORE hCertStore, DWORD dwCertEncodingType,
644 DWORD dwFindFlags, DWORD dwFindType,
645 const void* pvFindPara,
646 PCCERT_CONTEXT pPrevCertContext);
647 static BOOL (WINAPI *pCertCloseStore)(HCERTSTORE hCertStore, DWORD dwFlags);
648 static BOOL (WINAPI *pCryptMsgClose)(HCRYPTMSG hCryptMsg);
649 static BOOL (WINAPI *pCertCompareCertificate)(DWORD dwCertEncodingType, PCERT_INFO pCertId1,
650 PCERT_INFO pCertId2);
651 static BOOL (WINAPI *pCertFreeCertificateContext)(PCCERT_CONTEXT pCertContext);
653 void LoadCrypt32(void)
655 hCrypt32 = LoadLibrary("crypt32");
659 (FARPROC) pCertGetNameString = GetProcAddress( hCrypt32, "CertGetNameString" );
660 (FARPROC) pCryptQueryObject = GetProcAddress( hCrypt32, "CryptQueryObject" );
661 (FARPROC) pCryptMsgGetParam = GetProcAddress( hCrypt32, "CryptMsgGetParam" );
662 (FARPROC) pCertFindCertificateInStore = GetProcAddress( hCrypt32, "CertFindCertificateInStore" );
663 (FARPROC) pCertCloseStore = GetProcAddress( hCrypt32, "CertCloseStore" );
664 (FARPROC) pCryptMsgClose = GetProcAddress( hCrypt32, "CryptMsgClose" );
665 (FARPROC) pCertCompareCertificate = GetProcAddress( hCrypt32, "CertCompareCertificate" );
666 (FARPROC) pCertFreeCertificateContext = GetProcAddress( hCrypt32, "CertFreeCertificateContext" );
668 if ( !pCertGetNameString ||
669 !pCryptQueryObject ||
670 !pCryptMsgGetParam ||
671 !pCertFindCertificateInStore ||
674 !pCertCompareCertificate ||
675 !pCertFreeCertificateContext)
677 FreeLibrary(hCrypt32);
682 void UnloadCrypt32(void)
684 FreeLibrary(hCrypt32);
687 #define ENCODING (X509_ASN_ENCODING | PKCS_7_ASN_ENCODING)
689 PCCERT_CONTEXT GetCertCtx(CHAR * filename)
691 wchar_t wfilename[260];
697 HCERTSTORE hStore = NULL;
698 HCRYPTMSG hMsg = NULL;
699 PCMSG_SIGNER_INFO pSignerInfo = NULL;
700 PCCERT_CONTEXT pCertContext = NULL;
703 if ( hCrypt32 == NULL )
706 ZeroMemory(&CertInfo, sizeof(CertInfo));
707 mbstowcs(wfilename, filename, 260);
709 fResult = pCryptQueryObject(CERT_QUERY_OBJECT_FILE,
711 CERT_QUERY_CONTENT_FLAG_PKCS7_SIGNED_EMBED,
712 CERT_QUERY_FORMAT_FLAG_BINARY,
722 afsi_log("CryptQueryObject failed for [%s] with error 0x%x",
728 fResult = pCryptMsgGetParam(hMsg,
729 CMSG_SIGNER_INFO_PARAM,
735 afsi_log("CryptMsgGetParam failed for [%s] with error 0x%x",
741 pSignerInfo = (PCMSG_SIGNER_INFO)LocalAlloc(LPTR, dwSignerInfo);
743 fResult = pCryptMsgGetParam(hMsg,
744 CMSG_SIGNER_INFO_PARAM,
750 afsi_log("CryptMsgGetParam failed for [%s] with error 0x%x",
756 CertInfo.Issuer = pSignerInfo->Issuer;
757 CertInfo.SerialNumber = pSignerInfo->SerialNumber;
759 pCertContext = pCertFindCertificateInStore(hStore,
762 CERT_FIND_SUBJECT_CERT,
767 afsi_log("CertFindCertificateInStore for file [%s] failed with 0x%x",
775 LocalFree(pSignerInfo);
778 CertFreeCertificateContext(pCertContext);*/
781 pCertCloseStore(hStore,0);
784 pCryptMsgClose(hMsg);
789 BOOL VerifyTrust(CHAR * filename)
791 WIN_TRUST_ACTDATA_CONTEXT_WITH_SUBJECT fContextWSubject;
792 WIN_TRUST_SUBJECT_FILE fSubjectFile;
793 GUID trustAction = WIN_SPUB_ACTION_PUBLISHED_SOFTWARE;
794 GUID subject = WIN_TRUST_SUBJTYPE_PE_IMAGE;
795 wchar_t wfilename[260];
797 BOOL success = FALSE;
799 LONG (WINAPI *pWinVerifyTrust)(HWND hWnd, GUID* pgActionID, WINTRUST_DATA* pWinTrustData) = NULL;
802 if (filename == NULL )
805 hWinTrust = LoadLibrary("wintrust");
809 if (((FARPROC) pWinVerifyTrust =
810 GetProcAddress( hWinTrust, "WinVerifyTrust" )) == NULL )
812 FreeLibrary(hWinTrust);
816 mbstowcs(wfilename, filename, 260);
818 fSubjectFile.hFile = CreateFile(filename, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING,
820 fSubjectFile.lpPath = wfilename;
821 fContextWSubject.hClientToken = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ,
822 FALSE, GetCurrentProcessId());
823 fContextWSubject.SubjectType = &subject;
824 fContextWSubject.Subject = &fSubjectFile;
826 ret = pWinVerifyTrust(INVALID_HANDLE_VALUE, &trustAction, (WINTRUST_DATA *)&fContextWSubject);
828 if ( fSubjectFile.hFile != INVALID_HANDLE_VALUE )
829 CloseHandle( fSubjectFile.hFile );
830 if ( fContextWSubject.hClientToken != INVALID_HANDLE_VALUE )
831 CloseHandle( fContextWSubject.hClientToken );
833 if (ret == ERROR_SUCCESS) {
836 DWORD gle = GetLastError();
838 case TRUST_E_PROVIDER_UNKNOWN:
839 afsi_log("VerifyTrust failed: \"Generic Verify V2\" Provider Unknown");
841 case TRUST_E_NOSIGNATURE:
842 afsi_log("VerifyTrust failed: Unsigned executable");
844 case TRUST_E_EXPLICIT_DISTRUST:
845 afsi_log("VerifyTrust failed: Certificate Marked as Untrusted by the user");
847 case TRUST_E_SUBJECT_NOT_TRUSTED:
848 afsi_log("VerifyTrust failed: File is not trusted");
850 case TRUST_E_BAD_DIGEST:
851 afsi_log("VerifyTrust failed: Executable has been modified");
853 case CRYPT_E_SECURITY_SETTINGS:
854 afsi_log("VerifyTrust failed: local security options prevent verification");
857 afsi_log("VerifyTrust failed: 0x%X", GetLastError());
861 FreeLibrary(hWinTrust);
865 void LogCertCtx(PCCERT_CONTEXT pCtx) {
867 LPTSTR szName = NULL;
869 if ( hCrypt32 == NULL )
872 // Get Issuer name size.
873 if (!(dwData = pCertGetNameString(pCtx,
874 CERT_NAME_SIMPLE_DISPLAY_TYPE,
875 CERT_NAME_ISSUER_FLAG,
879 afsi_log("CertGetNameString failed: 0x%x", GetLastError());
883 // Allocate memory for Issuer name.
884 szName = (LPTSTR)LocalAlloc(LPTR, dwData * sizeof(TCHAR));
887 if (!(pCertGetNameString(pCtx,
888 CERT_NAME_SIMPLE_DISPLAY_TYPE,
889 CERT_NAME_ISSUER_FLAG,
893 afsi_log("CertGetNameString failed: 0x%x", GetLastError());
897 // print Issuer name.
898 afsi_log("Issuer Name: %s", szName);
902 // Get Subject name size.
903 if (!(dwData = pCertGetNameString(pCtx,
904 CERT_NAME_SIMPLE_DISPLAY_TYPE,
909 afsi_log("CertGetNameString failed: 0x%x", GetLastError());
913 // Allocate memory for subject name.
914 szName = (LPTSTR)LocalAlloc(LPTR, dwData * sizeof(TCHAR));
917 if (!(pCertGetNameString(pCtx,
918 CERT_NAME_SIMPLE_DISPLAY_TYPE,
923 afsi_log("CertGetNameString failed: 0x%x", GetLastError());
927 // Print Subject Name.
928 afsi_log("Subject Name: %s", szName);
936 BOOL AFSModulesVerify(void)
939 CHAR afsdVersion[128];
940 CHAR modVersion[128];
941 CHAR checkName[1024];
942 BOOL trustVerified = FALSE;
948 PCCERT_CONTEXT pCtxService = NULL;
950 DWORD (WINAPI *pGetModuleFileNameExA)(HANDLE hProcess, HMODULE hModule, LPTSTR lpFilename, DWORD nSize);
951 BOOL (WINAPI *pEnumProcessModules)(HANDLE hProcess, HMODULE* lphModule, DWORD cb, LPDWORD lpcbNeeded);
952 DWORD dummyLen, code;
953 DWORD cacheSize = CM_CONFIGDEFAULT_CACHESIZE;
954 DWORD verifyServiceSig = TRUE;
957 hPSAPI = LoadLibrary("psapi");
959 if ( hPSAPI == NULL )
962 if (!GetModuleFileName(NULL, filename, sizeof(filename)))
965 if (GetVersionInfo(filename, afsdVersion, sizeof(afsdVersion)))
968 afsi_log("%s version %s", filename, afsdVersion);
970 if (((FARPROC) pGetModuleFileNameExA =
971 GetProcAddress( hPSAPI, "GetModuleFileNameExA" )) == NULL ||
972 ((FARPROC) pEnumProcessModules =
973 GetProcAddress( hPSAPI, "EnumProcessModules" )) == NULL)
980 code = RegOpenKeyEx(HKEY_LOCAL_MACHINE,
981 AFSREG_CLT_SVC_PARAM_SUBKEY,
982 0, KEY_QUERY_VALUE, &parmKey);
983 if (code == ERROR_SUCCESS) {
984 dummyLen = sizeof(cacheSize);
985 code = RegQueryValueEx(parmKey, "CacheSize", NULL, NULL,
986 (BYTE *) &cacheSize, &dummyLen);
987 RegCloseKey (parmKey);
990 code = RegOpenKeyEx(HKEY_LOCAL_MACHINE, AFSREG_CLT_OPENAFS_SUBKEY,
991 0, KEY_QUERY_VALUE, &parmKey);
992 if (code == ERROR_SUCCESS) {
993 dummyLen = sizeof(verifyServiceSig);
994 code = RegQueryValueEx(parmKey, "VerifyServiceSignature", NULL, NULL,
995 (BYTE *) &verifyServiceSig, &dummyLen);
996 RegCloseKey (parmKey);
999 if (verifyServiceSig && cacheSize < 716800) {
1000 trustVerified = VerifyTrust(filename);
1002 afsi_log("Signature Verification disabled");
1005 if (trustVerified) {
1008 // get a certificate context for the signer of afsd_service.
1009 pCtxService = GetCertCtx(filename);
1011 LogCertCtx(pCtxService);
1014 // Get a list of all the modules in this process.
1015 hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ,
1016 FALSE, GetCurrentProcessId());
1018 if (pEnumProcessModules(hProcess, hMods, sizeof(hMods), &cbNeeded))
1020 afsi_log("Num of Process Modules: %d", (cbNeeded / sizeof(HMODULE)));
1022 for (i = 0; i < (cbNeeded / sizeof(HMODULE)); i++)
1024 char szModName[2048];
1026 // Get the full path to the module's file.
1027 if (pGetModuleFileNameExA(hProcess, hMods[i], szModName, sizeof(szModName)))
1029 lstrcpy(checkName, szModName);
1032 if ( strstr(checkName, "afspthread.dll") ||
1033 strstr(checkName, "afsauthent.dll") ||
1034 strstr(checkName, "afsrpc.dll") ||
1035 strstr(checkName, "libafsconf.dll") ||
1036 strstr(checkName, "libosi.dll") )
1038 if (GetVersionInfo(szModName, modVersion, sizeof(modVersion))) {
1043 afsi_log("%s version %s", szModName, modVersion);
1044 if (strcmp(afsdVersion,modVersion)) {
1045 afsi_log("Version mismatch: %s", szModName);
1048 if ( trustVerified ) {
1049 if ( !VerifyTrust(szModName) ) {
1050 afsi_log("Signature Verification failed: %s", szModName);
1053 else if (pCtxService) {
1054 PCCERT_CONTEXT pCtx = GetCertCtx(szModName);
1056 if (!pCtx || !pCertCompareCertificate(X509_ASN_ENCODING | PKCS_7_ASN_ENCODING,
1057 pCtxService->pCertInfo,
1059 afsi_log("Certificate mismatch: %s", szModName);
1067 pCertFreeCertificateContext(pCtx);
1076 pCertFreeCertificateContext(pCtxService);
1080 FreeLibrary(hPSAPI);
1082 CloseHandle(hProcess);
1087 control serviceex exists only on 2000/xp. These functions will be loaded dynamically.
1090 typedef SERVICE_STATUS_HANDLE ( * RegisterServiceCtrlHandlerExFunc )( LPCTSTR , LPHANDLER_FUNCTION_EX , LPVOID );
1091 typedef SERVICE_STATUS_HANDLE ( * RegisterServiceCtrlHandlerFunc )( LPCTSTR , LPHANDLER_FUNCTION );
1093 RegisterServiceCtrlHandlerExFunc pRegisterServiceCtrlHandlerEx = NULL;
1094 RegisterServiceCtrlHandlerFunc pRegisterServiceCtrlHandler = NULL;
1097 afsd_Main(DWORD argc, LPTSTR *argv)
1111 afsd_DbgBreakAllocInit();
1112 _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF /*| _CRTDBG_CHECK_ALWAYS_DF*/ |
1113 _CRTDBG_CHECK_CRT_DF /* | _CRTDBG_DELAY_FREE_MEM_DF */ );
1116 afsd_SetUnhandledExceptionFilter();
1118 osi_InitPanic(afsd_notifier);
1119 osi_InitTraceOption();
1125 WaitToTerminate = CreateEvent(NULL, TRUE, FALSE, TEXT("afsd_service_WaitToTerminate"));
1126 if ( GetLastError() == ERROR_ALREADY_EXISTS )
1127 afsi_log("Event Object Already Exists: %s", TEXT("afsd_service_WaitToTerminate"));
1130 hAdvApi32 = LoadLibrary("advapi32.dll");
1131 if (hAdvApi32 == NULL)
1133 afsi_log("Fatal: cannot load advapi32.dll");
1137 pRegisterServiceCtrlHandlerEx = (RegisterServiceCtrlHandlerExFunc)GetProcAddress(hAdvApi32, "RegisterServiceCtrlHandlerExA");
1138 if (pRegisterServiceCtrlHandlerEx)
1140 afsi_log("running on 2000+ - using RegisterServiceCtrlHandlerEx");
1141 StatusHandle = RegisterServiceCtrlHandlerEx(AFS_DAEMON_SERVICE_NAME, afsd_ServiceControlHandlerEx, NULL );
1145 StatusHandle = RegisterServiceCtrlHandler(AFS_DAEMON_SERVICE_NAME, afsd_ServiceControlHandler);
1148 ServiceStatus.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
1149 ServiceStatus.dwServiceSpecificExitCode = 0;
1150 ServiceStatus.dwCurrentState = SERVICE_START_PENDING;
1151 ServiceStatus.dwWin32ExitCode = NO_ERROR;
1152 ServiceStatus.dwCheckPoint = 1;
1153 ServiceStatus.dwWaitHint = 120000;
1154 /* accept Power Events */
1155 ServiceStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN | SERVICE_ACCEPT_POWEREVENT | SERVICE_ACCEPT_PARAMCHANGE;
1156 SetServiceStatus(StatusHandle, &ServiceStatus);
1159 LogEvent(EVENTLOG_INFORMATION_TYPE, MSG_SERVICE_START_PENDING);
1161 #ifdef REGISTER_POWER_NOTIFICATIONS
1168 /* see if we should handle power notifications */
1169 code = RegOpenKeyEx(HKEY_LOCAL_MACHINE, AFSREG_CLT_SVC_PARAM_SUBKEY,
1170 0, KEY_QUERY_VALUE, &hkParm);
1171 if (code == ERROR_SUCCESS) {
1172 dummyLen = sizeof(bpower);
1173 code = RegQueryValueEx(hkParm, "FlushOnHibernate", NULL, NULL,
1174 (BYTE *) &bpower, &dummyLen);
1176 if(code != ERROR_SUCCESS)
1179 RegCloseKey(hkParm);
1181 /* create thread used to flush cache */
1183 PowerNotificationThreadCreate();
1184 powerEventsRegistered = 1;
1189 /* Verify the versions of the DLLs which were loaded */
1190 if (!AFSModulesVerify()) {
1191 ServiceStatus.dwCurrentState = SERVICE_STOPPED;
1192 ServiceStatus.dwWin32ExitCode = NO_ERROR;
1193 ServiceStatus.dwCheckPoint = 0;
1194 ServiceStatus.dwWaitHint = 0;
1195 ServiceStatus.dwControlsAccepted = 0;
1196 SetServiceStatus(StatusHandle, &ServiceStatus);
1198 LogEvent(EVENTLOG_ERROR_TYPE, MSG_SERVICE_INCORRECT_VERSIONS);
1200 /* exit if initialization failed */
1204 /* allow an exit to be called prior to any initialization */
1205 hHookDll = LoadLibrary(AFSD_HOOK_DLL);
1209 AfsdInitHook initHook = ( AfsdInitHook ) GetProcAddress(hHookDll, AFSD_INIT_HOOK);
1212 hookRc = initHook();
1214 FreeLibrary(hHookDll);
1217 if (hookRc == FALSE)
1219 ServiceStatus.dwCurrentState = SERVICE_STOPPED;
1220 ServiceStatus.dwWin32ExitCode = NO_ERROR;
1221 ServiceStatus.dwCheckPoint = 0;
1222 ServiceStatus.dwWaitHint = 0;
1223 ServiceStatus.dwControlsAccepted = 0;
1224 SetServiceStatus(StatusHandle, &ServiceStatus);
1226 /* exit if initialization failed */
1231 /* allow another 120 seconds to start */
1232 ServiceStatus.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
1233 ServiceStatus.dwServiceSpecificExitCode = 0;
1234 ServiceStatus.dwCurrentState = SERVICE_START_PENDING;
1235 ServiceStatus.dwWin32ExitCode = NO_ERROR;
1236 ServiceStatus.dwCheckPoint = 2;
1237 ServiceStatus.dwWaitHint = 120000;
1238 /* accept Power Events */
1239 ServiceStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN | SERVICE_ACCEPT_POWEREVENT | SERVICE_ACCEPT_PARAMCHANGE;
1240 SetServiceStatus(StatusHandle, &ServiceStatus);
1244 /* Perform Volume Status Notification Initialization */
1245 cm_VolStatus_Initialization();
1248 MainThreadId = GetCurrentThreadId();
1249 jmpret = setjmp(notifier_jmp);
1254 code = afsd_InitCM(&reason);
1256 afsi_log("afsd_InitCM failed: %s (code = %d)", reason, code);
1257 osi_panic(reason, __FILE__, __LINE__);
1261 ServiceStatus.dwCheckPoint = 3;
1262 ServiceStatus.dwWaitHint = 30000;
1263 SetServiceStatus(StatusHandle, &ServiceStatus);
1265 code = afsd_InitDaemons(&reason);
1267 afsi_log("afsd_InitDaemons failed: %s (code = %d)", reason, code);
1268 osi_panic(reason, __FILE__, __LINE__);
1271 /* allow an exit to be called post rx initialization */
1272 hHookDll = LoadLibrary(AFSD_HOOK_DLL);
1276 AfsdRxStartedHook rxStartedHook = ( AfsdRxStartedHook ) GetProcAddress(hHookDll, AFSD_RX_STARTED_HOOK);
1279 hookRc = rxStartedHook();
1281 FreeLibrary(hHookDll);
1284 if (hookRc == FALSE)
1286 ServiceStatus.dwCurrentState = SERVICE_STOPPED;
1287 ServiceStatus.dwWin32ExitCode = NO_ERROR;
1288 ServiceStatus.dwCheckPoint = 0;
1289 ServiceStatus.dwWaitHint = 0;
1290 ServiceStatus.dwControlsAccepted = 0;
1291 SetServiceStatus(StatusHandle, &ServiceStatus);
1293 /* exit if initialization failed */
1299 ServiceStatus.dwCheckPoint = 4;
1300 ServiceStatus.dwWaitHint = 15000;
1301 SetServiceStatus(StatusHandle, &ServiceStatus);
1304 /* the following ifdef chooses the mode of operation for the service. to enable
1305 * a runtime flag (instead of compile-time), pioctl() would need to dynamically
1306 * determine the mode, in order to use the correct ioctl special-file path. */
1308 code = afsd_InitSMB(&reason, MessageBox);
1310 afsi_log("afsd_InitSMB failed: %s (code = %d)", reason, code);
1311 osi_panic(reason, __FILE__, __LINE__);
1314 code = ifs_Init(&reason);
1316 afsi_log("ifs_Init failed: %s (code = %d)", reason, code);
1317 osi_panic(reason, __FILE__, __LINE__);
1319 for (cnt = 0; cnt < WORKER_THREADS; cnt++)
1320 hAFSDWorkerThread[cnt] = CreateThread(NULL, 0, ifs_MainLoop, 0, 0, NULL);
1323 /* allow an exit to be called post smb initialization */
1324 hHookDll = LoadLibrary(AFSD_HOOK_DLL);
1328 AfsdSmbStartedHook smbStartedHook = ( AfsdSmbStartedHook ) GetProcAddress(hHookDll, AFSD_SMB_STARTED_HOOK);
1331 hookRc = smbStartedHook();
1333 FreeLibrary(hHookDll);
1336 if (hookRc == FALSE)
1338 ServiceStatus.dwCurrentState = SERVICE_STOPPED;
1339 ServiceStatus.dwWin32ExitCode = NO_ERROR;
1340 ServiceStatus.dwCheckPoint = 0;
1341 ServiceStatus.dwWaitHint = 0;
1342 ServiceStatus.dwControlsAccepted = 0;
1343 SetServiceStatus(StatusHandle, &ServiceStatus);
1345 /* exit if initialization failed */
1350 MountGlobalDrives();
1353 ServiceStatus.dwCurrentState = SERVICE_RUNNING;
1354 ServiceStatus.dwWin32ExitCode = NO_ERROR;
1355 ServiceStatus.dwCheckPoint = 5;
1356 ServiceStatus.dwWaitHint = 0;
1358 /* accept Power events */
1359 ServiceStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN | SERVICE_ACCEPT_POWEREVENT | SERVICE_ACCEPT_PARAMCHANGE;
1360 SetServiceStatus(StatusHandle, &ServiceStatus);
1363 LogEvent(EVENTLOG_INFORMATION_TYPE, MSG_SERVICE_RUNNING);
1366 /* Notify any volume status handlers that we have started */
1367 cm_VolStatus_Service_Started();
1369 /* allow an exit to be called when started */
1370 hHookDll = LoadLibrary(AFSD_HOOK_DLL);
1374 AfsdStartedHook startedHook = ( AfsdStartedHook ) GetProcAddress(hHookDll, AFSD_STARTED_HOOK);
1377 hookRc = startedHook();
1379 FreeLibrary(hHookDll);
1382 if (hookRc == FALSE)
1384 ServiceStatus.dwCurrentState = SERVICE_STOPPED;
1385 ServiceStatus.dwWin32ExitCode = NO_ERROR;
1386 ServiceStatus.dwCheckPoint = 0;
1387 ServiceStatus.dwWaitHint = 0;
1388 ServiceStatus.dwControlsAccepted = 0;
1389 SetServiceStatus(StatusHandle, &ServiceStatus);
1391 /* exit if initialization failed */
1397 WaitForSingleObject(WaitToTerminate, INFINITE);
1399 WaitForMultipleObjects(WORKER_THREADS, hAFSDWorkerThread, TRUE, INFINITE);
1400 for (cnt = 0; cnt < WORKER_THREADS; cnt++)
1401 CloseHandle(hAFSDWorkerThread[cnt]);
1404 ServiceStatus.dwCurrentState = SERVICE_STOP_PENDING;
1405 ServiceStatus.dwWin32ExitCode = NO_ERROR;
1406 ServiceStatus.dwCheckPoint = 6;
1407 ServiceStatus.dwWaitHint = 120000;
1408 ServiceStatus.dwControlsAccepted = 0;
1409 SetServiceStatus(StatusHandle, &ServiceStatus);
1411 afsi_log("Received Termination Signal, Stopping Service");
1414 LogEvent(EVENTLOG_ERROR_TYPE, MSG_SERVICE_ERROR_STOP);
1416 LogEvent(EVENTLOG_INFORMATION_TYPE, MSG_SERVICE_STOPPING);
1418 /* allow an exit to be called prior to stopping the service */
1419 hHookDll = LoadLibrary(AFSD_HOOK_DLL);
1423 AfsdStoppingHook stoppingHook = ( AfsdStoppingHook ) GetProcAddress(hHookDll, AFSD_STOPPING_HOOK);
1426 hookRc = stoppingHook();
1428 FreeLibrary(hHookDll);
1433 #ifdef AFS_FREELANCE_CLIENT
1434 cm_FreelanceShutdown();
1435 afsi_log("Freelance Shutdown complete");
1438 DismountGlobalDrives();
1439 afsi_log("Global Drives dismounted");
1441 cm_DaemonShutdown();
1442 afsi_log("Daemon shutdown complete");
1447 afsi_log("Buffer shutdown complete");
1450 afsi_log("rx finalization complete");
1454 afsi_log("smb shutdown complete");
1459 cm_ReleaseAllLocks();
1462 afsi_log("rx finalization complete");
1464 cm_ShutdownMappedMemory();
1466 #ifdef REGISTER_POWER_NOTIFICATIONS
1467 /* terminate thread used to flush cache */
1468 if (powerEventsRegistered)
1469 PowerNotificationThreadExit();
1472 /* Notify any Volume Status Handlers that we are stopped */
1473 cm_VolStatus_Service_Stopped();
1475 /* Cleanup any Volume Status Notification Handler */
1476 cm_VolStatus_Finalize();
1478 /* allow an exit to be called after stopping the service */
1479 hHookDll = LoadLibrary(AFSD_HOOK_DLL);
1483 AfsdStoppedHook stoppedHook = ( AfsdStoppedHook ) GetProcAddress(hHookDll, AFSD_STOPPED_HOOK);
1486 hookRc = stoppedHook();
1488 FreeLibrary(hHookDll);
1492 /* Remove the ExceptionFilter */
1493 SetUnhandledExceptionFilter(NULL);
1495 ServiceStatus.dwCurrentState = SERVICE_STOPPED;
1496 ServiceStatus.dwWin32ExitCode = GlobalStatus ? ERROR_EXCEPTION_IN_SERVICE : NO_ERROR;
1497 ServiceStatus.dwCheckPoint = 7;
1498 ServiceStatus.dwWaitHint = 0;
1499 ServiceStatus.dwControlsAccepted = 0;
1500 SetServiceStatus(StatusHandle, &ServiceStatus);
1503 DWORD __stdcall afsdMain_thread(void* notUsed)
1505 char * argv[2] = {AFS_DAEMON_SERVICE_NAME, NULL};
1506 afsd_Main(1, (LPTSTR*)argv);
1512 fprintf(stderr, "afsd_service.exe [--validate-cache <cache-path>]");
1516 main(int argc, char * argv[])
1518 static SERVICE_TABLE_ENTRY dispatchTable[] = {
1519 {AFS_DAEMON_SERVICE_NAME, (LPSERVICE_MAIN_FUNCTION) afsd_Main},
1524 for (i = 1; i < argc; i++) {
1525 if (!stricmp(argv[i],"--validate-cache")) {
1526 if (++i != argc - 1) {
1531 return cm_ValidateMappedMemory(argv[i]);
1538 if (!StartServiceCtrlDispatcher(dispatchTable))
1540 LONG status = GetLastError();
1541 if (status == ERROR_FAILED_SERVICE_CONTROLLER_CONNECT)
1544 hAFSDMainThread = CreateThread(NULL, 0, afsdMain_thread, 0, 0, &tid);
1546 printf("Hit <Enter> to terminate OpenAFS Client Service\n");
1548 SetEvent(WaitToTerminate);
1555 if ( hAFSDMainThread ) {
1556 WaitForSingleObject( hAFSDMainThread, INFINITE );
1557 CloseHandle( hAFSDMainThread );