int netctrl_connect() { int port; char ip[IP_ADDR_LEN]; if (cfg_getstring(SECTION_NAME_IP, ip, IP_ADDR_LEN) != SUCCESS){ return ERROR; } printf("NET CONNECT GETSTRING %s\n", ip); port = cfg_getnumber(SECTION_NAME_PORT); if (port == 0) return ERROR; port = 9000; printf("NET CONNECT GET PORT %d\n", port); if (net_open(ip, port) != SUCCESS) return ERROR; printf("NET CONNECT OPEN\n"); return SUCCESS; }
void compatibility_sysv_utmp_clean() { char utmp_cfg = parse_boolean (cfg_getstring ("configuration-compatibility-sysv/utmp", NULL)); if (utmp_cfg) { notice (4, "cleaning utmp"); updateutmp_f (utmp_clean, NULL); } /* don't worry if it's not OK, as utmp is pretty much useless to eINIT, so no reason to bitch about it... */ }
int linux_hwclock_run() { if (!linux_hwclock_enabled) { linux_hwclock_enabled = 1; char *options = cfg_getstring ("configuration-services-hwclock/options", NULL); if (!options) options = "--utc"; char tmp [BUFFERSIZE]; esprintf (tmp, BUFFERSIZE, "/sbin/hwclock --hctosys %s", options); system (tmp); } return status_ok; }
int linux_static_dev_run() { char *dm; if (!linux_static_dev_enabled && (dm = cfg_getstring("configuration-system-device-manager", NULL)) && strmatch (dm, "static")) { linux_static_dev_enabled = 1; mount ("proc", "/proc", "proc", 0, NULL); mount ("sys", "/sys", "sysfs", 0, NULL); mount ("devpts", "/dev/pts", "devpts", 0, NULL); mount ("shm", "/dev/shm", "tmpfs", 0, NULL); ethread_spawn_detached ((void *(*)(void *))linux_static_dev_hotplug, (void *)NULL); FILE *he = fopen ("/proc/sys/kernel/hotplug", "w"); if (he) { char *hotplug_handler = cfg_getstring ("configuration-system-hotplug-handler", NULL); if (hotplug_handler) { fputs (hotplug_handler, he); } else { fputs ("", he); } fputs ("\n", he); fclose (he); } linux_static_dev_load_kernel_extensions(); mount ("usbfs", "/proc/bus/usb", "usbfs", 0, NULL); return status_ok; } else return status_failed; }
int linux_hwclock_shutdown() { if (linux_hwclock_enabled) { char *options = cfg_getstring ("configuration-services-hwclock/options", NULL); if (!options) options = "--utc"; char tmp [BUFFERSIZE]; esprintf (tmp, BUFFERSIZE, "/sbin/hwclock --systohc %s", options); system (tmp); linux_hwclock_enabled = 0; } return status_ok; }
int linux_hotplug_configure (struct lmodule *tm) { module_init (tm); exec_configure (tm); char *dm = cfg_getstring("configuration-system-device-manager", NULL); /* this module won't work unless we're using either mdev, edev or a static dev, due to the hotplug event reader not being implemented in udev */ if (!dm || (strcmp (dm, "mdev") && strcmp (dm, "edev") && strcmp (dm, "static"))) { return status_configure_failed | status_not_in_use; } event_listen (einit_event_subsystem_hotplug, linux_hotplug_hotplug_event_handler); return 1; }
int linux_alsasound_configure (struct lmodule *pa) { module_init (pa); pa->enable = linux_alsasound_enable; pa->disable = linux_alsasound_disable; char *statefile = cfg_getstring ("configuration-services-alsasound/statefile", NULL); if (statefile) { char *files[2]; files[0] = statefile; files[1] = 0; char *after = after_string_from_files (files); if (after) { ((struct smodule *)pa->module)->si.after = set_str_add_stable(NULL, after); efree (after); } } return 0; }
int linux_kernel_modules_load (char **modules) { if (!modules) return status_failed; pthread_t **threads = NULL; char *modprobe_command = cfg_getstring ("configuration-command-modprobe/with-env", 0); uint32_t i = 0; for (; modules[i]; i++) if (strcmp ("", modules[i])) { const char *tpldata[] = { "module", modules[i], NULL }; char *applied = apply_variables (modprobe_command, tpldata); if (applied) { notice (4, "loading kernel module: %s", modules[i]); if (modules[i+1]) { pthread_t *threadid = emalloc (sizeof (pthread_t)); if (ethread_create (threadid, NULL, (void *(*)(void *))linux_kernel_modules_load_exec, applied)) { linux_kernel_modules_load_exec (applied); } else { threads = (pthread_t **)setadd ((void **)threads, threadid, SET_NOALLOC); } } else { linux_kernel_modules_load_exec (applied); } } } free (modules); if (threads) { int i = 0; for (; threads[i]; i++) { pthread_join (*(threads[i]), NULL); free (threads[i]); } free (threads); } return status_ok; }
int linux_alsasound_disable (void *param, struct einit_event *status) { int ret = status_ok; char *statefile = cfg_getstring ("configuration-services-alsasound/statefile", NULL); if (statefile) { fprintf(stdout,"%s",statefile); struct stat fileattrib; if (stat(statefile, &fileattrib) == 0) { pid_t pid = fork(); if (pid==0) { char *cmd[] = { "/usr/sbin/alsactl", "-f", statefile, "store", (char *)0 }; if (!execv (cmd[0], cmd)) { ret = status_failed; } } } else { char msg[BUFFERSIZE]; snprintf(msg,BUFFERSIZE,"Could not find %s, unmute mixer manually.",statefile); fprintf(stdout,"%s",msg); ret = status_failed; } } return ret; }
int main(int argc, char *argv[]) { pthread_t thread_wdt; pthread_t thread_log; pthread_t thread_fifoSrv; pthread_t thread_snmpSrv; pthread_t thread_sendfifo; pthread_t thread_ch1, thread_ch2; pthread_t thread_rtSend, thread_rtRecv; struct wdt_thread_arg wdt_targ; struct log_thread_arg log_targ; struct fifo_thread_arg fifoSrv_targ; struct snmp_thread_arg snmpSrv_targ; struct sfifo_thread_arg sendfifo_targ; struct chan_thread_arg ch1_targ, ch2_targ; struct rt_thread_arg rtSend_targ, rtRecv_targ; int result; char cfile[64]; char lfile[64]; char lfile_old[64]; char lifeFile[64]; int rs_parity, rs_databits, rs_stopbit; int rs_speed; unsigned int utxdel; int tscan; int tout, nretries; int wdt_en; unsigned long wdt_tm; int ch1_enable, ch2_enable; char ip[16]; unsigned int fifo_port; char rt_ipSend[16]; char rt_ipRecv[16]; unsigned int rt_portSend, rt_portRecv; char logSend_ip[16]; unsigned int logSend_port, logMaxLines; int snmp_n, snmp_uso; char *tempip; char ls_gen[32]; char req_ag[32]; char req_ns[32]; char req_gl[32]; char req_ms[32]; int cdDest; int cdaId; int cdnsId; int cdquLogId; int cdmsId; int i; char key[7] = {0}; TOHT *cfg; if( argc == 2) sprintf(cfile, argv[1]); else { sprintf(cfile, "mslave_default.cfg"); gen_moxa_default_cfg(cfile); /** Генерация slave конфиг файла * по умолчанию */ } cfg = cfg_load(cfile); /** Загрузили общий конфиг */ /** Установка лог файла */ sprintf(lfile, cfg_getstring(cfg, "moxa:log", NULL)); sprintf(lfile_old, cfg_getstring(cfg, "moxa:log_old", NULL)); bo_setLogParam(lfile, lfile_old, 0, 1000); /** Генерация таблицы для расчета контрольной суммы * кадра сети RS485 по алгоритму CRC16-MODBUS */ gen_tbl_crc16modbus(); /** Установка таймеров */ tscan = cfg_getint(cfg, "moxa:Tscan", -1); tout = cfg_getint(cfg, "moxa:Tout", -1); nretries = cfg_getint(cfg, "moxa:nRetries", -1); /** Установка параметров WatchDog */ wdt_targ.tsec = cfg_getint(cfg, "WDT:Tsec", -1); wdt_targ.tusec = cfg_getint(cfg, "WDT:Tusec", -1); wdt_tm = (unsigned long)cfg_getint(cfg, "WDT:Tms", -1); wdt_en = cfg_getint(cfg, "WDT:enable", -1); /** Инициализация файла для контроля жизни программы через CRON */ sprintf(lifeFile, cfg_getstring(cfg, "WDT:lifeFile", NULL)); /* gen_moxa_cron_life(lifeFile); */ /** IP адрес узла */ sprintf(ip, cfg_getstring(cfg, "eth0:ip", NULL)); /** FIFO сервер */ fifo_port = (unsigned int)cfg_getint(cfg, "FIFO:port", -1); fifoSrv_targ.qu_len = cfg_getint(cfg, "FIFO:queue_len", -1); fifoSrv_targ.len = cfg_getint(cfg, "FIFO:len", -1); /** RT SEND server IP, port */ sprintf(rt_ipSend, cfg_getstring(cfg, "RT:sendIp", NULL)); rt_portSend = (unsigned int)cfg_getint(cfg, "RT:sendPort", -1); /** RT RECV server IP, port */ sprintf(rt_ipRecv, cfg_getstring(cfg, "RT:recvIp", NULL)); rt_portRecv = (unsigned int)cfg_getint(cfg, "RT:recvPort", -1); /** LOGGER server IP, port, максимальное количество строк */ sprintf(logSend_ip, cfg_getstring(cfg, "LOGGER:sendIp", NULL)); logSend_port = (unsigned int)cfg_getint(cfg, "LOGGER:sendPort", -1); logMaxLines = (unsigned int)cfg_getint(cfg, "LOGGER:maxLines", -1); /** SNMP */ snmp_n = cfg_getint(cfg, "SNMP:n", -1); /** Адрес УСО */ snmp_uso = cfg_getint(cfg, "SNMP:uso", -1); if (snmp_n > 0 && snmp_n <= SNMP_IP_MAX) for (i=0; i<snmp_n; i++) { sprintf(key, "SNMP:%01d", i+1); snmpSrv_targ.ip[i] = malloc(sizeof(char) * 16); tempip = cfg_getstring(cfg, key, NULL); memcpy(*(snmpSrv_targ.ip+i), tempip, strlen(tempip)+1); } /** Загрузка параметров серийного порта */ /** 0: none, 1: odd, 2: even, 3: space, 4: mark */ rs_parity = cfg_getint(cfg, "RS:prmParity", -1); /** 5 .. 8 */ rs_databits = cfg_getint(cfg, "RS:prmDatabits", -1); /** 1, 2 */ rs_stopbit = cfg_getint(cfg, "RS:prmStopbit", -1); /** Скорость канала RS485 */ rs_speed = cfg_getint(cfg, "RS:speed", -1); /** Длительность одного бита (в микросекундах) вычисляется по формуле: T= 1000000 / V, где V - скорость передачи в бодах. Например, для скорости 19200 бод длительность одного бита составляет 1000000/19200= 52 мкс. */ /** коэффициент для задержки на время передачи по серийному каналу */ utxdel = 1000000 / rs_speed * 10; /** Главная подсистема ЛС 'General' */ sprintf(ls_gen, cfg_getstring(cfg, "LS:gen", NULL)); cdDest = mfnv1a(ls_gen); /** Разрешение на выдачу данных 'AccessGranted' */ sprintf(req_ag, cfg_getstring(cfg, "REQ:ag", NULL)); cdaId = mfnv1a(req_ag); /** Состояние сети RS485 */ sprintf(req_ns, cfg_getstring(cfg, "REQ:ns", NULL)); cdnsId = mfnv1a(req_ns); /** Запрос лога */ sprintf(req_gl, cfg_getstring(cfg, "REQ:gl", NULL)); cdquLogId = mfnv1a(req_gl); /** Состояние магистрали */ sprintf(req_ms, cfg_getstring(cfg, "REQ:ms", NULL)); cdmsId = mfnv1a(req_ms); /** Установка параметров и открытие порта 1 RS485 */ ch1_targ.port = cfg_getint(cfg, "RS485_1:port", -1) - 1; ch1_targ.src = cfg_getint(cfg, "RS485_1:adr", -1); ch1_targ.dst_beg = cfg_getint(cfg, "RS485_1:dstBeg", -1); ch1_targ.dst_end = cfg_getint(cfg, "RS485_1:dstEnd", -1); ch1_enable = cfg_getint(cfg, "RS485_1:enable", -1); if (ch1_enable) { SerialSetParam(ch1_targ.port, rs_parity, rs_databits, rs_stopbit); SerialOpen(ch1_targ.port); SerialSetSpeed(ch1_targ.port, rs_speed); printf("Open port%d, speed= %d\n", ch1_targ.port+1, rs_speed); } else printf("Port1 disabled\n"); /** Установка параметров и открытие порта 2 RS485 */ ch2_targ.port = cfg_getint(cfg, "RS485_2:port", -1) - 1; ch2_targ.src = cfg_getint(cfg, "RS485_2:adr", -1); ch2_targ.dst_beg = cfg_getint(cfg, "RS485_2:dstBeg", -1); ch2_targ.dst_end = cfg_getint(cfg, "RS485_2:dstEnd", -1); ch2_enable = cfg_getint(cfg, "RS485_2:enable", -1); if (ch2_enable) { SerialSetParam(ch2_targ.port, rs_parity, rs_databits, rs_stopbit); SerialOpen(ch2_targ.port); SerialSetSpeed(ch2_targ.port, rs_speed); printf("Open port%d, speed2= %d\n", ch2_targ.port+1, rs_speed); } else printf("Port2 disabled\n"); cfg_free(cfg); /** Выделение памяти под буфер для глобальной таблицы * маршрутов загружаемой с контроллера master */ rtBuf = (unsigned char *)malloc(BO_MAX_TAB_BUF); if(rtBuf == NULL) { bo_log("main() ERROR %s", "can't alloc mem for rtBuf"); return 1; } bo_log("Init ok"); printf("Init ok\n"); if (bo_init_fifo_out(10) == -1) { bo_log("bo_init_fifo_out() ERROR"); return 1; } /** Установка атрибутов функционирования нитей PTHREAD: * - инициализирует структуру, указываемую pattr, значениями "по умолчанию"; * - область действия конкуренции (scope) определяет связность * потока с LWP; * - отсоединенность (detachstate); * - область действия блокировки PTHREAD_PROCESS_PRIVATE. */ pthread_attr_init(&pattr); pthread_attr_setscope(&pattr, PTHREAD_SCOPE_SYSTEM); pthread_attr_setdetachstate(&pattr, PTHREAD_CREATE_JOINABLE); pthread_mutex_init(&mx_psv, NULL); pthread_mutex_init(&mx_actFIFO, NULL); pthread_mutex_init(&mx_rtl, NULL); pthread_mutex_init(&mx_rtg, NULL); pthread_mutex_init(&mx_sendSocket, NULL); init_thrState(&psvdata_ready); init_thrState(&psvAnsdata_ready); init_thrState(&actFIFOdata_ready); init_thrRxBuf(&rxBuf); init_thrTxBuf(&txBuf); init_thrDstBuf(&dstBuf); init_thrRxBuf(&rx2Buf); init_thrTxBuf(&tx2Buf); init_thrDstBuf(&dst2Buf); /** Инициализация условных переменных с выделением памяти */ pthread_cond_init(&psvdata, NULL); pthread_cond_init(&psvAnsdata, NULL); pthread_cond_init(&actFIFOdata, NULL); /** Таблицы маршрутов */ rtl = ht_new(0); /** собственный узел */ rtg = ht_new(0); /** внешние узлы */ rtSend_sock = 0; rtRecv_sock = 0; logSend_sock = 0; fifo_idx = 0; log_targ.logSend_ip = logSend_ip; log_targ.logSend_port = logSend_port; result = pthread_create(&thread_log, &pattr, &logSendSock_connect, &log_targ); if (result) { printf("th_log: result = %d: %s\n", result, strerror(errno)); return 1; } rtRecv_targ.ip = rt_ipRecv; rtRecv_targ.port = rt_portRecv; rtRecv_targ.host_ip = ip; result = pthread_create(&thread_rtRecv, &pattr, &rtbl_recv, &rtRecv_targ); if (result) { printf("th_rtRecv: result = %d: %s\n", result, strerror(errno)); return 1; } rtSend_targ.ip = rt_ipSend; rtSend_targ.port = rt_portSend; rtSend_targ.host_ip = ip; result = pthread_create(&thread_rtSend, &pattr, &rtbl_send, &rtSend_targ); if (result) { printf("th_rtSend: result = %d: %s\n", result, strerror(errno)); return 1; } if (snmp_n > 0 && snmp_n <= SNMP_IP_MAX) { snmpSrv_targ.n = snmp_n; printf("ip=%s, n=%d\n", (snmpSrv_targ.ip[0]), snmpSrv_targ.n); result = pthread_create(&thread_snmpSrv, &pattr, &snmp_serv, &snmpSrv_targ); if (result) { printf("th_snmpSrv: result = %d: %s\n", result, strerror(errno)); return 1; } printf("snmp start ok\n"); } fifoSrv_targ.port = fifo_port; result = pthread_create(&thread_fifoSrv, &pattr, &fifo_serv, &fifoSrv_targ); if (result) { printf("th_fifoSrv: result = %d: %s\n", result, strerror(errno)); return 1; } write(1, "fifo start ok\n", 14); sendfifo_targ.port = fifo_port; result = pthread_create(&thread_sendfifo, &pattr, &send_fifo, &sendfifo_targ); if (result) { printf("th_sendfifo: result = %d: %s\n", result, strerror(errno)); return 1; } write(1, "send_fifo start ok\n", 14); ch1_targ.ch1_enable = ch1_enable; ch1_targ.ch2_enable = ch2_enable; ch1_targ.tscan = tscan; ch1_targ.tout = tout; ch1_targ.utxdel = utxdel; ch1_targ.wdt_en = wdt_en; ch1_targ.nretries = nretries; ch1_targ.ip = ip; ch1_targ.fifo_port = fifo_port; ch1_targ.snmp_n = snmp_n; ch1_targ.snmp_uso = snmp_uso; ch1_targ.logMaxLines = logMaxLines; ch1_targ.cdDest = cdDest; ch1_targ.cdaId = cdaId; ch1_targ.cdnsId = cdnsId; ch1_targ.cdquLogId = cdquLogId; ch1_targ.cdmsId = cdmsId; result = pthread_create(&thread_ch1, &pattr, &chan1, &ch1_targ); if (result) { printf("th_ch1: result = %d: %s\n", result, strerror(errno)); return 1; } write(1, "ch1 start ok\n", 13); ch2_targ.ch1_enable = ch1_enable; ch2_targ.ch2_enable = ch2_enable; ch2_targ.tscan = tscan; ch2_targ.tout = tout; ch2_targ.utxdel = utxdel; ch2_targ.wdt_en = wdt_en; ch2_targ.nretries = nretries; ch2_targ.ip = ip; ch2_targ.fifo_port = fifo_port; ch2_targ.snmp_n = snmp_n; ch2_targ.snmp_uso = snmp_uso; ch2_targ.logMaxLines = logMaxLines; ch2_targ.cdDest = cdDest; ch2_targ.cdaId = cdaId; ch2_targ.cdnsId = cdnsId; ch2_targ.cdquLogId = cdquLogId; ch2_targ.cdmsId = cdmsId; result = pthread_create(&thread_ch2, &pattr, &chan2, &ch2_targ); if (result) { printf("th_ch2: result = %d: %s\n", result, strerror(errno)); return 1; } write(1, "ch2 start ok\n", 13); #if defined (__MOXA_TARGET__) && defined (__WDT__) if (wdt_en) { /* set watch dog timer, must be refreshed in 5ms..60s */ wdt_fd = mxwdg_open(wdt_tm); if (wdt_fd < 0) { printf("fail to open the watch dog !: %d [%s]\n", wdt_fd, strerror(errno)); return 1; } init_thrWdtlife(&wdt_life); printf("WatchDog enabled ok\n"); } #endif wdt_targ.wdt_en = wdt_en; wdt_targ.lifeFile = lifeFile; result = pthread_create(&thread_wdt, &pattr, &wdt, &wdt_targ); if (result) { printf("th_wdt: result = %d: %s\n", result, strerror(errno)); return 1; } /** Ожидаем завершения потоков */ if (!pthread_equal(pthread_self(), thread_log)) pthread_join(thread_log, NULL); if (!pthread_equal(pthread_self(), thread_rtRecv)) pthread_join(thread_rtRecv, NULL); if (!pthread_equal(pthread_self(), thread_rtSend)) pthread_join(thread_rtSend, NULL); if (snmp_n > 0 && snmp_n <= SNMP_IP_MAX) if (!pthread_equal(pthread_self(), thread_snmpSrv)) pthread_join(thread_snmpSrv, NULL); if (!pthread_equal(pthread_self(), thread_fifoSrv)) pthread_join(thread_fifoSrv, NULL); if (!pthread_equal(pthread_self(), thread_sendfifo)) pthread_join(thread_sendfifo, NULL); if (!pthread_equal(pthread_self(), thread_ch1)) pthread_join(thread_ch1, NULL); if (!pthread_equal(pthread_self(), thread_ch2)) pthread_join(thread_ch2, NULL); if (!pthread_equal(pthread_self(), thread_wdt)) pthread_join(thread_wdt, NULL); /** Разрушаем блокировки и условные переменные, освобождаем память. */ pthread_mutex_destroy(&mx_psv); pthread_mutex_destroy(&mx_actFIFO); pthread_mutex_destroy(&mx_rtl); pthread_mutex_destroy(&mx_rtg); pthread_mutex_destroy(&mx_sendSocket); destroy_thrRxBuf(&rxBuf); destroy_thrTxBuf(&txBuf); destroy_thrDstBuf(&dstBuf); destroy_thrRxBuf(&rx2Buf); destroy_thrTxBuf(&tx2Buf); destroy_thrDstBuf(&dst2Buf); pthread_cond_destroy(&psvdata); pthread_cond_destroy(&psvAnsdata); pthread_cond_destroy(&actFIFOdata); destroy_thrState(&psvdata_ready); destroy_thrState(&psvAnsdata_ready); destroy_thrState(&actFIFOdata_ready); #if defined (__MOXA_TARGET__) && defined (__WDT__) if (wdt_en) { destroy_thrWdtlife(&wdt_life); mxwdg_close(wdt_fd); } #endif if(rtBuf != NULL) free(rtBuf); rt_free(rtl); rt_free(rtg); return 0; }
mh_history_params* load_params(const char *path) { mh_history_params *p = allocate(1, sizeof(*p)); config_t *cfg = new_cfg(); cfg_loadfile(cfg, path); const char *input; config_setting_t *inputs = cfg_findsetting(cfg, "inputs"); input = cfg_getstring(inputs, "matches_512_256"); p->matches_512_256 = strdup(input); check_file_harsh(p->matches_512_256, "Wrong matches_512_256 in configs"); input = cfg_getstring(inputs, "matches_1024_512"); p->matches_1024_512 = strdup(input); check_file_harsh(p->matches_1024_512, "Wrong matches_1024_512 in configs"); const char *raw_matches_256_path = cfg_getstring(inputs, "matches_256"); const char *raw_matches_512_path = cfg_getstring(inputs, "matches_512"); const char *raw_matches_1024_path = cfg_getstring(inputs, "matches_1024"); p->num_match_files = cfg_getint(inputs, "num_of_match_files"); p->matches_256 = allocate(p->num_match_files, sizeof(char*)); p->matches_512 = allocate(p->num_match_files, sizeof(char*)); p->matches_1024 = allocate(p->num_match_files, sizeof(char*)); int i; char match_fname[1024], *errormsg; for(i = 0; i < p->num_match_files; i++){ sprintf(match_fname, raw_matches_256_path, i, i+1); p->matches_256[i] = strdup(match_fname); errormsg = concat(2, match_fname, " does not exist"); check_file_harsh(p->matches_256[i], errormsg); sprintf(match_fname, raw_matches_512_path, i, i+1); p->matches_512[i] = strdup(match_fname); errormsg = concat(2, match_fname, " does not exist"); check_file_harsh(p->matches_512[i], errormsg); sprintf(match_fname, raw_matches_1024_path, i, i+1); p->matches_1024[i] = strdup(match_fname); errormsg = concat(2, match_fname, " does not exist"); check_file_harsh(p->matches_1024[i], errormsg); } const char *raw_halos_256_path = cfg_getstring(inputs, "halos_256"); const char *raw_halos_512_path = cfg_getstring(inputs, "halos_512"); const char *raw_halos_1024_path = cfg_getstring(inputs, "halos_1024"); p->num_halo_files = cfg_getint(inputs, "num_of_halo_files"); p->halos_256 = allocate(p->num_halo_files, sizeof(char*)); p->halos_512 = allocate(p->num_halo_files, sizeof(char*)); p->halos_1024 = allocate(p->num_halo_files, sizeof(char*)); char halo_fname[1024]; for(i = 0; i < p->num_halo_files; i++){ sprintf(halo_fname, raw_halos_256_path, i); p->halos_256[i] = strdup(halo_fname); errormsg = concat(2, halo_fname, " does not exist"); check_file_harsh(p->halos_256[i], errormsg); sprintf(halo_fname, raw_halos_512_path, i); p->halos_512[i] = strdup(halo_fname); errormsg = concat(2, halo_fname, " does not exist"); check_file_harsh(p->halos_512[i], errormsg); sprintf(halo_fname, raw_halos_1024_path, i); p->halos_1024[i] = strdup(halo_fname); errormsg = concat(2, halo_fname, " does not exist"); check_file_harsh(p->halos_1024[i], errormsg); } const char *output; config_setting_t *outputs = cfg_findsetting(cfg, "outputs"); output = cfg_getstring(outputs, "ascii"); p->ascii_output = strdup(output); char *for_dir_check = strdup(output); if(check_dir(dirname(for_dir_check)) != CD_DIR_EXIST){ printf("[Error! Wrong ascii_output dir in configs]\n"); exit(EXIT_FAILURE); } return p; }
int einit_feedback_visual_fbsplash_enable () { char *tmp = NULL, *fbtheme = NULL, *fbmode = "silent"; char freetheme = 0, freemode = 0, have_verbose_tty = 0; einit_feedback_visual_fbsplash_worker_thread_keep_running = 1; ethread_create (&fbsplash_thread, NULL, einit_feedback_visual_fbsplash_worker_thread, NULL); if (einit_initial_environment) { /* check for kernel params */ uint32_t i = 0; for (; einit_initial_environment[i]; i++) { if (strstr (einit_initial_environment[i], "splash=")) { char *params = estrdup(einit_initial_environment[i] + 7); if (params) { char **p = str2set (',', params); if (p) { for (i = 0; p[i]; i++) { char *sep = strchr (p[i], ':'); if (sep) { *sep = 0; sep++; if (strmatch (p[i], "theme")) { fbtheme = estrdup (sep); freetheme = 1; } } else { fbmode = estrdup(p[i]); freemode = 1; } } free (p); } free (params); } break; } } } /* if (fbtheme || (fbtheme = cfg_getstring ("configuration-feedback-visual-fbsplash-theme", NULL))) { char tmpx[BUFFERSIZE]; esprintf (tmpx, BUFFERSIZE, "set theme %s", fbtheme); fbsplash_queue_comand(tmpx); if (freetheme) free (fbtheme); // notice (1, tmpx); }*/ if ((tmp = cfg_getstring ("configuration-feedback-visual-fbsplash-daemon-ttys/silent", NULL))) { char tmpx[BUFFERSIZE]; esprintf (tmpx, BUFFERSIZE, "set tty silent %s", tmp); fbsplash_queue_comand(tmpx); } if ((tmp = cfg_getstring ("configuration-feedback-visual-std-io/stdio", NULL))) { char *x = strstr (tmp, "tty"); if (x && *(x+3)) { char tmpx[BUFFERSIZE]; esprintf (tmpx, BUFFERSIZE, "set tty verbose %s", x+3); fbsplash_queue_comand(tmpx); have_verbose_tty = 1; } } if (!have_verbose_tty && (tmp = cfg_getstring ("configuration-feedback-visual-fbsplash-daemon-ttys/verbose", NULL))) { char tmpx[BUFFERSIZE]; esprintf (tmpx, BUFFERSIZE, "set tty verbose %s", tmp); fbsplash_queue_comand(tmpx); } if ((tmp = cfg_getstring ("configuration-feedback-visual-fbsplash-daemon-fifo", NULL))) { fbsplash_fifo = tmp; } if (fbmode) { char tmpx[BUFFERSIZE]; esprintf (tmpx, BUFFERSIZE, "set mode %s", fbmode); fbsplash_queue_comand(tmpx); fbsplash_queue_comand("repaint"); if (freemode) free (fbmode); // notice (1, tmpx); } fbsplash_queue_comand("progress 0"); return status_ok; }
void core_einit_event_handler (struct einit_event *ev) { if (ev->type == einit_core_configuration_update) { struct cfgnode *node; char *str; ev->chain_type = einit_core_update_modules; if ((node = cfg_getnode ("core-mortality-bad-malloc", NULL))) mortality[bitch_emalloc] = node->value; if ((node = cfg_getnode ("core-mortality-bad-stdio", NULL))) mortality[bitch_stdio] = node->value; if ((node = cfg_getnode ("core-mortality-bad-regex", NULL))) mortality[bitch_regex] = node->value; if ((node = cfg_getnode ("core-mortality-bad-expat", NULL))) mortality[bitch_expat] = node->value; if ((node = cfg_getnode ("core-mortality-bad-dl", NULL))) mortality[bitch_dl] = node->value; if ((node = cfg_getnode ("core-mortality-bad-lookup", NULL))) mortality[bitch_lookup] = node->value; if ((node = cfg_getnode ("core-mortality-bad-pthreads", NULL))) mortality[bitch_epthreads] = node->value; if ((node = cfg_getnode ("core-settings-allow-code-unloading", NULL))) einit_allow_code_unloading = node->flag; if ((str = cfg_getstring ("core-scheduler-niceness/core", NULL))) einit_core_niceness_increment = parse_integer (str); if ((str = cfg_getstring ("core-scheduler-niceness/tasks", NULL))) einit_task_niceness_increment = parse_integer (str); } else if (ev->type == einit_core_update_modules) { struct lmodule *lm; repeat: lm = mlist; einit_new_node = 0; while (lm) { if (lm->source && strmatch(lm->source, "core")) { lm = mod_update (lm); // tell module to scan for changes if it's a module-loader if (lm->module && (lm->module->mode & einit_module_loader) && (lm->scanmodules != NULL)) { notice (8, "updating modules (%s)", lm->module->rid ? lm->module->rid : "unknown"); lm->scanmodules (mlist); /* if an actual new node has been added to the configuration, repeat this step */ if (einit_new_node) goto repeat; } } lm = lm->next; } /* give the module-logic code and others a chance at processing the current list */ struct einit_event update_event = evstaticinit(einit_core_module_list_update); update_event.para = mlist; event_emit (&update_event, einit_event_flag_broadcast); evstaticdestroy(update_event); } else if (ev->type == einit_core_recover) { // call everyone's recover-function (if defined) struct lmodule *lm = mlist; while (lm) { if (lm->recover) { lm->recover (lm); } lm = lm->next; } } else if (ev->type == einit_core_suspend_all) { // suspend everyone (if possible) struct lmodule *lm = mlist; int ok = 0; while (lm) { ok += (mod (einit_module_suspend, lm, NULL) == status_ok) ? 1 : 0; lm = lm->next; } if (ok) notice (4, "%i modules suspended", ok); event_snooze_time = event_timer_register_timeout(60); } else if (ev->type == einit_core_resume_all) { // resume everyone (if necessary) struct lmodule *lm = mlist; int ok = 0; while (lm) { ok += (mod (einit_module_resume, lm, NULL) == status_ok) ? 1 : 0; lm = lm->next; } if (ok) notice (4, "%i available", ok); } }
char updateutmp_f (enum utmp_action options, struct utmp *new_entry) { int ufile; struct stat st; // strip the utmp_add action if we don't get a new entry to add along with it if ((options & utmp_add) && !new_entry) options ^= utmp_add; // if we don't have anything to do, bail out if (!options) return -1; if (coremode == einit_mode_sandbox) ufile = eopen ("var/run/utmp", O_RDWR); else ufile = eopen ("/var/run/utmp", O_RDWR); if (ufile) { if (!fstat (ufile, &st) && st.st_size) { struct utmp *utmpentries = mmap (NULL, st.st_size, PROT_READ | PROT_WRITE, MAP_SHARED, ufile, 0); if (utmpentries != MAP_FAILED) { uint32_t entries = st.st_size / sizeof(struct utmp), i = 0; eclose (ufile); ufile = 0; for (i = 0; i < entries; i++) { #ifdef LINUX switch (utmpentries[i].ut_type) { case DEAD_PROCESS: if (options & utmp_add) { memcpy (&(utmpentries[i]), new_entry, sizeof (struct utmp)); options ^= utmp_add; } break; case RUN_LVL: if (options & utmp_clean) { /* the higher 8 bits contain the old runlevel, the lower 8 bits the current one */ char *new_previous_runlevel = cfg_getstring ("configuration-compatibility-sysv-simulate-runlevel/before", NULL), *new_runlevel = cfg_getstring ("configuration-compatibility-sysv-simulate-runlevel/now", NULL); if (new_runlevel && new_runlevel[0]) { if (new_previous_runlevel) utmpentries[i].ut_pid = (new_previous_runlevel[0] << 8) | new_runlevel[0]; else utmpentries[i].ut_pid = (utmpentries[i].ut_pid << 8) | new_runlevel[0]; } } break; case UT_UNKNOWN: case BOOT_TIME: case NEW_TIME: case OLD_TIME: case INIT_PROCESS: case LOGIN_PROCESS: case USER_PROCESS: case ACCOUNTING: if (options & utmp_clean) { #ifdef LINUX struct stat xst; char path[BUFFERSIZE]; esprintf (path, BUFFERSIZE, "/proc/%i/", utmpentries[i].ut_pid); if (stat (path, &xst)) { // stat path under proc to see if process exists // if not... #endif // clean utmp record if (options & utmp_add) { memcpy (&(utmpentries[i]), new_entry, sizeof (struct utmp)); options ^= utmp_add; } else { utmpentries[i].ut_type = DEAD_PROCESS; memset (&(utmpentries[i].ut_user), 0, sizeof (utmpentries[i].ut_user)); memset (&(utmpentries[i].ut_host), 0, sizeof (utmpentries[i].ut_host)); memset (&(utmpentries[i].ut_time), 0, sizeof (utmpentries[i].ut_time)); } #ifdef LINUX } #endif } break; #ifdef DEBUG default: notice (6, "bad UTMP entry: [%c%c%c%c] %i (%s), %s@%s: %i.%i\n", utmpentries[i].ut_id[0], utmpentries[i].ut_id[1], utmpentries[i].ut_id[2], utmpentries[i].ut_id[3], utmpentries[i].ut_type, utmpentries[i].ut_line, utmpentries[i].ut_user, utmpentries[i].ut_host, (int)utmpentries[i].ut_tv.tv_sec, (int)utmpentries[i].ut_tv.tv_usec); break; #endif } if ((options & utmp_modify) && (utmpentries[i].ut_pid == new_entry->ut_pid)) { memcpy (&(utmpentries[i]), new_entry, sizeof (struct utmp)); options ^= utmp_modify; } #endif if (!options) break; } munmap (utmpentries, st.st_size); } else { bitch(bitch_stdio, 0, "mmap() failed"); } } if (ufile) eclose (ufile); } else { bitch(bitch_stdio, 0, "open() failed"); } if (options & utmp_add) { // still didn't get to add this.. try to append it to the file if (coremode == einit_mode_sandbox) ufile = open ("var/run/utmp", O_WRONLY | O_APPEND); else ufile = open ("/var/run/utmp", O_WRONLY | O_APPEND); if (ufile) { if (write(ufile, new_entry, sizeof (struct utmp)) != sizeof (struct utmp)) { bitch(bitch_stdio, 0, "short write to utmp file"); } eclose (ufile); } else { bitch(bitch_stdio, 0, "mmap() failed"); } options ^= utmp_add; } return 0; }
void *linux_bootchart_thread (void *ignored) { struct cfgnode *node; char *save_to = "/var/log/bootchart.tgz"; FILE *f; char try_acct = 1; signed int extra_wait = 0; if ((node = cfg_getnode ("configuration-bootchart-extra-waiting-time", NULL)) && node->value) { extra_wait = node->value; } char *buffer_ds = NULL; char *buffer_ps = NULL; char *buffer_st = NULL; while (!shutting_down && (linux_bootchart_have_thread || (extra_wait > 0))) { char *uptime = linux_bootchart_get_uptime(); if (linux_bootchart_process_accounting && try_acct) { if (acct ("/dev/kernel_pacct") == -1) try_acct = 1; } if (uptime) { buffer_ds = linux_bootchart_update_ds (buffer_ds, uptime); buffer_ps = linux_bootchart_update_ps (buffer_ps, uptime); buffer_st = linux_bootchart_update_st (buffer_st, uptime); free (uptime); uptime = NULL; } usleep (linux_bootchart_sleep_time); if (!linux_bootchart_have_thread) extra_wait -= linux_bootchart_sleep_time; } if ((node = cfg_getnode ("configuration-bootchart-save-to", NULL)) && node->svalue) { save_to = node->svalue; } if (coremode & einit_mode_sandbox) { save_to = "bootchart.tgz"; } mkdir ("/tmp/bootchart.einit", 0755); if (buffer_ds) { if ((f = fopen ("/tmp/bootchart.einit/proc_diskstats.log", "w"))) { fputs (buffer_ds, f); fclose (f); } free (buffer_ds); buffer_ds = NULL; } if (buffer_ps) { if ((f = fopen ("/tmp/bootchart.einit/proc_ps.log", "w"))) { fputs (buffer_ps, f); fclose (f); } free (buffer_ps); buffer_ps = NULL; } if (buffer_st) { if ((f = fopen ("/tmp/bootchart.einit/proc_stat.log", "w"))) { fputs (buffer_st, f); fclose (f); } free (buffer_st); buffer_st = NULL; } if (linux_bootchart_process_accounting) { char *r = readfile ("/dev/kernel_pacct"); if (r) { if ((f = fopen ("/tmp/bootchart.einit/kernel_pacct", "w"))) { fputs (r, f); fclose (f); } unlink ("/dev/kernel_pacct"); } acct(NULL); } if ((f = fopen ("/tmp/bootchart.einit/header", "w"))) { char *t, buffer[BUFFERSIZE]; time_t ti = time(NULL); /* we're emulating bootchartd-0.8/0.9's format... */ eputs ("version = 0.8\n", f); if (gethostname (buffer, BUFFERSIZE) == 0) { eprintf (f, "title = eINIT Boot Chart for %s, %s", buffer, ctime(&ti)); } else { eprintf (f, "title = eINIT Boot Chart, %s", ctime(&ti)); } fprintf (f, "system.uname = %s %s %s %s\n", osinfo.sysname, osinfo.release, osinfo.version, osinfo.machine); if ((t = readfile ("/etc/gentoo-release"))) { strtrim (t); eprintf (f, "system.release = %s\n", t); free (t); } else { eputs ("system.release = unknown\n", f); } if ((t = readfile ("/proc/cpuinfo"))) { char **r = str2set ('\n', t); char *n = NULL; int i; if (r) { for (i = 0; r[i]; i++) { if (strstr (r[i], "model name") == r[i]) { n = r[i]; break; } } if (n) eprintf (f, "system.cpu = %s\n", n); else eputs ("system.cpu = unknown\n", f); } free (t); } else { eputs ("system.cpu = unknown\n", f); } if ((t = readfile ("/proc/cmdline"))) { eprintf (f, "system.kernel.options = %s\n", t); free (t); } fclose (f); } char buffer[BUFFERSIZE]; if (coremode & einit_mode_sandbox) { esprintf (buffer, BUFFERSIZE, "export pwx=`pwd`; cd /tmp/bootchart.einit; tar czf \"${pwx}/%s\" *", save_to); } else { esprintf (buffer, BUFFERSIZE, "cd /tmp/bootchart.einit; tar czf %s *", save_to); } system (buffer); unlink_recursive ("/tmp/bootchart.einit/", 1); char *di = cfg_getstring ("configuration-bootchart-chart-directory", NULL); char *fo = cfg_getstring ("configuration-bootchart-chart-format", NULL); esprintf (buffer, BUFFERSIZE, "bootchart -o %s -f %s %s", di, fo, save_to); return NULL; }