bool client_handler::read_message(handler *h, buffer &buf) { int plen = buf.length(); Log::d("read_message1"); if (serv->read_chunk(h, &buf)) { Log::d("fd(" + inttostr(h->fd.get_fd()) + ") asked for disconnection"); disconnect(); return false; } Log::d("read_message2"); if (message_type == NOT_EVALUATED) { // recalc message len int lb = find_double_line_break(buf.string_data(), plen); if (lb != -1) { //Log::d("plen is " + inttostr(plen) + ", lb is " + inttostr(lb) + " in \n\"" + buf.string_data() + "\""); std::string content_length_str; int len; if (extract_header(buf.string_data(), lb, "Content-Length", content_length_str)) { len = strtoint(content_length_str); message_type = VIA_CONTENT_LENGTH; } else { len = 0; message_type = extract_header(buf.string_data(), lb, "Transfer-Encoding", content_length_str) ? VIA_TRANSFER_ENCODING : WITHOUT_BODY; } message_len = len + lb; } } if (message_type != HTTPS_MODE) { Log::d("read_message(" + inttostr(buf.length()) + ", " + inttostr(message_len) + ")"); } if (message_type == NOT_EVALUATED) { return false; } if (message_type == VIA_TRANSFER_ENCODING) { while (buf.length() > message_len) { /*Log::d("kek is " + inttostr((int) buf.string_data()[message_len - 1]) + " " + inttostr((int) buf.string_data()[message_len]) + " " + inttostr((int) buf.string_data()[message_len + 1]));*/ if (buf.string_data()[message_len] == '0') { return true; } size_t linebreak = buf.string_data().find("\r\n", (size_t) message_len); if (linebreak != std::string::npos) { std::string chunklen = buf.string_data().substr((size_t) message_len, linebreak - message_len); Log::d("Next chunk len is " + chunklen); message_len += chunklen.length() + hextoint(chunklen) + 4; } else { break; } } return false; } else { return buf.length() == message_len; } }
void array_list_drop_last (array_list al) { array_list_header *h = extract_header (al); JERRY_ASSERT (h->len > 0); h->len--; }
static enum okay makeheader(FILE *fp, struct header *hp) { char *tempEdit; FILE *nf; int c; if ((nf = Ftemp(&tempEdit, "Re", "w+", 0600, 1)) == NULL) { perror(catgets(catd, CATSET, 66, "temporary mail edit file")); Fclose(nf); unlink(tempEdit); Ftfree(&tempEdit); return STOP; } unlink(tempEdit); Ftfree(&tempEdit); extract_header(fp, hp); while ((c = getc(fp)) != EOF) putc(c, nf); if (fp != collf) Fclose(collf); Fclose(fp); collf = nf; if (check_from_and_sender(hp->h_from, hp->h_sender)) return STOP; return OKAY; }
void array_list_set_last_element (array_list al, size_t index, void *elem) { array_list_header *h = extract_header (al); JERRY_ASSERT (index != 0 && index <= h->len); array_list_set_element (al, (size_t) (h->len - index), elem); }
static string extrapolate_levin_description(const vector<DrtPred> &preds) { string description; metric *d = metric_singleton::get_metric_instance(); vector<DrtPred>::const_iterator piter = preds.begin(); vector<DrtPred>::const_iterator pend = preds.end(); string lev_tmp; for (; piter != pend; ++piter) { string head_str = extract_header(*piter); if (piter->is_verb()) { lev_tmp = d->get_levin_verb(head_str); if (lev_tmp.size()) { description += lev_tmp; description += "-"; } } else { lev_tmp = d->get_levin_noun(head_str); if (lev_tmp.size()) { description += lev_tmp; description += "-"; } } } description.erase(description.size() - 1); return description; }
void array_list_set_element (array_list al, size_t index, void *elem) { array_list_header *h = extract_header (al); JERRY_ASSERT (index < h->len); memcpy (data (al) + (index * h->element_size), elem, h->element_size); }
void print_custom_header(buffer* buf) { header msg_header = extract_header(buf); fprintf(stdout, "Version: %d\n", msg_header.data[CST_VERSION]); fprintf(stdout, "Command: %d\n", msg_header.data[CST_COMMAND]); fprintf(stdout, "Sequence: %d\n", msg_header.data[CST_SEQUENCE]); fprintf(stdout, "Total: %d\n", msg_header.data[CST_TOTAL_SIZE]); fprintf(stdout, "Payload: %d\n", msg_header.data[CST_PAYLOAD_SIZE]); }
void * array_list_last_element (array_list al, size_t index) { array_list_header *h = extract_header (al); if (index == 0 || index > h->len) { return NULL; } return array_list_element (al, (size_t) (h->len - index)); }
void print_header(buffer* buf) { header msg_header = extract_header(buf); fprintf(stdout, "Version: %d\n", msg_header.data[UP_VERSION]); fprintf(stdout, "Password: %d\n", msg_header.data[UP_IDENTIFIER]); fprintf(stdout, "Request: %d\n", msg_header.data[UP_CLIENT_REQUEST]); fprintf(stdout, "Data: %d\n", msg_header.data[UP_REQUEST_DATA]); fprintf(stdout, "Offset: %d\n", msg_header.data[UP_BYTE_OFFSET]); fprintf(stdout, "Total: %d\n", msg_header.data[UP_TOTAL_SIZE]); fprintf(stdout, "Payload: %d\n", msg_header.data[UP_PAYLOAD_SIZE]); }
void * array_list_element (array_list al, size_t index) { array_list_header *h = extract_header (al); if (h->len <= index) { return NULL; } return data (al) + (index * h->element_size); }
//------------------------------------------------------------------------------------------------- Message *Message::factory(const F8MetaCntx& ctx, const f8String& from) { Message *msg(0); f8String len, mtype; if (extract_header(from, len, mtype)) { const unsigned mlen(fast_atoi<unsigned>(len.c_str())); const BaseMsgEntry *bme(ctx._bme.find_ptr(mtype)); if (!bme) throw InvalidMessage(mtype); msg = bme->_create(); #if defined PERMIT_CUSTOM_FIELDS if (ctx._ube) ctx._ube->post_msg_ctor(msg); #endif #if defined CODECTIMING ostringstream gerr; gerr << "decode(" << mtype << "):"; IntervalTimer itm; #endif msg->decode(from); #if defined CODECTIMING gerr << itm.Calculate(); GlobalLogger::log(gerr.str()); #endif static_cast<body_length *>(msg->_header->_fields.find(Common_BodyLength)->second)->set(mlen); Fields::const_iterator fitr(msg->_header->_fields.find(Common_MsgType)); static_cast<msg_type *>(fitr->second)->set(mtype); #if defined POPULATE_METADATA msg->check_set_rlm(fitr->second); #endif const char *pp(from.data() + from.size() - 7); if (*pp != '1' || *(pp + 1) != '0') // 10=XXX^A throw InvalidMessage(from); if (!ctx.has_flag(F8MetaCntx::noverifychksum)) // permit chksum calculation to be skipped { const f8String chksum(pp + 3, 3); static_cast<check_sum *>(msg->_trailer->_fields.find(Common_CheckSum)->second)->set(chksum); const unsigned chkval(fast_atoi<unsigned>(chksum.c_str())), mchkval(calc_chksum(from, 0, from.size() - 7)); if (chkval != mchkval) throw BadCheckSum(mchkval); } } else { //cerr << "Message::factory throwing" << endl; throw InvalidMessage(from); } return msg; }
//------------------------------------------------------------------------------------------------- Message *Message::factory(const F8MetaCntx& ctx, const f8String& from) { Message *msg(0); f8String len, mtype; if (extract_header(from, len, mtype)) { const unsigned mlen(fast_atoi<unsigned>(len.c_str())); const BaseMsgEntry *bme(ctx._bme.find_ptr(mtype)); if (!bme) throw InvalidMessage(mtype); msg = bme->_create(); #if defined PERMIT_CUSTOM_FIELDS if (ctx._ube) ctx._ube->post_msg_ctor(msg); #endif #if defined CODECTIMING ostringstream gerr; gerr << "decode(" << mtype << "):"; IntervalTimer itm; #endif msg->decode(from); #if defined CODECTIMING gerr << itm.Calculate(); GlobalLogger::log(gerr.str()); #endif Fields::const_iterator fitr(msg->_header->_fields.find(Common_BodyLength)); static_cast<body_length *>(fitr->second)->set(mlen); fitr = msg->_header->_fields.find(Common_MsgType); static_cast<msg_type *>(fitr->second)->set(mtype); #if defined POPULATE_METADATA msg->check_set_rlm(fitr->second); #endif f8String chksum; if (extract_trailer(from, chksum)) { Fields::const_iterator fitr(msg->_trailer->_fields.find(Common_CheckSum)); static_cast<check_sum *>(fitr->second)->set(chksum); const unsigned chkval(fast_atoi<unsigned>(chksum.c_str())), // chksum value mchkval(calc_chksum(from, 0)); // chksum pos if (chkval != mchkval) throw BadCheckSum(mchkval); } } else { //cerr << "Message::factory throwing" << endl; throw InvalidMessage(from); } return msg; }
/* * Extract bmp pallet only * data: raw data (pointer to data top) * return: extracted pallet data */ cgdata *bmp_getpal(BYTE *data) { cgdata *cg = g_new0(cgdata, 1); bmp_header *bmp = extract_header(data); cg->pal = g_new(Pallet256, 1); getpal(cg->pal, data + bmp->bmpPp); cg->type = ALCG_BMP8; cg->pic = NULL; cg->alpha = NULL; g_free(bmp); return cg; }
static pair<DrtVect, DrtMgu> break_off_complements(DrtVect drtvect) { DrtMgu mgu; for (int n = 0; n < drtvect.size(); ++n) { string fref = extract_first_tag(drtvect.at(n)); string header = extract_header (drtvect.at(n)); if (drtvect.at(n).is_complement() && ref_is_verb(fref)) { string old_ref = fref; string new_ref = string("_[broken_off]_") + boost::lexical_cast<string>(n) + "_" + fref; implant_first(drtvect.at(n), new_ref); mgu.add(old_ref, new_ref); } } return make_pair(drtvect, mgu); }
//------------------------------------------------------------------------------------------------- Message *Message::factory(const F8MetaCntx& ctx, const f8String& from) { Message *msg(0); char mtype[MAX_MSGTYPE_FIELD_LEN] = {}, len[MAX_MSGTYPE_FIELD_LEN] = {}; if (extract_header(from, len, mtype)) { const unsigned mlen(fast_atoi<unsigned>(len)); const BaseMsgEntry *bme(ctx._bme.find_ptr(mtype)); if (!bme) throw InvalidMessage(mtype); msg = bme->_create(); #if defined CODECTIMING IntervalTimer itm; #endif msg->decode(from); #if defined CODECTIMING _decode_timings._cpu_used += itm.Calculate().AsDouble(); ++_decode_timings._msg_count; #endif static_cast<body_length *>(msg->_header->_fields.find(Common_BodyLength)->second)->set(mlen); Fields::const_iterator fitr(msg->_header->_fields.find(Common_MsgType)); static_cast<msg_type *>(fitr->second)->set(mtype); #if defined POPULATE_METADATA msg->check_set_rlm(fitr->second); #endif const char *pp(from.data() + from.size() - 7); if (*pp != '1' || *(pp + 1) != '0') // 10=XXX^A throw InvalidMessage(from); if (!ctx.has_flag(F8MetaCntx::noverifychksum)) // permit chksum calculation to be skipped { const f8String chksum(pp + 3, 3); static_cast<check_sum *>(msg->_trailer->_fields.find(Common_CheckSum)->second)->set(chksum); const unsigned chkval(fast_atoi<unsigned>(chksum.c_str())), mchkval(calc_chksum(from, 0, from.size() - 7)); if (chkval != mchkval) throw BadCheckSum(mchkval); } } else { //cerr << "Message::factory throwing" << endl; throw InvalidMessage(from); } return msg; }
static pair<DrtVect, DrtMgu> break_off_specifications(DrtVect drtvect) { DrtMgu mgu; for (int n = 0; n < drtvect.size(); ++n) { string fref = extract_first_tag(drtvect.at(n)); string header = extract_header (drtvect.at(n)); if (drtvect.at(n).is_complement() && ref_is_name(fref) && header.find("@QUANTITY") == string::npos // these are properties of the predicate && header.find("@GENITIVE") == string::npos ) { string old_ref = fref; string new_ref = string("_[broken_off]_") + boost::lexical_cast<string>(n) + "_" + fref; implant_first(drtvect.at(n), new_ref); mgu.add(old_ref, new_ref); } } return make_pair(drtvect, mgu); }
/** * Parses data into RTPMessage struct. Stores headers separately from the payload data * and so the length variable is set accordingly. */ RTPMessage *msg_parse ( const uint8_t *data, int length ) { RTPMessage *retu = calloc(1, sizeof (RTPMessage)); retu->header = extract_header ( data, length ); /* It allocates memory and all */ if ( !retu->header ) { LOGGER_WARNING("Header failed to extract!"); free(retu); return NULL; } uint16_t from_pos = retu->header->length; retu->length = length - from_pos; if ( GET_FLAG_EXTENSION ( retu->header ) ) { retu->ext_header = extract_ext_header ( data + from_pos, length ); if ( retu->ext_header ) { retu->length -= ( 4 /* Minimum ext header len */ + retu->ext_header->length * size_32 ); from_pos += ( 4 /* Minimum ext header len */ + retu->ext_header->length * size_32 ); } else { /* Error */ LOGGER_WARNING("Ext Header failed to extract!"); rtp_free_msg(NULL, retu); return NULL; } } else { retu->ext_header = NULL; } if ( length - from_pos <= MAX_RTP_SIZE ) memcpy ( retu->data, data + from_pos, length - from_pos ); else { LOGGER_WARNING("Invalid length!"); rtp_free_msg(NULL, retu); return NULL; } retu->next = NULL; return retu; }
/* * Extract 24bit bmp, header, pallet and pixel * data: raw data (pointer to data top) * return: extracted image data and information */ cgdata *bmp16m_extract(BYTE *data) { cgdata *cg = g_new0(cgdata, 1); bmp_header *bmp = extract_header(data); /* +10: margin for broken cg */ cg->pic = (BYTE *)g_new(WORD, (bmp->bmpXW + 10) * (bmp->bmpYW + 10)); extract_24bit(bmp, (WORD *)cg->pic, data + bmp->bmpDp); cg->type = ALCG_BMP24; cg->x = 0; cg->y = 0; cg->width = bmp->bmpXW; cg->height = bmp->bmpYW; cg->alpha = NULL; cg->pal = NULL; g_free(bmp); return cg; }
/* * Extract 8bit bmp, header, pallet and pixel * data: raw data (pointer to data top) * return: extracted image data and information */ cgdata *bmp256_extract(BYTE *data) { bmp_header *bmp = extract_header(data); cgdata *cg = g_new0(cgdata, 1); cg->pal = g_new(Pallet256, 1); getpal(cg->pal, data + bmp->bmpPp); /* +10: margin for broken cg */ cg->pic = g_new(BYTE, (bmp->bmpXW + 10) * (bmp->bmpYW + 10)); extract_8bit(bmp, cg->pic, data + bmp->bmpDp); cg->type = ALCG_BMP8; cg->x = 0; cg->y = 0; cg->width = bmp->bmpXW; cg->height = bmp->bmpYW; cg->alpha = NULL; g_free(bmp); return cg; }
vector<DrtVect> solver::updateCurrentLayer(const Level ¤t_layer, DrtVect question) { path_memory mem_tmp = current_layer.getMemory(); vector<DrtVect> qvect = current_layer.getData(); DrtMgu upg = get_all_levels_upg(mem_tmp); qvect / upg; question /upg; k_->addTemporary(question); for (int m = 0; m < qvect.size(); ++m) { DrtVect drtvect = qvect.at(m); for (int n = 0; n < drtvect.size(); ++n) { string fref = extract_first_tag(drtvect.at(n)); string head = extract_header(drtvect.at(n)); vector<string> all_names; if (drtvect.at(n).is_name()) all_names = k_->getNounNames(fref); else if (drtvect.at(n).is_verb()) all_names = k_->getVerbNames(fref); if (all_names.size() == 0) continue; if (head == "[*]" || head == "[what]" || head == "person" || head == "place" //|| head == "time" ) { string new_name = all_names.at(0); if (new_name == "[any]") new_name = "[*]"; implant_header(drtvect.at(n), new_name); } } qvect.at(m) = drtvect; } k_->clearAllTemporary(); return qvect; }
array_list array_list_append (array_list al, void *element) { array_list_header *h = extract_header (al); if ((h->len + 1) * h->element_size + sizeof (array_list_header) > h->size) { size_t size = mem_heap_recommend_allocation_size (h->size + h->element_size); JERRY_ASSERT (size > h->size); uint8_t* new_block_p = (uint8_t*) mem_heap_alloc_block (size, MEM_HEAP_ALLOC_SHORT_TERM); memcpy (new_block_p, h, h->size); memset (new_block_p + h->size, 0, size - h->size); mem_heap_free_block ((uint8_t *) h); h = (array_list_header *) new_block_p; h->size = size; al = (array_list) h; } memcpy (data (al) + (h->len * h->element_size), element, h->element_size); h->len++; return al; }
void client_handler::handle(const epoll_event &e) { if (!(e.events & EPOLLOUT) || (e.events & EPOLLIN) || !output_buffer.empty()) { Log::d("Client handler: " + eetostr(e)); } if (e.events & EPOLLOUT) { if (serv->write_chunk(this, output_buffer) && message_type != HTTPS_MODE) { Log::d("Finished resending host response to client"); if (message_type == PRE_HTTPS_MODE) { message_type = HTTPS_MODE; std::string hostname; extract_header(input_buffer.string_data(), input_buffer.length(), "Host", hostname); input_buffer.clear(); output_buffer.clear(); serv->modify_handler(this, EPOLLIN | EPOLLOUT); resolve_host_ip(hostname, EPOLLIN | EPOLLOUT); } else { input_buffer.clear(); message_len = -1; message_type = NOT_EVALUATED; serv->modify_handler(this, EPOLLIN); } } } if (e.events & EPOLLIN) { if (read_message(this, input_buffer) && message_type != HTTPS_MODE) { std::string data = input_buffer.string_data(); serv->modify_handler(this, 0); std::string hostname; if (extract_header(data, (int) data.length(), "Host", hostname)) { if (message_type == WITHOUT_BODY && extract_method(data) == "CONNECT") { //output_buffer.set("HTTP/1.0 404 Fail\r\nProxy-agent: BotHQ-Agent/1.2\r\n\r\n"); output_buffer.set("HTTP/1.0 200 OK\r\nProxy-agent: BotHQ-Agent/1.2\r\n\r\n"); serv->modify_handler(this, EPOLLOUT); message_type = PRE_HTTPS_MODE; Log::d("entering HTTPS_MODE"); } else { if (message_type == WITHOUT_BODY && extract_method(data) == "GET") { // modifying status line size_t from = data.find(hostname) + hostname.length(); Log::d("from is " + inttostr(from) + ", hostname is " + hostname); data = "GET " + input_buffer.string_data().substr(from, input_buffer.string_data().length() - from); input_buffer.clear(); input_buffer.put(data.c_str(), data.length()); Log::d("new query is: \"\n" + input_buffer.string_data() + "\""); Log::d("First line is \"" + input_buffer.string_data().substr(0, input_buffer.string_data().find("\r\n")) + "\""); } resolve_host_ip(hostname, EPOLLOUT); } } else { //TODO: send correspond answer Log::fatal("Client headers do not contain 'host' header"); //exit(-1); } } } }
/* void protocol1 * buffer* recv_buffer - buffer containing the message sent by the client to the proxy * server_stat* status - status and general information from the server * Processes the recv_buf as the class protocol dictates */ void protocol1(buffer* recv_buf, server_stat* status){ struct timeval timeout; struct timeval timeout_0; // timeouts timeout.tv_sec = 1; timeout.tv_usec = 0; timeout_0.tv_sec = 0; timeout_0.tv_usec = 0; timeout_setup(status->udp_sock, timeout); // giant mess of conditionals fprintf(stdout, "\tversion 1 protocol\n"); int error = 0; header msg_header = extract_header(recv_buf); if (status->connected == 0) { if (check_pass(&msg_header, 0)) { if (get_command(&msg_header) == CONNECT) { fprintf(stdout, "\tReplying with password\n"); status->connected = 1; msg_header.data[1] = status->password; insert_header(recv_buf, msg_header); if (udp_send(recv_buf, status) < 0) { fprintf(stderr, "sendto()\n"); } } else { fprintf(stderr, "ERROR: Unexpected Command\n"); error = -2; } } else { fprintf(stderr, "ERROR: Incorrect Password\n"); } } else if (status->connected == 1) { if (check_pass(&msg_header, status->password)) { if (get_command(&msg_header) == CONNECT) { status->connected = 2; timeout_setup(status->udp_sock, timeout_0); fprintf(stdout, "\tConnected to a client\n"); } else { fprintf(stderr, "ERROR: Unexpected Command\n"); error = -2; } } else { fprintf(stderr, "ERROR: Incorrect Password\n"); error = -2; } } else { if (!check_pass(&msg_header, status->password)) { fprintf(stderr, "ERROR: Incorrect Password\n"); error = -2; } else { fprintf(stdout, "\t\tReceived Message:\n"); print_header(recv_buf); switch (get_command(&msg_header)) { case CONNECT: fprintf(stderr, "ERROR: Unexpected Command\n"); error = -2; break; case QUIT: quit(recv_buf, status); timeout_setup(status->udp_sock, timeout_0); break; default: error = request_command(recv_buf, status); break; } } } if (error == -2) { fprintf(stderr, "ERROR: Invalid client request\n"); send_error(status, CLIENT_ERROR); } else if (error == -1) { fprintf(stderr, "ERROR: Problem with http response\n"); send_error(status, HTTP_ERROR); } }
/* void request_image * buffer* recv_buffer - buffer containing the message sent by the client to the proxy * server_stat* status - status and general information from the server * Sends an acknowledgement to the client * Requests "stuff" from the robot * Forwards data from robot to client * Returns -2 if error processing client request * -1 if error in http response * 1 if successful */ int request_command(buffer* recv_buf, server_stat* status) { unsigned char http_message[1000]; // used to hold http message from robot buffer* http_data = create_buffer(BUFFER_LEN); int n; header request_header; // header from the client buffer* response; // buffer to send to client struct timeval timeout; timeout.tv_sec = 0; timeout.tv_usec = 500000; fprintf(stdout, "\tProcessing request\n"); // acknowledgement of command to client udp_send(recv_buf, status); // create the http request memset(http_message, '\0', 1000); request_header = extract_header(recv_buf); switch (request_header.data[UP_CLIENT_REQUEST]) { case IMAGE: fprintf(stdout, "\t\tContacting image port\n"); snprintf((char*)http_message, 100, "GET /snapshot?topic=/robot_%d/image?width=600?height=500 HTTP/1.1\r\n\r\n", status->r_stat.id); status->r_stat.http_sock = tcp_connect(status->r_stat.hostname, IMAGE_PORT); break; case GPS: fprintf(stdout, "\t\tContacting gps port\n"); snprintf((char*)http_message, 100, "GET /state?id=%s HTTP/1.1\r\n\r\n", status->r_stat.name); status->r_stat.http_sock = tcp_connect(status->r_stat.hostname, GPS_PORT); break; case LASERS: fprintf(stdout, "\t\tContacting lasers port\n"); snprintf((char*)http_message, 100, "GET /state?id=%s HTTP/1.1\r\n\r\n", status->r_stat.name); status->r_stat.http_sock = tcp_connect(status->r_stat.hostname, LASERS_PORT); break; case dGPS: fprintf(stdout, "\t\tContacting dgps port\n"); snprintf((char*)http_message, 100, "GET /state?id=%s HTTP/1.1\r\n\r\n", status->r_stat.name); status->r_stat.http_sock = tcp_connect(status->r_stat.hostname, dGPS_PORT); break; case MOVE: fprintf(stdout, "\t\tContacting move port\n"); snprintf((char*)http_message, 100, "GET /twist?id=%s&lx=%d HTTP/1.1\r\n\r\n", status->r_stat.name, request_header.data[UP_REQUEST_DATA]); status->r_stat.http_sock = tcp_connect(status->r_stat.hostname, GPS_PORT); break; case TURN: fprintf(stdout, "\t\tContacting turn port\n"); snprintf((char*)http_message, 100, "GET /twist?id=%s&az=%d HTTP/1.1\r\n\r\n", status->r_stat.name, request_header.data[UP_REQUEST_DATA]); status->r_stat.http_sock = tcp_connect(status->r_stat.hostname, GPS_PORT); break; case STOP: fprintf(stdout, "\t\tContacting stop port\n"); snprintf((char*)http_message, 100, "GET /twist?id=%s&lx=0&az=0 HTTP/1.1\r\n\r\n", status->r_stat.name); status->r_stat.http_sock = tcp_connect(status->r_stat.hostname, GPS_PORT); break; default: fprintf(stderr, "ERROR: Invalid client request\n"); return -2; break; } // send the http request fprintf(stdout, "\t\tWriting request to server\n"); timeout_setup(status->r_stat.http_sock, timeout); write(status->r_stat.http_sock, (char*)http_message, strlen((char*)http_message)); // read http message into a buffer fprintf(stdout, "\t\tReceiving reply from server\n"); memset(http_message, '\0', 1000); while ((n = read(status->r_stat.http_sock, (char*)http_message, 1000)) > 0) { fprintf(stdout, "\t\t\tReceived %d bytes\n", n); append_buffer(http_data, (unsigned char*)http_message, n); memset(http_message, '\0', 1000); } fprintf(stdout, "\t\tTotal bytes received: %d\n", http_data->len); // see what we go fprintf(stdout, "\t\tAssembled Message:\n%s\n", http_data->data); // check for '200 OK' char ret_code[4]; memcpy(ret_code, http_data->data + 9, 3); // HTTP/1.1 <ret_code> ~~~~ ret_code[3] = '\0'; if (atoi(ret_code) != 200) { fprintf(stderr, "ERROR: bad http request\n"); response = create_message(0, status->password, HTTP_ERROR, 0, 0, 0, 0); udp_send(response, status); return 0; } // send it to client int http_header_len = http_get_data(http_data->data) - http_data->data; int a = 0; while ((a + http_header_len) < http_data->len) { response = create_message(request_header.data[UP_VERSION], request_header.data[UP_IDENTIFIER], request_header.data[UP_CLIENT_REQUEST], request_header.data[UP_REQUEST_DATA], a, (http_data->len - http_header_len), ((http_data->len - (a + http_header_len)) > UP_MAX_PAYLOAD ? UP_MAX_PAYLOAD:(http_data->len - (a + http_header_len)))); append_buffer(response, http_data->data + a + http_header_len, UP_MAX_PAYLOAD); fprintf(stdout, "\n\t\tAssembled packet:\n"); print_header(response); fprintf(stdout, "%s\n", response->data + UP_HEADER_LEN); fprintf(stdout, "\t\tSending packet\n"); udp_send(response, status); fprintf(stdout, "\t\tPacket sent\n"); delete_buffer(response); a += 272; } fprintf(stdout, "\t\tRequest complete!\n"); memset(http_message, '\0', 1000); delete_buffer(http_data); return 1; }
/* * Main function */ int main(int argc, char** argv) { struct timeval t_out; int i, iflag, hflag, nflag, pflag; server_stat status; char *port; char usage[100]; snprintf(usage, 100, "Usage: %s -i <robot_id> -n <robot-name> -h <http_hostname> -p <udp_port>", argv[0]); status.r_stat.hostname[0] = '\0'; if (argc != 9) { fprintf(stderr, "%s\n", usage); return -1; } // read in the required arguments iflag = hflag = pflag = 0; for (i = 1; i < argc; i+=2) { if (strcmp(argv[i], "-n") == 0) { status.r_stat.id = atoi(argv[i + 1]); iflag = 1; } else if (strcmp(argv[i], "-h") == 0) { strncpy(status.r_stat.hostname, argv[i + 1], BUFFER_LEN - 1); hflag = 1; } else if (strcmp(argv[i], "-p") == 0) { port = argv[i + 1]; pflag = 1; } else if (strcmp(argv[i], "-i") == 0) { status.r_stat.name = argv[i + 1]; nflag = 1; }else { fprintf(stderr, "%s\n", usage); return -1; } } if (!(iflag && hflag && nflag && pflag)) { fprintf(stderr, "%s\n", usage); return -1; } // set up the udp socket status.udp_sock = udp_server(port); // timeouts t_out.tv_sec = 60; t_out.tv_usec = 0; timeout_setup(status.udp_sock, t_out); // execution loop srand(time(NULL)); status.size = sizeof(status.cliaddr); status.password = rand() + 1; status.connected = 0; buffer* recv_buf = create_buffer(BUFFER_LEN); for (;;) { timeout_setup(status.udp_sock, t_out); unsigned char temp[BUFFER_LEN]; memset(temp, '\0', BUFFER_LEN); int f = 10000; if ((f = recvfrom(status.udp_sock, temp, BUFFER_LEN, 0, (struct sockaddr *)(&status.cliaddr), &status.size)) < 0) { if (status.connected != 0) { buffer* quit_buf = create_message(0, status.password, QUIT, 0, 0, 0, 0); quit(quit_buf, &status); fprintf(stdout, "Waiting for a connection\n"); } } else { // decipher message clear_buffer(recv_buf); append_buffer(recv_buf, temp, f); header msg_header = extract_header(recv_buf); fprintf(stdout, "\nMessage received\n"); fprintf(stdout, "\tMessage size: %d\n", f); // send to correct protocol void (*protocol_func)(buffer*, server_stat*); protocol_func = check_version(&msg_header) ? &protocol1:&protocol2; protocol_func(recv_buf, &status); } if (status.connected != 0) { fprintf(stdout, "Waiting for a message\n"); } fflush(stdout); fflush(stderr); } return 0; }
size_t array_list_len (array_list al) { array_list_header *h = extract_header (al); return h->len; }
void array_list_free (array_list al) { array_list_header *h = extract_header (al); mem_heap_free_block ((uint8_t *) h); }