2 * Copyright 2000, International Business Machines Corporation and others.
5 * This software has been released under the terms of the IBM Public
6 * License. For details, see the LICENSE file in the top-level source
7 * directory or online at http://www.openafs.org/dl/license10.html
10 #include <afs/param.h>
20 #include "afsd_init.h"
35 // The following is defined if you want to receive Power notifications,
36 // including Hibernation, and also subsequent flushing of AFS volumes
38 #define REGISTER_POWER_NOTIFICATIONS 1
39 #define FLUSH_VOLUME 1
43 #include "afsd_flushvol.h"
45 extern void afsi_log(char *pattern, ...);
47 static SERVICE_STATUS ServiceStatus;
48 static SERVICE_STATUS_HANDLE StatusHandle;
50 HANDLE hAFSDMainThread = NULL;
52 HANDLE WaitToTerminate;
57 unsigned int MainThreadId;
61 extern int traceOnPanic;
62 extern HANDLE afsi_file;
64 int powerEventsRegistered = 0;
67 * Notifier function for use by osi_panic
69 static void afsd_notifier(char *msgp, char *filep, long line)
76 sprintf(tbuffer, "Error at file %s, line %d: %s",
79 sprintf(tbuffer, "Error at unknown location: %s", msgp);
81 h = RegisterEventSource(NULL, AFS_DAEMON_EVENT_NAME);
83 ReportEvent(h, EVENTLOG_ERROR_TYPE, 0, line, NULL, 1, 0, ptbuf, NULL);
84 DeregisterEventSource(h);
88 osi_LogEnable(afsd_logp);
90 afsd_ForceTrace(TRUE);
93 afsi_log("--- begin dump ---");
94 cm_DumpSCache(afsi_file, "a");
96 cm_dnlcDump(afsi_file, "a");
98 cm_DumpBufHashTable(afsi_file, "a");
99 smb_DumpVCP(afsi_file, "a");
100 afsi_log("--- end dump ---");
106 SetEvent(WaitToTerminate);
109 if (GetCurrentThreadId() == MainThreadId)
110 longjmp(notifier_jmp, 1);
113 ServiceStatus.dwCurrentState = SERVICE_STOPPED;
114 ServiceStatus.dwWin32ExitCode = NO_ERROR;
115 ServiceStatus.dwCheckPoint = 0;
116 ServiceStatus.dwWaitHint = 0;
117 ServiceStatus.dwControlsAccepted = 0;
118 SetServiceStatus(StatusHandle, &ServiceStatus);
124 * For use miscellaneously in smb.c; need to do better
126 static int _stdcall DummyMessageBox(HWND h, LPCTSTR l1, LPCTSTR l2, UINT ui)
132 afsd_ServiceFlushVolume(DWORD dwlpEventData)
134 DWORD dwRet = ERROR_NETWORK_BUSY; /* or NO_ERROR */
137 ** If UI bit is not set, user interaction is not possible
138 ** BUT, since we are a NON-interactive service, and therefore
139 ** have NO user I/O, it doesn't much matter.
140 ** This benign code left here as example of how to find this out
142 BOOL bUI = (dwlpEventData & 1);
145 if ( PowerNotificationThreadNotify() )
151 /* flush was unsuccessful, or timeout - deny shutdown */
152 dwRet = ERROR_NETWORK_BUSY;
155 /* to deny hibernate, simply return
156 // any value besides NO_ERROR.
158 // dwRet = ERROR_NETWORK_BUSY;
165 /* service control handler used in nt4 only for backward compat. */
167 afsd_ServiceControlHandler(DWORD ctrlCode)
170 DWORD dummyLen, doTrace;
174 case SERVICE_CONTROL_STOP:
176 RpcMgmtStopServerListening(NULL);
178 /* Force trace if requested */
179 code = RegOpenKeyEx(HKEY_LOCAL_MACHINE,
181 0, KEY_QUERY_VALUE, &parmKey);
182 if (code != ERROR_SUCCESS)
185 dummyLen = sizeof(doTrace);
186 code = RegQueryValueEx(parmKey, "TraceOnShutdown",
188 (BYTE *) &doTrace, &dummyLen);
189 RegCloseKey (parmKey);
190 if (code != ERROR_SUCCESS)
193 afsd_ForceTrace(FALSE);
194 buf_ForceTrace(FALSE);
198 ServiceStatus.dwCurrentState = SERVICE_STOP_PENDING;
199 ServiceStatus.dwWin32ExitCode = NO_ERROR;
200 ServiceStatus.dwCheckPoint = 1;
201 ServiceStatus.dwWaitHint = 10000;
202 ServiceStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP;
203 SetServiceStatus(StatusHandle, &ServiceStatus);
204 SetEvent(WaitToTerminate);
206 case SERVICE_CONTROL_INTERROGATE:
207 ServiceStatus.dwCurrentState = SERVICE_RUNNING;
208 ServiceStatus.dwWin32ExitCode = NO_ERROR;
209 ServiceStatus.dwCheckPoint = 0;
210 ServiceStatus.dwWaitHint = 0;
211 ServiceStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP;
212 SetServiceStatus(StatusHandle, &ServiceStatus);
214 /* XXX handle system shutdown */
215 /* XXX handle pause & continue */
221 ** Extended ServiceControlHandler that provides Event types
222 ** for monitoring Power events, for example.
225 afsd_ServiceControlHandlerEx(
233 DWORD dummyLen, doTrace;
235 DWORD dwRet = ERROR_CALL_NOT_IMPLEMENTED;
239 case SERVICE_CONTROL_STOP:
241 RpcMgmtStopServerListening(NULL);
243 /* Force trace if requested */
244 code = RegOpenKeyEx(HKEY_LOCAL_MACHINE,
246 0, KEY_QUERY_VALUE, &parmKey);
247 if (code != ERROR_SUCCESS)
250 dummyLen = sizeof(doTrace);
251 code = RegQueryValueEx(parmKey, "TraceOnShutdown",
253 (BYTE *) &doTrace, &dummyLen);
254 RegCloseKey (parmKey);
255 if (code != ERROR_SUCCESS)
258 afsd_ForceTrace(FALSE);
259 buf_ForceTrace(FALSE);
263 ServiceStatus.dwCurrentState = SERVICE_STOP_PENDING;
264 ServiceStatus.dwWin32ExitCode = NO_ERROR;
265 ServiceStatus.dwCheckPoint = 1;
266 ServiceStatus.dwWaitHint = 10000;
267 ServiceStatus.dwControlsAccepted = 0;
268 SetServiceStatus(StatusHandle, &ServiceStatus);
269 SetEvent(WaitToTerminate);
273 case SERVICE_CONTROL_INTERROGATE:
274 ServiceStatus.dwCurrentState = SERVICE_RUNNING;
275 ServiceStatus.dwWin32ExitCode = NO_ERROR;
276 ServiceStatus.dwCheckPoint = 0;
277 ServiceStatus.dwWaitHint = 0;
278 ServiceStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_POWEREVENT;
279 SetServiceStatus(StatusHandle, &ServiceStatus);
283 /* XXX handle system shutdown */
284 /* XXX handle pause & continue */
285 case SERVICE_CONTROL_POWEREVENT:
288 ** dwEventType of this notification == WPARAM of WM_POWERBROADCAST
289 ** Return NO_ERROR == return TRUE for that message, i.e. accept request
290 ** Return any error code to deny request,
291 ** i.e. as if returning BROADCAST_QUERY_DENY
293 if (powerEventsRegistered) {
294 switch((int) dwEventType)
296 case PBT_APMQUERYSUSPEND:
297 case PBT_APMQUERYSTANDBY:
301 dwRet = afsd_ServiceFlushVolume((DWORD) lpEventData);
307 /* allow remaining case PBT_WhatEver */
310 case PBT_APMRESUMECRITICAL:
311 case PBT_APMRESUMESUSPEND:
312 case PBT_APMRESUMESTANDBY:
313 case PBT_APMBATTERYLOW:
314 case PBT_APMPOWERSTATUSCHANGE:
315 case PBT_APMOEMEVENT:
316 case PBT_APMRESUMEAUTOMATIC:
322 } /* end switch(ctrlCode) */
326 /* There is similar code in client_config\drivemap.cpp GlobalMountDrive()
328 * Mount a drive into AFS if there global mapping
330 /* DEE Could check first if we are run as SYSTEM */
331 #define MAX_RETRIES 30
332 static void MountGlobalDrives(void)
334 char szAfsPath[_MAX_PATH];
335 char szDriveToMapTo[5];
339 DWORD dwIndex = 0, dwRetry = 0;
341 DWORD dwSubMountSize;
342 char szSubMount[256];
345 sprintf(szKeyName, "%s\\GlobalAutoMapper", AFSConfigKeyName);
347 dwResult = RegOpenKeyEx(HKEY_LOCAL_MACHINE, szKeyName, 0, KEY_QUERY_VALUE, &hKey);
348 if (dwResult != ERROR_SUCCESS)
351 while (dwRetry < MAX_RETRIES) {
352 dwDriveSize = sizeof(szDriveToMapTo);
353 dwSubMountSize = sizeof(szSubMount);
354 dwResult = RegEnumValue(hKey, dwIndex++, szDriveToMapTo, &dwDriveSize, 0, &dwType, szSubMount, &dwSubMountSize);
355 if (dwResult != ERROR_MORE_DATA) {
356 if (dwResult != ERROR_SUCCESS) {
357 if (dwResult != ERROR_NO_MORE_ITEMS)
358 afsi_log("Failed to read GlobalAutoMapper values: %d\n", dwResult);
363 for ( ; dwRetry < MAX_RETRIES; dwRetry++)
366 memset (&nr, 0x00, sizeof(NETRESOURCE));
368 sprintf(szAfsPath,"\\\\%s\\%s",cm_NetbiosName,szSubMount);
370 nr.dwScope = RESOURCE_GLOBALNET; /* ignored parameter */
371 nr.dwType=RESOURCETYPE_DISK;
372 nr.lpLocalName=szDriveToMapTo;
373 nr.lpRemoteName=szAfsPath;
374 nr.dwDisplayType = RESOURCEDISPLAYTYPE_SHARE; /* ignored parameter */
375 nr.dwUsage = RESOURCEUSAGE_CONNECTABLE; /* ignored parameter */
377 dwResult = WNetAddConnection2(&nr,NULL,NULL,0);
378 afsi_log("GlobalAutoMap of %s to %s %s (%d)", szDriveToMapTo, szSubMount,
379 (dwResult == NO_ERROR) ? "succeeded" : "failed", dwResult);
380 if (dwResult == NO_ERROR) {
383 /* wait for smb server to come up */
384 Sleep((DWORD)1000 /* miliseconds */);
386 /* Disconnect any previous mappings */
387 dwResult = WNetCancelConnection2(szDriveToMapTo, 0, TRUE);
394 static void DismountGlobalDrives()
396 char szAfsPath[_MAX_PATH];
397 char szDriveToMapTo[5];
403 DWORD dwSubMountSize;
404 char szSubMount[256];
407 sprintf(szKeyName, "%s\\GlobalAutoMapper", AFSConfigKeyName);
409 dwResult = RegOpenKeyEx(HKEY_LOCAL_MACHINE, szKeyName, 0, KEY_QUERY_VALUE, &hKey);
410 if (dwResult != ERROR_SUCCESS)
414 dwDriveSize = sizeof(szDriveToMapTo);
415 dwSubMountSize = sizeof(szSubMount);
416 dwResult = RegEnumValue(hKey, dwIndex++, szDriveToMapTo, &dwDriveSize, 0, &dwType, szSubMount, &dwSubMountSize);
417 if (dwResult != ERROR_MORE_DATA) {
418 if (dwResult != ERROR_SUCCESS) {
419 if (dwResult != ERROR_NO_MORE_ITEMS)
420 afsi_log("Failed to read GlobalAutoMapper values: %d\n", dwResult);
425 sprintf(szAfsPath,"\\\\%s\\%s",cm_NetbiosName,szSubMount);
427 dwResult = WNetCancelConnection2(szDriveToMapTo, 0, TRUE);
428 dwResult = WNetCancelConnection(szAfsPath, TRUE);
430 afsi_log("Disconnect from GlobalAutoMap of %s to %s %s", szDriveToMapTo, szSubMount, dwResult ? "succeeded" : "failed");
437 GetVersionInfo( CHAR * filename, CHAR * szOutput, DWORD dwOutput )
439 DWORD dwVersionHandle;
440 LPVOID pVersionInfo = 0;
442 LPDWORD pLangInfo = 0;
443 LPTSTR szVersion = 0;
445 TCHAR szVerQ[] = TEXT("\\StringFileInfo\\12345678\\FileVersion");
446 DWORD size = GetFileVersionInfoSize(filename, &dwVersionHandle);
449 afsi_log("GetFileVersionInfoSize failed");
450 return GetLastError();
453 pVersionInfo = malloc(size);
455 afsi_log("out of memory 1");
456 return ERROR_NOT_ENOUGH_MEMORY;
459 GetFileVersionInfo(filename, dwVersionHandle, size, pVersionInfo);
460 if (retval = GetLastError())
462 afsi_log("GetFileVersionInfo failed: %d", retval);
466 VerQueryValue(pVersionInfo, TEXT("\\VarFileInfo\\Translation"),
467 (LPVOID*)&pLangInfo, &len);
468 if (retval = GetLastError())
470 afsi_log("VerQueryValue 1 failed: %d", retval);
475 TEXT("\\StringFileInfo\\%04x%04x\\FileVersion"),
476 LOWORD(*pLangInfo), HIWORD(*pLangInfo));
478 VerQueryValue(pVersionInfo, szVerQ, (LPVOID*)&szVersion, &len);
479 if (retval = GetLastError())
481 /* try again with language 409 since the old binaries were tagged wrong */
483 TEXT("\\StringFileInfo\\0409%04x\\FileVersion"),
486 VerQueryValue(pVersionInfo, szVerQ, (LPVOID*)&szVersion, &len);
487 if (retval = GetLastError()) {
488 afsi_log("VerQueryValue 2 failed: [%s] %d", szVerQ, retval);
492 snprintf(szOutput, dwOutput, TEXT("%s"), szVersion);
493 szOutput[dwOutput - 1] = 0;
502 static HINSTANCE hCrypt32;
503 static DWORD (WINAPI *pCertGetNameString)(PCCERT_CONTEXT pCertContext, DWORD dwType, DWORD dwFlags,
504 void* pvTypePara, LPTSTR pszNameString, DWORD cchNameString);
505 static BOOL (WINAPI *pCryptQueryObject)(DWORD dwObjectType, const void* pvObject, DWORD dwExpectedContentTypeFlags,
506 DWORD dwExpectedFormatTypeFlags, DWORD dwFlags,
507 DWORD* pdwMsgAndCertEncodingType, DWORD* pdwContentType,
508 DWORD* pdwFormatType, HCERTSTORE* phCertStore,
509 HCRYPTMSG* phMsg, const void** ppvContext);
510 static BOOL (WINAPI *pCryptMsgGetParam)(HCRYPTMSG hCryptMsg, DWORD dwParamType, DWORD dwIndex,
511 void* pvData, DWORD* pcbData);
512 static PCCERT_CONTEXT (WINAPI *pCertFindCertificateInStore)(HCERTSTORE hCertStore, DWORD dwCertEncodingType,
513 DWORD dwFindFlags, DWORD dwFindType,
514 const void* pvFindPara,
515 PCCERT_CONTEXT pPrevCertContext);
516 static BOOL (WINAPI *pCertCloseStore)(HCERTSTORE hCertStore, DWORD dwFlags);
517 static BOOL (WINAPI *pCryptMsgClose)(HCRYPTMSG hCryptMsg);
518 static BOOL (WINAPI *pCertCompareCertificate)(DWORD dwCertEncodingType, PCERT_INFO pCertId1,
519 PCERT_INFO pCertId2);
520 static BOOL (WINAPI *pCertFreeCertificateContext)(PCCERT_CONTEXT pCertContext);
522 void LoadCrypt32(void)
524 hCrypt32 = LoadLibrary("crypt32");
528 (FARPROC) pCertGetNameString = GetProcAddress( hCrypt32, "CertGetNameString" );
529 (FARPROC) pCryptQueryObject = GetProcAddress( hCrypt32, "CryptQueryObject" );
530 (FARPROC) pCryptMsgGetParam = GetProcAddress( hCrypt32, "CryptMsgGetParam" );
531 (FARPROC) pCertFindCertificateInStore = GetProcAddress( hCrypt32, "CertFindCertificateInStore" );
532 (FARPROC) pCertCloseStore = GetProcAddress( hCrypt32, "CertCloseStore" );
533 (FARPROC) pCryptMsgClose = GetProcAddress( hCrypt32, "CryptMsgClose" );
534 (FARPROC) pCertCompareCertificate = GetProcAddress( hCrypt32, "CertCompareCertificate" );
535 (FARPROC) pCertFreeCertificateContext = GetProcAddress( hCrypt32, "CertFreeCertificateContext" );
537 if ( !pCertGetNameString ||
538 !pCryptQueryObject ||
539 !pCryptMsgGetParam ||
540 !pCertFindCertificateInStore ||
543 !pCertCompareCertificate ||
544 !pCertFreeCertificateContext)
546 FreeLibrary(hCrypt32);
551 void UnloadCrypt32(void)
553 FreeLibrary(hCrypt32);
556 #define ENCODING (X509_ASN_ENCODING | PKCS_7_ASN_ENCODING)
558 PCCERT_CONTEXT GetCertCtx(CHAR * filename)
560 wchar_t wfilename[260];
566 HCERTSTORE hStore = NULL;
567 HCRYPTMSG hMsg = NULL;
568 PCMSG_SIGNER_INFO pSignerInfo = NULL;
569 PCCERT_CONTEXT pCertContext = NULL;
572 if ( hCrypt32 == NULL )
575 ZeroMemory(&CertInfo, sizeof(CertInfo));
576 mbstowcs(wfilename, filename, 260);
578 fResult = pCryptQueryObject(CERT_QUERY_OBJECT_FILE,
580 CERT_QUERY_CONTENT_FLAG_PKCS7_SIGNED_EMBED,
581 CERT_QUERY_FORMAT_FLAG_BINARY,
591 afsi_log("CryptQueryObject failed for [%s] with error 0x%x",
597 fResult = pCryptMsgGetParam(hMsg,
598 CMSG_SIGNER_INFO_PARAM,
604 afsi_log("CryptMsgGetParam failed for [%s] with error 0x%x",
610 pSignerInfo = (PCMSG_SIGNER_INFO)LocalAlloc(LPTR, dwSignerInfo);
612 fResult = pCryptMsgGetParam(hMsg,
613 CMSG_SIGNER_INFO_PARAM,
619 afsi_log("CryptMsgGetParam failed for [%s] with error 0x%x",
625 CertInfo.Issuer = pSignerInfo->Issuer;
626 CertInfo.SerialNumber = pSignerInfo->SerialNumber;
628 pCertContext = pCertFindCertificateInStore(hStore,
631 CERT_FIND_SUBJECT_CERT,
636 afsi_log("CertFindCertificateInStore for file [%s] failed with 0x%x",
644 LocalFree(pSignerInfo);
647 CertFreeCertificateContext(pCertContext);*/
650 pCertCloseStore(hStore,0);
653 pCryptMsgClose(hMsg);
658 BOOL VerifyTrust(CHAR * filename)
660 WIN_TRUST_ACTDATA_CONTEXT_WITH_SUBJECT fContextWSubject;
661 WIN_TRUST_SUBJECT_FILE fSubjectFile;
662 GUID trustAction = WIN_SPUB_ACTION_PUBLISHED_SOFTWARE;
663 GUID subject = WIN_TRUST_SUBJTYPE_PE_IMAGE;
664 wchar_t wfilename[260];
666 BOOL success = FALSE;
668 LONG (WINAPI *pWinVerifyTrust)(HWND hWnd, GUID* pgActionID, WINTRUST_DATA* pWinTrustData) = NULL;
671 if (filename == NULL )
674 hWinTrust = LoadLibrary("wintrust");
678 if (((FARPROC) pWinVerifyTrust =
679 GetProcAddress( hWinTrust, "WinVerifyTrust" )) == NULL )
681 FreeLibrary(hWinTrust);
685 mbstowcs(wfilename, filename, 260);
687 fSubjectFile.hFile = CreateFile(filename, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING,
689 fSubjectFile.lpPath = wfilename;
690 fContextWSubject.hClientToken = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ,
691 FALSE, GetCurrentProcessId());
692 fContextWSubject.SubjectType = &subject;
693 fContextWSubject.Subject = &fSubjectFile;
695 ret = pWinVerifyTrust(INVALID_HANDLE_VALUE, &trustAction, (WINTRUST_DATA *)&fContextWSubject);
697 if ( fSubjectFile.hFile != INVALID_HANDLE_VALUE )
698 CloseHandle( fSubjectFile.hFile );
699 if ( fContextWSubject.hClientToken != INVALID_HANDLE_VALUE )
700 CloseHandle( fContextWSubject.hClientToken );
702 if (ret == ERROR_SUCCESS) {
705 DWORD gle = GetLastError();
707 case TRUST_E_PROVIDER_UNKNOWN:
708 afsi_log("VerifyTrust failed: \"Generic Verify V2\" Provider Unknown");
710 case TRUST_E_NOSIGNATURE:
711 afsi_log("VerifyTrust failed: Unsigned executable");
713 case TRUST_E_EXPLICIT_DISTRUST:
714 afsi_log("VerifyTrust failed: Certificate Marked as Untrusted by the user");
716 case TRUST_E_SUBJECT_NOT_TRUSTED:
717 afsi_log("VerifyTrust failed: File is not trusted");
719 case TRUST_E_BAD_DIGEST:
720 afsi_log("VerifyTrust failed: Executable has been modified");
722 case CRYPT_E_SECURITY_SETTINGS:
723 afsi_log("VerifyTrust failed: local security options prevent verification");
726 afsi_log("VerifyTrust failed: 0x%X", GetLastError());
730 FreeLibrary(hWinTrust);
734 void LogCertCtx(PCCERT_CONTEXT pCtx) {
736 LPTSTR szName = NULL;
738 if ( hCrypt32 == NULL )
741 // Get Issuer name size.
742 if (!(dwData = pCertGetNameString(pCtx,
743 CERT_NAME_SIMPLE_DISPLAY_TYPE,
744 CERT_NAME_ISSUER_FLAG,
748 afsi_log("CertGetNameString failed: 0x%x", GetLastError());
752 // Allocate memory for Issuer name.
753 szName = (LPTSTR)LocalAlloc(LPTR, dwData * sizeof(TCHAR));
756 if (!(pCertGetNameString(pCtx,
757 CERT_NAME_SIMPLE_DISPLAY_TYPE,
758 CERT_NAME_ISSUER_FLAG,
762 afsi_log("CertGetNameString failed: 0x%x", GetLastError());
766 // print Issuer name.
767 afsi_log("Issuer Name: %s", szName);
771 // Get Subject name size.
772 if (!(dwData = pCertGetNameString(pCtx,
773 CERT_NAME_SIMPLE_DISPLAY_TYPE,
778 afsi_log("CertGetNameString failed: 0x%x", GetLastError());
782 // Allocate memory for subject name.
783 szName = (LPTSTR)LocalAlloc(LPTR, dwData * sizeof(TCHAR));
786 if (!(pCertGetNameString(pCtx,
787 CERT_NAME_SIMPLE_DISPLAY_TYPE,
792 afsi_log("CertGetNameString failed: 0x%x", GetLastError());
796 // Print Subject Name.
797 afsi_log("Subject Name: %s", szName);
805 BOOL AFSModulesVerify(void)
808 CHAR afsdVersion[128];
809 CHAR modVersion[128];
810 CHAR checkName[1024];
811 BOOL trustVerified = FALSE;
817 PCCERT_CONTEXT pCtxService = NULL;
819 DWORD (WINAPI *pGetModuleFileNameExA)(HANDLE hProcess, HMODULE hModule, LPTSTR lpFilename, DWORD nSize);
820 BOOL (WINAPI *pEnumProcessModules)(HANDLE hProcess, HMODULE* lphModule, DWORD cb, LPDWORD lpcbNeeded);
821 DWORD dummyLen, code;
822 DWORD verifyServiceSig = TRUE;
825 hPSAPI = LoadLibrary("psapi");
827 if ( hPSAPI == NULL )
830 if (!GetModuleFileName(NULL, filename, sizeof(filename)))
833 if (GetVersionInfo(filename, afsdVersion, sizeof(afsdVersion)))
836 afsi_log("%s version %s", filename, afsdVersion);
838 if (((FARPROC) pGetModuleFileNameExA =
839 GetProcAddress( hPSAPI, "GetModuleFileNameExA" )) == NULL ||
840 ((FARPROC) pEnumProcessModules =
841 GetProcAddress( hPSAPI, "EnumProcessModules" )) == NULL)
847 code = RegOpenKeyEx(HKEY_LOCAL_MACHINE, "SOFTWARE\\OpenAFS\\Client",
848 0, KEY_QUERY_VALUE, &parmKey);
849 if (code == ERROR_SUCCESS) {
850 dummyLen = sizeof(verifyServiceSig);
851 code = RegQueryValueEx(parmKey, "VerifyServiceSignature", NULL, NULL,
852 (BYTE *) &verifyServiceSig, &dummyLen);
853 RegCloseKey (parmKey);
856 if (verifyServiceSig)
857 trustVerified = VerifyTrust(filename);
862 // get a certificate context for the signer of afsd_service.
863 pCtxService = GetCertCtx(filename);
865 LogCertCtx(pCtxService);
868 // Get a list of all the modules in this process.
869 hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ,
870 FALSE, GetCurrentProcessId());
872 if (pEnumProcessModules(hProcess, hMods, sizeof(hMods), &cbNeeded))
874 afsi_log("Num of Process Modules: %d", (cbNeeded / sizeof(HMODULE)));
876 for (i = 0; i < (cbNeeded / sizeof(HMODULE)); i++)
878 char szModName[2048];
880 // Get the full path to the module's file.
881 if (pGetModuleFileNameExA(hProcess, hMods[i], szModName, sizeof(szModName)))
883 lstrcpy(checkName, szModName);
886 if ( strstr(checkName, "afspthread.dll") ||
887 strstr(checkName, "afsauthent.dll") ||
888 strstr(checkName, "afsrpc.dll") ||
889 strstr(checkName, "libafsconf.dll") ||
890 strstr(checkName, "libosi.dll") )
892 if (GetVersionInfo(szModName, modVersion, sizeof(modVersion))) {
897 afsi_log("%s version %s", szModName, modVersion);
898 if (strcmp(afsdVersion,modVersion)) {
899 afsi_log("Version mismatch: %s", szModName);
902 if ( trustVerified ) {
903 if ( !VerifyTrust(szModName) ) {
904 afsi_log("Signature Verification failed: %s", szModName);
907 else if (pCtxService) {
908 PCCERT_CONTEXT pCtx = GetCertCtx(szModName);
910 if (!pCtx || !pCertCompareCertificate(X509_ASN_ENCODING | PKCS_7_ASN_ENCODING,
911 pCtxService->pCertInfo,
913 afsi_log("Certificate mismatch: %s", szModName);
921 pCertFreeCertificateContext(pCtx);
930 pCertFreeCertificateContext(pCtxService);
936 CloseHandle(hProcess);
940 typedef BOOL ( APIENTRY * AfsdInitHook )(void);
941 #define AFSD_INIT_HOOK "AfsdInitHook"
942 #define AFSD_HOOK_DLL "afsdhook.dll"
945 control serviceex exists only on 2000/xp. These functions will be loaded dynamically.
948 typedef SERVICE_STATUS_HANDLE ( * RegisterServiceCtrlHandlerExFunc )( LPCTSTR , LPHANDLER_FUNCTION_EX , LPVOID );
949 typedef SERVICE_STATUS_HANDLE ( * RegisterServiceCtrlHandlerFunc )( LPCTSTR , LPHANDLER_FUNCTION );
951 RegisterServiceCtrlHandlerExFunc pRegisterServiceCtrlHandlerEx = NULL;
952 RegisterServiceCtrlHandlerFunc pRegisterServiceCtrlHandler = NULL;
954 void afsd_Main(DWORD argc, LPTSTR *argv)
963 AfsdInitHook initHook;
966 _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF /*| _CRTDBG_CHECK_ALWAYS_DF*/ |
967 _CRTDBG_CHECK_CRT_DF /* | _CRTDBG_DELAY_FREE_MEM_DF */ );
970 osi_InitPanic(afsd_notifier);
971 osi_InitTraceOption();
977 WaitToTerminate = CreateEvent(NULL, TRUE, FALSE, TEXT("afsd_service_WaitToTerminate"));
978 if ( GetLastError() == ERROR_ALREADY_EXISTS )
979 afsi_log("Event Object Already Exists: %s", TEXT("afsd_service_WaitToTerminate"));
982 hAdvApi32 = LoadLibrary("advapi32.dll");
983 if (hAdvApi32 == NULL)
985 afsi_log("Fatal: cannot load advapi32.dll");
989 pRegisterServiceCtrlHandlerEx = (RegisterServiceCtrlHandlerExFunc)GetProcAddress(hAdvApi32, "RegisterServiceCtrlHandlerExA");
990 if (pRegisterServiceCtrlHandlerEx)
992 afsi_log("running on 2000+ - using RegisterServiceCtrlHandlerEx");
993 StatusHandle = RegisterServiceCtrlHandlerEx(AFS_DAEMON_SERVICE_NAME, afsd_ServiceControlHandlerEx, NULL );
997 StatusHandle = RegisterServiceCtrlHandler(AFS_DAEMON_SERVICE_NAME, afsd_ServiceControlHandler);
1000 ServiceStatus.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
1001 ServiceStatus.dwServiceSpecificExitCode = 0;
1002 ServiceStatus.dwCurrentState = SERVICE_START_PENDING;
1003 ServiceStatus.dwWin32ExitCode = NO_ERROR;
1004 ServiceStatus.dwCheckPoint = 1;
1005 ServiceStatus.dwWaitHint = 30000;
1006 /* accept Power Events */
1007 ServiceStatus.dwControlsAccepted = SERVICE_ACCEPT_POWEREVENT;
1008 SetServiceStatus(StatusHandle, &ServiceStatus);
1012 HANDLE h; char *ptbuf[1];
1013 h = RegisterEventSource(NULL, AFS_DAEMON_EVENT_NAME);
1014 ptbuf[0] = "AFS start pending";
1015 ReportEvent(h, EVENTLOG_INFORMATION_TYPE, 0, 0, NULL, 1, 0, ptbuf, NULL);
1016 DeregisterEventSource(h);
1019 #ifdef REGISTER_POWER_NOTIFICATIONS
1026 /* see if we should handle power notifications */
1027 code = RegOpenKeyEx(HKEY_LOCAL_MACHINE, AFSConfigKeyName, 0, KEY_QUERY_VALUE, &hkParm);
1028 if (code == ERROR_SUCCESS) {
1029 dummyLen = sizeof(bpower);
1030 code = RegQueryValueEx(hkParm, "FlushOnHibernate", NULL, NULL,
1031 (BYTE *) &bpower, &dummyLen);
1033 if(code != ERROR_SUCCESS)
1036 RegCloseKey(hkParm);
1038 /* create thread used to flush cache */
1040 PowerNotificationThreadCreate();
1041 powerEventsRegistered = 1;
1046 /* Verify the versions of the DLLs which were loaded */
1047 if (!AFSModulesVerify()) {
1048 ServiceStatus.dwCurrentState = SERVICE_STOPPED;
1049 ServiceStatus.dwWin32ExitCode = NO_ERROR;
1050 ServiceStatus.dwCheckPoint = 0;
1051 ServiceStatus.dwWaitHint = 0;
1052 ServiceStatus.dwControlsAccepted = 0;
1053 SetServiceStatus(StatusHandle, &ServiceStatus);
1055 /* exit if initialization failed */
1059 /* allow an exit to be called prior to any initialization */
1060 hInitHookDll = LoadLibrary(AFSD_HOOK_DLL);
1063 BOOL hookRc = FALSE;
1064 initHook = ( AfsdInitHook ) GetProcAddress(hInitHookDll, AFSD_INIT_HOOK);
1067 hookRc = initHook();
1069 FreeLibrary(hInitHookDll);
1070 hInitHookDll = NULL;
1072 if (hookRc == FALSE)
1074 ServiceStatus.dwCurrentState = SERVICE_STOPPED;
1075 ServiceStatus.dwWin32ExitCode = NO_ERROR;
1076 ServiceStatus.dwCheckPoint = 0;
1077 ServiceStatus.dwWaitHint = 0;
1078 ServiceStatus.dwControlsAccepted = 0;
1079 SetServiceStatus(StatusHandle, &ServiceStatus);
1081 /* exit if initialization failed */
1086 /* allow another 15 seconds to start */
1087 ServiceStatus.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
1088 ServiceStatus.dwServiceSpecificExitCode = 0;
1089 ServiceStatus.dwCurrentState = SERVICE_START_PENDING;
1090 ServiceStatus.dwWin32ExitCode = NO_ERROR;
1091 ServiceStatus.dwCheckPoint = 2;
1092 ServiceStatus.dwWaitHint = 20000;
1093 /* accept Power Events */
1094 ServiceStatus.dwControlsAccepted = SERVICE_ACCEPT_POWEREVENT;
1095 SetServiceStatus(StatusHandle, &ServiceStatus);
1100 MainThreadId = GetCurrentThreadId();
1101 jmpret = setjmp(notifier_jmp);
1106 code = afsd_InitCM(&reason);
1108 afsi_log("afsd_InitCM failed: %s (code = %d)", reason, code);
1109 osi_panic(reason, __FILE__, __LINE__);
1113 ServiceStatus.dwCheckPoint++;
1114 ServiceStatus.dwWaitHint -= 5000;
1115 SetServiceStatus(StatusHandle, &ServiceStatus);
1117 code = afsd_InitDaemons(&reason);
1119 afsi_log("afsd_InitDaemons failed: %s (code = %d)", reason, code);
1120 osi_panic(reason, __FILE__, __LINE__);
1124 ServiceStatus.dwCheckPoint++;
1125 ServiceStatus.dwWaitHint -= 5000;
1126 SetServiceStatus(StatusHandle, &ServiceStatus);
1128 code = afsd_InitSMB(&reason, MessageBox);
1130 afsi_log("afsd_InitSMB failed: %s (code = %d)", reason, code);
1131 osi_panic(reason, __FILE__, __LINE__);
1134 MountGlobalDrives();
1137 ServiceStatus.dwCurrentState = SERVICE_RUNNING;
1138 ServiceStatus.dwWin32ExitCode = NO_ERROR;
1139 ServiceStatus.dwCheckPoint = 0;
1140 ServiceStatus.dwWaitHint = 0;
1142 /* accept Power events */
1143 ServiceStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_POWEREVENT;
1144 SetServiceStatus(StatusHandle, &ServiceStatus);
1147 HANDLE h; char *ptbuf[1];
1148 h = RegisterEventSource(NULL, AFS_DAEMON_EVENT_NAME);
1149 ptbuf[0] = "AFS running";
1150 ReportEvent(h, EVENTLOG_INFORMATION_TYPE, 0, 0, NULL, 1, 0, ptbuf, NULL);
1151 DeregisterEventSource(h);
1155 WaitForSingleObject(WaitToTerminate, INFINITE);
1158 HANDLE h; char *ptbuf[1];
1159 h = RegisterEventSource(NULL, AFS_DAEMON_EVENT_NAME);
1160 ptbuf[0] = "AFS quitting";
1161 ReportEvent(h, GlobalStatus ? EVENTLOG_ERROR_TYPE : EVENTLOG_INFORMATION_TYPE,
1162 0, 0, NULL, 1, 0, ptbuf, NULL);
1163 DeregisterEventSource(h);
1166 DismountGlobalDrives();
1170 #ifdef REGISTER_POWER_NOTIFICATIONS
1171 /* terminate thread used to flush cache */
1172 if (powerEventsRegistered)
1173 PowerNotificationThreadExit();
1176 /* Remove the ExceptionFilter */
1177 SetUnhandledExceptionFilter(NULL);
1179 ServiceStatus.dwCurrentState = SERVICE_STOPPED;
1180 ServiceStatus.dwWin32ExitCode = GlobalStatus ? ERROR_EXCEPTION_IN_SERVICE : NO_ERROR;
1181 ServiceStatus.dwCheckPoint = 0;
1182 ServiceStatus.dwWaitHint = 0;
1183 ServiceStatus.dwControlsAccepted = 0;
1184 SetServiceStatus(StatusHandle, &ServiceStatus);
1187 DWORD __stdcall afsdMain_thread(void* notUsed)
1189 char * argv[2] = {AFS_DAEMON_SERVICE_NAME, NULL};
1190 afsd_Main(1, (LPTSTR*)argv);
1197 static SERVICE_TABLE_ENTRY dispatchTable[] = {
1198 {AFS_DAEMON_SERVICE_NAME, (LPSERVICE_MAIN_FUNCTION) afsd_Main},
1202 if (!StartServiceCtrlDispatcher(dispatchTable))
1204 LONG status = GetLastError();
1205 if (status == ERROR_FAILED_SERVICE_CONTROLLER_CONNECT)
1208 hAFSDMainThread = CreateThread(NULL, 0, afsdMain_thread, 0, 0, &tid);
1210 printf("Hit <Enter> to terminate OpenAFS Client Service\n");
1212 SetEvent(WaitToTerminate);
1216 if ( hAFSDMainThread ) {
1217 WaitForSingleObject( hAFSDMainThread, INFINITE );
1218 CloseHandle( hAFSDMainThread );