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 cacheSize = CM_CONFIGDEFAULT_CACHESIZE;
823 DWORD verifyServiceSig = TRUE;
826 hPSAPI = LoadLibrary("psapi");
828 if ( hPSAPI == NULL )
831 if (!GetModuleFileName(NULL, filename, sizeof(filename)))
834 if (GetVersionInfo(filename, afsdVersion, sizeof(afsdVersion)))
837 afsi_log("%s version %s", filename, afsdVersion);
839 if (((FARPROC) pGetModuleFileNameExA =
840 GetProcAddress( hPSAPI, "GetModuleFileNameExA" )) == NULL ||
841 ((FARPROC) pEnumProcessModules =
842 GetProcAddress( hPSAPI, "EnumProcessModules" )) == NULL)
849 code = RegOpenKeyEx(HKEY_LOCAL_MACHINE,
850 "SYSTEM\\CurrentControlSet\\Services\\TransarcAFSDaemon\\Parameters",
851 0, KEY_QUERY_VALUE, &parmKey);
852 if (code == ERROR_SUCCESS) {
853 dummyLen = sizeof(cacheSize);
854 code = RegQueryValueEx(parmKey, "CacheSize", NULL, NULL,
855 (BYTE *) &cacheSize, &dummyLen);
856 RegCloseKey (parmKey);
859 code = RegOpenKeyEx(HKEY_LOCAL_MACHINE, "SOFTWARE\\OpenAFS\\Client",
860 0, KEY_QUERY_VALUE, &parmKey);
861 if (code == ERROR_SUCCESS) {
862 dummyLen = sizeof(verifyServiceSig);
863 code = RegQueryValueEx(parmKey, "VerifyServiceSignature", NULL, NULL,
864 (BYTE *) &verifyServiceSig, &dummyLen);
865 RegCloseKey (parmKey);
868 if (verifyServiceSig && cacheSize < 716800) {
869 trustVerified = VerifyTrust(filename);
871 afsi_log("Signature Verification disabled");
877 // get a certificate context for the signer of afsd_service.
878 pCtxService = GetCertCtx(filename);
880 LogCertCtx(pCtxService);
883 // Get a list of all the modules in this process.
884 hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ,
885 FALSE, GetCurrentProcessId());
887 if (pEnumProcessModules(hProcess, hMods, sizeof(hMods), &cbNeeded))
889 afsi_log("Num of Process Modules: %d", (cbNeeded / sizeof(HMODULE)));
891 for (i = 0; i < (cbNeeded / sizeof(HMODULE)); i++)
893 char szModName[2048];
895 // Get the full path to the module's file.
896 if (pGetModuleFileNameExA(hProcess, hMods[i], szModName, sizeof(szModName)))
898 lstrcpy(checkName, szModName);
901 if ( strstr(checkName, "afspthread.dll") ||
902 strstr(checkName, "afsauthent.dll") ||
903 strstr(checkName, "afsrpc.dll") ||
904 strstr(checkName, "libafsconf.dll") ||
905 strstr(checkName, "libosi.dll") )
907 if (GetVersionInfo(szModName, modVersion, sizeof(modVersion))) {
912 afsi_log("%s version %s", szModName, modVersion);
913 if (strcmp(afsdVersion,modVersion)) {
914 afsi_log("Version mismatch: %s", szModName);
917 if ( trustVerified ) {
918 if ( !VerifyTrust(szModName) ) {
919 afsi_log("Signature Verification failed: %s", szModName);
922 else if (pCtxService) {
923 PCCERT_CONTEXT pCtx = GetCertCtx(szModName);
925 if (!pCtx || !pCertCompareCertificate(X509_ASN_ENCODING | PKCS_7_ASN_ENCODING,
926 pCtxService->pCertInfo,
928 afsi_log("Certificate mismatch: %s", szModName);
936 pCertFreeCertificateContext(pCtx);
945 pCertFreeCertificateContext(pCtxService);
951 CloseHandle(hProcess);
955 typedef BOOL ( APIENTRY * AfsdInitHook )(void);
956 #define AFSD_INIT_HOOK "AfsdInitHook"
957 #define AFSD_HOOK_DLL "afsdhook.dll"
960 control serviceex exists only on 2000/xp. These functions will be loaded dynamically.
963 typedef SERVICE_STATUS_HANDLE ( * RegisterServiceCtrlHandlerExFunc )( LPCTSTR , LPHANDLER_FUNCTION_EX , LPVOID );
964 typedef SERVICE_STATUS_HANDLE ( * RegisterServiceCtrlHandlerFunc )( LPCTSTR , LPHANDLER_FUNCTION );
966 RegisterServiceCtrlHandlerExFunc pRegisterServiceCtrlHandlerEx = NULL;
967 RegisterServiceCtrlHandlerFunc pRegisterServiceCtrlHandler = NULL;
969 void afsd_Main(DWORD argc, LPTSTR *argv)
978 AfsdInitHook initHook;
981 _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF /*| _CRTDBG_CHECK_ALWAYS_DF*/ |
982 _CRTDBG_CHECK_CRT_DF /* | _CRTDBG_DELAY_FREE_MEM_DF */ );
985 osi_InitPanic(afsd_notifier);
986 osi_InitTraceOption();
992 WaitToTerminate = CreateEvent(NULL, TRUE, FALSE, TEXT("afsd_service_WaitToTerminate"));
993 if ( GetLastError() == ERROR_ALREADY_EXISTS )
994 afsi_log("Event Object Already Exists: %s", TEXT("afsd_service_WaitToTerminate"));
997 hAdvApi32 = LoadLibrary("advapi32.dll");
998 if (hAdvApi32 == NULL)
1000 afsi_log("Fatal: cannot load advapi32.dll");
1004 pRegisterServiceCtrlHandlerEx = (RegisterServiceCtrlHandlerExFunc)GetProcAddress(hAdvApi32, "RegisterServiceCtrlHandlerExA");
1005 if (pRegisterServiceCtrlHandlerEx)
1007 afsi_log("running on 2000+ - using RegisterServiceCtrlHandlerEx");
1008 StatusHandle = RegisterServiceCtrlHandlerEx(AFS_DAEMON_SERVICE_NAME, afsd_ServiceControlHandlerEx, NULL );
1012 StatusHandle = RegisterServiceCtrlHandler(AFS_DAEMON_SERVICE_NAME, afsd_ServiceControlHandler);
1015 ServiceStatus.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
1016 ServiceStatus.dwServiceSpecificExitCode = 0;
1017 ServiceStatus.dwCurrentState = SERVICE_START_PENDING;
1018 ServiceStatus.dwWin32ExitCode = NO_ERROR;
1019 ServiceStatus.dwCheckPoint = 1;
1020 ServiceStatus.dwWaitHint = 30000;
1021 /* accept Power Events */
1022 ServiceStatus.dwControlsAccepted = SERVICE_ACCEPT_POWEREVENT;
1023 SetServiceStatus(StatusHandle, &ServiceStatus);
1027 HANDLE h; char *ptbuf[1];
1028 h = RegisterEventSource(NULL, AFS_DAEMON_EVENT_NAME);
1029 ptbuf[0] = "AFS start pending";
1030 ReportEvent(h, EVENTLOG_INFORMATION_TYPE, 0, 0, NULL, 1, 0, ptbuf, NULL);
1031 DeregisterEventSource(h);
1034 #ifdef REGISTER_POWER_NOTIFICATIONS
1041 /* see if we should handle power notifications */
1042 code = RegOpenKeyEx(HKEY_LOCAL_MACHINE, AFSConfigKeyName, 0, KEY_QUERY_VALUE, &hkParm);
1043 if (code == ERROR_SUCCESS) {
1044 dummyLen = sizeof(bpower);
1045 code = RegQueryValueEx(hkParm, "FlushOnHibernate", NULL, NULL,
1046 (BYTE *) &bpower, &dummyLen);
1048 if(code != ERROR_SUCCESS)
1051 RegCloseKey(hkParm);
1053 /* create thread used to flush cache */
1055 PowerNotificationThreadCreate();
1056 powerEventsRegistered = 1;
1061 /* Verify the versions of the DLLs which were loaded */
1062 if (!AFSModulesVerify()) {
1063 ServiceStatus.dwCurrentState = SERVICE_STOPPED;
1064 ServiceStatus.dwWin32ExitCode = NO_ERROR;
1065 ServiceStatus.dwCheckPoint = 0;
1066 ServiceStatus.dwWaitHint = 0;
1067 ServiceStatus.dwControlsAccepted = 0;
1068 SetServiceStatus(StatusHandle, &ServiceStatus);
1070 /* exit if initialization failed */
1074 /* allow an exit to be called prior to any initialization */
1075 hInitHookDll = LoadLibrary(AFSD_HOOK_DLL);
1078 BOOL hookRc = FALSE;
1079 initHook = ( AfsdInitHook ) GetProcAddress(hInitHookDll, AFSD_INIT_HOOK);
1082 hookRc = initHook();
1084 FreeLibrary(hInitHookDll);
1085 hInitHookDll = NULL;
1087 if (hookRc == FALSE)
1089 ServiceStatus.dwCurrentState = SERVICE_STOPPED;
1090 ServiceStatus.dwWin32ExitCode = NO_ERROR;
1091 ServiceStatus.dwCheckPoint = 0;
1092 ServiceStatus.dwWaitHint = 0;
1093 ServiceStatus.dwControlsAccepted = 0;
1094 SetServiceStatus(StatusHandle, &ServiceStatus);
1096 /* exit if initialization failed */
1101 /* allow another 15 seconds to start */
1102 ServiceStatus.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
1103 ServiceStatus.dwServiceSpecificExitCode = 0;
1104 ServiceStatus.dwCurrentState = SERVICE_START_PENDING;
1105 ServiceStatus.dwWin32ExitCode = NO_ERROR;
1106 ServiceStatus.dwCheckPoint = 2;
1107 ServiceStatus.dwWaitHint = 20000;
1108 /* accept Power Events */
1109 ServiceStatus.dwControlsAccepted = SERVICE_ACCEPT_POWEREVENT;
1110 SetServiceStatus(StatusHandle, &ServiceStatus);
1115 MainThreadId = GetCurrentThreadId();
1116 jmpret = setjmp(notifier_jmp);
1121 code = afsd_InitCM(&reason);
1123 afsi_log("afsd_InitCM failed: %s (code = %d)", reason, code);
1124 osi_panic(reason, __FILE__, __LINE__);
1128 ServiceStatus.dwCheckPoint++;
1129 ServiceStatus.dwWaitHint -= 5000;
1130 SetServiceStatus(StatusHandle, &ServiceStatus);
1132 code = afsd_InitDaemons(&reason);
1134 afsi_log("afsd_InitDaemons failed: %s (code = %d)", reason, code);
1135 osi_panic(reason, __FILE__, __LINE__);
1139 ServiceStatus.dwCheckPoint++;
1140 ServiceStatus.dwWaitHint -= 5000;
1141 SetServiceStatus(StatusHandle, &ServiceStatus);
1143 code = afsd_InitSMB(&reason, MessageBox);
1145 afsi_log("afsd_InitSMB failed: %s (code = %d)", reason, code);
1146 osi_panic(reason, __FILE__, __LINE__);
1149 MountGlobalDrives();
1152 ServiceStatus.dwCurrentState = SERVICE_RUNNING;
1153 ServiceStatus.dwWin32ExitCode = NO_ERROR;
1154 ServiceStatus.dwCheckPoint = 0;
1155 ServiceStatus.dwWaitHint = 0;
1157 /* accept Power events */
1158 ServiceStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_POWEREVENT;
1159 SetServiceStatus(StatusHandle, &ServiceStatus);
1162 HANDLE h; char *ptbuf[1];
1163 h = RegisterEventSource(NULL, AFS_DAEMON_EVENT_NAME);
1164 ptbuf[0] = "AFS running";
1165 ReportEvent(h, EVENTLOG_INFORMATION_TYPE, 0, 0, NULL, 1, 0, ptbuf, NULL);
1166 DeregisterEventSource(h);
1170 WaitForSingleObject(WaitToTerminate, INFINITE);
1173 HANDLE h; char *ptbuf[1];
1174 h = RegisterEventSource(NULL, AFS_DAEMON_EVENT_NAME);
1175 ptbuf[0] = "AFS quitting";
1176 ReportEvent(h, GlobalStatus ? EVENTLOG_ERROR_TYPE : EVENTLOG_INFORMATION_TYPE,
1177 0, 0, NULL, 1, 0, ptbuf, NULL);
1178 DeregisterEventSource(h);
1181 DismountGlobalDrives();
1185 #ifdef REGISTER_POWER_NOTIFICATIONS
1186 /* terminate thread used to flush cache */
1187 if (powerEventsRegistered)
1188 PowerNotificationThreadExit();
1191 /* Remove the ExceptionFilter */
1192 SetUnhandledExceptionFilter(NULL);
1194 ServiceStatus.dwCurrentState = SERVICE_STOPPED;
1195 ServiceStatus.dwWin32ExitCode = GlobalStatus ? ERROR_EXCEPTION_IN_SERVICE : NO_ERROR;
1196 ServiceStatus.dwCheckPoint = 0;
1197 ServiceStatus.dwWaitHint = 0;
1198 ServiceStatus.dwControlsAccepted = 0;
1199 SetServiceStatus(StatusHandle, &ServiceStatus);
1202 DWORD __stdcall afsdMain_thread(void* notUsed)
1204 char * argv[2] = {AFS_DAEMON_SERVICE_NAME, NULL};
1205 afsd_Main(1, (LPTSTR*)argv);
1212 static SERVICE_TABLE_ENTRY dispatchTable[] = {
1213 {AFS_DAEMON_SERVICE_NAME, (LPSERVICE_MAIN_FUNCTION) afsd_Main},
1217 if (!StartServiceCtrlDispatcher(dispatchTable))
1219 LONG status = GetLastError();
1220 if (status == ERROR_FAILED_SERVICE_CONTROLLER_CONNECT)
1223 hAFSDMainThread = CreateThread(NULL, 0, afsdMain_thread, 0, 0, &tid);
1225 printf("Hit <Enter> to terminate OpenAFS Client Service\n");
1227 SetEvent(WaitToTerminate);
1231 if ( hAFSDMainThread ) {
1232 WaitForSingleObject( hAFSDMainThread, INFINITE );
1233 CloseHandle( hAFSDMainThread );