/** * Example of a simple notification listener */ int main(int argc, char *argv[]) { error_notify_msg_t msg; int s, len, total; void *pos; s = make_connection(); if (s < 0) { return 1; } while (1) { total = 0; pos = &msg; while (total < sizeof(msg)) { len = read(s, pos, sizeof(msg) - total); if (len < 0) { fprintf(stderr, "read failed: %s\n", strerror(errno)); close(s); return 1; } total += len; pos += len; } printf("%d %s %s %s %s\n", ntohl(msg.type), msg.name, msg.id, msg.ip, msg.str); } close(s); return 0; }
int main (int argc, char *argv[]) { #ifdef WIN32 WSADATA wsaData; WORD wVersionRequired = (1 << 8) + 1; #endif if (argc < 3) exit (1); #ifndef WIN32 signal (SIGPIPE, SIG_IGN); #else if (WSAStartup (wVersionRequired, &wsaData)) { printf ("*** FAILED: Windows sockets unable to initialize\n"); exit (1); } #endif make_connection (argv[1], atoi (argv[2]), &fd); if (0 > read_resp (stdout)) exit (3); if (SendMailFile (stdin)) return 0; else exit (2); }
connection_struct *make_connection_with_chdir(const char *service_in, DATA_BLOB password, const char *dev, uint16 vuid, NTSTATUS *status) { connection_struct *conn = NULL; conn = make_connection(service_in, password, dev, vuid, status); /* * make_connection() does not change the directory for us any more * so we have to do it as a separate step --jerry */ if ( conn && vfs_ChDir(conn,conn->connectpath) != 0 ) { DEBUG(0,("move_driver_to_download_area: Can't change " "directory to %s for [print$] (%s)\n", conn->connectpath,strerror(errno))); yield_connection(conn, lp_servicename(SNUM(conn))); conn_free(conn); *status = NT_STATUS_UNSUCCESSFUL; return NULL; } return conn; }
int chlogif_check_connect_logserver(int tid, unsigned int tick, int id, intptr_t data) { if (login_fd > 0 && session[login_fd] != NULL) return 0; ShowInfo("Attempt to connect to login-server...\n"); login_fd = make_connection(charserv_config.login_ip, charserv_config.login_port, false,10); if (login_fd == -1) { //Try again later. [Skotlex] login_fd = 0; return 0; } session[login_fd]->func_parse = chlogif_parse; session[login_fd]->flag.server = 1; realloc_fifo(login_fd, FIFOSIZE_SERVERLINK, FIFOSIZE_SERVERLINK); WFIFOHEAD(login_fd,86); WFIFOW(login_fd,0) = 0x2710; memcpy(WFIFOP(login_fd,2), charserv_config.userid, 24); memcpy(WFIFOP(login_fd,26), charserv_config.passwd, 24); WFIFOL(login_fd,50) = 0; WFIFOL(login_fd,54) = htonl(charserv_config.char_ip); WFIFOW(login_fd,58) = htons(charserv_config.char_port); memcpy(WFIFOP(login_fd,60), charserv_config.server_name, 20); WFIFOW(login_fd,80) = 0; WFIFOW(login_fd,82) = charserv_config.char_maintenance; WFIFOW(login_fd,84) = charserv_config.char_new_display; //only display (New) if they want to [Kevin] WFIFOSET(login_fd,86); return 1; }
void level::install_sender() { do { _senderX = static_cast<unsigned short>(mtrandom::random(0, static_cast<int>(_size_cell))); _senderY = static_cast<unsigned short>(mtrandom::random(0, static_cast<int>(_size_cell))); } while (!_wrap_mode && (_senderX == 0 || _senderX == _size_cell - 1 || _senderY == 0 || _senderY == _size_cell - 1)); cell& srv = cell_at(_senderX, _senderY); srv.set_type_sender(); //Define zero point (sender output cell) _zeroX = _senderX; _zeroY = _senderY; switch (mtrandom::random(0, 4)) { case 0: _zeroX = (_zeroX + 1) % _size_cell; break; case 1: _zeroX = _zeroX == 0 ? _size_cell - 1 : _zeroX - 1; break; case 2: _zeroY = (_zeroY + 1) % _size_cell; break; case 3: _zeroY = _zeroY == 0 ? _size_cell - 1 : _zeroY - 1; break; default: assert(false); break; } make_connection(_senderX, _senderY, _zeroX, _zeroY); }
void login(iscsid_login_req_t * req, iscsid_response_t * res) { session_t *sess; connection_t *conn; sess = calloc(1, sizeof(*sess)); if (sess == NULL) { res->status = ISCSID_STATUS_NO_RESOURCES; return; } TAILQ_INIT(&sess->connections); strlcpy((char *)sess->entry.sid.name, (char *)req->sym_name, sizeof(sess->entry.sid.name)); LOCK_SESSIONS; conn = make_connection(sess, req, res, 0); if (conn == NULL) free(sess); else { sess->target = conn->target; TAILQ_INSERT_TAIL(&list[SESSION_LIST].list, &sess->entry, link); list[SESSION_LIST].num_entries++; } UNLOCK_SESSIONS; }
/*========================================== * timerFunction * Chk the connection to char server, (if it down) *------------------------------------------*/ static int check_connect_char_server(int tid, unsigned int tick, int id, intptr_t data) { static int displayed = 0; if ( char_fd <= 0 || session[char_fd] == NULL ) { if ( !displayed ) { ShowStatus("Attempting to connect to Char Server. Please wait.\n"); displayed = 1; } chrif_state = 0; char_fd = make_connection(char_ip, char_port,false); if (char_fd == -1)//Attempt to connect later. [Skotlex] return 0; session[char_fd]->func_parse = chrif_parse; session[char_fd]->flag.server = 1; realloc_fifo(char_fd, FIFOSIZE_SERVERLINK, FIFOSIZE_SERVERLINK); chrif_connect(char_fd); chrif_connected = (chrif_state == 2); srvinfo = 0; } else { if (srvinfo == 0) { chrif_ragsrvinfo(battle_config.base_exp_rate, battle_config.job_exp_rate, battle_config.item_rate_common); srvinfo = 1; } } if ( chrif_isconnected() ) displayed = 0; return 0; }
int main(int argc, const char **argv) { amqp_connection_state_t conn; char *queue = NULL; int got_something; struct poptOption options[] = { INCLUDE_OPTIONS(connect_options), {"queue", 'q', POPT_ARG_STRING, &queue, 0, "the queue to consume from", "queue"}, POPT_AUTOHELP { NULL, 0, 0, NULL, 0 } }; process_all_options(argc, argv, options); if (!queue) { fprintf(stderr, "queue not specified\n"); return 1; } conn = make_connection(); got_something = do_get(conn, queue); close_connection(conn); return got_something ? 0 : 2; }
static void tell_emacs_to_resume(int sig) { char buffer[GSERV_BUFSZ + 1]; int sz; int s; /* socket / msqid to server */ int connect_type; /* CONN_UNIX, CONN_INTERNET, or ONN_IPC */ /* Why is SYSV so retarded? */ /* We want emacs to realize that we are resuming */ #ifdef SIGCONT signal(SIGCONT, tell_emacs_to_resume); #endif connect_type = make_connection(NULL, 0, &s); SNPRINTF(sz, buffer, sizeof(buffer), "(gnuserv-eval '(resume-pid-console %d))", (int)getpid()); send_string(s, buffer); #ifdef SYSV_IPC if (connect_type == (int)CONN_IPC) disconnect_from_ipc_server(s, msgp, FALSE); #else /* !SYSV_IPC */ if (connect_type != (int)CONN_IPC) disconnect_from_server(s, FALSE); #endif /* !SYSV_IPC */ }
/************************************************************************** Try to connect to a server (get_server_address() must be called first!): - try to create a TCP socket and connect it to `server_addr' - if successful: - start monitoring the socket for packets from the server - send a "login request" packet to the server and - return 0 - if unable to create the connection, close the socket, put an error message in ERRBUF and return the Unix error code (ie., errno, which will be non-zero). **************************************************************************/ static int try_to_connect(const char *username, char *errbuf, int errbufsize) { close_socket_set_callback(close_socket_callback); /* connection in progress? wait. */ if (client.conn.used) { (void) mystrlcpy(errbuf, _("Connection in progress."), errbufsize); return -1; } if ((client.conn.sock = socket(server_addr.saddr.sa_family, SOCK_STREAM, 0)) == -1) { (void) mystrlcpy(errbuf, fc_strerror(fc_get_errno()), errbufsize); return -1; } if (fc_connect(client.conn.sock, &server_addr.saddr, sockaddr_size(&server_addr)) == -1) { (void) mystrlcpy(errbuf, fc_strerror(fc_get_errno()), errbufsize); fc_closesocket(client.conn.sock); client.conn.sock = -1; #ifdef HAVE_WINSOCK return -1; #else return errno; #endif } make_connection(client.conn.sock, username); return 0; }
int main(int argc,char **argv) { int sockfd,newsockfd; arg_check(argc); sockfd=set_server(NULL,argv[1]); newsockfd=make_connection(sockfd); GET(newsockfd); }
jstring Java_euphoria_psycho_comic_util_Utilities_request(JNIEnv *env, jstring host, jstring path) { const char *n_host = (*env)->GetStringUTFChars(env, host, 0); const char *n_path = (*env)->GetStringUTFChars(env, path, 0); LOGW("%s",n_host); Buffer *response = buffer_alloc(255); int status = 0; int sockfd = 0; struct addrinfo *res = NULL; status = init_connection(n_host, "80", &res); error_unless(status == 0, "Could not resolve host: %s\n", gai_strerror(status)); jstring result1 = (*env)->NewStringUTF(env, n_host); return result1; sockfd = make_connection(res); error_unless(sockfd > 0, "Could not make connection to '"); status = make_request(sockfd, n_host, n_path); error_unless(status > 0, "Sending request failed"); status = fetch_response(sockfd, &response, RECV_SIZE); error_unless(status >= 0, "Fetching response failed"); printf("%s\n", response->contents); close(sockfd); freeaddrinfo(res); jstring result = (*env)->NewStringUTF(env, response->contents); buffer_free(response); (*env)->ReleaseStringUTFChars(env, host, n_host); (*env)->ReleaseStringUTFChars(env, path, n_path); return result; error: if (sockfd > 0) { close(sockfd); } if (res != NULL) { freeaddrinfo(res); } (*env)->ReleaseStringUTFChars(env, host, n_host); (*env)->ReleaseStringUTFChars(env, path, n_path); return (*env)->NewStringUTF(env, "Error"); buffer_free(response); // return (*env)->NewStringUTF(env, "Hello from JNI ! Compiled with ABI " // ABI // "."); }
void finger_func(struct connection *c) { int p; if ((p = get_port(c->url)) == -1) { setcstate(c, S_INTERNAL); abort_connection(c); return; } c->from = 0; make_connection(c, p, &c->sock1, finger_send_request); }
/**************************************************************************** A callback that GGZ calls when we are connected to the freeciv server. ****************************************************************************/ static void handle_ggzmod_server(GGZMod * ggzmod, GGZModEvent e, const void *data) { const int *socket = data; const char *username = ggzmod_get_player(ggzmod, NULL, NULL); if (!username) { username = "******"; } make_connection(*socket, username); }
static void reconnect(conn_t *conn) { if(++tries > 3) { EXIT_PROGRAM(RECONNECT_FAIL); } if (conn->sd != -1) close(conn->sd); if (make_connection(conn->remote, conn) < 0) { print_con_info(conn, "Unable to reconnect to %s: %s", conn->remote, strerror(errno)); EXIT_PROGRAM(RECONNECT_FAIL); } tries = 0; }
/* backend for tree connect call */ NTSTATUS smbsrv_tcon_backend(struct smbsrv_request *req, union smb_tcon *con) { NTSTATUS status; if (con->generic.level == RAW_TCON_TCON) { DATA_BLOB password; password = data_blob_string_const(con->tcon.in.password); status = make_connection(req, con->tcon.in.service, password, con->tcon.in.dev); if (!NT_STATUS_IS_OK(status)) { return status; } con->tcon.out.max_xmit = req->smb_conn->negotiate.max_recv; con->tcon.out.tid = req->tcon->tid; return status; } /* TODO: take a look at tconx.in.flags! */ status = make_connection(req, con->tconx.in.path, con->tconx.in.password, con->tconx.in.device); if (!NT_STATUS_IS_OK(status)) { return status; } con->tconx.out.tid = req->tcon->tid; con->tconx.out.dev_type = talloc_strdup(req, req->tcon->ntvfs->dev_type); con->tconx.out.fs_type = talloc_strdup(req, req->tcon->ntvfs->fs_type); con->tconx.out.options = SMB_SUPPORT_SEARCH_BITS | (share_int_option(req->tcon->ntvfs->config, SHARE_CSC_POLICY, SHARE_CSC_POLICY_DEFAULT) << 2); if (share_bool_option(req->tcon->ntvfs->config, SHARE_MSDFS_ROOT, SHARE_MSDFS_ROOT_DEFAULT) && lp_host_msdfs(req->smb_conn->lp_ctx)) { con->tconx.out.options |= SMB_SHARE_IN_DFS; } return status; }
void ftp_func(struct connection *c) { /*setcstate(c, S_CONN);*/ /*set_timeout(c);*/ if (get_keepalive_socket(c)) { int p; if ((p = get_port(c->url)) == -1) { setcstate(c, S_INTERNAL); abort_connection(c); return; } make_connection(c, p, &c->sock1, ftp_options.fast_ftp ? ftp_login : ftp_get_banner); } else ftp_send_retr_req(c, S_SENT); }
void http_func(struct connection *c) { /*setcstate(c, S_CONN);*/ /*set_timeout(c);*/ if (get_keepalive_socket(c)) { int p; if ((p = get_port(c->url)) == -1) { setcstate(c, S_INTERNAL); abort_connection(c); return; } make_connection(c, p, &c->sock1, http_send_header); } else http_send_header(c); }
/* Establish connection to a peer. As a backend, it uses the internal and more * generic connection creater which takes care of DNS querying etc. */ enum bittorrent_state make_bittorrent_peer_connection(struct bittorrent_connection *bittorrent, struct bittorrent_peer *peer_info) { enum bittorrent_state result = BITTORRENT_STATE_OUT_OF_MEM; struct uri *uri = NULL; struct string uri_string = NULL_STRING; struct bittorrent_peer_connection *peer; peer = init_bittorrent_peer_connection(-1); if (!peer) goto out; peer->local.initiater = 1; add_to_list(bittorrent->peers, peer); peer->bittorrent = bittorrent; peer->bitfield = init_bitfield(bittorrent->meta.pieces); if (!peer->bitfield) goto out; memcpy(peer->id, peer_info->id, sizeof(peer->id)); /* XXX: Very hacky; construct a fake URI from which make_connection() * can extract the IP address and port number. */ /* FIXME: Rather change the make_connection() interface. This is an ugly * hack. */ if (!init_string(&uri_string)) goto out; if (!add_format_to_string(&uri_string, #ifdef CONFIG_IPV6 strchr((const char *)peer_info->ip, ':') ? "bittorrent-peer://[%s]:%u/" : #endif "bittorrent-peer://%s:%u/", peer_info->ip, (unsigned) peer_info->port)) goto out; uri = get_uri(uri_string.source, 0); if (!uri) goto out; make_connection(peer->socket, uri, send_bittorrent_peer_handshake, 1); result = BITTORRENT_STATE_OK; out: if (uri) done_uri(uri); done_string(&uri_string); if (peer && result != BITTORRENT_STATE_OK) done_bittorrent_peer_connection(peer); return result; }
/************************************************************************** Try to connect to a server (get_server_address() must be called first!): - try to create a TCP socket and connect it to `names' - if successful: - start monitoring the socket for packets from the server - send a "login request" packet to the server and - return 0 - if unable to create the connection, close the socket, put an error message in ERRBUF and return the Unix error code (ie., errno, which will be non-zero). **************************************************************************/ static int try_to_connect(const char *username, char *errbuf, int errbufsize) { int i; int sock = -1; connections_set_close_callback(client_conn_close_callback); /* connection in progress? wait. */ if (client.conn.used) { (void) fc_strlcpy(errbuf, _("Connection in progress."), errbufsize); return -1; } /* Try all (IPv4, IPv6, ...) addresses until we have a connection. */ sock = -1; for (i = 0; i < name_count; i++) { if ((sock = socket(names[i].saddr.sa_family, SOCK_STREAM, 0)) == -1) { /* Probably EAFNOSUPPORT or EPROTONOSUPPORT. */ continue; } if (fc_connect(sock, &names[i].saddr, sockaddr_size(&names[i])) == -1) { fc_closesocket(sock); sock = -1; continue; } else { /* We have a connection! */ break; } } client.conn.sock = sock; if (client.conn.sock == -1) { fc_errno err = fc_get_errno(); /* Save errno value before calling anything */ (void) fc_strlcpy(errbuf, fc_strerror(err), errbufsize); #ifdef HAVE_WINSOCK return -1; #else return err; #endif /* HAVE_WINSOCK */ } make_connection(client.conn.sock, username); return 0; }
status_t handle_port_command(user_session_t *session, string_t *args, size_t len) { status_t error; if (!session->server->port_enabled) { //This command can't actually send back a 'not implemented' response, so //approximate it with an "unrecognized command" response error = send_500(session); goto exit0; } if (!session->logged_in) { error = send_530(session); goto exit0; } size_t ip_len; string_t *split = string_split(args + 1, ',', &ip_len); string_t host; string_initialize(&host); uint16_t port; error = parse_ip_and_port(split, ip_len, &host, &port); if (error) { error = send_501(session); goto exit1; } error = make_connection(&session->data_sock, string_c_str(&host), port); if (error) { send_response(session->command_sock, SERVICE_NOT_AVAILABLE, "Could not connect to port", session->server->log, 0); goto exit1; } error = send_200(session); if (error) { goto exit1; } exit1: string_uninitialize(&host); exit0: return error; }
void add_connection(iscsid_login_req_t * req, iscsid_response_t * res) { session_t *sess; LOCK_SESSIONS; sess = find_session(&req->session_id); if (sess == NULL) { UNLOCK_SESSIONS; res->status = ISCSID_STATUS_INVALID_SESSION_ID; return; } make_connection(sess, req, res, 0); UNLOCK_SESSIONS; }
bool level::make_route(const unsigned short x, const unsigned short y) { unsigned short next_x = 0, next_y = 0; //Next coordinates bool result = false; int try_counter = 5; while (try_counter && !result) { short i, j; do { i = 1 - static_cast<unsigned short>(mtrandom::random(0, 3)); j = 1 - static_cast<unsigned short>(mtrandom::random(0, 3)); } while ((i && j) || (!i && !j)); //Diagonal if (!_wrap_mode) { if ((j < 0 && x == 0) || (j > 0 && x == _size_cell - 1) || (i < 0 && y == 0) || (i > 0 && y == _size_cell - 1)) { --try_counter; continue; } } const unsigned short cp_x = (j < 0 && x == 0) ? _size_cell - 1 : (x + j) % _size_cell; const unsigned short cp_y = (i < 0 && y == 0) ? _size_cell - 1 : (y + i) % _size_cell; cell& cell = cell_at(cp_x, cp_y); if (!cell.is_used() && cell.can_add_tube()) { result = true; next_x = cp_x; next_y = cp_y; } --try_counter; } if (!result) return false; //min point - we don't have a route make_connection(x, y, next_x, next_y); cell_at(x, y).set_used(true); if (cell_at(next_x, next_y).tube_type() == cell::tt_joiner || (next_x == _zeroX && next_y == _zeroY)) return true; return make_route(next_x, next_y); }
int main(int argc, char *argv[]) { char buf[128]; int fd, len; u_int16_t msglen; fd = make_connection(); if (fd < 0) { return 1; } while (1) { len = recv(fd, &msglen, sizeof(msglen), 0); if (len != sizeof(msglen)) { break; } msglen = ntohs(msglen); while (msglen) { if (sizeof(buf) > msglen) { len = msglen; } else { len = sizeof(buf); } len = recv(fd, &buf, len, 0); if (len < 0) { break; } msglen -= len; printf("%.*s", len, buf); } printf("\n"); if (len < 0) { break; } } fprintf(stderr, "reading from socket failed: %s\n", strerror(errno)); close(fd); return 1; }
int main(int argc, const char **argv) { amqp_connection_state_t conn; char *queue = NULL; int durable = 0; struct poptOption options[] = { INCLUDE_OPTIONS(connect_options), { "queue", 'q', POPT_ARG_STRING, &queue, 0, "the queue name to declare, or the empty string", "queue" }, { "durable", 'd', POPT_ARG_VAL, &durable, 1, "declare a durable queue", NULL }, POPT_AUTOHELP { NULL, '\0', 0, NULL, 0, NULL, NULL } }; process_all_options(argc, argv, options); if (queue == NULL) { fprintf(stderr, "queue name not specified\n"); return 1; } conn = make_connection(); { amqp_queue_declare_ok_t *reply = amqp_queue_declare(conn, 1, cstring_bytes(queue), 0, durable, 0, 0, amqp_empty_table); if (reply == NULL) { die_rpc(amqp_get_rpc_reply(conn), "queue.declare"); } printf("%.*s\n", (int)reply->queue.len, (char *)reply->queue.bytes); } close_connection(conn); return 0; }
int main(int argc, const char **argv) { amqp_connection_state_t conn; char *queue = NULL; int if_unused = 0; int if_empty = 0; struct poptOption options[] = { INCLUDE_OPTIONS(connect_options), {"queue", 'q', POPT_ARG_STRING, &queue, 0, "the queue name to delete", "queue"}, {"if-unused", 'u', POPT_ARG_VAL, &if_unused, 1, "do not delete unless queue is unused", NULL}, {"if-empty", 'e', POPT_ARG_VAL, &if_empty, 1, "do not delete unless queue is empty", NULL}, POPT_AUTOHELP { NULL, 0, 0, NULL, 0 } }; process_all_options(argc, argv, options); if (queue == NULL || *queue == '\0') { fprintf(stderr, "queue name not specified\n"); return 1; } conn = make_connection(); { amqp_queue_delete_ok_t *reply = amqp_queue_delete(conn, 1, cstring_bytes(queue), if_unused, if_empty); if (reply == NULL) { die_rpc(amqp_get_rpc_reply(conn), "queue.delete"); } printf("%u\n", reply->message_count); } close_connection(conn); return 0; }
/*========================================== * timer�� * char�I�Ƃ̐ڑ����m�F���A������Ă�����ēx�ڑ����� *------------------------------------------*/ static int check_connect_char_server(int tid, unsigned int tick, int id, intptr_t data) { static int displayed = 0; if (char_fd <= 0 || session[char_fd] == NULL) { if (!displayed) { ShowStatus("Estabelecendo conexao com o servidor de personagens. Por favor aguarde.\n"); displayed = 1; } chrif_state = 0; char_fd = make_connection(char_ip, char_port); if (char_fd == -1) { //Attempt to connect later. [Skotlex] return 0; } session[char_fd]->func_parse = chrif_parse; session[char_fd]->flag.server = 1; realloc_fifo(char_fd, FIFOSIZE_SERVERLINK, FIFOSIZE_SERVERLINK); chrif_connect(char_fd); chrif_connected = (chrif_state == 2); #ifndef TXT_ONLY srvinfo = 0; #endif /* not TXT_ONLY */ } else { #ifndef TXT_ONLY if (srvinfo == 0) { chrif_ragsrvinfo(battle_config.base_exp_rate, battle_config.job_exp_rate, battle_config.item_rate_common); srvinfo = 1; } #endif /* not TXT_ONLY */ } if (chrif_isconnected()) displayed = 0; return 0; }
/** * <JA> * メイン関数 * * @param argc [in] 引数列の長さ * @param argv [in] 引数列 * * @return * </JA>エラー時 1,通常終了時 0 を返す. * <EN> * Main function. * * @param argc [in] number of argument. * @param argv [in] array of arguments. * * @return 1 on error, 0 on success. * </EN> */ int main(int argc, char *argv[]) { Recog *recog; Jconf *jconf; int ret; int i; boolean is_continues; /* create instance */ recog = j_recog_new(); jconf = j_jconf_new(); recog->jconf = jconf; /********************/ /* setup parameters */ /********************/ /* register additional options */ j_add_option("-in", 1, 1, "input from", opt_in); j_add_option("-out", 1, 1, "output to", opt_out); j_add_option("-server", 1, 1, "hostname (-out adinnet)", opt_server); j_add_option("-NA", 1, 1, "NetAudio server host:unit (-in netaudio)", opt_NA); j_add_option("-port", 1, 1, "port number (-out adinnet)", opt_port); j_add_option("-inport", 1, 1, "port number (-in adinnet)", opt_inport); j_add_option("-filename", 1, 1, "(base) filename to record (-out file)", opt_filename); j_add_option("-startid", 1, 1, "recording start id (-out file)", opt_startid); j_add_option("-freq", 1, 1, "sampling frequency in Hz", opt_freq); j_add_option("-nosegment", 0, 0, "not segment input speech, record all", opt_nosegment); j_add_option("-segment", 0, 0, "force segment input speech", opt_segment); j_add_option("-oneshot", 0, 0, "exit after the first input", opt_oneshot); j_add_option("-raw", 0, 0, "save in raw (BE) format", opt_raw); j_add_option("-autopause", 0, 0, "automatically pause at each input end", opt_autopause); j_add_option("-loosesync", 0, 0, "loose sync of resume among servers", opt_loosesync); j_add_option("-rewind", 1, 1, "rewind to the msec", opt_rewind); j_add_option("-h", 0, 0, "display this help", opt_help); j_add_option("-help", 0, 0, "display this help", opt_help); j_add_option("--help", 0, 0, "display this help", opt_help); /* when no argument, output help and exit */ if (argc <= 1) { opt_help(jconf, NULL, 0); return 0; } /* read arguments and set parameters */ if (j_config_load_args(jconf, argc, argv) == -1) { fprintf(stderr, "Error reading arguments\n"); return -1; } /* check needed arguments */ if (speech_output == SPOUT_FILE && filename == NULL) { fprintf(stderr, "Error: output filename not specified\n"); return(-1); } if (speech_output == SPOUT_ADINNET && adinnet_servnum < 1) { fprintf(stderr, "Error: adinnet server name for output not specified\n"); return(-1); } if (jconf->input.speech_input == SP_ADINNET && speech_output != SPOUT_ADINNET && adinnet_servnum >= 1) { fprintf(stderr, "Warning: you specified port num by -port, but it's for output\n"); fprintf(stderr, "Warning: you may specify input port by -inport instead.\n"); fprintf(stderr, "Warning: now the default value (%d) will be used\n", ADINNET_PORT); } #ifdef USE_NETAUDIO if (jconf->input.speech_input == SP_NETAUDIO && jconf->input.netaudio_devname == NULL) { fprintf(stderr, "Error: NetAudio server name not specified\n"); return(-1); } #endif if (adinnet_portnum != adinnet_servnum) { /* if only one server, use default */ if (adinnet_servnum == 1) { adinnet_port[0] = ADINNET_PORT; adinnet_portnum = 1; } else { fprintf(stderr, "Error: you should specify both server names and different port for each!\n"); fprintf(stderr, "\tserver:"); for(i=0;i<adinnet_servnum;i++) fprintf(stderr, " %s", adinnet_serv[i]); fprintf(stderr, "\n\tport :"); for(i=0;i<adinnet_portnum;i++) fprintf(stderr, " %d", adinnet_port[i]); fprintf(stderr, "\n"); return(-1); } } /* set Julius default parameters for unspecified acoustic parameters */ apply_para(&(jconf->am_root->analysis.para), &(jconf->am_root->analysis.para_default)); /* set some values */ jconf->input.sfreq = jconf->am_root->analysis.para.smp_freq; jconf->input.period = jconf->am_root->analysis.para.smp_period; jconf->input.frameshift = jconf->am_root->analysis.para.frameshift; jconf->input.framesize = jconf->am_root->analysis.para.framesize; /* disable successive segmentation when no segmentation available */ if (!jconf->detect.silence_cut) continuous_segment = FALSE; /* store sampling rate locally */ sfreq = jconf->am_root->analysis.para.smp_freq; /********************/ /* setup for output */ /********************/ if (speech_output == SPOUT_FILE) { /* allocate work area for output file name */ if (continuous_segment) { outpath = (char *)mymalloc(strlen(filename) + 10); } else { if (use_raw) { outpath = filename; } else { outpath = new_output_filename(filename, ".wav"); } } } else if (speech_output == SPOUT_ADINNET) { /* connect to adinnet server(s) */ for(i=0;i<adinnet_servnum;i++) { fprintf(stderr, "connecting to #%d (%s:%d)...", i+1, adinnet_serv[i], adinnet_port[i]); sd[i] = make_connection(adinnet_serv[i], adinnet_port[i]); if (sd[i] < 0) return 1; /* on error */ fprintf(stderr, "connected\n"); } } else if (speech_output == SPOUT_STDOUT) { /* output to stdout */ fd = 1; fprintf(stderr,"[STDOUT]"); } /**********************/ /* interrupt handling */ /**********************/ if (signal(SIGINT, interrupt_record) == SIG_ERR) { fprintf(stderr, "Warning: signal interruption may collapse output\n"); } if (signal(SIGTERM, interrupt_record) == SIG_ERR) { fprintf(stderr, "Warning: signal interruption may collapse output\n"); } #ifdef SIGPIPE if (signal(SIGPIPE, interrupt_record) == SIG_ERR) { fprintf(stderr, "Warning: signal interruption may collapse output\n"); } #endif #ifdef SIGQUIT if (signal(SIGQUIT, interrupt_record) == SIG_ERR) { fprintf(stderr, "Warning: signal interruption may collapse output\n"); } #endif /***************************/ /* initialize input device */ /***************************/ if (jconf->input.speech_input == SP_ADINNET) { jconf->input.adinnet_port = adinnet_port_in; } if (j_adin_init(recog) == FALSE) { fprintf(stderr, "Error in initializing adin device\n"); return -1; } if (rewind_msec > 0) { /* allow adin module to keep triggered speech while pausing */ #ifdef HAVE_PTHREAD if (recog->adin->enable_thread) { recog->adin->ignore_speech_while_recog = FALSE; } #endif } /*********************/ /* add some callback */ /*********************/ callback_add(recog, CALLBACK_EVENT_SPEECH_START, record_trigger_time, NULL); /**************************************/ /* display input/output configuration */ /**************************************/ put_status(recog); /*******************/ /* begin recording */ /*******************/ if (continuous_segment) { /* reset parameter for successive output */ total_speechlen = 0; sid = startid; } fprintf(stderr,"[start recording]\n"); if (jconf->input.speech_input == SP_RAWFILE) file_counter = 0; /*********************/ /* input stream loop */ /*********************/ while(1) { /* begin A/D input of a stream */ ret = j_open_stream(recog, NULL); switch(ret) { case 0: /* succeeded */ break; case -1: /* error */ /* go on to next input */ continue; case -2: /* end of recognition process */ switch(jconf->input.speech_input) { case SP_RAWFILE: fprintf(stderr, "%d files processed\n", file_counter); break; case SP_STDIN: fprintf(stderr, "reached end of input on stdin\n"); break; default: fprintf(stderr, "failed to begin input stream\n"); } /* exit recording */ goto record_end; } /*********************************/ /* do VAD and recording */ /*********************************/ do { /* process one segment with segmentation */ /* for incoming speech input, speech detection and segmentation are performed and, adin_callback_* is called for speech output for each segment block. */ /* adin_go() return when input segmented by long silence, or input stream reached to the end */ speechlen = 0; stop_at_next = FALSE; if (jconf->input.speech_input == SP_MIC) { fprintf(stderr, "<<< please speak >>>"); } if (speech_output == SPOUT_ADINNET) { ret = adin_go(adin_callback_adinnet, adinnet_check_command, recog); } else { ret = adin_go(adin_callback_file, NULL, recog); } /* return value of adin_go: -2: input terminated by pause command from adinnet server -1: input device read error or callback process error 0: paused by input stream (end of file, etc..) >0: detected end of speech segment: by adin-cut, or by callback process (or return value of ad_check (<0) (== not used in this program)) */ /* if PAUSE or TERMINATE command has been received while input, stop_at_next is TRUE here */ switch(ret) { case -2: /* terminated by terminate command from server */ fprintf(stderr, "[terminated by server]\n"); break; case -1: /* device read error or callback error */ fprintf(stderr, "[error]\n"); break; case 0: /* reached to end of input */ fprintf(stderr, "[eof]\n"); break; default: /* input segmented by silence or callback process */ fprintf(stderr, "[segmented]\n"); break; } if (ret == -1) { /* error in input device or callback function, so terminate program here */ return 1; } /*************************/ /* one segment processed */ /*************************/ if (speech_output == SPOUT_FILE) { /* close output files */ if (close_files() == FALSE) return 1; } else if (speech_output == SPOUT_ADINNET) { if (speechlen > 0) { if (ret >= 0 || stop_at_next) { /* segmented by adin-cut or end of stream or server-side command */ /* send end-of-segment ack to client */ adin_send_end_of_segment(); } /* output info */ printf("sent: %d samples (%.2f sec.) [%6d (%5.2fs) - %6d (%5.2fs)]\n", speechlen, (float)speechlen / (float)sfreq, trigger_sample, (float)trigger_sample / (float)sfreq, trigger_sample + speechlen, (float)(trigger_sample + speechlen) / (float)sfreq); } } /*************************************/ /* increment ID and total sample len */ /*************************************/ if (continuous_segment) { total_speechlen += speechlen; sid++; } /***************************************************/ /* with adinnet server, if terminated by */ /* server-side PAUSE command, wait for RESUME here */ /***************************************************/ if (pause_each) { /* pause at each end */ //if (speech_output == SPOUT_ADINNET && speechlen > 0) { if (speech_output == SPOUT_ADINNET) { if (adinnet_wait_command() < 0) { /* command error: terminate program here */ return 1; } } } else { if (speech_output == SPOUT_ADINNET && stop_at_next) { if (adinnet_wait_command() < 0) { /* command error: terminate program here */ return 1; } } } /* loop condition check */ is_continues = FALSE; if (continuous_segment && (ret > 0 || ret == -2)) { is_continues = TRUE; } } while (is_continues); /* to the next segment in this input stream */ /***********************/ /* end of input stream */ /***********************/ adin_end(recog->adin); } /* to the next input stream (i.e. next input file in SP_RAWFILE) */ record_end: if (speech_output == SPOUT_FILE) { if (continuous_segment) { printf("recorded total %d samples (%.2f sec.) segmented to %s.%04d - %s.%04d files\n", total_speechlen, (float)total_speechlen / (float)sfreq, filename, 0, filename, sid-1); } } return 0; }
int main(int argc, char *argv[]) { FILE *bron; float distweight[1024]; float total,max,threshold; int i,j,nrddt,mid,sock,connected,nrdist,maxnr; char **dtwords; char **dwords; char thisdtword[1024]; char thisdword[1024]; char locaps[1024]; char target[1024]; char stem[1024]; char classifyline[32768]; char line[32768]; char buff[32768]; char feats[NRFEAT][1024]; char *part; char category[1024]; char ddtmatch; sscanf(argv[1],"%f",&threshold); if ((threshold<0.5)|| (threshold>1.0)) { fprintf(stderr,"[t-dt_checker] ERROR: threshold value not between 0.5 and 1.0\n"); exit(1); } bron=fopen(argv[2],"r"); nrddt=0; fgets(line,32768,bron); while (!feof(bron)) { nrddt++; fgets(line,32768,bron); } fclose(bron); dtwords=malloc(nrddt*sizeof(char*)); dwords=malloc(nrddt*sizeof(char*)); bron=fopen(argv[2],"r"); for (i=0; i<nrddt; i++) { fscanf(bron,"%s %s ", thisdtword,thisdword); dtwords[i]=malloc((strlen(thisdtword)+1)*sizeof(char)); strcpy(dtwords[i],thisdtword); dwords[i]=malloc((strlen(thisdword)+1)*sizeof(char)); strcpy(dwords[i],thisdword); } fclose(bron); if (DEBUG) fprintf(stderr,"read %d t-dt triggers from %s\n", nrddt,argv[2]); // process inst file // first, start up communications with the Timbl server ignore_pipe(); sock=make_connection(PORT,SOCK_STREAM,MACHINE); if (sock==-1) { fprintf(stderr,"the confusible server is not responding\n"); exit(1); } else connected=1; // cut off the Timbl welcome message sock_gets(sock,buff,sizeof(buff)-1); // cut off the Timbl base message sock_gets(sock,buff,sizeof(buff)-1); // tell the Timbl server to use the t-dt base sock_puts(sock,"base t-dt\n"); // cut off the Timbl acknowledgement sock_gets(sock,buff,sizeof(buff)-1); mid=NRFEAT/2; bron=fopen(argv[3],"r"); fgets(line,32768,bron); while (!feof(bron)) { part=strtok(line," \n"); for (i=0; ((part!=NULL)&&(i<NRFEAT)); i++) { strcpy(feats[i],part); part=strtok(NULL," \n"); } if (!((strcmp(feats[mid],"<begin>")==0)|| (strcmp(feats[mid],"<end>")==0))) { strcpy(locaps,""); for (i=0; i<strlen(feats[mid]); i++) { strcat(locaps," "); if ((feats[mid][i]>='A')&& (feats[mid][i]<='Z')) locaps[i]=feats[mid][i]+32; else locaps[i]=feats[mid][i]; } ddtmatch=0; i=0; while ((i<nrddt)&& (!ddtmatch)) { if ((strcmp(feats[mid],dtwords[i])==0)|| (strcmp(locaps,dtwords[i])==0)|| (strcmp(feats[mid],dwords[i])==0)|| (strcmp(locaps,dwords[i])==0)) ddtmatch=1; if (!ddtmatch) i++; } fprintf(stdout,"%s", feats[mid]); if (ddtmatch) { // call Timbl strcpy(classifyline,"c "); for (j=0; j<NRFEAT; j++) { strcat(classifyline,feats[j]); strcat(classifyline," "); } strcat(classifyline,"?\n"); if (DEBUG) fprintf(stderr,"\ncalling Timbl with %s", classifyline); sock_puts(sock,classifyline); sock_gets(sock,buff,sizeof(buff)); if (DEBUG) fprintf(stderr,"getting back: %s\n", buff); part=strtok(buff," \n"); part=strtok(NULL," \n"); strcpy(category,""); for (j=1; j<strlen(part)-1; j++) { strcat(category," "); category[j-1]=part[j]; } while ((part!=NULL)&& (strcmp(part,"{")!=0)) part=strtok(NULL," \n"); if (part!=NULL) { nrdist=0; while ((part!=NULL)&& (strcmp(part,"}")!=0)) { part=strtok(NULL," \n"); if (strcmp(part,"}")!=0) { part=strtok(NULL," \n"); if (part[strlen(part)-1]==',') sscanf(part,"%f,",&distweight[nrdist]); else sscanf(part,"%f",&distweight[nrdist]); nrdist++; } } if (DEBUG) { fprintf(stderr,"distro of %d: ", nrdist); for (i=0; i<nrdist; i++) fprintf(stderr," %9.4f", distweight[i]); } max=0.0; total=0.0; for (i=0; i<nrdist; i++) { total+=distweight[i]; if (distweight[i]>max) { max=distweight[i]; maxnr=i; } } if (DEBUG) fprintf(stderr," - max %6.3f certainty\n", (max/total)); if ((max/total>=threshold)&& (total>MINOCC)) { if (strcmp(category,target)!=0) { fprintf(stdout," %s", category); fprintf(stderr,"correcting %s to %s\n", feats[mid],category); } } } } fprintf(stdout,"\n"); } fgets(line,32768,bron); } fclose(bron); close(sock); return 0; }
int main(int argc, char *argv[]) { FILE *bron; int i,j,mid,sock,connected,withletters,nrexceptions=0; float letterratio; char classifyline[32768]; char word[1024]; char word2[1024]; char locap[1024]; char partlocap[1024]; char line[32768]; char buff[32768]; char feats[NRFEAT][1024]; char ***exceptions; char *part; char inflection,exception,locapmatch; // read exceptions bron=fopen(argv[1],"r"); fgets(line,32768,bron); while (!feof(bron)) { nrexceptions++; fgets(line,32768,bron); } fclose(bron); exceptions=malloc(nrexceptions*sizeof(char**)); bron=fopen(argv[1],"r"); for (i=0; i<nrexceptions; i++) { fscanf(bron,"%s %s ", word,word2); exceptions[i]=malloc(2*sizeof(char*)); exceptions[i][0]=malloc((strlen(word)+1)*sizeof(char)); exceptions[i][1]=malloc((strlen(word2)+1)*sizeof(char)); strcpy(exceptions[i][0],word); strcpy(exceptions[i][1],word2); } if (DEBUG2) fprintf(stderr,"read %d exception pairs from %s\n", nrexceptions,argv[1]); // process inst file // first, start up communications with the WOPR server ignore_pipe(); sock=make_connection(PORT,SOCK_STREAM,MACHINE); if (sock==-1) { fprintf(stderr,"the WOPR server is not responding\n"); exit(1); } else connected=1; mid=NRFEAT/2; bron=fopen(argv[2],"r"); fgets(line,32768,bron); while (!feof(bron)) { part=strtok(line," \n"); for (i=0; ((part!=NULL)&&(i<NRFEAT)); i++) { strcpy(feats[i],part); part=strtok(NULL," \n"); } strcpy(word,feats[mid]); if (!((strcmp(word,"<begin>")==0)|| (strcmp(word,"<end>")==0))) { fprintf(stdout,"%s", word); strcpy(locap,""); withletters=0; for (i=0; i<strlen(word); i++) { strcat(locap," "); if ((word[i]>='A')&&(word[i]<='Z')) locap[i]=word[i]+32; else locap[i]=word[i]; if ((locap[i]>='a')&&(locap[i]<='z')) withletters++; } letterratio=(1.*withletters)/(1.*strlen(word)); if (letterratio>0.5) { /* ignore_pipe(); sock=make_connection(PORT,SOCK_STREAM,MACHINE); if (sock==-1) { fprintf(stderr,"the WOPR server is not responding\n"); exit(1); } else connected=1; */ // call WOPR strcpy(classifyline,""); for (j=0; j<NRFEAT; j++) { if (j!=mid) { strcat(classifyline,feats[j]); strcat(classifyline," "); } } strcat(classifyline,word); strcat(classifyline,"\n"); if (DEBUG2) fprintf(stderr,"calling WOPR with %s", classifyline); sock_puts(sock,classifyline); sock_gets(sock,buff,sizeof(buff)); if (DEBUG2) fprintf(stderr,"getting back: %s\n", buff); part=strtok(buff,"\t\n"); while ((part!=NULL)&& (strcmp(part,"__EMPTY__")!=0)) { // special WOPR check exception=0; for (i=0; ((i<nrexceptions)&&(!exception)); i++) { if (((strcmp(word,exceptions[i][0])==0)&& (strcmp(part,exceptions[i][1])==0))|| ((strcmp(word,exceptions[i][1])==0)&& (strcmp(part,exceptions[i][0])==0))) { exception=1; if (DEBUG) fprintf(stderr,"WOPR caught an exception (%s %s) and will remain silent\n", word,part); } } // check: locap match? locapmatch=0; strcpy(partlocap,""); for (i=0; i<strlen(part); i++) { strcat(partlocap," "); if ((part[i]>='A')&&(part[i]<='Z')) partlocap[i]=part[i]+32; else partlocap[i]=part[i]; } if (strcmp(partlocap,locap)==0) locapmatch=1; // check: plural? inflection=0; if (!exception) { if ((((part[strlen(part)-1]=='s')&& (word[strlen(word)-1]!='s')))|| (((part[strlen(part)-1]!='s')&& (word[strlen(word)-1]=='s')))) inflection=1; if ((((part[strlen(part)-1]=='e')&& (word[strlen(word)-1]!='e')))|| (((part[strlen(part)-1]!='e')&& (word[strlen(word)-1]=='e')))) inflection=1; if ((((part[strlen(part)-1]=='n')&& (word[strlen(word)-1]=='t')))|| (((part[strlen(part)-1]=='t')&& (word[strlen(word)-1]=='n')))) inflection=1; } if ((!inflection)&& (!exception)&& (!locapmatch)&& (strlen(part)>MINLEN)) { fprintf(stdout," %s", part); fprintf(stderr,"WOPR corrects [%s] into [%s]\n", word,part); } part=strtok(NULL,"\t\n"); } //close(sock); } fprintf(stdout,"\n"); } fgets(line,32768,bron); } fclose(bron); close(sock); return 0; }