void register_vehicle(int fd, struct vehicle_list *vehicles) { int16_t port; char *addr; uint32_t data_size, id; if(socket_read(fd, &port, sizeof(int16_t)) != sizeof(int16_t)) return; port = ntohs(port); if(socket_read(fd, &data_size, sizeof(uint32_t)) != sizeof(uint32_t)) return; data_size = ntohl(data_size); addr = (char*)malloc(data_size + 1); if(addr == NULL) error_exit("Memory allocation:"); if(socket_read(fd, addr, data_size) != data_size) { free(addr); return; } addr[data_size] = 0; id = htonl(l_add_vehicle(vehicles, port, addr)); socket_write(fd, "k", 1); socket_write(fd, &id, sizeof(uint32_t)); printf("Vehicle %d registered. Count = %d\n", ntohl(id), vehicles->num_vehicles); free(addr); }
int socket_main(int hsocket) { struct sockaddr_in sock; int asocket; /* Active socket */ socklen_t sock_len; char buffer[200]; int got; sock_len = sizeof(struct sockaddr_in); asocket = accept( hsocket, (struct sockaddr *)&sock, &sock_len ); if (asocket == -1) { return -1; } socket_write( asocket, "Hi there\n", 9 ); while (1) { while (socket_poll(asocket)==0) {} if ((got=socket_read(asocket, buffer, 200))>0) { socket_write( asocket, buffer, got ); } else break; } close(asocket); return 0; }
void get_history(int fd, struct vehicle_list *vehicles) { int32_t id, count, x, y; struct single_vehicle *v; struct position *p; if(socket_read(fd, &id, sizeof(uint32_t)) != sizeof(uint32_t)) return; id = ntohl(id); count = begin_getting_history(vehicles, id, &v); count = htonl(count); if(socket_write(fd, &count, sizeof(uint32_t)) == sizeof(uint32_t) && v != NULL) { p = get_positions(v); while(p != NULL) { x = htonl(p->x); y = htonl(p->y); if(socket_write(fd, &x, sizeof(int32_t)) != sizeof(int32_t)) break; if(socket_write(fd, &y, sizeof(int32_t)) != sizeof(int32_t)) break; p = get_next_position(p); } } end_getting_history(vehicles, v); }
/* * Sends a response to a command continuation request. */ int send_continuation(session *ssn, const char *data, size_t len) { if (ssn->socket == -1) return -1; if (socket_write(ssn, data, len) == -1 || socket_write(ssn, "\r\n", strlen("\r\n")) == -1) return -1; if (opts.debug) { unsigned int i; debug("sending continuation data (%d):\n\n", ssn->socket); for (i = 0; i < len; i++) debugc(data[i]); debug("\r\n\n"); } return 0; }
/** * HTTP PUT buffer contents to a remote URL * @param url URL to PUT the contents to * @param buf Buffer whose contents to send * @param count Size of buffer (number of bytes to send) * @return HTTP status code, 200 for OK. See the HTTP RFC for details. */ int http_put_buf(const char *url, const void *buf, size_t count) { char *host = url_get_field(url, URL_HOST); char *port = url_get_field(url, URL_PORT); char *path = url_get_field(url, URL_PATH); int response_code = -1; if (host && port && path) { String *buffer = string_new(""); string_append_c(buffer, "PUT "); string_append_c(buffer, path); string_append_c(buffer, " HTTP/1.1\r\n"); string_append_c(buffer, "Host: "); string_append_c(buffer, host); string_append_c(buffer, "\r\n"); string_append_c(buffer, "Content-type: text/plain\r\n"); if (count > 0) { char length_str[16]; snprintf(length_str, sizeof length_str, "%zu", count); string_append_c(buffer, "Content-length: "); string_append_c(buffer, length_str); string_append_c(buffer, "\r\n"); } string_append_c(buffer, "Connection: close\r\n"); string_append_c(buffer, "Iam: anilakar\r\n"); string_append_c(buffer, "\r\n"); int http_socket = socket_tcp_connect(host, port); if (http_socket >= 0) { if (-1 == socket_write(http_socket, buffer->c_str, buffer->size) || -1 == socket_write(http_socket, buf, count)) { VERBOSE("Could not write to HTTP server."); } else { char response[512]; // Need only the first line int r = socket_read(http_socket, response, sizeof response - 1); response[r] = '\0'; sscanf(response, "HTTP/1.1 %d", &response_code); } } socket_close(&http_socket); string_delete(buffer); } else { VERBOSE("Malformed URL: %s", url); } free(path); free(port); free(host); VERBOSE("HTTP Response: %d", response_code); return response_code; }
bool NameResolution::waitForData(ims::name::NameResolutionSourceType sourceType) { // prepare the command cmdLen = 3; uint16_t tmpCmdLen = htons(cmdLen); memcpy(buf, &tmpCmdLen, sizeof(uint16_t)); buf[2] = 0; // type, NameResolution buf[3] = -3; // function, waitForData if (sourceType == ims::name::NameResolutionSourceType::ANY) { buf[4] = 0; } else if (sourceType == ims::name::NameResolutionSourceType::DNS) { buf[4] = 1; } // issue the command if (socket_write(conn_fd, buf, cmdLen + 2, sockTimeout) != cmdLen + 2) { // something went wrong...reconnect, try one more time, then fail close(conn_fd); if (!establishConnection()) { return false; } if (socket_write(conn_fd, buf, cmdLen + 2, sockTimeout) != cmdLen + 2) { return false; } } do { if (socket_read(conn_fd, buf, 1, sockTimeout) != 1) { // error return false; } } while (buf[0] == 0); return true; }
// main //----------------------------------------------------------------------------------- int main (int argc, char *argv[]) { int s, size; pthread_t thread; char buf[256]; if (argc == 1) { printf ("usage: client <server IP address>\n"); exit (1); } s = socket_connect (argv[1], 1024); pthread_mutex_init (&g_mutex, NULL); pthread_create (&thread, NULL, thread_recv, (void *) &s); // メインループ //--------------------------------------------------- while (g_main_loop) { fgets (buf, 256, stdin); size = strlen (buf); fprintf (stderr, "sending[%d] %s", size, buf); socket_write (s, &size, sizeof (int)); socket_write (s, buf, size); } pthread_join (thread, NULL); exit (0); }
static void write_string(int fd, char const * message) { size_t const length = (message) ? strlen(message) : 0; socket_write(fd, (void const *)&length, sizeof(size_t)); if (length > 0) { socket_write(fd, (void const *)message, length); } }
static bool8 NPServerSendROMInfoToClient (int c) { if (!npplayer[c].online) return (false); NPNotification("Server: Sending ROM information to client %d...", c); if (NPServerSendMesToClient(c, kNPServerROMInfoWillSend) == false) { NPError("Server: Failed to send messsage to client.", 1301); return (false); } if (NPServerGetMesFromClient(c) != kNPClientROMInfoWaiting) { NPError("Server: Failed to receive messsage from client.", 1302); return (false); } uint8 mes[16]; uint32 l; char drive[_MAX_DRIVE + 1], dir[_MAX_DIR + 1], fname[_MAX_FNAME + 1], ext[_MAX_EXT + 1]; _splitpath(Memory.ROMFilename, drive, dir, fname, ext); l = strlen(fname); WRITE_LONG(mes + 0, Memory.ROMCRC32); WRITE_LONG(mes + 4, deviceSetting); WRITE_BYTE(mes + 8, 0); // reserved WRITE_BYTE(mes + 9, 0); // reserved WRITE_BYTE(mes + 10, 0); // reserved WRITE_BYTE(mes + 11, 0); // reserved WRITE_LONG(mes + 12, l); if (socket_write(npplayer[c].socket, mes, 16) != 16) { NPError("Server: Failed to send ROM information to client.", 1303); return (false); } if (socket_write(npplayer[c].socket, (uint8 *) fname, l) != (int) l) { NPError("Server: Failed to send ROM name to client.", 1304); return (false); } NPNotification("Server: Sent ROM information to client %d.", c); return (true); // next: kNPClientROMOpened }
bool NameResolution::getMappings(ims::name::NameIPMap &mappings, ims::name::NameResolutionSourceType sourceType) { // prepare the command cmdLen = 3; uint16_t tmpCmdLen = htons(cmdLen); memcpy(buf, &tmpCmdLen, sizeof(uint16_t)); buf[2] = 0; // type, NameResolution buf[3] = 4; // function, getMappings if (sourceType == ims::name::NameResolutionSourceType::ANY) { buf[4] = 0; } else if (sourceType == ims::name::NameResolutionSourceType::DNS) { buf[4] = 1; } // issue the command if (socket_write(conn_fd, buf, cmdLen + 2, sockTimeout) != cmdLen + 2) { // something went wrong...reconnect, try one more time, then fail close(conn_fd); if (!establishConnection()) { return false; } if (socket_write(conn_fd, buf, cmdLen + 2, sockTimeout) != cmdLen + 2) { return false; } } // at this point, all is well, and command has been issued // read back the # of mappings uint32_t count32; if (socket_read(conn_fd, (char *) &count32, sizeof(uint32_t), sockTimeout) != sizeof(uint32_t)) { // error return false; } count32 = ntohl(count32); // FIXME fill a buffer instead of reading one at a time for (uint32_t i = 0; i < count32; ++i) { if (socket_read(conn_fd, (char *) &nameLen, 1, sockTimeout) != 1) { return false; } if (socket_read(conn_fd, buf, nameLen, sockTimeout) != nameLen) { return false; } tmpName.assign(buf, nameLen); if (socket_read(conn_fd, (char *) &ip, sizeof(uint32_t), sockTimeout) != sizeof(uint32_t)) { return false; } mappings.insert(std::make_pair(tmpName, ntohl(ip))); } return true; }
static bool8 NPClientReplyPhaseSpanTest (void) { uint8 mes[21]; int l = npclient.numplayers * 4 + 1; NPNotification("Client: Replying sending / receiving pad states test...", -1); for (int n = 0; n < 5; n++) { if (socket_read(npclient.socket, mes, l) != l) return (false); if (socket_write(npclient.socket, mes, 5) != 5) return (false); } NPNotification("Client: Replied sending / receiving pad states test.", -1); NPNotification("Client: Receiving phase span value from server...", -1); if (socket_read(npclient.socket, mes, 4) != 4) return (false); npclient.phasespan = READ_LONG(mes + 0); NPNotification(" phase span: %d (frames)", npclient.phasespan); NPNotification("Client: Received phase span value from server.", -1); return (true); }
/* Handle a RST 38 (system call) */ int handle_sys(int scall, int parameter) { char buffer[2]; switch (scall) { case 0: { /* Read in from telnet */ if (flags&DSOCKETS) { return socket_get(tsocket); } return 0; break; } case 1: { /* Write to telnet */ if (flags&DSOCKETS) { buffer[0]=(parameter&0x0ff); return socket_write( tsocket, buffer, 1); } return -1; } case 2: { /* Return !0 if data is available */ if (flags&DSOCKETS) { return socket_poll( tsocket ); } return -1; } } return 0; }
static void run_networking_test(bool server) { if (!server) { connection_t *conn = connection_create(&on_connect); if (!conn) return; printf("connecting to localhost on port 1337\n"); socket_connect(conn, "127.0.0.1", "1337"); char buffer[1024]; while (fgets(buffer, sizeof buffer, stdin)) socket_write(conn, buffer); } else { socket_t *sock = socket_create(on_accept); if (!sock) return; printf("Server will bind to port 1337.\n"); socket_listen(sock, NULL, 1337, 10); while (1) { sleep(5); printf("%d connections ATM\n", sock->num_connections); } } }
static void on_connect(connection_t *s) { s->on_read = on_read; s->on_disconnect = on_disconnect; socket_write(s, "hi %s\n", s->ip); }
void send_svr_disconnect(int sock, char *user_name) { /* * Disconnect message to svr: * +2+22+592+{user_len}{user} */ int rc = PBSE_NONE; int len = 0, user_len = 0, user_ll = 0, resp_msg_len = 0; char tmp_buf[8]; char *resp_msg = NULL; user_len = strlen(user_name); sprintf(tmp_buf, "%d", user_len); user_ll = strlen(tmp_buf); len += 8; len += user_ll; len += 1; len += user_len; len += LOGIN_NAME_MAX + 1; resp_msg = (char *)calloc(1, len); sprintf(resp_msg, "+2+22+59%d+%d%s", user_ll, user_len, user_name); resp_msg_len = strlen(resp_msg); if ((rc = socket_write(sock, resp_msg, resp_msg_len)) != resp_msg_len) { if (debug_mode == TRUE) fprintf(stderr, "Can not send close message to pbs_server!! (socket #%d)\n", sock); } free(resp_msg); }
int socket_write_all(int sock, const void *buff, size_t len) { size_t nleft; ssize_t nwritten; const char *ptr; ptr = buff; nleft = len; while (nleft > 0) { if ( (nwritten = socket_write(sock, ptr, nleft)) <= 0) { if (nwritten < 0 && errno == EINTR) nwritten = 0; /* and call write() again */ else return (-1); /* error */ } nleft -= nwritten; ptr += nwritten; } return len; }
/** * Send the response to the client. If the response has already been * commited, this function does nothing. */ static void send_response(HttpResponse res) { Socket_T S= res->S; if(!res->is_committed) { char date[STRLEN]; char server[STRLEN]; char *headers= get_headers(res); int length = StringBuffer_length(res->outputbuffer); res->is_committed= TRUE; get_date(date, STRLEN); get_server(server, STRLEN); socket_print(S, "%s %d %s\r\n", res->protocol, res->status, res->status_msg); socket_print(S, "Date: %s\r\n", date); socket_print(S, "Server: %s\r\n", server); socket_print(S, "Content-Length: %d\r\n", length); socket_print(S, "Connection: close\r\n"); if(headers) socket_print(S, "%s", headers); socket_print(S, "\r\n"); if(length) socket_write(S, (unsigned char *)StringBuffer_toString(res->outputbuffer), length); FREE(headers); } }
long tcp_sout (TCPSTREAM *stream,char *string,unsigned long size) { int i; fd_set fds; struct timeval tmo; time_t t = time (0); if (stream->tcpso < 0) return NIL; while (size > 0) { /* until request satisfied */ time_t tl = time (0); /* start of request */ tmo.tv_sec = ttmo_write; /* write timeout */ tmo.tv_usec = 0; FD_ZERO (&fds); /* initialize selection vector */ FD_SET (stream->tcpso,&fds);/* set bit in selection vector */ errno = NIL; /* block and write */ while (((i = select (getdtablesize (),0,&fds,0,ttmo_write ? &tmo : 0)) < 0) && (errno == EINTR)); if (!i) { /* timeout? */ time_t tc = time (0); if (tmoh && ((*tmoh) (tc - t,tc - tl))) continue; else return tcp_abort (stream); } else if (i < 0) return tcp_abort (stream); while (((i = socket_write (stream->tcpso,string,size)) < 0) && (errno == EINTR)); if (i < 0) return tcp_abort (stream); size -= i; /* how much we sent */ string += i; } return T; /* all done */ }
int nettest2(void) { int err; sockaddr addr; fd = socket_create(SOCK_PROTO_TCP, 0); printf("created socket, fd %d\n", fd); if(fd < 0) return 0; memset(&addr, 0, sizeof(addr)); addr.addr.len = 4; addr.addr.type = ADDR_TYPE_IP; addr.port = 9; NETADDR_TO_IPV4(addr.addr) = IPV4_DOTADDR_TO_ADDR(63,203,215,73); err = socket_connect(fd, &addr); printf("socket_connect returns %d\n", err); if(err < 0) return err; for(;;) { char buf[4096]; socket_write(fd, buf, sizeof(buf)); } return 0; }
string query_ident(object who) { string name, ipno, id; mixed info; if(!interactive(who)) return 0; name = (string)who->query_real_name(); ipno = query_ip_number(who); if(stringp(info=ident_info[id=name+"@"+ipno])) return info; if(info + RETRY_TIME < time() && requests[id] < MAX_RETRIES) { reqno++; info=reqno +" "+query_ip_port(who)+" "+ipno; if((info=socket_write(sd, info, IDENTSERVER)) < 0) { _syslog("identd: socket_write failed: " + info); return 0; } ident_info[id]=time(); requests[id]++; requests[reqno]=id; } return 0; }
/** * A simple 'SSH protocol version exchange' implemetation based on * RFC (http://www.openssh.com/txt/draft-ietf-secsh-transport-14.txt) * * @author Igor Homyakov, <*****@*****.**> * * @file */ int check_ssh(Socket_T s) { char buf[STRLEN]; ASSERT(s); if(!socket_readln(s, buf, sizeof(buf))) { LogError("SSH: error receiving identification string -- %s\n", STRERROR); return FALSE; } if(! Util_startsWith(buf, "SSH-")) { LogError("SSH: protocol error %s\n", buf); return FALSE; } /* send identification string back to server */ if(socket_write(s, buf, strlen(buf)) <= 0) { LogError("SSH: error sending identification string -- %s\n", STRERROR); return FALSE; } /* Read one extra line to prevent the "Read from socket failed" warning */ socket_readln(s, buf, sizeof(buf)); return TRUE; }
// physical layer function to send data. int phy_send(COMMCTX* ctx, char* buffer, int size) { SOCK_CTX* mctx; mctx=(SOCK_CTX*)ctx->sock_ctx; return socket_write(mctx->sock, buffer, size); }
int Dps_ftp_send_cmd(DPS_CONN *connp, const char *cmd) { char *buf; size_t len; connp->err = 0; len = dps_strlen(cmd)+2; buf = DpsXmalloc(len+1); if (buf == NULL) return -1; dps_snprintf(buf, len+1, "%s\r\n", cmd); socket_buf_clear(connp); if (socket_write(connp, buf)){ DPS_FREE( buf); return -1; } #ifdef DEBUG_FTP fprintf(stderr, "ftp://%s (cmd) : %s", connp->hostname, buf); /*DpsLog(connp->indexer, DPS_LOG_DEBUG, "ftp://%s (cmd) : %s", connp->hostname, buf);*/ #endif DPS_FREE(buf); if (Dps_ftp_read_line(connp)) return -1; #ifdef DEBUG_FTP fprintf(stderr, "ftp://%s (reply): %s", connp->hostname, connp->buf); /*DpsLog(connp->indexer, DPS_LOG_DEBUG, "ftp://%s (reply): %s", connp->hostname, connp->buf);*/ #endif return(Dps_ftp_get_reply(connp)); }
/** Called to write into the socket * \see oml_outs_write_f * * If the connection needs to be re-established, header is sent first, then buffer, * * \see \see open_socket, socket_write */ static ssize_t net_stream_write(OmlOutStream* hdl, uint8_t* buffer, size_t length, uint8_t* header, size_t header_length) { OmlNetOutStream* self = (OmlNetOutStream*)hdl; size_t count; /* The header can be NULL, but header_length MUST be 0 in that case */ assert(header || !header_length); /* Initialise the socket the first time */ while (self->socket == NULL) { logdebug ("%s: Connecting to server\n", self->dest); if (!open_socket(self)) { logdebug("%s: Connection attempt failed\n", self->dest); return 0; } } /* If the underlying socket has registered a disconnection, it will reconnect on its own * however, we need to check it to make sure we send the headers before anything else */ if(socket_is_disconnected(self->socket)) { self->header_written = 0; } out_stream_write_header(hdl, socket_write, header, header_length); if(o_log_level_active(O_LOG_DEBUG4)) { char *out = to_octets(buffer, length); logdebug("%s: Sending data %s\n", self->dest, out); oml_free(out); } count = socket_write(hdl, buffer, length); return count; }
void stream_file(int sock, char* name){ int fnlen = strlen(movie_dir) + strlen(name) + 1; char* filename = (char*) calloc(fnlen, sizeof(char)); strcat(filename, movie_dir); strcat(filename, "/"); strcat(filename, name); FILE* fd = fopen(filename, "r"); int delay_ms = 150; char* line = NULL; size_t len; ssize_t read; struct timespec sleep_time; sleep_time.tv_sec = delay_ms / 1000; sleep_time.tv_nsec = (delay_ms % 1000) * 1000000; while((read = getline(&line, &len, fd)) > 0){ socket_write(sock, line); if(strcmp(line, "end\n") == 0){ nanosleep(&sleep_time, NULL); } } fclose(fd); }
// Report that a child has exited void child_cb(EV_P_ ev_child *w, int revents) { char str[100]; char format[] = "{\"processTerminated\" : " " {\"pid\" : %d, \"returnCode\" : %d, \"bySignal\" : %d, \"endTime\" : %ld }}"; struct timeval tp; gettimeofday(&tp, NULL); long int time = (long int) tp.tv_sec * 1000 + tp.tv_usec; sprintf(str, format, w->rpid, WEXITSTATUS(w->rstatus), WSTOPSIG(w->rstatus), time); socket_t *s = w->data; ev_child_stop (EV_A_ w); frame_t *frame = malloc(sizeof(frame_t)); frame->fin = 1; frame->opcode = WS_OP_BIN; frame->len = strlen(str); frame->payload = str; int fr_len; char *fr_str = write_frame(frame, &fr_len); socket_write(s, fr_str, fr_len); free(frame); free(fr_str); ilist_remove(processes, w->rpid); }
void send_static_message(int sock, char *message) { if (socket_write(sock, message, strlen(message)) < 0) { pthread_cond_signal(&ready_to_reconnect); } }
static int send_status(int sockfd, struct iovec *iovec, int status) { ProxyHeader header; int retval, msg_size; if (status < 0) { header.type = T_ERROR; } else { header.type = T_SUCCESS; } header.size = sizeof(status); /* * marshal the return status. We don't check error. * because we are sure we have enough space for the status */ msg_size = proxy_marshal(iovec, 0, "ddd", header.type, header.size, status); if (msg_size < 0) { return msg_size; } retval = socket_write(sockfd, iovec->iov_base, msg_size); if (retval < 0) { return retval; } return 0; }
static int say(Socket_T socket, char *msg) { if (socket_write(socket, msg, strlen(msg)) < 0) { socket_setError(socket, "LMTP: error sending data -- %s", STRERROR); return FALSE; } return TRUE; }
/* * send response in two parts * 1) ProxyHeader * 2) Response or error status * This function should be called with marshaled response * send_response constructs header part and error part only. * send response sends {ProxyHeader,Response} if the request was success * otherwise sends {ProxyHeader,error status} */ static int send_response(int sock, struct iovec *iovec, int size) { int retval; ProxyHeader header; /* * If response size exceeds available iovec->iov_len, * we return ENOBUFS */ if (size > PROXY_MAX_IO_SZ) { size = -ENOBUFS; } if (size < 0) { /* * In case of error we would not have got the error encoded * already so encode the error here. */ header.type = T_ERROR; header.size = sizeof(size); proxy_marshal(iovec, PROXY_HDR_SZ, "d", size); } else { header.type = T_SUCCESS; header.size = size; } proxy_marshal(iovec, 0, "dd", header.type, header.size); retval = socket_write(sock, iovec->iov_base, header.size + PROXY_HDR_SZ); if (retval < 0) { return retval; } return 0; }