/***************************************************************************** Envia o mesmo IR repetidamente *****************************************************************************/ void repeat_IR(char *str_IdIr, char qtd_interval_100ms, char time_start_100ms) { char i, cont=0, start=0; memset(buf_rx,0,sizeof(buf_rx)); NVIC_EnableIRQ(UART2_IRQn); /*Habilita a interrupção serial para receber a tecla despressionada (TOU 000)*/ while(1) { /*Sai do laço caso a tecla deixe de ser pressionada ou aconteça algum erro ao enviar o IR*/ if(strstr(buf_rx,"TOU 000") || buf_tx[0] == 'E') break; else cmd_ir_send(str_IdIr); /*Envia o IR localizado no endereço recebido pela função*/ wdt_feed(); if(!start) /*Apenas na inicialização*/ { if(time_start_100ms) /*Existe tempo de start para o IR*/ { while(1) /*Loop para da um tempo minimo para o primeiro IR enviado*/ { /*Contagem de tempo para comparação com o tempo de Start*/ timer_poll(); if(tick) if(++cont >= time_start_100ms)break; } } start = 1; } /*Continua no laço caso não tenha intervalo de repetição*/ if(!qtd_interval_100ms) continue; /*Contagem de tempo para comparação com o intervalo de repetição*/ cont=0; while(1) { wdt_feed(); timer_poll(); if(tick) if(++cont >= qtd_interval_100ms) /*No primeiro IR demora um pouco mais*/ break; } } NVIC_DisableIRQ(UART2_IRQn); /*Desabilita novamente a interrupção serial*/ memset(buf_rx,0,sizeof(buf_rx)); for(i=TOUCH_0;i<=TOUCH_15;i++) /*Loop para desligar todos os leds 4x4*/ out_leds &= ~(1<<i); touch_led_press = TOUCH_NONE; if(buf_tx[0] == 'E') /*Houve algum erro ao enviar o IR?*/ { beep(BEEP_ERROR); strcat(buf_tx,"\r\r\0"); uart_putString(0,buf_tx); /*String de erro*/ } }
int system_send_buf_to_host( char* buf, int buf_size ) { char* sendbuf; int stat = 0; if( g_send_package_socket != 0) { stat = tcp_get_state( g_send_package_socket ); switch ( stat ) { case TCP_STATE_FREE: case TCP_STATE_CLOSED: tcp_connect ( g_send_package_socket, g_send_package_socket_ip, g_send_package_socket_port, 0); #if 1 return -2; #else // wait connect // maybe need while( 1 ){ stat = tcp_get_state( g_send_package_socket ); timer_poll (); main_TcpNet (); if( stat == TCP_STATE_CONNECT ) break; } #endif break; } if( stat == TCP_STATE_CONNECT ) { while(tcp_check_send ( g_send_package_socket) != __TRUE) { timer_poll (); main_TcpNet (); } if (tcp_check_send ( g_send_package_socket) == __TRUE) { sendbuf = tcp_get_buf( buf_size ); memcpy( sendbuf, buf, buf_size ); tcp_send ( g_send_package_socket, sendbuf, buf_size); #if 1 return 1; #else while( 1 ){ stat = tcp_get_state( g_send_package_socket ); timer_poll (); main_TcpNet (); if( stat == TCP_STATE_CONNECT ) break; } #endif } } else{ return -3; } } else return -4; return -5; }
short verify(char *public_key, char *document, char *signature){ gcry_error_t error; gcry_mpi_t r_mpi; if ((error = gcry_mpi_scan(&r_mpi, GCRYMPI_FMT_HEX, document, 0, NULL))) { printf("Error in gcry_mpi_scan() in encrypt(): %s\nSource: %s\n", gcry_strerror(error), gcry_strsource(error)); exit(1); } gcry_sexp_t data; size_t erroff; if ((error = gcry_sexp_build(&data, &erroff, "(data (flags raw) (value %m))", r_mpi))) { printf("Error in gcry_sexp_build() in sign() at %ld: %s\nSource: %s\n", erroff, gcry_strerror(error), gcry_strsource(error)); exit(1); } gcry_sexp_t sig = sexp_new(signature); gcry_sexp_t public_sexp = sexp_new(public_key); short good_sig = 1; struct timeval timer; timer_start(&timer); if ((error = gcry_pk_verify(sig, data, public_sexp))) { if (gcry_err_code(error) != GPG_ERR_BAD_SIGNATURE) { printf("Error in gcry_pk_verify(): %s\nSource: %s\n", gcry_strerror(error), gcry_strsource(error)); exit(1); } good_sig = 0; } timer_poll("libgcrypt Verify: %d.%06d seconds\n", &timer); return good_sig; }
char* sign(char *private_key, char *document){ gcry_error_t error; gcry_mpi_t r_mpi; if ((error = gcry_mpi_scan(&r_mpi, GCRYMPI_FMT_HEX, document, 0, NULL))) { printf("Error in gcry_mpi_scan() in encrypt(): %s\nSource: %s\n", gcry_strerror(error), gcry_strsource(error)); exit(1); } gcry_sexp_t data; size_t erroff; if ((error = gcry_sexp_build(&data, &erroff, "(data (flags raw) (value %m))", r_mpi))) { printf("Error in gcry_sexp_build() in sign() at %ld: %s\nSource: %s\n", erroff, gcry_strerror(error), gcry_strsource(error)); exit(1); } gcry_sexp_t private_sexp = sexp_new(private_key); gcry_sexp_t r_sig; struct timeval timer; timer_start(&timer); if ((error = gcry_pk_sign(&r_sig, data, private_sexp))) { printf("Error in gcry_pk_sign(): %s\nSource: %s\n", gcry_strerror(error), gcry_strsource(error)); exit(1); } timer_poll("libgcrypt Sign: %d.%06d seconds\n", &timer); return sexp_string(r_sig); }
char* decrypt(char *private_key, char *ciphertext){ gcry_error_t error; gcry_sexp_t data = sexp_new(ciphertext); gcry_sexp_t private_sexp = sexp_new(private_key); gcry_sexp_t r_plain; struct timeval timer; timer_start(&timer); if ((error = gcry_pk_decrypt(&r_plain, data, private_sexp))) { printf("Error in gcry_pk_decrypt(): %s\nSource: %s\n", gcry_strerror(error), gcry_strsource(error)); exit(1); } timer_poll("\nSoftware decrypt: %d.%06d seconds\n", &timer); gcry_mpi_t r_mpi = gcry_sexp_nth_mpi(r_plain, 0, GCRYMPI_FMT_USG); unsigned char *plaintext; size_t plaintext_size; if ((error = gcry_mpi_aprint(GCRYMPI_FMT_HEX, &plaintext, &plaintext_size, r_mpi))) { printf("Error in gcry_mpi_aprint(): %s\nSource: %s\n", gcry_strerror(error), gcry_strsource(error)); exit(1); } // Return type hack return (char *) plaintext; }
char* encrypt(rsa_packet * packet, char *public_key, char *plaintext){ gcry_error_t error; gcry_mpi_t r_mpi; if ((error = gcry_mpi_scan(&r_mpi, GCRYMPI_FMT_HEX, plaintext, 0, NULL))) { printf("Error in gcry_mpi_scan() in encrypt(): %s\nSource: %s\n", gcry_strerror(error), gcry_strsource(error)); exit(1); } gcry_sexp_t data; size_t erroff; if ((error = gcry_sexp_build(&data, &erroff, "(data (flags raw) (value %m))", r_mpi))) { printf("Error in gcry_sexp_build() in encrypt() at %ld: %s\nSource: %s\n", erroff, gcry_strerror(error), gcry_strsource(error)); exit(1); } gcry_sexp_t public_sexp = sexp_new(public_key); gcry_sexp_t r_ciph; struct timeval timer; timer_start(&timer); if ((error = gcry_pk_encrypt(&r_ciph, data, public_sexp))) { printf("Error in gcry_pk_encrypt(): %s\nSource: %s\n", gcry_strerror(error), gcry_strsource(error)); exit(1); } timer_poll("\nSoftware encrypt: %d.%06d seconds\n", &timer); gcry_sexp_t cipher_sexp = gcry_sexp_cdr(gcry_sexp_find_token(r_ciph, "a", 1)); gcry_mpi_t cipher_mpi = gcry_sexp_nth_mpi(cipher_sexp, 0, GCRYMPI_FMT_USG); gcry_mpi_print(GCRYMPI_FMT_USG, packet->ciphertext, 256, &packet->cipher_len, cipher_mpi); return sexp_string(r_ciph); }
int main(int argc, char** argv) { struct heaptimer_t* timer; struct task_t* t; struct task_step_t* t1, *t2, *t3; struct timeval timeout; struct timeval tv; int32_t loop = argc > 1 ? atoi(argv[1]) : 3; cp = curl_pool_init(); assert(cp); timer = timer_init(); assert(timer); t = task_init(on_success, on_fail, (void*)&loop); assert(t); t1 = task_step_init(t1_run); assert(t1); task_push_back_step(t, t1); id = task_step_id(t1); t2 = task_step_init(t2_run); assert(t2); task_push_back_step(t, t2); t3 = task_step_init(t3_run); assert(t3); task_push_back_step(t, t3); timeout.tv_sec = 1; timeout.tv_usec = 0; task_run(t, timer, &timeout); while (1) { if (curl_pool_running_count(cp) > 0) { curl_pool_run(cp); } util_gettimeofday(&tv, NULL); timer_poll(timer, &tv); if (task_finished(t) == 0) { break; } } task_release(t); timer_release(timer); curl_pool_release(cp); return 0; }
/* the main loop that needs to be run at least 200 times per second. */ void doMessenger(Messenger *m) { networking_poll(); doDHT(); doLossless_UDP(); doNetCrypto(); doInbound(m); doFriends(m); timer_poll(); }
int main (void) { /* Main Thread of the TcpNet */ init (); LEDrun = __TRUE; dhcp_tout = DHCP_TOUT; while (1) { timer_poll (); main_TcpNet (); dhcp_check (); blink_led (); } }
void poll(struct ctx_server* hs) { /* this will trigger any scheduled timer callbacks */ timer_poll(); /* handle console input */ console_poll(); /* wl api 'tick' */ wl_tick(timer_get_ms()); /* lwip driver poll */ wlif_poll(hs->net_cfg.netif); if (initSpiComplete) spi_poll(hs->net_cfg.netif); #ifdef WITH_GUI gui_exec(timer_get_ms()); #endif }
int main(void) { wl_err_t wl_status; int status; struct ctx_server *hs; enum wl_host_attention_mode mode; startup_init(); board_init(); led_init(); tc_init(); delay_init(FOSC0); #ifdef _TEST_SPI_ for (;;) { /* handle console input */ console_poll(); spi_poll(NULL); } #else printk("Arduino Wifi Startup... [%s]\n", timestamp); size_t size_ctx_server = sizeof(struct ctx_server); hs = calloc(1, size_ctx_server); ASSERT(hs, "out of memory"); size_t size_netif = sizeof(struct netif); hs->net_cfg.netif = calloc(1, size_netif); ASSERT(hs->net_cfg.netif, "out of memory"); hs->net_cfg.dhcp_enabled = INIT_IP_CONFIG; INFO_INIT("hs:%p size:0x%x netif:%p size:0x%x\n", hs, size_ctx_server, hs->net_cfg.netif, size_netif); initShell(hs); timer_init(NULL, NULL); lwip_init(); status = fw_download_init(); ASSERT(status == 0, "failed to prepare for firmware download\n"); wl_status = wl_transport_init(fw_read_cb, hs, &mode); if (wl_status != WL_SUCCESS) goto err; INFO_INIT("Mode: 0x%x\n", mode); wl_status = wl_init(hs, wl_init_complete_cb, mode); if (wl_status != WL_SUCCESS) goto err; /* start main loop */ for (;;) poll(hs); err: /* show error message on console and display if wlan initialization fails */ #define WL_CARD_FAILURE_STR "Could not detect wl device, aborting\n" #define WL_FIRMWARE_INVALID_STR "Invalid firmware data, aborting\n" #define WL_OTHER_FAILURE_STR "Failed to start wl initialization\n" switch (wl_status) { case WL_CARD_FAILURE: printk(WL_CARD_FAILURE_STR); break; case WL_FIRMWARE_INVALID: printk(WL_FIRMWARE_INVALID_STR); break; default: printk(WL_OTHER_FAILURE_STR); break; } for (;;) { timer_poll(); } #endif }
/* Calls the timing functions ------------------------------------------------*/ void BFH_GLCD_UDP (void) { #if (USE_UDP == 1) timer_poll (); main_TcpNet (); #endif }
int main(int argc, char* argv[]) { rsa_packet packet; int i; bool cipher_done = 0; Command cmd; timeval hard_time; int sceMiVersion = SceMi::Version( SCEMI_VERSION_STRING ); SceMiParameters params("scemi.params"); SceMi *sceMi = SceMi::Init(sceMiVersion, ¶ms); // Initialize the crypto library crypto_init(); // Initialize the SceMi inport InportProxyT<Command> inport ("", "scemi_rsaxactor_req_inport", sceMi); // Initialize the SceMi outport OutportQueueT<BIG_INT> outport ("", "scemi_rsaxactor_resp_outport", sceMi); ResetXactor reset("", "scemi", sceMi); ShutdownXactor shutdown("", "scemi_shutdown", sceMi); // Service SceMi requests SceMiServiceThread *scemi_service_thread = new SceMiServiceThread (sceMi); reset.reset(); char *test_texts[] = { "deadbeef" , "badf00d" , "0ff1ce" , "cafe" , "defaced" , "aeb45a0ee831ad6e538f9c59300290db92696abbaa06a0b1df6ca317239292160d81f220c99bd788cce66cc41033e2c3eddb" , "46f4ef8bf4cf769bc5ab709267981dbb44801f9c419e99a2fc7639baaf6de6741cee37af64d5d50c87402713505cb51a88fb" , "4d889e31f9a92bd62df29e16047beb747fc92e3eceebab44d399b386825d1f55294f6d854e56d0f9a7b610c67b2ae7b5e5bd36" , "8ecbff22d54c29902bda135826fd302787742d4ce7a064f73c4ecca822235035fbdf1350bb7d9abcb4f54eb3257f2c96798d2e" , "853493ee4fd1fe0cde743cba9b180bff20bd457c152e258b9e3b478bd25fa60a6766b8d36a95885c2c47aaa63f22ff93ebea08" , "050e383b35f7688879a54ef463961533f040f943467b6a5617fdf88000c91c662d0688ddd5144f12c49106d8d81a5e04ff5ca2" , "f355db88fb426ebea4a551ad129d4fcb243b903411e638a08a81e22bfe250937f1194caea4d1f312f06ecfa906d79e8c948a0d" , "11d1e35094599325a2122f2f919a64e4d4ace48812f192ea7c11410c539707149c5d335f921f132d11795bcc1ebbf4a20b65e9" , "7b101a938d50b8dc88780235f226bc1c6650df830c3290565e12d6b9c347c06b1fb0b6fb2e648019c8526e2d4adc4dc766dba5" , "7305d1b0e93f54de5fa19eb1089fa6fbc566f8479cd381ca5894492c3078d23ef3d7a1923b9a96ffb7bf2b727fc28c6d522e54" , "4228043134c88aed152a8cd0d9aef45f742e6d12511d0ecbfbf34ea593998c499f19c6315e8779184ab58dd8e731a25d410d61" , "c04bb261996776e003d70116c3d7d56c6e2375f349983d478416f6600edeec1dbc286d4a57445be4ded180dcb7e157b35a8a4f" , "eac2be8a8e3ef31a292c4faafa9c8a63acf1e4046672c5379215f6f145ce2062ace5587f3ea226f628178426062dd9ff81186c" , "c3387e260634be9995b52c1f7114cf23d01cce8ef598cc8e5364db272aee60d06e626a2a67964d7391d5ed5c7193ab36eba81e" , "ac84645df2aaca9dee4d03e8b900007905f9bfe93bbef391ea7b57513948ec88b252add18db987b0ff886e1c7d25152f7dc1af" , "7176de621be4b8d4f5060b6ae0ab188d2c33f3aeddaddbe639cd89a8ca5784a8cdb0135108eb7f35020556795764c71536b49e" , "1a3f9f30e4c3d5d244c1d9e6cfb8f4dd47f686efb74e99de63358750e6f0622b24afc212a472bf9a93b0d39e79ff4a71ee57c6" , "68a9101d17cadfa1d89353a1d12d878dede2630904fbd8bf08ee36ccaa3c2b1759415ec3fe54bfa9f1034c5a20d01673fa06f6" , "31206814135169d02ec6893064bcaab54d9a2cc44fedc5e16dba2d97adca09fd6838af21e06def28a3815dccae369ce1e2f4af" , "f536b2e57395c6421008095dc6832282d8083ac466debc88f5979e8ada0e0b4820754f0325de29d77c46eada3683bb5be3fd10" }; for (int tests = 0; tests < 20; tests++) { char *public_key, *private_key; printf("Generating keypair in software..."); generate_key(&packet, &public_key, &private_key); #ifdef DEFINE printf("Raw data dump\n Modulus length: %zi\n", packet.mod_len); for(i = 0; i < packet.mod_len; i++) { printf("%02X", packet.mod[i]); } printf("\nPrivate exponent length: %zi\n", packet.priv_len); for(i = 0; i < packet.priv_len; i++) { printf("%02X", packet.priv_exp[i]); } printf("\nPublic exponent length: %zi\n", packet.pub_len); for(i = 0; i < packet.pub_len; i++) { printf("%02X", packet.pub_exp[i]); } #endif printf("Public Key:\n%s\n", public_key); printf("Private Key:\n%s\n", private_key); char *plaintext = test_texts[tests]; printf("Plain Text:\n%s\n\n", plaintext); char *ciphertext; ciphertext = encrypt(&packet, public_key, plaintext); printf("Software-calculated cipher Text:\n%s\n", ciphertext); printf("\nCiphertext length: %zi\n", packet.cipher_len); for(i = 0; i < packet.cipher_len; i++) { printf("%02X", packet.ciphertext[i]); } char *decrypted; decrypted = decrypt(private_key, ciphertext); printf("\nSoftware-decrypted plain Text:\n%s\n\n", decrypted); /*char *signature; signature = sign(private_key, plaintext); printf("Software signature:\n%s\n", signature); if (verify(public_key, plaintext, signature)) { printf("Software signature GOOD!\n"); } else { printf("Software signature BAD!\n"); }*/ printf("Sending to FPGA..\n"); // Pack the command for transport to FPGA // Command is specified in Command.h, run build and look in tbinclude // Assuming mod_len >= priv_len/pub_len/len(ciphertext) for(i = 0; i < packet.mod_len; i++) { cmd.m_modulus = packet.mod[packet.mod_len - i - 1]; // Send the data for decryption if(i < packet.priv_len) { cmd.m_exponent = packet.priv_exp[packet.priv_len - i - 1]; } else { cmd.m_exponent = 0; } // Since the exponent is short, pack it backwards if(i < packet.cipher_len) { cmd.m_data = packet.ciphertext[packet.cipher_len - i - 1]; } else { cmd.m_data = 0; } //printf("Sending message %i, mod: %X coeff: %X data:%X\n", i, cmd.m_data.get(), cmd.m_exponent.get(), cmd.m_data.get()); inport.sendMessage(cmd); } printf("Sending padding, 1 packet"); cmd.m_modulus = 0; cmd.m_exponent = 0; cmd.m_data = 0; timer_start(&hard_time); inport.sendMessage(cmd); printf("Getting result.."); std::cout << "Result: " << outport.getMessage() << std::endl; timer_poll("FPGA wall time: %d.%06d seconds\n", &hard_time); } std::cout << "shutting down..." << std::endl; shutdown.blocking_send_finish(); scemi_service_thread->stop(); scemi_service_thread->join(); SceMi::Shutdown(sceMi); std::cout << "finished" << std::endl; return 0; }
int test_logic_task(const char* param) { timerheap_t* timer = timer_create_heap(); if (!timer) { fprintf(stderr, "timer create fail\n"); return -1; } _curl_pool = curlp_create(); if (!_curl_pool) { fprintf(stderr, "curl create fail\n"); timer_release(timer); return -1; } task_t* t = task_create(on_success, on_fail, NULL); if (!t) { fprintf(stderr, "task create fail\n"); timer_release(timer); curlp_release(_curl_pool); return -1; } struct timeval timeout; struct timeval tv; t1_param_t p; p.loop = (param ? atoi(param) : 3); task_step_t* t1 = task_step_create(t1_run, (void*)&p); task_step_t* t2 = task_step_create(t2_run, NULL); task_step_t* t3 = task_step_create(t3_run, NULL); if (!t1 || !t2 || !t3) { fprintf(stderr, "task step create fail\n"); if (t1) task_step_release(t1); if (t2) task_step_release(t2); if (t3) task_step_release(t3); task_release(t); timer_release(timer); curlp_release(_curl_pool); return -1; } task_push_back_step(t, t1); _task_step_id = task_step_id(t1); task_push_back_step(t, t2); task_push_back_step(t, t3); timeout.tv_sec = 3; timeout.tv_usec = 0; task_run(t, timer, &timeout); while (1) { if (curlp_running_count(_curl_pool) > 0) { curlp_poll(_curl_pool); } gettimeofday(&tv, NULL); timer_poll(timer, &tv); if (task_is_finished(t) == 0) { break; } } task_release(t); timer_release(timer); curlp_release(_curl_pool); return 0; }
/* We need this */ int main(int argc, char *argv[]) { int optc, show_help, show_version, show_usage; char *local_file, *cmd_listen_port, *cmd_pid_file; int inetd_mode, no_daemon; /* Set up some globals */ progname = argv[0]; listen_port = x_strdup(DEFAULT_LISTEN_PORT); pid_file = (DEFAULT_PID_FILE ? x_strdup(DEFAULT_PID_FILE) : 0); #ifndef DEBUG no_daemon = 0; #else /* DEBUG */ no_daemon = 1; #endif /* DEBUG */ local_file = cmd_listen_port = cmd_pid_file = 0; show_help = show_version = show_usage = inetd_mode = 0; while ((optc = getopt_long(argc, argv, GETOPTIONS, long_opts, NULL)) != -1) { switch (optc) { case 'h': show_help = 1; break; case 'v': show_version = 1; break; case 'D': #ifndef DEBUG no_daemon = 1; #else /* DEBUG */ no_daemon = 0; #endif /* DEBUG */ break; case 'I': inetd_mode = 1; break; case 'P': free(cmd_listen_port); cmd_listen_port = x_strdup(optarg); break; case 'p': free(cmd_pid_file); cmd_pid_file = x_strdup(optarg); break; case 'f': free(local_file); local_file = x_strdup(optarg); break; default: show_usage = 1; break; } } if (show_usage || (optind < argc)) { _print_usage(); return 1; } if (show_version) { _print_version(); if (!show_help) return 0; } if (show_help) { _print_help(); return 0; } /* If no -f was specified use the home directory */ if (!local_file && !inetd_mode) { struct stat statinfo; struct passwd *pw; pw = getpwuid(geteuid()); if (pw && pw->pw_dir) { local_file = x_sprintf("%s/%s", pw->pw_dir, USER_CONFIG_FILENAME); debug("Local config file: %s", local_file); if (!stat(local_file, &statinfo) && (statinfo.st_mode & 0077)) { fprintf(stderr, "%s: Permissions of %s must be 0700 or " "more restrictive\n", progname, local_file); free(local_file); return 2; } if (cfg_read(local_file, &listen_port, &pid_file, &g)) { /* If the local one didn't exist, set to 0 so we open global one */ free(local_file); local_file = 0; } else { config_file = x_strdup(local_file); } } } else if (local_file) { if (cfg_read(local_file, &listen_port, &pid_file, &g)) { /* This is fatal! */ fprintf(stderr, "%s: Couldn't read configuration from %s: %s\n", progname, local_file, strerror(errno)); free(local_file); return 2; } else { config_file = x_strdup(local_file); } } /* Read global config file if local one not found */ if (!local_file) { char *global_file; /* Not fatal if it doesn't exist */ global_file = x_sprintf("%s/%s", SYSCONFDIR, GLOBAL_CONFIG_FILENAME); debug("Global config file: %s", global_file); cfg_read(global_file, &listen_port, &pid_file, &g); config_file = x_strdup(global_file); free(global_file); } else { free(local_file); } /* Check we got some connection classes */ if (!connclasses) { fprintf(stderr, "%s: No connection classes have been defined.\n", progname); return 2; } /* -P overrides config file */ if (cmd_listen_port) { free(listen_port); listen_port = cmd_listen_port; } /* -p overrides pid file */ if (cmd_pid_file) { free(pid_file); pid_file = cmd_pid_file; } /* Set signal handlers */ signal(SIGTERM, _sig_term); signal(SIGINT, _sig_term); signal(SIGHUP, _sig_hup); signal(SIGCHLD, _sig_child); #ifdef DEBUG_MEMORY signal(SIGUSR1, _sig_usr); signal(SIGUSR2, _sig_usr); #endif /* DEBUG_MEMORY */ /* Broken Pipe? This means that someone disconnected while we were sending stuff. Naughty! */ signal(SIGPIPE, SIG_IGN); if (!inetd_mode) { debug("Ordinary console dodge-monkey mode"); /* Make listening socket before we fork */ if (ircnet_listen(listen_port)) { fprintf(stderr, "%s: Unable to establish listen port\n", progname); return 3; } /* go daemon here */ if (!no_daemon) { switch (go_daemon()) { case -1: return -1; case 0: break; default: return 0; } } } else { /* running under inetd means we are backgrounded right *now* */ in_background = 1; debug("Inetd SuperTed mode!"); /* Hook STDIN into a new proxy */ ircnet_hooksocket(STDIN_FILENO); } /* Open a connection to syslog if we're in the background */ if (in_background) openlog(PACKAGE, LOG_PID, LOG_USER); if (pid_file) { FILE *pidfile; pidfile = fopen(pid_file, "w"); if (pidfile) { fchmod(fileno(pidfile), 0600); fprintf(pidfile, "%d\n", getpid()); fclose(pidfile); } else { syscall_fail("fopen", pid_file, 0); } } /* Main loop! */ while (!stop_poll) { int ns, nt, status; pid_t pid; ircnet_expunge_proxies(); dccnet_expunge_proxies(); ns = net_poll(); nt = timer_poll(); /* Reap any children */ while ((pid = waitpid(-1, &status, WNOHANG)) > 0) { debug("Reaped process %d, exit status %d", pid, status); /* Handle any DNS children */ dns_endrequest(pid, status); } /* Reload the configuration file? */ if (reload_config) { _reload_config(); reload_config = 0; } if (!ns && !nt) break; } if (pid_file) { unlink(pid_file); } /* Free up stuff */ ircnet_flush(); dccnet_flush(); dns_flush(); timer_flush(); /* Do a lingering close on all sockets */ net_closeall(); net_flush(); /* Close down and free up memory */ if (!inetd_mode && !no_daemon) closelog(); free(listen_port); free(pid_file); free(config_file); #ifdef DEBUG_MEMORY mem_report("termination"); #endif /* DEBUG_MEMORY */ return 0; }