int run_net_script(envid_t veid, int op, list_head_t *ip_h, int state, int skip_arpdetect) { char *argv[3]; char *envp[10]; char *script; int ret; char buf[STR_SIZE]; int i = 0; char *skip_str = "SKIP_ARPDETECT=yes"; if (list_empty(ip_h)) return 0; snprintf(buf, sizeof(buf), "VEID=%d", veid); envp[i++] = strdup(buf); snprintf(buf, sizeof(buf), "VE_STATE=%s", state2str(state)); envp[i++] = strdup(buf); envp[i++] = list2str("IP_ADDR", ip_h); envp[i++] = strdup(ENV_PATH); if (skip_arpdetect) envp[i++] = strdup(skip_str); envp[i] = NULL; switch (op) { case ADD: script = VPS_NET_ADD; break; case DEL: script = VPS_NET_DEL; break; default: return 0; } argv[0] = script; argv[1] = NULL; ret = run_script(script, argv, envp, 0); free_arg(envp); return ret; }
bool GLExecPrivSepHelper::chown_sandbox_to_user(PrivSepError &err) { ASSERT(m_initialized); if (m_sandbox_owned_by_user) { dprintf(D_FULLDEBUG, "GLExecPrivSepHelper::chown_sandbox_to_user: "******"sandbox already user-owned\n"); return true; } dprintf(D_FULLDEBUG, "changing sandbox ownership to the user\n"); ArgList args; args.AppendArg(m_setup_script); args.AppendArg(m_glexec); args.AppendArg(m_proxy); args.AppendArg(m_sandbox); args.AppendArg(m_glexec_retries); args.AppendArg(m_glexec_retry_delay); MyString error_desc = "error changing sandbox ownership to the user: "******"GLEXEC_HOLD_ON_INITIAL_FAILURE",true) ) { // Do not put the job on hold due to glexec failure. // It will simply return to idle status and try again. hold_code = 0; } err.setHoldInfo( hold_code, rc, error_desc.Value()); return false; } m_sandbox_owned_by_user = true; return true; }
int main(int argc, char** argv, char** env) { int status; char* fake_argv[3]; running_as_cgi = 1; check_caller(logident, parentgid); /* for these CGI programs, we can ignore argc and argv since they * don't contain anything useful. `script' will always be the driver * program and argv will always just contain the name of the real * script for the driver to import and execute (padded with two dummy * values in argv[0] and argv[1] that are ignored by run_script(). */ fake_argv[0] = NULL; fake_argv[1] = NULL; fake_argv[2] = script; status = run_script("driver", 3, fake_argv, env); fatal(logident, status, "%s", strerror(errno)); return status; }
int start (int argc, char **argv) { int rc; PyObject *new_path; PySys_SetArgv(argc, argv); // PySys_SetArgv munged the path - specifically, it added the // directory of argv[0] at the start of sys.path. // Create a new list object for the path, and rely on our // implementation knowledge of set_path above, which writes into // the static Py_GetPath() buffer (Note: Py_GetPath() does *not* // return the current sys.path value - its just a static buffer // holding the initial Python paths) new_path = PyList_New(1); if (new_path) { PyObject *entry = PyString_FromString(Py_GetPath()); if (entry && (0==PyList_SetItem(new_path, 0, entry))) PySys_SetObject("path", new_path); Py_DECREF(new_path); } rc = run_script(); fini(); return rc; }
bool PreludeScript::run() { v8::Context::Scope context_scope(get_context()); global_template_factory.Dispose(); global_template_factory.Clear(); //TODO: check whether proper type of value returned v8::Handle<v8::Value> prelude_result = run_script(get_context()); if (prelude_result.IsEmpty()) { set_last_error(v8::String::New("Prelude script did not return any value")); return false; } if (prelude_result->IsFunction()) { global_template_factory = v8::Persistent<v8::Function>::New(prelude_result.As<v8::Function>()); return true; } else { set_last_error(v8::String::New("Prelude script must return a function")); return false; } }
/* perform a release */ static void perform_release(void) { char buffer[16]; struct in_addr temp_addr; /* send release packet */ #if !defined(TCSUPPORT_CT) if (state == BOUND || state == RENEWING || state == REBINDING || state == REQUESTING || state == RENEW_REQUESTED) { #endif temp_addr.s_addr = server_addr; sprintf(buffer, "%s", inet_ntoa(temp_addr)); temp_addr.s_addr = requested_ip; LOG(LOG_INFO, "Unicasting a release of %s to %s", inet_ntoa(temp_addr), buffer); send_release(server_addr, requested_ip); /* unicast */ run_script(NULL, "deconfig"); } LOG(LOG_INFO, "Entering released state"); change_mode(LISTEN_NONE); state = RELEASED; timeout = 0x7fffffff; }
int run_and_remove_extendedcommand() { char tmp[PATH_MAX]; sprintf(tmp, "cp %s /tmp/%s", EXTENDEDCOMMAND_SCRIPT, basename(EXTENDEDCOMMAND_SCRIPT)); __system(tmp); remove(EXTENDEDCOMMAND_SCRIPT); int i = 0; for (i = 20; i > 0; i--) { ui_print("Waiting for SD Card to mount (%ds)\n", i); if (ensure_path_mounted("/sdcard") == 0) { ui_print("SD Card mounted...\n"); break; } sleep(1); } remove("/sdcard/clockworkmod/.recoverycheckpoint"); if (i == 0) { ui_print("Timed out waiting for SD card... continuing anyways."); } sprintf(tmp, "/tmp/%s", basename(EXTENDEDCOMMAND_SCRIPT)); return run_script(tmp); }
static int maybe_make_dhfile(struct conf *conf, const char *ca_dir) { int a=0; const char *args[12]; char *path=NULL; struct stat statp; if(!lstat(conf->ssl_dhfile, &statp)) { free(path); return 0; } setup_stuff_done++; logp("Creating %s\n", conf->ssl_dhfile); logp("Running '%s --dhfile %s --dir %s'\n", conf->ca_burp_ca, conf->ssl_dhfile, ca_dir); a=0; args[a++]=conf->ca_burp_ca; args[a++]="--dhfile"; args[a++]=conf->ssl_dhfile; args[a++]="--dir"; args[a++]=ca_dir; args[a++]=NULL; if(run_script(NULL /* no async yet */, args, NULL, conf, 1 /* wait */, 0, 0 /* do not use logp - stupid openssl prints lots of dots one at a time with no way to turn it off */)) { logp("Error running %s\n", conf->ca_burp_ca); free(path); return -1; } free(path); return 0; }
int main(int argc, char *argv[]) { atexit(x); if (argc != 2) { fprintf(stderr, "Usage: %s {test-script}\n", argv[0]); return EXIT_FAILURE; } FILE *script = fopen(argv[1], "r"); if (!script) { fprintf(stderr, "Failed loading script file: %s\n", argv[1]); return EXIT_FAILURE; } if (!run_script(script)) { fprintf(stderr, "Failed running test script\n"); fclose(script); return EXIT_FAILURE; } fclose(script); return EXIT_SUCCESS; }
static int run_timer_script( struct asfd *asfd, const char *timer_script, const char *cname, struct sdirs *sdirs, struct strlist *timer_args, struct conf **cconfs) { int a=0; const char *args[12]; args[a++]=timer_script; args[a++]=cname; args[a++]=sdirs->current; args[a++]=sdirs->clients; args[a++]="reserved1"; args[a++]="reserved2"; args[a++]=NULL; return run_script(asfd, args, timer_args, cconfs, 1 /* wait */, 1 /* use logp */, 0 /* no log_remote */); }
int GUIAction::doAction(Action action, int isThreaded /* = 0 */) { static string zip_queue[10]; static int zip_queue_index; int simulate; std::string arg = gui_parse_text(action.mArg); std::string function = gui_parse_text(action.mFunction); DataManager::GetValue(TW_SIMULATE_ACTIONS, simulate); if (function == "reboot") { //curtainClose(); this sometimes causes a crash sync(); if (arg == "recovery") tw_reboot(rb_recovery); else if (arg == "poweroff") tw_reboot(rb_poweroff); else if (arg == "bootloader") tw_reboot(rb_bootloader); else if (arg == "download") tw_reboot(rb_download); else tw_reboot(rb_system); // This should never occur return -1; } if (function == "home") { PageManager::SelectPackage("TWRP"); gui_changePage("main"); return 0; } if (function == "key") { PageManager::NotifyKey(getKeyByName(arg)); return 0; } if (function == "page") { std::string page_name = gui_parse_text(arg); return gui_changePage(page_name); } if (function == "reload") { int check = 0, ret_val = 0; std::string theme_path; operation_start("Reload Theme"); theme_path = DataManager::GetSettingsStoragePath(); if (ensure_path_mounted(theme_path.c_str()) < 0) { LOGE("Unable to mount %s during reload function startup.\n", theme_path.c_str()); check = 1; } theme_path += "/TWRP/theme/ui.zip"; if (check != 0 || PageManager::ReloadPackage("TWRP", theme_path) != 0) { // Loading the custom theme failed - try loading the stock theme LOGI("Attempting to reload stock theme...\n"); if (PageManager::ReloadPackage("TWRP", "/res/ui.xml")) { LOGE("Failed to load base packages.\n"); ret_val = 1; } } operation_end(ret_val, simulate); } if (function == "readBackup") { set_restore_files(); return 0; } if (function == "set") { if (arg.find('=') != string::npos) { string varName = arg.substr(0, arg.find('=')); string value = arg.substr(arg.find('=') + 1, string::npos); DataManager::GetValue(value, value); DataManager::SetValue(varName, value); } else DataManager::SetValue(arg, "1"); return 0; } if (function == "clear") { DataManager::SetValue(arg, "0"); return 0; } if (function == "mount") { if (arg == "usb") { DataManager::SetValue(TW_ACTION_BUSY, 1); if (!simulate) usb_storage_enable(); else ui_print("Simulating actions...\n"); } else if (!simulate) { string cmd; if (arg == "EXTERNAL") cmd = "mount " + DataManager::GetStrValue(TW_EXTERNAL_MOUNT); else if (arg == "INTERNAL") cmd = "mount " + DataManager::GetStrValue(TW_INTERNAL_MOUNT); else cmd = "mount " + arg; __system(cmd.c_str()); if (arg == "/data" && DataManager::GetIntValue(TW_HAS_DATADATA) == 1) __system("mount /datadata"); } else ui_print("Simulating actions...\n"); return 0; } if (function == "umount" || function == "unmount") { if (arg == "usb") { if (!simulate) usb_storage_disable(); else ui_print("Simulating actions...\n"); DataManager::SetValue(TW_ACTION_BUSY, 0); } else if (!simulate) { string cmd; if (arg == "EXTERNAL") cmd = "umount " + DataManager::GetStrValue(TW_EXTERNAL_MOUNT); else if (arg == "INTERNAL") cmd = "umount " + DataManager::GetStrValue(TW_INTERNAL_MOUNT); else if (DataManager::GetIntValue(TW_DONT_UNMOUNT_SYSTEM) == 1 && (arg == "system" || arg == "/system")) return 0; else cmd = "umount " + arg; __system(cmd.c_str()); if (arg == "/data" && DataManager::GetIntValue(TW_HAS_DATADATA) == 1) __system("umount /datadata"); } else ui_print("Simulating actions...\n"); return 0; } if (function == "restoredefaultsettings") { operation_start("Restore Defaults"); if (simulate) // Simulated so that people don't accidently wipe out the "simulation is on" setting ui_print("Simulating actions...\n"); else { DataManager::ResetDefaults(); mount_current_storage(); } operation_end(0, simulate); } if (function == "copylog") { operation_start("Copy Log"); if (!simulate) { char command[255]; mount_current_storage(); sprintf(command, "cp /tmp/recovery.log %s", DataManager::GetCurrentStoragePath().c_str()); __system(command); sync(); ui_print("Copied recovery log to %s.\n", DataManager::GetCurrentStoragePath().c_str()); } else simulate_progress_bar(); operation_end(0, simulate); return 0; } if (function == "compute" || function == "addsubtract") { if (arg.find("+") != string::npos) { string varName = arg.substr(0, arg.find('+')); string string_to_add = arg.substr(arg.find('+') + 1, string::npos); int amount_to_add = atoi(string_to_add.c_str()); int value; DataManager::GetValue(varName, value); DataManager::SetValue(varName, value + amount_to_add); return 0; } if (arg.find("-") != string::npos) { string varName = arg.substr(0, arg.find('-')); string string_to_subtract = arg.substr(arg.find('-') + 1, string::npos); int amount_to_subtract = atoi(string_to_subtract.c_str()); int value; DataManager::GetValue(varName, value); value -= amount_to_subtract; if (value <= 0) value = 0; DataManager::SetValue(varName, value); return 0; } } if (function == "setguitimezone") { string SelectedZone; DataManager::GetValue(TW_TIME_ZONE_GUISEL, SelectedZone); // read the selected time zone into SelectedZone string Zone = SelectedZone.substr(0, SelectedZone.find(';')); // parse to get time zone string DSTZone = SelectedZone.substr(SelectedZone.find(';') + 1, string::npos); // parse to get DST component int dst; DataManager::GetValue(TW_TIME_ZONE_GUIDST, dst); // check wether user chose to use DST string offset; DataManager::GetValue(TW_TIME_ZONE_GUIOFFSET, offset); // pull in offset string NewTimeZone = Zone; if (offset != "0") NewTimeZone += ":" + offset; if (dst != 0) NewTimeZone += DSTZone; DataManager::SetValue(TW_TIME_ZONE_VAR, NewTimeZone); update_tz_environment_variables(); return 0; } if (function == "togglestorage") { if (arg == "internal") { DataManager::SetValue(TW_USE_EXTERNAL_STORAGE, 0); DataManager::SetValue(TW_STORAGE_FREE_SIZE, (int)((sdcint.sze - sdcint.used) / 1048576LLU)); } else if (arg == "external") { DataManager::SetValue(TW_USE_EXTERNAL_STORAGE, 1); DataManager::SetValue(TW_STORAGE_FREE_SIZE, (int)((sdcext.sze - sdcext.used) / 1048576LLU)); } if (mount_current_storage() == 0) { if (arg == "internal") { // Save the current zip location to the external variable DataManager::SetValue(TW_ZIP_EXTERNAL_VAR, DataManager::GetStrValue(TW_ZIP_LOCATION_VAR)); // Change the current zip location to the internal variable DataManager::SetValue(TW_ZIP_LOCATION_VAR, DataManager::GetStrValue(TW_ZIP_INTERNAL_VAR)); } else if (arg == "external") { // Save the current zip location to the internal variable DataManager::SetValue(TW_ZIP_INTERNAL_VAR, DataManager::GetStrValue(TW_ZIP_LOCATION_VAR)); // Change the current zip location to the external variable DataManager::SetValue(TW_ZIP_LOCATION_VAR, DataManager::GetStrValue(TW_ZIP_EXTERNAL_VAR)); } } else { // We weren't able to toggle for some reason, restore original setting if (arg == "internal") { DataManager::SetValue(TW_USE_EXTERNAL_STORAGE, 1); DataManager::SetValue(TW_STORAGE_FREE_SIZE, (int)((sdcext.sze - sdcext.used) / 1048576LLU)); } else if (arg == "external") { DataManager::SetValue(TW_USE_EXTERNAL_STORAGE, 0); DataManager::SetValue(TW_STORAGE_FREE_SIZE, (int)((sdcint.sze - sdcint.used) / 1048576LLU)); } } return 0; } if (function == "overlay") return gui_changeOverlay(arg); if (function == "queuezip") { if (zip_queue_index >= 10) { ui_print("Maximum zip queue reached!\n"); return 0; } DataManager::GetValue("tw_filename", zip_queue[zip_queue_index]); if (strlen(zip_queue[zip_queue_index].c_str()) > 0) { zip_queue_index++; DataManager::SetValue(TW_ZIP_QUEUE_COUNT, zip_queue_index); } return 0; } if (function == "cancelzip") { if (zip_queue_index <= 0) { ui_print("Minimum zip queue reached!\n"); return 0; } else { zip_queue_index--; DataManager::SetValue(TW_ZIP_QUEUE_COUNT, zip_queue_index); } return 0; } if (function == "queueclear") { zip_queue_index = 0; DataManager::SetValue(TW_ZIP_QUEUE_COUNT, zip_queue_index); return 0; } if (function == "sleep") { usleep(atoi(arg.c_str())); return 0; } if (isThreaded) { if (function == "flash") { int i, ret_val = 0; for (i=0; i<zip_queue_index; i++) { operation_start("Flashing"); DataManager::SetValue("tw_filename", zip_queue[i]); DataManager::SetValue(TW_ZIP_INDEX, (i + 1)); ret_val = flash_zip(zip_queue[i], arg, simulate); if (ret_val != 0) { ui_print("Error flashing zip '%s'\n", zip_queue[i].c_str()); i = 10; // Error flashing zip - exit queue ret_val = 1; } } zip_queue_index = 0; DataManager::SetValue(TW_ZIP_QUEUE_COUNT, zip_queue_index); if (DataManager::GetIntValue(TW_HAS_INJECTTWRP) == 1 && DataManager::GetIntValue(TW_INJECT_AFTER_ZIP) == 1) { operation_start("ReinjectTWRP"); ui_print("Injecting TWRP into boot image...\n"); if (simulate) { simulate_progress_bar(); } else { __system("injecttwrp --dump /tmp/backup_recovery_ramdisk.img /tmp/injected_boot.img --flash"); ui_print("TWRP injection complete.\n"); } } operation_end(ret_val, simulate); return 0; } if (function == "wipe") { operation_start("Format"); DataManager::SetValue("tw_partition", arg); if (simulate) { simulate_progress_bar(); } else { if (arg == "data") wipe_data(0); else if (arg == "battery") wipe_battery_stats(); else if (arg == "rotate") wipe_rotate_data(); else if (arg == "dalvik") wipe_dalvik_cache(); else erase_volume(arg.c_str()); if (arg == "/sdcard") { ensure_path_mounted(SDCARD_ROOT); mkdir("/sdcard/TWRP", 0777); DataManager::Flush(); } } update_system_details(); operation_end(0, simulate); return 0; } if (function == "refreshsizes") { operation_start("Refreshing Sizes"); if (simulate) { simulate_progress_bar(); } else update_system_details(); operation_end(0, simulate); } if (function == "nandroid") { operation_start("Nandroid"); if (simulate) { DataManager::SetValue("tw_partition", "Simulation"); simulate_progress_bar(); } else { if (arg == "backup") nandroid_back_exe(); else if (arg == "restore") nandroid_rest_exe(); else { operation_end(1, simulate); return -1; } } operation_end(0, simulate); return 0; } if (function == "fixpermissions") { operation_start("Fix Permissions"); LOGI("fix permissions started!\n"); if (simulate) { simulate_progress_bar(); } else fix_perms(); LOGI("fix permissions DONE!\n"); operation_end(0, simulate); return 0; } if (function == "dd") { operation_start("imaging"); if (simulate) { simulate_progress_bar(); } else { char cmd[512]; sprintf(cmd, "dd %s", arg.c_str()); __system(cmd); } operation_end(0, simulate); return 0; } if (function == "partitionsd") { operation_start("Partition SD Card"); if (simulate) { simulate_progress_bar(); } else { int allow_partition; DataManager::GetValue(TW_ALLOW_PARTITION_SDCARD, allow_partition); if (allow_partition == 0) { ui_print("This device does not have a real SD Card!\nAborting!\n"); } else { // Below seen in Koush's recovery char sddevice[256]; Volume *vol = volume_for_path("/sdcard"); strcpy(sddevice, vol->device); // Just need block not whole partition sddevice[strlen("/dev/block/mmcblkX")] = NULL; char es[64]; std::string ext_format; int ext, swap; DataManager::GetValue("tw_sdext_size", ext); DataManager::GetValue("tw_swap_size", swap); DataManager::GetValue("tw_sdpart_file_system", ext_format); sprintf(es, "/sbin/sdparted -es %dM -ss %dM -efs %s -s > /cache/part.log",ext,swap,ext_format.c_str()); LOGI("\nrunning script: %s\n", es); run_script("\nContinue partitioning?", "\nPartitioning sdcard : ", es, "\nunable to execute parted!\n(%s)\n", "\nOops... something went wrong!\nPlease check the recovery log!\n", "\nPartitioning complete!\n\n", "\nPartitioning aborted!\n\n", 0); // recreate TWRP folder and rewrite settings - these will be gone after sdcard is partitioned ensure_path_mounted(SDCARD_ROOT); mkdir("/sdcard/TWRP", 0777); DataManager::Flush(); DataManager::SetValue(TW_ZIP_EXTERNAL_VAR, "/sdcard"); if (DataManager::GetIntValue(TW_USE_EXTERNAL_STORAGE) == 1) DataManager::SetValue(TW_ZIP_LOCATION_VAR, "/sdcard"); update_system_details(); } } operation_end(0, simulate); return 0; } if (function == "installhtcdumlock") { operation_start("Install HTC Dumlock"); if (simulate) { simulate_progress_bar(); } else install_htc_dumlock(); operation_end(0, simulate); return 0; } if (function == "htcdumlockrestoreboot") { operation_start("HTC Dumlock Restore Boot"); if (simulate) { simulate_progress_bar(); } else htc_dumlock_restore_original_boot(); operation_end(0, simulate); return 0; } if (function == "htcdumlockreflashrecovery") { operation_start("HTC Dumlock Reflash Recovery"); if (simulate) { simulate_progress_bar(); } else htc_dumlock_reflash_recovery_to_boot(); operation_end(0, simulate); return 0; } if (function == "cmd") { int op_status = 0; operation_start("Command"); ui_print("Running command: '%s'\n", arg.c_str()); if (simulate) { simulate_progress_bar(); } else { op_status = __system(arg.c_str()); if (op_status != 0) op_status = 1; } operation_end(op_status, simulate); return 0; } if (function == "reinjecttwrp") { int op_status = 0; operation_start("ReinjectTWRP"); ui_print("Injecting TWRP into boot image...\n"); if (simulate) { simulate_progress_bar(); } else { __system("injecttwrp --dump /tmp/backup_recovery_ramdisk.img /tmp/injected_boot.img --flash"); ui_print("TWRP injection complete.\n"); } operation_end(op_status, simulate); return 0; } } else { pthread_t t; pthread_create(&t, NULL, thread_start, this); return 0; } return -1; }
int main(void) { struct script_config config; struct kerberos_config *krbconf; char *user; /* * Load the Kerberos principal and password from a file, but set the * principal as extra[0] and use something else bogus as the user. We * want to test that alt_auth_map works when there's no relationship * between the mapped principal and the user. */ krbconf = kerberos_setup(TAP_KRB_NEEDS_PASSWORD); memset(&config, 0, sizeof(config)); config.user = "******"; config.authtok = krbconf->password; config.extra[0] = krbconf->username; config.extra[1] = krbconf->userprinc; /* * Generate a testing krb5.conf file with a nonexistent default realm so * that we can be sure that our principals will stay fully-qualified in * the logs. */ kerberos_generate_conf("bogus.example.com"); config.extra[2] = "bogus.example.com"; /* Test without password prompting. */ plan_lazy(); run_script("data/scripts/alt-auth/basic", &config); run_script("data/scripts/alt-auth/basic-debug", &config); run_script("data/scripts/alt-auth/fail", &config); run_script("data/scripts/alt-auth/fail-debug", &config); run_script("data/scripts/alt-auth/force", &config); run_script("data/scripts/alt-auth/only", &config); /* * If the alternate account exists but the password is incorrect, we * should not fall back to the regular account. Test with debug so that * we don't need two principals configured. */ config.authtok = "bogus incorrect password"; run_script("data/scripts/alt-auth/force-fail-debug", &config); /* * Switch to our correct user (but wrong realm) realm to test username * mapping to a different realm. */ config.authtok = krbconf->password; config.user = krbconf->username; config.extra[2] = krbconf->realm; run_script("data/scripts/alt-auth/username-map", &config); /* * Split the username into two parts, one in the PAM configuration and one * in the real username, so that we can test interpolation of the username * when %s isn't the first token. */ config.user = &krbconf->username[1]; user = bstrndup(krbconf->username, 1); config.extra[3] = user; run_script("data/scripts/alt-auth/username-map-prefix", &config); free(user); config.extra[3] = NULL; /* * Ensure that we don't add the realm of the authentication username when * the alt_auth_map already includes a realm. */ basprintf(&user, "*****@*****.**", krbconf->username); config.user = user; diag("re-running username-map with fully-qualified PAM user"); run_script("data/scripts/alt-auth/username-map", &config); free(user); config.user = krbconf->username; /* * Add the password and make the user match our authentication principal, * and then test fallback to normal authentication when alternative * authentication fails. */ config.user = krbconf->userprinc; config.password = krbconf->password; config.extra[2] = krbconf->realm; run_script("data/scripts/alt-auth/fallback", &config); run_script("data/scripts/alt-auth/fallback-debug", &config); run_script("data/scripts/alt-auth/fallback-realm", &config); run_script("data/scripts/alt-auth/force-fallback", &config); run_script("data/scripts/alt-auth/only-fail", &config); return 0; }
int main(int argc, char *argv[]) #endif { unsigned char *temp, *message; unsigned long t1 = 0, t2 = 0, xid = 0; unsigned long start = 0, lease; fd_set rfds; int retval; struct timeval tv; int c, len; struct dhcpMessage packet; struct in_addr temp_addr; int pid_fd; time_t now; int max_fd; int sig; static struct option arg_options[] = { {"clientid", required_argument, 0, 'c'}, {"foreground", no_argument, 0, 'f'}, {"background", no_argument, 0, 'b'}, {"hostname", required_argument, 0, 'H'}, {"hostname", required_argument, 0, 'h'}, {"interface", required_argument, 0, 'i'}, {"now", no_argument, 0, 'n'}, {"pidfile", required_argument, 0, 'p'}, {"quit", no_argument, 0, 'q'}, {"request", required_argument, 0, 'r'}, {"script", required_argument, 0, 's'}, {"version", no_argument, 0, 'v'}, {"help", no_argument, 0, '?'}, {0, 0, 0, 0} }; /* get options */ while (1) { int option_index = 0; c = getopt_long(argc, argv, "c:fbH:h:i:np:qr:s:v", arg_options, &option_index); if (c == -1) break; switch (c) { case 'c': len = strlen(optarg) > 255 ? 255 : strlen(optarg); if (client_config.clientid) free(client_config.clientid); client_config.clientid = xmalloc(len + 2); client_config.clientid[OPT_CODE] = DHCP_CLIENT_ID; client_config.clientid[OPT_LEN] = len; client_config.clientid[OPT_DATA] = '\0'; strncpy(client_config.clientid + OPT_DATA, optarg, len); break; case 'f': client_config.foreground = 1; break; case 'b': client_config.background_if_no_lease = 1; break; case 'h': case 'H': len = strlen(optarg) > 255 ? 255 : strlen(optarg); if (client_config.hostname) free(client_config.hostname); client_config.hostname = xmalloc(len + 2); client_config.hostname[OPT_CODE] = DHCP_HOST_NAME; client_config.hostname[OPT_LEN] = len; strncpy(client_config.hostname + 2, optarg, len); break; case 'i': client_config.interface = optarg; break; case 'n': client_config.abort_if_no_lease = 1; break; case 'p': client_config.pidfile = optarg; break; case 'q': client_config.quit_after_lease = 1; break; case 'r': requested_ip = inet_addr(optarg); break; case 's': client_config.script = optarg; break; case 'v': printf("udhcpcd, version %s\n\n", VERSION); exit_client(0); break; default: show_usage(); } } OPEN_LOG("udhcpc"); LOG(LOG_INFO, "udhcp client (v%s) started", VERSION); pid_fd = pidfile_acquire(client_config.pidfile); pidfile_write_release(pid_fd); if (read_interface(client_config.interface, &client_config.ifindex, NULL, client_config.arp) < 0) exit_client(1); if (!client_config.clientid) { client_config.clientid = xmalloc(6 + 3); client_config.clientid[OPT_CODE] = DHCP_CLIENT_ID; client_config.clientid[OPT_LEN] = 7; client_config.clientid[OPT_DATA] = 1; memcpy(client_config.clientid + 3, client_config.arp, 6); } /* setup signal handlers */ socketpair(AF_UNIX, SOCK_STREAM, 0, signal_pipe); signal(SIGUSR1, signal_handler); signal(SIGUSR2, signal_handler); signal(SIGTERM, signal_handler); state = INIT_SELECTING; run_script(NULL, "deconfig"); change_mode(LISTEN_RAW); for (;;) { tv.tv_sec = timeout - time(0); tv.tv_usec = 0; FD_ZERO(&rfds); if (listen_mode != LISTEN_NONE && fd < 0) { if (listen_mode == LISTEN_KERNEL) fd = listen_socket(INADDR_ANY, CLIENT_PORT, client_config.interface); else fd = raw_socket(client_config.ifindex); if (fd < 0) { LOG(LOG_ERR, "FATAL: couldn't listen on socket, %s", strerror(errno)); exit_client(0); } } if (fd >= 0) FD_SET(fd, &rfds); FD_SET(signal_pipe[0], &rfds); if (tv.tv_sec > 0) { DEBUG(LOG_INFO, "Waiting on select...\n"); max_fd = signal_pipe[0] > fd ? signal_pipe[0] : fd; retval = select(max_fd + 1, &rfds, NULL, NULL, &tv); } else retval = 0; /* If we already timed out, fall through */ now = time(0); if (retval == 0) { /* timeout dropped to zero */ switch (state) { case INIT_SELECTING: if (packet_num < 3) { if (packet_num == 0) xid = random_xid(); /* send discover packet */ send_discover(xid, requested_ip); /* broadcast */ timeout = now + ((packet_num == 2) ? 4 : 2); packet_num++; } else { if (client_config.background_if_no_lease) { LOG(LOG_INFO, "No lease, forking to background."); background(); } else if (client_config.abort_if_no_lease) { LOG(LOG_INFO, "No lease, failing."); exit_client(1); } /* wait to try again */ packet_num = 0; timeout = now + 60; } break; case RENEW_REQUESTED: case REQUESTING: if (packet_num < 3) { /* send request packet */ if (state == RENEW_REQUESTED) send_renew(xid, server_addr, requested_ip); /* unicast */ else send_selecting(xid, server_addr, requested_ip); /* broadcast */ timeout = now + ((packet_num == 2) ? 10 : 2); packet_num++; } else { /* timed out, go back to init state */ if (state == RENEW_REQUESTED) run_script(NULL, "deconfig"); state = INIT_SELECTING; timeout = now; packet_num = 0; change_mode(LISTEN_RAW); } break; case BOUND: /* Lease is starting to run out, time to enter renewing state */ state = RENEWING; change_mode(LISTEN_KERNEL); DEBUG(LOG_INFO, "Entering renew state"); /* fall right through */ case RENEWING: /* Either set a new T1, or enter REBINDING state */ if ((t2 - t1) <= (lease / 14400 + 1)) { /* timed out, enter rebinding state */ state = REBINDING; timeout = now + (t2 - t1); DEBUG(LOG_INFO, "Entering rebinding state"); } else { /* send a request packet */ send_renew(xid, server_addr, requested_ip); /* unicast */ t1 = (t2 - t1) / 2 + t1; timeout = t1 + start; } break; case REBINDING: /* Either set a new T2, or enter INIT state */ if ((lease - t2) <= (lease / 14400 + 1)) { /* timed out, enter init state */ state = INIT_SELECTING; LOG(LOG_INFO, "Lease lost, entering init state"); run_script(NULL, "deconfig"); timeout = now; packet_num = 0; change_mode(LISTEN_RAW); } else { /* send a request packet */ send_renew(xid, 0, requested_ip); /* broadcast */ t2 = (lease - t2) / 2 + t2; timeout = t2 + start; } break; case RELEASED: /* yah, I know, *you* say it would never happen */ timeout = 0x7fffffff; break; } } else if (retval > 0 && listen_mode != LISTEN_NONE && FD_ISSET(fd, &rfds)) { /* a packet is ready, read it */ if (listen_mode == LISTEN_KERNEL) len = get_packet(&packet, fd); else len = get_raw_packet(&packet, fd); if (len == -1 && errno != EINTR) { DEBUG(LOG_INFO, "error on read, %s, reopening socket", strerror(errno)); change_mode(listen_mode); /* just close and reopen */ } if (len < 0) continue; if (packet.xid != xid) { DEBUG(LOG_INFO, "Ignoring XID %lx (our xid is %lx)", (unsigned long) packet.xid, xid); continue; } if ((message = get_option(&packet, DHCP_MESSAGE_TYPE)) == NULL) { DEBUG(LOG_ERR, "couldnt get option from packet -- ignoring"); continue; } switch (state) { case INIT_SELECTING: /* Must be a DHCPOFFER to one of our xid's */ if (*message == DHCPOFFER) { if ((temp = get_option(&packet, DHCP_SERVER_ID))) { memcpy(&server_addr, temp, 4); xid = packet.xid; requested_ip = packet.yiaddr; /* enter requesting state */ state = REQUESTING; timeout = now; packet_num = 0; } else { DEBUG(LOG_ERR, "No server ID in message"); } } break; case RENEW_REQUESTED: case REQUESTING: case RENEWING: case REBINDING: if (*message == DHCPACK) { if (!(temp = get_option(&packet, DHCP_LEASE_TIME))) { LOG(LOG_ERR, "No lease time with ACK, using 1 hour lease"); lease = 60 * 60; } else { memcpy(&lease, temp, 4); lease = ntohl(lease); } /* enter bound state */ t1 = lease / 2; /* little fixed point for n * .875 */ t2 = (lease * 0x7) >> 3; temp_addr.s_addr = packet.yiaddr; LOG(LOG_INFO, "Lease of %s obtained, lease time %ld", inet_ntoa(temp_addr), lease); start = now; timeout = t1 + start; requested_ip = packet.yiaddr; run_script(&packet, ((state == RENEWING || state == REBINDING) ? "renew" : "bound")); state = BOUND; change_mode(LISTEN_NONE); if (client_config.quit_after_lease) exit_client(0); if (!client_config.foreground) background(); } else if (*message == DHCPNAK) { /* return to init state */ LOG(LOG_INFO, "Received DHCP NAK"); run_script(&packet, "nak"); if (state != REQUESTING) run_script(NULL, "deconfig"); state = INIT_SELECTING; timeout = now; requested_ip = 0; packet_num = 0; change_mode(LISTEN_RAW); sleep(3); /* avoid excessive network traffic */ } break; /* case BOUND, RELEASED: - ignore all packets */ } } else if (retval > 0 && FD_ISSET(signal_pipe[0], &rfds)) {
int main(void) { struct script_config config; struct kerberos_password *password; DIR *tmpdir; struct dirent *file; char *tmppath, *path; /* Load the Kerberos principal and password from a file. */ password = kerberos_config_password(); if (password == NULL) skip_all("Kerberos tests not configured"); memset(&config, 0, sizeof(config)); config.user = password->username; config.password = password->password; config.extra[0] = password->principal; /* Generate a testing krb5.conf file. */ kerberos_generate_conf(password->realm); /* Get the temporary directory and store that as the %1 substitution. */ tmppath = test_tmpdir(); config.extra[1] = tmppath; plan_lazy(); /* * We need to ensure that the only thing in the test temporary directory * is the krb5.conf file that we generated, since we're going to check for * cleanup by looking for any out-of-place files. */ tmpdir = opendir(tmppath); if (tmpdir == NULL) sysbail("cannot open directory %s", tmppath); while ((file = readdir(tmpdir)) != NULL) { if (strcmp(file->d_name, ".") == 0 || strcmp(file->d_name, "..") == 0) continue; if (strcmp(file->d_name, "krb5.conf") == 0) continue; basprintf(&path, "%s/%s", tmppath, file->d_name); if (unlink(path) < 0) sysbail("cannot delete temporary file %s", path); free(path); } closedir(tmpdir); /* * Authenticate only, call pam_end, and be sure the ticket cache is * gone. The auth-only script sets ccache_dir to the temporary directory, * so the module will create a temporary ticket cache there and then * should clean it up. */ run_script("data/scripts/cache-cleanup/auth-only", &config); path = NULL; tmpdir = opendir(tmppath); if (tmpdir == NULL) sysbail("cannot open directory %s", tmppath); while ((file = readdir(tmpdir)) != NULL) { if (strcmp(file->d_name, ".") == 0 || strcmp(file->d_name, "..") == 0) continue; if (strcmp(file->d_name, "krb5.conf") == 0) continue; if (path == NULL) basprintf(&path, "%s/%s", tmppath, file->d_name); } closedir(tmpdir); if (path != NULL) diag("found stray temporary file %s", path); ok(path == NULL, "ticket cache cleaned up"); if (path != NULL) free(path); test_tmpdir_free(tmppath); kerberos_config_password_free(password); return 0; }
void check_pipe(char *pipe_name) { fd_set fdset; struct timeval timeout = {0, 10}; int i; int fd; FD_ZERO(&fdset); if (f == NULL) { /* blocks f = fopen(pipe_name,"r"); */ fd = open(pipe_name, O_RDONLY | O_NONBLOCK); f = fdopen(fd,"r"); if(f == NULL) { perror(pipe_name); return; } } for(;;) { if(f != NULL) FD_SET(fileno(f), &fdset); switch(select(FD_SETSIZE, &fdset, NULL, NULL, &timeout)) { case -1: if(errno != EINTR) { perror("select"); exit(1); } return; case 0: /* printf("timeout\n"); */ return; default: if(f != NULL && FD_ISSET(fileno(f),&fdset)) { char line[1024]; if(fgets(line,sizeof(line),f) == NULL) { struct stat s; /* EOF reached, if f was a pipe, reopen it */ /* printf("EOF, reopening pipe"); */ /* f = fopen(pipe_name,"r"); */ /* printf("EOF, %s\n",pipe_name); */ fclose(f); f = NULL; return; /* always re-open on call to check_pipe if(stat(pipe_name,&s) == -1) { perror(pipe_name); exit(1); } if(S_ISFIFO(s.st_mode)) { printf("pipe, %s\n",pipe_name); f = fopen(pipe_name,"r"); } */ } else { int index; int len = strlen(line); /* len = strlen(line); */ if (len > 0) line[len-1] = 0; /* WLH 6 Nov 98 printf("%s: %s\n",pipe_name,line); */ get_current_display(&index); run_script(index, line); } } else { /* printf("select default not FD_ISSET, %s\n",pipe_name); */ return; } } /* end switch(select(FD_SETSIZE,&fdset,NULL,NULL,&timeout)) */ } /* end for (;;) */ }
int main(void) { struct script_config config; struct kerberos_config *krbconf; char *newpass, *date; struct passwd pwd; time_t now; /* Load the Kerberos principal and password from a file. */ krbconf = kerberos_setup(TAP_KRB_NEEDS_PASSWORD); memset(&config, 0, sizeof(config)); config.user = krbconf->username; config.password = krbconf->password; config.extra[0] = krbconf->userprinc; /* * Ensure we can expire the password. Heimdal has a prompt for the * expiration time, so save that to use as a substitution in the script. */ now = time(NULL) - 1; if (!kerberos_expire_password(krbconf->userprinc, now)) skip_all("kadmin not configured or kadmin mismatch"); date = bstrdup(ctime(&now)); date[strlen(date) - 1] = '\0'; config.extra[1] = date; /* Generate a testing krb5.conf file. */ kerberos_generate_conf(krbconf->realm); /* Create a fake passwd struct for our user. */ memset(&pwd, 0, sizeof(pwd)); pwd.pw_name = krbconf->username; pwd.pw_uid = getuid(); pwd.pw_gid = getgid(); basprintf(&pwd.pw_dir, "%s/tmp", getenv("BUILD")); pam_set_pwd(&pwd); /* * We'll be changing the password to something new. This needs to be * sufficiently random that it's unlikely to fall afoul of password * strength checking. */ basprintf(&newpass, "ngh1,a%lu nn9af6", (unsigned long) getpid()); config.newpass = newpass; plan_lazy(); /* Default behavior. */ #ifdef HAVE_KRB5_HEIMDAL run_script("data/scripts/expired/basic-heimdal", &config); config.newpass = krbconf->password; config.password = newpass; kerberos_expire_password(krbconf->userprinc, now); run_script("data/scripts/expired/basic-heimdal-debug", &config); #else run_script("data/scripts/expired/basic-mit", &config); config.newpass = krbconf->password; config.password = newpass; kerberos_expire_password(krbconf->userprinc, now); run_script("data/scripts/expired/basic-mit-debug", &config); #endif /* Test again with PAM_SILENT, specified two ways. */ #ifdef HAVE_KRB5_HEIMDAL config.newpass = newpass; config.password = krbconf->password; kerberos_expire_password(krbconf->userprinc, now); run_script("data/scripts/expired/basic-heimdal-silent", &config); config.newpass = krbconf->password; config.password = newpass; kerberos_expire_password(krbconf->userprinc, now); run_script("data/scripts/expired/basic-heimdal-flag-silent", &config); #else config.newpass = newpass; config.password = krbconf->password; kerberos_expire_password(krbconf->userprinc, now); run_script("data/scripts/expired/basic-mit-silent", &config); config.newpass = krbconf->password; config.password = newpass; kerberos_expire_password(krbconf->userprinc, now); run_script("data/scripts/expired/basic-mit-flag-silent", &config); #endif /* * We can only run the remaining checks if we can suppress the Kerberos * library behavior of prompting for a new password when the password has * expired. */ #ifdef HAVE_KRB5_GET_INIT_CREDS_OPT_SET_CHANGE_PASSWORD_PROMPT /* Check the forced failure behavior. */ run_script("data/scripts/expired/fail", &config); run_script("data/scripts/expired/fail-debug", &config); /* Defer the error to the account management check. */ config.newpass = newpass; config.password = krbconf->password; config.authtok = krbconf->password; kerberos_expire_password(krbconf->userprinc, now); run_script("data/scripts/expired/defer", &config); config.newpass = krbconf->password; config.password = newpass; config.authtok = newpass; kerberos_expire_password(krbconf->userprinc, now); run_script("data/scripts/expired/defer-debug", &config); #else /* !HAVE_KRB5_GET_INIT_CREDS_OPT_SET_CHANGE_PASSWORD_PROMPT */ /* Mention that we skipped something for the record. */ skip_block(4, "cannot disable library password prompting"); #endif /* HAVE_KRB5_GET_INIT_CREDS_OPT_SET_CHANGE_PASSWORD_PROMPT */ /* In case we ran into some error, try to unexpire the password. */ kerberos_expire_password(krbconf->userprinc, 0); free(date); free(newpass); free(pwd.pw_dir); return 0; }
void run_startup_script() { run_script("\\\\fls0\\eigensup.txt"); }
// Return 0 for everything OK, signed and returned, -1 for error. static int sign_client_cert(struct asfd *asfd, const char *client, struct conf *conf) { int a=0; int ret=-1; char msg[256]=""; char csrpath[512]=""; char crtpath[512]=""; struct stat statp; const char *args[15]; csr_done=0; snprintf(csrpath, sizeof(csrpath), "%s/%s.csr", gca_dir, client); snprintf(crtpath, sizeof(crtpath), "%s/%s.crt", gca_dir, client); if(!strcmp(client, conf->ca_name)) { char msg[512]=""; snprintf(msg, sizeof(msg), "Will not accept a client certificate request with the same name as the CA (%s)!", conf->ca_name); log_and_send(asfd, msg); // Do not goto end, as it will delete things; return -1; } if(!lstat(crtpath, &statp)) { char msg[512]=""; snprintf(msg, sizeof(msg), "Will not accept a client certificate request for '%s' - %s already exists!", client, crtpath); log_and_send(asfd, msg); // Do not goto end, as it will delete things; return -1; } if(!lstat(csrpath, &statp)) { char msg[512]=""; snprintf(msg, sizeof(msg), "Will not accept a client certificate request for '%s' - %s already exists!", client, csrpath); log_and_send(asfd, msg); // Do not goto end, as it will delete things; return -1; } // Tell the client that we will do it, and send the server name at the // same time. snprintf(msg, sizeof(msg), "csr ok:%s", conf->ca_server_name); if(asfd->write_str(asfd, CMD_GEN, msg)) { // Do not goto end, as it will delete things; return -1; } /* After this point, we might have uploaded files, so on error, go to end and delete any new files. */ // Get the CSR from the client. if(receive_a_file(asfd, csrpath, conf)) goto end; // Now, sign it. logp("Signing certificate signing request from %s\n", client); logp("Running '%s --name %s --ca %s --sign --batch --dir %s --config %s'\n", conf->ca_burp_ca, client, conf->ca_name, gca_dir, conf->ca_conf); a=0; args[a++]=conf->ca_burp_ca; args[a++]="--name"; args[a++]=client; args[a++]="--ca"; args[a++]=conf->ca_name; args[a++]="--sign"; args[a++]="--batch"; args[a++]="--dir"; args[a++]=gca_dir; args[a++]="--config"; args[a++]=conf->ca_conf; args[a++]=NULL; if(run_script(asfd, args, NULL, conf, 1 /* wait */, 0, 0 /* do not use logp - stupid openssl prints lots of dots one at a time with no way to turn it off */)) { logp("Error running %s\n", conf->ca_burp_ca); goto end; } // Now, we should have a signed certificate. // Need to send it back to the client. if(send_a_file(asfd, crtpath, conf)) goto end; // Also need to send the CA public certificate back to the client. if(send_a_file(asfd, conf->ssl_cert_ca, conf)) goto end; ret=0; csr_done++; end: if(ret<0) { unlink(crtpath); unlink(csrpath); } return ret; }
int ifplugd_main(int argc UNUSED_PARAM, char **argv) { int iface_status; int delay_time; const char *iface_status_str; struct pollfd netlink_pollfd[1]; unsigned opts; const char *api_mode_found; #if ENABLE_FEATURE_PIDFILE char *pidfile_name; pid_t pid_from_pidfile; #endif INIT_G(); opt_complementary = "t+:u+:d+"; opts = getopt32(argv, OPTION_STR, &G.iface, &G.script_name, &G.poll_time, &G.delay_up, &G.delay_down, &G.api_mode, &G.extra_arg); G.poll_time *= 1000; applet_name = xasprintf("ifplugd(%s)", G.iface); #if ENABLE_FEATURE_PIDFILE pidfile_name = xasprintf(CONFIG_PID_FILE_PATH "/ifplugd.%s.pid", G.iface); pid_from_pidfile = read_pid(pidfile_name); if (opts & FLAG_KILL) { if (pid_from_pidfile > 0) /* Upstream tool use SIGINT for -k */ kill(pid_from_pidfile, SIGINT); return EXIT_SUCCESS; } if (pid_from_pidfile > 0 && kill(pid_from_pidfile, 0) == 0) bb_error_msg_and_die("daemon already running"); #endif api_mode_found = strchr(api_modes, G.api_mode[0]); if (!api_mode_found) bb_error_msg_and_die("unknown API mode '%s'", G.api_mode); G.api_method_num = api_mode_found - api_modes; if (!(opts & FLAG_NO_DAEMON)) bb_daemonize_or_rexec(DAEMON_CHDIR_ROOT, argv); xmove_fd(xsocket(AF_INET, SOCK_DGRAM, 0), ioctl_fd); if (opts & FLAG_MONITOR) { struct sockaddr_nl addr; int fd = xsocket(PF_NETLINK, SOCK_DGRAM, NETLINK_ROUTE); memset(&addr, 0, sizeof(addr)); addr.nl_family = AF_NETLINK; addr.nl_groups = RTMGRP_LINK; addr.nl_pid = getpid(); xbind(fd, (struct sockaddr*)&addr, sizeof(addr)); xmove_fd(fd, netlink_fd); } write_pidfile(pidfile_name); /* this can't be moved before socket creation */ if (!(opts & FLAG_NO_SYSLOG)) { openlog(applet_name, 0, LOG_DAEMON); logmode |= LOGMODE_SYSLOG; } bb_signals(0 | (1 << SIGINT ) | (1 << SIGTERM) | (1 << SIGQUIT) | (1 << SIGHUP ) /* why we ignore it? */ /* | (1 << SIGCHLD) - run_script does not use it anymore */ , record_signo); bb_error_msg("started: %s", bb_banner); if (opts & FLAG_MONITOR) { struct ifreq ifrequest; set_ifreq_to_ifname(&ifrequest); G.iface_exists = (network_ioctl(SIOCGIFINDEX, &ifrequest, NULL) == 0); } if (G.iface_exists) maybe_up_new_iface(); iface_status = detect_link(); if (iface_status == IFSTATUS_ERR) goto exiting; iface_status_str = strstatus(iface_status); if (opts & FLAG_MONITOR) { bb_error_msg("interface %s", G.iface_exists ? "exists" : "doesn't exist, waiting"); } /* else we assume it always exists, but don't mislead user * by potentially lying that it really exists */ if (G.iface_exists) { bb_error_msg("link is %s", iface_status_str); } if ((!(opts & FLAG_NO_STARTUP) && iface_status == IFSTATUS_UP ) || (opts & FLAG_INITIAL_DOWN) ) { if (run_script(iface_status_str) != 0) goto exiting; } /* Main loop */ netlink_pollfd[0].fd = netlink_fd; netlink_pollfd[0].events = POLLIN; delay_time = 0; while (1) { int iface_status_old; int iface_exists_old; switch (bb_got_signal) { case SIGINT: case SIGTERM: bb_got_signal = 0; goto cleanup; case SIGQUIT: bb_got_signal = 0; goto exiting; default: bb_got_signal = 0; break; } if (poll(netlink_pollfd, (opts & FLAG_MONITOR) ? 1 : 0, G.poll_time ) < 0 ) { if (errno == EINTR) continue; bb_perror_msg("poll"); goto exiting; } iface_status_old = iface_status; iface_exists_old = G.iface_exists; if ((opts & FLAG_MONITOR) && (netlink_pollfd[0].revents & POLLIN) ) { G.iface_exists = check_existence_through_netlink(); if (G.iface_exists < 0) /* error */ goto exiting; if (iface_exists_old != G.iface_exists) { bb_error_msg("interface %sappeared", G.iface_exists ? "" : "dis"); if (G.iface_exists) maybe_up_new_iface(); } } /* note: if !G.iface_exists, returns DOWN */ iface_status = detect_link(); if (iface_status == IFSTATUS_ERR) { if (!(opts & FLAG_MONITOR)) goto exiting; iface_status = IFSTATUS_DOWN; } iface_status_str = strstatus(iface_status); if (iface_status_old != iface_status) { bb_error_msg("link is %s", iface_status_str); if (delay_time) { /* link restored its old status before * we run script. don't run the script: */ delay_time = 0; } else { delay_time = monotonic_sec(); if (iface_status == IFSTATUS_UP) delay_time += G.delay_up; if (iface_status == IFSTATUS_DOWN) delay_time += G.delay_down; if (delay_time == 0) delay_time++; } } if (delay_time && (int)(monotonic_sec() - delay_time) >= 0) { delay_time = 0; if (run_script(iface_status_str) != 0) goto exiting; } } /* while (1) */ cleanup: if (!(opts & FLAG_NO_SHUTDOWN) && (iface_status == IFSTATUS_UP || (iface_status == IFSTATUS_DOWN && delay_time) ) ) { setenv(IFPLUGD_ENV_PREVIOUS, strstatus(iface_status), 1); setenv(IFPLUGD_ENV_CURRENT, strstatus(-1), 1); run_script("down\0up"); /* reusing string */ } exiting: remove_pidfile(pidfile_name); bb_error_msg_and_die("exiting"); }
/* * Background process -- runs with privilege. */ static void down_root_server(const int fd, char *const *argv, char *const *envp, const int verb) { /* * Do initialization */ if (DEBUG(verb)) { fprintf(stderr, "DOWN-ROOT: BACKGROUND: INIT command='%s'\n", argv[0]); } /* * Tell foreground that we initialized successfully */ if (send_control(fd, RESPONSE_INIT_SUCCEEDED) == -1) { warn("DOWN-ROOT: BACKGROUND: write error on response socket [1]"); goto done; } /* * Event loop */ while (1) { int command_code; int exit_code = -1; /* get a command from foreground process */ command_code = recv_control(fd); if (DEBUG(verb)) { fprintf(stderr, "DOWN-ROOT: BACKGROUND: received command code: %d\n", command_code); } switch (command_code) { case COMMAND_RUN_SCRIPT: if ( (exit_code = run_script(argv, envp)) == 0) /* Succeeded */ { if (send_control(fd, RESPONSE_SCRIPT_SUCCEEDED) == -1) { warn("DOWN-ROOT: BACKGROUND: write error on response socket [2]"); goto done; } } else /* Failed */ { fprintf(stderr, "DOWN-ROOT: BACKGROUND: %s exited with exit code %i\n", argv[0], exit_code); if (send_control(fd, RESPONSE_SCRIPT_FAILED) == -1) { warn("DOWN-ROOT: BACKGROUND: write error on response socket [3]"); goto done; } } break; case COMMAND_EXIT: goto done; case -1: warn("DOWN-ROOT: BACKGROUND: read error on command channel"); goto done; default: fprintf(stderr, "DOWN-ROOT: BACKGROUND: unknown command code: code=%d, exiting\n", command_code); goto done; } } done: if (DEBUG(verb)) { fprintf(stderr, "DOWN-ROOT: BACKGROUND: EXIT\n"); } return; }
static int burp_ca_init(struct conf *conf, const char *ca_dir) { int a=0; const char *args[15]; char linktarget[1024]=""; if(is_dir_lstat(ca_dir)) return 0; setup_stuff_done++; logp("Initialising %s\n", ca_dir); logp("Running '%s --init --ca %s --dir %s --config %s'\n", conf->ca_burp_ca, conf->ca_name, ca_dir, conf->ca_conf); args[a++]=conf->ca_burp_ca; args[a++]="--init"; args[a++]="--ca"; args[a++]=conf->ca_name; args[a++]="--dir"; args[a++]=ca_dir; args[a++]="--config"; args[a++]=conf->ca_conf; args[a++]=NULL; if(run_script(NULL /* no async yet */, args, NULL, conf, 1 /* wait */, 0, 0 /* do not use logp - stupid openssl prints lots of dots one at a time with no way to turn it off */)) { logp("Error running %s\n", conf->ca_burp_ca); return -1; } logp("Generating server key and cert signing request\n"); logp("Running '%s --key --request --name %s --dir %s --config %s'\n", conf->ca_burp_ca, conf->ca_server_name, ca_dir, conf->ca_conf); a=0; args[a++]=conf->ca_burp_ca; args[a++]="--key"; args[a++]="--request"; args[a++]="--name"; args[a++]=conf->ca_server_name; args[a++]="--dir"; args[a++]=ca_dir; args[a++]="--config"; args[a++]=conf->ca_conf; args[a++]=NULL; if(run_script(NULL /* no async yet */, args, NULL, conf, 1 /* wait */, 0, 0 /* do not use logp - stupid openssl prints lots of dots one at a time with no way to turn it off */)) { logp("Error running %s\n", conf->ca_burp_ca); return -1; } logp("Signing request\n"); logp("Running '%s --sign --ca %s --name %s --batch --dir %s --config %s'\n", conf->ca_burp_ca, conf->ca_name, conf->ca_server_name, ca_dir, conf->ca_conf); a=0; args[a++]=conf->ca_burp_ca; args[a++]="--sign"; args[a++]="--ca"; args[a++]=conf->ca_name; args[a++]="--name"; args[a++]=conf->ca_server_name; args[a++]="--batch"; args[a++]="--dir"; args[a++]=ca_dir; args[a++]="--config"; args[a++]=conf->ca_conf; args[a++]=NULL; if(run_script(NULL /* no async yet */, args, NULL, conf, 1 /* wait */, 0, 0 /* do not use logp - stupid openssl prints lots of dots one at a time with no way to turn it off */)) { logp("Error running %s\n", conf->ca_burp_ca); return -1; } snprintf(linktarget, sizeof(linktarget), "%s/CA_%s.crt", ca_dir, conf->ca_name); if(strcmp(linktarget, conf->ssl_cert_ca)) { remove_file(conf->ssl_cert_ca); if(symlink_file(linktarget, conf->ssl_cert_ca)) return -1; } snprintf(linktarget, sizeof(linktarget), "%s/%s.crt", ca_dir, conf->ca_server_name); if(strcmp(linktarget, conf->ssl_cert)) { remove_file(conf->ssl_cert); if(symlink_file(linktarget, conf->ssl_cert)) return -1; } snprintf(linktarget, sizeof(linktarget), "%s/%s.key", ca_dir, conf->ca_server_name); if(strcmp(linktarget, conf->ssl_key)) { remove_file(conf->ssl_key); if(symlink_file(linktarget, conf->ssl_key)) return -1; } return 0; }
int main(int argc, char *argv[]) #endif { char *temp, *message; unsigned long t1 = 0, t2 = 0, xid = 0; unsigned long start = 0, lease; fd_set rfds; int fd, retval; struct timeval tv; int c, len; struct ifreq ifr; struct dhcpMessage packet; struct in_addr temp_addr; int pid_fd; static struct option options[] = { {"clientid", required_argument, 0, 'c'}, {"foreground", no_argument, 0, 'f'}, {"hostname", required_argument, 0, 'H'}, {"help", no_argument, 0, 'h'}, {"interface", required_argument, 0, 'i'}, {"now", no_argument, 0, 'n'}, {"pidfile", required_argument, 0, 'p'}, {"quit", no_argument, 0, 'q'}, {"request", required_argument, 0, 'r'}, {"script", required_argument, 0, 's'}, {"version", no_argument, 0, 'v'}, {0, 0, 0, 0} }; /* get options */ while (1) { int option_index = 0; // brcm c = getopt_long(argc, argv, "c:fH:hi:np:qr:s:d:v", options, &option_index); if (c == -1) break; switch (c) { case 'c': len = strlen(optarg) > 255 ? 255 : strlen(optarg); if (client_config.clientid) free(client_config.clientid); client_config.clientid = malloc(len + 2); client_config.clientid[OPT_CODE] = DHCP_CLIENT_ID; client_config.clientid[OPT_LEN] = len; strncpy(client_config.clientid + 2, optarg, len); break; case 'f': client_config.foreground = 1; break; case 'H': len = strlen(optarg) > 255 ? 255 : strlen(optarg); if (client_config.hostname) free(client_config.hostname); client_config.hostname = malloc(len + 2); client_config.hostname[OPT_CODE] = DHCP_HOST_NAME; client_config.hostname[OPT_LEN] = len; strncpy(client_config.hostname + 2, optarg, len); break; case 'h': print_usage(); return 0; case 'i': client_config.interface = optarg; // brcm strcpy(session_path, optarg); break; case 'n': client_config.abort_if_no_lease = 1; break; case 'p': client_config.pidfile = optarg; break; case 'q': client_config.quit_after_lease = 1; break; case 'r': requested_ip = inet_addr(optarg); break; // brcm case 'd': strcpy(vendor_class_id, optarg); break; case 's': client_config.script = optarg; break; case 'v': printf("udhcpcd, version %s\n\n", VERSION); break; } } // brcm if (strlen(session_path) > 0) { sprintf(status_path, "%s/%s/%s", _PATH_WAN_DIR, session_path, _PATH_MSG); sprintf(pid_path, "%s/%s/%s", _PATH_WAN_DIR, session_path, _PATH_PID); } OPEN_LOG("udhcpc"); LOG(LOG_INFO, "udhcp client (v%s) started", VERSION); pid_fd = pidfile_acquire(client_config.pidfile); pidfile_write_release(pid_fd); if ((fd = socket(AF_INET, SOCK_RAW, IPPROTO_RAW)) >= 0) { strcpy(ifr.ifr_name, client_config.interface); if (ioctl(fd, SIOCGIFINDEX, &ifr) == 0) { DEBUG(LOG_INFO, "adapter index %d", ifr.ifr_ifindex); client_config.ifindex = ifr.ifr_ifindex; } else { LOG(LOG_ERR, "SIOCGIFINDEX failed! %s", strerror(errno)); exit_client(1); } if (ioctl(fd, SIOCGIFHWADDR, &ifr) == 0) { memcpy(client_config.arp, ifr.ifr_hwaddr.sa_data, 6); DEBUG(LOG_INFO, "adapter hardware address %02x:%02x:%02x:%02x:%02x:%02x", client_config.arp[0], client_config.arp[1], client_config.arp[2], client_config.arp[3], client_config.arp[4], client_config.arp[5]); } else { LOG(LOG_ERR, "SIOCGIFHWADDR failed! %s", strerror(errno)); exit_client(1); } } else { LOG(LOG_ERR, "socket failed! %s", strerror(errno)); exit_client(1); } close(fd); fd = -1; /* setup signal handlers */ signal(SIGUSR1, renew_requested); signal(SIGUSR2, release_requested); signal(SIGTERM, terminate); state = INIT_SELECTING; // brcm // run_script(NULL, "deconfig"); // brcm setStatus(0); for (;;) { // brcm if ((old_mode != listen_mode) || (fd == -1)) { old_mode = listen_mode; if (fd > 0) { close(fd); fd = -1; } if (listen_mode == LISTEN_RAW) { if ((fd = raw_socket(client_config.ifindex)) < 0) { LOG(LOG_ERR, "couldn't create raw socket -- au revoir"); exit_client(0); } } else if (listen_mode == LISTEN_KERNEL) { if ((fd = listen_socket(INADDR_ANY, CLIENT_PORT, client_config.interface)) < 0) { LOG(LOG_ERR, "couldn't create server socket -- au revoir"); exit_client(0); } } else fd = -1; } tv.tv_sec = timeout - time(0); tv.tv_usec = 0; FD_ZERO(&rfds); if (listen_mode) FD_SET(fd, &rfds); if (tv.tv_sec > 0) { retval = select(fd + 1, &rfds, NULL, NULL, &tv); } else retval = 0; /* If we already timed out, fall through */ if (retval == 0) { /* timeout dropped to zero */ switch (state) { case INIT_SELECTING: // brcm setStatus(0); if (packet_num < 3) { if (packet_num == 0) xid = random_xid(); /* send discover packet */ send_discover(xid, requested_ip); /* broadcast */ timeout = time(0) + ((packet_num == 2) ? 10 : 2); packet_num++; } else { if (client_config.abort_if_no_lease) { LOG(LOG_INFO, "No lease, failing."); exit_client(1); } /* wait to try again */ packet_num = 0; timeout = time(0) + 60; } break; case RENEW_REQUESTED: case REQUESTING: if (packet_num < 3) { /* send request packet */ if (state == RENEW_REQUESTED) send_renew(xid, server_addr, requested_ip); /* unicast */ else send_selecting(xid, server_addr, requested_ip); /* broadcast */ timeout = time(0) + ((packet_num == 2) ? 10 : 2); packet_num++; } else { /* timed out, go back to init state */ state = INIT_SELECTING; timeout = time(0); packet_num = 0; listen_mode = LISTEN_RAW; } break; case BOUND: /* Lease is starting to run out, time to enter renewing state */ state = RENEWING; listen_mode = LISTEN_KERNEL; DEBUG(LOG_INFO, "Entering renew state"); /* fall right through */ case RENEWING: /* Either set a new T1, or enter REBINDING state */ if ((t2 - t1) <= (lease / 14400 + 1)) { /* timed out, enter rebinding state */ state = REBINDING; timeout = time(0) + (t2 - t1); DEBUG(LOG_INFO, "Entering rebinding state"); } else { /* send a request packet */ send_renew(xid, server_addr, requested_ip); /* unicast */ t1 = (t2 - t1) / 2 + t1; timeout = t1 + start; } break; case REBINDING: /* Either set a new T2, or enter INIT state */ if ((lease - t2) <= (lease / 14400 + 1)) { /* timed out, enter init state */ state = INIT_SELECTING; LOG(LOG_INFO, "Lease lost, entering init state"); run_script(NULL, "deconfig"); timeout = time(0); packet_num = 0; listen_mode = LISTEN_RAW; } else { /* send a request packet */ send_renew(xid, 0, requested_ip); /* broadcast */ t2 = (lease - t2) / 2 + t2; timeout = t2 + start; } break; case RELEASED: /* yah, I know, *you* say it would never happen */ timeout = 0xffffffff; break; } } else if (retval > 0 && listen_mode != LISTEN_NONE && FD_ISSET(fd, &rfds)) { /* a packet is ready, read it */ if (listen_mode == LISTEN_KERNEL) { if (get_packet(&packet, fd) < 0) continue; } else { if (get_raw_packet(&packet, fd) < 0) continue; } if (packet.xid != xid) { DEBUG(LOG_INFO, "Ignoring XID %lx (our xid is %lx)", (unsigned long) packet.xid, xid); continue; } if ((message = get_option(&packet, DHCP_MESSAGE_TYPE)) == NULL) { DEBUG(LOG_ERR, "couldnt get option from packet -- ignoring"); continue; } switch (state) { case INIT_SELECTING: /* Must be a DHCPOFFER to one of our xid's */ if (*message == DHCPOFFER) { if ((temp = get_option(&packet, DHCP_SERVER_ID))) { memcpy(&server_addr, temp, 4); xid = packet.xid; requested_ip = packet.yiaddr; /* enter requesting state */ state = REQUESTING; timeout = time(0); packet_num = 0; } else { DEBUG(LOG_ERR, "No server ID in message"); } } break; case RENEW_REQUESTED: case REQUESTING: case RENEWING: case REBINDING: if (*message == DHCPACK) { if (!(temp = get_option(&packet, DHCP_LEASE_TIME))) { LOG(LOG_ERR, "No lease time with ACK, using 1 hour lease"); lease = 60*60; } else { memcpy(&lease, temp, 4); lease = ntohl(lease); } /* enter bound state */ t1 = lease / 2; /* little fixed point for n * .875 */ t2 = (lease * 0x7) >> 3; temp_addr.s_addr = packet.yiaddr; LOG(LOG_INFO, "Lease of %s obtained, lease time %ld", inet_ntoa(temp_addr), lease); start = time(0); timeout = t1 + start; requested_ip = packet.yiaddr; run_script(&packet, ((state == RENEWING || state == REBINDING) ? "renew" : "bound")); state = BOUND; listen_mode = LISTEN_NONE; // brcm setStatus(1); background(); } else if (*message == DHCPNAK) { /* return to init state */ LOG(LOG_INFO, "Received DHCP NAK"); if (state != REQUESTING) run_script(NULL, "deconfig"); state = INIT_SELECTING; timeout = time(0); requested_ip = 0; packet_num = 0; listen_mode = LISTEN_RAW; // brcm setStatus(0); } break; case BOUND: case RELEASED: /* ignore all packets */ break; } } else if (retval == -1 && errno == EINTR) {
void select_script_and_run() { char filename[MAX_FILENAME_SIZE+1] = ""; if(fileBrowser(filename, (unsigned char*)"*.txt", "Scripts")) { run_script(filename); } }
/** * load_config * Load configuration from a file - From this we set up the lists of files * which decides what script to load on what wnck event. */ int load_config(gchar *filename) { lua_State *config_lua_state = NULL; int result = 0; const gchar *current_file = NULL; GSList *temp_window_open_file_list = NULL; // set the current window to NULL, we don't need to be able to modify // the windows when reading the config set_current_window(NULL); // First get list of Lua files in folder - Then read variables from // devilspie2.lua and put the files in the required lists. gchar *script_folder = g_path_get_dirname(filename); GDir *dir = g_dir_open(script_folder, 0, NULL); if (!g_file_test(script_folder, G_FILE_TEST_IS_DIR)) { printf(_("script_folder isn't a folder.")); printf("\n"); return -1; } int total_number_of_files = 0; config_lua_state = init_script(); if (g_file_test(filename, G_FILE_TEST_EXISTS)) { if (load_script(config_lua_state, filename)!=0) { printf(_("Error: %s"), filename); printf("\n"); result = -1; goto EXITPOINT; } run_script(config_lua_state); file_window_close_list = get_table_of_strings(config_lua_state, script_folder, "scripts_window_close"); } // add the files in the folder to our linked list while ((current_file = g_dir_read_name(dir))) { gchar *temp_filename = g_build_path(G_DIR_SEPARATOR_S, script_folder, current_file, NULL); // we only bother with *.lua in the folder if (g_str_has_suffix(current_file, ".lua")) { if (!is_in_any_list(temp_filename)) { temp_window_open_file_list = add_lua_file_to_list(temp_window_open_file_list, temp_filename); } total_number_of_files++; } g_free(temp_filename); } file_window_open_list = temp_window_open_file_list; EXITPOINT: if (config_lua_state) done_script(config_lua_state); return result; }
int WINAPI wWinMain(HINSTANCE hInst, HINSTANCE hPrevInst, LPWSTR cmdline, int cmdshow) { const WCHAR *ext, *filename = NULL; IActiveScriptParse *parser; IActiveScript *script; WCHAR **argv; CLSID clsid; int argc, i; DWORD res; WINE_TRACE("(%p %p %s %x)\n", hInst, hPrevInst, wine_dbgstr_w(cmdline), cmdshow); argv = CommandLineToArgvW(cmdline, &argc); if(!argv) return 1; for(i=0; i<argc; i++) { if(*argv[i] == '/' || *argv[i] == '-') { if(!set_host_properties(argv[i])) return 1; }else { filename = argv[i]; argums = argv+i+1; numOfArgs = argc-i-1; break; } } if(!filename) { WINE_FIXME("No file name specified\n"); return 1; } res = GetFullPathNameW(filename, sizeof(scriptFullName)/sizeof(WCHAR), scriptFullName, NULL); if(!res || res > sizeof(scriptFullName)/sizeof(WCHAR)) return 1; ext = strchrW(filename, '.'); if(!ext) ext = filename; if(!get_engine_clsid(ext, &clsid)) { WINE_FIXME("Could not find engine for %s\n", wine_dbgstr_w(ext)); return 1; } CoInitialize(NULL); if(!create_engine(&clsid, &script, &parser)) { WINE_FIXME("Could not create script engine\n"); CoUninitialize(); return 1; } if(init_engine(script, parser)) { run_script(filename, script, parser); IActiveScript_Close(script); ITypeInfo_Release(host_ti); }else { WINE_FIXME("Script initialization failed\n"); } IActiveScript_Release(script); IActiveScriptParse_Release(parser); CoUninitialize(); return 0; }
/* * The mother of all processes. */ int main(int argc, char *argv[]) { state_t initial_transition = runcom; char kenv_value[PATH_MAX]; int c; struct sigaction sa; sigset_t mask; /* Dispose of random users. */ if (getuid() != 0) errx(1, "%s", strerror(EPERM)); /* System V users like to reexec init. */ if (getpid() != 1) { #ifdef COMPAT_SYSV_INIT /* So give them what they want */ if (argc > 1) { if (strlen(argv[1]) == 1) { char runlevel = *argv[1]; int sig; switch (runlevel) { case '0': /* halt + poweroff */ sig = SIGUSR2; break; case '1': /* single-user */ sig = SIGTERM; break; case '6': /* reboot */ sig = SIGINT; break; case 'c': /* block further logins */ sig = SIGTSTP; break; case 'q': /* rescan /etc/ttys */ sig = SIGHUP; break; default: goto invalid; } kill(1, sig); _exit(0); } else invalid: errx(1, "invalid run-level ``%s''", argv[1]); } else #endif errx(1, "already running"); } /* * Note that this does NOT open a file... * Does 'init' deserve its own facility number? */ openlog("init", LOG_CONS, LOG_AUTH); /* * Create an initial session. */ if (setsid() < 0) warning("initial setsid() failed: %m"); /* * Establish an initial user so that programs running * single user do not freak out and die (like passwd). */ if (setlogin("root") < 0) warning("setlogin() failed: %m"); /* * This code assumes that we always get arguments through flags, * never through bits set in some random machine register. */ while ((c = getopt(argc, argv, "dsf")) != -1) switch (c) { case 'd': devfs = 1; break; case 's': initial_transition = single_user; break; case 'f': runcom_mode = FASTBOOT; break; default: warning("unrecognized flag '-%c'", c); break; } if (optind != argc) warning("ignoring excess arguments"); /* * We catch or block signals rather than ignore them, * so that they get reset on exec. */ handle(badsys, SIGSYS, 0); handle(disaster, SIGABRT, SIGFPE, SIGILL, SIGSEGV, SIGBUS, SIGXCPU, SIGXFSZ, 0); handle(transition_handler, SIGHUP, SIGINT, SIGTERM, SIGTSTP, SIGUSR1, SIGUSR2, 0); handle(alrm_handler, SIGALRM, 0); sigfillset(&mask); delset(&mask, SIGABRT, SIGFPE, SIGILL, SIGSEGV, SIGBUS, SIGSYS, SIGXCPU, SIGXFSZ, SIGHUP, SIGINT, SIGTERM, SIGTSTP, SIGALRM, SIGUSR1, SIGUSR2, 0); sigprocmask(SIG_SETMASK, &mask, (sigset_t *) 0); sigemptyset(&sa.sa_mask); sa.sa_flags = 0; sa.sa_handler = SIG_IGN; sigaction(SIGTTIN, &sa, (struct sigaction *)0); sigaction(SIGTTOU, &sa, (struct sigaction *)0); /* * Paranoia. */ close(0); close(1); close(2); if (kenv(KENV_GET, "init_script", kenv_value, sizeof(kenv_value)) > 0) { state_func_t next_transition; if ((next_transition = run_script(kenv_value)) != 0) initial_transition = (state_t) next_transition; } if (kenv(KENV_GET, "init_chroot", kenv_value, sizeof(kenv_value)) > 0) { if (chdir(kenv_value) != 0 || chroot(".") != 0) warning("Can't chroot to %s: %m", kenv_value); } /* * Additional check if devfs needs to be mounted: * If "/" and "/dev" have the same device number, * then it hasn't been mounted yet. */ if (!devfs) { struct stat stst; dev_t root_devno; stat("/", &stst); root_devno = stst.st_dev; if (stat("/dev", &stst) != 0) warning("Can't stat /dev: %m"); else if (stst.st_dev == root_devno) devfs++; } if (devfs) { struct iovec iov[4]; char *s; int i; char _fstype[] = "fstype"; char _devfs[] = "devfs"; char _fspath[] = "fspath"; char _path_dev[]= _PATH_DEV; iov[0].iov_base = _fstype; iov[0].iov_len = sizeof(_fstype); iov[1].iov_base = _devfs; iov[1].iov_len = sizeof(_devfs); iov[2].iov_base = _fspath; iov[2].iov_len = sizeof(_fspath); /* * Try to avoid the trailing slash in _PATH_DEV. * Be *very* defensive. */ s = strdup(_PATH_DEV); if (s != NULL) { i = strlen(s); if (i > 0 && s[i - 1] == '/') s[i - 1] = '\0'; iov[3].iov_base = s; iov[3].iov_len = strlen(s) + 1; } else { iov[3].iov_base = _path_dev; iov[3].iov_len = sizeof(_path_dev); } nmount(iov, 4, 0); if (s != NULL) free(s); } /* * Start the state machine. */ transition(initial_transition); /* * Should never reach here. */ return 1; }
int vcs_main() /*int argc; No longer needed for Python interface char *argv[];*/ { /* This program is a test for later development of script processing. */ int argc = 0; char **argv = NULL; char *getenv(); FILE *fopen(), fpcdat; int i,j,k; int got_font_or_geom = 0; float fv=1.0; char *ptri, *ptro; int mode=0777; char str[2], buf[1024]; char logo_data2[388680]; struct display_tab *dtab; extern struct table_line Tl_tab; extern struct table_mark Tm_tab; extern struct table_fill Tf_tab; extern struct table_FT_VCS_FONTS TTFFONTS; struct table_FT_VCS_FONTS *current_font; int *pi; static int read_initial_attribute = 0; FILE *logo_file,*logo_file2; char c; /* f_init(); */ /* Additional initialization for the 'default' */ /* line, marker and fillarea secondary attributes */ get_int_size_and_set_value( &Tl_tab.ltyp, 1, (int)1 ); Tl_tab.ltyp_size=1; get_float_size_and_set_value( &Tl_tab.lwsf, 1, &fv ); Tl_tab.lwsf_size=1.0; get_int_size_and_set_value( &Tl_tab.lci, 1, (int)1 ); Tl_tab.lci_size=1; get_int_size_and_set_value( &Tm_tab.mtyp, 1, (int)1 ); Tm_tab.mtyp_size=1; get_float_size_and_set_value(&Tm_tab.msize, 1, &fv); Tm_tab.msize_size=1.0; get_int_size_and_set_value( &Tm_tab.mci, 1, (int)1 ); Tm_tab.mci_size=1; get_int_size_and_set_value( &Tf_tab.fais, 1, (int)1 ); Tf_tab.fais_size=1; get_int_size_and_set_value( &Tf_tab.fasi, 1, (int)1 ); Tf_tab.fasi_size=1; get_int_size_and_set_value( &Tf_tab.faci, 1, (int)1 ); Tf_tab.faci_size=1; /* Use extended name lengths at cddrs interface */ cw_set_string_option(CW_EXTENDED); /* Find a base directory. */ if ((base_dir=getenv(DOT_DIRECTORY_ENV)) == NULL) { if ((base_dir=getenv("HOME")) == NULL || strlen(base_dir) ==0) { strcpy(dirbase,"./"); strcat(dirbase,DOT_DIRECTORY); } else { strcpy(dirbase,base_dir); strcat(dirbase,"/"); strcat(dirbase,DOT_DIRECTORY); } } else strcpy(dirbase,base_dir); base_dir=dirbase; if (mkdir(base_dir,mode) != 0 && errno != EEXIST) { printf ("Error - you don't have a base directory.\n"); printf ("The environment variable"); printf (DOT_DIRECTORY_ENV); printf (" or HOME needs to be set!\n"); return 0; } /* First time around add user's home to path of fonts */ if (read_initial_attribute==0) { /* logo stuff */ logo = cairo_image_surface_create_for_data(&logo_data[0],logo_format,logo_width,logo_height,logo_stride); logo_p = cairo_pattern_create_for_surface(logo); i = FT_Init_FreeType( &ft_library ); if (i!=0) { err_warn(1,fperr,"Error - could not load the FT library!\n"); return 0; } current_font = &TTFFONTS; while (current_font!=NULL) { strcpy(font_file,base_dir); strcat(font_file,"/"); strcat(font_file,current_font->path); strcpy(current_font->path,font_file); /* add code here to check it actually exists ? */ current_font=current_font->next; } } strcpy(script_file,base_dir); strcat(script_file,"/"); strcat(script_file,"initial.attributes"); fpin=fpout=fperr=NULL; ptri=ptro=ptre=NULL; if (argc >= 2) { for (i=1; i < argc; i++) { if (strncmp (argv[i],"-e",2) == 0) { if (strlen(argv[i]) > (size_t)2) j=2; else if (++i < argc) j=0; else return -1; ptre=argv[i]; ptre+=j; if ((strchr(ptre,'/')==NULL) && base_dir != NULL) { strcpy(error_file,base_dir); strcat(error_file,"/"); strcat(error_file,ptre); } else strcpy(error_file,ptre); ptre=error_file; } } } if (ptre != NULL && (fperr=fopen(ptre,"w")) == NULL) { printf ("****Error opening error message file: %s \n",ptre); return -1; } else if (ptre == NULL) { if (base_dir != NULL) { strcpy(error_file,base_dir); strcat(error_file,"/"); strcat(error_file,errf); } else strcpy(error_file,errf); ptre=error_file; if ((fperr=fopen(ptre,"w"))==NULL) { printf ("****Error opening default error message file: %s\n", ptre); return -1; } } /* First of all initialize the FT library */ /* open GKS */ gopks(fperr,0); /* Read the initial attributes script if is exists. */ if (access(script_file,R_OK) < 0) { printf("Warning - no initial.attributes file.\n"); } else { if (fperr == NULL) fperr=stdout; /* For normalization purposes, only read in the initial attribute one time, since * there may be templates that are already normalized... */ if (read_initial_attribute == 0) k=rscript(); read_initial_attribute = 1; if (k == 0) err_warn(1,fperr, "Error - from read of initial attributes: %d\n",k); if (fpin != NULL) fclose(fpin); } script_file[0]='\0'; fpin=fpout=NULL; ptri=ptro=ptre=NULL; if (argc >= 2) { for (i=1; i < argc; i++) { if (strncmp (argv[i],"-i",2) == 0) { do_interactive = 1; if (strlen(argv[i]) > (size_t)2) j=2; else if (++i < argc) j=0; else return -1; ptri=argv[i]; ptri+=j; if (strncmp("./",ptri,2) == 0) ptri+=2; if (strchr(ptri,'/')==NULL) { get_a_path(script_file); strcat(script_file,"/"); strcat(script_file,ptri); } else strcpy(script_file,ptri); ptri=script_file; } else if (strncmp (argv[i],"-ni",3) == 0) { do_interactive = 0; if (strlen(argv[i]) > (size_t)3) j=3; else if (++i < argc) j=0; else return -1; ptri=argv[i]; ptri+=j; if (strncmp("./",ptri,3) == 0) ptri+=3; if (strchr(ptri,'/')==NULL) { get_a_path(script_file); strcat(script_file,"/"); strcat(script_file,ptri); } else strcpy(script_file,ptri); ptri=script_file; } else if (strncmp (argv[i],"-o",2) == 0) { do_interactive = 1; if (strlen(argv[i]) > (size_t)2) j=2; else if (++i < argc) j=0; else return -1; ptro=argv[i]; ptro+=j; if ((strchr(ptro,'/')==NULL) && base_dir != NULL) { strcpy(output_file,base_dir); strcat(output_file,"/"); strcat(output_file,ptro); } else strcpy(output_file,ptro); /* Put a ".scr" extension on the name if needed. */ if ( (j=strlen(ptro)) < 4 || strcmp(".scr",&ptro[j-4]) != 0) { strcat(output_file,".scr"); } ptro=output_file; } else if (strncmp (argv[i],"-e",2) == 0) { do_interactive = 1; printf ("Error file is: %s.\n",argv[i]); } else if (strncmp (argv[i],"-geom",5) == 0) { do_interactive = 1; got_font_or_geom = 1; } else if (strncmp (argv[i],"-quiet",6) == 0) { do_interactive = 1; } else if (strncmp (argv[i],"-font",5) == 0) { do_interactive = 1; got_font_or_geom = 1; } else { if (got_font_or_geom == 0) printf ("Argument %s not used.\n",argv[i]); got_font_or_geom = 1; } }; }; if (ptro != NULL && (fpout=fopen(ptro,"w")) == NULL) { /* printf("script_file1 = %s\n", script_file);*/ printf ("****Error opening script output file: %s \n",ptro); return -1; } if (fpout != NULL) fprintf(fpout,"canvas(open)\n"); /* Open Workstation Independent Segment Storage. */ gopwk(7,NULL,"WISS"); gacwk(7); gsclip(GNOCLIP); /* If there is an input file defined, read and process the script. */ strcpy(buf, script_file); if ((ptri != NULL) && (k=run_script() == 0)) { /* printf("script_file2 = %s\n", script_file);*/ printf ("****Error opening script output file: %s \n",buf); } return 0; }
// Loop forever monitoring pins for activity. int watch_pins() { struct pollfd *fdlist; int i; char *pin_path; int pin_path_len; char valbuf[3]; struct timespec ts; unsigned char switch_state[num_pins]; long long now, down_at[num_pins]; valbuf[2] = '\0'; memset(switch_state, 0, num_pins); pin_path_len = strlen(GPIO_BASE) + GPIODIRLEN + strlen("value") + 3; pin_path = (char *)malloc(pin_path_len); fdlist = (struct pollfd *)malloc(sizeof(struct pollfd) * num_pins); for (i=0; i<num_pins; i++) { int fd; snprintf(pin_path, pin_path_len, "%s/gpio%d/value", GPIO_BASE, pins[i].pin); fd = open(pin_path, O_RDONLY); read(fd, valbuf, 2); fdlist[i].fd = fd; fdlist[i].events = POLLPRI; } LOG_INFO("starting to monitor for gpio events"); while (1) { int err; err = poll(fdlist, num_pins, -1); if (-1 == err) { perror("poll"); exit(1); } for (i=0; i<num_pins; i++) { if (fdlist[i].revents & POLLPRI) { LOG_DEBUG("pin %d: received event", pins[i].pin); lseek(fdlist[i].fd, 0, SEEK_SET); read(fdlist[i].fd, valbuf, 2); // for pins use 'switch' edge mode, we only trigger // an event when we receive the '1' event more than // DEBOUNCE_INTERVAL nanoseconds after the '0' event. if (EDGE_SWITCH == pins[i].edge) { clock_gettime(CLOCK_MONOTONIC, &ts); now = ts.tv_sec * NANOS + ts.tv_nsec; if (switch_state[i] == 0 && valbuf[0] == '1') { down_at[i] = now; switch_state[i] = 1; } else if (switch_state[i] == 1 && valbuf[0] == '0') { if (now - down_at[i] > DEBOUNCE_INTERVAL) { switch_state[i] = 0; goto run_script; } } continue; } run_script: run_script(pins[i].pin, valbuf[0] == '1' ? 1 : 0); } } } }
int pet_data_init(struct map_session_data *sd, struct s_pet *pet) { struct pet_data *pd; int i = 0, interval = 0; nullpo_retr(1,sd); Assert((sd->status.pet_id == 0 || sd->pd == NULL) || sd->pd->master == sd); if(sd->status.account_id != pet->account_id || sd->status.char_id != pet->char_id) { sd->status.pet_id = 0; return 1; } if(sd->status.pet_id != pet->pet_id) { if(sd->status.pet_id) { //Wrong pet?? Set incubate to no and send it back for saving pet->incubate = 1; intif_save_petdata(sd->status.account_id,pet); sd->status.pet_id = 0; return 1; } //The pet_id value was lost? Odd, restore it sd->status.pet_id = pet->pet_id; } i = search_petDB_index(pet->class_,PET_CLASS); if(i < 0) { sd->status.pet_id = 0; return 1; } sd->pd = pd = (struct pet_data *)aCalloc(1,sizeof(struct pet_data)); pd->bl.type = BL_PET; pd->bl.id = npc_get_new_npc_id(); pd->master = sd; pd->petDB = &pet_db[i]; pd->db = mob_db(pet->class_); memcpy(&pd->pet,pet,sizeof(struct s_pet)); status_set_viewdata(&pd->bl,pet->class_); unit_dataset(&pd->bl); pd->ud.dir = sd->ud.dir; pd->bl.m = sd->bl.m; pd->bl.x = sd->bl.x; pd->bl.y = sd->bl.y; unit_calc_pos(&pd->bl,sd->bl.x,sd->bl.y,sd->ud.dir); pd->bl.x = pd->ud.to_x; pd->bl.y = pd->ud.to_y; map_addiddb(&pd->bl); status_calc_pet(pd,SCO_FIRST); pd->last_thinktime = gettick(); pd->state.skillbonus = 0; if(battle_config.pet_status_support) run_script(pet_db[i].pet_script,0,sd->bl.id,0); if(pd->petDB) { if(pd->petDB->pet_friendly_script) status_calc_pc(sd,SCO_NONE); if(battle_config.pet_hungry_delay_rate != 100) interval = pd->petDB->hungry_delay * battle_config.pet_hungry_delay_rate / 100; else interval = pd->petDB->hungry_delay; } if(interval <= 0) interval = 1; pd->pet_hungry_timer = add_timer(gettick() + interval,pet_hungry,sd->bl.id,0); pd->masterteleport_timer = INVALID_TIMER; return 0; }
int run_backup(struct async *as, struct sdirs *sdirs, struct conf **cconfs, const char *incexc, int *timer_ret, int resume) { int ret; char okstr[32]=""; struct asfd *asfd=as->asfd; struct iobuf *rbuf=asfd->rbuf; const char *cname=get_string(cconfs[OPT_CNAME]); if(get_string(cconfs[OPT_RESTORE_CLIENT])) { // This client is not the original client, so a backup might // cause all sorts of trouble. logp("Not allowing backup of %s\n", cname); return asfd->write_str(asfd, CMD_GEN, "Backup is not allowed"); } // Set quality of service bits on backups. asfd->set_bulk_packets(asfd); if(!strncmp_w(rbuf->buf, "backupphase1timed")) { int a=0; const char *args[12]; int checkonly=!strncmp_w(rbuf->buf, "backupphase1timedcheck"); if(checkonly) logp("Client asked for a timer check only.\n"); args[a++]=get_string(cconfs[OPT_TIMER_SCRIPT]); args[a++]=cname; args[a++]=sdirs->current; args[a++]=sdirs->clients; args[a++]="reserved1"; args[a++]="reserved2"; args[a++]=NULL; if((*timer_ret=run_script(asfd, args, get_strlist(cconfs[OPT_TIMER_ARG]), cconfs, 1 /* wait */, 1 /* use logp */, 0 /* no log_remote */ ))<0) { logp("Error running timer script for %s\n", cname); return *timer_ret; } if(*timer_ret) { if(!checkonly) logp("Not running backup of %s\n", cname); return asfd->write_str(asfd, CMD_GEN, "timer conditions not met"); } if(checkonly) { logp("Client asked for a timer check only,\n"); logp("so a backup is not happening right now.\n"); return asfd->write_str(asfd, CMD_GEN, "timer conditions met"); } logp("Running backup of %s\n", cname); } else if(!get_int(cconfs[OPT_CLIENT_CAN_FORCE_BACKUP])) { logp("Not allowing forced backup of %s\n", cname); return asfd->write_str(asfd, CMD_GEN, "Forced backup is not allowed"); } snprintf(okstr, sizeof(okstr), "%s:%d", resume?"resume":"ok", get_int(cconfs[OPT_COMPRESSION])); if(asfd->write_str(asfd, CMD_GEN, okstr)) return -1; if((ret=do_backup_server(as, sdirs, cconfs, incexc, resume))) goto end; if((ret=delete_backups(sdirs, cname, get_strlist(cconfs[OPT_KEEP]), get_string(cconfs[OPT_MANUAL_DELETE])))) goto end; end: return ret; }