int main() { char **value; int valnum; int i; void *cfgdata; cfgdata = init_conf(); if(load_conf(cfgdata,"../../etc/dp.conf") < 0) { printf("load configuration file failure.\n"); return -1; } const char *weekday[] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"}; printf("[test] int: %d\n",getconfint(cfgdata,"test","int",0,1,2,6)); printf("[test] float: %.2f\n",getconfloat(cfgdata,"test","float",0,1.0,1.0,999.99)); printf("[test] string: %s\n",getconfstring(cfgdata,"test","string",0,"not fount",weekday,NULL,7,NULL)); printf("[test] multi-value: \n"); getconfmulti(cfgdata,"test","multi",0,"not found"," ",&value,&valnum); for(i=0;i<valnum;i++) printf("%s ",value[i]); printf("\n"); free_conf(cfgdata); }
int load_conf_ip_hash_mmap_connect() { if (load_conf() == -1) //读取配置 return -1; if (build_dir() == -1) //创建cdn测速的待发文件目录,idc和cdn的mmap文件所在目录 return -1; if (load_ip() == -1) //读入ip库 return -1; if (load_hash() == -1) //创建hash表,用以记录mmap中每一条记录在mmap中的偏移 return -1; if (load_mmap() == -1) //创建mmap文件 return -1; if (load_linkip(link_ip_config_file) == -1) return -1; DEBUG_LOG("GET from ip:ip_ready\t:[%u]",idc_test_ip_mmap.ready_num); DEBUG_LOG("GET from area:area_ready\t:[%u]",idc_test_area_mmap.ready_num); set_hash_for_area_mmap();//从ip库中读出每一条"省市运营商"记录,写入mmap,并相应建立area的hash表 int data; backup_mmap_file(0, &data); if (connect_2_dbserver() == -1) return 0; return 0; }
void sj_init_conf(struct v7 *v7, char *conf_str) { int i; const char *names[] = {"sys.json", "user.json"}; v7_val_t conf = v7_create_object(v7); v7_set(v7, v7_get_global_object(v7), "conf", ~0, 0, conf); if (conf_str != NULL) { v7_val_t res; enum v7_err err; /* * Usage of strlen in weird here * but we use snprintf as well. * TODO(alashkin): think about providing len * as function argument AND changing of snprintf to * something else */ size_t len = strlen(conf_str); char *f = (char *) malloc(len + 3); snprintf(f, len + 3, "(%s)", conf_str); /* TODO(mkm): simplify when we'll have a C json parse API */ err = v7_exec(v7, &res, f); free(f); if (err != V7_OK) { printf("exc parsing dev conf: %s\n", f); v7_println(v7, res); } else { v7_set(v7, conf, "dev", ~0, 0, res); } } for (i = 0; i < (int) sizeof(names) / sizeof(names[0]); i++) { const char *name = names[i]; v7_set(v7, conf, name, strlen(name) - 5, 0, load_conf(v7, name)); } }
int main(int argc, char **argv) { /* I18n */ setlocale(LC_ALL, ""); #if ENABLE_NLS bindtextdomain(PACKAGE, LOCALEDIR); textdomain(PACKAGE); #endif abrt_init(argv); const char *dump_dir_name = "."; const char *conf_filename = NULL; const char *chroot = NULL; /* Can't keep these strings/structs static: _() doesn't support that */ const char *program_usage_string = _( "& [-v] [-c CONFFILE] [-r CHROOT] -d DIR\n" "\n" "Query package database and save package and component name" ); enum { OPT_v = 1 << 0, OPT_d = 1 << 1, OPT_c = 1 << 2, OPT_r = 1 << 2, }; /* Keep enum above and order of options below in sync! */ struct options program_options[] = { OPT__VERBOSE(&g_verbose), OPT_STRING('d', NULL, &dump_dir_name, "DIR" , _("Problem directory")), OPT_STRING('c', NULL, &conf_filename, "CONFFILE", _("Configuration file")), OPT_STRING('r', "chroot", &chroot, "CHROOT" , _("Use this directory as RPM root")), OPT_END() }; /*unsigned opts =*/ parse_opts(argc, argv, program_options, program_usage_string); export_abrt_envvars(0); log_notice("Loading settings"); if (load_conf(conf_filename) != 0) return 1; /* syntax error (logged already by load_conf) */ log_notice("Initializing rpm library"); rpm_init(); GList *li; for (li = settings_setOpenGPGPublicKeys; li != NULL; li = g_list_next(li)) { log_notice("Loading GPG key '%s'", (char*)li->data); rpm_load_gpgkey((char*)li->data); } int r = SavePackageDescriptionToDebugDump(dump_dir_name, chroot); /* Close RPM database */ rpm_destroy(); return r; }
static gboolean plugin_load(PurplePlugin *plugin) { FILE *which_pf; char line[1024]; which_pf= popen("which festival 2>/dev/null","r"); fscanf(which_pf,"%1023s",line); pclose(which_pf); if( *line != '/') return FALSE; char proc[1024]; sprintf(proc, "%s %s", snd((char *)purple_prefs_get_string("/pidgin/sound/method")), line); purple_debug(PURPLE_DEBUG_INFO, "pidgin festival", proc); int errno=0; festival_pf= popen(proc,"w"); if(errno) { pclose(festival_pf); return FALSE; } load_conf(); void *conv_handle = purple_conversations_get_handle(); void *blist_handle = purple_blist_get_handle(); void *accounts_handle = purple_accounts_get_handle(); purple_signal_connect(conv_handle, "received-im-msg", plugin, PURPLE_CALLBACK(im_recv_im), NULL); purple_signal_connect(conv_handle, "received-chat-msg", plugin, PURPLE_CALLBACK(im_recv_im), NULL); purple_signal_connect(conv_handle, "conversation-created", plugin, PURPLE_CALLBACK(chat_created), NULL); purple_signal_connect(blist_handle, "buddy-signed-on", plugin, PURPLE_CALLBACK(buddy_signed_on_cb), NULL); purple_signal_connect(blist_handle, "buddy-signed-off", plugin, PURPLE_CALLBACK(buddy_signed_off_cb), NULL); purple_signal_connect(conv_handle, "chat-buddy-joined", plugin, PURPLE_CALLBACK(chat_buddy_joined_cb), NULL); purple_signal_connect(conv_handle, "chat-buddy-left", plugin, PURPLE_CALLBACK(chat_buddy_left_cb), NULL); /* Buddy List subsystem signals */ purple_signal_connect(blist_handle, "buddy-away", plugin, PURPLE_CALLBACK(buddy_away_cb), NULL); purple_signal_connect(blist_handle, "buddy-back", plugin, PURPLE_CALLBACK(buddy_back_cb), NULL); purple_signal_connect(blist_handle, "buddy-idle", plugin, PURPLE_CALLBACK(buddy_idle_cb), NULL); purple_signal_connect(blist_handle, "buddy-unidle", plugin, PURPLE_CALLBACK(buddy_unidle_cb), NULL); purple_signal_connect(accounts_handle, "account-connecting", plugin, PURPLE_CALLBACK(account_connecting_cb), NULL); return TRUE; }
/* Main Routine */ int main_construct(FILE *log, dictionary *conf, int listenfd) { int connfd = 0; struct sockaddr_in serv_addr; char sendBuff[140]; //Start main loop while(1) { //If data is recieved - run mysql_status and write result to socket connfd = accept(listenfd, (struct sockaddr*)NULL, NULL); if (connfd != -1) { char *message = "HTTP/1.1 503 Service Unavailable\r\nContent-Type: text/plain\r\nConnection: close\r\nContent-Length: 44\r\n\r\nMariaDB Cluster Node is not synced.\r\n"; char *status = mysql_status(conf, log); if (strncmp("4", status, 1024) == 0) { message = "HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nConnection: close\r\nContent-Length: 40\r\n\r\nMariaDB Cluster Node is synced.\r\n"; } snprintf(sendBuff, sizeof(sendBuff), "%s\r\n", message); write(connfd, sendBuff, strlen(sendBuff)); } //Signal Actions if (sig_flag == 4) { put_log(log, "INFO - Shutting down HAwk..."); put_log(log, "INFO - Releasing Socket"); close(listenfd); //Freeing configuration dictionary iniparser_freedict(conf); put_log(log, "INFO - Closing Log Files"); fflush(log); fclose(log); close(connfd); break; } if (sig_flag == 6) { put_log(log, "INFO - Received HUP. Reloading..."); fflush(log); fclose(log); close(connfd); log = open_logs(); put_log(log, "INFO - Successfully reloaded logs"); //free(conf); iniparser_freedict(conf); conf = load_conf(); sig_flag = 0; } close(connfd); sleep(1); } return 0; }
static void parse_options(struct poclidek_ctx *cctx, struct poldek_ts *ts, int argc, char **argv, int mode) { struct argp argp = { common_options, parse_opt, args_doc, poldek_BANNER, 0, 0, 0}; int n, i, index, hide_child_opts = 0; struct argp_child *child; args_init(cctx, ts, argc, argv, mode); n = 0; while (poclidek_opgroup_tab[n]) n++; child = alloca((n + 2) * sizeof(*child)); args.opgroup_rts = n_array_new(n, NULL, NULL); for (i=0; i < n; i++) { struct poclidek_opgroup_rt *rt; child[i] = *(poclidek_opgroup_tab[i]->argp_child); rt = poclidek_opgroup_rt_new(args.ts, args.opctx); rt->run = poclidek_opgroup_tab[i]->run; n_array_push(args.opgroup_rts, rt); } child[i].argp = NULL; argp.children = child; if (poclidek_argv_is_help(argc, (const char **)argv)) hide_child_opts = 1; #if GENDOCBOOK hide_child_opts = 1; #endif argp_prepare_child_options(&argp, hide_child_opts); poldek_set_verbose(0); index = 0; argp_parse(&argp, argc, argv, ARGP_IN_ORDER, &index, &args); if (!poclidek_op_ctx_verify_major_mode(args.opctx)) exit(EXIT_FAILURE); if (!load_conf(&args)) exit(EXIT_FAILURE); #if GENDOCBOOK if (args.cnflags & OPT_AS_FLAG(OPT_DOCB)) { argp_as_docbook(&argp); exit(EXIT_SUCCESS); } #endif return; }
bool log_initializer::reload_conf() { if(conf_file==""){ LOG4CXX_ERROR(user_logger,"unable reload log configuration file, load_conf first"); return false; } reset(); load_conf(conf_file); return true; }
int configure(int argc, char **argv){ parse_cmdline(argc, argv); if(conf.help){ display_help(); return 1; } if(conf.version) display_version(); if(strcmp(conf.confile, "")!=0 && load_conf(conf.confile)) return 1; if(conf.config) show_config(); }
static void initsh(t_lexlist **list, t_list **histo, t_sllist **myenv) { *list = NULL; *histo = get_hist_from_file(HISTORY_FILE, myenv); if (!*histo) *histo = init_history(); update_alias(1, NULL); load_conf(myenv); auto_comp(NULL, NULL, 0, *myenv); update_history(*histo); }
int main(int argc, char** argv){ load_conf(argv[1]); //Initialisiere Felder vector<vector<double> > u_0; vector<vector<double> > v_0; vector<vector<double> > T; init_u(u_0, v_0); init_T(T); //Erstelle den Temperaturvektor std::vector<double> T_Vec = reshape_vector(T); //Berechne die BTCS-Matrix std::vector<std::vector<double> > M = BCTS_implicit_Matrix(u_0,v_0); //Berechne die untere Dreiecksmatrix std::vector<std::vector<double> > LD = triangularize(M); //Integration long int t_start;//TIME LOG time(&t_start); cout << "W = " << omega<< endl; int i_t = 0;//Zähler für die Snapshots for(int n=0; n*dt<t_fin; n++){ //Füge Dirichlet-Randbedingungen in den Vektor ein impose_dirichlet(T_Vec,u_0,v_0); //Löse das Gleichungssystem SOR(T_Vec,M,LD, omega, r_end); //Snapshots if( (n+1)*dt >= t_snap[i_t] && (n+1)*dt<t_snap[i_t+1]){ ostringstream snap_name; snap_name <<dirname<< (n+1)*dt << "_" << Pe << "_"<< Nx<<"_"<<Ny<<"_"<<dt<<"_"<<b_Q<<".txt"; save_data(shape_back(T_Vec, T_unten,T_oben), snap_name.str().c_str()); } if((n+1)*dt>=t_snap[i_t]){ i_t+=1; } } cout<<endl; T=shape_back(T_Vec, T_unten, T_oben); //TIME LOG long int t_finished; time(&t_finished); cout << "\n\n"<< t_finished-t_start<<endl; //print_array(T); save_data(T,"aktuell.txt"); return 0; }
int main (int argc, char *argv[]) { gk_conf_t gc; char strurl[512] = {0}; struct stat st; time_t s_tm,e_tm, now; char * fname, * url; srand((unsigned) time(NULL)); if(an_args(argc, argv, &gc)) { return 0; } if(load_conf(&gc)) { return 0; } if (gk_action_list[gc.action].act_func) { return gk_action_list[gc.action].act_func(&gc); } return 0; }
static void start_daemon(const char *progname, struct a6o_daemon_options *opts) { struct a6o_conf *conf; struct armadito *armadito; int server_sock; struct server *server; a6o_error *error = NULL; GMainLoop *loop; loop = g_main_loop_new(NULL, FALSE); log_init(opts->s_log_level, !opts->no_daemon); if (!opts->no_daemon) daemonize(); if (opts->pid_file != NULL) create_pid_file(opts->pid_file); a6o_log(ARMADITO_LOG_SERVICE, ARMADITO_LOG_LEVEL_NONE, "starting %s%s", progname, opts->no_daemon ? "" : " in daemon mode"); conf = a6o_conf_new(); load_conf(conf); load_conf_dir(conf); armadito = a6o_open(conf, &error); if (armadito == NULL) { a6o_error_print(error, stderr); exit(EXIT_FAILURE); } server_sock = create_server_socket(opts); server = server_new(armadito, server_sock, opts->ipc_type); g_main_loop_run(loop); }
int main() { load_conf(); sig_init(); if( (dbgfd = cap_openfile(capg.save_dbg, CAP_TMP_CAMID, capg.save_dbg_name)) < 0) dbgfd = STDERR_FILENO; // main capture thread, capture/encode/send video data if(capg.mock_enable) Pthread_create(&mock_tid, NULL, mock_main, NULL); else Pthread_create(&cap_tid, NULL, cap_main, NULL); // for communication, listen other process's command Pthread_create(&comm_tid, NULL, comm_main, NULL); // handle signal thread Pthread_create(&sig_tid, NULL, sig_main, NULL); // wait thread over if(capg.mock_enable) Pthread_join(mock_tid, NULL); else Pthread_join(cap_tid, NULL); Pthread_join(comm_tid, NULL); Pthread_join(sig_tid, NULL); cap_closefile(capg.save_dbg, dbgfd); return 0; }
int main(int argc, char *argv[]) { int ret; int id; int op; struct sender_t *sender; char cfg[PATH_MAX]; const char * const config_path[2] = { CONFIG_CUSTOMIZE, CONFIG_INSTALL }; const struct option opts[] = { { "config", required_argument, NULL, 'c' }, { "help", no_argument, NULL, 'h' }, { "version", no_argument, NULL, 'V' }, { NULL, 0, NULL, 0 } }; cfg[0] = 0; while ((op = getopt_long(argc, argv, "c:hV", opts, NULL)) != -1) { switch (op) { case 'c': strncpy(cfg, optarg, PATH_MAX); break; case 'h': usage(); return 0; case 'V': printf("version is %d.%d-%s, build by %s@%s\n", AP_MAJOR_VERSION, AP_MINOR_VERSION, AP_BUILD_VERSION, AP_BUILD_USER, AP_BUILD_TIME); return 0; case '?': usage(); return -1; } } if (!cfg[0]) { if (file_exists(config_path[0])) strncpy(cfg, config_path[0], PATH_MAX); else strncpy(cfg, config_path[1], PATH_MAX); } cfg[PATH_MAX - 1] = 0; ret = load_conf(cfg); if (ret) return -1; init_crash_reclassify(); ret = init_sender(); if (ret) return -1; init_event_queue(); ret = init_event_handler(); if (ret) return -1; ret = init_channels(); if (ret) return -1; while (1) { for_each_sender(id, sender, conf) { if (!sender) continue; uptime(sender); } } return 0; }
int main(int argc, char* argv[]) { int ret = 0; char c = 0; bzero(&g_conf, sizeof(g_conf)); ret = init_log(argv[0]); while ((c = getopt(argc, argv, "f:d:i:m:hv")) != -1) { switch (c) { case 'd': snprintf(g_conf.conf_path, gbdt::GBDT_MAX_PATH_LEN, "%s", optarg); g_conf.conf_path[gbdt::GBDT_MAX_PATH_LEN-1] = '\0'; break; case 'f': snprintf(g_conf.conf_file, gbdt::GBDT_MAX_PATH_LEN, "%s", optarg); g_conf.conf_file[gbdt::GBDT_MAX_PATH_LEN-1] = '\0'; break; case 'i': snprintf(g_conf.input_file, gbdt::GBDT_MAX_PATH_LEN, "%s", optarg); g_conf.input_file[gbdt::GBDT_MAX_PATH_LEN-1] = '\0'; break; case 'm': snprintf(g_conf.model_file, gbdt::GBDT_MAX_PATH_LEN, "%s", optarg); g_conf.model_file[gbdt::GBDT_MAX_PATH_LEN-1] = '\0'; break; case 'h': case 'v': case '?': show_usage(argv[0]); return 1; } } if (g_conf.conf_path[0] == 0 || g_conf.conf_file[0] == 0 || g_conf.input_file[0] == 0 || g_conf.model_file[0] == 0) { show_usage(argv[0]); return 1; } ret = load_conf(g_conf.conf_path, g_conf.conf_file); if (ret != 0) { return ret; } gbdt::GBDT gbdt; ret = gbdt.init(g_conf.conf_path, g_conf.conf_file); if (ret != 0) { LOG(WARNING) << "fail to init gbdt"; return ret; } ret = gbdt.load(g_conf.model_file); if (ret != 0) { LOG(WARNING) << "fail to load model from " << g_conf.model_file; return ret; } ret = gbdt.test(g_conf.input_file); if (ret != 0) { LOG(WARNING) << "fail to read gbdt using file " << g_conf.input_file; return ret; } return 0; }
/** * @brief main The entrance of zimg. * * @param argc Count of args. * @param argv Arg list. * * @return It returns a int to system. */ int main(int argc, char **argv) { /* Set signal handlers */ sigset_t sigset; sigemptyset(&sigset); struct sigaction siginfo = { .sa_sigaction = &sighandler, .sa_mask = sigset, .sa_flags = SA_RESTART, }; sigaction(SIGINT, &siginfo, NULL); sigaction(SIGTERM, &siginfo, NULL); if (argc < 2) { usage(argc, argv); return -1; } settings_init(); int i; for (i = 1; i < argc; i++) { if (strcmp(argv[i], "-d") == 0) { settings.is_daemon = 1; } else { conf_file = argv[i]; } } if (conf_file == NULL) { usage(argc, argv); return -1; } if (is_file(conf_file) == -1) { fprintf(stderr, "'%s' is not a file or not exists!\n", conf_file); return -1; } if (load_conf(conf_file) == -1) { fprintf(stderr, "'%s' load failed!\n", conf_file); return -1; } if (bind_check(settings.port) == -1) { fprintf(stderr, "Port %d bind failed!\n", settings.port); return -1; } if (settings.is_daemon == 1) { if (daemon(1, 1) < 0) { fprintf(stderr, "Create daemon failed!\n"); return -1; } else { fprintf(stdout, "zimg %s\n", settings.version); fprintf(stdout, "Copyright (c) 2013-2014 zimg.buaa.us\n"); fprintf(stderr, "\n"); } } //init the Path zimg need to use. //start log module... ./log/zimg.log if (mk_dirf(settings.log_name) != 1) { fprintf(stderr, "%s log path create failed!\n", settings.log_name); return -1; } log_init(); if (settings.script_name[0] != '\0') { if (is_file(settings.script_name) == -1) { fprintf(stderr, "%s open failed!\n", settings.script_name); return -1; } settings.script_on = 1; } if (is_dir(settings.img_path) != 1) { if (mk_dirs(settings.img_path) != 1) { LOG_PRINT(LOG_DEBUG, "img_path[%s] Create Failed!", settings.img_path); fprintf(stderr, "%s Create Failed!\n", settings.img_path); return -1; } } LOG_PRINT(LOG_DEBUG, "Paths Init Finished."); if (settings.mode == 2) { LOG_PRINT(LOG_DEBUG, "Begin to Test Memcached Connection..."); memcached_st *beans = memcached_create(NULL); char mserver[32]; snprintf(mserver, 32, "%s:%d", settings.beansdb_ip, settings.beansdb_port); memcached_server_st *servers = memcached_servers_parse(mserver); servers = memcached_servers_parse(mserver); memcached_server_push(beans, servers); memcached_server_list_free(servers); memcached_behavior_set(beans, MEMCACHED_BEHAVIOR_BINARY_PROTOCOL, 0); memcached_behavior_set(beans, MEMCACHED_BEHAVIOR_NO_BLOCK, 1); memcached_behavior_set(beans, MEMCACHED_BEHAVIOR_TCP_KEEPALIVE, 1); LOG_PRINT(LOG_DEBUG, "beansdb Connection Init Finished."); if (set_cache(beans, "zimg", "1") == -1) { LOG_PRINT(LOG_DEBUG, "Beansdb[%s] Connect Failed!", mserver); fprintf(stderr, "Beansdb[%s] Connect Failed!\n", mserver); memcached_free(beans); return -1; } else { LOG_PRINT(LOG_DEBUG, "beansdb connected to: %s", mserver); } memcached_free(beans); } else if (settings.mode == 3) { redisContext* c = redisConnect(settings.ssdb_ip, settings.ssdb_port); if (c->err) { redisFree(c); LOG_PRINT(LOG_DEBUG, "Connect to ssdb server faile"); fprintf(stderr, "SSDB[%s:%d] Connect Failed!\n", settings.ssdb_ip, settings.ssdb_port); return -1; } else { LOG_PRINT(LOG_DEBUG, "Connect to ssdb server Success"); } } //init magickwand MagickCoreGenesis((char *) NULL, MagickFalse); /* ExceptionInfo *exception=AcquireExceptionInfo(); MagickInfo *jpeg_info = (MagickInfo *)GetMagickInfo("JPEG", exception); if(jpeg_info->thread_support != MagickTrue) LOG_PRINT(LOG_DEBUG, "thread_support != MagickTrue"); jpeg_info->thread_support = MagickTrue; if(jpeg_info->thread_support != MagickTrue) LOG_PRINT(LOG_DEBUG, "thread_support != MagickTrue"); MagickInfo *jpg_info = (MagickInfo *)GetMagickInfo("JPG", exception); jpg_info->thread_support = MagickTrue; */ int result = pthread_key_create(&gLuaStateKey, thread_lua_dtor); if (result != 0) { LOG_PRINT(LOG_ERROR, "Could not allocate TLS key for lua_State."); } //begin to start httpd... LOG_PRINT(LOG_DEBUG, "Begin to Start Httpd Server..."); LOG_PRINT(LOG_INFO, "zimg started"); evbase = event_base_new(); evhtp_t *htp = evhtp_new(evbase, NULL); evhtp_set_cb(htp, "/dump", dump_request_cb, NULL); evhtp_set_cb(htp, "/upload", post_request_cb, NULL); evhtp_set_cb(htp, "/admin", admin_request_cb, NULL); evhtp_set_cb(htp, "/info", info_request_cb, NULL); evhtp_set_cb(htp, "/echo", echo_cb, NULL); evhtp_set_gencb(htp, get_request_cb, NULL); #ifndef EVHTP_DISABLE_EVTHR evhtp_use_threads(htp, init_thread, settings.num_threads, NULL); #endif evhtp_set_max_keepalive_requests(htp, settings.max_keepalives); evhtp_bind_socket(htp, settings.ip, settings.port, settings.backlog); event_base_loop(evbase, 0); evhtp_unbind_socket(htp); //evhtp_free(htp); event_base_free(evbase); free_headers_conf(settings.headers); free_access_conf(settings.up_access); free_access_conf(settings.down_access); free_access_conf(settings.admin_access); free(settings.mp_set); return 0; }
int main(void) { pid_t pid, sid; //Fork off the parent process pid = fork(); if (pid < 0) { exit(EXIT_FAILURE); } //If we got a good PID, then we can exit the parent process if (pid > 0) { exit(EXIT_SUCCESS); } //Change the file mode mask umask(0); //Load Configuration File dictionary *conf = load_conf(); //Opening Log FILE *log = open_logs(); //Query for UID/GID uid_t id = getid_byName(get_config(conf, "hawk:daemon_user")); //Set UID if (setuid(id) != 0) { put_log(log, "FATAL - Could not set UID for daemon"); exit(1); } //Create a new SID for the child process sid = setsid(); if (sid < 0) { put_log(log, "FATAL - Session ID was not set properly"); exit(EXIT_FAILURE); } //Write PID file if(strcmp(get_config(conf, "hawk:pid_path"),"") > 0) { FILE *pidfile; pidfile = fopen(get_config(conf, "hawk:pid_path"), "w"); fprintf(pidfile, "%d", getpid()); fflush(pidfile); } //Initialize Socket int listenfd = socket_init(conf); //Close out the standard file descriptors fflush(stdin); fflush(stdout); fflush(stderr); close(STDIN_FILENO); close(STDOUT_FILENO); close(STDERR_FILENO); signal(SIGHUP, signal_handler); signal(SIGTERM, signal_handler); //Begin main routine put_log(log, "INFO - Starting HAwk..."); main_construct(log, conf, listenfd); return 0; }
//simple demo: int main (int argc, char *argv[]) { //issue printf("\n -=[ Hello, and welcome to RollCageX version %s ]=-\n\n%s\n", VERSION, ISSUE); //end if (argc != 1) printf("(Passing arguments - not supported)\n\n"); //check if program was called with another pwd (got '/' in "name") if (char *s = strrchr(argv[0], '/')) { *s='\0'; //modify string to end at last slash printf("(changing pwd: %s)\n", argv[0]); chdir (argv[0]); } printlog(0, "Loading...\n"); load_conf ("data/internal.conf", (char *)&internal, internal_index); if (!graphics_init()) return -1; //TODO: there should be menus here, but menu/osd system is not implemented yet... also: //on failure, rcx should not just terminate but instead abort the race and warn the user //MENU: welcome to rcx, please select profile or create a new profile Profile *prof = Profile_Load ("data/profiles/default"); if (!prof) return -1; //GOTO: profile menu if (!physics_init()) { //menu: warn and quit! graphics_quit(); return -1; } //MENU: select race type // - assuming 2P free roam - //MENU: P1: select theme/car Car_Template *venom_template = Car_Template::Load("data/teams/Nemesis/cars/Venom"); if (!venom_template) return -1; //GOTO: car selection menu //MENU: P2: select theme/car Car_Template *reaper_template = Car_Template::Load("data/teams/Vostok/cars/Reaper"); if (!reaper_template) return -1; //GOTO: car selection //MENU: select world/track if (!load_track((char *)"data/worlds/Sandbox/tracks/Box")) return -1; //GOTO: track selection menu //TMP: load box for online spawning box = Object_Template::Load("data/objects/misc/box"); sphere = Object_Template::Load("data/objects/misc/sphere"); funbox = Object_Template::Load("data/objects/misc/funbox"); if (!box || !sphere || !funbox) return -1; //spawn car Venom = venom_template->Spawn(track.start[0]-4, track.start[1], track.start[2]); prof->car = Venom; camera.car = Venom; //lets spawn another car: Reaper = reaper_template->Spawn(track.start[0]+4, track.start[1], track.start[2]); //MENU: race configured, start? start_race(); //race done, remove all objects... Object::Destroy_All(); //MENU: race done, replay, play again, quit? // - assuming quit - //remove loaded data (not all data, only "racetime" - for this race) Racetime_Data::Destroy_All(); //MENU: back to main menu here // - assuming player wants to log out - physics_quit(); Profile_Remove_All(); //should only be one active profile right now, but any case, remove all //MENU: select profile // - assumes player wants to quit - graphics_quit(); //some basic info (until menu for printing it) print_info(); printf("\nBye!\n\n"); return 0; }
int main(int argc, char** argv) { string_map* parameters = parse_parameters(argc, argv); opkg_conf *conf = load_conf((char*)get_string_map_element(parameters, "config")); char* run_type = get_string_map_element(parameters, "run-type"); int force_overwrite_other_files = get_string_map_element(parameters, "force-overwrite") != NULL ? 1 : 0; int force_overwrite_configs = get_string_map_element(parameters, "force-overwrite-configs") != NULL ? 1 : 0; int force_depends = get_string_map_element(parameters, "force-depends") != NULL ? 1 : 0; int force_reinstall = get_string_map_element(parameters, "force-reinstall") != NULL ? 1 : 0; int remove_orphaned_depends = get_string_map_element(parameters, "autoremove") != NULL ? REMOVE_ALL_ORPHANED_DEPENDENCIES : REMOVE_NO_ORPHANED_DEPENDENCIES; remove_orphaned_depends = get_string_map_element(parameters, "autoremove-same-destination") != NULL ? REMOVE_ORPHANED_DEPENDENCIES_IN_SAME_DEST : remove_orphaned_depends; char* install_root = get_string_map_element(parameters, "install-destination"); install_root = install_root == NULL ? strdup("root") : install_root; char* link_root = get_string_map_element(parameters, "link-destination"); char* tmp_root = get_string_map_element(parameters, "tmp_dir"); tmp_root = tmp_root == NULL ? strdup("/tmp") : tmp_root; string_map* pkgs = get_string_map_element(parameters, "package-list"); char* format_str = get_string_map_element(parameters, "output-format"); int format = OUTPUT_HUMAN_READABLE; if(format_str != NULL) { format = strcmp(format_str, "json") == 0 ? OUTPUT_JSON : format; format = strcmp(format_str, "js") == 0 || strcmp(format_str, "javascript") == 0 ? OUTPUT_JAVASCRIPT : format; } if(strcmp(run_type, "install") == 0) { do_install(conf, pkgs, install_root, link_root, 0, force_overwrite_configs, force_overwrite_other_files, force_reinstall, tmp_root); } else if(strcmp(run_type, "remove") == 0) { do_remove(conf, pkgs, !force_overwrite_configs, remove_orphaned_depends, force_depends, 1); } else if(strcmp(run_type, "upgrade") == 0) { do_upgrade(conf, pkgs, !force_overwrite_configs, install_root, link_root); } else if(strcmp(run_type, "update") == 0) { update(conf); } else if((strcmp(run_type, "list") == 0) || strcmp(run_type, "list-installed") == 0 || strcmp(run_type, "list_installed") == 0) { do_list(conf, parameters, format); } else if(strcmp(run_type, "dest-info") == 0 || strcmp(run_type, "dest_info") == 0) { do_print_dest_info(conf, format); } else if(strcmp(run_type, "info") == 0) { do_print_info(conf, parameters, install_root, format); } return(0); }
//simple demo: int main (int argc, char *argv[]) { //issue printf("\n -=[ Hello, and welcome to RollCageX version %s ]=-\n\n", VERSION); printf(" Copyright (C) 2009, This program comes with ABSOLUTELY NO WARRANTY; see\n \"license.txt\" for details\n\n"); printf(" This is free software, and you are welcome to redistribute it and/or modify\n it under the GNU General Public License as published by the Free Software\n Foundation, version 3 or (at your option) later\n\n"); printf("= Credits (nicknames refers to usernames on the gorcx.net forum):\n"); printf(" \"MaAkaJon\"\t\tproject creator\n"); printf(" \"Soul Slinger\"\tcoder (created this and the earlier versions)\n"); printf(" All of you on the planetrollcage.com and gorcx.net forums!\n\n"); printf("* Projects that made RCX possible:\n"); printf(" GNU\t\t\t\tdefines computer freedom itself... :-)\n"); printf(" Simple DirectMedia Layer\twindow handling, input/outputs\n"); printf(" Open Dynamics Engine\trigid body dynamics\n"); printf("= End of credits\n\n"); printf(" Default controls (can be changed in profile):\n"); printf(" > Arrow keys: Steering and throttling\n"); printf(" > Spacebar: Drifting break\n"); printf(" > Left Alt: Soft breaks\n"); printf(" > Q and E: change camera distance along Z axis\n"); printf(" > A and D: change camera distance along X axis\n"); printf(" > W and S: change camera distance along Y axis\n"); printf(" > F1 to F4: change camera settings\n"); printf(" > F5: spawn box\n"); printf(" > F6: spawn box (10s above ground)\n\n"); //end of issue if (argc != 1) printf("(Passing arguments - not supported)\n\n"); //printlog needs internal.verbosity, set it to default value printf("(verbosity level is assumed \"1\" until read from internal conf)\n"); internal.verbosity = 1; //check if program was called with another pwd (got '/' in "name") int count; for (count = strlen(argv[0]); count != -1; --count) if (argv[0][count] == '/') { char pwd[count+2]; //1 for \0 and 1 for [0] strncpy (pwd, argv[0], count+1); pwd[count+1] = '\0'; printf ("(changing pwd: %s)\n", pwd); chdir (pwd); break; } if (load_conf ((char *)"data/internal.conf", (char *)&internal, internal_index)) return -1; if (graphics_init()) return -1; //<insert menu here> profile *prof = load_profile ((char *)"data/profiles/default"); if (!prof) return -1; venom = load_car((char *)"data/teams/Nemesis/cars/Venom"); if (!venom) emergency_quit(); prof->car = venom; camera.car = venom; //menu done, race selected, starting race... if (physics_init()) { graphics_quit(); return -1; } if (load_track((char *)"data/worlds/Sandbox/tracks/Box")) emergency_quit(); //load box for online spawning box = load_object((char *)"data/objects/misc/box"); sphere = load_object((char *)"data/objects/misc/sphere"); if (!box) emergency_quit(); spawn_car (venom, track.start[0], track.start[1], track.start[2]); focused_car = venom; //single-thread function //WARNING: Don't run the game constantly for more than around 49 days! //(or the realtime will wrap, and the timing solution will go crazy) Uint32 simtime = SDL_GetTicks(); //set simulated time to realtime Uint32 realtime; //real time (with possible delay since last update) Uint32 stepsize_ms = internal.stepsize*1000+0.0001; //calculate stepsize from s to ms (append 0.0001 for correct conversion) printlog (0, "\n-> Starting Race\n"); runlevel = running; while (runlevel == running) { event_step(stepsize_ms); //always check for events physics_step(); simtime += stepsize_ms; //if realtime is larger than simtime (and graphics threshold) if (SDL_GetTicks()+internal.threshold > simtime) { printlog(2, "\nWarning: simtime less than realtime (to low stepsize), dropping frame..\n\n"); ++stepsize_warnings; } else //we got time left to draw frame on { graphics_step(stepsize_ms); realtime = SDL_GetTicks(); if (simtime > realtime) { SDL_Delay (simtime - realtime); } else { printlog(2, "\nWarning: (not sleeping, realtime became to high (to low treshold?))\n"); ++threshold_warnings; } } } printlog(0, "-> Race done!\n"); free_all(); physics_quit(); //race done //<insert menu here> //menu done, quit selected, ending graphics and terminating program graphics_quit(); printlog(0, "\n<-- Some basic info: -->\n"); printlog(0, "(does not interest most people)\n"); printlog(0, "Race time (ms): %i\n", simtime); printlog(0, "Stepsize-to-low (framedrop) warnings: %i\n", stepsize_warnings); printlog(0, "Graphics-threshold-to-low warnings: %i\n", threshold_warnings); printlog(0, "\nBye!\n\n"); return 0; }
int main(int argc, char ** argv) { signal(SIGPIPE, SIG_IGN); signal(SIGTERM, stop_server); signal(SIGINT, stop_server); const char *conf_path = NULL; if (argc < 2) { printf("usage:%s conf_path\n", argv[0]); return -1; } conf_path = argv[1]; if (load_conf(conf_path)) { LOG_ERROR("read %s error", conf_path); return -1; } woo::open_log(g_conf.log_path, g_conf.log_buf_size, g_conf.log_type, g_conf.log_flush_type); p_global_db_company = new GlobalDbCompany(); if(NULL == p_global_db_company){ LOG_ERROR("new global db company is eror!"); return -1; } p_global_db_company->load_config("../conf/global_db_config.ini"); query_handle_data = create_handle_data(g_conf.thread_num); if (! query_handle_data) { LOG_ERROR("create query handle error"); return -1; } time_t now = time(NULL); req_id = now << 32L; /*控制服务*/ control_server = woo::tcp_server_create(); if (! control_server) { LOG_ERROR("create tcp server error"); return -1; } /*查询服务*/ query_server = woo::tcp_server_create(); if (! query_server) { LOG_ERROR("create tcp server error"); return -1; } int ret = 0; ret = woo::tcp_server_open(query_server, g_conf.ip, g_conf.query_port, woo::binary_recv, query_req_handle, query_handle_data, g_conf.thread_num, g_conf.long_conn, g_conf.recv_buf_size, g_conf.send_buf_size, g_conf.recv_to, g_conf.send_to); if (ret) { LOG_ERROR("open query tcp server error"); return -1; } ret = woo::tcp_server_open(control_server, g_conf.ip, g_conf.control_port, woo::binary_recv, control_req_handle, NULL, 1, g_conf.long_conn, g_conf.recv_buf_size, g_conf.send_buf_size, g_conf.recv_to, g_conf.send_to); if (ret) { LOG_ERROR("open update tcp server error"); return -1; } if (woo::tcp_server_run(control_server, true)) { LOG_ERROR("update tcp server run error"); return -1; } if (woo::tcp_server_run(query_server, true)) { LOG_ERROR("query tcp server run error"); return -1; } LOG_TRACE("query server started"); woo::tcp_server_wait(control_server); LOG_TRACE("update server stoped"); woo::tcp_server_wait(query_server); LOG_TRACE("query server stoped"); return 0; }
int musician_init(PGconn **dbh, int coupling, int instrument, int soloist, int musician_id, int play_chords, int genetic) { int res; struct rc_conf_s conf; int *prioargs, priosize; *dbh = NULL; res = priosize = 0; if (load_conf(DEFAULT_RC_PATH, &conf) < 4) { fprintf(stderr, "error while loading configuration (%s)\n", strerror(errno)); return 1; } *dbh = db_connect(conf.db_host, conf.db_name, conf.db_user, conf.db_passwd); if (*dbh == NULL) return -1; /* Check if there is a custom prioargs array for this musician. Otherwise use the one decided by the director */ mfields.custom_prioargs = 0; priosize = get_fixed_prioargs(*dbh, instrument, soloist, &prioargs); if (priosize == 1) { if (prioargs == NULL) { fprintf(stderr, "Error in get fixed prioargs\n"); return -1; } memcpy(mfields.prioargs, prioargs, QUARTER_QUERY_ARGS * sizeof(int)); mfields.custom_prioargs = 1; } else if (priosize != 0) { fprintf(stderr, "Error in get fixed prioargs\n"); return -1; } int i = 0; print_debug("prioargs "); print_debug_array(mfields.prioargs, QUARTER_QUERY_ARGS); mfields.instrument = instrument; mfields.prev_octave = -1; mfields.play_chords = play_chords; if (mfields.octave_min == -1 && mfields.octave_max == -1) { res = get_range(*dbh, instrument, &(mfields.octave_min), &(mfields.octave_max)); } else if (mfields.octave_min == -1 || mfields.octave_max == -1) { fprintf(stderr, "Invalid octave range [%d %d]\n", mfields.octave_min, mfields.octave_max); return -1; } if (res != 0 || (mfields.octave_max - mfields.octave_min) > MIDI_NOCTAVES) { fprintf(stderr, "Invalid octave range [%d %d]\n", mfields.octave_min, mfields.octave_max); return -1; } return 0; }
/** * @brief main The entrance of zimg. * * @param argc Count of args. * @param argv Arg list. * * @return It returns a int to system. */ int main(int argc, char **argv) { int i; retry_sleep.tv_sec = 0; retry_sleep.tv_nsec = RETRY_TIME_WAIT; //1000 ns = 1 us /* Set signal handlers */ sigset_t sigset; sigemptyset(&sigset); struct sigaction siginfo = { .sa_handler = sighandler, .sa_mask = sigset, .sa_flags = SA_RESTART, }; sigaction(SIGINT, &siginfo, NULL); sigaction(SIGTERM, &siginfo, NULL); if(argc < 2) { usage(argc, argv); return -1; } settings_init(); const char *conf_file = NULL; for(i=1; i<argc; i++) { if(strcmp(argv[i], "-d") == 0){ settings.is_daemon = 1; }else{ conf_file = argv[i]; } } if(conf_file == NULL) { usage(argc, argv); return -1; } if(is_file(conf_file) == -1) { fprintf(stderr, "'%s' is not a file or not exists!\n", conf_file); return -1; } if(load_conf(conf_file) == -1) { fprintf(stderr, "'%s' load failed!\n", conf_file); return -1; } if(settings.is_daemon == 1) { if(daemon(1, 1) < 0) { fprintf(stderr, "Create daemon failed!\n"); return -1; } else { fprintf(stdout, "zimg %s\n", settings.version); fprintf(stdout, "Copyright (c) 2013-2014 zimg.buaa.us\n"); fprintf(stderr, "\n"); } } //init the Path zimg need to use. LOG_PRINT(LOG_DEBUG, "Begin to Init the Path zimg Using..."); //start log module... ./log/zimg.log if(settings.log) { const char *log_path = "./log"; if(is_dir(log_path) != 1) { if(mk_dir(log_path) != 1) { LOG_PRINT(LOG_DEBUG, "log_path[%s] Create Failed!", log_path); fprintf(stderr, "log_path[%s] Create Failed!\n", log_path); return -1; } } log_init(); } if(is_dir(settings.img_path) != 1) { if(mk_dir(settings.img_path) != 1) { LOG_PRINT(LOG_DEBUG, "img_path[%s] Create Failed!", settings.img_path); fprintf(stderr, "%s Create Failed!\n", settings.img_path); return -1; } } LOG_PRINT(LOG_DEBUG,"Paths Init Finished."); if(settings.mode == 2) { LOG_PRINT(LOG_DEBUG, "Begin to Test Memcached Connection..."); memcached_st *beans = memcached_create(NULL); char mserver[32]; snprintf(mserver, 32, "%s:%d", settings.beansdb_ip, settings.beansdb_port); memcached_server_st *servers = memcached_servers_parse(mserver); servers = memcached_servers_parse(mserver); memcached_server_push(beans, servers); memcached_server_list_free(servers); memcached_behavior_set(beans, MEMCACHED_BEHAVIOR_BINARY_PROTOCOL, 0); memcached_behavior_set(beans, MEMCACHED_BEHAVIOR_NO_BLOCK, 1); memcached_behavior_set(beans, MEMCACHED_BEHAVIOR_TCP_KEEPALIVE, 1); LOG_PRINT(LOG_DEBUG, "beansdb Connection Init Finished."); if(set_cache(beans, "zimg", "1") == -1) { LOG_PRINT(LOG_DEBUG, "Beansdb[%s] Connect Failed!", mserver); fprintf(stderr, "Beansdb[%s] Connect Failed!\n", mserver); memcached_free(beans); return -1; } else { LOG_PRINT(LOG_DEBUG, "beansdb connected to: %s", mserver); } memcached_free(beans); } else if(settings.mode == 3) { redisContext* c = redisConnect(settings.ssdb_ip, settings.ssdb_port); if(c->err) { redisFree(c); LOG_PRINT(LOG_DEBUG, "Connect to ssdb server faile"); fprintf(stderr, "SSDB[%s:%d] Connect Failed!\n", settings.ssdb_ip, settings.ssdb_port); return -1; } else { LOG_PRINT(LOG_DEBUG, "Connect to ssdb server Success"); } } //init magickwand MagickWandGenesis(); //begin to start httpd... LOG_PRINT(LOG_DEBUG, "Begin to Start Httpd Server..."); LOG_PRINT(LOG_INFO, "zimg started"); evbase = event_base_new(); evhtp_t *htp = evhtp_new(evbase, NULL); evhtp_set_cb(htp, "/dump", dump_request_cb, NULL); evhtp_set_cb(htp, "/upload", post_request_cb, NULL); //evhtp_set_gencb(htp, echo_cb, NULL); evhtp_set_gencb(htp, send_document_cb, NULL); #ifndef EVHTP_DISABLE_EVTHR evhtp_use_threads(htp, init_thread, settings.num_threads, NULL); #endif evhtp_set_max_keepalive_requests(htp, settings.max_keepalives); evhtp_bind_socket(htp, "0.0.0.0", settings.port, settings.backlog); event_base_loop(evbase, 0); evhtp_unbind_socket(htp); evhtp_free(htp); event_base_free(evbase); MagickWandTerminus(); free_access_conf(settings.up_access); free_access_conf(settings.down_access); fprintf(stdout, "\nByebye!\n"); return 0; }
void * logger_init(void *handle, const char *ident, int logopt, int facility) { int res, _res; char *hp; LOG_HANDLE *lhp; if (handle == NULL) { /* parse the config file */ res = load_conf(NULL, "server", NULL, conf_str_array); _res = load_conf(NULL, "server", conf_int_array, NULL); if (res != 0 || _res != 0) { PRINT("ERROR! Can not parse the logger configuration."); return NULL; } if (log_fd != NULL) fclose(log_fd); lhp = (LOG_HANDLE *)malloc(sizeof(LOG_HANDLE)); if (lhp == NULL) { PRINT("logger init failed. not enough memory."); return NULL; } local_handle = lhp; lhp->log_path = log_path; lhp->log_filenameprefix = log_filenameprefix; lhp->log_ident = log_ident; lhp->host_name = host_name; if (strncmp("csflogger", log_method, 1) == 0) { csf_log_method = CSF_LOGGER; /* set the log ident */ memset(log_ident, '\0', MAX_MSG_LEN + 1); strlcpy(log_ident, ident, MAX_MSG_LEN + 1); /* get the current pid */ pid = getpid(); /* get the current host name(not full domain name) */ memset(host_name, '\0', HOST_NAME_MAXLEN + 1); if (gethostname(host_name, HOST_NAME_MAXLEN) == 0 && host_name != NULL) { hp = host_name; while (*hp != '\0') { if (*hp == '.') { *hp = '\0'; break; } hp++; } } else { memmove(host_name, "NULL", 5); } /* get time per file */ switch (log_timeperfile[0]) { case 'm': csf_log_tpf = WLOG_MONTH; break; case 'd': csf_log_tpf = WLOG_DAY; break; case 'h': csf_log_tpf = WLOG_HOUR; break; default : csf_log_tpf = WLOG_HOUR; break; } /* get the log time zone */ if (log_timezone[0] == 'U') { csf_log_timezone = WLOG_UTC; } else { csf_log_timezone = WLOG_LOCAL; } /* point to current logger function */ is_syslog = 0; /* create and open the csf build-in log file */ if (create_logfile() != LOG_CREATE_OK) { PRINT("ERROR! Can not create log file."); return NULL; } } else { /* point to current logger function */ is_syslog = 1; /* open the syslog */ openlog(ident, logopt, facility); } lhp->csf_log_method = csf_log_method; lhp->csf_log_timezone = csf_log_timezone; lhp->csf_log_tpf = csf_log_tpf; lhp->is_syslog = is_syslog; lhp->pid = pid; } else { local_handle = (LOG_HANDLE *)handle; } return local_handle; }
int main(int argc, char *argv[]) { /* * Alloc the global structures * We can access these structs via the macro in ec_globals.h */ globals_alloc(); GBL_PROGRAM = strdup(EC_PROGRAM); GBL_VERSION = strdup(EC_VERSION); SAFE_CALLOC(GBL_DEBUG_FILE, strlen(EC_PROGRAM) + strlen("-") + strlen(EC_VERSION) + strlen("_debug.log") + 1, sizeof(char)); sprintf(GBL_DEBUG_FILE, "%s-%s_debug.log", GBL_PROGRAM, EC_VERSION); DEBUG_INIT(); DEBUG_MSG("main -- here we go !!"); /* initialize the filter mutex */ filter_init_mutex(); /* register the main thread as "init" */ ec_thread_register(EC_PTHREAD_SELF, "init", "initialization phase"); /* activate the signal handler */ signal_handler(); /* ettercap copyright */ fprintf(stdout, "\n" EC_COLOR_BOLD "%s %s" EC_COLOR_END " copyright %s %s\n\n", GBL_PROGRAM, GBL_VERSION, EC_COPYRIGHT, EC_AUTHORS); /* getopt related parsing... */ parse_options(argc, argv); /* check the date */ time_check(); /* load the configuration file */ load_conf(); /* * get the list of available interfaces * * this function will not return if the -I option was * specified on command line. it will instead print the * list and exit */ capture_getifs(); /* initialize the user interface */ ui_init(); /* initialize the network subsystem */ network_init(); /* * always disable the kernel ip forwarding (except when reading from file). * the forwarding will be done by ettercap. */ if(!GBL_OPTIONS->read && !GBL_OPTIONS->unoffensive && !GBL_OPTIONS->only_mitm) { disable_ip_forward(); #ifdef OS_LINUX if (!GBL_OPTIONS->read) disable_interface_offload(); #endif /* binds ports and set redirect for ssl wrapper */ if(GBL_SNIFF->type == SM_UNIFIED && GBL_OPTIONS->ssl_mitm) ssl_wrap_init(); } /* * drop root privileges * we have already opened the sockets with high privileges * we don't need anymore root privs. */ drop_privs(); /***** !! NO PRIVS AFTER THIS POINT !! *****/ /* load all the plugins */ plugin_load_all(); /* print how many dissectors were loaded */ conf_dissectors(); /* load the mac-fingerprints */ manuf_init(); /* load the tcp-fingerprints */ fingerprint_init(); /* load the services names */ services_init(); /* load http known fileds for user/pass */ http_fields_init(); #ifdef HAVE_EC_LUA /* Initialize lua */ ec_lua_init(); #endif /* set the encoding for the UTF-8 visualization */ set_utf8_encoding((u_char*)GBL_CONF->utf8_encoding); /* print all the buffered messages */ if (GBL_UI->type == UI_TEXT) USER_MSG("\n"); ui_msg_flush(MSG_ALL); /**** INITIALIZATION PHASE TERMINATED ****/ /* * we are interested only in the mitm attack i * if entered, this function will not return... */ if (GBL_OPTIONS->only_mitm) only_mitm(); /* create the dispatcher thread */ ec_thread_new("top_half", "dispatching module", &top_half, NULL); /* this thread becomes the UI then displays it */ ec_thread_register(EC_PTHREAD_SELF, GBL_PROGRAM, "the user interface"); ui_start(); /******************************************** * reached only when the UI is shutted down ********************************************/ /* Call all the proper stop methods to ensure * that no matter what UI was selected, everything is * turned off gracefully */ clean_exit(0); return 0; //Never reaches here }
int main(int argc, char **argv) { GOptionContext *context; GMainLoop *loop; GError *error = NULL; FprintManager *manager; DBusGProxy *driver_proxy; guint32 request_name_ret; int r = 0; bindtextdomain (GETTEXT_PACKAGE, LOCALEDIR); bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8"); textdomain (GETTEXT_PACKAGE); context = g_option_context_new ("Fingerprint handler daemon"); g_option_context_add_main_entries (context, entries, GETTEXT_PACKAGE); g_type_init(); if (g_option_context_parse (context, &argc, &argv, &error) == FALSE) { g_print ("couldn't parse command-line options: %s\n", error->message); g_error_free (error); return 1; } if (g_fatal_warnings) { GLogLevelFlags fatal_mask; fatal_mask = g_log_set_always_fatal (G_LOG_FATAL_MASK); fatal_mask |= G_LOG_LEVEL_WARNING | G_LOG_LEVEL_CRITICAL; g_log_set_always_fatal (fatal_mask); } /* Load the configuration file, * and the default storage plugin */ if (!load_conf()) set_storage_file (); store.init (); r = fp_init(); if (r < 0) { g_error("fprint init failed with error %d\n", r); return r; } loop = g_main_loop_new(NULL, FALSE); r = setup_pollfds(); if (r < 0) { g_print("pollfd setup failed\n"); goto err; } g_print("Launching FprintObject\n"); /* Obtain a connection to the session bus */ fprintd_dbus_conn = dbus_g_bus_get(DBUS_BUS_SYSTEM, &error); if (fprintd_dbus_conn == NULL) g_error("Failed to open connection to bus: %s", error->message); /* create the one instance of the Manager object to be shared between * all fprintd users */ manager = fprint_manager_new(no_timeout); driver_proxy = dbus_g_proxy_new_for_name(fprintd_dbus_conn, DBUS_SERVICE_DBUS, DBUS_PATH_DBUS, DBUS_INTERFACE_DBUS); if (!org_freedesktop_DBus_request_name(driver_proxy, FPRINT_SERVICE_NAME, 0, &request_name_ret, &error)) g_error("Failed to get name: %s", error->message); if (request_name_ret != DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER) { g_error ("Got result code %u from requesting name", request_name_ret); exit(1); } g_message("D-Bus service launched with name: %s", FPRINT_SERVICE_NAME); g_message("entering main loop"); g_main_loop_run(loop); g_message("main loop completed"); err: fp_exit(); return 0; }
int API main (int argc, char *argv[], char *envp[]) { struct routeup rtc; int hwclock_fd = -1; time_t last_success = 0; struct opts opts; int wait_time = 0; set_conf_defaults(&opts); parse_argv(&opts, argc, argv); check_conf(&opts); load_conf(&opts); check_conf(&opts); if (!opts.sources) add_source_to_conf(&opts, DEFAULT_HOST, DEFAULT_PORT, DEFAULT_PROXY); /* grab a handle to /dev/rtc for sync_hwclock() */ if (opts.should_sync_hwclock && (hwclock_fd = open (DEFAULT_RTC_DEVICE, O_RDONLY)) < 0) { pinfo ("can't open hwclock fd"); opts.should_sync_hwclock = 0; } /* set up a netlink context if we need one */ if (opts.should_netlink && routeup_setup (&rtc)) pfatal ("Can't open netlink socket"); if (!is_sane_time (time (NULL))) { struct timeval tv = { 0, 0 }; /* * If the time is before the build timestamp, we're probably on * a system with a broken rtc. Try loading the timestamp off * disk. */ tv.tv_sec = RECENT_COMPILE_DATE; if (opts.should_load_disk && load_disk_timestamp (timestamp_path, &tv.tv_sec)) pinfo ("can't load disk timestamp"); if (!opts.dry_run && settimeofday (&tv, NULL)) pfatal ("settimeofday() failed"); dbus_announce(); /* * don't save here - we either just loaded this time or used the * default time, and neither of those are good to save */ sync_and_save (hwclock_fd, opts.should_sync_hwclock, 0); } /* register a signal handler to save time at shutdown */ if (opts.should_save_disk) signal (SIGTERM, sigterm_handler); /* * Try once right away. If we fail, wait for a route to appear, then try * for a while; repeat whenever another route appears. Try until we * succeed. */ if (!tlsdate (&opts, envp)) { last_success = time (NULL); sync_and_save (hwclock_fd, opts.should_sync_hwclock, opts.should_save_disk); dbus_announce(); } /* * Loop until we catch a fatal signal or routeup_once() fails. We run * tlsdate at least once a day, but possibly as often as routes come up; * this should handle cases like a VPN being brought up and down * periodically. */ wait_time = add_jitter(opts.steady_state_interval, opts.jitter); while (wait_for_event (&rtc, opts.should_netlink, wait_time) >= 0) { /* * If a route just came up, run tlsdate; if it * succeeded, then we're good and can keep time locally * from now on. */ int i; int backoff = opts.wait_between_tries; wait_time = add_jitter(opts.steady_state_interval, opts.jitter); if (time (NULL) - last_success < opts.min_steady_state_interval) continue; for (i = 0; i < opts.max_tries && tlsdate (&opts, envp); ++i) { if (backoff < 1) fatal ("backoff too small? %d", backoff); sleep (backoff); if (backoff < MAX_SANE_BACKOFF) backoff *= 2; } if (i != opts.max_tries) { last_success = time (NULL); info ("tlsdate succeeded"); sync_and_save (hwclock_fd, opts.should_sync_hwclock, opts.should_save_disk); dbus_announce(); } } return 1; }
gint main (gint argc, gchar *argv[]) { Window root; //gettext bindtextdomain( "gamine", LOCALDIR ); textdomain( "gamine" ); gamine_t cb; GtkWidget *window; GdkWindow *gdkwindow; GtkWindow *gtkwindow; GdkScreen *screen; GdkPixbuf *cursor_pixbuf; GdkPixbuf *icon_pixbuf; GdkCursor *cursor; GdkColor bg_color; gchar *cursorfile; gchar *iconfile; cb.is_cairo = FALSE; gtk_init (&argc, &argv); gst_init (&argc, &argv); gconf_init(argc, argv, NULL); gst_play_background (cb.bus, "BachJSBrandenburgConcertNo2inFMajorBWV1047mvmt1.ogg", TRUE); window = gtk_window_new (GTK_WINDOW_TOPLEVEL); /* Create the drawing area and configuration */ cb.da = gtk_drawing_area_new (); bg_color.red = 65535; bg_color.green = 65535; bg_color.blue = 65535; gtk_widget_modify_bg (cb.da, GTK_STATE_NORMAL, &bg_color); gtk_container_add (GTK_CONTAINER (window), cb.da); cb.gc = gconf_client_get_default(); gtkwindow = GTK_WINDOW(window); gtk_window_set_title (gtkwindow, "Gamine"); gtk_window_set_wmclass(gtkwindow, "gamine", "Gamine"); gtk_container_set_border_width (GTK_CONTAINER (gtkwindow), 0); /* Event signals */ g_signal_connect (gtkwindow, "destroy", G_CALLBACK (gtk_main_quit), >kwindow); g_signal_connect (G_OBJECT (cb.da), "expose-event", G_CALLBACK (display_help), &cb); g_signal_connect (cb.da, "motion_notify_event", G_CALLBACK (draw_line), &cb); g_signal_connect (cb.da, "button_press_event", G_CALLBACK (draw_star), &cb); g_signal_connect (gtkwindow, "key-press-event", G_CALLBACK (gamine_on_key), &cb); gtk_widget_set_events (cb.da, gtk_widget_get_events (cb.da) | GDK_LEAVE_NOTIFY_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK | GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK); /* Set fullscreen, grab mouse/keyboard, ...*/ gtk_widget_show_all (GTK_WIDGET(gtkwindow)); gdkwindow = GDK_WINDOW(GTK_WIDGET(gtkwindow)->window); screen = gtk_widget_get_screen (cb.da); gtk_window_present (gtkwindow); gtk_window_stick(gtkwindow); //gtk_window_set_keep_above (gtkwindow), True); //gtk_window_set_transient_for (gtkwindow, NULL); //set fullscreen gdk_window_fullscreen (gdkwindow); gtk_window_fullscreen (gtkwindow); gdk_window_raise (gdkwindow); //set full screen without window manager XMoveResizeWindow(GDK_WINDOW_XDISPLAY(gdkwindow), GDK_WINDOW_XID(gdkwindow), 0, 0, gdk_screen_get_width (screen), gdk_screen_get_height (screen)); root = DefaultRootWindow(GDK_WINDOW_XDISPLAY (gdkwindow)); XGrabPointer(GDK_WINDOW_XDISPLAY (gdkwindow), root, True, PointerMotionMask, GrabModeAsync, GrabModeAsync, root, None, CurrentTime); XGrabKeyboard(GDK_WINDOW_XDISPLAY (gdkwindow), root, True, GrabModeAsync, GrabModeAsync, CurrentTime); //remove keyboard repeat XAutoRepeatOff(GDK_WINDOW_XDISPLAY (gdkwindow)); gtk_window_has_toplevel_focus (gtkwindow); /*cursor*/ cursorfile = g_build_filename(DATADIR, "pencil.png", NULL); if (!g_file_test (cursorfile, G_FILE_TEST_EXISTS)) { printf(gettext("*** error: %s does not exists***\n"), cursorfile); } else { cursor_pixbuf = gdk_pixbuf_new_from_file(cursorfile, NULL); cursor = gdk_cursor_new_from_pixbuf(gdk_display_get_default(), cursor_pixbuf, 0, 38); gdk_window_set_cursor(gdkwindow, cursor); gdk_cursor_unref(cursor); gdk_pixbuf_unref(cursor_pixbuf); } g_free(cursorfile); /*Set icon*/ iconfile = g_build_filename(DATADIR, "gamine.png", NULL); if (!g_file_test (iconfile, G_FILE_TEST_EXISTS)) printf(gettext("*** error: %s does not exists***\n"), iconfile); else { icon_pixbuf = gdk_pixbuf_new_from_file(iconfile, NULL); gtk_window_set_icon (gtkwindow, icon_pixbuf); gdk_pixbuf_unref (icon_pixbuf); } g_free(iconfile); load_conf(&cb); gtk_main (); //set keyboard repeat XAutoRepeatOn(GDK_WINDOW_XDISPLAY (gdkwindow)); XCloseDisplay(GDK_WINDOW_XDISPLAY (gdkwindow)); return 0; }
int API main (int argc, char *argv[], char *envp[]) { initalize_syslog (); struct state state; /* TODO(wad) EVENT_BASE_FLAG_PRECISE_TIMER | EVENT_BASE_FLAG_PRECISE_TIMER */ struct event_base *base = event_base_new(); if (!base) { fatal ("could not allocated new event base"); } /* Add three priority levels: * 0 - time saving. Must be done before any other events are handled. * 1 - network synchronization events * 2 - any other events (wake, platform, etc) */ event_base_priority_init (base, MAX_EVENT_PRIORITIES); memset (&state, 0, sizeof (state)); set_conf_defaults (&state.opts); parse_argv (&state.opts, argc, argv); check_conf (&state); load_conf (&state.opts); check_conf (&state); if (!state.opts.sources) add_source_to_conf (&state.opts, DEFAULT_HOST, DEFAULT_PORT, DEFAULT_PROXY); state.base = base; state.envp = envp; state.backoff = state.opts.wait_between_tries; /* TODO(wad) move this into setup_time_setter */ /* grab a handle to /dev/rtc for time-setter. */ if (state.opts.should_sync_hwclock && platform->rtc_open(&state.hwclock)) { pinfo ("can't open hwclock fd"); state.opts.should_sync_hwclock = 0; } /* install the SIGCHLD handler for the setter and tlsdate */ if (setup_sigchld_event (&state, 1)) { error ("Failed to setup SIGCHLD event"); goto out; } /* fork off the privileged helper */ info ("spawning time setting helper . . ."); if (setup_time_setter (&state)) { error ("could not fork privileged coprocess"); goto out; } /* release the hwclock now that the time-setter is running. */ if (state.opts.should_sync_hwclock) { platform->rtc_close (&state.hwclock); } /* drop privileges before touching any untrusted data */ drop_privs_to (state.opts.user, state.opts.group); /* register a signal handler to save time at shutdown */ if (state.opts.should_save_disk) { struct event *event = event_new (base, SIGTERM, EV_SIGNAL|EV_PERSIST, action_sigterm, &state); if (!event) fatal ("Failed to create SIGTERM event"); event_priority_set (event, PRI_SAVE); event_add (event, NULL); } if (state.opts.should_dbus && init_dbus (&state)) { error ("Failed to initialize DBus"); goto out; } /* Register the tlsdate event before any listeners could show up. */ state.events[E_TLSDATE] = event_new (base, -1, EV_TIMEOUT, action_run_tlsdate, &state); if (!state.events[E_TLSDATE]) { error ("Failed to create tlsdate event"); goto out; } event_priority_set (state.events[E_TLSDATE], PRI_NET); /* The timeout and fd will be filled in per-call. */ if (setup_tlsdate_status (&state)) { error ("Failed to create tlsdate status event"); goto out; } /* TODO(wad) Could use a timeout on this to catch setter death? */ /* EV_READ is for truncation/EPIPE notification */ state.events[E_SAVE] = event_new (base, state.setter_save_fd, EV_READ|EV_WRITE, action_sync_and_save, &state); if (!state.events[E_SAVE]) { error ("Failed to create sync & save event"); goto out; } event_priority_set (state.events[E_SAVE], PRI_SAVE); /* Start by grabbing the system time. */ state.last_sync_type = SYNC_TYPE_RTC; state.last_time = time (NULL); /* If possible, grab disk time and check the two. */ if (state.opts.should_load_disk) { time_t disk_time = state.last_time; if (!load_disk_timestamp (state.timestamp_path, &disk_time)) { info ("disk timestamp available: yes"); if (!is_sane_time (state.last_time) || state.last_time < disk_time) { state.last_sync_type = SYNC_TYPE_DISK; state.last_time = disk_time; } } else { info ("disk timestamp available: no"); } } if (!is_sane_time (state.last_time)) { state.last_sync_type = SYNC_TYPE_BUILD; state.last_time = RECENT_COMPILE_DATE + 1; } /* Save and announce the initial time source. */ trigger_event (&state, E_SAVE, -1); info ("initial time sync type: %s", sync_type_str (state.last_sync_type)); /* Initialize platform specific loop behavior */ if (platform_init_cros (&state)) { error ("Failed to initialize platform code"); goto out; } if (setup_event_route_up (&state)) { error ("Failed to setup route up monitoring"); goto out; } if (setup_event_timer_sync (&state)) { error ("Failed to setup a timer event"); goto out; } if (setup_event_timer_continuity (&state)) { error ("Failed to setup continuity timer"); goto out; } /* Add a forced sync event to the event list. */ action_kickoff_time_sync (-1, EV_TIMEOUT, &state); info ("Entering dispatch . . ."); event_base_dispatch (base); info ("tlsdated terminating gracefully"); out: return cleanup_main (&state); }