/** * @brief Set the dot the from input * @param this_dot the dot input * @return Void */ void mode_5_input_dot(char this_dot) { last_dot = this_dot; log_msg("In input dot: %x", this_dot); play_dot(this_dot); }
static int festival_speak(char *data, size_t bytes, SPDMessageType msgtype) { int ret; log_msg(OTTS_LOG_NOTICE, "module_speak()\n"); if (festival_speaking) { log_msg(OTTS_LOG_ERR, "Speaking when requested to write\n"); return -1; } festival_stop_request = 0; festival_message_type = msgtype; if ((msgtype == SPD_MSGTYPE_TEXT) && (msg_settings.spelling_mode == SPD_SPELL_ON)) festival_message_type = SPD_MSGTYPE_SPELL; /* If the connection crashed or language or voice change, we will need to set all the parameters again */ if (COM_SOCKET) { if (festival_connection_crashed) { log_msg(OTTS_LOG_NOTICE, "Recovering after a connection loss"); clean_old_settings_table(); festival_info = festivalOpen(festival_info); if (festival_info) festival_connection_crashed = 0; else { log_msg(OTTS_LOG_CRIT, "Can't recover. Not possible to open connection to Festival."); return -1; } ret = FestivalSetMultiMode(festival_info, "t"); if (ret != 0) return -1; } } /* If the voice was changed, re-set all the parameters */ // TODO: Handle synthesis_voice change too if ((msg_settings.voice_type != msg_settings_old.voice_type) || (msg_settings.voice.language != NULL) && (msg_settings_old.voice.language != NULL) && (strcmp (msg_settings.voice.language, msg_settings_old.voice.language))) { log_msg(OTTS_LOG_INFO, "Cleaning old settings table"); clean_old_settings_table(); } /* Setting voice parameters */ log_msg(OTTS_LOG_INFO, "Updating parameters"); UPDATE_STRING_PARAMETER(voice.language, festival_set_language); UPDATE_PARAMETER(voice_type, festival_set_voice); UPDATE_STRING_PARAMETER(voice.name, festival_set_synthesis_voice); UPDATE_PARAMETER(rate, festival_set_rate); UPDATE_PARAMETER(pitch, festival_set_pitch); UPDATE_PARAMETER(volume, festival_set_volume); UPDATE_PARAMETER(punctuation_mode, festival_set_punctuation_mode); UPDATE_PARAMETER(cap_let_recogn, festival_set_cap_let_recogn); if (festival_connection_crashed) { log_msg(OTTS_LOG_ERR, "ERROR: Festival connection not working!"); return -1; } log_msg(OTTS_LOG_DEBUG, "Requested data: |%s| \n", data); g_free(*festival_message); *festival_message = g_strdup(data); /* Send semaphore signal to the speaking thread */ festival_speaking = 1; sem_post(festival_semaphore); log_msg(OTTS_LOG_INFO, "Festival: leaving write() normaly\n\r"); return bytes; }
void add_iface(char *iface) { char errbuf[PCAP_ERRBUF_SIZE]; char const *filter; struct iface_config *ifc; int rc; if (cfg.v4_flag) filter = ip4_filter; else if (cfg.v6_flag) filter = ip6_filter; else filter = def_filter; ifc = (struct iface_config *) calloc(1, sizeof(struct iface_config)); ifc->name = iface; ifc->pcap_handle = pcap_open_live(iface, SNAP_LEN, cfg.promisc_flag, 1000, errbuf); if (ifc->pcap_handle == NULL) { log_msg(LOG_WARNING, "Skipping interface %s, %s", iface, errbuf); goto error; } rc = pcap_datalink(ifc->pcap_handle); if (rc != DLT_EN10MB) { log_msg(LOG_WARNING, "Skipping interface %s, invalid data link layer %s (%s).", iface, pcap_datalink_val_to_name(rc), pcap_datalink_val_to_description(rc)); goto error_pcap; } rc = pcap_compile(ifc->pcap_handle, &ifc->pcap_filter, filter, 0, 0); if (rc == -1) { log_msg(LOG_WARNING, "Skipping interface %s, %s", iface, pcap_geterr(ifc->pcap_handle)); goto error_pcap; } rc = pcap_setfilter(ifc->pcap_handle, &ifc->pcap_filter); if (rc == -1) { log_msg(LOG_WARNING, "Skipping iface %s, %s", iface, pcap_geterr(ifc->pcap_handle)); goto error_filter; } rc = pcap_fileno(ifc->pcap_handle); #if HAVE_LIBEVENT2 ifc->event = event_new(cfg.eb, rc, EV_READ|EV_PERSIST, read_cb, ifc); if(!ifc->event) log_msg(LOG_ERR, "%s: event_new(...)", __FUNCTION__); event_add(ifc->event, NULL); #else event_set(&ifc->event, rc, EV_READ|EV_PERSIST, read_cb, ifc); event_add(&ifc->event, NULL); #endif if (cfg.hashsize < 1 || cfg.hashsize > 65536) log_msg(LOG_ERR, "%s: hash size (%d) must be >= 1 and <= 65536", __FUNCTION__, cfg.hashsize); if (cfg.ratelimit) { ifc->cache = calloc(cfg.hashsize, sizeof(*ifc->cache)); if (!ifc->cache) log_msg(LOG_ERR, "%s: unable to allocate memory for hash cache", __FUNCTION__); } ifc->next = cfg.interfaces; cfg.interfaces = ifc; log_msg(LOG_DEBUG, "Opened interface %s (%s)", iface, pcap_datalink_val_to_description(pcap_datalink(ifc->pcap_handle))); return; error_filter: pcap_freecode(&ifc->pcap_filter); error_pcap: pcap_close(ifc->pcap_handle); error: free(ifc); }
static int comment_match_exists(const fko_srv_options_t *opts) { int res = 1; char *ndx = NULL; struct fw_chain *in_chain = &(opts->fw_config->chain[IPT_INPUT_ACCESS]); zero_cmd_buffers(); /* Add a harmless rule to the iptables OUTPUT chain that uses the comment * match and make sure it exists. If not, return zero. Otherwise, delete * the rule and return true. */ snprintf(cmd_buf, CMD_BUFSIZE-1, "%s " IPT_TMP_COMMENT_ARGS, opts->fw_config->fw_command, in_chain->table, in_chain->to_chain, 1, /* first rule */ in_chain->target ); res = run_extcmd(cmd_buf, err_buf, CMD_BUFSIZE, 0); if (opts->verbose) log_msg(LOG_INFO, "comment_match_exists() CMD: '%s' (res: %d, err: %s)", cmd_buf, res, err_buf); zero_cmd_buffers(); snprintf(cmd_buf, CMD_BUFSIZE-1, "%s " IPT_LIST_RULES_ARGS, opts->fw_config->fw_command, in_chain->table, in_chain->to_chain ); res = run_extcmd(cmd_buf, cmd_out, STANDARD_CMD_OUT_BUFSIZE, 0); if(!EXTCMD_IS_SUCCESS(res)) log_msg(LOG_ERR, "Error %i from cmd:'%s': %s", res, cmd_buf, cmd_out); ndx = strstr(cmd_out, TMP_COMMENT); if(ndx == NULL) res = 0; /* did not find the tmp comment */ else res = 1; if(res == 1) { /* Delete the tmp comment rule */ zero_cmd_buffers(); snprintf(cmd_buf, CMD_BUFSIZE-1, "%s " IPT_DEL_RULE_ARGS, opts->fw_config->fw_command, in_chain->table, in_chain->to_chain, 1 ); run_extcmd(cmd_buf, err_buf, CMD_BUFSIZE, 0); } return res; }
/* Iterate over the configure firewall access chains and purge expired * firewall rules. */ void check_firewall_rules(const fko_srv_options_t *opts) { char exp_str[12]; char rule_num_str[6]; char *ndx, *rn_start, *rn_end, *tmp_mark; int i, res, rn_offset; time_t now, rule_exp, min_exp = 0; struct fw_chain *ch = opts->fw_config->chain; time(&now); /* Iterate over each chain and look for active rules to delete. */ for(i = 0; i < NUM_FWKNOP_ACCESS_TYPES; i++) { /* If there are no active rules or we have not yet * reached our expected next expire time, continue. */ if(ch[i].active_rules == 0 || ch[i].next_expire > now) continue; zero_cmd_buffers(); rn_offset = 0; /* There should be a rule to delete. Get the current list of * rules for this chain and delete the ones that are expired. */ snprintf(cmd_buf, CMD_BUFSIZE-1, "%s " IPT_LIST_RULES_ARGS, opts->fw_config->fw_command, ch[i].table, ch[i].to_chain ); res = run_extcmd(cmd_buf, cmd_out, STANDARD_CMD_OUT_BUFSIZE, 0); if (opts->verbose) log_msg(LOG_INFO, "check_firewall_rules() CMD: '%s' (res: %d, err: %s)", cmd_buf, res, err_buf); if(!EXTCMD_IS_SUCCESS(res)) { log_msg(LOG_ERR, "Error %i from cmd:'%s': %s", res, cmd_buf, cmd_out); continue; } if(opts->verbose > 1) log_msg(LOG_INFO, "RES=%i, CMD_BUF: %s\nRULES LIST: %s", res, cmd_buf, cmd_out); ndx = strstr(cmd_out, EXPIRE_COMMENT_PREFIX); if(ndx == NULL) { /* we did not find an expected rule. */ log_msg(LOG_ERR, "Did not find expire comment in rules list %i.\n", i); if (ch[i].active_rules > 0) ch[i].active_rules--; continue; } /* walk the list and process rules as needed. */ while (ndx != NULL) { /* Jump forward and extract the timestamp */ ndx += strlen(EXPIRE_COMMENT_PREFIX); /* remember this spot for when we look for the next * rule. */ tmp_mark = ndx; strlcpy(exp_str, ndx, 11); rule_exp = (time_t)atoll(exp_str); if(rule_exp <= now) { /* Backtrack and get the rule number and delete it. */ rn_start = ndx; while(--rn_start > cmd_out) { if(*rn_start == '\n') break; } if(*rn_start != '\n') { /* This should not happen. But if it does, complain, * decrement the active rule value, and go on. */ log_msg(LOG_ERR, "Rule parse error while finding rule line start in chain %i", i); if (ch[i].active_rules > 0) ch[i].active_rules--; break; } rn_start++; rn_end = strchr(rn_start, ' '); if(rn_end == NULL) { /* This should not happen. But if it does, complain, * decrement the active rule value, and go on. */ log_msg(LOG_ERR, "Rule parse error while finding rule number in chain %i", i); if (ch[i].active_rules > 0) ch[i].active_rules--; break; } strlcpy(rule_num_str, rn_start, (rn_end - rn_start)+1); zero_cmd_buffers(); snprintf(cmd_buf, CMD_BUFSIZE-1, "%s " IPT_DEL_RULE_ARGS, opts->fw_config->fw_command, ch[i].table, ch[i].to_chain, atoi(rule_num_str) - rn_offset ); res = run_extcmd(cmd_buf, err_buf, CMD_BUFSIZE, 0); if (opts->verbose) log_msg(LOG_INFO, "check_firewall_rules() CMD: '%s' (res: %d, err: %s)", cmd_buf, res, err_buf); if(EXTCMD_IS_SUCCESS(res)) { log_msg(LOG_INFO, "Removed rule %s from %s with expire time of %u.", rule_num_str, ch[i].to_chain, rule_exp ); rn_offset++; if (ch[i].active_rules > 0) ch[i].active_rules--; } else log_msg(LOG_ERR, "Error %i from cmd:'%s': %s", res, cmd_buf, err_buf); } else { /* Track the minimum future rule expire time. */ if(rule_exp > now) min_exp = (min_exp < rule_exp) ? min_exp : rule_exp; } /* Push our tracking index forward beyond (just processed) _exp_ * string so we can continue to the next rule in the list. */ ndx = strstr(tmp_mark, EXPIRE_COMMENT_PREFIX); } /* Set the next pending expire time accordingly. 0 if there are no * more rules, or whatever the next expected (min_exp) time will be. */ if(ch[i].active_rules < 1) ch[i].next_expire = 0; else if(min_exp) ch[i].next_expire = min_exp; } }
int verify_file_perms_ownership(const char *file) { int res = 1; #if HAVE_STAT struct stat st; /* Every file that the fwknop client deals with should be owned * by the user and permissions set to 600 (user read/write) */ if((stat(file, &st)) == 0) { /* Make sure it is a regular file */ if(S_ISREG(st.st_mode) != 1 && S_ISLNK(st.st_mode) != 1) { log_msg(LOG_VERBOSITY_ERROR, "[-] file: %s is not a regular file or symbolic link.", file ); /* when we start in enforcing this instead of just warning * the user res = 0; */ } if((st.st_mode & (S_IRWXU|S_IRWXG|S_IRWXO)) != (S_IRUSR|S_IWUSR)) { log_msg(LOG_VERBOSITY_ERROR, "[-] file: %s permissions should only be user read/write (0600, -rw-------)", file ); /* when we start in enforcing this instead of just warning * the user res = 0; */ } if(st.st_uid != getuid()) { log_msg(LOG_VERBOSITY_ERROR, "[-] file: %s not owned by current effective user id", file); /* when we start in enforcing this instead of just warning * the user res = 0; */ } } else { /* if the path doesn't exist, just return, but otherwise something * went wrong */ if(errno != ENOENT) { log_msg(LOG_VERBOSITY_ERROR, "[-] stat() against file: %s returned: %s", file, strerror(errno)); res = 0; } } #endif return res; }
/* Print all firewall rules currently instantiated by the running fwknopd * daemon to stdout. */ int fw_dump_rules(const fko_srv_options_t *opts) { int i; int res, got_err = 0; struct fw_chain *ch = opts->fw_config->chain; if (opts->fw_list_all == 1) { fprintf(stdout, "Listing all iptables rules in applicable tables...\n"); fflush(stdout); for(i=0; i<(NUM_FWKNOP_ACCESS_TYPES); i++) { if(fwc.chain[i].target[0] == '\0') continue; zero_cmd_buffers(); /* Create the list command */ snprintf(cmd_buf, CMD_BUFSIZE-1, "%s " IPT_LIST_ALL_RULES_ARGS, opts->fw_config->fw_command, ch[i].table ); res = system(cmd_buf); if (opts->verbose) log_msg(LOG_INFO, "fw_dump_rules() CMD: '%s' (res: %d)", cmd_buf, res); /* Expect full success on this */ if(! EXTCMD_IS_SUCCESS(res)) { log_msg(LOG_ERR, "Error %i from cmd:'%s': %s", res, cmd_buf, err_buf); got_err++; } } } else { fprintf(stdout, "Listing rules in fwknopd iptables chains...\n"); fflush(stdout); for(i=0; i<(NUM_FWKNOP_ACCESS_TYPES); i++) { if(fwc.chain[i].target[0] == '\0') continue; zero_cmd_buffers(); /* Create the list command */ snprintf(cmd_buf, CMD_BUFSIZE-1, "%s " IPT_LIST_RULES_ARGS, opts->fw_config->fw_command, ch[i].table, ch[i].to_chain ); fprintf(stdout, "\n"); fflush(stdout); res = system(cmd_buf); if (opts->verbose) log_msg(LOG_INFO, "fw_dump_rules() CMD: '%s' (res: %d)", cmd_buf, res); /* Expect full success on this */ if(! EXTCMD_IS_SUCCESS(res)) { log_msg(LOG_ERR, "Error %i from cmd:'%s': %s", res, cmd_buf, err_buf); got_err++; } } } return(got_err); }
void updateSharedGold(DWORD goldAmount) { Unit* ptChar = D2GetClientPlayer(); log_msg("SharedGold = %d\n",goldAmount); PCPY->sharedGold = goldAmount; }
static int fl_audio_init(char **status_info) { log_msg(OTTS_LOG_WARN, "Opening audio"); return module_audio_init_spd(status_info); }
int main(int argc, char *argv[]) { char *file = NULL; char c; int daemon = 0; int rc = OK; if (getuid() != 0) { fprintf(stderr, "Run me as root please\n"); return 1; } while ((c = getopt(argc, argv, "c:dvh")) != EOF) { switch (c) { case 'c': file = strdup(optarg); if (file == NULL) { fprintf(stderr, "Failed to alloc memory\n"); exit(1); } break; case 'd': daemon++; break; case 'v': show_version(); exit(0); break; case 'h': usage(argv[0]); exit(0); break; default: usage(argv[0]); exit(1); } } init_filter(); set_conf_file(file); parse_conf(); rc = init_log(); if (rc != OK) { fprintf(stderr, "Failed to open log file \n"); return 1; } ip_socket_fd = ip_socket(); if (ip_socket_fd < 0) { fprintf(stderr, "Failed to create raw socket \n"); return 1; } rc = create_pipe(&ip_pipe_in_fd, &ip_pipe_out_fd); if (rc != OK) { fprintf(stderr, "Failed to create net pipe \n"); return 1; } rc = create_pipe(&cmd_pipe_in_fd, &cmd_pipe_out_fd); if (rc != OK) { fprintf(stderr, "Failed to create cmd pipe \n"); return 1; } log_msg(LOG_WARN, "Icmp Knock daemon %s started", version); /* Go daemon mode */ if (daemon) { switch (fork()) { case -1: fprintf(stderr, "fork(): call failed \n"); return 3; case 0: close(STDIN_FILENO); close(STDOUT_FILENO); close(STDERR_FILENO); if (setsid() == -1) { exit(1); } break; default : return 0; } } parent_pid = getpid(); child_pid = fork(); switch (child_pid) { case -1: fprintf(stderr, "fork(): call failed \n"); return 1; break; case 0: agent_main(); break; default : principal_main(); break; } return OK; }
int do_capture(void) { pcap_t *adhandle; char errbuf[PCAP_ERRBUF_SIZE]; struct bpf_program fcode; char buf[512]; struct pcap_pkthdr *header; const u_char *data; int res; int svindex=0; if ((adhandle=pcap_open_live(config.device, 65536, 1, 1000, errbuf)) == NULL) { //MessageBox(0, errbuf, "Error", MB_OK); log_msg("dbg", "pcap_open_live failed opening device: %s\r\n", config.device); //pcap_freealldevs(alldevs); return -2; } if (strcmp("Chronos", config.server) == 0) { svindex = 0; } else if (strcmp("Naia", config.server) == 0) { svindex = 1; } sprintf(buf, "tcp and ip host %s", _servers[svindex]); if (pcap_compile(adhandle, &fcode, buf, 1, 0xffffffff) < 0) { //MessageBox(0, "Error compiling pcap filter.", "Error", MB_OK); log_msg("dbg", "error compiling pcap filter.\r\n"); pcap_close(adhandle); //pcap_freealldevs(alldevs); return -3; } if (pcap_setfilter(adhandle, &fcode) < 0) { //MessageBox(0, "Error setting pcap filter.", "Error", MB_OK); log_msg("dbg", "error setting pcap filter.\r\n"); pcap_close(adhandle); //pcap_freealldevs(alldevs); return -4; } log_msg("dbg", "Listening on %s...\r\n", config.device); //pcap_freealldevs(alldevs); stopcapturing = 0; _svstream = open_stream(); _clstream = open_stream(); _isfirst = 1; _svbufsize = 0; _clbufsize = 0; while ((res=pcap_next_ex(adhandle, &header, &data)) >= 0 && !stopcapturing) { if (res == 0) { continue; } handle_raw_packet(header, data); } log_msg("dbg", "Stopped capture.\r\n"); close_stream(_svstream); close_stream(_clstream); _svstream = 0; _clstream = 0; pcap_close(adhandle); return 0; }
/* Fork off and run a "dummy" TCP server. The return value is the PID of * the child process or -1 if there is a fork error. */ int run_tcp_server(fko_srv_options_t *opts) { pid_t pid, ppid; int s_sock, c_sock, sfd_flags, clen, selval; int reuse_addr = 1, is_err; fd_set sfd_set; struct sockaddr_in saddr, caddr; struct timeval tv; char sipbuf[MAX_IPV4_STR_LEN] = {0}; unsigned short port; port = strtol_wrapper(opts->config[CONF_TCPSERV_PORT], 0, MAX_PORT, NO_EXIT_UPON_ERR, &is_err); if(is_err != FKO_SUCCESS) { log_msg(LOG_ERR, "[*] Invalid max TCPSERV_PORT value."); exit(EXIT_FAILURE); } log_msg(LOG_INFO, "Kicking off TCP server to listen on port %i.", port); /* Fork off a child process to run the command and provide its outputs. */ pid = fork(); /* Non-zero pid means we are the parent or there was a fork error. * in either case we simply return that value to the caller. */ if (pid != 0) { opts->tcp_server_pid = pid; return(pid); } /* Get our parent PID so we can periodically check for it. We want to * know when it goes away so we can to. */ ppid = getppid(); /* We are the child. The first thing to do is close our copy of the * parent PID file so we don't end up holding the lock if the parent * suffers a sudden death that doesn't take us out too. */ close(opts->lock_fd); /* Now, let's make a TCP server */ if ((s_sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0) { log_msg(LOG_ERR, "run_tcp_server: socket() failed: %s", strerror(errno)); exit(EXIT_FAILURE); } /* So that we can re-bind to it without TIME_WAIT problems */ if(setsockopt(s_sock, SOL_SOCKET, SO_REUSEADDR, &reuse_addr, sizeof(reuse_addr)) == -1) { log_msg(LOG_ERR, "run_tcp_server: setsockopt error: %s", strerror(errno)); exit(EXIT_FAILURE); } /* Make our main socket non-blocking so we don't have to be stuck on * listening for incoming connections. */ if((sfd_flags = fcntl(s_sock, F_GETFL, 0)) < 0) { log_msg(LOG_ERR, "run_tcp_server: fcntl F_GETFL error: %s", strerror(errno)); exit(EXIT_FAILURE); } sfd_flags |= O_NONBLOCK; if(fcntl(s_sock, F_SETFL, sfd_flags) < 0) { log_msg(LOG_ERR, "run_tcp_server: fcntl F_SETFL error setting O_NONBLOCK: %s", strerror(errno)); exit(EXIT_FAILURE); } /* Construct local address structure */ memset(&saddr, 0, sizeof(saddr)); saddr.sin_family = AF_INET; /* Internet address family */ saddr.sin_addr.s_addr = htonl(INADDR_ANY); /* Any incoming interface */ saddr.sin_port = htons(port); /* Local port */ /* Bind to the local address */ if (bind(s_sock, (struct sockaddr *) &saddr, sizeof(saddr)) < 0) { log_msg(LOG_ERR, "run_tcp_server: bind() failed: %s", strerror(errno)); exit(EXIT_FAILURE); } /* Mark the socket so it will listen for incoming connections * (but only one at a time) */ if (listen(s_sock, 1) < 0) { log_msg(LOG_ERR, "run_tcp_server: listen() failed: %s", strerror(errno)); exit(EXIT_FAILURE); } clen = sizeof(caddr); /* Now loop and accept and drop connections after the first packet or a * short timeout. */ while(1) { /* Initialize and setup the socket for select. */ FD_ZERO(&sfd_set); FD_SET(s_sock, &sfd_set); /* Set our select timeout to 200 ms. */ tv.tv_sec = 0; tv.tv_usec = 200000; selval = select(s_sock+1, &sfd_set, NULL, NULL, &tv); if(selval == -1) { /* Select error - so kill the child and bail. */ log_msg(LOG_ERR, "run_tcp_server: select error socket: %s", strerror(errno)); exit(EXIT_FAILURE); } if(selval == 0) { /* Timeout - So we check to make sure our parent is still there by simply * using kill(ppid, 0) and checking the return value. */ if(kill(ppid, 0) != 0 && errno == ESRCH) exit(EXIT_FAILURE); continue; } /* Wait for a client to connect */ if((c_sock = accept(s_sock, (struct sockaddr *) &caddr, (socklen_t *)&clen)) < 0) { log_msg(LOG_ERR, "run_tcp_server: accept() failed: %s", strerror(errno)); exit(EXIT_FAILURE); /* Should this be fatal? */ } if(opts->verbose) { memset(sipbuf, 0x0, MAX_IPV4_STR_LEN); inet_ntop(AF_INET, &(caddr.sin_addr.s_addr), sipbuf, MAX_IPV4_STR_LEN); log_msg(LOG_INFO, "tcp_server: Got TCP connection from %s.", sipbuf); } /* Though hacky and clunky, we just sleep for a second then * close the socket. No need to read or write anything. This * just gives the client a sufficient window to send their * request on this socket. In any case the socket is closed * after that time. */ usleep(1000000); shutdown(c_sock, SHUT_RDWR); close(c_sock); } }
static void * audio_cap_jack_init(const char *cfg) { struct state_jack_capture *s; jack_status_t status; const char **ports; int i; if(!cfg || strcmp(cfg, "help") == 0) { audio_cap_jack_help("jack"); return &audio_init_state_ok; } s = (struct state_jack_capture *) calloc(1, sizeof(struct state_jack_capture)); if(!s) { fprintf(stderr, "[JACK capture] Unable to allocate memory.\n"); goto error; } s->client = jack_client_open(PACKAGE_STRING, JackNullOption, &status); if(status & JackFailure) { fprintf(stderr, "[JACK capture] Opening JACK client failed.\n"); goto error; } ports = jack_get_ports(s->client, cfg, NULL, JackPortIsOutput); if(ports == NULL) { fprintf(stderr, "[JACK capture] Unable to output ports matching %s.\n", cfg); goto release_client; } i = 0; while(ports[i]) i++; if(i < (int) audio_capture_channels) { fprintf(stderr, "[JACK capture] Requested channel count %d not found (matching pattern %s).\n", audio_capture_channels, cfg); goto release_client; } s->frame.ch_count = audio_capture_channels; s->frame.bps = 4; if (audio_capture_sample_rate) { log_msg(LOG_LEVEL_WARNING, "[JACK capture] Ignoring user specified sample rate!\n"); } s->frame.sample_rate = jack_get_sample_rate (s->client); s->frame.max_size = s->frame.ch_count * s->frame.bps * s->frame.sample_rate; s->frame.data = malloc(s->frame.max_size); s->tmp = malloc(s->frame.max_size); s->data = ring_buffer_init(s->frame.max_size); if(jack_set_sample_rate_callback(s->client, jack_samplerate_changed_callback, (void *) s)) { fprintf(stderr, "[JACK capture] Registring callback problem.\n"); goto release_client; } if(jack_set_process_callback(s->client, jack_process_callback, (void *) s) != 0) { fprintf(stderr, "[JACK capture] Process callback registration problem.\n"); goto release_client; } if(jack_activate(s->client)) { fprintf(stderr, "[JACK capture] Cannot activate client.\n"); goto release_client; } { int port; char name[32]; for(port = 0; port < s->frame.ch_count; port++) { snprintf(name, 32, "capture_%02u", port); s->input_ports[port] = jack_port_register(s->client, name, JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput, 0); /* attach ports */ if(jack_connect(s->client, ports[port], jack_port_name(s->input_ports[port]))) { fprintf(stderr, "[JACK capture] Cannot connect input ports.\n"); } } } free(ports); s->can_process = true; return s; release_client: jack_client_close(s->client); error: free(s); return NULL; }
/* * @brief Step through the main stages in the code. * @return Void */ void mode_5_main(void) { switch(current_state) { case INITIAL: /* if (!done_rd_dict) { log_msg("Reading dictionary file..."); play_direction(MP3_PLEASE_WAIT) init_read_dict((unsigned char *)"wordsEn.txt"); while (!done_rd_dict) read_dict_file(); } */ play_welcome(); current_state = REQUEST_QUESTION; break; case REQUEST_QUESTION: if (got_input) { got_input = false; current_state = GENERATE_QUESTION; } break; case GENERATE_QUESTION: if (cell == 0) { // if return was entered twice mode_5_chosen_word[input_word_index] = '\0'; // if (bin_srch_dict((unsigned char *)mode_5_chosen_word)) { // valid word; switch to player 2 // @TODO "valid word, please hand device to player 2 and press enter when ready" // play_mode_audio(MP3_VALID_WORD_PASS_DEVICE); input_word_index = 0; play_feedback(MP3_YOUR_WORD_IS); play_string(mode_5_chosen_word, strlen(mode_5_chosen_word)); play_feedback(MP3_PASS_DEVICE_PRESS_ENTER); current_state = SWITCH_USERS; /* } else { // invalid word; clear variables and try again play_feedback(MP3_WORD_NOT_FOUND); mode_5_reset(); current_state = REQUEST_QUESTION; } */ } else if (mode_5_valid_letter(cell)) { // letter valid; word not complete log_msg("Letter %c entered.", entered_letter); char letter[2] = {entered_letter, '\0'}; play_lang_audio(letter); // reset because too many letters were input if (input_word_index == MAX_WORD_LENGTH) { log_msg("Too many letters inputted!"); play_feedback(MP3_TOO_LONG); mode_5_reset(); current_state = REQUEST_QUESTION; break; } mode_5_chosen_word[input_word_index] = entered_letter; // add letter to chosen_word input_word_index++; current_state = REQUEST_QUESTION; } else { // invalid letter play_feedback(MP3_INVALID_PATTERN); current_state = REQUEST_QUESTION; } break; case SWITCH_USERS: if (got_input) { got_input = false; current_state = PROMPT; } break; case PROMPT: log_msg("Entering ask for guess state."); play_direction(MP3_PLAYER_2); play_feedback(MP3_YOUR_WORD_IS_NOW); play_string(input_word, strlen(mode_5_chosen_word)); play_direction(MP3_GUESS_A_LETTER); current_state = GET_INPUT; break; case GET_INPUT: if (got_input) { got_input = false; current_state = PROCESS_ANSWER; } break; case PROCESS_ANSWER: log_msg("Entering checkans state."); if (cell == 0) // nothing entered: repeat word current_state = GAME_OVER; else if (mode_5_valid_letter(cell)) { // valid letter: read aloud char buff[7]; sprintf(buff, "%c", entered_letter); play_lang_audio(buff); //@todo fix this current_state = CHECK_ANSWER; } else { play_feedback(MP3_INVALID_PATTERN); mistakes++; current_state = GAME_OVER; } break; case CHECK_ANSWER: log_msg("Entering check match state."); if (mode_5_place_letter()) // letters is in word; fn places it play_feedback(MP3_YES); else { play_feedback(MP3_NO); if (!mode_5_is_past_mistake(entered_letter)) { mistake_pool[mistakes] = entered_letter; mistakes++; } else play_feedback(MP3_YOU_HAVE_MADE_THE_SAME_MISTAKE); } current_state = GAME_OVER; break; case GAME_OVER: log_msg("Entering evaluate game state."); if (!strncmp(input_word, mode_5_chosen_word, strlen(mode_5_chosen_word))) { play_feedback(MP3_YOU_HAVE_GUESSED_THE_WORD); play_tada(); current_state = INITIAL; } else if (mistakes == max_mistakes) { play_feedback(MP3_7_MISTAKES_YOU_MISSED); play_string(mode_5_chosen_word, strlen(mode_5_chosen_word)); current_state = INITIAL; } else { if (mistakes > 0) { play_feedback(MP3_YOU_HAVE); play_number(max_mistakes - mistakes); if (max_mistakes - mistakes == 1) play_feedback(MP3_MISTAKE_REMAINING); else play_feedback(MP3_MISTAKES_REMAINING); } current_state = PROMPT; } break; default: log_msg("Invalid state_t %d", current_state); quit_mode(); break; } }
int main(int argc, char *argv[]) { int pid; pthread_t tcp_thread; char *err_msg; /* parse cmdline arguments */ parse_cmdline(argc, argv); /* initialize device communication */ err_msg = NULL; if (aquaero_init(&err_msg) != 0) { log_msg(LOG_ERR, err_msg); exit(EXIT_FAILURE); } /* daemonize */ if (opts.fork) { pid = fork(); switch (pid) { case -1: /* fork failure */ log_msg(LOG_ERR, "failed to fork into background: %s", strerror(errno)); exit(EXIT_FAILURE); break; case 0: /* child */ setsid(); log_msg(LOG_INFO, "started by user %d", getuid()); break; default: /* parent */ exit(EXIT_SUCCESS); break; } } /* write pid-file */ if (opts.pidfile) if (write_pidfile(pid) != 0) log_msg(LOG_WARNING, "failed to write %s: %s", PID_FILE, strerror(errno)); /* register signals */ signal(SIGINT, signal_handler); signal(SIGHUP, signal_handler); signal(SIGTERM, signal_handler); signal(SIGQUIT, signal_handler); /* setup data sync mutex */ if (pthread_mutex_init(&data_lock, NULL) != 0) err_die("failed to setup mutex, terminating"); /* initial poll */ if (poll_data() != 0) die(); /* start tcp server, spawn handler thread */ if (tcp_start_server() != 0) err_die("error opening tcp server socket, terminating"); if (pthread_create(&tcp_thread, NULL, tcp_handler, NULL) != 0) err_die("error spawning listen-thread, terminating"); log_msg(LOG_INFO, "listening on port %d", opts.port); /* start infinite polling-loop */ while (1) { if (poll_data() != 0) die(); sleep(opts.interval); } return 0; }
void *_flite_speak(void *nothing) { AudioTrack track; cst_wave *wav; unsigned int pos; char *buf; int bytes; int ret; log_msg(OTTS_LOG_DEBUG, "flite: speaking thread starting.......\n"); set_speaking_thread_parameters(); while (1) { sem_wait(flite_semaphore); log_msg(OTTS_LOG_INFO, "Semaphore on\n"); flite_stopped = 0; flite_speaking = 1; if (opentts_audio_set_volume(module_audio_id, flite_volume) < 0) { log_msg(OTTS_LOG_ERR, "Can't set volume. audio not initialized?\n"); continue; } /* TODO: free(buf) */ buf = (char *)g_malloc((FliteMaxChunkLength + 1) * sizeof(char)); pos = 0; module_report_event_begin(); while (1) { if (flite_stopped) { log_msg(OTTS_LOG_INFO, "Stop in child, terminating"); flite_speaking = 0; module_report_event_stop(); break; } bytes = module_get_message_part(*flite_message, buf, &pos, FliteMaxChunkLength, FliteDelimiters); if (bytes < 0) { log_msg(OTTS_LOG_DEBUG, "End of message"); flite_speaking = 0; module_report_event_end(); break; } buf[bytes] = 0; log_msg(OTTS_LOG_DEBUG, "Returned %d bytes from get_part\n", bytes); log_msg(OTTS_LOG_NOTICE, "Text to synthesize is '%s'\n", buf); if (flite_pause_requested && (current_index_mark != -1)) { log_msg(OTTS_LOG_INFO, "Pause requested in parent, position %d\n", current_index_mark); flite_pause_requested = 0; flite_position = current_index_mark; break; } if (bytes > 0) { log_msg(OTTS_LOG_DEBUG, "Speaking in child..."); log_msg(OTTS_LOG_NOTICE, "Trying to synthesize text"); wav = flite_text_to_wave(buf, flite_voice); if (wav == NULL) { log_msg(OTTS_LOG_NOTICE, "Stop in child, terminating"); flite_speaking = 0; module_report_event_stop(); break; } track.num_samples = wav->num_samples; track.num_channels = wav->num_channels; track.sample_rate = wav->sample_rate; track.bits = 16; track.samples = wav->samples; flite_strip_silence(&track); log_msg(OTTS_LOG_INFO, "Got %d samples", track.num_samples); if (track.samples != NULL) { if (flite_stopped) { log_msg(OTTS_LOG_NOTICE, "Stop in child, terminating"); flite_speaking = 0; module_report_event_stop(); delete_wave(wav); break; } log_msg(OTTS_LOG_INFO, "Playing part of the message"); switch (module_audio_id->format) { case SPD_AUDIO_LE: ret = opentts_audio_play (module_audio_id, track, SPD_AUDIO_LE); break; case SPD_AUDIO_BE: ret = opentts_audio_play (module_audio_id, track, SPD_AUDIO_BE); break; } if (ret < 0) log_msg(OTTS_LOG_WARN, "ERROR: spd_audio failed to play the track"); if (flite_stopped) { log_msg(OTTS_LOG_NOTICE, "Stop in child, terminating (s)"); flite_speaking = 0; module_report_event_stop(); delete_wave(wav); break; } } delete_wave(wav); } else if (bytes == -1) { log_msg(OTTS_LOG_INFO, "End of data in speaking thread"); flite_speaking = 0; module_report_event_end(); break; } else { flite_speaking = 0; module_report_event_end(); break; } if (flite_stopped) { log_msg(OTTS_LOG_NOTICE, "Stop in child, terminating"); flite_speaking = 0; module_report_event_stop(); break; } } flite_stopped = 0; g_free(buf); } flite_speaking = 0; log_msg(OTTS_LOG_NOTICE, "flite: speaking thread ended.......\n"); pthread_exit(NULL); }
void parse_cmdline(int argc, char *argv[]) { char c; int n; extern int optind, optopt, opterr; /* init options */ opts.port = PORT; opts.interval = INTERVAL; opts.fork = 1; opts.hddtemp = 0; opts.pidfile = 0; /* parse cmdline */ while ((c = getopt(argc, argv, "hFftp:i:")) != -1) { switch (c) { case 'h': print_help(); exit(EXIT_SUCCESS); break; case 'F': opts.fork = 0; break; case 'f': opts.pidfile = 1; break; case 't': opts.hddtemp = 1; break; case 'p': n = atoi(optarg); if (n < 1 || n > 65535) { log_msg(LOG_ERR, "invalid port: %d", n); exit(EXIT_FAILURE); } opts.port = n; break; case 'i': n = atoi(optarg); if (n < INTERVAL_MIN || n > INTERVAL_MAX) { log_msg(LOG_ERR, "invalid interval: %d", n); exit(EXIT_FAILURE); } opts.interval = n; break; case '?': if (optopt == 'p'|| optopt == 'i') { fprintf (stderr, "option -%c requires an argument.\n", optopt); } else { log_msg(LOG_ERR, "unknown option \"-%c\". Try -h for help.", optopt); } exit(EXIT_FAILURE); default: log_msg(LOG_ERR, "invalid arguments. Try -h for help."); exit(EXIT_FAILURE); } } return; }
int sigh_alrm (int num) { log_msg("Authentication timeout (%d seconds) exceeded.", timeout); exit(1); }
static int udf_mounted(service_id_t service_id, const char *opts, fs_index_t *index, aoff64_t *size, unsigned *linkcnt) { enum cache_mode cmode; /* Check for option enabling write through. */ if (str_cmp(opts, "wtcache") == 0) cmode = CACHE_MODE_WT; else cmode = CACHE_MODE_WB; udf_instance_t *instance = malloc(sizeof(udf_instance_t)); if (!instance) return ENOMEM; instance->sector_size = 0; /* Check for block size. Will be enhanced later */ if (str_cmp(opts, "bs=512") == 0) instance->sector_size = 512; else if (str_cmp(opts, "bs=1024") == 0) instance->sector_size = 1024; else if (str_cmp(opts, "bs=2048") == 0) instance->sector_size = 2048; /* initialize block cache */ int rc = block_init(service_id, MAX_SIZE); if (rc != EOK) return rc; rc = fs_instance_create(service_id, instance); if (rc != EOK) { free(instance); block_fini(service_id); return rc; } instance->service_id = service_id; instance->open_nodes_count = 0; /* Check Volume Recognition Sequence */ rc = udf_volume_recongnition(service_id); if (rc != EOK) { log_msg(LOG_DEFAULT, LVL_NOTE, "VRS failed"); fs_instance_destroy(service_id); free(instance); block_fini(service_id); return rc; } /* Search for Anchor Volume Descriptor */ udf_anchor_volume_descriptor_t avd; rc = udf_get_anchor_volume_descriptor(service_id, &avd); if (rc != EOK) { log_msg(LOG_DEFAULT, LVL_NOTE, "Anchor read failed"); fs_instance_destroy(service_id); free(instance); block_fini(service_id); return rc; } log_msg(LOG_DEFAULT, LVL_DEBUG, "Volume: Anchor volume descriptor found. Sector size=%" PRIu32, instance->sector_size); log_msg(LOG_DEFAULT, LVL_DEBUG, "Anchor: main sequence [length=%" PRIu32 " (bytes), start=%" PRIu32 " (sector)]", avd.main_extent.length, avd.main_extent.location); log_msg(LOG_DEFAULT, LVL_DEBUG, "Anchor: reserve sequence [length=%" PRIu32 " (bytes), start=%" PRIu32 " (sector)]", avd.reserve_extent.length, avd.reserve_extent.location); /* Initialize the block cache */ rc = block_cache_init(service_id, instance->sector_size, 0, cmode); if (rc != EOK) { fs_instance_destroy(service_id); free(instance); block_fini(service_id); return rc; } /* Read Volume Descriptor Sequence */ rc = udf_read_volume_descriptor_sequence(service_id, avd.main_extent); if (rc != EOK) { log_msg(LOG_DEFAULT, LVL_NOTE, "Volume Descriptor Sequence read failed"); fs_instance_destroy(service_id); free(instance); block_cache_fini(service_id); block_fini(service_id); return rc; } fs_node_t *rfn; rc = udf_node_get(&rfn, service_id, instance->volumes[DEFAULT_VOL].root_dir); if (rc != EOK) { log_msg(LOG_DEFAULT, LVL_NOTE, "Can't create root node"); fs_instance_destroy(service_id); free(instance); block_cache_fini(service_id); block_fini(service_id); return rc; } udf_node_t *node = UDF_NODE(rfn); *index = instance->volumes[DEFAULT_VOL].root_dir; *size = node->data_size; *linkcnt = node->link_cnt; return EOK; }
/** * Fetches username and password * @param username * @param password * @param file * @return 1 on success, otherwise 0 */ int credentials_retr (struct auth *ptr, char *file) { FILE *fd; char *tmp; char fbuf[CRED_BUF_SIZE]; int len = 0; if (file == NULL) { tmp = getenv("username"); if (tmp != NULL) strncpy(ptr->username, tmp, CRED_BUF_SIZE); tmp = getenv("password"); if (tmp != NULL) strncpy(ptr->password, tmp, CRED_BUF_SIZE); } else { if ((fd = fopen(file, "r")) == NULL) { log_msg("Unable to open credentials file %s: %s", file, strerror(errno)); return 0; } /* read username */ if (fgets(fbuf, sizeof(fbuf), fd) == NULL) { log_msg("Unable to read username from file: %s", strerror(errno)); return 0; } len = strlen(fbuf); if (fbuf[len - 1] == '\n') fbuf[len - 1] = '\0'; strncpy(ptr->username, fbuf, sizeof(fbuf)); /* read password */ if (fgets(fbuf, sizeof(fbuf), fd) == NULL) { log_msg("Unable to read password from file: %s", strerror(errno)); return 0; } len = strlen(fbuf); if (fbuf[len - 1] == '\n') fbuf[len - 1] = '\0'; strncpy(ptr->password, fbuf, sizeof(fbuf)); /** close file */ fclose(fd); } /* retrieve other stuff from environment */ ptr->common_name = getenv("common_name"); if (ptr->common_name == NULL) { log_msg("Warning: environmental variable common_name is not set."); ptr->common_name = ""; } ptr->untrusted_ip = getenv("untrusted_ip"); if (ptr->untrusted_ip == NULL) { log_msg("Warning: environmental variable untrusted_ip is not set."); ptr->untrusted_ip = ""; } tmp = getenv("untrusted_port"); if (tmp == NULL) { log_msg("Warning: environmental variable untrusted_port is not set."); ptr->untrusted_port = 0; } else ptr->untrusted_port = atoi(tmp); return 1; }
/* Quietly flush and delete all fwknop custom chains. */ static void delete_all_chains(const fko_srv_options_t *opts) { int i, res; int jump_rule_num; for(i=0; i<(NUM_FWKNOP_ACCESS_TYPES); i++) { if(fwc.chain[i].target[0] == '\0') continue; /* First look for a jump rule to this chain and remove it if it * is there. */ if((jump_rule_num = jump_rule_exists(i)) > 0) { zero_cmd_buffers(); snprintf(cmd_buf, CMD_BUFSIZE-1, "%s " IPT_DEL_RULE_ARGS, fwc.fw_command, fwc.chain[i].table, fwc.chain[i].from_chain, jump_rule_num ); res = run_extcmd(cmd_buf, err_buf, CMD_BUFSIZE, 0); if (opts->verbose) log_msg(LOG_INFO, "delete_all_chains() CMD: '%s' (res: %d, err: %s)", cmd_buf, res, err_buf); /* Expect full success on this */ if(! EXTCMD_IS_SUCCESS(res)) log_msg(LOG_ERR, "Error %i from cmd:'%s': %s", res, cmd_buf, err_buf); } zero_cmd_buffers(); /* Now flush and remove the chain. */ snprintf(cmd_buf, CMD_BUFSIZE-1, "(%s " IPT_FLUSH_CHAIN_ARGS "; %s " IPT_DEL_CHAIN_ARGS ")", // > /dev/null 2>&1", fwc.fw_command, fwc.chain[i].table, fwc.chain[i].to_chain, fwc.fw_command, fwc.chain[i].table, fwc.chain[i].to_chain ); res = run_extcmd(cmd_buf, err_buf, CMD_BUFSIZE, 0); if (opts->verbose) log_msg(LOG_INFO, "delete_all_chains() CMD: '%s' (res: %d, err: %s)", cmd_buf, res, err_buf); /* Expect full success on this */ if(! EXTCMD_IS_SUCCESS(res)) log_msg(LOG_ERR, "Error %i from cmd:'%s': %s", res, cmd_buf, err_buf); } }
/** * Connects to authentication server * @return FILE* server socket filehandle on success, otherwise NULL */ FILE * srv_connect (void) { FILE *socketfd = NULL; /** socket-wrapped filedescriptor */ struct sockaddr_un server_addr_un; struct sockaddr_in local_addr, server_addr; /* inet or unix domain socket? */ if (hostname[0] == '/') { log_msg("Connecting to authentication server using UNIX domain socket %s.", hostname); /** create unix socket */ if ((server_socket = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) { log_msg("Unable to create UNIX domain socket: %s (errno %d).", strerror(errno), errno); } server_addr_un.sun_family = AF_UNIX; strncpy(server_addr_un.sun_path, hostname, 108); int len = sizeof(server_addr_un.sun_family) + strlen(server_addr_un.sun_path); /** connect to server */ if (connect(server_socket, (const struct sockaddr *) &server_addr_un, len) < 0) { log_msg("Unable to connect to %s: %s (errno %d).", hostname, strerror(errno), errno); close(server_socket); return NULL; } } else { log_msg("Connecting to authentication server %s:%d using TCP socket.", hostname, port); struct hostent *h; /** hostentry */ /** resolve */ if ((h = gethostbyname(hostname)) == NULL) { log_msg("Unable resolve %s: %s (errno %d).", hostname, strerror(errno), errno); return NULL; } if (h == NULL) { log_msg("do_it(), line %d: (h->h_addr_list[0] == NULL) This is weird and should never happen!", __LINE__); return NULL; } server_addr.sin_family = h->h_addrtype; memcpy((char *) &server_addr.sin_addr.s_addr, h->h_addr_list[0], h->h_length); server_addr.sin_port = htons(port); /** create inet socket */ if ((server_socket = socket(AF_INET, SOCK_STREAM, 0)) < 0) { log_msg("Unable to create INET socket: %s (errno %d).", strerror(errno), errno); } /** bind any port number */ local_addr.sin_family = AF_INET; local_addr.sin_addr.s_addr = htonl(INADDR_ANY); local_addr.sin_port = htons(0); if (bind(server_socket, (struct sockaddr *) &local_addr, sizeof(local_addr)) < 0) { log_msg("Unable to bind %s:%d sock: %s (errno %d).", hostname, port, strerror(errno), errno); } /** connect to server */ if (connect(server_socket, (struct sockaddr *) &server_addr, sizeof(server_addr)) < 0) { log_msg("Unable to connect to %s:%d: %s (errno %d).", hostname, port, strerror(errno), errno); close(server_socket); return NULL; } } /** wrap socket to filedescriptor */ if ((socketfd = fdopen(server_socket, "r+")) == NULL) { log_msg("Unable to create stream fd: %s (errno %d).", strerror(errno), errno); close(server_socket); return NULL; } return socketfd; }
/* Rule Processing - Create an access request... */ int process_spa_request(const fko_srv_options_t *opts, const acc_stanza_t *acc, spa_data_t *spadat) { char nat_ip[MAX_IPV4_STR_LEN] = {0}; char snat_target[SNAT_TARGET_BUFSIZE] = {0}; char *ndx; unsigned int nat_port = 0; acc_port_list_t *port_list = NULL; acc_port_list_t *ple; unsigned int fst_proto; unsigned int fst_port; struct fw_chain *in_chain = &(opts->fw_config->chain[IPT_INPUT_ACCESS]); struct fw_chain *out_chain = &(opts->fw_config->chain[IPT_OUTPUT_ACCESS]); struct fw_chain *fwd_chain = &(opts->fw_config->chain[IPT_FORWARD_ACCESS]); struct fw_chain *dnat_chain = &(opts->fw_config->chain[IPT_DNAT_ACCESS]); struct fw_chain *snat_chain; /* We assign this later (if we need to). */ int res = 0; time_t now; unsigned int exp_ts; /* Parse and expand our access message. */ if(expand_acc_port_list(&port_list, spadat->spa_message_remain) != 1) return res; /* Start at the top of the proto-port list... */ ple = port_list; /* Remember the first proto/port combo in case we need them * for NAT access requests. */ fst_proto = ple->proto; fst_port = ple->port; /* Set our expire time value. */ time(&now); exp_ts = now + spadat->fw_access_timeout; /* For straight access requests, we currently support multiple proto/port * request. */ if((spadat->message_type == FKO_ACCESS_MSG || spadat->message_type == FKO_CLIENT_TIMEOUT_ACCESS_MSG) && !acc->force_nat) { /* Check to make sure that the jump rules exist for each * required chain */ if(jump_rule_exists(IPT_INPUT_ACCESS) == 0) add_jump_rule(opts, IPT_INPUT_ACCESS); if(out_chain->to_chain != NULL && strlen(out_chain->to_chain)) if(jump_rule_exists(IPT_OUTPUT_ACCESS) == 0) add_jump_rule(opts, IPT_OUTPUT_ACCESS); /* Create an access command for each proto/port for the source ip. */ while(ple != NULL) { zero_cmd_buffers(); snprintf(cmd_buf, CMD_BUFSIZE-1, "%s " IPT_ADD_RULE_ARGS, opts->fw_config->fw_command, in_chain->table, in_chain->to_chain, ple->proto, spadat->use_src_ip, ple->port, exp_ts, in_chain->target ); res = run_extcmd(cmd_buf, err_buf, CMD_BUFSIZE, 0); if (opts->verbose) log_msg(LOG_INFO, "process_spa_request() CMD: '%s' (res: %d, err: %s)", cmd_buf, res, err_buf); if(EXTCMD_IS_SUCCESS(res)) { log_msg(LOG_INFO, "Added Rule to %s for %s, %s expires at %u", in_chain->to_chain, spadat->use_src_ip, spadat->spa_message_remain, exp_ts ); in_chain->active_rules++; /* Reset the next expected expire time for this chain if it * is warranted. */ if(in_chain->next_expire < now || exp_ts < in_chain->next_expire) in_chain->next_expire = exp_ts; } else log_msg(LOG_ERR, "Error %i from cmd:'%s': %s", res, cmd_buf, err_buf); /* If we have to make an corresponding OUTPUT rule if out_chain target * is not NULL. */ if(out_chain->to_chain != NULL && strlen(out_chain->to_chain)) { zero_cmd_buffers(); snprintf(cmd_buf, CMD_BUFSIZE-1, "%s " IPT_ADD_OUT_RULE_ARGS, opts->fw_config->fw_command, out_chain->table, out_chain->to_chain, ple->proto, spadat->use_src_ip, ple->port, exp_ts, out_chain->target ); res = run_extcmd(cmd_buf, err_buf, CMD_BUFSIZE, 0); if (opts->verbose) log_msg(LOG_INFO, "process_spa_request() CMD: '%s' (res: %d, err: %s)", cmd_buf, res, err_buf); if(EXTCMD_IS_SUCCESS(res)) { log_msg(LOG_INFO, "Added OUTPUT Rule to %s for %s, %s expires at %u", out_chain->to_chain, spadat->use_src_ip, spadat->spa_message_remain, exp_ts ); out_chain->active_rules++; /* Reset the next expected expire time for this chain if it * is warranted. */ if(out_chain->next_expire < now || exp_ts < out_chain->next_expire) out_chain->next_expire = exp_ts; } else log_msg(LOG_ERR, "Error %i from cmd:'%s': %s", res, cmd_buf, err_buf); } ple = ple->next; } } /* NAT requests... */ else if(spadat->message_type == FKO_LOCAL_NAT_ACCESS_MSG || spadat->message_type == FKO_CLIENT_TIMEOUT_LOCAL_NAT_ACCESS_MSG || spadat->message_type == FKO_NAT_ACCESS_MSG || spadat->message_type == FKO_CLIENT_TIMEOUT_NAT_ACCESS_MSG || acc->force_nat) { /* Parse out the NAT IP and Port components. */ if(acc->force_nat) { strlcpy(nat_ip, acc->force_nat_ip, MAX_IPV4_STR_LEN); nat_port = acc->force_nat_port; } else { ndx = strchr(spadat->nat_access, ','); if(ndx != NULL) { strlcpy(nat_ip, spadat->nat_access, (ndx-spadat->nat_access)+1); nat_port = atoi(ndx+1); } } if(spadat->message_type == FKO_LOCAL_NAT_ACCESS_MSG) { /* Need to add an ACCEPT rule into the INPUT chain */ zero_cmd_buffers(); snprintf(cmd_buf, CMD_BUFSIZE-1, "%s " IPT_ADD_RULE_ARGS, opts->fw_config->fw_command, in_chain->table, in_chain->to_chain, fst_proto, spadat->use_src_ip, nat_port, exp_ts, in_chain->target ); res = run_extcmd(cmd_buf, err_buf, CMD_BUFSIZE, 0); if (opts->verbose) log_msg(LOG_INFO, "process_spa_request() CMD: '%s' (res: %d, err: %s)", cmd_buf, res, err_buf); if(EXTCMD_IS_SUCCESS(res)) { log_msg(LOG_INFO, "Added Rule to %s for %s, %s expires at %u", in_chain->to_chain, spadat->use_src_ip, spadat->spa_message_remain, exp_ts ); in_chain->active_rules++; /* Reset the next expected expire time for this chain if it * is warranted. */ if(in_chain->next_expire < now || exp_ts < in_chain->next_expire) in_chain->next_expire = exp_ts; } else log_msg(LOG_ERR, "Error %i from cmd:'%s': %s", res, cmd_buf, err_buf); } else if(fwd_chain->to_chain != NULL && strlen(fwd_chain->to_chain)) { /* Make our FORWARD and NAT rules, and make sure the * required jump rule exists */ if (jump_rule_exists(IPT_FORWARD_ACCESS) == 0) add_jump_rule(opts, IPT_FORWARD_ACCESS); zero_cmd_buffers(); snprintf(cmd_buf, CMD_BUFSIZE-1, "%s " IPT_ADD_FWD_RULE_ARGS, opts->fw_config->fw_command, fwd_chain->table, fwd_chain->to_chain, fst_proto, spadat->use_src_ip, nat_ip, nat_port, exp_ts, fwd_chain->target ); res = run_extcmd(cmd_buf, err_buf, CMD_BUFSIZE, 0); if (opts->verbose) log_msg(LOG_INFO, "process_spa_request() CMD: '%s' (res: %d, err: %s)", cmd_buf, res, err_buf); if(EXTCMD_IS_SUCCESS(res)) { log_msg(LOG_INFO, "Added FORWARD Rule to %s for %s, %s expires at %u", fwd_chain->to_chain, spadat->use_src_ip, spadat->spa_message_remain, exp_ts ); fwd_chain->active_rules++; /* Reset the next expected expire time for this chain if it * is warranted. */ if(fwd_chain->next_expire < now || exp_ts < fwd_chain->next_expire) fwd_chain->next_expire = exp_ts; } else log_msg(LOG_ERR, "Error %i from cmd:'%s': %s", res, cmd_buf, err_buf); } if(dnat_chain->to_chain != NULL && strlen(dnat_chain->to_chain)) { /* Make sure the required jump rule exists */ if (jump_rule_exists(IPT_DNAT_ACCESS) == 0) add_jump_rule(opts, IPT_DNAT_ACCESS); zero_cmd_buffers(); snprintf(cmd_buf, CMD_BUFSIZE-1, "%s " IPT_ADD_DNAT_RULE_ARGS, opts->fw_config->fw_command, dnat_chain->table, dnat_chain->to_chain, fst_proto, spadat->use_src_ip, fst_port, exp_ts, dnat_chain->target, nat_ip, nat_port ); res = run_extcmd(cmd_buf, err_buf, CMD_BUFSIZE, 0); if (opts->verbose) log_msg(LOG_INFO, "process_spa_request() CMD: '%s' (res: %d, err: %s)", cmd_buf, res, err_buf); if(EXTCMD_IS_SUCCESS(res)) { log_msg(LOG_INFO, "Added DNAT Rule to %s for %s, %s expires at %u", dnat_chain->to_chain, spadat->use_src_ip, spadat->spa_message_remain, exp_ts ); dnat_chain->active_rules++; /* Reset the next expected expire time for this chain if it * is warranted. */ if(dnat_chain->next_expire < now || exp_ts < dnat_chain->next_expire) dnat_chain->next_expire = exp_ts; } else log_msg(LOG_ERR, "Error %i from cmd:'%s': %s", res, cmd_buf, err_buf); } /* If SNAT (or MASQUERADE) is wanted, then we add those rules here as well. */ if(strncasecmp(opts->config[CONF_ENABLE_IPT_SNAT], "Y", 1) == 0) { zero_cmd_buffers(); /* Setup some parameter depending on whether we are using SNAT * or MASQUERADE. */ if(strncasecmp(opts->config[CONF_SNAT_TRANSLATE_IP], "__CHANGEME__", 10)!=0) { /* Using static SNAT */ snat_chain = &(opts->fw_config->chain[IPT_SNAT_ACCESS]); snprintf(snat_target, SNAT_TARGET_BUFSIZE-1, "--to-source %s:%i", opts->config[CONF_SNAT_TRANSLATE_IP], fst_port); } else { /* Using MASQUERADE */ snat_chain = &(opts->fw_config->chain[IPT_MASQUERADE_ACCESS]); snprintf(snat_target, SNAT_TARGET_BUFSIZE-1, "--to-ports %i", fst_port); } snprintf(cmd_buf, CMD_BUFSIZE-1, "%s " IPT_ADD_SNAT_RULE_ARGS, opts->fw_config->fw_command, snat_chain->table, snat_chain->to_chain, fst_proto, nat_ip, nat_port, exp_ts, snat_chain->target, snat_target ); res = run_extcmd(cmd_buf, err_buf, CMD_BUFSIZE, 0); if (opts->verbose) log_msg(LOG_INFO, "process_spa_request() CMD: '%s' (res: %d, err: %s)", cmd_buf, res, err_buf); if(EXTCMD_IS_SUCCESS(res)) { log_msg(LOG_INFO, "Added Source NAT Rule to %s for %s, %s expires at %u", snat_chain->to_chain, spadat->use_src_ip, spadat->spa_message_remain, exp_ts ); snat_chain->active_rules++; /* Reset the next expected expire time for this chain if it * is warranted. */ if(snat_chain->next_expire < now || exp_ts < snat_chain->next_expire) snat_chain->next_expire = exp_ts; } else log_msg(LOG_ERR, "Error %i from cmd:'%s': %s", res, cmd_buf, err_buf); } } /* Done with the port list for access rules. */ free_acc_port_list(port_list); return(res); }
/** * main routine */ int main (int argc, char **argv) { /** command line parsing */ extern char *optarg; extern int optind; char *tmp; struct auth *auth_str; struct sigaction act; struct termio tty, oldtty; int cred_from_cmdl = 0; MYNAME = basename(argv[0]); strncpy(hostname, DEFAULT_HOSTNAME, sizeof(hostname)); /** try to load configuration files */ load_config_files(); /** initialize authentication structure */ if ((auth_str = authstruct_init()) == NULL) { log_msg("Unable to initialize authentication structure... Possibly out of memory."); return 1; } /* configure command line parser */ static struct option long_options[] = { /* These options set a flag. */ {"default-config", no_argument, NULL, 'd'}, {"verbose", no_argument, NULL, 'v'}, {"version", no_argument, NULL, 'V'}, {"help", no_argument, NULL, 'h'}, /* These options require argument */ {"config", required_argument, NULL, 'c'}, {"hostname", required_argument, NULL, 'H'}, {"port", required_argument, NULL, 'p'}, {"user", required_argument, NULL, 'U'}, {"pass", required_argument, NULL, 'P'}, {"cn", required_argument, NULL, 'C'}, {"client-ip", required_argument, NULL, 'X'}, {"client-port", required_argument, NULL, 'Y'}, }; /* parse command line */ int r = 1; int opt_idx = 0; /* option index */ while (r) { int c = 0; /* option character */ c = getopt_long(argc, argv, "c:H:p:U:P:C:X:Y:vhdV", long_options, &opt_idx); switch (c) { case 'c': if (! load_config_file(optarg)) { fprintf(stderr, "Unable to parse config file '%s': %s\n", optarg, strerror(errno)); return 1; } break; case 'H': strncpy(hostname, optarg, sizeof(hostname)); break; case 'p': port = atoi(optarg); break; case 'U': strncpy(auth_str->username, optarg, CRED_BUF_SIZE); cred_from_cmdl = 1; break; case 'P': strncpy(auth_str->password, optarg, CRED_BUF_SIZE); cred_from_cmdl = 1; break; case 'C': auth_str->common_name = optarg; cred_from_cmdl = 1; break; case 'X': auth_str->untrusted_ip = optarg; cred_from_cmdl = 1; break; case 'Y': auth_str->untrusted_port = atoi(optarg); cred_from_cmdl = 1; break; case 'v': verbose = 1; break; case 'd': print_default_config(); return 0; break; case 'h': printhelp(); return 0; break; case 'V': printf("%s %s\n", MYNAME, VERSION); return 0; break; case '?': log_msg("Invalid command line options. Run %s --help for instructions\n", basename(argv[0])); return 1; break; default: r = 0; break; } } /** check if we're really called as openvpn argument */ if ((tmp = getenv("script_type")) == NULL || (strcmp(tmp, "auth-user-pass-verify") != 0 && strcmp(tmp, "user-pass-verify") != 0)) { log_msg("Program is not executed as --auth-user-pass-verify openvpn server argument. Environment variable \"script_type\" != \"(auth-)?user-pass-verify\" (%s)", tmp); cred_from_cmdl = 1; } /** openvpn server mode? */ if (! cred_from_cmdl) { /** retrieve credentials */ if (! credentials_retr(auth_str, argv[optind])) return 1; } /** testing mode? */ else { verbose = 1; log_msg("Program invoked in TEST mode."); /** no provided password? */ if (strlen(auth_str->password) < 1 ) { printf("No password was given from command line.\n"); printf("Password: "******"\n"); } fprintf(stderr, "\n--- VERBOSE OUTPUT ---\n"); } /** install signal handler */ act.sa_handler = sigh_alrm; sigemptyset(&act.sa_mask); act.sa_flags = 0; if (sigaction(SIGALRM, &act, NULL) != 0) { fprintf(stderr, "Unable to install ALRM (authentication timeout) signal handler: %s\n", strerror(errno)); return 1; } alarm(timeout); /** perform authentication */ r = authenticate(auth_str); if (cred_from_cmdl) { fprintf(stderr, "--- VERBOSE OUTPUT ---\n\n"); printf("Authentication %s.\n", ((r) ? "SUCCEEDED" : "FAILED")); } /** cleanup */ authstruct_destroy(auth_str); return (! r); }
static int festival_init(char **status_info) { int ret; GString *info; info = g_string_new(""); log_msg(OTTS_LOG_NOTICE, "module_init()"); /* Initialize appropriate communication mechanism */ FestivalComType = FestivalComunicationType; if (COM_SOCKET) { g_string_append(info, "Communicating with Festival through a socket. "); ret = init_festival_socket(); if (ret == -1) { ABORT ("Can't connect to Festival server. Check your configuration " "in /etc/opentts/modules/festival.conf for the specified host and port " "and check if Festival is really running there, e.g. with telnet. " "Please see documentation for more info."); } else if (ret == -2) { ABORT("Connect to the Festival server was successful, " "but I got disconnected immediately. This is most likely " "because of authorization problems. Check the variable " "server_access_list in etc/festival.scm and consult documentation " "for more information."); } } if (COM_LOCAL) { g_string_append(info, "Communicating with Festival through a local child process."); if (init_festival_standalone()) { ABORT ("Local connect to Festival failed for unknown reasons."); } } /* Get festival voice list */ festival_voice_list = festivalGetVoices(festival_info); /* Initialize global variables */ festival_message = (char **)g_malloc(sizeof(char *)); *festival_message = NULL; /* Initialize festival_speak thread to handle communication with festival in a separate thread (to be faster in communication with the OpenTTS daemon) */ festival_semaphore = module_semaphore_init(); if (festival_semaphore == NULL) return -1; log_msg(OTTS_LOG_INFO, "Festival: creating new thread for festival_speak\n"); festival_speaking = 0; ret = pthread_create(&festival_speak_thread, NULL, _festival_speak, NULL); if (ret != 0) { log_msg(OTTS_LOG_ERR, "Festival: thread failed\n"); g_string_append(info, "The module couldn't initialize threads" "This can be either an internal problem or an" "architecture problem. If you are sure your architecture" "supports threads, please report a bug."); *status_info = info->str; g_string_free(info, 0); return -1; } pthread_mutex_init(&sound_output_mutex, NULL); *status_info = info->str; g_string_free(info, 0); return 0; }
/* Run an external command returning exit status, and optionally filling * provided buffer with STDOUT output up to the size provided. * * Note: XXX: We are not using the timeout parameter at present. We still need * to implement a reliable timeout mechanism. */ static int _run_extcmd(uid_t uid, gid_t gid, const char *cmd, char *so_buf, const size_t so_buf_sz, const int cflag, const int timeout, const char *substr_search, int *pid_status, const fko_srv_options_t * const opts) { char so_read_buf[IO_READ_BUF_LEN] = {0}; pid_t pid=0; FILE *output; int retval = EXTCMD_SUCCESS_ALL_OUTPUT; int line_ctr = 0, found_str = 0, do_break = 0; char *argv_new[MAX_CMDLINE_ARGS]; /* for validation and/or execvpe() */ int argc_new=0; #if HAVE_EXECVPE int pipe_fd[2]; #endif #if AFL_FUZZING /* Don't allow command execution in AFL fuzzing mode */ return 0; #endif *pid_status = 0; /* Even without execvpe() we examine the command for basic validity * in term of number of args */ memset(argv_new, 0x0, sizeof(argv_new)); if(strtoargv(cmd, argv_new, &argc_new) != 1) { log_msg(LOG_ERR, "run_extcmd(): Error converting cmd str to argv via strtoargv()"); return EXTCMD_ARGV_ERROR; } #if !HAVE_EXECVPE /* if we are not using execvpe() then free up argv_new unconditionally * since was used only for validation */ free_argv(argv_new, &argc_new); #endif #if HAVE_EXECVPE if(opts->verbose > 1) log_msg(LOG_INFO, "run_extcmd() (with execvpe()): running CMD: %s", cmd); if(so_buf != NULL || substr_search != NULL) { if(pipe(pipe_fd) < 0) { log_msg(LOG_ERR, "run_extcmd(): pipe() failed: %s", strerror(errno)); free_argv(argv_new, &argc_new); return EXTCMD_PIPE_ERROR; } } //在子进程中创建CMD。 pid = fork(); if (pid == 0) { if(chdir("/") != 0) exit(EXTCMD_CHDIR_ERROR); if(so_buf != NULL || substr_search != NULL) { close(pipe_fd[0]); dup2(pipe_fd[1], STDOUT_FILENO); if(cflag & WANT_STDERR) dup2(pipe_fd[1], STDERR_FILENO); else close(STDERR_FILENO); } /* Take care of gid/uid settings before running the command. */ if(gid > 0) if(setgid(gid) < 0) exit(EXTCMD_SETGID_ERROR); if(uid > 0) if(setuid(uid) < 0) exit(EXTCMD_SETUID_ERROR); /* don't use env */ execvpe(argv_new[0], argv_new, (char * const *)NULL); } else if(pid == -1) { log_msg(LOG_ERR, "run_extcmd(): fork() failed: %s", strerror(errno)); free_argv(argv_new, &argc_new); return EXTCMD_FORK_ERROR; } /* Only the parent process makes it here */ if(so_buf != NULL || substr_search != NULL) { close(pipe_fd[1]); if ((output = fdopen(pipe_fd[0], "r")) != NULL) { if(so_buf != NULL) memset(so_buf, 0x0, so_buf_sz); while((fgets(so_read_buf, IO_READ_BUF_LEN, output)) != NULL) { line_ctr++; copy_or_search(so_read_buf, so_buf, so_buf_sz, substr_search, cflag, &found_str, &do_break); if(do_break) break; } fclose(output); /* Make sure we only have complete lines */ if(!(cflag & ALLOW_PARTIAL_LINES)) truncate_partial_line(so_buf); } else { log_msg(LOG_ERR, "run_extcmd(): could not fdopen() pipe output file descriptor."); free_argv(argv_new, &argc_new); return EXTCMD_OPEN_ERROR; } } free_argv(argv_new, &argc_new); waitpid(pid, pid_status, 0); #else if(opts->verbose > 1) log_msg(LOG_INFO, "run_extcmd() (without execvpe()): running CMD: %s", cmd); if(so_buf == NULL && substr_search == NULL) { /* Since we do not have to capture output, we will fork here (which we * * would have to do anyway if we are running as another user as well). * */ pid = fork(); if(pid == -1) { log_msg(LOG_ERR, "run_extcmd: fork failed: %s", strerror(errno)); return(EXTCMD_FORK_ERROR); } else if (pid == 0) { /* We are the child */ if(chdir("/") != 0) exit(EXTCMD_CHDIR_ERROR); /* Take care of gid/uid settings before running the command. */ if(gid > 0) if(setgid(gid) < 0) exit(EXTCMD_SETGID_ERROR); if(uid > 0) if(setuid(uid) < 0) exit(EXTCMD_SETUID_ERROR); *pid_status = system(cmd); exit(*pid_status); } /* Retval is forced to 0 as we don't care about the exit status of * the child (for now) */ retval = EXTCMD_SUCCESS_ALL_OUTPUT; } else { /* Looking for output use popen and fill the buffer to its limit. */ output = popen(cmd, "r"); if(output == NULL) { log_msg(LOG_ERR, "Got popen error %i: %s", errno, strerror(errno)); retval = EXTCMD_OPEN_ERROR; } else { if(so_buf != NULL) memset(so_buf, 0x0, so_buf_sz); while((fgets(so_read_buf, IO_READ_BUF_LEN, output)) != NULL) { line_ctr++; copy_or_search(so_read_buf, so_buf, so_buf_sz, substr_search, cflag, &found_str, &do_break); if(do_break) break; } pclose(output); /* Make sure we only have complete lines */ if(!(cflag & ALLOW_PARTIAL_LINES)) truncate_partial_line(so_buf); } } #endif if(substr_search != NULL) { /* The semantics of the return value changes in search mode to the line * number where the substring match was found, or zero if it wasn't found */ if(found_str) retval = line_ctr; else retval = 0; } else { if(WIFEXITED(*pid_status)) { /* Even if the child exited with an error condition, if we make it here * then the child exited normally as far as the OS is concerned (i.e. didn't * crash or get hit with a signal) */ retval = EXTCMD_SUCCESS_ALL_OUTPUT; } else retval = EXTCMD_EXECUTION_ERROR; } if(opts->verbose > 1) log_msg(LOG_INFO, "run_extcmd(): returning %d, pid_status: %d", retval, WIFEXITED(*pid_status) ? WEXITSTATUS(*pid_status) : *pid_status); return(retval); }
void *_festival_speak(void *nothing) { int ret; int bytes; int wave_cached; FT_Wave *fwave; int debug_count = 0; int r; int terminate = 0; char *callback; log_msg(OTTS_LOG_INFO, "festival: speaking thread starting.......\n"); cache_init(); set_speaking_thread_parameters(); while (1) { sem_wait: sem_wait(festival_semaphore); log_msg(OTTS_LOG_DEBUG, "Semaphore on, speaking\n"); opentts_audio_set_volume(module_audio_id, festival_volume); festival_stopped = 0; festival_speaking = 1; wave_cached = 0; fwave = NULL; terminate = 0; bytes = strlen(*festival_message); module_report_event_begin(); log_msg(OTTS_LOG_INFO, "Going to synthesize: |%s|", *festival_message); if (bytes > 0) { if (!is_text(festival_message_type)) { /* it is a raw text */ log_msg(OTTS_LOG_INFO, "Cache mechanisms..."); fwave = cache_lookup(*festival_message, festival_message_type, 1); if (fwave != NULL) { wave_cached = 1; if (fwave->num_samples != 0) { if (FestivalDebugSaveOutput) { char filename_debug [256]; sprintf(filename_debug, "/tmp/debug-festival-%d.snd", debug_count++); save_FT_Wave_snd(fwave, filename_debug); } festival_send_to_audio(fwave); if (!festival_stopped) { CLEAN_UP(0, module_report_event_end); } else { CLEAN_UP(0, module_report_event_stop); } } else { CLEAN_UP(0, module_report_event_end); } } } /* Set multi-mode for appropriate kind of events */ if (is_text(festival_message_type)) { /* it is a raw text */ ret = FestivalSetMultiMode(festival_info, "t"); if (ret != 0) CLP(0, module_report_event_stop); } else { /* it is some kind of event */ ret = FestivalSetMultiMode(festival_info, "nil"); if (ret != 0) CLP(0, module_report_event_stop); } switch (festival_message_type) { case SPD_MSGTYPE_TEXT: r = festivalStringToWaveRequest(festival_info, *festival_message); break; case SPD_MSGTYPE_SOUND_ICON: r = festivalSoundIcon(festival_info, *festival_message); break; case SPD_MSGTYPE_CHAR: r = festivalCharacter(festival_info, *festival_message); break; case SPD_MSGTYPE_KEY: r = festivalKey(festival_info, *festival_message); break; case SPD_MSGTYPE_SPELL: r = festivalSpell(festival_info, *festival_message); break; default: r = -1; } if (r < 0) { log_msg(OTTS_LOG_WARN, "Couldn't process the request to say the object."); CLP(0, module_report_event_stop); } } while (1) { wave_cached = 0; log_msg(OTTS_LOG_INFO, "Retrieving data\n"); /* (speechd-next) */ if (is_text(festival_message_type)) { if (festival_stopped) { log_msg(OTTS_LOG_INFO, "Module stopped 1"); CLEAN_UP(0, module_report_event_stop); } log_msg(OTTS_LOG_INFO, "Getting data in multi mode"); fwave = festivalGetDataMulti(festival_info, &callback, &festival_stop_request, FestivalReopenSocket); if (callback != NULL) { if ((festival_pause_requested) && (!strncmp (callback, INDEX_MARK_BODY, INDEX_MARK_BODY_LEN))) { log_msg(OTTS_LOG_NOTICE, "Pause requested, pausing."); module_report_index_mark (callback); g_free(callback); festival_pause_requested = 0; CLEAN_UP(0, module_report_event_pause); } else { module_report_index_mark (callback); g_free(callback); continue; } } } else { /* is event */ log_msg(OTTS_LOG_INFO, "Getting data in single mode"); fwave = festivalStringToWaveGetData(festival_info); terminate = 1; callback = NULL; } if (fwave == NULL) { log_msg(OTTS_LOG_INFO, "End of sound samples, terminating this message..."); CLEAN_UP(0, module_report_event_end); } if (festival_message_type == SPD_MSGTYPE_CHAR || festival_message_type == SPD_MSGTYPE_KEY || festival_message_type == SPD_MSGTYPE_SOUND_ICON) { log_msg(OTTS_LOG_DEBUG, "Storing record for %s in cache\n", *festival_message); /* cache_insert takes care of not inserting the same message again */ cache_insert(g_strdup(*festival_message), festival_message_type, fwave); wave_cached = 1; } if (festival_stopped) { log_msg(OTTS_LOG_NOTICE, "Module stopped 2"); CLEAN_UP(0, module_report_event_stop); } if (fwave->num_samples != 0) { log_msg(OTTS_LOG_INFO, "Sending message to audio: %ld bytes\n", (fwave->num_samples) * sizeof(short)); if (FestivalDebugSaveOutput) { char filename_debug[256]; sprintf(filename_debug, "/tmp/debug-festival-%d.snd", debug_count++); save_FT_Wave_snd(fwave, filename_debug); } log_msg(OTTS_LOG_INFO, "Playing sound samples"); festival_send_to_audio(fwave); if (!wave_cached) delete_FT_Wave(fwave); log_msg(OTTS_LOG_NOTICE, "End of playing sound samples"); } if (terminate) { log_msg(OTTS_LOG_INFO, "Ok, end of samples, returning"); CLP(0, module_report_event_end); } if (festival_stopped) { log_msg(OTTS_LOG_NOTICE, "Module stopped 3"); CLP(0, module_report_event_stop); } } } festival_stopped = 0; festival_speaking = 0; log_msg(OTTS_LOG_INFO, "festival: speaking thread ended.......\n"); pthread_exit(NULL); }
/** * @brief Resolve a domain name as an IP address. * * @param dns_str Name of the host to resolve. * @param hints Hints to reduce the number of result from getaddrinfo() * @param ip_str String where to store the resolve ip address * @param ip_bufsize Number of bytes available in the ip_str buffer * @param opts Client command line options * * @return 0 if successful, 1 if an error occured. */ int resolve_dst_addr(const char *dns_str, struct addrinfo *hints, char *ip_str, size_t ip_bufsize, fko_cli_options_t *opts) { int error; /* Function error return code */ struct addrinfo *result; /* Result of getaddrinfo() */ struct addrinfo *rp; /* Element of the linked list returned by getaddrinfo() */ #if WIN32 && WINVER <= 0x0600 struct sockaddr_in *in; char *win_ip; #else struct sockaddr_in *sai_remote; /* Remote host information as a sockaddr_in structure */ #endif /* Try to resolve the host name */ error = getaddrinfo(dns_str, NULL, hints, &result); if (error != 0) fprintf(stderr, "resolve_dst_addr() : %s\n", gai_strerror(error)); else { error = 1; /* Go through the linked list of addrinfo structures */ for (rp = result; rp != NULL; rp = rp->ai_next) { /* Apply --server-resolve-ipv4 criteria */ if(opts->spa_server_resolve_ipv4) { if(rp->ai_family != AF_INET) { log_msg(LOG_VERBOSITY_DEBUG, "Non-IPv4 resolution"); continue; } } memset(ip_str, 0, ip_bufsize); #if WIN32 && WINVER <= 0x0600 /* On older Windows systems (anything before Vista?), * we use inet_ntoa for now. */ in = (struct sockaddr_in*)(rp->ai_addr); win_ip = inet_ntoa(in->sin_addr); if (win_ip != NULL && (strlcpy(ip_str, win_ip, ip_bufsize) > 0)) #else sai_remote = (struct sockaddr_in *)get_in_addr((struct sockaddr *)(rp->ai_addr)); if (inet_ntop(rp->ai_family, sai_remote, ip_str, ip_bufsize) != NULL) #endif { error = 0; break; } else log_msg(LOG_VERBOSITY_ERROR, "resolve_dst_addr() : inet_ntop (%d) - %s", errno, strerror(errno)); } /* Free our result from getaddrinfo() */ freeaddrinfo(result); } return error; }
int main(int argc, char *argv[]) { char errbuf[PCAP_ERRBUF_SIZE]; char *dev; struct iface_config *ifc; int optind; int i; bzero(&cfg, sizeof(cfg)); /* Default configuration */ // cfg.ratelimit = 0; cfg.hashsize = 1; // cfg.quiet = 0; cfg.promisc_flag = 1; // cfg.ratelimit = 0; // cfg.sqlite_file = NULL; // cfg.uname = NULL; #if HAVE_LIBSQLITE3 cfg.sqlite_table = PACKAGE; #endif #if HAVE_LIBMYSQLCLIENT // cfg.mysql_db = NULL; cfg.mysql_table = PACKAGE; #endif argp_parse(&argp, argc, argv, 0, &optind, 0); if (!cfg.hostname) { cfg.hostname_len = sysconf(_SC_HOST_NAME_MAX); cfg.hostname = (char *)calloc(cfg.hostname_len, sizeof(char)); gethostname(cfg.hostname, cfg.hostname_len); } daemonize(); save_pid(); log_open(); libevent_init(); if (cfg.ratelimit > 0) log_msg(LOG_DEBUG, "Ratelimiting duplicate entries to 1 per %d seconds", cfg.ratelimit); else if (cfg.ratelimit == -1) log_msg(LOG_DEBUG, "Duplicate entries supressed indefinitely"); else log_msg(LOG_DEBUG, "Duplicate entries ratelimiting disabled"); if (cfg.promisc_flag) log_msg(LOG_DEBUG, "PROMISC mode enabled"); else log_msg(LOG_DEBUG, "PROMISC mode disabled"); if (argc > optind) { for (i = optind; i < argc; i++) add_iface(argv[i]); } else { dev = pcap_lookupdev(errbuf); if (dev != NULL) add_iface(dev); } if (!cfg.interfaces) log_msg(LOG_ERR, "No suitable interfaces found!"); if (cfg.uname) drop_root(cfg.uname); output_flatfile_init(); output_sqlite_init(); output_mysql_init(); /* main loop */ #if HAVE_LIBEVENT2 event_base_dispatch(cfg.eb); #else event_dispatch(); #endif output_mysql_close(); output_sqlite_close(); output_flatfile_close(); for (ifc = cfg.interfaces; ifc != NULL; ifc = del_iface(ifc)); libevent_close(); log_close(); del_pid(); blacklist_free(); free(cfg.hostname); return 0; }
/****************************************************************************** run_test() Run the given test case. ******************************************************************************/ void run_test(char *test) { char temp[PATH_MAX]; char *rstr; double elapsed = 0; int skip = FALSE, ignore=FALSE; int restart = FALSE; int flag = FALSE; struct stat info; // skip tests in the skip list snprintf(temp, PATH_MAX, " %s ", test); skip = (strindex(skip_test, temp) != NULL); if (skip == FALSE) ignore = (strindex(ignore_test, temp) != NULL); if (ignore) { // show test log_msg("%-46s ", test); // ignore rstr = TEST_IGNORE; ++total_ignore; } else if (!skip) // skip test? { char test_file[PATH_MAX]; char master_opt_file[PATH_MAX]; char slave_opt_file[PATH_MAX]; char slave_master_info_file[PATH_MAX]; char result_file[PATH_MAX]; char reject_file[PATH_MAX]; char out_file[PATH_MAX]; char err_file[PATH_MAX]; int err; arg_list_t al; NXTime_t start, stop; // skip slave? flag = skip_slave; skip_slave = (strncmp(test, "rpl", 3) != 0); if (flag != skip_slave) restart = TRUE; // create files snprintf(master_opt_file, PATH_MAX, "%s/%s-master.opt", test_dir, test); snprintf(slave_opt_file, PATH_MAX, "%s/%s-slave.opt", test_dir, test); snprintf(slave_master_info_file, PATH_MAX, "%s/%s.slave-mi", test_dir, test); snprintf(reject_file, PATH_MAX, "%s/%s%s", result_dir, test, REJECT_SUFFIX); snprintf(out_file, PATH_MAX, "%s/%s%s", result_dir, test, OUT_SUFFIX); snprintf(err_file, PATH_MAX, "%s/%s%s", result_dir, test, ERR_SUFFIX); // netware specific files snprintf(test_file, PATH_MAX, "%s/%s%s", test_dir, test, NW_TEST_SUFFIX); if (stat(test_file, &info)) { snprintf(test_file, PATH_MAX, "%s/%s%s", test_dir, test, TEST_SUFFIX); if (access(test_file,0)) { printf("Invalid test name %s, %s file not found\n",test,test_file); return; } } snprintf(result_file, PATH_MAX, "%s/%s%s", result_dir, test, NW_RESULT_SUFFIX); if (stat(result_file, &info)) { snprintf(result_file, PATH_MAX, "%s/%s%s", result_dir, test, RESULT_SUFFIX); } // init scripts snprintf(master_init_script, PATH_MAX, "%s/%s-master.sh", test_dir, test); if (stat(master_init_script, &info)) master_init_script[0] = NULL; else restart = TRUE; snprintf(slave_init_script, PATH_MAX, "%s/%s-slave.sh", test_dir, test); if (stat(slave_init_script, &info)) slave_init_script[0] = NULL; else restart = TRUE; // read options if (read_option(master_opt_file, master_opt)) restart = TRUE; if (read_option(slave_opt_file, slave_opt)) restart = TRUE; if (read_option(slave_master_info_file, slave_master_info)) restart = TRUE; // cleanup previous run remove(reject_file); remove(out_file); remove(err_file); // start or restart? if (!master_running) mysql_start(); else if (restart) mysql_restart(); // let the system stabalize sleep(1); // show test log_msg("%-46s ", test); // args init_args(&al); add_arg(&al, "%s", mysqltest_file); add_arg(&al, "--no-defaults"); add_arg(&al, "--port=%u", master_port); add_arg(&al, "--database=%s", db); add_arg(&al, "--user=%s", user); add_arg(&al, "--password=%s", password); add_arg(&al, "--silent"); add_arg(&al, "--basedir=%s/", mysql_test_dir); add_arg(&al, "--host=127.0.0.1"); add_arg(&al, "-v"); add_arg(&al, "-R"); add_arg(&al, "%s", result_file); if (use_openssl) { add_arg(&al, "--ssl-ca=%s", ca_cert); add_arg(&al, "--ssl-cert=%s", client_cert); add_arg(&al, "--ssl-key=%s", client_key); } // start timer NXGetTime(NX_SINCE_BOOT, NX_USECONDS, &start); // spawn err = spawn(mysqltest_file, &al, TRUE, test_file, out_file, err_file); // stop timer NXGetTime(NX_SINCE_BOOT, NX_USECONDS, &stop); // calculate elapsed = ((double)(stop - start)) / NX_USECONDS; total_time += elapsed; // free args free_args(&al); if (err == 0) { // pass rstr = TEST_PASS; ++total_pass; // increment total ++total_test; } else if (err == 62) { // skip rstr = TEST_SKIP; ++total_skip; } else if (err == 1) { // fail rstr = TEST_FAIL; ++total_fail; // increment total ++total_test; } else { rstr = TEST_BAD; } } else // early skips { // show test log_msg("%-46s ", test); // skip rstr = TEST_SKIP; ++total_skip; } // result log_msg("%10.06f %-14s\n", elapsed, rstr); }