int main(int argc, const char *argv[]) { errval_t err; printf("Spawnd up.\n"); vfs_init(); my_core_id = disp_get_core_id(); // read in the bootmodules file so that we know what to start get_bootmodules(); // construct sane inital environment init_environ(); err = start_service(); if (err_is_fail(err)) { USER_PANIC_ERR(err, "failed to start spawnd service loop"); } messages_handler_loop(); }
int main(int argc, char **argv) { kern_return_t kr; mach_port_t service_port = MACH_PORT_NULL; openlog("eapolcfg_auth", LOG_CONS | LOG_PID, LOG_DAEMON); if (geteuid() != 0) { syslog(LOG_ERR, "not running as root - exiting"); exit(EX_CONFIG); } kr = bootstrap_check_in(bootstrap_port, EAPOLCFG_AUTH_SERVER, &service_port); if (kr != BOOTSTRAP_SUCCESS) { syslog(LOG_ERR, "bootstrap_check_in() failed: %s", bootstrap_strerror(kr)); exit(EX_UNAVAILABLE); } start_service(service_port); while (1) { SInt32 rlStatus; rlStatus = CFRunLoopRunInMode(kCFRunLoopDefaultMode, 15.0, TRUE); if (rlStatus == kCFRunLoopRunTimedOut) { if (S_handled_request == FALSE) { /* we didn't handle a request in the last time interval */ break; } S_handled_request = FALSE; } } exit(EX_OK); return (0); }
void logger(context_t *source, char *fmt, ...) { static context_t *logger_context; if( ! logger_context ) { const char *logdriver = config_item( "global", "logger" ); if( logdriver ) { d_printf("Starting logging service %s\n",logdriver); start_service( & logger_context, logdriver, config_get_section( "global" ), 0L, 0L ); d_printf("logger context = %p\n",logger_context); } } va_list fmt_args; va_start( fmt_args, fmt ); char *log_buffer = alloca( LOG_BUFFER_MAX ); if( fmt ) { vsnprintf( log_buffer, LOG_BUFFER_MAX, fmt, fmt_args ); log_buffer[LOG_BUFFER_MAX-1] = 0; } if( logger_context ) { d_printf("Sending log details to log driver\n"); driver_data_t event = { TYPE_DATA, .source = source, {} }; event.event_data.bytes = strlen(log_buffer); event.event_data.data = log_buffer; emit( logger_context, EVENT_LOGGING, &event ); } else {
int main(int argc, char *argv[]) { if (argc == 2) { if (strcmp(argv[1], "install-service") == 0) { // Installs and starts the service install_service(); return 0; } else if (strcmp(argv[1], "remove-service") == 0) { // Stops and removes the service remove_service(); return 0; } else if (strcmp(argv[1], "service") == 0) { // Starts the Meterpreter as a service start_service(); return 0; } } // Starts the Meterpreter as a normal application start_meterpreter(); return 0; }
INT cmdStart(INT argc, CHAR **argv ) { char *string; long size = 100*sizeof(char); if (argc>4) { help(); return 0; } if (argc==2) { string = (char *) malloc(size); if (string != NULL) { sprintf(string,"rpcclient -c \"service enum\""); system(string); free(string); } return 0; } if (argc==3) { start_service(argv[1]); return 0; } return 0; }
HRESULT service_start_service( IWbemClassObject *obj, IWbemClassObject *in, IWbemClassObject **out ) { VARIANT name, retval; IWbemClassObject *sig; HRESULT hr; TRACE("%p, %p, %p\n", obj, in, out); hr = IWbemClassObject_Get( obj, prop_nameW, 0, &name, NULL, NULL ); if (hr != S_OK) return hr; hr = create_signature( class_serviceW, method_startserviceW, PARAM_OUT, &sig ); if (hr != S_OK) { VariantClear( &name ); return hr; } hr = IWbemClassObject_SpawnInstance( sig, 0, out ); if (hr != S_OK) { VariantClear( &name ); IWbemClassObject_Release( sig ); return hr; } hr = start_service( V_BSTR(&name), &retval ); if (hr != S_OK) goto done; hr = IWbemClassObject_Put( *out, param_returnvalueW, 0, &retval, CIM_UINT32 ); done: VariantClear( &name ); IWbemClassObject_Release( sig ); if (hr != S_OK) IWbemClassObject_Release( *out ); return hr; }
int main(int argc, const char *argv[]) { int listen_fd, new_fd; listen_fd = init_server(); // init server, listen while (true) { new_fd = accept_client(listen_fd); if (new_fd == -1) { perror("accept"); continue; } /* * if accepted, fork() */ if (!fork()) { // this is the child process close(listen_fd); // child doesn't need the listener if (send(new_fd, "Hello, world!", 13, 0) == -1) perror("send"); bind_file(new_fd); start_service(); close_connection(); close(new_fd); exit(0); } close(new_fd); } return 0; }
ERROR_CODE run_service() { /* allocates the return value to be used to gather the error result from the service calls */ ERROR_CODE return_value; /* allocates the socket data and then initializes the socket infrastructure (global structures) with it */ SOCKET_DATA socket_data; SOCKET_INITIALIZE(&socket_data); /* starts the service, this call should be able to bootstrap all the required structures and initialize the main loop, this should block the control flow fduring the run of the service */ return_value = start_service(service); /* tests the error code value for error and in case there's one runs the appropriate measures */ if(IS_ERROR_CODE(return_value)) { /* runs the socket finish so that the proper cleanup operations are performed and then re-raises the error*/ SOCKET_FINISH(); RAISE_AGAIN(return_value); } /* runs the socket finish releasing any pending memory information regarding the socket infra-structure */ SOCKET_FINISH(); /* raises no error */ RAISE_NO_ERROR; }
int ObBaseServer::start(bool need_wait) { int rc = OB_SUCCESS; rc = initialize(); if (rc != OB_SUCCESS) { TBSYS_LOG(WARN, "initialize failed"); } else { if (packet_factory_ == NULL) { rc = OB_INVALID_ARGUMENT; TBSYS_LOG(WARN, "packet factory can not be NULL, server not started"); } else { uint32_t local_ip = tbsys::CNetUtil::getLocalAddr(dev_name_); server_id_ = tbsys::CNetUtil::ipToAddr(local_ip, port_); streamer_.setPacketFactory(packet_factory_); setBatchPushPacket(batch_); // IServerAdapter's method transport_.start(); char spec[32]; snprintf(spec, 32, "tcp::%d", port_); spec[31] = '\0'; if (transport_.listen(spec, &streamer_, this) == NULL) { TBSYS_LOG(ERROR, "listen on port %d failed", port_); rc = OB_SERVER_LISTEN_ERROR; } else { TBSYS_LOG(INFO, "listened on port %d", port_); } if (rc == OB_SUCCESS) { rc = start_service(); } if (rc == OB_SUCCESS) { //wait_for_queue(); if (need_wait) { transport_.wait(); } } } } if (need_wait) { stop(); } return rc; }
int main(int argc, const char *argv[]) { errval_t err; printf("Spawnd up.\n"); vfs_init(); my_core_id = disp_get_core_id(); #if 0 debug_printf("spawnd invoked on core %d as:", my_core_id); for (int i = 0; i < argc; i++) { printf(" %s", argv[i]); } printf("\n"); #endif // read in the bootmodules file so that we know what to start get_bootmodules(); // construct sane inital environment init_environ(); if (argc >= 2 && strcmp(argv[1],"boot") == 0) { debug_printf("we're bsp. start other cores.\n"); // if we're the BSP, bring up the other cores is_bsp_core = true; #if defined(USE_KALUGA_DVM) && (!defined(__arm__) && !defined(__scc__) &&!defined(__k1om__)) err = start_service(); #else bsp_bootup(gbootmodules, argc, argv); #endif } else { // otherwise offer the spawn service err = start_service(); if (err_is_fail(err)) { USER_PANIC_ERR(err, "failed to start spawnd service loop"); } } messages_handler_loop(); }
void node::start_service( uint16_t cn, const fc::string& name, const node::new_channel_handler& cb ) { if( !my->_thread.is_current() ) { my->_thread.async( [&,this](){ return start_service( cn, name, cb ); } ).wait(); return; } if( !my->_services.insert( service( cn, name, cb ) ).second ) FC_THROW_MSG( "Unable to start service '%s' on channel '%s' because channel '%s' is in use.", name.c_str(), cn, cn ); slog( "Starting service '%s' on channel %d", name.c_str(), cn ); }
int otu_init(struct otu *u , struct skynet_context * ctx, char * parm) { if (parm == NULL) return 1; int max = 0; int sz = strlen(parm)+1; char watchdog[sz]; char binding[sz]; int client_tag = 0; int n = sscanf(parm, "%s %s %d %d", watchdog, binding, &client_tag, &max); if (n<4) { skynet_error(ctx, "Invalid otu parm %s", parm); return 1; } skynet_error(ctx, "Watchdog:%s, Binding:%s, Protocol:%d, MaxPeer:%d", watchdog, binding, client_tag, max); if (max <=0 ) { skynet_error(ctx, "Need max connection"); return 1; } if (client_tag == 0) { client_tag = PTYPE_CLIENT; } if (watchdog[0] == '!') { u->watchdog = 0; } else { u->watchdog = skynet_queryname(ctx, watchdog); if (u->watchdog == 0) { skynet_error(ctx, "Invalid watchdog %s",watchdog); return 1; } } u->ctx = ctx; hashid64_init(&u->hash, max); u->peer = skynet_malloc(max * sizeof(struct udp_peer)); memset(u->peer, 0, max *sizeof(struct udp_peer)); u->max_peer = max; int i; for (i=0;i<max;i++) { // u->peer[i].id = -1; } u->client_tag = client_tag; skynet_callback(ctx,u,_cb_otu); return start_service(u,binding); }
//lancement de l'analyse ring 0 void analysis::ring0analysis() { manager=NULL; service=NULL; int error=0; int status = 0; status= driverStatus(); if(status==0) { printf(" [-] Impossible to query the driver status.\n"); return; } //si pas déjà installé, installation if(status == DRIVER_NOT_INSTALLED) { //installation if(!install_driver()) { printf(" [-] Impossible to install the driver.\n"); error=2; } } //si pas démarré, démarrage if((status == DRIVER_STOPPED || status == DRIVER_NOT_INSTALLED) && !error) { if(!start_service()) { printf(" [-] Impossible to start the service.\n"); error=1; } } //si pas d'erreurs (et service lancé, donc), analyse if(!error) { ssdt(); //stop, puisque lancé if(!stop_service()) printf(" [-] Impossible to stop the service.\n"); } if(error<1) { //si installé, désinstallation if(!remove_driver()) printf(" [-] Impossible to delete the driver.\n"); } sCCleanHandles(); }
int main(int argc, char* argv[]) { if (argc > 1) { char *value = argv[1]; // Parameters should start with '/' or '-'. if (!(*value == '-' || *value == '/')) { std::cerr << "Unexpected parameter: " << value << std::endl << std::endl; show_usage(argv[0]); return 1; } // Skip past the first character. value = value + 1; if (*value == 'h' || *value == '?') { show_usage(argv[0]); } else if (strcmp(value, "shell") == 0) { while (!shutdown) { try { pushyd_once(&std::cout); } catch (std::exception const& e) { std::cerr << "std::exception caught: " << e.what() << std::endl; return 1; } catch (...) { std::cerr << "Unknown exception caught" << std::endl; return 1; } } } else if (strcmp(value, "install") == 0) { return service_install(); } } else { start_service(); } return 0; }
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpszCmdLine, int nCmdShow) { char exe_file_name[MAX_PATH], dir[MAX_PATH], *ptr; static struct WSAData wsa_state; ghInst=hInstance; GetModuleFileName(0, exe_file_name, MAX_PATH); /* set current directory */ strcpy(dir, exe_file_name); ptr=strrchr(dir, '\\'); /* last backslash */ if(ptr) ptr[1]='\0'; /* truncate program name */ if(!SetCurrentDirectory(dir)) { MessageBox(hwnd, "Cannot set current directory", options.win32_name, MB_ICONERROR); return 1; } /* setup service_path for CreateService() */ strcpy(service_path, "\""); strcat(service_path, exe_file_name); strcat(service_path, "\" -service"); /* strcat(service_path, lpszCmdLine); */ if(WSAStartup(0x0101, &wsa_state)) { win_log("Failed to initialize winsock"); error_mode=1; } if(!strcmpi(lpszCmdLine, "-service")) { if(!setjmp(jump_buf)) main_initialize(NULL, NULL); return start_service(); /* Always start service with -service option */ } if(!error_mode && !setjmp(jump_buf)) { /* TRY */ if(!strcmpi(lpszCmdLine, "-install")) { main_initialize(NULL, NULL); return install_service(); } else if(!strcmpi(lpszCmdLine, "-uninstall")) { main_initialize(NULL, NULL); return uninstall_service(); } else { /* not -service, -install or -uninstall */ main_initialize(lpszCmdLine[0] ? lpszCmdLine : NULL, NULL); } } /* CATCH */ return win_main(hInstance, hPrevInstance, lpszCmdLine, nCmdShow); }
int WINAPI manage_npf_driver(LPCTSTR LogFileName, char operation) { FILE *log; DWORD ReturnValue = NO_ERROR; if (LogFileName != NULL) log = fopen(LogFileName, "a"); else log = NULL; switch(operation) { case 's': ReturnValue = start_service(log,"NPF"); break; case 'x': ReturnValue = stop_service(log,"NPF"); break; case 'u': ReturnValue = delete_service(log,"NPF"); break; case 'i': ReturnValue = create_driver_service(log,"NPF","NetGroup Packet Filter Driver","system32\\drivers\\npf.sys"); break; case 'r': (void)delete_service(log,"NPF"); Sleep(100); ReturnValue = create_driver_service(log,"NPF","NetGroup Packet Filter Driver","system32\\drivers\\npf.sys"); break; case 'a': ReturnValue = change_start_type_service(log,"NPF", SERVICE_AUTO_START); break; case 'd': ReturnValue = change_start_type_service(log,"NPF", SERVICE_DEMAND_START); break; default: ReturnValue = ERROR_INVALID_PARAMETER; break; } if (log != NULL) fclose(log); return (int)ReturnValue; }
static void try_usb_modeswitch(const char * vendor_id,const char * product_id,const char * modeswitch_d){ char * config_filename = bprintf("%s/%04s_%04s",modeswitch_d,vendor_id ,product_id); ALOGD("Looking For usb_modeswitch config in location %s",config_filename); if(!file_exists(config_filename)){ // usb_modeswitch file not found for this device ALOGD("Config Not Found"); return ; } char * usb_modeswitch_command = bprintf("switch_ms_to_3g:-v0x%04s -p0x%04s -c%s",vendor_id ,product_id,config_filename); start_service(usb_modeswitch_command); free(usb_modeswitch_command); free(config_filename); }
char * configure_iis(HWND hDlg, char *resin_home, char *isapi_script) { char filter[1024]; int is_nt = (GetVersion() & 0x80000000) == 0; sprintf(filter, "%s\\isapi_srun.dll", isapi_script); char *metabase_msg = 0; add_resin_script_permission(isapi_script); char *script = add_resin_script_metabase(hDlg, isapi_script); metabase_msg = add_resin_filter_metabase(hDlg, filter); if (metabase_msg) add_resin_filter_registry(hDlg, isapi_script); int iis_restart = 0; char *msg = copy_filter(hDlg, resin_home, isapi_script, &iis_restart, is_nt); if (! is_nt) { } else if (iis_restart) start_service(IIS_SERVICE); else if (! msg) { if (MessageBox(hDlg, TEXT("Do you want to restart IIS to use the new filter?"), TEXT("Restart IIS?"), MB_OKCANCEL) == IDCANCEL) return 0; char *msg = stop_service(IIS_SERVICE); if (! msg) start_service(IIS_SERVICE); } if (! msg) return metabase_msg; else return msg; }
int monitor_service() { /* Set service status to started */ int ret = start_service(); if (ret) { char code[16]; _snprintf(code, sizeof(code), "%d", ret); log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_START_SERVICE_FAILED, exe, service_name, ret, 0); return ret; } log_event(EVENTLOG_INFORMATION_TYPE, NSSM_EVENT_STARTED_SERVICE, exe, flags, service_name, dir, 0); /* Monitor service service */ if (! RegisterWaitForSingleObject(&wait_handle, process_handle, end_service, (void *) pid, INFINITE, WT_EXECUTEONLYONCE | WT_EXECUTELONGFUNCTION)) { log_event(EVENTLOG_WARNING_TYPE, NSSM_EVENT_REGISTERWAITFORSINGLEOBJECT_FAILED, service_name, exe, error_string(GetLastError()), 0); } return 0; }
ssize_t logger_handler(context_t *ctx, event_t event, driver_data_t *event_data ) { event_data_t *data = 0L; logger_config_t *cf = (logger_config_t *) ctx->data; //x_printf(ctx, "<%s> Event = \"%s\" (%d)\n", ctx->name, event_map[event], event); if( event_data->type == TYPE_DATA ) data = & event_data->event_data; switch( event ) { case EVENT_INIT: if(( cf->log_driver = config_get_item( ctx->config, "logdriver" ) )) { if( strchr( cf->log_driver, '/' ) ) cf->log_fd = open( cf->log_driver, O_RDWR|O_APPEND|O_CREAT, 0777 ); else start_service( &cf->logger, cf->log_driver, ctx->config, ctx, 0L ); } cf->state = LOGGER_STATE_RUNNING; case EVENT_START: break; case EVENT_TERMINATE: context_terminate( ctx ); break; case EVENT_DATA_INCOMING: case EVENT_DATA_OUTGOING: case EVENT_LOGGING: if( data ) { char *logbuffer = alloca( LOG_BUFFER_MAX ); snprintf(logbuffer, LOG_BUFFER_MAX, "%s: %s", event_data->source?event_data->source->name:"(unknown)", (char *)data->data); logbuffer[LOG_BUFFER_MAX-1] = 0; time_t spec; char spec_buffer[32]; if( cf->logger ) { driver_data_t log_event = { TYPE_DATA, .source = ctx, {} }; log_event.event_data.data = logbuffer; log_event.event_data.bytes = strlen(logbuffer); emit(cf->logger, EVENT_DATA_OUTGOING, &log_event); } else {
void service_process(BOOL (*start_service)(PCSTR, PCWSTR), int argc, char** argv) { BOOL res; StringCbCopyA(service_nameA, sizeof(service_nameA), argv[2]); MultiByteToWideChar(CP_ACP, 0, service_nameA, -1, service_nameW, _countof(service_nameW)); StringCbPrintfW(named_pipe_name, sizeof(named_pipe_name), L"\\\\.\\pipe\\%ls_pipe", service_nameW); res = WaitNamedPipeW(named_pipe_name, NMPWAIT_USE_DEFAULT_WAIT); if (!res) return; hClientPipe = CreateFileW(named_pipe_name, GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (hClientPipe == INVALID_HANDLE_VALUE) return; service_trace("Service process starting...\n"); res = start_service(service_nameA, service_nameW); service_trace("Service process stopped.\n"); CloseHandle(hClientPipe); }
char * remove_iis(HWND hDlg) { char *msg = remove_resin_filter_metabase(hDlg); if (msg) return msg; int is_nt = (GetVersion() & 0x80000000) == 0; if (is_nt) { if (MessageBox(hDlg, TEXT("Do you want to restart IIS?"), TEXT("Restart IIS?"), MB_OKCANCEL) == IDCANCEL) return 0; msg = stop_service(IIS_SERVICE); if (! msg) start_service(IIS_SERVICE); } else { MessageBox(hDlg, TEXT("You will need to restart IIS to remove Resin. You may need to reboot to see the changes."), TEXT("Restart"), MB_OK); } return msg; }
int _tmain( int argc, TCHAR *argv[] ) { // LPCTSTR service_name = _T("hindsight"); TCHAR *service_name = _T("hindsight"); if ( argc == 1 ) return run_service( service_name ); if ( lstrcmpi(argv[1], TEXT("install")) == 0 ) { return install_service( service_name ); } if ( lstrcmpi(argv[1], TEXT("start")) == 0 ) { return start_service( service_name ); } if ( lstrcmpi(argv[1], TEXT("stop")) == 0 ) { return stop_service( service_name ); } if ( lstrcmpi(argv[1], TEXT("uninstall")) == 0 ) { return uninstall_service( service_name ); } return -1; }
ssize_t unicorn_handler(context_t *ctx, event_t event, driver_data_t *event_data) { event_data_t *data = 0L; event_child_t *child = 0L; unicorn_config_t *cf = (unicorn_config_t *) ctx->data; //x_printf(ctx, "<%s> Event = \"%s\" (%d)\n", ctx->name, event_map[event], event); if (event_data->type == TYPE_DATA) data = &event_data->event_data; else if( event_data->type == TYPE_CHILD ) child = & event_data->event_child; switch (event) { case EVENT_INIT: { x_printf(ctx,"calling event add SIGQUIT\n"); event_add( ctx, SIGQUIT, EH_SIGNAL ); x_printf(ctx,"calling event add SIGTERM\n"); event_add( ctx, SIGTERM, EH_SIGNAL ); x_printf(ctx,"calling event 1000 EH_WANT_TICK\n"); event_add( ctx, 1000, EH_WANT_TICK ); cf->driver = config_get_item( ctx->config, "endpoint" ); if( ! config_get_timeval( ctx->config, "retry", &cf->retry_time ) ) cf->retry_time = 120*1000; if( cf->driver ) start_service( &cf->modem, cf->driver, ctx->config, ctx, 0L ); if( !cf->modem ) { logger( ctx, "Unable to launch modem driver. Exiting\n" ); cf->state = UNICORN_STATE_ERROR; context_terminate( ctx ); return -1; } cf->state = UNICORN_STATE_IDLE; } break; case EVENT_TERMINATE: { cf->pending_action_timeout = rel_time(0L); cf->flags |= UNICORN_TERMINATING; // In process of terminating the modem driver cf->state = UNICORN_STATE_STOPPING; // In process of terminating self // Ensure 'exec' driver known not to restart when the modem driver terminates. // If the modem driver is something other than 'exec', this should be ignored. uint8_t flag = 0; driver_data_t notification = { TYPE_CUSTOM, ctx, {} }; notification.event_custom = &flag; emit(cf->modem, EXEC_SET_RESPAWN, ¬ification); if( cf->driver_state == CMD_ST_ONLINE ) { x_printf(ctx,"Driver is online - sending disconnect\n"); send_unicorn_command( ctx, CMD_DISCONNECT, CMD_ST_OFFLINE, 0, 0L ); } else { x_printf(ctx,"Driver is offline - sending shutdown\n"); send_unicorn_command( ctx, CMD_STATE, CMD_ST_OFFLINE, 0, 0L ); } } break; case EVENT_RESTART: // This event is used to signal that the modem driver needs to resync. // set the 'reconnecting' flag and send a disconnect x_printf(ctx,"EVENT_RESTART: - sending disconnect to modem\n"); //logger(ctx, "Sending disconnect command to modem driver"); if( event_data->source == ctx->owner ) { cf->pending_action_timeout = rel_time(0L); cf->flags |= UNICORN_WAITING_FOR_CONNECT; if( cf->modem ) { x_printf(ctx, "Sending CMD_DISCONNECT to modem driver (%s)\n",cf->modem->name); if( (event_data->type == TYPE_CUSTOM) && event_data->event_custom ) { logger(ctx, "Sending abort command to modem driver due to unexpected disconnect"); send_unicorn_command( ctx, CMD_ABORT, CMD_ST_OFFLINE, 0, 0L ); } else { logger(ctx, "Sending disconnect command to modem driver"); send_unicorn_command( ctx, CMD_DISCONNECT, CMD_ST_OFFLINE, 0, 0L ); } } else { x_printf(ctx, "Modem driver not running.. doing nothing.\n"); } } else { x_printf(ctx,"Forwarding EVENT_RESTART to owner (%s)\n",ctx->name); emit2( ctx, EVENT_RESTART, event_data); } break; case EVENT_CHILD: x_printf(ctx,"Got a message from a child (%s:%d).. probably starting\n", child->ctx->name, child->action); if ( child->ctx == cf->modem ) { if( child->action == CHILD_STARTING ) { cf->state = UNICORN_STATE_RUNNING; cf->flags &= ~(unsigned int) UNICORN_RESTARTING; // Assume ensure the first time the modem driver starts it skips the connection delay cf->flags |= UNICORN_FIRST_START; } if ( child->action == CHILD_STOPPED ) { x_printf(ctx,"Modem driver terminated - restart or terminate\n"); // modem driver terminated. Restart or exit. cf->state = UNICORN_STATE_IDLE; if ( cf->flags & UNICORN_TERMINATING ) { x_printf(ctx,"Terminating immediately\n"); context_terminate( ctx ); } else { x_printf(ctx,"Need to restart modem driver\n"); cf->flags |= UNICORN_RESTARTING; cf->pending_action_timeout = rel_time(0L); // Reset the driver state, and notify the parent that we are offline cf->driver_state = CMD_ST_UNKNOWN; context_owner_notify( ctx, CHILD_EVENT, UNICORN_MODE_OFFLINE ); } } } break; case EVENT_DATA_INCOMING: case EVENT_DATA_OUTGOING: if( event_data->source == cf->modem ) { size_t bytes = data->bytes; size_t offset = 0; while( bytes ) { size_t to_read = u_ringbuf_avail( &cf->input ); if( to_read > bytes ) to_read = bytes; u_ringbuf_write( &cf->input, &((char *)data->data)[offset], to_read ); bytes -= to_read; offset += to_read; while(process_unicorn_packet(ctx) >= 0); } return (ssize_t) offset; } else { send_unicorn_command( ctx, CMD_DATA, CMD_ST_ONLINE, data->bytes,data->data); return (ssize_t) data->bytes; } break; case EVENT_READ: break; case EVENT_EXCEPTION: break; case EVENT_SIGNAL: x_printf(ctx,"Woa! Got a sign from the gods... %d\n", event_data->event_signal); if( event_data->event_signal == SIGQUIT || event_data->event_signal == SIGTERM ) emit( ctx, EVENT_TERMINATE, 0L ); break; case EVENT_TICK: { time_t now = rel_time(0L); // Handle case where a massive time shift due to NTP resync causes all timeouts to fire simultaneously // This is technically deprecated due to the use of rel_time() if( (now - cf->last_message) > MAXIMUM_SAFE_TIMEDELTA ) { logger(ctx, "WARNING: Resetting timeout due to RTC time change"); cf->last_message = now; } if( ((now - cf->last_message) > UNICORN_KEEPALIVE_TIMEOUT ) && ( cf->driver_state != CMD_ST_UNKNOWN )) { if( ~ cf->flags & UNICORN_LAGGED ) { // Its been a couple of minutes since the last keepalive, reset the driver_state // to unknown and prompt for one. logger(ctx,"Forcing connection state request due to communications timeout.\n"); cf->flags |= UNICORN_LAGGED; cf->retry_count = UNICORN_KEEPALIVE_RETRY_MAX; } if( cf->retry_count ) { send_unicorn_command( ctx, CMD_STATE, CMD_ST_OFFLINE, 0, 0L ); cf->retry_count --; } else { // Its been a long time since the last message, despite prompting for one // restart the modem driver logger(ctx, "Communications timeout. Restarting modem driver."); uint8_t sig = SIGHUP; driver_data_t notification = { TYPE_CUSTOM, ctx, {} }; notification.event_custom = &sig; emit( cf->modem, EVENT_RESTART, ¬ification ); } cf->last_message = now; } if( (cf->flags & UNICORN_RESTARTING) && ((now - cf->pending_action_timeout) > UNICORN_RESTART_DELAY )) { x_printf(ctx,"Restart delay expired - restarting modem driver\n"); cf->pending_action_timeout = rel_time(0L); if( cf->driver ) start_service( &cf->modem, cf->driver, ctx->config, ctx, 0L ); } else if( (cf->flags & UNICORN_RECONNECTING) && ((now - cf->pending_action_timeout) > cf->retry_time )) { x_printf(ctx,"Reconnect delay expired - attempting reconnect\n"); cf->pending_action_timeout = rel_time(0L); cf->flags &= ~(unsigned int)UNICORN_RECONNECTING; if( cf->modem ) send_unicorn_command(ctx, CMD_CONNECT, CMD_ST_ONLINE, 0, 0 ); } else if( (cf->flags & UNICORN_WAITING_FOR_CONNECT) && ((now - cf->pending_action_timeout) > UNICORN_CONNECT_TIMEOUT )) { x_printf(ctx,"Timeout during connect - terminating modem driver\n"); cf->flags &= ~(unsigned int) UNICORN_WAITING_FOR_CONNECT; cf->state = UNICORN_STATE_IDLE; if( cf->modem ) emit( cf->modem, EVENT_TERMINATE, 0L ); } if( (cf->flags & UNICORN_TERMINATING) && ((now - cf->pending_action_timeout) > UNICORN_PROCESS_TERMINATION_TIMEOUT)) { x_printf(ctx,"termination timeout - killing the modem driver with prejudice\n"); cf->state = UNICORN_STATE_IDLE; if( cf->modem ) context_terminate( cf->modem ); context_terminate( ctx ); } // Special case.. If I am expecting a data frame, and it takes too long to arrive, // reset state. if( (cf->flags & UNICORN_EXPECTING_DATA) && ((now - cf->last_message) > FRAME_TIMEOUT)) { x_printf(ctx,"FRAME TIMEOUT - resetting input buffer\n"); u_ringbuf_init( &cf->input ); cf->flags &= ~(unsigned int)UNICORN_EXPECTING_DATA; } #ifndef NDEBUG size_t bytes = u_ringbuf_ready( &cf->input ); if( bytes ) x_printf(ctx,"Un-processed data in ring buffer... %d bytes\n",(int)bytes); #endif } break; default: x_printf(ctx,"\n *\n *\n * Emitted some kind of event \"%s\" (%d)\n *\n *\n", event_map[event], event); } return 0; }
static void handle_event(struct uevent *uevent,struct hotplug_info *hotplug_info) { write_uevent_logcat(uevent,uevent->type); //return ; int c =uevent->action[0]; switch(c) { case 'a':{ if(!strncmp(uevent->type,"usb_interface",12)){ // see if this interface is ripe for a switching write_uevent_logcat(uevent,uevent->type); try_usb_modeswitch(uevent->vendor_id, uevent->product_id,hotplug_info->modeswitch_d); }else if(!strncmp(uevent->type,"usb-serial",10)){ //Serial Killals write_uevent_logcat(uevent,uevent->type); } else if(!strncmp(uevent->subsystem,"tty",3)){ write_uevent_logcat(uevent,uevent->type); if(!strncmp(uevent->name,"ttyUSB0",7)) property_set("ril.pppd_tty", "/dev/ttyUSB0"); if(!strncmp(uevent->name,"ttyHS4",7) ) property_set("ril.pppd_tty", "/dev/ttyHS4"); if(!strncmp(uevent->name,"ttyHS3",7)){ property_set("rild.libargs", "-d /dev/ttyHS3"); property_set("rild.libpath", "/system/lib/libtcl-ril.so"); start_service("ril-daemon"); } if(!strncmp(uevent->name,"ttyUSB2",7)) { property_set("rild.libargs", "-d /dev/ttyUSB2"); property_set("rild.libpath", "/system/lib/libhuaweigeneric-ril.so"); start_service("ril-daemon"); } }else { //write_uevent_logcat(uevent,"ignored"); } break; } case 'r':{ if(!strncmp(uevent->type,"usb_device",10)){ //Serial Killa write_uevent_logcat(uevent,uevent->type); //handle_connection_connection(); } else if(!strncmp(uevent->subsystem,"tty",3)){ write_uevent_logcat(uevent,uevent->type); if(!strncmp(uevent->name,"ttyUSB2",7)) { ALOGD("Stopping Rild"); stop_service("ril-daemon"); }else if(!strncmp(uevent->name,"ttyUSB0",7)){ system("pkill -9 ppp"); ALOGD("Killing PPP"); } } break; } case 'c':{ //write_uevent_logcat(uevent,"ignored"); } break; } }
// WinMain parses the command line and either calls the main App // routine or, under NT, the main service routine. int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR szCmdLine, int iCmdShow) { if (VNCOS.OS_NOTSUPPORTED==true) { MessageBoxSecure(NULL, "Error OS not supported","Unsupported OS", MB_ICONERROR); return true; } // make vnc last service to stop SetProcessShutdownParameters(0x100,false); // handle dpi on aero /*HMODULE hUser32 = LoadLibrary(_T("user32.dll")); typedef BOOL (*SetProcessDPIAwareFunc)(); SetProcessDPIAwareFunc setDPIAware=NULL; if (hUser32) setDPIAware = (SetProcessDPIAwareFunc)GetProcAddress(hUser32, "SetProcessDPIAware"); if (setDPIAware) setDPIAware(); if (hUser32) FreeLibrary(hUser32);*/ #ifdef IPP InitIpp(); #endif #ifdef CRASHRPT CR_INSTALL_INFO info; memset(&info, 0, sizeof(CR_INSTALL_INFO)); info.cb = sizeof(CR_INSTALL_INFO); info.pszAppName = _T("UVNC"); info.pszAppVersion = _T("1.2.0.9"); info.pszEmailSubject = _T("UVNC server 1.2.0.9 Error Report"); info.pszEmailTo = _T("*****@*****.**"); info.uPriorities[CR_SMAPI] = 1; // Third try send report over Simple MAPI // Install all available exception handlers info.dwFlags |= CR_INST_ALL_POSSIBLE_HANDLERS; // Restart the app on crash info.dwFlags |= CR_INST_APP_RESTART; info.dwFlags |= CR_INST_SEND_QUEUED_REPORTS; info.dwFlags |= CR_INST_AUTO_THREAD_HANDLERS; info.pszRestartCmdLine = _T("/restart"); // Define the Privacy Policy URL // Install crash reporting int nResult = crInstall(&info); if (nResult != 0) { // Something goes wrong. Get error message. TCHAR szErrorMsg[512] = _T(""); crGetLastErrorMsg(szErrorMsg, 512); _tprintf_s(_T("%s\n"), szErrorMsg); return 1; } #endif bool Injected_autoreconnect=false; SPECIAL_SC_EXIT=false; SPECIAL_SC_PROMPT=false; setbuf(stderr, 0); // [v1.0.2-jp1 fix] Load resouce from dll hInstResDLL = NULL; //limit the vnclang.dll searchpath to avoid char szCurrentDir[MAX_PATH]; char szCurrentDir_vnclangdll[MAX_PATH]; if (GetModuleFileName(NULL, szCurrentDir, MAX_PATH)) { char* p = strrchr(szCurrentDir, '\\'); *p = '\0'; } strcpy (szCurrentDir_vnclangdll,szCurrentDir); strcat (szCurrentDir_vnclangdll,"\\"); strcat (szCurrentDir_vnclangdll,"vnclang_server.dll"); hInstResDLL = LoadLibrary(szCurrentDir_vnclangdll); if (hInstResDLL == NULL) { hInstResDLL = hInstance; } // RegisterLinkLabel(hInstResDLL); //Load all messages from ressource file Load_Localization(hInstResDLL) ; char WORKDIR[MAX_PATH]; if (GetModuleFileName(NULL, WORKDIR, MAX_PATH)) { char* p = strrchr(WORKDIR, '\\'); if (p == NULL) return 0; *p = '\0'; } char progname[MAX_PATH]; strncpy(progname, WORKDIR, sizeof progname); progname[MAX_PATH - 1] = 0; //strcat(WORKDIR,"\\"); //strcat(WORKDIR,"WinVNC.log"); vnclog.SetFile(); //vnclog.SetMode(4); //vnclog.SetLevel(10); #ifdef _DEBUG { // Get current flag int tmpFlag = _CrtSetDbgFlag( _CRTDBG_REPORT_FLAG ); // Turn on leak-checking bit tmpFlag |= _CRTDBG_LEAK_CHECK_DF; // Set flag to the new value _CrtSetDbgFlag( tmpFlag ); } #endif // Save the application instance and main thread id hAppInstance = hInstance; mainthreadId = GetCurrentThreadId(); // Initialise the VSocket system VSocketSystem socksys; if (!socksys.Initialised()) { MessageBoxSecure(NULL, sz_ID_FAILED_INIT, szAppName, MB_OK); #ifdef CRASHRPT crUninstall(); #endif return 0; } // look up the current service name in the registry. GetServiceName(progname, service_name); // Make the command-line lowercase and parse it size_t i; for (i = 0; i < strlen(szCmdLine); i++) { szCmdLine[i] = tolower(szCmdLine[i]); } BOOL argfound = FALSE; for (i = 0; i < strlen(szCmdLine); i++) { if (szCmdLine[i] <= ' ') continue; argfound = TRUE; if (strncmp(&szCmdLine[i], winvncSettingshelper, strlen(winvncSettingshelper)) == 0) { Sleep(3000); char mycommand[MAX_PATH]; i+=strlen(winvncSettingshelper); strcpy( mycommand, &(szCmdLine[i+1])); Set_settings_as_admin(mycommand); #ifdef CRASHRPT crUninstall(); #endif return 0; } if (strncmp(&szCmdLine[i], winvncStopserviceHelper, strlen(winvncStopserviceHelper)) == 0) { Sleep(3000); Set_stop_service_as_admin(); #ifdef CRASHRPT crUninstall(); #endif return 0; } if (strncmp(&szCmdLine[i], winvncKill, strlen(winvncKill)) == 0) { static HANDLE hShutdownEventTmp; hShutdownEventTmp = OpenEvent(EVENT_ALL_ACCESS, FALSE, "Global\\SessionEventUltra"); SetEvent(hShutdownEventTmp); CloseHandle(hShutdownEventTmp); //adzm 2010-02-10 - Finds the appropriate VNC window for any process. Sends this message to all of them! // do removed, loops forever with cpu 100 HWND hservwnd = NULL; hservwnd = FindWinVNCWindow(false); if (hservwnd!=NULL) { PostMessage(hservwnd, WM_COMMAND, 40002, 0); PostMessage(hservwnd, WM_CLOSE, 0, 0); } #ifdef CRASHRPT crUninstall(); #endif return 0; } if (strncmp(&szCmdLine[i], winvncopenhomepage, strlen(winvncopenhomepage)) == 0) { Open_homepage(); #ifdef CRASHRPT crUninstall(); #endif return 0; } if (strncmp(&szCmdLine[i], winvncopenforum, strlen(winvncopenforum)) == 0) { Open_forum(); #ifdef CRASHRPT crUninstall(); #endif return 0; } if (strncmp(&szCmdLine[i], winvncStartserviceHelper, strlen(winvncStartserviceHelper)) == 0) { Sleep(3000); Set_start_service_as_admin(); #ifdef CRASHRPT crUninstall(); #endif return 0; } if (strncmp(&szCmdLine[i], winvncInstallServiceHelper, strlen(winvncInstallServiceHelper)) == 0) { //Sleeps are realy needed, else runas fails... Sleep(3000); Set_install_service_as_admin(); #ifdef CRASHRPT crUninstall(); #endif return 0; } if (strncmp(&szCmdLine[i], winvncUnInstallServiceHelper, strlen(winvncUnInstallServiceHelper)) == 0) { Sleep(3000); Set_uninstall_service_as_admin(); #ifdef CRASHRPT crUninstall(); #endif return 0; } if (strncmp(&szCmdLine[i], winvncSoftwarecadHelper, strlen(winvncSoftwarecadHelper)) == 0) { Sleep(3000); Enable_softwareCAD_elevated(); #ifdef CRASHRPT crUninstall(); #endif return 0; } if (strncmp(&szCmdLine[i], winvncdelSoftwarecadHelper, strlen(winvncdelSoftwarecadHelper)) == 0) { Sleep(3000); delete_softwareCAD_elevated(); #ifdef CRASHRPT crUninstall(); #endif return 0; } if (strncmp(&szCmdLine[i], winvncRebootSafeHelper, strlen(winvncRebootSafeHelper)) == 0) { Sleep(3000); Reboot_in_safemode_elevated(); #ifdef CRASHRPT crUninstall(); #endif return 0; } if (strncmp(&szCmdLine[i], winvncRebootForceHelper, strlen(winvncRebootForceHelper)) == 0) { Sleep(3000); Reboot_with_force_reboot_elevated(); #ifdef CRASHRPT crUninstall(); #endif return 0; } if (strncmp(&szCmdLine[i], winvncSecurityEditorHelper, strlen(winvncSecurityEditorHelper)) == 0) { Sleep(3000); winvncSecurityEditorHelper_as_admin(); #ifdef CRASHRPT crUninstall(); #endif return 0; } if (strncmp(&szCmdLine[i], winvncSecurityEditor, strlen(winvncSecurityEditor)) == 0) { typedef void (*vncEditSecurityFn) (HWND hwnd, HINSTANCE hInstance); vncEditSecurityFn vncEditSecurity = 0; char szCurrentDirl[MAX_PATH]; if (GetModuleFileName(NULL, szCurrentDirl, MAX_PATH)) { char* p = strrchr(szCurrentDirl, '\\'); *p = '\0'; strcat (szCurrentDirl,"\\authSSP.dll"); } HMODULE hModule = LoadLibrary(szCurrentDirl); if (hModule) { vncEditSecurity = (vncEditSecurityFn) GetProcAddress(hModule, "vncEditSecurity"); HRESULT hr = CoInitialize(NULL); vncEditSecurity(NULL, hAppInstance); CoUninitialize(); FreeLibrary(hModule); } #ifdef CRASHRPT crUninstall(); #endif return 0; } if (strncmp(&szCmdLine[i], winvncSettings, strlen(winvncSettings)) == 0) { char mycommand[MAX_PATH]; i+=strlen(winvncSettings); strcpy( mycommand, &(szCmdLine[i+1])); Real_settings(mycommand); #ifdef CRASHRPT crUninstall(); #endif return 0; } if (strncmp(&szCmdLine[i], dsmpluginhelper, strlen(dsmpluginhelper)) == 0) { char mycommand[MAX_PATH]; i += strlen(dsmpluginhelper); strcpy(mycommand, &(szCmdLine[i + 1])); Secure_Plugin_elevated(mycommand); #ifdef CRASHRPT crUninstall(); #endif return 0; } if (strncmp(&szCmdLine[i], dsmplugininstance, strlen(dsmplugininstance)) == 0) { char mycommand[MAX_PATH]; i += strlen(dsmplugininstance); strcpy(mycommand, &(szCmdLine[i + 1])); Secure_Plugin(mycommand); #ifdef CRASHRPT crUninstall(); #endif return 0; } if (strncmp(&szCmdLine[i], winvncSoftwarecad, strlen(winvncSoftwarecad)) == 0) { Enable_softwareCAD(); #ifdef CRASHRPT crUninstall(); #endif return 0; } if (strncmp(&szCmdLine[i], winvncdelSoftwarecad, strlen(winvncdelSoftwarecad)) == 0) { delete_softwareCAD(); #ifdef CRASHRPT crUninstall(); #endif return 0; } if (strncmp(&szCmdLine[i], winvncRebootSafe, strlen(winvncRebootSafe)) == 0) { Reboot_in_safemode(); #ifdef CRASHRPT crUninstall(); #endif return 0; } if (strncmp(&szCmdLine[i], winvncRebootForce, strlen(winvncRebootForce)) == 0) { Reboot_with_force_reboot(); #ifdef CRASHRPT crUninstall(); #endif return 0; } if (strncmp(&szCmdLine[i], winvncStopservice, strlen(winvncStopservice)) == 0) { Real_stop_service(); #ifdef CRASHRPT crUninstall(); #endif return 0; } if (strncmp(&szCmdLine[i], winvncStartservice, strlen(winvncStartservice)) == 0) { Real_start_service(); #ifdef CRASHRPT crUninstall(); #endif return 0; } if (strncmp(&szCmdLine[i], winvncInstallService, strlen(winvncInstallService)) == 0) { // rest of command line service name, if provided. char *pServiceName = &szCmdLine[i]; // skip over command switch, find next whitepace while (*pServiceName && !isspace(*(unsigned char*)pServiceName)) ++pServiceName; // skip past whitespace to service name while (*pServiceName && isspace(*(unsigned char*)pServiceName)) ++pServiceName; // strip off any quotes if (*pServiceName && *pServiceName == '\"') ++pServiceName; if (*pServiceName) { // look for trailing quote, if found, terminate the string there. char *pQuote = pServiceName; pQuote = strrchr(pServiceName, '\"'); if (pQuote) *pQuote = 0; } // if a service name is supplied, and it differs except in case from // the default, use the supplied service name instead if (*pServiceName && (_strcmpi(pServiceName, service_name) != 0)) { strncpy(service_name, pServiceName, 256); service_name[255] = 0; } install_service(); Sleep(2000); char command[MAX_PATH + 32]; // 29 January 2008 jdp _snprintf(command, sizeof command, "net start \"%s\"", service_name); WinExec(command,SW_HIDE); #ifdef CRASHRPT crUninstall(); #endif return 0; } if (strncmp(&szCmdLine[i], winvncUnInstallService, strlen(winvncUnInstallService)) == 0) { char command[MAX_PATH + 32]; // 29 January 2008 jdp // rest of command line service name, if provided. char *pServiceName = &szCmdLine[i]; // skip over command switch, find next whitepace while (*pServiceName && !isspace(*(unsigned char*)pServiceName)) ++pServiceName; // skip past whitespace to service name while (*pServiceName && isspace(*(unsigned char*)pServiceName)) ++pServiceName; // strip off any quotes if (*pServiceName && *pServiceName == '\"') ++pServiceName; if (*pServiceName) { // look for trailing quote, if found, terminate the string there. char *pQuote = pServiceName; pQuote = strrchr(pServiceName, '\"'); if (pQuote) *pQuote = 0; } if (*pServiceName && (_strcmpi(pServiceName, service_name) != 0)) { strncpy(service_name, pServiceName, 256); service_name[255] = 0; } _snprintf(command, sizeof command, "net stop \"%s\"", service_name); WinExec(command,SW_HIDE); uninstall_service(); #ifdef CRASHRPT crUninstall(); #endif return 0; } if (strncmp(&szCmdLine[i], winvncRunService, strlen(winvncRunService)) == 0) { //Run as service if (!Myinit(hInstance)) return 0; fRunningFromExternalService = true; vncService::RunningFromExternalService(true); int returnvalue = WinVNCAppMain(); #ifdef CRASHRPT crUninstall(); #endif return returnvalue; } if (strncmp(&szCmdLine[i], winvncStartService, strlen(winvncStartService)) == 0) { start_service(szCmdLine); #ifdef CRASHRPT crUninstall(); #endif return 0; } if (strncmp(&szCmdLine[i], winvncRunAsUserApp, strlen(winvncRunAsUserApp)) == 0) { // WinVNC is being run as a user-level program if (!Myinit(hInstance)) return 0; int returnvalue = WinVNCAppMain(); #ifdef CRASHRPT crUninstall(); #endif return returnvalue; } if (strncmp(&szCmdLine[i], winvncSCexit, strlen(winvncSCexit)) == 0) { SPECIAL_SC_EXIT=true; i+=strlen(winvncSCexit); continue; } if (strncmp(&szCmdLine[i], winvncSCprompt, strlen(winvncSCprompt)) == 0) { SPECIAL_SC_PROMPT=true; i+=strlen(winvncSCprompt); continue; } if (strncmp(&szCmdLine[i], winvncmulti, strlen(winvncmulti)) == 0) { multi=true; i+=strlen(winvncmulti); continue; } if (strncmp(&szCmdLine[i], winvnchttp, strlen(winvnchttp)) == 0) { G_HTTP=true; i+=strlen(winvnchttp); continue; } if (strncmp(&szCmdLine[i], winvncStopReconnect, strlen(winvncStopReconnect)) == 0) { i+=strlen(winvncStopReconnect); vncService::PostAddStopConnectClientAll(); continue; } if (strncmp(&szCmdLine[i], winvncAutoReconnect, strlen(winvncAutoReconnect)) == 0) { // Note that this "autoreconnect" param MUST be BEFORE the "connect" one // on the command line ! // wa@2005 -- added support for the AutoReconnectId i+=strlen(winvncAutoReconnect); Injected_autoreconnect=true; int start, end; char* pszId = NULL; start = i; // skip any spaces and grab the parameter while (szCmdLine[start] <= ' ' && szCmdLine[start] != 0) start++; if ( strncmp( &szCmdLine[start], winvncAutoReconnectId, strlen(winvncAutoReconnectId) ) == 0 ) { end = start; while (szCmdLine[end] > ' ') end++; if (end - start > 0) { pszId = new char[end - start + 1]; strncpy(pszId, &(szCmdLine[start]), end - start); pszId[end - start] = 0; pszId = _strupr(pszId); } //multiple spaces between autoreconnect and id i = end; }// end of condition we found the ID: parameter // NOTE: id must be NULL or the ID:???? (pointer will get deleted when message is processed) // We can not contact a runnning service, permissions, so we must store the settings // and process until the vncmenu has been started if (!vncService::PostAddAutoConnectClient( pszId )) { PostAddAutoConnectClient_bool=true; if (pszId==NULL) { PostAddAutoConnectClient_bool_null=true; PostAddAutoConnectClient_bool=false; } else { strcpy(pszId_char,pszId); //memory leak fix delete[] pszId; pszId = NULL; } } if (pszId != NULL) delete[] pszId; pszId = NULL; continue; } if ( strncmp( &szCmdLine[i], winvncReconnectId, strlen(winvncReconnectId) ) == 0 ) { i+=strlen("-"); int start, end; char* pszId = NULL; start = i; end = start; while (szCmdLine[end] > ' ') end++; if (end - start > 0) { pszId = new char[end - start + 1]; if (pszId != 0) { strncpy(pszId, &(szCmdLine[start]), end - start); pszId[end - start] = 0; pszId = _strupr(pszId); } } i = end; if (!vncService::PostAddConnectClient( pszId )) { PostAddConnectClient_bool=true; if (pszId==NULL) { PostAddConnectClient_bool_null=true; PostAddConnectClient_bool=false; } else { strcpy(pszId_char,pszId); //memory leak fix delete[] pszId; pszId = NULL; } } if (pszId != NULL) delete[] pszId; pszId = NULL; continue; } if (strncmp(&szCmdLine[i], winvncConnect, strlen(winvncConnect)) == 0) { if (!Injected_autoreconnect) { vncService::PostAddStopConnectClient(); } // Add a new client to an existing copy of winvnc i+=strlen(winvncConnect); // First, we have to parse the command line to get the filename to use int start, end; start=i; while (szCmdLine[start] <= ' ' && szCmdLine[start] != 0) start++; end = start; while (szCmdLine[end] > ' ') end++; // Was there a hostname (and optionally a port number) given? if (end-start > 0) { char *name = new char[end-start+1]; if (name != 0) { strncpy(name, &(szCmdLine[start]), end-start); name[end-start] = 0; int port = INCOMING_PORT_OFFSET; char *portp = strchr(name, ':'); if (portp) { *portp++ = '\0'; if (*portp == ':') { port = atoi(++portp); // Port number after "::" } else { port = atoi(portp); // Display number after ":" } } vnclog.Print(LL_STATE, VNCLOG("test... %s %d\n"),name,port); strcpy_s(dnsname,name); VCard32 address = VSocket::Resolve(name); delete [] name; if (address != 0) { // Post the IP address to the server // We can not contact a runnning service, permissions, so we must store the settings // and process until the vncmenu has been started vnclog.Print(LL_INTERR, VNCLOG("PostAddNewClient III \n")); if (!vncService::PostAddNewClientInit(address, port)) { PostAddNewClient_bool=true; port_int=port; address_vcard=address; } } else { //ask for host,port PostAddNewClient_bool=true; port_int=0; address_vcard=0; Sleep(2000); //Beep(200,1000); return 0; } } i=end; continue; } else { // Tell the server to show the Add New Client dialog // We can not contact a runnning service, permissions, so we must store the settings // and process until the vncmenu has been started vnclog.Print(LL_INTERR, VNCLOG("PostAddNewClient IIII\n")); if (!vncService::PostAddNewClient(0, 0)) { PostAddNewClient_bool=true; port_int=0; address_vcard=0; } } continue; } //adzm 2009-06-20 if (strncmp(&szCmdLine[i], winvncRepeater, strlen(winvncRepeater)) == 0) { // set the default repeater host i+=strlen(winvncRepeater); // First, we have to parse the command line to get the host to use int start, end; start=i; while (szCmdLine[start] <= ' ' && szCmdLine[start] != 0) start++; end = start; while (szCmdLine[end] > ' ') end++; // Was there a hostname (and optionally a port number) given? if (end-start > 0) { if (g_szRepeaterHost) { delete[] g_szRepeaterHost; g_szRepeaterHost = NULL; } g_szRepeaterHost = new char[end-start+1]; if (g_szRepeaterHost != 0) { strncpy(g_szRepeaterHost, &(szCmdLine[start]), end-start); g_szRepeaterHost[end-start] = 0; // We can not contact a runnning service, permissions, so we must store the settings // and process until the vncmenu has been started vnclog.Print(LL_INTERR, VNCLOG("PostAddNewRepeaterClient I\n")); if (!vncService::PostAddNewRepeaterClient()) { PostAddNewRepeaterClient_bool=true; port_int=0; address_vcard=0; } } i=end; continue; } else { /* // Tell the server to show the Add New Client dialog // We can not contact a runnning service, permissions, so we must store the settings // and process until the vncmenu has been started vnclog.Print(LL_INTERR, VNCLOG("PostAddNewClient IIII\n")); if (!vncService::PostAddNewClient(0, 0)) { PostAddNewClient_bool=true; port_int=0; address_vcard=0; } */ } continue; } // Either the user gave the -help option or there is something odd on the cmd-line! // Show the usage dialog MessageBoxSecure(NULL, winvncUsageText, sz_ID_WINVNC_USAGE, MB_OK | MB_ICONINFORMATION); break; }; // If no arguments were given then just run if (!argfound) { if (!Myinit(hInstance)) { #ifdef CRASHRPT crUninstall(); #endif return 0; } int returnvalue= WinVNCAppMain(); #ifdef CRASHRPT crUninstall(); #endif return returnvalue; } #ifdef CRASHRPT crUninstall(); #endif return 0; }
int main(int argc, char *argv[]) { int i; pid_t pid; char *package_name = NULL; char *service_name = NULL; char *daemon_file_dir = NULL; int interval = SLEEP_INTERVAL; LOGI(LOG_TAG, "Copyright (c) 2015, Vincent Cheung<*****@*****.**>"); if (argc < 7) { LOGE(LOG_TAG, "usage: %s -p package-name -s " "daemon-service-name -t interval-time", argv[0]); return; } for (i = 0; i < argc; i ++) { if (!strcmp("-p", argv[i])) { package_name = argv[i + 1]; LOGD(LOG_TAG, "package name: %s", package_name); } if (!strcmp("-s", argv[i])) { service_name = argv[i + 1]; LOGD(LOG_TAG, "service name: %s", service_name); } if (!strcmp("-t", argv[i])) { interval = atoi(argv[i + 1]); LOGD(LOG_TAG, "interval: %d", interval); } } /* package name and service name should not be null */ if (package_name == NULL || service_name == NULL) { LOGE(LOG_TAG, "package name or service name is null"); return; } if ((pid = fork()) < 0) { exit(EXIT_SUCCESS); } else if (pid == 0) { /* add signal */ signal(SIGTERM, sigterm_handler); /* become session leader */ setsid(); /* change work directory */ chdir("/"); for (i = 0; i < MAXFILE; i ++) { close(i); } /* find pid by name and kill them */ int pid_list[100]; int total_num = find_pid_by_name(argv[0], pid_list); LOGD(LOG_TAG, "total num %d", total_num); for (i = 0; i < total_num; i ++) { int retval = 0; int daemon_pid = pid_list[i]; if (daemon_pid > 1 && daemon_pid != getpid()) { retval = kill(daemon_pid, SIGTERM); if (!retval) { LOGD(LOG_TAG, "kill daemon process success: %d", daemon_pid); } else { LOGD(LOG_TAG, "kill daemon process %d fail: %s", daemon_pid, strerror(errno)); exit(EXIT_SUCCESS); } } } LOGD(LOG_TAG, "child process fork ok, daemon start: %d", getpid()); while(sig_running) { interval = interval < SLEEP_INTERVAL ? SLEEP_INTERVAL : interval; select_sleep(interval, 0); LOGD(LOG_TAG, "check the service once, interval: %d", interval); /* start service */ start_service(package_name, service_name); } exit(EXIT_SUCCESS); } else { /* parent process */ exit(EXIT_SUCCESS); } }
// // Windows メイン関数 // int WINAPI _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpszArgs, int nWinMode) { MSG msg; HWND hMain; int err; // 初期化 install_flag = FALSE; uninstall_flag = FALSE; read_ini_flag = FALSE; start_flag = FALSE; no_error_flag = FALSE; question_flag = FALSE; ok_flag = FALSE; h_instance = hInstance; // 実行ディレクトリにある sexe.exe のフルパスを作成 GetModuleFileName(NULL, module_name, sizeof(module_name)); lstrcpy(execute_path, module_name); extract_directory(execute_path); lstrcpy(ini_name, execute_path); lstrcat(ini_name, _T("\\sexe.ini")); // コマンドライン解析 analyze_args(lpszArgs); // サービスで動作しているか? service_flag = check_execute_service(); // WindowsNT/2000 ? if(nt_flag) { // サービスとして動作中? if(service_flag) { // すでに動作中? if(!check_already()) { // サービスとして起動 start_service(); } } else { // 2011/5/31 // コマンドラインパラメータでインストール・アンインストール if(install_flag) { TCHAR *ext; if(service_name[0] == _T('\0')) { if(!no_error_flag) { // サービス名を指定してください MessageBoxResourceText(NULL, IDS_ERROR_NO_SERVICE_NAME, NULL, ERROR_HEADER, MB_OK); } return ERROR_PARAMETER; } ext = extract_ext(exe_name); if(exe_name[0] == _T('\0') || (_tcsicmp(ext, _T("exe")) && _tcsicmp(ext, _T("bat")))) { if(!no_error_flag) { // プログラム名を指定してください MessageBoxResourceText(NULL, IDS_ERROR_NO_PROGRAM_NAME, NULL, ERROR_HEADER, MB_OK); } return ERROR_PARAMETER; } if(question_flag) { // サービス service_name を登録しますか? if(MessageBoxResourceText(NULL, IDS_QUESTION_INSTALL, service_name, ERROR_HEADER, MB_YESNO) != IDYES) { return ERROR_NO_INSTALL; } } if(!read_ini_flag) { // ini ファイルから読み出したのでなければ設定値を保存 set_inifile(); } // インストール if((err = install_service()) == ERROR_SUCCESS) { if(start_flag) { // サービス開始 if(restart_service()) { if(ok_flag) { // サービス service_name を登録し、開始しました。 MessageBoxResourceText(NULL, IDS_INSTALL_START_OK, service_name, HEADER, MB_OK); } } else if(!no_error_flag) { // サービス service_name を登録しましたが、開始に失敗しました。 MessageBoxResourceText(NULL, IDS_ERROR_INSTALL_START, service_name, HEADER, MB_OK); return ERROR_START; } } else if(ok_flag) { // サービス service_name を登録しました。 MessageBoxResourceText(NULL, IDS_INSTALL_OK, service_name, HEADER, MB_OK); } } else { if(!no_error_flag) { if(err == ERROR_SERVICE_EXISTS) { // すでに同名のサービスが登録済みです MessageBoxResourceText(NULL, IDS_ERROR_SAME_SERVICE, NULL, ERROR_HEADER, MB_OK); } else { // サービスに登録できませんでした。\nサービスの権限があるユーザーでログインして実行してください。 MessageBoxResourceText(NULL, IDS_ERROR_INSTALL_SERVICE, NULL, ERROR_HEADER, MB_OK); } } return ERROR_INSTALL; } } else if(uninstall_flag) { if(service_name[0] == _T('\0')) { if(!no_error_flag) { // サービス名を指定してください MessageBoxResourceText(NULL, IDS_ERROR_NO_SERVICE_NAME, NULL, ERROR_HEADER, MB_OK); } return ERROR_PARAMETER; } if(question_flag) { // サービス service_name を削除しますか? if(MessageBoxResourceText(NULL, IDS_QUESTION_UNINSTALL, service_name, HEADER, MB_YESNO) != IDYES) { return ERROR_NO_INSTALL; } } if(service_install_flag) { // サービスから削除 if(remove_service()) { if(ok_flag) { // サービス service_name を削除しました MessageBoxResourceText(NULL, IDS_UNINSTALL_OK, service_name, HEADER, MB_OK); } } else { if(!no_error_flag) { // サービスから削除できませんでした。\nサービスの権限があるユーザーでログインして実行してください。 MessageBoxResourceText(NULL, IDS_ERROR_UNINSTALL_SERVICE, NULL, ERROR_HEADER, MB_OK); } return ERROR_INSTALL; } } else { if(!no_error_flag) { // サービス service_name は登録されていません MessageBoxResourceText(NULL, IDS_ERROR_NOT_INSTALL_SERVICE, service_name, ERROR_HEADER, MB_OK); } return ERROR_INSTALL; } } else { // 2010/6/10 Vista/7 で WM_DROPFILES を受ける funcChangeWindowMessageFilter ChangeWindowMessageFilter; if(ChangeWindowMessageFilter = (funcChangeWindowMessageFilter)GetProcAddress(LoadLibrary(_T("user32.dll")) ,"ChangeWindowMessageFilter")) { ChangeWindowMessageFilter(WM_DROPFILES, MSGFLT_ADD); ChangeWindowMessageFilter(WM_COPYDATA, MSGFLT_ADD); ChangeWindowMessageFilter(0x0049, MSGFLT_ADD); } // 設定ダイアログを表示 hMain = CreateDialog(hInstance, MAKEINTRESOURCE(IDD_DIALOG_SETUP), GetDesktopWindow(), (DLGPROC)MainFunc); ShowWindow(hMain, SW_SHOW); // Drag&Drop を受け入れる準備 DragAcceptFiles(hMain, TRUE); while(GetMessage(&msg, NULL, 0, 0)) { if(!IsDialogMessage(hMain, &msg)) { TranslateMessage(&msg); DispatchMessage(&msg); } } } } } else { // Windows NT/2000/XP/Vista/7 で起動してください。 MessageBoxResourceText(NULL, IDS_ERROR_OS, NULL, ERROR_HEADER, MB_OK); } return 0; }
int service_listen(void) { int sock; fd_set read_set; int status; struct sockaddr_in addr = { .sin_family = AF_INET, .sin_port = htons(PORT), .sin_addr = { INADDR_ANY } }; sock = socket(AF_INET, SOCK_STREAM, 0); if (sock == -1) { fprintf(stderr, "Failed to create listening socket: %s\n", strerror(errno)); return -1; } status = bind(sock, (struct sockaddr*)&addr, sizeof(addr)); if (status == -1) { fprintf(stderr, "Failed to bind() socket: %s\n", strerror(errno)); return -1; } status = listen(sock, 2); if (status == -1) { fprintf(stderr, "Error in listen(): %s\n", strerror(errno)); return -1; } FD_ZERO(&read_set); FD_SET(sock, &read_set); for (;;) { printf("selecting.........\n"); fflush(stdout); status = select(sock+1, &read_set, NULL, NULL, NULL); printf("select returned!! %d\n", status); fflush(stdout); if (status == 0) continue; if (status == -1) { fprintf(stderr, "Failed on select(): %s\n", strerror(errno)); return -1; } break; } status = close(sock); if (status == -1) { fprintf(stderr, "Failed to close() socket: %s\n", strerror(errno)); return -1; } start_service(); return 0; }
static void handle_uevent(struct uevent *uevent) { // We need to handle the write_uevent_logcat(uevent,"DONGLED"); int c =uevent->action[0]; switch(c) { case 'a':{ if( strlen(uevent->type) == 0 ) { // if no type is specified then look for a tty subsystem if ( strlen(uevent->subsystem) == 0 ){ // handle zero length subsystem return ; // No Subsystem and No type means nothing doing }else if( !strncmp(uevent->subsystem,"tty",strlen(uevent->subsystem))){ // got a tty subsystem if(!strncmp(uevent->name,"ttyUSB0",strlen(uevent->name))){ property_set("ril.pppd_tty", "/dev/ttyUSB0"); return ; } if(!strncmp(uevent->name,"ttyHS4",strlen(uevent->name)) ){ property_set("ril.pppd_tty", "/dev/ttyHS4"); return ; } if(!strncmp(uevent->name,"ttyHS3",strlen(uevent->name))){ property_set("rild.libargs", "-d /dev/ttyHS3"); property_set("rild.libpath", "/system/lib/libtcl-ril.so"); stop_service("ril-daemon"); sleep(1); start_service("ril-daemon"); return ; } if(!strncmp(uevent->name,"ttyUSB2",strlen(uevent->name))) { property_set("rild.libargs", "-d /dev/ttyUSB2"); property_set("rild.libpath", "/system/lib/libhuaweigeneric-ril.so"); stop_service("ril-daemon"); sleep(1); start_service("ril-daemon"); return; } } return; }else{ if( !strncmp(uevent->type,"usb_device",strlen(uevent->type))) { // i'm not a massive fan of sleeping, it implies an unknown quantity // however we need to give the usb subsystem a chance to catch up // there is another option of handling the uevent->type = "usb_interface" // but that is fired multiple times where as usb_device is raised once sleep(2); // convert the vendor and product to int, this is more convient than messing around with strings int vendor = get_int_from_hexstring(uevent->vendor_id); int product = get_int_from_hexstring(uevent->product_id); process_add_usb_device_uevent(vendor,product); return ; } } } } return ; }