Esempio n. 1
0
static inline void __RemoveFromPath(const TCHAR *path) {
  HKEY env_hkey;
  LONG reg_open_return = RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("System\\CurrentControlSet\\Control\\Session Manager\\Environment"), 0, KEY_ALL_ACCESS, &env_hkey);
  if (reg_open_return == ERROR_SUCCESS) {
    DWORD path_original_length;
    RegQueryValueEx(env_hkey, _T("Path"), NULL, NULL, NULL, &path_original_length);
    TCHAR *path_original = (TCHAR *)malloc(path_original_length + sizeof(TCHAR));
    RegQueryValueEx(env_hkey, _T("Path"), NULL, NULL, (LPBYTE)path_original, &path_original_length);
    path_original_length /= sizeof(TCHAR);
    int path_length = 0;
    TCHAR *path_pos;
    if (path_pos = FindPathInsidePath(path, path_original, &path_length)) {
      TCHAR *path_new = (TCHAR *)malloc((path_original_length - path_length + 1) * sizeof(TCHAR));
      _tcsnccpy(path_new, path_original, path_pos - path_original);
      _tcsnccpy(path_new + (path_pos - path_original), _T(";"), 1);
      _tcsnccpy(path_new + (path_pos - path_original) + 1, path_pos + path_length, path_original + path_original_length - path_pos - path_length);
      TCHAR *path_final = path_new;
      while (path_final < path_new + _tcslen(path_new)) {
        if (*path_final == _T(';')) {
          path_final++;
        } else {
          break;
        }
      }
      int path_final_size = _tcslen(path_final);
      while (path_final_size > 0) {
        if (*(path_final + path_final_size - 1) == _T(';')) {
          path_final_size--;
        } else {
          break;
        }
      }
      path_final[path_final_size] = _T('\0');
      path_final_size++; // RegSetValueEx required NULL terminated size
      path_final_size *= sizeof(TCHAR);

      RegSetValueEx(env_hkey, _T("Path"), 0, REG_EXPAND_SZ, (LPBYTE)path_final, path_final_size);
    } else {
      _ftprintf(stderr, _T("Path already removed"));
    }
    RegCloseKey(env_hkey);
    SendMessageTimeout(HWND_BROADCAST, WM_SETTINGCHANGE, 0, (LPARAM)"Environment", SMTO_ABORTIFHUNG, 3000, NULL);
    SendMessageTimeout(HWND_BROADCAST, WM_SETTINGCHANGE, 0, (LPARAM)L"Environment", SMTO_ABORTIFHUNG, 3000, NULL);

  } else {
    _ftprintf(stderr, _T("Key opened error."));
  }
}
Esempio n. 2
0
static inline void __AddToPath(const TCHAR *path) {
  HKEY env_hkey;
  LONG reg_open_return = RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("System\\CurrentControlSet\\Control\\Session Manager\\Environment"), 0, KEY_ALL_ACCESS, &env_hkey);
  if (reg_open_return == ERROR_SUCCESS) {
    DWORD path_original_length;
    RegQueryValueEx(env_hkey, _T("Path"), NULL, NULL, NULL, &path_original_length);
    TCHAR *path_original = (TCHAR *)malloc(path_original_length + sizeof(TCHAR));
    LONG c = RegQueryValueEx(env_hkey, _T("Path"), NULL, NULL, (LPBYTE)path_original, &path_original_length);
    path_original_length /= sizeof(TCHAR);
    TCHAR *path_pos;
    if (path_pos = FindPathInsidePath(path, path_original, NULL)) {
      _ftprintf(stderr, _T("Path already added"));
    } else {
      _ftprintf(stderr, _T("%s\n with length %ld"), path_original, path_original_length);
      TCHAR *path_new = (TCHAR *)malloc((path_original_length + _tcslen(path) + 1) * sizeof(TCHAR));
      _tcsnccpy(path_new, path_original, path_original_length);
      _tcscpy(path_new + path_original_length - 1, _T(";"));
      _tcscpy(path_new + path_original_length, path);
      RegSetValueEx(env_hkey, _T("Path"), 0, REG_EXPAND_SZ, (LPBYTE)path_new, (path_original_length + _tcslen(path) + 1) * sizeof(TCHAR));
    }
    RegCloseKey(env_hkey);
    SendMessageTimeout(HWND_BROADCAST, WM_SETTINGCHANGE, 0, (LPARAM)"Environment", SMTO_ABORTIFHUNG, 3000, NULL);
    SendMessageTimeout(HWND_BROADCAST, WM_SETTINGCHANGE, 0, (LPARAM)L"Environment", SMTO_ABORTIFHUNG, 3000, NULL);
  } else {
    _ftprintf(stderr, _T("Key opened error."));
  }
}
Esempio n. 3
0
int platform_makeDir(const char *path)
{
    LPSECURITY_ATTRIBUTES lpSecurityAttributes = NULL;
    int   bSuccess    = 0;
    DWORD dwLastError = 0;

    const BOOL bCD = CreateDirectory(path, lpSecurityAttributes);

    if (!bCD)
    {
        dwLastError = GetLastError();
    }
    else
    {
        return 0;
    }

    switch (dwLastError)
    {
    case ERROR_ALREADY_EXISTS:
        bSuccess = 1;
        break;

    case ERROR_PATH_NOT_FOUND:
       {
           TCHAR   szPrev[MAX_PATH] = { 0 };
           LPCTSTR szLast           = _tcsrchr(path, '\\');
           _tcsnccpy(szPrev, path, (int)(szLast - path));
           if (!platform_makeDir(szPrev))
           {
               bSuccess = CreateDirectory(path, lpSecurityAttributes) != 0;
               if (!bSuccess)
               {
                   bSuccess = (GetLastError() == ERROR_ALREADY_EXISTS);
               }
           }
           else
           {
               bSuccess = 0;
           }
       }
       break;

    default:
        bSuccess = 0;
        break;
    }

    return bSuccess ? 0 : -1;
}
Esempio n. 4
0
void CServiceModule::Init(HINSTANCE h, LPCTSTR lpszServiceName, const GUID* plibid)
{
    CComModule::Init(ObjectMap, h, plibid);

    m_bService = TRUE;

	_tcsnccpy(m_szServiceName, lpszServiceName, sizeof(m_szServiceName) / sizeof(TCHAR));
   // LoadString(h, nServiceNameID, m_szServiceName, sizeof(m_szServiceName) / sizeof(TCHAR));

    // set up the initial service status 
    m_hServiceStatus = NULL;
    m_status.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
    m_status.dwCurrentState = SERVICE_STOPPED;
    m_status.dwControlsAccepted = SERVICE_ACCEPT_STOP;
    m_status.dwWin32ExitCode = 0;
    m_status.dwServiceSpecificExitCode = 0;
    m_status.dwCheckPoint = 0;
    m_status.dwWaitHint = 0;
}
Esempio n. 5
0
int CreateService(const TCHAR *pszStartStopName,
                  const TCHAR *pszDisplayName,
                  int iServiceType,
                  int iStartType,
                  const TCHAR *pszBinPath,
                  const TCHAR *pszLoadOrderGroup,
                  const TCHAR *pszDependencies,
                  const TCHAR *pszLogonUser,
                  const TCHAR *pszLogonPassword)
{
    int rc = ERROR_SUCCESS;

    _tprintf(_T("Installing service %ws (%ws) ...\n"), pszDisplayName, pszStartStopName);

    SC_HANDLE hSCManager = OpenSCManager (NULL, NULL, SC_MANAGER_ALL_ACCESS);
    if (hSCManager == NULL)
    {
        _tprintf(_T("Could not get handle to SCM! Error: %ld\n"), GetLastError());
        return EXIT_FAIL;
    }

    /* Fixup end of multistring. */
    TCHAR szDepend[ _MAX_PATH ] = { 0 }; /* @todo Use dynamically allocated string here! */
    if (pszDependencies != NULL)
    {
        _tcsnccpy (szDepend, pszDependencies, wcslen(pszDependencies));
        DWORD len = (DWORD)wcslen (szDepend);
        szDepend [len + 1] = 0;

        /* Replace comma separator on null separator. */
        for (DWORD i = 0; i < len; i++)
        {
            if (',' == szDepend [i])
                szDepend [i] = 0;
        }
    }

    DWORD dwTag = 0xDEADBEAF;
    SC_HANDLE hService = CreateService (hSCManager,           /* SCManager database handle. */
                                        pszStartStopName,     /* Name of service. */
                                        pszDisplayName,       /* Name to display. */
                                        SERVICE_ALL_ACCESS,   /* Desired access. */
                                        iServiceType,         /* Service type. */
                                        iStartType,           /* Start type. */
                                        SERVICE_ERROR_NORMAL, /* Error control type. */
                                        pszBinPath,           /* Service's binary. */
                                        pszLoadOrderGroup,    /* Ordering group. */
                                        (pszLoadOrderGroup != NULL) ? &dwTag : NULL,           /* Tag identifier. */
                                        (pszDependencies != NULL) ? szDepend : NULL,           /* Dependencies. */
                                        (pszLogonUser != NULL) ? pszLogonUser: NULL,           /* Account. */
                                        (pszLogonPassword != NULL) ? pszLogonPassword : NULL); /* Password. */
    if (NULL == hService)
    {
        DWORD dwErr = GetLastError();
        switch (dwErr)
        {

        case ERROR_SERVICE_EXISTS:
        {
            _tprintf(_T("Service already exists. No installation required. Updating the service config.\n"));

            hService = OpenService (hSCManager,          /* SCManager database handle. */
                                    pszStartStopName,    /* Name of service. */
                                    SERVICE_ALL_ACCESS); /* Desired access. */
            if (NULL == hService)
            {
                dwErr = GetLastError();
                _tprintf(_T("Could not open service! Error: %ld\n"), dwErr);
            }
            else
            {
                BOOL fResult = ChangeServiceConfig (hService,            /* Service handle. */
                                                   iServiceType,         /* Service type. */
                                                   iStartType,           /* Start type. */
                                                   SERVICE_ERROR_NORMAL, /* Error control type. */
                                                   pszBinPath,           /* Service's binary. */
                                                   pszLoadOrderGroup,    /* Ordering group. */
                                                   (pszLoadOrderGroup != NULL) ? &dwTag : NULL,          /* Tag identifier. */
                                                   (pszDependencies != NULL) ? szDepend : NULL,          /* Dependencies. */
                                                   (pszLogonUser != NULL) ? pszLogonUser: NULL,          /* Account. */
                                                   (pszLogonPassword != NULL) ? pszLogonPassword : NULL, /* Password. */
                                                   pszDisplayName);      /* Name to display. */
                if (fResult)
                    _tprintf(_T("The service config has been successfully updated.\n"));
                else
                {
                    dwErr = GetLastError();
                    _tprintf(_T("Could not change service config! Error: %ld\n"), dwErr);
                }
                CloseServiceHandle(hService);
            }

            /*
             * This entire branch do not return an error to avoid installations failures,
             * if updating service parameters. Better to have a running system with old
             * parameters and the failure information in the installation log.
             */
            break;
        }

        case ERROR_INVALID_PARAMETER:

            _tprintf(_T("Invalid parameter specified!\n"));
            rc = EXIT_FAIL;
            break;

        default:

            _tprintf(_T("Could not create service! Error: %ld\n"), dwErr);
            rc = EXIT_FAIL;
            break;
        }

        if (rc == EXIT_FAIL)
            goto cleanup;
    }
    else
    {
        CloseServiceHandle (hService);
        _tprintf(_T("Installation of service successful!\n"));
    }

cleanup:

    if (hSCManager != NULL)
        CloseServiceHandle (hSCManager);

    return rc;
}
Esempio n. 6
0
LONG GetJobNumber (PROCESS_INFORMATION *pProcessInfo, LPCTSTR Command)

/* Create a job number for the new process, and enter
	the new process information into the job database. */

/* The job database is maintained in a shared file in the C:\temp directory.
	The name is a combination of the user name and ".JobMgt".
	The file is created at the time of the first job and deleted
	when the last job is killed.
	This file is shared by all the job management functions. 
	The file is assumed to be "small" (< 4 GB). If the file
	is large, the code will fail in several places, but there
	is protection to limit the number of jobs (arbitrarily, but
	not unreasonably) to 10000 (MAX_JOBS_ALLOWED).
	Return -1 in case of failure. */
{
	HANDLE hJobData, hProcess;
	JM_JOB JobRecord;
	DWORD JobNumber = 0, nXfer, ExitCode;
	DWORD FsLow, FsHigh;
	TCHAR JobMgtFileName [MAX_PATH];
	OVERLAPPED RegionStart;
	
	if (!GetJobMgtFileName (JobMgtFileName)) return -1;
	hJobData = CreateFile (JobMgtFileName, GENERIC_READ | GENERIC_WRITE,
			FILE_SHARE_READ | FILE_SHARE_WRITE,
			NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
	if (hJobData == INVALID_HANDLE_VALUE) {
		ReportError (_T ("Failed to open Job DB."), 0, TRUE);
		return -1;
	}

	/*  Lock the entire file plus one record for exclusive
		access as we will be making a new entry. Note how it
	    is necessary (and possible!) to lock beyond the current
		end of file. Doing so prevents concurrent attempts to add
		a new record at the end of the file. */

	RegionStart.Offset = 0;
	RegionStart.OffsetHigh = 0;
	RegionStart.hEvent = (HANDLE)0;
	FsLow = GetFileSize (hJobData, &FsHigh);
	LockFileEx (hJobData, LOCKFILE_EXCLUSIVE_LOCK,
		0, FsLow + SJM_JOB, FsHigh, &RegionStart);

	__try { /* Assure that the region is unlocked. */

	/* Read records to find empty slot (corresponding to the job number).
		Extend the file to create a new job number if required. */

	while (JobNumber < MAX_JOBS_ALLOWED &&
		ReadFile (hJobData, &JobRecord, SJM_JOB, &nXfer, NULL) && (nXfer > 0)) {
		if (JobRecord.ProcessId == 0) break;

		/* Also use this slot if corresponding job has ended. */

		hProcess = OpenProcess (PROCESS_ALL_ACCESS, FALSE, JobRecord.ProcessId);
		if (hProcess == NULL) break;
		if (GetExitCodeProcess (hProcess, &ExitCode)
			&& CloseHandle (hProcess) && (ExitCode != STILL_ACTIVE))
			break;

		JobNumber++;
	}

	/* Either an empty slot has been found, or we are at end
		of the file and need to create a new one, or we've
	    exceeded the max number of jobs. */
	if (JobNumber >= MAX_JOBS_ALLOWED) return -1;

	if (nXfer != 0)		/* Not at end of file. Back up a record. */
		SetFilePointer (hJobData, -(LONG) SJM_JOB, NULL, FILE_CURRENT);
					/* Enter the new Job record. */
	JobRecord.ProcessId = pProcessInfo->dwProcessId;
	_tcsnccpy (JobRecord.CommandLine, Command, MAX_PATH);
	WriteFile (hJobData, &JobRecord, SJM_JOB, &nXfer, NULL);
	}

	__finally {		/* Release the lock on the file. */
		UnlockFileEx (hJobData, 0, FsLow + SJM_JOB, FsHigh, &RegionStart);
		CloseHandle (hJobData);
	}
	return JobNumber + 1;
}
Esempio n. 7
0
        // FNSplit differs from fnsplit in that it can split the path without
        // splitting a DBCS character whose trail byte can have the value of
        // 0x5C that also represents '\\' in the ASCII set.
        Int16u FNSplit(const char * pathP, 
                       char       * driveP,
                       char       * dirP, 
                       char       * nameP, 
                       char       * extP)
        {
            register char   * pB;
            register Int16u Wrk;
            Int16u Ret;
            char buf[MAXPATH + 2];

            //Set all string to default value zero
            Ret = 0;
            if (driveP)
                *driveP = 0;
            if (dirP)
                *dirP = 0;
            if (nameP)
                *nameP = 0;
            if (extP)
                *extP = 0;

            // Copy filename into template up to MAXPATH characters
            pB = buf;
            while (*pathP == ' ')
                pathP++;

            if ((Wrk = lstrlen(pathP)) > MAXPATH)
                Wrk = MAXPATH;
            pB [0] = 0;  // put a stopper at string beginning
            _tcsnccpy(pB + 1, pathP, Wrk);
            pB [++Wrk] = '\0';

            // forward-scan pathname and record occurences of '/', '\\', or '.'
            TokenIndexList * slashList = 0,
                           * bkSlashList = 0,
                           * dotList = 0;

            RegisterTokens (slashList, pB, '/');
            RegisterTokens (bkSlashList, pB, '\\');
            RegisterTokens (dotList, pB, '.');
    
            //Split the filename and fill corresponding nonzero pointers
            Int16s index = Wrk;
            Wrk = 0; // from this point on, Wrk serves as a Boolean flag
                     // indicating whether a directory is detected
            for ( ; ; )
            {
                --index;
                switch (pB [index])
                {
                    case '.'  :
                        if (!IsAsciiToken (dotList, index))
                            continue;

                        if (!Wrk && (pB [index + 1] == '\0'))
                            Wrk = IsDirDot(slashList, bkSlashList, pB, index);

                        if ((!Wrk) && ((Ret & EXTENSION) == 0))
                        {
                            Ret |= EXTENSION;
                            CopyIt (extP, pB + index, MAXEXT - 1);
                            pB [index] = 0;
                        }
                        continue;

                    case ':'  :
                        if (index != 2) // i.e., if not second char
                            continue;

                    case '\0' :
                        if (Wrk) // directory exists
                        {
                            if (pB [index + 1])
                                Ret |= DIRECTORY;
                            CopyIt(dirP, pB + index + 1, MAXDIR - 1);
                            pB [index + 1] = 0;
    
                            Int16u dirL = lstrlen (dirP);
                            if (dirL == 0)
                                break;

                            switch (dirP [dirL - 1])
                            {
                                case '\\':
                                    if (IsAsciiToken (bkSlashList, index + dirL))
                                        break;

                                case '/':
                                    if (IsAsciiToken (slashList, index + dirL))
                                        break;

                                default: // add trailing slash
                                    dirP [dirL] = '\\';
                                    dirP [dirL + 1] = '\0';
                            }
                            break;
                        }

                    case '/'  :
                    case '\\' :
                        if (!Wrk && (pB [index] == '\0' ||
                            IsAsciiToken (pB [index] == '/' ? slashList : bkSlashList, index)))
                        {
                            Wrk++;
                            if (pB [index + 1])
                                Ret |= FILENAME;
                            CopyIt(nameP, pB + index + 1, MAXFILE - 1);
                            pB [index + 1] = 0;
                            if (pB [index] == 0 ||
                                (pB [index] == ':' && index == 2))
                            break;
                        }
                        continue;

                    case '*'  :
                    case '?'  :
                        if (!Wrk)
                            Ret |= WILDCARDS;
                    default :
                        continue;
                } // switch
                break;
            } // for

            if (pB [2] == ':')
            {
                if (pB [0])
                    Ret |= DRIVE;
                CopyIt(driveP, &pB [1], MAXDRIVE - 1);
            }   

            DeleteIndexList (slashList);
            DeleteIndexList (bkSlashList);
            DeleteIndexList (dotList);

            return (Ret);
        }
Esempio n. 8
0
/**
 * @brief Find directory inside a Windows-style PATH variable
 *
 * @param dir directory to find
 * @param path PATH variable
 * @param size the pointer to size to store size of directory name, can be set to NULL
 * @param rawsize the pointer to size of raw version of dir
 * @return The position the first to be removed
 */
static inline TCHAR *FindPathInsidePath(const TCHAR *dir, const TCHAR *path, int *size) {
  TCHAR *dir_copy = (TCHAR *)malloc((_tcslen(dir) + 1) * sizeof(TCHAR));
  memset(dir_copy, 0, (_tcslen(dir) + 1) * sizeof(TCHAR));
  _tcsnccpy(dir_copy, dir, _tcslen(dir));
  for (TCHAR *dir_iterator = dir_copy + _tcslen(dir) - 1; dir_iterator > dir_copy; dir_iterator--) {
    if (*dir_iterator == _T('\\')) {
      dir_iterator[0] = _T('\0');
    } else {
      break;
    }
  }
  int raw_size = _tcslen(dir_copy);
  TCHAR *remain_string = (TCHAR *)path;
  TCHAR *return_string = NULL;
  int return_size = _tcslen(dir_copy);
  while (remain_string < path + _tcslen(path)) {
    remain_string = _tcsstr(remain_string, dir_copy);
    if (!remain_string) { // No search found
      break;
    }
    if (remain_string >= path) {
      if (*(remain_string - 1) == _T(';')) { // prefix ';'
        return_string = remain_string - 1;
        return_size++;
      } else {
        return_string = remain_string;
      }
      if (*(remain_string + _tcslen(dir_copy)) == _T('\\')) { // postfix '\\'
        return_size++;
        if (*(remain_string + _tcslen(dir_copy) + 1) == _T(';')) { // postfix '\\;'
          return_size++;
          break;
        } else {
          if (return_string + return_size >= path + _tcslen(path)) {
            break;
          } else {
            return_string = NULL;
            return_size = _tcslen(dir_copy);
            remain_string += _tcslen(dir_copy);
            continue;
          }
        }
      } else if (*(remain_string + _tcslen(dir_copy)) == _T(';')) { // postfix ';'
        return_size++;
        break;
      } else {
        if (return_string + return_size >= path + _tcslen(path)) {
          break;
        } else {
          return_string = NULL;
          return_size = _tcslen(dir_copy);
          remain_string += _tcslen(dir_copy);
          continue;
        }
      }
    }
  }
  free(dir_copy);
  if (size) {
    *size = return_size;
  }
  return return_string;
}
Esempio n. 9
0
BOOL CALLBACK DlgProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
	TCHAR *disk=new TCHAR[3];
	TCHAR m[]={'\\'};
	DWORD type;
	switch(message)
	{
	case WM_CLOSE:
		EndDialog(hWnd, 0);
		return TRUE;
	case WM_INITDIALOG:
		hCbox=CreateWindow(TEXT("COMBOBOX"),TEXT(""),WS_CHILD|WS_VISIBLE|CBS_SORT|CBS_DROPDOWNLIST,10,10,200,80,hWnd,HMENU(100),0,0);
		hInfo=CreateWindow(TEXT("STATIC"),TEXT("File system"),WS_CHILD|WS_VISIBLE,210,10,200,200,hWnd,HMENU(1000),0,0);
		disk_list=GetLogicalDrives();
		for (int i=0;i<26;++i)
			if (disk_list&(1<<i)){
				TCHAR r[30];
				TCHAR a[30];
				_tcscpy(r,TEXT(" :\\ "));
				r[0] = static_cast<wchar_t>(65+i);
				type=GetDriveType(r);
				switch (type)
				{
				case DRIVE_UNKNOWN:
					_tcscpy(a,TEXT("DRIVE_UNKNOWN"));
					break;
				case DRIVE_NO_ROOT_DIR:
					_tcscpy(a,TEXT("DRIVE_NO_ROOT_DIR"));
					break;
				case DRIVE_REMOVABLE:
					_tcscpy(a,TEXT("DRIVE_REMOVABLE"));
					break;
				case DRIVE_FIXED:
					_tcscpy(a,TEXT("DRIVE_FIXED"));
					break;
				case DRIVE_REMOTE:
					_tcscpy(a,TEXT("DRIVE_REMOTE"));
					break;
				case DRIVE_CDROM:
					_tcscpy(a,TEXT("DRIVE_CDROM"));
					break;
				case DRIVE_RAMDISK:
					_tcscpy(a,TEXT("DRIVE_RAMDISK"));
					break;
				}
				_tcscat(r,a);
				SendMessage(hCbox,CB_ADDSTRING,0,LPARAM(r));
			}
			return TRUE;
	case WM_COMMAND:
		if (LOWORD(wParam)==100){
			DWORD ch=SendMessage(hCbox,CB_GETCURSEL,0,0);
			if (ch<4) {
				TCHAR buf[40];
				SendMessage(hCbox,CB_GETLBTEXT,ch,LPARAM(buf));
				TCHAR disk[4],disk1[4];
				_tcsnccpy(disk,buf,3);
				TCHAR kbuf[256];
				disk[3]='\0';
				BOOL b=GetVolumeInformation(disk,0,0,0,0,0,kbuf,256);
				
				if (b)
					SetWindowText(hInfo,kbuf);
			}
		}

		return TRUE;
	default:
		return FALSE;
	}
}