Beispiel #1
1
BOOL InitApp (LPSTR pszCmdLineA)
{
   BOOL fShow = FALSE;
   BOOL fQuiet = FALSE;
   BOOL fExit = FALSE;
   BOOL fInstall = FALSE;
   BOOL fUninstall = FALSE;
   BOOL fAutoInit = FALSE;
   BOOL fNetDetect = FALSE;
   BOOL fRenewMaps = FALSE;

   // Initialize our global variables and window classes
   //
   memset (&g, 0x00, sizeof(g));
   g.fStartup = TRUE;

   // Parse the command-line
   //
   while (pszCmdLineA && *pszCmdLineA)
      {
      if ((*pszCmdLineA != '-') && (*pszCmdLineA != '/'))
         break;

      switch (*(++pszCmdLineA))
         {
         case 'a':
         case 'A':
            fAutoInit = TRUE;
            break;

         case 'm':
         case 'M':
            fRenewMaps = TRUE;
            break;

         case 'n':
         case 'N':
            fNetDetect = TRUE;
            break;

         case 's':
         case 'S':
            fShow = TRUE;
            break;

         case 'q':
         case 'Q':
            fQuiet = TRUE;
            break;

         case 'e':
         case 'E':
            fExit = TRUE;
            break;

         case 'i':
         case 'I':
            fInstall = TRUE;
            break;

         case 'u':
         case 'U':
            fUninstall = TRUE;
            break;

         case ':':
             CopyAnsiToString(g.SmbName,pszCmdLineA);
			 MapShareName(pszCmdLineA);
			 break;

         case 'z':
         case 'Z':
             DoUnMapShare(TRUE);
             return(0);

         case 'x':
         case 'X':
             TestAndDoMapShare(SERVICE_START_PENDING);
             TestAndDoMapShare(SERVICE_RUNNING);
             return 0;
         }

      while (*pszCmdLineA && (*pszCmdLineA != ' '))
         ++pszCmdLineA;
	  if (*pszCmdLineA==' ') ++pszCmdLineA;
      }

   if (fInstall)
      Shortcut_FixStartup (cszSHORTCUT_NAME, g.fStartup = TRUE);
   else if (fUninstall)
      Shortcut_FixStartup (cszSHORTCUT_NAME, g.fStartup = FALSE);

   if (fInstall || fUninstall)
      {
      HKEY hk;
      if (RegCreateKeyEx (HKEY_CURRENT_USER, AFSREG_USER_OPENAFS_SUBKEY, 0, NULL, 0,
                         (IsWow64()?KEY_WOW64_64KEY:0)|KEY_WRITE, NULL, &hk, NULL) == 0)
         {
         DWORD dwSize = sizeof(g.fStartup);
         DWORD dwType = REG_DWORD;
         RegSetValueEx (hk, TEXT("ShowTrayIcon"), NULL, dwType, (PBYTE)&g.fStartup, dwSize);
         RegCloseKey (hk);
         }
      }

   // Only show up if there's not another version of this app around already.
   //
   for (HWND hSearch = GetWindow (GetDesktopWindow(), GW_CHILD);
        hSearch && IsWindow(hSearch);
        hSearch = GetWindow (hSearch, GW_HWNDNEXT))
      {
      TCHAR szClassName[ cchRESOURCE ];
      if (GetClassName (hSearch, szClassName, cchRESOURCE))
         {
         if (!lstrcmpi (szClassName, cszCLASSNAME))
            {
            if (fShow)
               PostMessage (hSearch, WM_COMMAND, M_ACTIVATE, 0);
            else if (fExit)
               PostMessage (hSearch, WM_COMMAND, M_TERMINATE_NOW, 0);
            else if (fUninstall)
               PostMessage (hSearch, WM_COMMAND, M_TERMINATE_NOW, 0);
            return FALSE;
            }
         }
      }

   if (fExit || fUninstall || fInstall)
      return FALSE;

   HKEY hk;
    if (RegOpenKeyEx (HKEY_CURRENT_USER, AFSREG_USER_OPENAFS_SUBKEY, 0,
                       (IsWow64()?KEY_WOW64_64KEY:0)|KEY_QUERY_VALUE, &hk) == 0)
    {
        DWORD dwSize = sizeof(g.fStartup);
        DWORD dwType = REG_DWORD;
        RegQueryValueEx (hk, TEXT("ShowTrayIcon"), NULL, &dwType, (PBYTE)&g.fStartup, &dwSize);
        RegCloseKey (hk);
    }
    else if (RegOpenKeyEx (HKEY_LOCAL_MACHINE, AFSREG_CLT_OPENAFS_SUBKEY, 0,
                            (IsWow64()?KEY_WOW64_64KEY:0)|KEY_QUERY_VALUE, &hk) == 0)
      {
      DWORD dwSize = sizeof(g.fStartup);
      DWORD dwType = REG_DWORD;
      RegQueryValueEx (hk, TEXT("ShowTrayIcon"), NULL, &dwType, (PBYTE)&g.fStartup, &dwSize);
      RegCloseKey (hk);
      }

   Shortcut_FixStartup (cszSHORTCUT_NAME, g.fStartup);

   // Is this Windows NT?
   //
   OSVERSIONINFO Version;
   memset (&Version, 0x00, sizeof(Version));
   Version.dwOSVersionInfoSize = sizeof(Version);
   if (GetVersionEx (&Version))
      g.fIsWinNT = (Version.dwPlatformId == VER_PLATFORM_WIN32_NT) ? TRUE : FALSE;

   if (!g.fIsWinNT)
      lstrcpy (g.szHelpFile, TEXT("afs-light.hlp"));
   else
      lstrcpy (g.szHelpFile, TEXT("afs-nt.hlp"));

   // Initialize winsock etc
   //
   WSADATA Data;
   WSAStartup (0x0101, &Data);

   InitCommonControls();
   RegisterCheckListClass();
   osi_Init();
   lock_InitializeMutex(&g.expirationCheckLock, "expiration check lock", 0);
   lock_InitializeMutex(&g.credsLock, "global creds lock", 0);

   KFW_AFS_wait_for_service_start();

   if ( IsDebuggerPresent() ) {
       if ( !g.fIsWinNT )
           OutputDebugString("No Service Present on non-NT systems\n");
       else {
           if ( IsServiceRunning() )
               OutputDebugString("AFSD Service started\n");
           else {
               OutputDebugString("AFSD Service stopped\n");
               if ( !IsServiceConfigured() )
                   OutputDebugString("AFSD Service not configured\n");
               else if ( fAutoInit )
                   OutputDebugString("AFSD Service will be started\n");
           }
       }
   }

    // If the service isn't started yet, and autoInit start the service
    if ( g.fIsWinNT && !IsServiceRunning() && IsServiceConfigured() && fAutoInit ) {
        SC_HANDLE hManager;

        if ((hManager = OpenSCManager( NULL, NULL,
                                       SC_MANAGER_CONNECT |
                                       SC_MANAGER_ENUMERATE_SERVICE |
                                       SC_MANAGER_QUERY_LOCK_STATUS)) != NULL )
        {
            SC_HANDLE hService;
            if ((hService = OpenService( hManager, TEXT("TransarcAFSDaemon"),
                                         SERVICE_QUERY_STATUS | SERVICE_START) ) != NULL)
            {
                if (StartService(hService, 0, 0)) {
                    if ( IsDebuggerPresent() )
                        OutputDebugString("AFSD Service start successful\n");
                    fRenewMaps = TRUE;
                } else if ( IsDebuggerPresent() )
                    OutputDebugString("AFSD Service start failed\n");

                CloseServiceHandle (hService);
            }

            CloseServiceHandle (hManager);
        }
        KFW_AFS_wait_for_service_start();
    }

    KFW_initialize();

   // Create a main window. All further initialization will be done during
   // processing of WM_INITDIALOG.
   //
   WNDCLASS wc;
   if (!GetClassInfo (NULL, WC_DIALOG, &wc))   // Get dialog class info
      return FALSE;
   wc.hInstance = THIS_HINST;
   wc.hIcon = TaLocale_LoadIcon (IDI_MAIN);
   wc.lpszClassName = cszCLASSNAME;
   wc.style |= CS_GLOBALCLASS;
   RegisterClass(&wc);

   g.hMain = ModelessDialog (IDD_MAIN, NULL, (DLGPROC)Main_DlgProc);
   if (g.hMain == NULL)
      return FALSE;

   // If the service isn't started yet, show our startup wizard.
   //
   if (!IsServiceRunning() && !fQuiet)
      {
      if (!g.fIsWinNT)
         Message (MB_ICONHAND, IDS_UNCONFIG_TITLE_95, IDS_UNCONFIG_DESC_95);
      else if (IsServiceConfigured())
         ShowStartupWizard();
      else if (!IsServerInstalled())
         Message (MB_ICONHAND, IDS_UNCONFIG_TITLE, IDS_UNCONFIG_DESC);
      }
   if (IsServiceRunning()) {
      if ( fRenewMaps )
      {
          if ( IsDebuggerPresent() )
              OutputDebugString("Renewing Drive Maps\n");
          DoMapShareChange(FALSE);
      }
      if (fShow)
      {
      if ( IsDebuggerPresent() )
          OutputDebugString("Displaying Main window\n");
      Main_Show (TRUE);
      }
      // If the root cell is reachable and we have no tokens
      // display the Obtain Tokens dialog to the user
      if ( fAutoInit ) {
          if ( IsDebuggerPresent() )
              OutputDebugString("Obtaining Tokens (if needed)\n");
          ObtainTokensFromUserIfNeeded(g.hMain);
      }
   } else if ( IsDebuggerPresent() )
       OutputDebugString("AFSD Service Stopped\n");

    if ( fNetDetect ) {
        // Start IP Address Change Monitor
        if ( IsDebuggerPresent() )
            OutputDebugString("Activating Network Change Monitor\n");
        IpAddrChangeMonitorInit(g.hMain);
    }
    Main_EnableRemindTimer(TRUE);
    return TRUE;
}
Beispiel #2
0
BOOL CALLBACK Main_DlgProc (HWND hDlg, UINT msg, WPARAM wp, LPARAM lp)
{
   static UINT msgCheckTerminate = 0;
   if (msgCheckTerminate == 0)
      msgCheckTerminate = RegisterWindowMessage (TEXT("AfsCredsCheckTerminate"));

   if (msg == msgCheckTerminate)
      {
      Main_OnCheckTerminate();
      }
   else switch (msg)
      {
      case WM_INITDIALOG:
         g.hMain = hDlg;
         Main_OnInitDialog (hDlg);
         break;

      case WM_DESTROY:
         Creds_CloseLibraries();
         ChangeTrayIcon (NIM_DELETE);
         break;

      case WM_ACTIVATEAPP:
         if (wp)
            {
            Main_RepopulateTabs (FALSE);
            }
         break;

      case WM_COMMAND:
         switch (LOWORD(wp))
            {
            case IDOK:
            case IDCANCEL:
               Main_Show (FALSE);
               break;

            case M_ACTIVATE:
               if (g.fIsWinNT || IsServiceRunning())
                  {
                  if (!lp) // Got here from "/show" parameter? switch tabs.
                     {
                     HWND hTab = GetDlgItem (g.hMain, IDC_TABS);
                     TabCtrl_SetCurSel (hTab, 0);
                     Main_OnSelectTab();
                     }
                  Main_Show (TRUE);
                  }
               else
                  {
                  Message (MB_ICONHAND, IDS_UNCONFIG_TITLE_95, IDS_UNCONFIG_DESC_95);
                  }
               break;

            case M_TERMINATE:
               if (g.fIsWinNT && IsServiceRunning())
                  ModalDialog (IDD_TERMINATE, NULL, (DLGPROC)Terminate_DlgProc);
               else if (g.fIsWinNT)
                  ModalDialog (IDD_TERMINATE_SMALL, NULL, (DLGPROC)Terminate_DlgProc);
               else // (!g.fIsWinNT)
                  ModalDialog (IDD_TERMINATE_SMALL_95, NULL, (DLGPROC)Terminate_DlgProc);
               break;

            case M_TERMINATE_NOW:
               Quit();
               break;

            case M_REMIND:
               Main_OnCheckMenuRemind();
               break;
            }
         break;

      case WM_TIMER:
         Main_OnRemindTimer();
         break;

      case WM_NOTIFY:
         switch (((NMHDR*)lp)->code)
            {
            case TCN_SELCHANGE:
               Main_OnSelectTab();
               break;
            }
         break;

      case WM_TRAYICON:
         switch (lp)
            {
            case WM_LBUTTONDOWN:
               if (IsServiceRunning() || !IsServiceConfigured())
                  Main_Show (TRUE);
               else if (!g.fIsWinNT)
                  Message (MB_ICONHAND, IDS_UNCONFIG_TITLE_95, IDS_UNCONFIG_DESC_95);
               else
                  ShowStartupWizard();
               break;

            case WM_RBUTTONDOWN:
               HMENU hm;
               if ((hm = TaLocale_LoadMenu (MENU_TRAYICON)) != 0)
                  {
                  POINT pt;
                  GetCursorPos(&pt);

                  HMENU hmDummy = CreateMenu();
                  InsertMenu (hmDummy, 0, MF_POPUP, (UINT)hm, NULL);

                  BOOL fRemind = FALSE;
                  lock_ObtainMutex(&g.credsLock);
                  for (size_t iCreds = 0; iCreds < g.cCreds; ++iCreds)
                     {
                     if (g.aCreds[ iCreds ].fRemind)
                        fRemind = TRUE;
                     }
                  lock_ReleaseMutex(&g.credsLock);
                  CheckMenuItem (hm, M_REMIND, MF_BYCOMMAND | ((fRemind) ? MF_CHECKED : MF_UNCHECKED));
		  SetForegroundWindow(hDlg);
                  TrackPopupMenu (GetSubMenu (hmDummy, 0),
                                  TPM_RIGHTALIGN | TPM_RIGHTBUTTON,
                                  pt.x, pt.y, NULL, hDlg, NULL);
		  PostMessage(hDlg, WM_NULL, 0, 0);
                  DestroyMenu (hmDummy);
                  }
               break;

            case WM_MOUSEMOVE:
               Main_OnMouseOver();
               break;
            }
         break;
      case WM_OBTAIN_TOKENS:
          if ( InterlockedIncrement (&g.fShowingMessage) != 1 )
              InterlockedDecrement (&g.fShowingMessage);
          else
              ShowObtainCreds (wp, (char *)lp);
          GlobalFree((void *)lp);
          break;

      case WM_START_SERVICE:
          {
              SC_HANDLE hManager;
              if ((hManager = OpenSCManager ( NULL, NULL, 
                                              SC_MANAGER_CONNECT |
                                              SC_MANAGER_ENUMERATE_SERVICE |
                                              SC_MANAGER_QUERY_LOCK_STATUS)) != NULL)
              {
                  SC_HANDLE hService;
                  if ((hService = OpenService ( hManager, TEXT("TransarcAFSDaemon"), 
                                                SERVICE_QUERY_STATUS | SERVICE_START)) != NULL)
                  {
                      if (StartService (hService, 0, 0))
                          TestAndDoMapShare(SERVICE_START_PENDING);
		      if ( KFW_is_available() && KFW_AFS_wait_for_service_start() ) {
#ifdef USE_MS2MIT
			  KFW_import_windows_lsa();
#endif /* USE_MS2MIT */
			  KFW_AFS_renew_tokens_for_all_cells();
		      }

                      CloseServiceHandle (hService);
                  }

                  CloseServiceHandle (hManager);
              }
              if (KFW_AFS_wait_for_service_start())
		  ObtainTokensFromUserIfNeeded(g.hMain);
          }
          break;
      }

   return FALSE;
}
Beispiel #3
0
DWORD APIENTRY NPLogonNotify(
	PLUID lpLogonId,
	LPCWSTR lpAuthentInfoType,
	LPVOID lpAuthentInfo,
	LPCWSTR lpPreviousAuthentInfoType,
	LPVOID lpPreviousAuthentInfo,
	LPWSTR lpStationName,
	LPVOID StationHandle,
	LPWSTR *lpLogonScript)
{
    char uname[MAX_USERNAME_LENGTH]="";
    char password[MAX_PASSWORD_LENGTH]="";
    char logonDomain[MAX_DOMAIN_LENGTH]="";
    char cell[256]="<non-integrated logon>";
    char homePath[MAX_PATH]="";
    char szLogonId[128] = "";

    MSV1_0_INTERACTIVE_LOGON *IL;

    DWORD code = 0, code2;

    int pw_exp;
    char *reason;
    char *ctemp;

    BOOLEAN interactive;
    BOOLEAN flag;
    DWORD LSPtype, LSPsize;
    HKEY NPKey;

    HWND hwndOwner = (HWND)StationHandle;

    BOOLEAN afsWillAutoStart;

    BOOLEAN lowercased_name = TRUE;

    LogonOptions_t opt; /* domain specific logon options */
    int retryInterval;
    int sleepInterval;

    /* Are we interactive? */
    interactive = (wcsicmp(lpStationName, L"WinSta0") == 0);

#ifdef DISABLE_NON_INTERACTIVE
    /* Do not do anything if the logon session is not interactive. */
    if (!interactive)
	return 0;
#endif

    (void) RegOpenKeyEx(HKEY_LOCAL_MACHINE, AFSREG_CLT_SVC_PARAM_SUBKEY,
                         0, KEY_QUERY_VALUE, &NPKey);
    LSPsize=sizeof(TraceOption);
    RegQueryValueEx(NPKey, REG_CLIENT_TRACE_OPTION_PARM, NULL,
                     &LSPtype, (LPBYTE)&TraceOption, &LSPsize);

    RegCloseKey (NPKey);

    DebugEvent("NPLogonNotify - LoginId(%d,%d)", lpLogonId->HighPart, lpLogonId->LowPart);

    /* Make sure the AFS Libraries are initialized */
    AfsLogonInit();

    /* Initialize Logon Script to none */
    *lpLogonScript=NULL;
    
    /* MSV1_0_INTERACTIVE_LOGON and KERB_INTERACTIVE_LOGON are equivalent for
     * our purposes */

    if ( wcsicmp(lpAuthentInfoType,L"MSV1_0:Interactive") && 
         wcsicmp(lpAuthentInfoType,L"Kerberos:Interactive") )
    {
        DebugEvent("Unsupported Authentication Info Type: %S",
                   lpAuthentInfoType);
        return 0;
    }

    IL = (MSV1_0_INTERACTIVE_LOGON *) lpAuthentInfo;

    /* Convert from Unicode to ANSI */

    /*TODO: Use SecureZeroMemory to erase passwords */
    if (!UnicodeStringToANSI(IL->UserName, uname, MAX_USERNAME_LENGTH) ||
	 !UnicodeStringToANSI(IL->Password, password, MAX_PASSWORD_LENGTH) ||
	 !UnicodeStringToANSI(IL->LogonDomainName, logonDomain, MAX_DOMAIN_LENGTH))
 	return 0;

    /* Make sure AD-DOMANS sent from login that is sent to us is striped */
    ctemp = strchr(uname, '@');
    if (ctemp) *ctemp = 0;

    /* is the name all lowercase? */
    for ( ctemp = uname; *ctemp ; ctemp++) {
        if ( !islower(*ctemp) ) {
            lowercased_name = FALSE;
            break;
        }
    }

    /*
     * Get Logon options
     */

    GetDomainLogonOptions( lpLogonId, uname, logonDomain, &opt );
    retryInterval = opt.retryInterval;
    sleepInterval = opt.sleepInterval;
    *lpLogonScript = opt.logonScript;

    if (retryInterval < sleepInterval)
        sleepInterval = retryInterval;

    DebugEvent("Got logon script: %S",opt.logonScript);

    afsWillAutoStart = AFSWillAutoStart();

    DebugEvent("LogonOption[%x], Service AutoStart[%d]",
                opt.LogonOption,afsWillAutoStart);
    
    /* Check for zero length password if integrated logon*/
    if ( ISLOGONINTEGRATED(opt.LogonOption) )  {
        if ( password[0] == 0 ) {
            DebugEvent0("Password is the empty string");
            code = GT_PW_NULL;
            reason = "zero length password is illegal";
            code=0;
        }

        /* Get cell name if doing integrated logon.  
           We might overwrite this if we are logging into an AD realm and we find out that
           the user's home dir is in some other cell. */
        DebugEvent("About to call cm_GetRootCellName(%s)",cell);
        code = cm_GetRootCellName(cell);
        if (code < 0) { 
            DebugEvent0("Unable to obtain Root Cell");
            code = KTC_NOCELL;
            reason = "unknown cell";
            code=0;
        } else {
            DebugEvent("Cell is %s",cell);
        }       

        /* We get the user's home directory path, if applicable, though we can't lookup the
           cell right away because the client service may not have started yet. This call
           also sets the AD_REALM flag in opt.flags if applicable. */
        if (ISREMOTE(opt.flags)) {
            DebugEvent0("Is Remote");
            GetAdHomePath(homePath,MAX_PATH,lpLogonId,&opt);
        }
    }

    /* loop until AFS is started. */
    if (afsWillAutoStart) {
	while (IsServiceRunning() || IsServiceStartPending()) {
	    DebugEvent("while(autostart) LogonOption[%x], Service AutoStart[%d]",
			opt.LogonOption,afsWillAutoStart);

	    if (ISADREALM(opt.flags)) {
		code = GetFileCellName(homePath,cell,256);
		if (!code) {
		    DebugEvent("profile path [%s] is in cell [%s]",homePath,cell);
		}
		/* Don't bail out if GetFileCellName failed.
		 * The home dir may not be in AFS after all. 
		 */
	    } else
		code=0;
		
	    /* if Integrated Logon  */
	    if (ISLOGONINTEGRATED(opt.LogonOption))
	    {			
		if ( KFW_is_available() ) {
		    SetEnvironmentVariable(DO_NOT_REGISTER_VARNAME, "");
                    if (opt.realm) {
			char * principal, *p;
			size_t len, tlen;

			StringCchLength(opt.realm, MAX_DOMAIN_LENGTH, &tlen);
			len = tlen;
			StringCchLength(uname, MAX_USERNAME_LENGTH, &tlen);
			len += tlen + 2;

			/* tlen is now the length of uname in characters */
			principal = (char *)malloc(len * sizeof(char));
			if ( principal ) {
			    StringCchCopy(principal, len, uname);
			    p = principal + tlen;
			    *p++ = '@';
                            StringCchCopy(p, len - tlen -1, opt.realm);
                            code = KFW_AFS_get_cred(principal, cell, password, 0, opt.smbName, &reason);
                            DebugEvent("KFW_AFS_get_cred  uname=[%s] smbname=[%s] cell=[%s] code=[%d]",
					    principal,opt.smbName,cell,code);
			    free(principal);
			}
                    } else {
                        code = KFW_AFS_get_cred(uname, cell, password, 0, opt.smbName, &reason);
                        DebugEvent("KFW_AFS_get_cred  uname=[%s] smbname=[%s] cell=[%s] code=[%d]",
                                    uname,opt.smbName,cell,code);
                    }
		    SetEnvironmentVariable(DO_NOT_REGISTER_VARNAME, NULL);
		    if (code == 0 && opt.theseCells) { 
			char * principal, *p;
			size_t len, tlen;

			StringCchLength(opt.realm ? opt.realm : cell, MAX_DOMAIN_LENGTH, &tlen);
			len = tlen;
			StringCchLength(uname, MAX_USERNAME_LENGTH, &tlen);
			len += tlen + 2;

			/* tlen is now the length of uname in characters */
			principal = (char *)malloc(len * sizeof(char));
			if ( principal ) {
			    StringCchCopy(principal, len, uname);
			    p = principal + tlen;
			    *p++ = '@';
                            if (opt.realm) {
                                StringCchCopy(p, len - tlen -1, opt.realm);
                            } else {
                                StringCchCopy(p, len - tlen - 1, cell);
                                for ( ;*p; p++) {
                                    *p = toupper(*p);
                                }
                            }
			    p = opt.theseCells;
			    while ( *p ) {
                                if ( cm_stricmp_utf8(p, cell) ) {
                                    SetEnvironmentVariable(DO_NOT_REGISTER_VARNAME, "");
                                    code2 = KFW_AFS_get_cred(principal, p, 0, 0, opt.smbName, &reason);
                                    SetEnvironmentVariable(DO_NOT_REGISTER_VARNAME, NULL);
                                    DebugEvent("KFW_AFS_get_cred  uname=[%s] smbname=[%s] cell=[%s] code=[%d]",
                                               principal,opt.smbName,p,code2);
                                }
				p += strlen(p) + 1;
			    }
			    free(principal);
			}
		    }
		} else {
		    code = ka_UserAuthenticateGeneral2(KA_USERAUTH_VERSION+KA_USERAUTH_AUTHENT_LOGON,
							uname, "", cell, password, opt.smbName, 0, &pw_exp, 0,
							&reason);
		    DebugEvent("AFS AfsLogon - (INTEGRATED only)ka_UserAuthenticateGeneral2 Code[%x] uname[%s] smbname=[%s] Cell[%s] PwExp=[%d] Reason=[%s]",
				code,uname,opt.smbName,cell,pw_exp,reason?reason:"");
		}       
		if ( code && code != KTC_NOCM && code != KTC_NOCMRPC && !lowercased_name ) {
		    for ( ctemp = uname; *ctemp ; ctemp++) {
			*ctemp = tolower(*ctemp);
		    }
		    lowercased_name = TRUE;
		    goto sleeping;
		}

		/* is service started yet?*/

		/* If we've failed because the client isn't running yet and the
		 * client is set to autostart (and therefore it makes sense for
		 * us to wait for it to start) then sleep a while and try again. 
		 * If the error was something else, then give up. */
		if (code != KTC_NOCM && code != KTC_NOCMRPC)
		    break;
	    }
	    else {  
		/*JUST check to see if its running*/
		if (IsServiceRunning())
		    break;
		if (!IsServiceStartPending()) {
		    code = KTC_NOCMRPC;
		    reason = "AFS Service start failed";
		    break;
		}
	    }

	    /* If the retry interval has expired and we still aren't
	     * logged in, then just give up if we are not in interactive
	     * mode or the failSilently flag is set, otherwise let the
	     * user know we failed and give them a chance to try again. */
	    if (retryInterval <= 0) {
		reason = "AFS not running";
		if (!interactive || opt.failSilently)
		    break;
		flag = MessageBox(hwndOwner,
				   "AFS is still starting.  Retry?",
				   "AFS Logon",
				   MB_ICONQUESTION | MB_RETRYCANCEL);
		if (flag == IDCANCEL)
		    break;

		/* Wait just a little while and try again */
		retryInterval = opt.retryInterval;
	    }

	  sleeping:
	    Sleep(sleepInterval * 1000);
	    retryInterval -= sleepInterval;
	}
    }
    DebugEvent0("while loop exited");

    /* remove any kerberos 5 tickets currently held by the SYSTEM account
     * for this user 
     */

    if (ISLOGONINTEGRATED(opt.LogonOption) && KFW_is_available()) {
#ifdef KFW_LOGON
	sprintf(szLogonId,"%d.%d",lpLogonId->HighPart, lpLogonId->LowPart);
	KFW_AFS_copy_cache_to_system_file(uname, szLogonId);
#endif
	KFW_AFS_destroy_tickets_for_principal(uname);
    }

    if (code) {
	char msg[128];
	HANDLE h;
	char *ptbuf[1];

	StringCbPrintf(msg, sizeof(msg), "Integrated login failed: %s", reason);

	if (ISLOGONINTEGRATED(opt.LogonOption) && interactive && !opt.failSilently)
	    MessageBox(hwndOwner, msg, "AFS Logon", MB_OK);

	h = RegisterEventSource(NULL, AFS_LOGON_EVENT_NAME);
	ptbuf[0] = msg;
	ReportEvent(h, EVENTLOG_WARNING_TYPE, 0, 1008, NULL,
		     1, 0, ptbuf, NULL);
	DeregisterEventSource(h);
	    
        code = MapAuthError(code);
        SetLastError(code);

        if (ISLOGONINTEGRATED(opt.LogonOption) && (code!=0))
        {
            if (*lpLogonScript)
                LocalFree(*lpLogonScript);
            *lpLogonScript = NULL;
            if (!afsWillAutoStart)	// its not running, so if not autostart or integrated logon then just skip
                code = 0;
        }
    }

    if (opt.theseCells) free(opt.theseCells);
    if (opt.smbName) free(opt.smbName);
    if (opt.realm) free(opt.realm);

    DebugEvent("AFS AfsLogon - Exit","Return Code[%x]",code);
    return code;
}