int main(int argc, char* argv[]) { printf("payload compiled " __DATE__ " " __TIME__ "\n"); disable_watchdog(); printf("watchdog disabled.\n"); init_tcp(); init_usb(); printf("usbmux initialized\n"); return socket_listen(); }
YJDouyuBarrage::YJDouyuBarrage(QWidget *parent) : QMainWindow(parent) { m_clientTypeCount = new ClientTypeCount; ui.setupUi(this); init_tcp(); init_keepAlive_thread(); init_connection(); }
int sc_tcp_ipv4_listen(struct sc_tcp_server *self, const struct sc_tcp_server_settings *settings, const char *addr, unsigned port, int f, unsigned backlog) { struct sockaddr_in sin = { .sin_family = AF_INET }; int e; //s = settings; if((e = init_ipv4(&sin, addr, port)) != 1) return e; return init_tcp(self, settings, (struct sockaddr *)&sin, sizeof(sin), f, backlog); }
select_db(char *s) { REQ rq; RES res; init_tcp(); rq.req=htonl(NET_CONNECTDB); rq.len=htonl(strlen(s)+1); netwrite(&rq,sizeof(rq)); netwrite(s,strlen(s)+1); netread(&res,sizeof(res)); res.res=ntohl(res.res); if (!res.res) printf("error:%s %s\n", neterr()); return res.res; }
int init_msg_tau (const char *name) { key_s *key; unint i; init_tcp(ServerIP); strlcpy(Me.pr_name, name, TAU_NAME); for (i = MAX_KEYS; i > 0; i--) { key = &Me.pr_keys[i]; *(key_s **)key = Me.pr_top; Me.pr_top = key; } init_dq( &Me.pr_msgq); return 0; }
/* TCPIP マネージャの初期化 */ ER init_tcpip () { if (!initialized) { init_timer (); init_link (); init_ip (); init_udp (); init_tcp (); init_arp (); initialized = 1; } return (E_OK); }
void init_system (void) { /* Initialize configured interfaces and applications. */ #if ETH_ENABLE == 1 init_eth_link (); #endif #if PPP_ENABLE == 1 init_ppp_link (); #endif #if SLIP_ENABLE == 1 init_slip_link (); #endif #if (IGMP_ENABLE & ETH_ENABLE) == 1 init_igmp (); #endif #if UDP_ENABLE == 1 init_udp (); #endif #if TCP_ENABLE == 1 init_tcp (); #endif #if HTTP_ENABLE == 1 init_http (); #endif #if TNET_ENABLE == 1 init_tnet (); #endif #if TFTP_ENABLE == 1 init_tftp (); #endif #if (NBNS_ENABLE & ETH_ENABLE) == 1 init_nbns (); #endif #if (DHCP_ENABLE & ETH_ENABLE) == 1 init_dhcp (); #endif #if DNS_ENABLE == 1 init_dns (); #endif #if SMTP_ENABLE == 1 init_smtp (); #endif }
/* 1:ok, 0:bad address, -1:errno */ int eh_server_ipv4_tcp(struct eh_server *self, const char *addr, unsigned port, bool cloexec) { struct sockaddr_in sin; int fd; int e = init_ipv4(&sin, addr, port); if (e != 1) return e; /* 0 or -1 */ if ((fd = init_tcp(sin.sin_family, cloexec)) < 0) return -1; /* socket() call failed */ else if (bind(fd, (struct sockaddr *)&sin, sizeof(sin)) < 0) { close(fd); return -1; /* bind() failed */ } eh_io_init(&self->connection_watcher, connect_callback, self, fd, EH_READ); return 1; }
int do_http (cmd_tbl_t *cmdtp, int flag, int argc, char *argv[]) { int ret; printf("HTTP Start......\n"); if (argc > 1) http_debug = DEBUG; else http_debug = 0; http_state = HTTP_START; init_tcp(); if (ret = NetLoop(HTTP) < 0) { printf("HTTP Stop......%d\n",ret); return 1; } printf("HTTP Stop......%d\n",ret); return 0; }
/** * Main routine, start of the program execution. * \param argc the number of arguments * \param argv pointer to the arguments array * \return don't return on sucess, -1 on error * \see main_loop */ int main(int argc, char** argv) { /* configure by default logging to syslog */ int cfg_log_stderr = 0; FILE* cfg_stream; int c,r; char *tmp; int tmp_len; int port; int proto; char *options; int ret; unsigned int seed; int rfd; /*init*/ ret=-1; my_argc=argc; my_argv=argv; /*init pkg mallocs (before parsing cfg or cmd line !)*/ if (init_pkg_mallocs()==-1) goto error00; init_route_lists(); /* process command line (get port no, cfg. file path etc) */ opterr=0; options="f:cCm:b:l:n:N:rRvdDETSVhw:t:u:g:P:G:W:o:"; while((c=getopt(argc,argv,options))!=-1){ switch(c){ case 'f': cfg_file=optarg; break; case 'C': config_check |= 2; case 'c': if (config_check==3) break; config_check |= 1; cfg_log_stderr=1; /* force stderr logging */ break; case 'm': shm_mem_size=strtol(optarg, &tmp, 10) * 1024 * 1024; if (tmp &&(*tmp)){ LM_ERR("bad shmem size number: -m %s\n", optarg); goto error00; }; break; case 'b': maxbuffer=strtol(optarg, &tmp, 10); if (tmp &&(*tmp)){ LM_ERR("bad max buffer size number: -b %s\n", optarg); goto error00; } break; case 'l': if (parse_phostport(optarg, strlen(optarg), &tmp, &tmp_len, &port, &proto)<0){ LM_ERR("bad -l address specifier: %s\n", optarg); goto error00; } tmp[tmp_len]=0; /* null terminate the host */ /* add a new addr. to our address list */ if (add_listen_iface(tmp, port, proto, 0, 0, 0)!=0){ LM_ERR("failed to add new listen address\n"); goto error00; } break; case 'n': children_no=strtol(optarg, &tmp, 10); if ((tmp==0) ||(*tmp)){ LM_ERR("bad process number: -n %s\n", optarg); goto error00; } break; case 'v': check_via=1; break; case 'r': received_dns|=DO_DNS; break; case 'R': received_dns|=DO_REV_DNS; case 'd': #ifdef CHANGEABLE_DEBUG_LEVEL (*debug)++; #else debug++; #endif break; case 'D': dont_fork=1; break; case 'E': cfg_log_stderr=1; break; case 'T': #ifdef USE_TCP tcp_disable=1; #else LM_WARN("tcp support not compiled in\n"); #endif break; case 'S': #ifdef USE_SCTP sctp_disable=1; #else LM_WARN("sctp support not compiled in\n"); #endif break; case 'N': #ifdef USE_TCP tcp_children_no=strtol(optarg, &tmp, 10); if ((tmp==0) ||(*tmp)){ LM_ERR("bad process number: -N %s\n", optarg); goto error00; } #else LM_WARN("tcp support not compiled in\n"); #endif break; case 'W': #ifdef USE_TCP tcp_poll_method=get_poll_type(optarg); if (tcp_poll_method==POLL_NONE){ LM_ERR("bad poll method name: -W %s\ntry " "one of %s.\n", optarg, poll_support); goto error00; } #else LM_WARN("tcp support not compiled in\n"); #endif break; case 'V': printf("version: %s\n", version); printf("flags: %s\n", flags ); print_ct_constants(); printf("%s\n",id); printf("%s compiled on %s with %s\n", __FILE__, compiled, COMPILER ); exit(0); break; case 'h': printf("version: %s\n", version); printf("%s",help_msg); exit(0); break; case 'w': working_dir=optarg; break; case 't': chroot_dir=optarg; break; case 'u': user=optarg; break; case 'g': group=optarg; break; case 'P': pid_file=optarg; break; case 'G': pgid_file=optarg; break; case 'o': if (add_arg_var(optarg) < 0) LM_ERR("cannot add option %s\n", optarg); break; case '?': if (isprint(optopt)) LM_ERR("Unknown option `-%c`.\n", optopt); else LM_ERR("Unknown option character `\\x%x`.\n", optopt); goto error00; case ':': LM_ERR("Option `-%c` requires an argument.\n", optopt); goto error00; default: abort(); } } log_stderr = cfg_log_stderr; /* fill missing arguments with the default values*/ if (cfg_file==0) cfg_file=CFG_FILE; /* load config file or die */ cfg_stream=fopen (cfg_file, "r"); if (cfg_stream==0){ LM_ERR("loading config file(%s): %s\n", cfg_file, strerror(errno)); goto error00; } /* seed the prng, try to use /dev/urandom if possible */ /* no debugging information is logged, because the standard log level prior the config file parsing is L_NOTICE */ seed=0; if ((rfd=open("/dev/urandom", O_RDONLY))!=-1){ try_again: if (read(rfd, (void*)&seed, sizeof(seed))==-1){ if (errno==EINTR) goto try_again; /* interrupted by signal */ LM_WARN("could not read from /dev/urandom (%d)\n", errno); } LM_DBG("initialize the pseudo random generator from " "/dev/urandom\n"); LM_DBG("read %u from /dev/urandom\n", seed); close(rfd); }else{ LM_WARN("could not open /dev/urandom (%d)\n", errno); LM_WARN("using a unsafe seed for the pseudo random number generator"); } seed+=getpid()+time(0); LM_DBG("seeding PRNG with %u\n", seed); srand(seed); LM_DBG("test random number %u\n", rand()); /*register builtin modules*/ register_builtin_modules(); #ifdef USE_TLS /* initialize default TLS domains, must be done before reading the config */ if (pre_init_tls()<0){ LM_CRIT("could not pre_init_tls, exiting...\n"); goto error00; } #endif /* USE_TLS */ if (preinit_black_lists()!=0) { LM_CRIT("failed to alloc black list's anchor\n"); goto error00; } /* parse the config file, prior to this only default values e.g. for debugging settings will be used */ yyin=cfg_stream; if ((yyparse()!=0)||(cfg_errors)){ LM_ERR("bad config file (%d errors)\n", cfg_errors); goto error00; } if (config_check>1 && check_rls()!=0) { LM_ERR("bad function call in config file\n"); return ret; } #ifdef EXTRA_DEBUG print_rl(); #endif /* init the resolver, before fixing the config */ resolv_init(); /* fix parameters */ if (port_no<=0) port_no=SIP_PORT; #ifdef USE_TLS if (tls_port_no<=0) tls_port_no=SIPS_PORT; #endif if (children_no<=0) children_no=CHILD_NO; #ifdef USE_TCP if (!tcp_disable){ if (tcp_children_no<=0) tcp_children_no=children_no; } #endif if (working_dir==0) working_dir="/"; /* get uid/gid */ if (user){ if (user2uid(&uid, &gid, user)<0){ LM_ERR("bad user name/uid number: -u %s\n", user); goto error00; } } if (group){ if (group2gid(&gid, group)<0){ LM_ERR("bad group name/gid number: -u %s\n", group); goto error00; } } if (fix_all_socket_lists()!=0){ LM_ERR("failed to initialize list addresses\n"); goto error00; } /* print all the listen addresses */ printf("Listening on \n"); print_all_socket_lists(); printf("Aliases: \n"); /*print_aliases();*/ print_aliases(); printf("\n"); if (dont_fork){ LM_WARN("no fork mode %s\n", (udp_listen)?( (udp_listen->next)?" and more than one listen address found" "(will use only the first one)":"" ):"and no udp listen address found" ); } if (config_check){ LM_NOTICE("config file ok, exiting...\n"); return 0; } time(&startup_time); /*init shm mallocs * this must be here * -to allow setting shm mem size from the command line * => if shm_mem should be settable from the cfg file move * everything after * -it must be also before init_timer and init_tcp * -it must be after we know uid (so that in the SYSV sems case, * the sems will have the correct euid) * --andrei */ if (init_shm_mallocs()==-1) goto error; /*init timer, before parsing the cfg!*/ if (init_timer()<0){ LM_CRIT("could not initialize timer, exiting...\n"); goto error; } #ifdef USE_TCP if (!tcp_disable){ /*init tcp*/ if (init_tcp()<0){ LM_CRIT("could not initialize tcp, exiting...\n"); goto error; } } #ifdef USE_TLS if (!tls_disable){ /* init tls*/ if (init_tls()<0){ LM_CRIT("could not initialize tls, exiting...\n"); goto error; } } #endif /* USE_TLS */ #endif /* USE_TCP */ /* init_daemon? */ if (!dont_fork){ if ( daemonize((log_name==0)?argv[0]:log_name, &own_pgid) <0 ) goto error; } /* install signal handlers */ if (install_sigs() != 0){ LM_ERR("could not install the signal handlers\n"); goto error; } #ifdef CHANGEABLE_DEBUG_LEVEL #ifdef SHM_MEM debug=shm_malloc(sizeof(int)); if (debug==0) { LM_ERR("ERROR: out of memory\n"); goto error; } *debug = debug_init; #else LM_WARN("no shm mem support compiled -> changeable debug " "level turned off\n"); #endif #endif if (disable_core_dump) set_core_dump(0, 0); else set_core_dump(1, shm_mem_size+PKG_MEM_POOL_SIZE+4*1024*1024); if (open_files_limit>0){ if(increase_open_fds(open_files_limit)<0){ LM_ERR("ERROR: error could not increase file limits\n"); goto error; } } /* print OpenSIPS version to log for history tracking */ LM_NOTICE("version: %s\n", version); /* print some data about the configuration */ #ifdef SHM_MEM LM_INFO("using %ld Mb shared memory\n", ((shm_mem_size/1024)/1024)); #endif LM_INFO("using %i Mb private memory per process\n", ((PKG_MEM_POOL_SIZE/1024)/1024)); /* init serial forking engine */ if (init_serialization()!=0) { LM_ERR("failed to initialize serialization\n"); goto error; } /* Init statistics */ if (init_stats_collector()<0) { LM_ERR("failed to initialize statistics\n"); goto error; } /* Init MI */ if (init_mi_core()<0) { LM_ERR("failed to initialize MI core\n"); goto error; } /* init black list engine */ if (init_black_lists()!=0) { LM_CRIT("failed to init black lists\n"); goto error; } /* init resolver's blacklist */ if (resolv_blacklist_init()!=0) { LM_CRIT("failed to create DNS blacklist\n"); goto error; } /* init modules */ if (init_modules() != 0) { LM_ERR("error while initializing modules\n"); goto error; } /* register route timers */ if(register_route_timers() < 0) { LM_ERR("Failed to register timer\n"); goto error; } /* check pv context list */ if(pv_contextlist_check() != 0) { LM_ERR("used pv context that was not defined\n"); goto error; } /* init multi processes support */ if (init_multi_proc_support()!=0) { LM_ERR("failed to init multi-proc support\n"); goto error; } #ifdef PKG_MALLOC /* init stats support for pkg mem */ if (init_pkg_stats(counted_processes)!=0) { LM_ERR("failed to init stats for pkg\n"); goto error; } #endif /* fix routing lists */ if ( (r=fix_rls())!=0){ LM_ERR("failed to fix configuration with err code %d\n", r); goto error; }; ret=main_loop(); error: /*kill everything*/ kill_all_children(SIGTERM); /*clean-up*/ cleanup(0); error00: return ret; }
static int start_server(char *interface) { struct sockaddr_in client_addr; socklen_t client_len; int client_fd; char *client_ip_addr; struct hostent *client_host; FILE *fp; char *buffer; char *uri; char *method; int continue_proc = TRUE; if (init_tcp(interface) < 0) { fprintf(stderr, "init TCP failed\n"); return STATUS_ERROR; } if (!interface) strcpy(local_ip_addr, "localhost"); client_len = sizeof(client_addr); while (continue_proc) { client_fd = accept(server_fd, (struct sockaddr *) &client_addr, &client_len); if (client_fd < 0) { perror("errorn in accept"); continue; } client_host = gethostbyaddr( (const char *) &client_addr.sin_addr.s_addr, sizeof(client_addr.sin_addr.s_addr), AF_INET); if (client_host == NULL) { perror("error in gethostbyaddr"); /* No need to bail out */ } client_ip_addr = inet_ntoa(client_addr.sin_addr); if (client_ip_addr == NULL) { perror("Can't get client IP\n"); close(client_fd); continue; } set_socket_timeout(client_fd); fprintf(stdout, "Received Request from %s\n", client_ip_addr); fp = fdopen(client_fd, "r+"); if (fp == NULL) { perror("error in fdopen"); close(client_fd); continue; } buffer = malloc(MAX_BUFFER_SIZE); if (!buffer) { perror("error in malloc"); fclose(fp); close(client_fd); continue; } if (fgets(buffer, MAX_BUFFER_SIZE, fp) == NULL) goto continue_loop; uri = NULL; method = NULL; method = strtok(buffer, " "); if (!method) { flush_request_buffer(fp); send_error(fp, "none", "400", "Bad request", "unknown method"); goto continue_loop; } if (strncasecmp(method, "GET", 3)) { flush_request_buffer(fp); send_error(fp, method, "501", "Not Implemented", "Only GET is supported"); goto continue_loop; } uri = strtok(NULL, " "); if (!uri) { flush_request_buffer(fp); send_error(fp, method, "400", "Bad request", "Bad request"); goto continue_loop; } flush_request_buffer(fp); if (!process_cmd(fp, uri, MAX_BUFFER_SIZE, buffer)) continue_proc = FALSE; fprintf(stdout, "processing done\n"); continue_loop: free(buffer); fclose(fp); close(client_fd); } return STATUS_SUCCESS; }
int main(int argc, char **argv) { init_tcp(PORT); verbose = 0; /* Initialize the xmit files */ /* init calls init_dma as well */ init(); /* DEFAULTS */ center_freq = CARRIERFREQ/pow(10,6); mod_freq = MOD_FREQ; bits_per_sym = BITS_PER_SYM; pkt_size = PKT_SIZE; freq_deviation = FREQ_SPACING; packetize = ON; strcpy(file_name,"No File"); repeat = OFF; addr = ON; address_char = ADDR; header = ON; tx_file_name = ON; flags[FILE_TRANSMIT] = OFF; flags[OUTPUT_DATA] = ON; flags[COUT_DATA_HEX] = OFF; flags[COUT_DATA_CHAR] = ON; flags[DSA_PAGE] = OFF; tx_type = 0; echo = 0; int option; while ((option = getopt(argc,argv,"qvhNPerHADXCOt:f:m:d:b:p:F:")) != EOF) { switch (option) { case 'h': usage(); return 0; case 'q': verbose = 0; break; case 'v': verbose = 1; break; case 'f': center_freq = atof(optarg); break; case 'm': mod_freq = atof(optarg); break; case 'd': freq_deviation = atof(optarg); break; case 'b': bits_per_sym = atof(optarg); break; case 'p': pkt_size = atof(optarg); break; case 'P': packetize = 0; break; case 'r': repeat = 1; break; case 'F': strcpy(file_name,strdup(optarg)); break; case 'a': addr = 0; break; case 'A': address_char = *optarg; break; case 'H': header = 0; break; case 'N': tx_file_name = OFF; break; case 'D': flags[DSA_PAGE] = ON; break; case 'X': flags[COUT_DATA_HEX] = ON; break; case 'C': flags[COUT_DATA_CHAR] = OFF; break; case 'O': flags[OUTPUT_DATA] = OFF; break; case 't': tx_type = atof(optarg); break; case 'e': echo = atof(optarg); break; default: usage(); return 0; } } if ((listen(socket_fd, BACKLOG)) == -1) error("Listening Failure\n"); /* ******************************** */ /* *** Main Lock Loop For TCP *** */ /* ******************************** */ while(1) { size = sizeof(struct sockaddr_in); if((client_fd = accept(socket_fd, (struct sockaddr *)&dest, &size))==-1 ) error("accept"); if(verbose) printf("Server got connection from client %s\n", inet_ntoa(dest.sin_addr)); while(1) { if((num = recv(client_fd, buffer, BUFFER_LEN,0))== -1) error("recv"); else if (num == 0) { if(verbose) printf("Connection closed\n"); //So I can now wait for another client break; } buffer[num] = '\0'; if(verbose) printf("Server:Msg Received %s\n", buffer); char *config_check = strstr(buffer,"CONFIG"); if(config_check != NULL) { configure(buffer); continue; } // use the num*8 to allocate memory // and then copy over the data // from the buffer for loop n // after converting to binary if(echo) { if ((send(client_fd,buffer, strlen(buffer),0))== -1) { if(verbose) printf("Failure Sending Message\n"); close(client_fd); break; } } printf("Server:Msg being sent: %s\nNumber of bytes sent: %d\n",buffer, strlen(buffer)); /* TX SECTION */ int *data = NULL; int num_samples = 16; if(strcmp(file_name,"No File")) { if(verbose) printf("File Name : %s\n",file_name); num_samples = file_breakdown(file_name,&data); flags[FILE_TRANSMIT] = 1; //error("\nFILE CHECK COMPLETE"); } else { num_samples = 16; data = malloc(num_samples*sizeof(int)); int tmp_data[16] = {1,0,1,0,1,1,1,1,0,0,0,0,1,1,0,1}; int i; for(i = 0; i < num_samples; i++) data[i] = tmp_data[i]; } if(strlen(buffer) > 0) { num_samples = strlen(buffer)*8; data = malloc(num_samples*sizeof(int)); data = string_breakdown(buffer); } if(verbose) printf("TX TYPE = %i\n\n",tx_type); switch(tx_type) { case 0: /***************** DMA_FSK TEST ********************/ dma_fsk_transmit(data,num_samples); break; case 1: /***************** DMA_OOK TEST ********************/ dma_ook_transmit(data,num_samples); break; case 2: /******************* FSK TEST **********************/ fsk_transmit(data, num_samples); break; case 3: /******************* OOK TEST **********************/ ook_transmit(data, num_samples); break; default: break; } free(data); data = NULL; } //End of Inner While... //Close Connection Socket close(client_fd); } //Outer While close(socket_fd); error("terminate"); return 0; }
int main(int argc, char** argv) { FILE* cfg_stream; int c,r; char *tmp; int tmp_len; int port; int proto; char *options; int ret; unsigned int seed; int rfd; /*init*/ ret=-1; my_argc=argc; my_argv=argv; /*init pkg mallocs (before parsing cfg or cmd line !)*/ if (init_pkg_mallocs()==-1) goto error; #ifdef DBG_MSG_QA fprintf(stderr, "WARNING: ser startup: " "DBG_MSG_QA enabled, ser may exit abruptly\n"); #endif /* process command line (get port no, cfg. file path etc) */ opterr=0; options= #ifdef STATS "s:" #endif "f:cm:b:l:n:N:rRvdDETVhw:t:u:g:P:G:i:x:"; while((c=getopt(argc,argv,options))!=-1){ switch(c){ case 'f': cfg_file=optarg; break; case 'c': config_check=1; log_stderr=1; /* force stderr logging */ break; case 's': #ifdef STATS stat_file=optarg; #endif break; case 'm': shm_mem_size=strtol(optarg, &tmp, 10) * 1024 * 1024; if (tmp &&(*tmp)){ fprintf(stderr, "bad shmem size number: -m %s\n", optarg); goto error; }; LOG(L_INFO, "ser: shared memory: %ld bytes\n", shm_mem_size ); break; case 'b': maxbuffer=strtol(optarg, &tmp, 10); if (tmp &&(*tmp)){ fprintf(stderr, "bad max buffer size number: -p %s\n", optarg); goto error; } break; case 'l': if (parse_phostport(optarg, &tmp, &tmp_len, &port, &proto)<0){ fprintf(stderr, "bad -l address specifier: %s\n", optarg); goto error; } tmp[tmp_len]=0; /* null terminate the host */ /* add a new addr. to our address list */ if (add_listen_iface(tmp, port, proto, 0)!=0){ fprintf(stderr, "failed to add new listen address\n"); goto error; } break; case 'n': children_no=strtol(optarg, &tmp, 10); if ((tmp==0) ||(*tmp)){ fprintf(stderr, "bad process number: -n %s\n", optarg); goto error; } break; case 'v': check_via=1; break; case 'r': received_dns|=DO_DNS; break; case 'R': received_dns|=DO_REV_DNS; case 'd': debug++; break; case 'D': dont_fork=1; break; case 'E': log_stderr=1; break; case 'T': #ifdef USE_TCP tcp_disable=1; #else fprintf(stderr,"WARNING: tcp support not compiled in\n"); #endif break; case 'N': #ifdef USE_TCP tcp_children_no=strtol(optarg, &tmp, 10); if ((tmp==0) ||(*tmp)){ fprintf(stderr, "bad process number: -N %s\n", optarg); goto error; } #else fprintf(stderr,"WARNING: tcp support not compiled in\n"); #endif break; case 'V': printf("version: %s\n", version); printf("flags: %s\n", flags ); print_ct_constants(); printf("%s\n",id); printf("%s compiled on %s with %s\n", __FILE__, compiled, COMPILER ); exit(0); break; case 'h': printf("version: %s\n", version); printf("%s",help_msg); exit(0); break; case 'w': working_dir=optarg; break; case 't': chroot_dir=optarg; break; case 'u': user=optarg; break; case 'g': group=optarg; break; case 'P': pid_file=optarg; break; case 'G': pgid_file=optarg; break; case 'i': fifo=optarg; break; case 'x': unixsock_name=optarg; break; case '?': if (isprint(optopt)) fprintf(stderr, "Unknown option `-%c´.\n", optopt); else fprintf(stderr, "Unknown option character `\\x%x´.\n", optopt); goto error; case ':': fprintf(stderr, "Option `-%c´ requires an argument.\n", optopt); goto error; default: abort(); } } /* fill missing arguments with the default values*/ if (cfg_file==0) cfg_file=CFG_FILE; /* load config file or die */ cfg_stream=fopen (cfg_file, "r"); if (cfg_stream==0){ fprintf(stderr, "ERROR: loading config file(%s): %s\n", cfg_file, strerror(errno)); goto error; } /* seed the prng */ /* try to use /dev/urandom if possible */ seed=0; if ((rfd=open("/dev/urandom", O_RDONLY))!=-1){ try_again: if (read(rfd, (void*)&seed, sizeof(seed))==-1){ if (errno==EINTR) goto try_again; /* interrupted by signal */ LOG(L_WARN, "WARNING: could not read from /dev/urandom (%d)\n", errno); } DBG("read %u from /dev/urandom\n", seed); close(rfd); }else{ LOG(L_WARN, "WARNING: could not open /dev/urandom (%d)\n", errno); } seed+=getpid()+time(0); DBG("seeding PRNG with %u\n", seed); srand(seed); DBG("test random number %u\n", rand()); /* register a diagnostic FIFO command - moved to fifo server - bogdan if (register_core_fifo()<0) { LOG(L_CRIT, "unable to register core FIFO commands\n"); goto error; }*/ /*register builtin modules*/ register_builtin_modules(); yyin=cfg_stream; if ((yyparse()!=0)||(cfg_errors)){ fprintf(stderr, "ERROR: bad config file (%d errors)\n", cfg_errors); goto error; } print_rl(); /* fix parameters */ if (port_no<=0) port_no=SIP_PORT; #ifdef USE_TLS if (tls_port_no<=0) tls_port_no=SIPS_PORT; #endif if (children_no<=0) children_no=CHILD_NO; #ifdef USE_TCP if (!tcp_disable){ if (tcp_children_no<=0) tcp_children_no=children_no; } #endif if (working_dir==0) working_dir="/"; /* get uid/gid */ if (user){ if (user2uid(&uid, &gid, user)<0){ fprintf(stderr, "bad user name/uid number: -u %s\n", user); goto error; } } if (group){ if (group2gid(&gid, group)<0){ fprintf(stderr, "bad group name/gid number: -u %s\n", group); goto error; } } /* fix sock/fifo uid/gid */ if (sock_user){ if (user2uid(&sock_uid, 0, sock_user)<0){ fprintf(stderr, "bad socket user name/uid number %s\n", user); goto error; } } if (sock_group){ if (group2gid(&sock_gid, sock_group)<0){ fprintf(stderr, "bad group name/gid number: -u %s\n", group); goto error; } } if (fix_all_socket_lists()!=0){ fprintf(stderr, "failed to initialize list addresses\n"); goto error; } /* print all the listen addresses */ printf("Listening on \n"); print_all_socket_lists(); printf("Aliases: \n"); /*print_aliases();*/ print_aliases(); printf("\n"); if (dont_fork){ fprintf(stderr, "WARNING: no fork mode %s\n", (udp_listen)?( (udp_listen->next)?" and more than one listen address found" "(will use only the the first one)":"" ):"and no udp listen address found" ); } if (config_check){ fprintf(stderr, "config file ok, exiting...\n"); goto error; } /*init shm mallocs * this must be here * -to allow setting shm mem size from the command line * => if shm_mem should be settable from the cfg file move * everything after * -it must be also before init_timer and init_tcp * -it must be after we know uid (so that in the SYSV sems case, * the sems will have the correct euid) * --andrei */ if (init_shm_mallocs()==-1) goto error; /*init timer, before parsing the cfg!*/ if (init_timer()<0){ LOG(L_CRIT, "could not initialize timer, exiting...\n"); goto error; } #ifdef USE_TCP if (!tcp_disable){ /*init tcp*/ if (init_tcp()<0){ LOG(L_CRIT, "could not initialize tcp, exiting...\n"); goto error; } } #ifdef USE_TLS if (!tls_disable){ /* init tls*/ if (init_tls()<0){ LOG(L_CRIT, "could not initialize tls, exiting...\n"); goto error; } } #endif /* USE_TLS */ #endif /* USE_TCP */ /* init_daemon? */ if (!dont_fork){ if ( daemonize(argv[0]) <0 ) goto error; } if (install_sigs() != 0){ fprintf(stderr, "ERROR: could not install the signal handlers\n"); goto error; } /*alloc pids*/ #ifdef SHM_MEM pt=shm_malloc(sizeof(struct process_table)*process_count()); #else pt=pkg_malloc(sizeof(struct process_table)*process_count()); #endif if (pt==0){ fprintf(stderr, "ERROR: out of memory\n"); goto error; } memset(pt, 0, sizeof(struct process_table)*process_count()); if (disable_core_dump) set_core_dump(0, 0); else set_core_dump(1, shm_mem_size+PKG_MEM_POOL_SIZE+4*1024*1024); if (open_files_limit>0){ if(increase_open_fds(open_files_limit)<0){ fprintf(stderr, "ERROR: error could not increase file limits\n"); goto error; } } if (init_modules() != 0) { fprintf(stderr, "ERROR: error while initializing modules\n"); goto error; } /* fix routing lists */ if ( (r=fix_rls())!=0){ fprintf(stderr, "ERROR: error %d while trying to fix configuration\n", r); goto error; }; #ifdef STATS if (init_stats( dont_fork ? 1 : children_no )==-1) goto error; #endif ret=main_loop(); /*kill everything*/ kill_all_children(SIGTERM); /*clean-up*/ cleanup(0); return ret; error: /*kill everything*/ kill_all_children(SIGTERM); /*clean-up*/ cleanup(0); return -1; }
int main(int argc, char* argv[]) { int i; int nandReadOnly=0; struct stat st; printf("Starting ramdisk tool\n"); printf("Compiled " __DATE__ " " __TIME__ "\n"); printf("Revision " HGVERSION "\n"); CFMutableDictionaryRef matching; io_service_t service = 0; matching = IOServiceMatching("IOWatchDogTimer"); if (matching == NULL) { printf("unable to create matching dictionary for class IOWatchDogTimer\n"); } service = IOServiceGetMatchingService(kIOMasterPortDefault, matching); if (service == 0) { printf("unable to create matching dictionary for class IOWatchDogTimer\n"); } uint32_t zero = 0; CFNumberRef n = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &zero); IORegistryEntrySetCFProperties(service, n); IOObjectRelease(service); CFMutableDictionaryRef deviceInfos = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); get_device_infos(deviceInfos); init_tcp(); sysctlbyname("kern.bootargs", bootargs, &bootargs_len, NULL, 0); if (strstr(bootargs, "nand-readonly") || strstr(bootargs, "nand-disable")) { printf("NAND read only mode, data partition wont be mounted\n"); nandReadOnly = 1; } else { printf("Waiting for data partition\n"); for(i=0; i < 10; i++) { if(!stat("/dev/disk0s2s1", &st)) { system("/sbin/fsck_hfs /dev/disk0s2s1"); break; } if(!stat("/dev/disk0s1s2", &st)) { system("/sbin/fsck_hfs /dev/disk0s1s2"); break; } if(!stat("/dev/disk0s2", &st)) { system("/sbin/fsck_hfs /dev/disk0s2"); break; } sleep(5); } } init_usb(CFDictionaryGetValue(deviceInfos, CFSTR("udid"))); printf("USB init done\n"); system("mount /"); //make ramdisk writable chmod("/var/root/.ssh/authorized_keys", 0600); chown("/var/root/.ssh/authorized_keys", 0, 0); chown("/var/root/.ssh", 0, 0); chown("/var/root/", 0, 0); printf(" ####### ## ##\n"); printf("## ## ## ## \n"); printf("## ## ## ## \n"); printf("## ## ##### \n"); printf("## ## ## ## \n"); printf("## ## ## ## \n"); printf(" ####### ## ##\n"); printf("iphone-dataprotection ramdisk\n"); printf("revision: " HGVERSION " " __DATE__ " " __TIME__ "\n"); if(!stat(execve_params[0], &st)) { printf("Running %s\n", execve_params[0]); if((i = posix_spawn(NULL, execve_params[0], NULL, NULL, execve_params, execve_env))) printf("posix_spawn(%s) returned %d\n", execve_params[0], i); } else { printf("%s is missing\n", execve_params[0]); } /*if (nandReadOnly) {*/ if(!stat(ioflash[0], &st)) { printf("Running %s\n", ioflash[0]); if((i = posix_spawn(NULL, ioflash[0], NULL, NULL, ioflash, execve_env))) printf("posix_spawn(%s) returned %d\n", execve_params[0], i); } /*}*/ CFMutableDictionaryRef handlers = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, NULL); CFDictionaryAddValue(handlers, CFSTR("DeviceInfo"), device_info); CFDictionaryAddValue(handlers, CFSTR("GetSystemKeyBag"), load_system_keybag); CFDictionaryAddValue(handlers, CFSTR("BruteforceSystemKeyBag"), bruteforce_system_keybag); CFDictionaryAddValue(handlers, CFSTR("KeyBagGetPasscodeKey"), keybag_get_passcode_key); CFDictionaryAddValue(handlers, CFSTR("GetEscrowRecord"), get_escrow_record); CFDictionaryAddValue(handlers, CFSTR("DownloadFile"), download_file); CFDictionaryAddValue(handlers, CFSTR("AES"), remote_aes); CFDictionaryAddValue(handlers, CFSTR("Reboot"), reboot__); serve_plist_rpc(1999, handlers); return 0; }
/* * Daemonize and persist pid */ int daemon_start() { struct sigaction sig_action; sigset_t sig_set; pid_t otherpid; int curPID; pthread_t tcp4_thread, udp4_thread; pthread_t tcp6_thread, udp6_thread; /* Check if we can acquire the pid file */ pfh = pidfile_open(NULL, 0600, &otherpid); if (pfh == NULL) { if (errno == EEXIST) { errx(EXIT_FAILURE, "Daemon already running, pid: %jd.", (intmax_t)otherpid); } err(EXIT_FAILURE, "Cannot open or create pidfile"); } init_logger(); /* Initialize TCP46 and UDP46 sockets */ if (init_tcp() == EXIT_FAILURE) return (EXIT_FAILURE); if (init_udp() == EXIT_FAILURE) return (EXIT_FAILURE); /* start daemonizing */ curPID = fork(); switch (curPID) { case 0: /* This process is the child */ break; case -1: /* fork() failed, should exit */ perror("fork"); return (EXIT_FAILURE); default: /* fork() successful, should exit * (parent) */ return (EXIT_SUCCESS); } /* we are the child, complete the daemonization */ /* Close standard IO */ fclose(stdin); fclose(stdout); fclose(stderr); /* Block unnecessary signals */ sigemptyset(&sig_set); sigaddset(&sig_set, SIGCHLD); /* ignore child - i.e. we don't need * to wait for it */ sigaddset(&sig_set, SIGTSTP); /* ignore tty stop signals */ sigaddset(&sig_set, SIGTTOU); /* ignore tty background writes */ sigaddset(&sig_set, SIGTTIN); /* ignore tty background reads */ sigprocmask(SIG_BLOCK, &sig_set, NULL); /* Block the above specified * signals */ /* Catch necessary signals */ sig_action.sa_handler = signal_handler; sigemptyset(&sig_action.sa_mask); sig_action.sa_flags = 0; sigaction(SIGTERM, &sig_action, NULL); sigaction(SIGHUP, &sig_action, NULL); sigaction(SIGINT, &sig_action, NULL); /* create new session and process group */ setsid(); /* persist pid */ pidfile_write(pfh); /* Create TCP and UDP listener threads */ pthread_create(&tcp4_thread, NULL, tcp4_handler, NULL); pthread_create(&udp4_thread, NULL, udp4_handler, NULL); #ifdef PF_INET6 pthread_create(&tcp6_thread, NULL, tcp6_handler, NULL); pthread_create(&udp6_thread, NULL, udp6_handler, NULL); #endif /* * Wait for threads to terminate, which normally shouldn't ever * happen */ pthread_join(tcp4_thread, NULL); pthread_join(udp4_thread, NULL); #ifdef PF_INET6 pthread_join(tcp6_thread, NULL); pthread_join(udp6_thread, NULL); #endif return (EXIT_SUCCESS); }
int main(int ac, char *av[]) { char rpath[MAX_NAME_LEN]; int status, *jstatus; simplequeue_t *outputQ, *workQ, *qtoa; // setup the program properties setupProgram(ac, av); // creates a PID file under router_name.pid in the current directory status = makePIDFile(rconfig.router_name, rpath); // shutdown the router on receiving SIGUSR1 or SIGUSR2 redefineSignalHandler(SIGUSR1, shutdownRouter); redefineSignalHandler(SIGUSR2, shutdownRouter); outputQ = createSimpleQueue("outputQueue", INFINITE_Q_SIZE, 0, 1); workQ = createSimpleQueue("work Queue", INFINITE_Q_SIZE, 0, 1); GNETInit(&(rconfig.ghandler), rconfig.config_dir, rconfig.router_name, outputQ); ARPInit(); IPInit(); init_ports(); init_tcp(); /*uint32_t dest_ip = 12319800; uint16_t dest_port = 123; uint16_t src_port = 456; char *data = "Hello"; int len = 6; send_udp(dest_ip,dest_port,src_port,data,len);*/ /* *Test udp_recv * */ /*open_port(1, UDP_PROTOCOL); gpacket_t *packet = (gpacket_t *) malloc(sizeof(gpacket_t)); ip_packet_t *ipPacket = (ip_packet_t *)(packet->data.data); ipPacket->ip_src = {0x1,0x1,0x1,0x1}; ipPacket->ip_dst = {0x2,0x2,0x2,0x2}; ipPacket->ip_cksum = 65535; ipPacket->ip_pkt_len = ipPacket->ip_hdr_len; udphdr_t *udpHeader = (udphdr_t *)((uchar *)ipPacket + ipPacket->ip_hdr_len*4); udpHeader->source = 0; // ports udpHeader->dest = 1; udpHeader->len = 0; // length of data in octets udpHeader->check = 65535; udp_recv(packet); free(packet); free(ipPacket); free(udpHeader);*/ /* * * * End test udp_recv * */ printf("dis router"); classifier = createClassifier(); filter = createFilter(classifier, 0); pcore = createPacketCore(rconfig.router_name, outputQ, workQ); // add a default Queue.. the createClassifier has already added a rule with "default" tag // char *qname, char *dqisc, double qweight, double delay_us, int nslots); addPktCoreQueue(pcore, "default", "taildrop", 1.0, 2.0, 0); rconfig.scheduler = PktCoreSchedulerInit(pcore); rconfig.worker = PktCoreWorkerInit(pcore); infoInit(rconfig.config_dir, rconfig.router_name); addTarget("Output Queue", outputQ); qtoa = getCoreQueue(pcore, "default"); if (qtoa != NULL) addTarget("Default Queue", qtoa); else printf("Error .. found null queue for default\n"); // start the CLI.. CLIInit(&(rconfig)); wait4thread(rconfig.scheduler); wait4thread(rconfig.worker); wait4thread(rconfig.ghandler); }