コード例 #1
0
ファイル: process.c プロジェクト: codoranro/tinc
bool remove_service(void) {
	manager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
	if(!manager) {
		logger(LOG_ERR, "Could not open service manager: %s", winerror(GetLastError()));
		return false;
	}

	service = OpenService(manager, identname, SERVICE_ALL_ACCESS);

	if(!service) {
		logger(LOG_ERR, "Could not open %s service: %s", identname, winerror(GetLastError()));
		return false;
	}

	if(!ControlService(service, SERVICE_CONTROL_STOP, &status))
		logger(LOG_ERR, "Could not stop %s service: %s", identname, winerror(GetLastError()));
	else
		logger(LOG_INFO, "%s service stopped", identname);

	if(!DeleteService(service)) {
		logger(LOG_ERR, "Could not remove %s service: %s", identname, winerror(GetLastError()));
		return false;
	}

	logger(LOG_INFO, "%s service removed", identname);

	return true;
}
コード例 #2
0
ファイル: win_main.c プロジェクト: AvinashKiran/mupdf
void winreplacefile(char *source, char *target)
{
	wchar_t wsource[PATH_MAX];
	wchar_t wtarget[PATH_MAX];

	int sz = MultiByteToWideChar(CP_UTF8, 0, source, -1, wsource, PATH_MAX);
	if (sz == 0)
	{
		winerror(&gapp, "cannot convert filename to Unicode");
		return;
	}

	sz = MultiByteToWideChar(CP_UTF8, 0, target, -1, wtarget, PATH_MAX);
	if (sz == 0)
	{
		winerror(&gapp, "cannot convert filename to Unicode");
		return;
	}

#if (_WIN32_WINNT >= 0x0500)
	ReplaceFile(wtarget, wsource, NULL, REPLACEFILE_IGNORE_MERGE_ERRORS, NULL, NULL);
#else
	DeleteFile(wtarget);
	MoveFile(wsource, wtarget);
#endif
}
コード例 #3
0
ファイル: daemon_test.cpp プロジェクト: Redi0/myCpp11Study
static void WINAPI win_service_main(DWORD argc, LPTSTR *argv)
{
	printf("Service Main\n");
	win_service_status.dwServiceType = SERVICE_WIN32;
	win_service_status.dwControlsAccepted = SERVICE_ACCEPT_STOP;
	win_service_status.dwWin32ExitCode = 0;
	win_service_status.dwServiceSpecificExitCode = 0;
	win_service_status.dwCheckPoint = 0;
	win_service_status.dwWaitHint = 0;

	win_service_status_handle = RegisterServiceCtrlHandler(svcname, win_service_handler);
	if (win_service_status_handle == (SERVICE_STATUS_HANDLE)0)
	{
		winerror(__FILE__, __LINE__, "Failed to Register Service Control Handler");
		return;
	}

	win_service_status.dwCurrentState = SERVICE_START_PENDING;
	if (!SetServiceStatus(win_service_status_handle, &win_service_status))
	{
		winerror(__FILE__, __LINE__, "Failed to Set Service Status");
	}

	/* start server */
	server->Start();
	printf("Run as Daemon Success\n");

	while (true)  Sleep(10000000);

	win_service_status.dwCurrentState = server ? SERVICE_RUNNING : SERVICE_STOPPED;
	if (!SetServiceStatus(win_service_status_handle, &win_service_status))
	{
		winerror(__FILE__, __LINE__, "Failed to Set Service Status");
	}
}
コード例 #4
0
ファイル: daemon_test.cpp プロジェクト: Redi0/myCpp11Study
/** SCM state change handler */
static void WINAPI win_service_handler(DWORD control)
{
	printf("Service Handler %d", control);
	switch (control)
	{
	case SERVICE_CONTROL_INTERROGATE:
		break;
	case SERVICE_CONTROL_SHUTDOWN:
	case SERVICE_CONTROL_STOP:
		if (server)
		{
			win_service_status.dwCurrentState = SERVICE_STOP_PENDING;
			if (!SetServiceStatus(win_service_status_handle, &win_service_status))
			{
				winerror(__FILE__, __LINE__, "Failed to Set Service Status");
			}

			/* shutdown server */
			server->Stop();
		}
		win_service_status.dwCurrentState = SERVICE_STOPPED;
		win_service_status.dwCheckPoint = 0;
		win_service_status.dwWaitHint = 0;
		break;
	}

	if (!SetServiceStatus(win_service_status_handle, &win_service_status))
	{
		winerror(__FILE__, __LINE__, "Failed to Set Service Status");
		printf("Failed to Set Service Status\n");
	}
}
コード例 #5
0
ファイル: unimrcp_service.c プロジェクト: bitbluesky/unimrcp
/** Stop service */
static apt_bool_t uni_service_stop(const char *name)
{
	apt_bool_t status = TRUE;
	SERVICE_STATUS ss_status;
	SC_HANDLE sch_service;
	SC_HANDLE sch_manager = OpenSCManager(0,0,SC_MANAGER_ALL_ACCESS);
	if (!name) name = WIN_SERVICE_NAME;
	if(!sch_manager) {
		winerror("Failed to Open SCManager");
		return FALSE;
	}

	sch_service = OpenService(sch_manager,name,SERVICE_STOP);
	if(!sch_service) {
		winerror("Failed to Open Service");
		CloseServiceHandle(sch_manager);
		return FALSE;
	}

	if(!ControlService(sch_service,SERVICE_CONTROL_STOP,&ss_status)) {
		winerror("Failed to Stop Service");
		status = FALSE;
	} else
		printf("UniMRCP service %s stopped\n", name);

	CloseServiceHandle(sch_service);
	CloseServiceHandle(sch_manager);
	return status;
}
コード例 #6
0
ファイル: unimrcp_service.c プロジェクト: bitbluesky/unimrcp
/** Start service */
static apt_bool_t uni_service_start(const char *name)
{
	apt_bool_t status = TRUE;
	SC_HANDLE sch_service;
	SC_HANDLE sch_manager = OpenSCManager(0,0,SC_MANAGER_ALL_ACCESS);
	if (!name) name = WIN_SERVICE_NAME;
	if(!sch_manager) {
		winerror("Failed to Open SCManager");
		return FALSE;
	}

	sch_service = OpenService(sch_manager,name,SERVICE_START);
	if(!sch_service) {
		winerror("Failed to Open Service");
		CloseServiceHandle(sch_manager);
		return FALSE;
	}

	if(!StartService(sch_service,0,NULL)) {
		winerror("Failed to Start Service");
		status = FALSE;
	} else
		printf("UniMRCP service %s started\n", name);
	CloseServiceHandle(sch_service);
	CloseServiceHandle(sch_manager);
	return status;
}
コード例 #7
0
ファイル: process.c プロジェクト: codoranro/tinc
bool install_service(void) {
	char command[4096] = "\"";
	char **argp;
	bool space;
	SERVICE_DESCRIPTION description = {"Virtual Private Network daemon"};

	manager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
	if(!manager) {
		logger(LOG_ERR, "Could not open service manager: %s", winerror(GetLastError()));
		return false;
	}

	if(!strchr(program_name, '\\')) {
		GetCurrentDirectory(sizeof command - 1, command + 1);
		strncat(command, "\\", sizeof command - strlen(command));
	}

	strncat(command, program_name, sizeof command - strlen(command));

	strncat(command, "\"", sizeof command - strlen(command));

	for(argp = g_argv + 1; *argp; argp++) {
		space = strchr(*argp, ' ');
		strncat(command, " ", sizeof command - strlen(command));
		
		if(space)
			strncat(command, "\"", sizeof command - strlen(command));
		
		strncat(command, *argp, sizeof command - strlen(command));

		if(space)
			strncat(command, "\"", sizeof command - strlen(command));
	}

	service = CreateService(manager, identname, identname,
			SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS, SERVICE_AUTO_START, SERVICE_ERROR_NORMAL,
			command, NULL, NULL, NULL, NULL, NULL);
	
	if(!service) {
		DWORD lasterror = GetLastError();
		logger(LOG_ERR, "Could not create %s service: %s", identname, winerror(lasterror));
		if(lasterror != ERROR_SERVICE_EXISTS)
			return false;
	}

	if(service) {
		ChangeServiceConfig2(service, SERVICE_CONFIG_DESCRIPTION, &description);
		logger(LOG_INFO, "%s service installed", identname);
	} else {
		service = OpenService(manager, identname, SERVICE_ALL_ACCESS);
	}

	if(!StartService(service, 0, NULL))
		logger(LOG_WARNING, "Could not start %s service: %s", identname, winerror(GetLastError()));
	else
		logger(LOG_INFO, "%s service started", identname);

	return true;
}
コード例 #8
0
ファイル: win_main.c プロジェクト: aramobile/CS194-MuPDF
int WINAPI
WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd)
{
	int argc;
	LPWSTR *argv = CommandLineToArgvW(GetCommandLineW(), &argc);
	char argv0[256];
	MSG msg;
	int fd;
	int code;
	fz_context *ctx;

	ctx = fz_new_context(NULL, NULL, FZ_STORE_DEFAULT);
	if (!ctx)
	{
		fprintf(stderr, "cannot initialise context\n");
		exit(1);
	}
	pdfapp_init(ctx, &gapp);

	GetModuleFileNameA(NULL, argv0, sizeof argv0);
	install_app(argv0);

	winopen();

	if (argc == 2)
	{
		wcscpy(wbuf, argv[1]);
	}
	else
	{
		if (!winfilename(wbuf, nelem(wbuf)))
			exit(0);
	}

	fd = _wopen(wbuf, O_BINARY | O_RDONLY, 0666);
	if (fd < 0)
		winerror(&gapp, "cannot open file");

	code = WideCharToMultiByte(CP_UTF8, 0, wbuf, -1, filename, sizeof filename, NULL, NULL);
	if (code == 0)
		winerror(&gapp, "cannot convert filename to utf-8");

	pdfapp_open(&gapp, filename, fd, 0);

	while (GetMessage(&msg, NULL, 0, 0))
	{
		TranslateMessage(&msg);
		DispatchMessage(&msg);
	}

	pdfapp_close(&gapp);

	return 0;
}
コード例 #9
0
ファイル: sysshellcall.c プロジェクト: dvincent/frontier
static boolean getcmdexitcode (Handle hprocess, long *status) {
	
	/*
	2006-03-10 aradke: wait for child process to exit, then get its exit code
	*/
	
	DWORD res;
	boolean fl = true;
	
	*status = 0;
	
	releasethreadglobals ();
	
	res = WaitForSingleObject (hprocess, INFINITE);
	
	grabthreadglobals ();
	
	if (res != WAIT_OBJECT_0)
		goto exit;
		
	fl = GetExitCodeProcess (hprocess, status);
	
	if (!fl)
		winerror ();

exit:	
	CloseHandle (hprocess);
	
	return (fl);
	} /*getcmdexitcode*/
コード例 #10
0
ファイル: error.c プロジェクト: SWI-Prolog/packages-table
int
error_func(int type, const char *pred, int argi, intptr_t argl)
{ switch(type)
  { case ERR_INSTANTIATION:
    { char buf[1024];

      sprintf(buf, "%s: instantiation error on argument %d", pred, argi);
      return PL_warning(buf);
    }
    case ERR_IO:
    { char buf[1024];

#ifdef __WINDOWS__
      char *msg = winerror(argi);
      sprintf(buf, "%s: IO error %s", pred, msg);
      free(msg);
#else
      sprintf(buf, "%s: IO error %s", pred, strerror(argi));
#endif

      return PL_warning(buf);
    }
  }

  return PL_warning("Table package: unknown error");
}
コード例 #11
0
ファイル: win_main.c プロジェクト: n1tehawk/mupdf
char *winpassword(pdfapp_t *app, char *filename)
{
	char buf[1024], *s;
	int code;

	if (password)
	{
		char *p = password;
		password = NULL;
		return p;
	}

	strcpy(buf, filename);
	s = buf;
	if (strrchr(s, '\\')) s = strrchr(s, '\\') + 1;
	if (strrchr(s, '/')) s = strrchr(s, '/') + 1;
	if (strlen(s) > 32)
		strcpy(s + 30, "...");
	sprintf(pd_filename, "The file \"%s\" is encrypted.", s);
	code = DialogBoxW(NULL, L"IDD_DLOGPASS", hwndframe, dlogpassproc);
	if (code <= 0)
		winerror(app, "cannot create password dialog");
	if (pd_okay)
		return pd_password;
	return NULL;
}
コード例 #12
0
ファイル: win_main.c プロジェクト: AvinashKiran/mupdf
int wingetsavepath(pdfapp_t *app, char *buf, int len)
{
	wchar_t twbuf[PATH_MAX];
	OPENFILENAME ofn;

	wcscpy(twbuf, wbuf);
	memset(&ofn, 0, sizeof(OPENFILENAME));
	ofn.lStructSize = sizeof(OPENFILENAME);
	ofn.hwndOwner = hwndframe;
	ofn.lpstrFile = twbuf;
	ofn.nMaxFile = PATH_MAX;
	ofn.lpstrInitialDir = NULL;
	ofn.lpstrTitle = L"MuPDF: Save PDF file";
	ofn.lpstrFilter = L"Documents (*.pdf;*.xps;*.cbz;*.zip)\0*.zip;*.cbz;*.xps;*.pdf\0PDF Files (*.pdf)\0*.pdf\0XPS Files (*.xps)\0*.xps\0CBZ Files (*.cbz;*.zip)\0*.zip;*.cbz\0All Files\0*\0\0";
	ofn.Flags = OFN_HIDEREADONLY;
	if (GetSaveFileName(&ofn))
	{
		int code = WideCharToMultiByte(CP_UTF8, 0, twbuf, -1, buf, MIN(PATH_MAX, len), NULL, NULL);
		if (code == 0)
		{
			winerror(&gapp, "cannot convert filename to utf-8");
			return 0;
		}

		wcscpy(wbuf, twbuf);
		strcpy(filename, buf);
		return 1;
	}
	else
	{
		return 0;
	}
}
コード例 #13
0
ファイル: process.c プロジェクト: codoranro/tinc
VOID WINAPI run_service(DWORD argc, LPTSTR* argv) {
	int err = 1;
	extern int main2(int argc, char **argv);


	status.dwServiceType = SERVICE_WIN32; 
	status.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;
	status.dwWin32ExitCode = 0; 
	status.dwServiceSpecificExitCode = 0; 
	status.dwCheckPoint = 0; 

	statushandle = RegisterServiceCtrlHandlerEx(identname, controlhandler, NULL); 

	if (!statushandle) {
		logger(LOG_ERR, "System call `%s' failed: %s", "RegisterServiceCtrlHandlerEx", winerror(GetLastError()));
		err = 1;
	} else {
		status.dwWaitHint = 30000; 
		status.dwCurrentState = SERVICE_START_PENDING; 
		SetServiceStatus(statushandle, &status);

		status.dwWaitHint = 0; 
		status.dwCurrentState = SERVICE_RUNNING;
		SetServiceStatus(statushandle, &status);

		err = main2(argc, argv);

		status.dwWaitHint = 0;
		status.dwCurrentState = SERVICE_STOPPED; 
		//status.dwWin32ExitCode = err; 
		SetServiceStatus(statushandle, &status);
	}

	return;
}
コード例 #14
0
ファイル: sysshellcall.c プロジェクト: dvincent/frontier
static boolean getcmdshell (Handle *hshell) {

	/*
	2006-03-09 aradke: return name or path of command shell in hshell.
		check the COMSPEC environment variable first. if it does not exist, resort
		to guessing the name of the shell based on the current OS version.
		caller is responsible for disposing the handle if we return true.
	*/
	
	OSVERSIONINFO osinfo;
	bigstring bs;
	
	if (getenvironmentvariable ("COMSPEC", false, hshell))
		return (true);

	osinfo.dwOSVersionInfoSize = sizeof (osinfo);
		
	if (GetVersionEx (&osinfo) == nil) {
		winerror ();
		return (false);
		}

	if (osinfo.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS) {
		copystring ("\x0b" "command.com", bs); /*Win95/98/ME: actual DOS command interpreter*/
		}
	else {
		copystring ("\x07" "cmd.exe", bs); /*WinNT and successors: DOS emulation*/
		}

	return (newtexthandle (bs, hshell));
	} /*getcmdshell*/
コード例 #15
0
ファイル: launcher.c プロジェクト: python-doc-tw/cpython-tw
static void
error(int rc, wchar_t * format, ... )
{
    va_list va;
    wchar_t message[MSGSIZE];
    wchar_t win_message[MSGSIZE];
    int len;

    va_start(va, format);
    len = _vsnwprintf_s(message, MSGSIZE, _TRUNCATE, format, va);

    if (rc == 0) {  /* a Windows error */
        winerror(GetLastError(), win_message, MSGSIZE);
        if (len >= 0) {
            _snwprintf_s(&message[len], MSGSIZE - len, _TRUNCATE, L": %ls",
                         win_message);
        }
    }

#if !defined(_WINDOWS)
    fwprintf(stderr, L"%ls\n", message);
#else
    MessageBox(NULL, message, TEXT("Python Launcher is sorry to say ..."),
               MB_OK);
#endif
    exit(rc);
}
コード例 #16
0
ファイル: x11_main.c プロジェクト: Asido/MuPDF
void winreloadfile(pdfapp_t *app)
{
	int fd;

	pdfapp_close(app);

	fd = open(filename, O_BINARY | O_RDONLY, 0666);
	if (fd < 0)
		winerror(app, fz_throw("cannot reload file '%s'", filename));

	pdfapp_open(app, filename, fd, 1);
}
コード例 #17
0
ファイル: win_main.c プロジェクト: AvinashKiran/mupdf
int winchoiceinput(pdfapp_t *app, int nopts, char *opts[], int *nvals, char *vals[])
{
	int code;
	cd_nopts = nopts;
	cd_nvals = nvals;
	cd_opts = opts;
	cd_vals = vals;
	code = DialogBoxW(NULL, L"IDD_DLOGLIST", hwndframe, dlogchoiceproc);
	if (code <= 0)
		winerror(app, "cannot create text input dialog");
	return pd_okay;
}
コード例 #18
0
ファイル: win_main.c プロジェクト: AvinashKiran/mupdf
char *wintextinput(pdfapp_t *app, char *inittext, int retry)
{
	int code;
	td_retry = retry;
	fz_strlcpy(td_textinput, inittext ? inittext : "", sizeof td_textinput);
	code = DialogBoxW(NULL, L"IDD_DLOGTEXT", hwndframe, dlogtextproc);
	if (code <= 0)
		winerror(app, "cannot create text input dialog");
	if (pd_okay)
		return td_textinput;
	return NULL;
}
コード例 #19
0
ファイル: win_main.c プロジェクト: n1tehawk/mupdf
void wincopyfile(char *source, char *target)
{
	wchar_t wsource[PATH_MAX];
	wchar_t wtarget[PATH_MAX];

	int sz = MultiByteToWideChar(CP_UTF8, 0, source, -1, wsource, PATH_MAX);
	if (sz == 0)
	{
		winerror(&gapp, "cannot convert filename to Unicode");
		return;
	}

	sz = MultiByteToWideChar(CP_UTF8, 0, target, -1, wtarget, PATH_MAX);
	if (sz == 0)
	{
		winerror(&gapp, "cannot convert filename to Unicode");
		return;
	}

	CopyFile(wsource, wtarget, FALSE);
}
コード例 #20
0
ファイル: errstr-Nt.c プロジェクト: 8l/inferno
int
errstr(char *buf, uint nerr)
{
	DWORD le;

	le = GetLastError();
	if(le == Magic)
		utfecpy(buf, buf+nerr, errstring);
	else
		winerror(le, buf, nerr);
	return 1;
}
コード例 #21
0
ファイル: win_main.c プロジェクト: aramobile/CS194-MuPDF
void winreloadfile(pdfapp_t *app)
{
	int fd;

	pdfapp_close(app);

	fd = _wopen(wbuf, O_BINARY | O_RDONLY, 0666);
	if (fd < 0)
		winerror(&gapp, "cannot reload file");

	pdfapp_open(app, filename, fd, 1);
}
コード例 #22
0
ファイル: win_main.c プロジェクト: Asido/MuPDF
void win32error(char *msg)
{
	LPSTR buf;
	int code = GetLastError();
	FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER |
		FORMAT_MESSAGE_FROM_SYSTEM |
		FORMAT_MESSAGE_IGNORE_INSERTS,
		NULL,
		code,
		MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
		(LPSTR)&buf, 0, NULL);
	winerror(&gapp, fz_throw("%s:\n%s", msg, buf));
}
コード例 #23
0
ファイル: daemon_test.cpp プロジェクト: Redi0/myCpp11Study
/** Run SCM service */
void WindowsServiceDaemon(const char *name)
{
	SERVICE_TABLE_ENTRY win_service_table[2];
	svcname = name ? name : WIN_SERVICE_NAME;
	memset(&win_service_table, 0, sizeof(win_service_table));
	win_service_table->lpServiceName = (LPSTR)svcname;
	win_service_table->lpServiceProc = win_service_main;

	printf("Run as Service Daemon : %s\n", svcname);
	if (!StartServiceCtrlDispatcher(win_service_table))
	{
		winerror(__FILE__, __LINE__, "Failed to Connect to SCM");
	}
}
コード例 #24
0
ファイル: win_main.c プロジェクト: Asido/MuPDF
int WINAPI
WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd)
{
	int argc;
	LPWSTR *argv = CommandLineToArgvW(GetCommandLineW(), &argc);
	char argv0[256];
	MSG msg;
	int fd;
	int code;

	fz_accelerate();

	pdfapp_init(&gapp);

	GetModuleFileNameA(NULL, argv0, sizeof argv0);
	install_app(argv0);

	winopen();

	if (argc == 2)
	{
		wcscpy(wbuf, argv[1]);
	}
	else
	{
		if (!winfilename(wbuf, nelem(wbuf)))
			exit(0);
	}

	fd = _wopen(wbuf, O_BINARY | O_RDONLY, 0666);
	if (fd < 0)
		winerror(&gapp, fz_throw("cannot open file '%s'", filename));

	code = WideCharToMultiByte(CP_UTF8, 0, wbuf, -1, filename, sizeof filename, NULL, NULL);
	if (code == 0)
		win32error("cannot convert filename to utf-8");

	pdfapp_open(&gapp, filename, fd, 0);

	while (GetMessage(&msg, NULL, 0, 0))
	{
		TranslateMessage(&msg);
		DispatchMessage(&msg);
	}

	pdfapp_close(&gapp);

	return 0;
}
コード例 #25
0
bool write_packet(vpn_packet_t *packet) {
	long lenout;

	ifdebug(TRAFFIC) logger(LOG_DEBUG, "Writing packet of %d bytes to %s",
			   packet->len, device_info);

	if(!WriteFile (device_handle, packet->data, packet->len, &lenout, NULL)) {
		logger(LOG_ERR, "Error while writing to %s %s: %s", device_info, device, winerror(GetLastError()));
		return false;
	}

	device_total_out += packet->len;

	return true;
}
コード例 #26
0
ファイル: process.c プロジェクト: codoranro/tinc
bool init_service(void) {
	SERVICE_TABLE_ENTRY services[] = {
		{identname, run_service},
		{NULL, NULL}
	};

	if(!StartServiceCtrlDispatcher(services)) {
		if(GetLastError() == ERROR_FAILED_SERVICE_CONTROLLER_CONNECT) {
			return false;
		}
		else
			logger(LOG_ERR, "System call `%s' failed: %s", "StartServiceCtrlDispatcher", winerror(GetLastError()));
	}

	return true;
}
コード例 #27
0
ファイル: sysshellcall.c プロジェクト: dvincent/frontier
static boolean getenvironmentvariable (char *name, boolean flwinerror, Handle *hresult) {
	
	/*
	2006-03-09 aradke: utility function for getting a Windows environment variable
		as a handle without terminating nil char.
	*/
	
	Handle h;
	long res;

	res = GetEnvironmentVariable (name, nil, 0); /*get required space*/

	if (res == 0) {
		if (flwinerror)
			winerror ();
		return (false);
		}

	if (!newclearhandle (res, &h))
		return (false);

	lockhandle (h);

	res = GetEnvironmentVariable (name, *h, res); /*get actual value*/

	unlockhandle (h);
	
	assert (gethandlesize (h) == res + 1);

	if (!sethandlesize (h, res)) {	/*drop trailing nil char*/
		disposehandle (h);
		return (false);
		}

	*hresult = h;
		
	return (true);
	} /*getenvironmentvariable*/
コード例 #28
0
ファイル: tincd.c プロジェクト: Rumko/tinc
int main(int argc, char **argv) {
	program_name = argv[0];

	if(!parse_options(argc, argv))
		return 1;
	
	make_names();

	if(show_version) {
		printf("%s version %s (built %s %s, protocol %d)\n", PACKAGE,
			   VERSION, __DATE__, __TIME__, PROT_CURRENT);
		printf("Copyright (C) 1998-2010 Ivo Timmermans, Guus Sliepen and others.\n"
				"See the AUTHORS file for a complete list.\n\n"
				"tinc comes with ABSOLUTELY NO WARRANTY.  This is free software,\n"
				"and you are welcome to redistribute it under certain conditions;\n"
				"see the file COPYING for details.\n");

		return 0;
	}

	if(show_help) {
		usage(false);
		return 0;
	}

	if(kill_tincd)
		return !kill_other(kill_tincd);

	openlogger("tinc", use_logfile?LOGMODE_FILE:LOGMODE_STDERR);

	g_argv = argv;

	init_configuration(&config_tree);

	/* Slllluuuuuuurrrrp! */

	RAND_load_file("/dev/urandom", 1024);

	ENGINE_load_builtin_engines();
	ENGINE_register_all_complete();

	OpenSSL_add_all_algorithms();

	if(generate_keys) {
		read_server_config();
		return !keygen(generate_keys);
	}

	if(!read_server_config())
		return 1;

#ifdef HAVE_LZO
	if(lzo_init() != LZO_E_OK) {
		logger(LOG_ERR, "Error initializing LZO compressor!");
		return 1;
	}
#endif

#ifdef HAVE_MINGW
	if(WSAStartup(MAKEWORD(2, 2), &wsa_state)) {
		logger(LOG_ERR, "System call `%s' failed: %s", "WSAStartup", winerror(GetLastError()));
		return 1;
	}

	if(!do_detach || !init_service())
		return main2(argc, argv);
	else
		return 1;
}
コード例 #29
0
ファイル: unimrcp_service.c プロジェクト: bitbluesky/unimrcp
/** Register/install service in SCM */
static apt_bool_t uni_service_register(const char *root_dir_path, apr_pool_t *pool,
                                       const char *name,
                                       apt_bool_t autostart,
                                       unsigned long recover,
                                       int log_priority,
                                       const char *disp_name,
                                       const char *description)
{
	apr_status_t status;
	char buf[4096];
	static const size_t len = sizeof(buf);
	size_t pos = 0;
	char *root_dir;
	SERVICE_DESCRIPTION desc;
	SC_HANDLE sch_service;
	SC_HANDLE sch_manager;

	/* Normalize root directory path and make it absolute */
	status = apr_filepath_merge(&root_dir, NULL, root_dir_path,
		APR_FILEPATH_NOTRELATIVE | APR_FILEPATH_NATIVE | APR_FILEPATH_TRUENAME, pool);
	if (status != APR_SUCCESS) {
		printf("Error making root directory absolute: %d %.512s\n", status,
			apr_strerror(status, buf, 512));
		return FALSE;
	}
	buf[pos++] = '"';
	pos = apr_cpystrn(buf + pos, root_dir, len - pos) - buf;
	if ((buf[pos - 1] != '\\') && (pos < len))
		/* Add trailing backslash */
		buf[pos++] = '\\';
	pos = apr_cpystrn(buf + pos, "bin\\unimrcpserver.exe\" --service -o 2", len - pos) - buf;
	if (log_priority >= 0) {
		pos = apr_cpystrn(buf + pos, " -l ", len - pos) - buf;
		if (pos < len - 34)
			pos += strlen(itoa(log_priority, buf + pos, 10));
	}
	if (name) {
		pos = apr_cpystrn(buf + pos, " --name \"", len - pos) - buf;
		pos = apr_cpystrn(buf + pos, name, len - pos) - buf;
		if ((buf[pos - 1] == '\\') && (pos < len))
			/* `\"' might be misinterpreted as escape, so replace `\' with `\\' */
			buf[pos++] = '\\';
		if (pos < len)
			buf[pos++] = '"';
	}
	pos = apr_cpystrn(buf + pos, " --root-dir \"", len - pos) - buf;
	pos = apr_cpystrn(buf + pos, root_dir, len - pos) - buf;
	if ((buf[pos - 1] == '\\') && (pos < len))
		/* `\"' might be misinterpreted as escape, so replace `\' with `\\' */
		buf[pos++] = '\\';
	if (pos < len)
		buf[pos++] = '"';
	if (pos < len)
		buf[pos] = 0;
	else {
		puts("Service Command Too Long");
		return FALSE;
	}
	if (!disp_name || !*disp_name) {
		if (name)
			disp_name = apr_pstrcat(pool, name, " ", "UniMRCP Server", NULL);
		else
			disp_name = "UniMRCP Server";
	}
	if (!description || !*description)
		description = "Launches UniMRCP Server";

	sch_manager = OpenSCManager(0,0,SC_MANAGER_ALL_ACCESS);
	if(!sch_manager) {
		winerror("Failed to Open SCManager");
		return FALSE;
	}
	sch_service = CreateService(
					sch_manager,
					name ? name : WIN_SERVICE_NAME,
					disp_name,
					GENERIC_EXECUTE | SERVICE_CHANGE_CONFIG,
					SERVICE_WIN32_OWN_PROCESS,
					autostart ? SERVICE_AUTO_START : SERVICE_DEMAND_START,
					SERVICE_ERROR_NORMAL,
					buf,0,0,0,0,0);
	if(!sch_service) {
		winerror("Failed to Create Service");
		CloseServiceHandle(sch_manager);
		return FALSE;
	}

	desc.lpDescription = (char *) description;
	if(!ChangeServiceConfig2(sch_service,SERVICE_CONFIG_DESCRIPTION,&desc)) {
		winerror("Failed to Set Service Description");
	}

	if (recover) {
		SERVICE_FAILURE_ACTIONS sfa;
		SC_ACTION action;
		sfa.dwResetPeriod = 0;
		sfa.lpCommand = "";
		sfa.lpRebootMsg = "";
		sfa.cActions = 1;
		sfa.lpsaActions = &action;
		action.Delay = recover * 1000;
		action.Type = SC_ACTION_RESTART;
		if (!ChangeServiceConfig2(sch_service,SERVICE_CONFIG_FAILURE_ACTIONS,&sfa)) {
			winerror("Failed to Set Service Restart on Failure");
		}
	}

	CloseServiceHandle(sch_service);
	CloseServiceHandle(sch_manager);
	printf("UniMRCP service %s registered\n", name ? name : WIN_SERVICE_NAME);
	return TRUE;
}
コード例 #30
0
ファイル: launcher.c プロジェクト: python-doc-tw/cpython-tw
static void
locate_pythons_for_key(HKEY root, REGSAM flags)
{
    HKEY core_root, ip_key;
    LSTATUS status = RegOpenKeyExW(root, CORE_PATH, 0, flags, &core_root);
    wchar_t message[MSGSIZE];
    DWORD i;
    size_t n;
    BOOL ok;
    DWORD type, data_size, attrs;
    INSTALLED_PYTHON * ip, * pip;
    wchar_t ip_version[IP_VERSION_SIZE];
    wchar_t ip_path[IP_SIZE];
    wchar_t * check;
    wchar_t ** checkp;
    wchar_t *key_name = (root == HKEY_LOCAL_MACHINE) ? L"HKLM" : L"HKCU";

    if (status != ERROR_SUCCESS)
        debug(L"locate_pythons_for_key: unable to open PythonCore key in %ls\n",
              key_name);
    else {
        ip = &installed_pythons[num_installed_pythons];
        for (i = 0; num_installed_pythons < MAX_INSTALLED_PYTHONS; i++) {
            status = RegEnumKeyW(core_root, i, ip_version, IP_VERSION_SIZE);
            if (status != ERROR_SUCCESS) {
                if (status != ERROR_NO_MORE_ITEMS) {
                    /* unexpected error */
                    winerror(status, message, MSGSIZE);
                    debug(L"Can't enumerate registry key for version %ls: %ls\n",
                          ip_version, message);
                }
                break;
            }
            else {
                wcsncpy_s(ip->version, MAX_VERSION_SIZE, ip_version,
                          MAX_VERSION_SIZE-1);
                _snwprintf_s(ip_path, IP_SIZE, _TRUNCATE,
                             L"%ls\\%ls\\InstallPath", CORE_PATH, ip_version);
                status = RegOpenKeyExW(root, ip_path, 0, flags, &ip_key);
                if (status != ERROR_SUCCESS) {
                    winerror(status, message, MSGSIZE);
                    // Note: 'message' already has a trailing \n
                    debug(L"%ls\\%ls: %ls", key_name, ip_path, message);
                    continue;
                }
                data_size = sizeof(ip->executable) - 1;
                status = RegQueryValueExW(ip_key, NULL, NULL, &type,
                                          (LPBYTE)ip->executable, &data_size);
                RegCloseKey(ip_key);
                if (status != ERROR_SUCCESS) {
                    winerror(status, message, MSGSIZE);
                    debug(L"%ls\\%ls: %ls\n", key_name, ip_path, message);
                    continue;
                }
                if (type == REG_SZ) {
                    data_size = data_size / sizeof(wchar_t) - 1;  /* for NUL */
                    if (ip->executable[data_size - 1] == L'\\')
                        --data_size; /* reg value ended in a backslash */
                    /* ip->executable is data_size long */
                    for (checkp = location_checks; *checkp; ++checkp) {
                        check = *checkp;
                        _snwprintf_s(&ip->executable[data_size],
                                     MAX_PATH - data_size,
                                     MAX_PATH - data_size,
                                     L"%ls%ls", check, PYTHON_EXECUTABLE);
                        attrs = GetFileAttributesW(ip->executable);
                        if (attrs == INVALID_FILE_ATTRIBUTES) {
                            winerror(GetLastError(), message, MSGSIZE);
                            debug(L"locate_pythons_for_key: %ls: %ls",
                                  ip->executable, message);
                        }
                        else if (attrs & FILE_ATTRIBUTE_DIRECTORY) {
                            debug(L"locate_pythons_for_key: '%ls' is a \
directory\n",
                                  ip->executable, attrs);
                        }
                        else if (find_existing_python(ip->executable)) {
                            debug(L"locate_pythons_for_key: %ls: already \
found\n", ip->executable);
                        }
                        else {
                            /* check the executable type. */
                            ok = GetBinaryTypeW(ip->executable, &attrs);
                            if (!ok) {
                                debug(L"Failure getting binary type: %ls\n",
                                      ip->executable);
                            }
                            else {
                                if (attrs == SCS_64BIT_BINARY)
                                    ip->bits = 64;
                                else if (attrs == SCS_32BIT_BINARY)
                                    ip->bits = 32;
                                else
                                    ip->bits = 0;
                                if (ip->bits == 0) {
                                    debug(L"locate_pythons_for_key: %ls: \
invalid binary type: %X\n",
                                          ip->executable, attrs);
                                }
                                else {
                                    if (wcschr(ip->executable, L' ') != NULL) {
                                        /* has spaces, so quote */
                                        n = wcslen(ip->executable);
                                        memmove(&ip->executable[1],
                                                ip->executable, n * sizeof(wchar_t));
                                        ip->executable[0] = L'\"';
                                        ip->executable[n + 1] = L'\"';
                                        ip->executable[n + 2] = L'\0';
                                    }
                                    debug(L"locate_pythons_for_key: %ls \
is a %dbit executable\n",
                                        ip->executable, ip->bits);
                                    ++num_installed_pythons;
                                    pip = ip++;
                                    if (num_installed_pythons >=
                                        MAX_INSTALLED_PYTHONS)
                                        break;
                                    /* Copy over the attributes for the next */
                                    *ip = *pip;
                                }
                            }
                        }
                    }