static void opts(int argc, char **argv) { int i; for (i = 1; i < argc; ++i) { if (argv[i][0] != '-') usage("unknown option", argv[i]); if (argv[i][1] == 0 || argv[i][2] != 0) usage("unknown option",argv[i]); switch (argv[i][1]) { case 'd': detach = 1; break; case 'p': port = parse_port(argv[++i]); break; case 'l': host_addr = parse_host(argv[++i]); break; case 'z': job_data_size_limit = parse_size_t(argv[++i]); break; case 'u': user = argv[++i]; break; case 'h': usage(NULL, NULL); default: usage("unknown option", argv[i]); } } }
//authority = [ userinfo "@" ] host [ ":" port ] TextCursor parse_authority(TextCursor cursor) { try { TextCursor cursor_copy(parse_userinfo(cursor)); if(get_char(cursor_copy) != '@') throw ParseError(); cursor = cursor_copy; } catch(ParseError) { } cursor = parse_host(cursor); try { TextCursor cursor_copy2(cursor); if(get_char(cursor_copy2) != ':') throw ParseError(); cursor = parse_port(cursor_copy2); } catch(ParseError) { } return cursor; }
Request new_request(str method, str host, str path) { Request retval = (Request)reserve(sizeof(struct request_struct)); if (!retval) return NULL; retval->method = method; retval->host = NULL; retval->port = 0; parse_host(retval,host); retval->path = path; retval->socket = NULL; retval->usage = new_usage(0); retval->headers = new_headers(); retval->query_vars = new_headers(); retval->contents = NULL; retval->raw_contents = NULL; retval->response = NULL; retval->cb = NULL; retval->body = 0; retval->done = 0; retval->written = 0; retval->length = -1; retval->retries = 0; retval->ssl = 0; retval->keepalive = 0; retval->proxy = 0; retval->cached = 0; return retval; }
Variant f_stream_socket_sendto(CObjRef socket, CStrRef data, int flags /* = 0 */, CStrRef address /* = null_string */) { String host; int port; parse_host(address, host, port); return f_socket_sendto(socket, data, data.size(), flags, host, port); }
//------------------------------------------------------------------------- // parsing functions //------------------------------------------------------------------------- // all commands start with $ // $packet <addr> <port> -> <addr> <port> // $packet -> client // $packet -> server // $client <addr> <port> // $server <addr> <port> static void parse_command(FileImpl* impl, char* s) { if ( !strncmp(s, "packet -> client", 16) ) set_c2s(impl, 0); else if ( !strncmp(s, "packet -> server", 16) ) set_c2s(impl, 1); else if ( !strncmp(s, "packet ", 7) ) parse_pci(impl, s+7); else if ( !strncmp(s, "client ", 7) ) parse_host(s+7, &impl->cfg.src_addr, &impl->cfg.src_port); else if ( !strncmp(s, "server ", 7) ) parse_host(s+7, &impl->cfg.dst_addr, &impl->cfg.dst_port); }
static void parse_pci(FileImpl* impl, const char* s) { parse_host(s, &impl->pci.src_addr, &impl->pci.src_port); s = strstr(s, "->"); if ( !s ) return; parse_host(s+2, &impl->pci.dst_addr, &impl->pci.dst_port); // hack until client / server is resolved: if ( impl->pci.src_port >= impl->pci.dst_port ) impl->pci.flags |= DAQ_USR_FLAG_TO_SERVER; else impl->pci.flags &= ~DAQ_USR_FLAG_TO_SERVER; }
void send_response() { str host = parse_host(client.request,find_header(client.request->headers,_("Host"))); str method = parse_method(client.request); begin_response(); client.response->status = host && method ? dispatch_method(method) : error_handler(400); end_response(); disconnect(); }
int pa_parse_address(const char *name, pa_parsed_address *ret_p) { const char *p; pa_assert(name); pa_assert(ret_p); memset(ret_p, 0, sizeof(pa_parsed_address)); ret_p->type = PA_PARSED_ADDRESS_TCP_AUTO; if (*name == '{') { char *id, *pfx; /* The URL starts with a host id for detecting local connections */ if (!(id = pa_machine_id())) return -1; pfx = pa_sprintf_malloc("{%s}", id); pa_xfree(id); if (!pa_startswith(name, pfx)) { pa_xfree(pfx); /* Not local */ return -1; } p = name + strlen(pfx); pa_xfree(pfx); } else p = name; if (*p == '/') ret_p->type = PA_PARSED_ADDRESS_UNIX; else if (pa_startswith(p, "unix:")) { ret_p->type = PA_PARSED_ADDRESS_UNIX; p += sizeof("unix:")-1; } else if (pa_startswith(p, "tcp:")) { ret_p->type = PA_PARSED_ADDRESS_TCP4; p += sizeof("tcp:")-1; } else if (pa_startswith(p, "tcp4:")) { ret_p->type = PA_PARSED_ADDRESS_TCP4; p += sizeof("tcp4:")-1; } else if (pa_startswith(p, "tcp6:")) { ret_p->type = PA_PARSED_ADDRESS_TCP6; p += sizeof("tcp6:")-1; } if (ret_p->type == PA_PARSED_ADDRESS_UNIX) ret_p->path_or_host = pa_xstrdup(p); else if (!(ret_p->path_or_host = parse_host(p, &ret_p->port))) return -1; return 0; }
static int hext_setup(FileImpl* impl) { if ( !strcmp(impl->name, "tty") ) { impl->fyle = stdin; } else if ( !(impl->fyle = fopen(impl->name, "r")) ) { DPE(impl->error, "%s: can't open file (%s)\n", DAQ_NAME, strerror(errno)); return -1; } parse_host("192.168.1.2 12345", &impl->cfg.src_addr, &impl->cfg.src_port); parse_host("10.1.2.3 80", &impl->cfg.dst_addr, &impl->cfg.dst_port); impl->cfg.ip_proto = impl->pci.ip_proto = IPPROTO_TCP; impl->cfg.flags = impl->pci.flags = DAQ_USR_FLAG_TO_SERVER; impl->start = 1; return 0; }
Variant f_stream_socket_recvfrom(CObjRef socket, int length, int flags /* = 0 */, CStrRef address /* = null_string */) { String host; int port; parse_host(address, host, port); Variant ret; Variant retval = f_socket_recvfrom(socket, ref(ret), length, flags, host, port); if (!same(retval, false) && retval.toInt64() >= 0) { return ret.toString(); // watch out, "ret", not "retval" } return false; }
static void parse_socket(CStrRef socket, String &protocol, String &host, int &port) { String address; int pos = socket.find("://"); if (pos >= 0) { protocol = socket.substr(0, pos); address = socket.substr(pos + 3); } else { protocol = "tcp"; address = socket; } parse_host(address, host, port); }
Variant f_stream_socket_sendto(CObjRef socket, CStrRef data, int flags /* = 0 */, CStrRef address /* = null_string */) { String host; int port; if (address == null_string) { Socket *sock = socket.getTyped<Socket>(); host = sock->getAddress(); port = sock->getPort(); } else { parse_host(address, host, port); } return f_socket_sendto(socket, data, data.size(), flags, host, port); }
bool URL::parse(const std::string& str) { clear(); bytebuffer buff(str.c_str(),str.length()); bool continue_hand=true; // now ====> http://www.example.com:8080/login/auth.do?user=test&pass=12344321 #ifdef _DEBUG //std::cout<<"parse URL = >"<< buff.as_string()<< std::endl; #endif // _DEBUG if(continue_hand) continue_hand=parse_protocol(buff,m_url_protocol); // now ====> www.example.com:8080/login/auth.do?user=test&pass=12344321 #ifdef _DEBUG //std::cout<<"parse_protocol = >"<< buff.as_string()<< std::endl; #endif // _DEBUG if(continue_hand) continue_hand=parse_host(buff,m_url_host); // now ====> :8080/login/auth.do?user=test&pass=12344321 #ifdef _DEBUG //std::cout<<"parse_host = >"<< buff.as_string()<< std::endl; #endif // _DEBUG if(continue_hand) continue_hand=parse_port(buff,m_url_port); // now ====> /login/auth.do?user=test&pass=12344321 #ifdef _DEBUG //std::cout<<"parse_port = >"<< buff.as_string()<< std::endl; #endif // _DEBUG if(continue_hand) continue_hand=parse_path(buff,m_url_path); // now ====> ?user=test&pass=12344321 #ifdef _DEBUG //std::cout<<"parse_path = >"<< buff.as_string()<< std::endl; #endif // _DEBUG if(continue_hand) continue_hand=parse_query(buff,m_url_query_list); // now ====> [empty] return continue_hand; }
// authority = [ userinfo "@" ] host [ ":" port ] // port = *DIGIT static IteratorT parse_authority(IteratorT begin, IteratorT end, Authority & authority) { IteratorT user_info_begin = begin; IteratorT user_info_end = parse_string(parse_user_info_character, begin, end); IteratorT host_begin = parse_constant("@", user_info_end, end); // Can we parse the "@" symbol? if (host_begin != user_info_end) { // Valid user info was found: authority.user_info_begin = user_info_begin; authority.user_info_end = user_info_end; } else { host_begin = begin; } IteratorT host_end = parse_host(host_begin, end); if (host_end == host_begin) { // We can't continue as host is required. return host_end; } authority.host_begin = host_begin; authority.host_end = host_end; IteratorT port_begin = parse_constant(":", host_end, end); if (port_begin != host_end) { IteratorT port_end = parse_predicate(is_numeric, port_begin, end); authority.port_begin = port_begin; authority.port_end = port_end; return port_end; } else { return host_end; } }
void BugzillaPreferences::update_icon_store() { if (!sharp::directory_exists (s_image_dir)) { return; } icon_store->clear(); // clear out the old entries std::list<std::string> icon_files; sharp::directory_get_files (s_image_dir, icon_files); for(std::list<std::string>::const_iterator iter = icon_files.begin(); iter != icon_files.end(); ++iter) { const std::string & icon_file(*iter); sharp::FileInfo file_info(icon_file); Glib::RefPtr<Gdk::Pixbuf> pixbuf; try { pixbuf = Gdk::Pixbuf::create_from_file(icon_file); } catch (const Glib::Error & e) { DBG_OUT("Error loading Bugzilla Icon %s: %s", icon_file.c_str(), e.what().c_str()); } if (!pixbuf) { continue; } std::string host = parse_host (file_info); if (!host.empty()) { Gtk::TreeIter treeiter = icon_store->append (); (*treeiter)[m_columns.icon] = pixbuf; (*treeiter)[m_columns.host] = host; (*treeiter)[m_columns.file_path] = icon_file; } } }
struct url_t *url_parse(const char *url) { struct url_t *self = url_new(); const char *p = url; if (!(p = parse_protocol(self, p))) { url_free(self); return NULL; } self->has_port = has_port(p); if (!(p = parse_host(self, p))) { url_free(self); return NULL; } if (!(p = parse_port(self, p))) { url_free(self); return NULL; } self->path = strdup(p); return self; }
int main(int argc, char* argv[]) { int ifindex; test_t* t; int c; printf("# ef_vi_version_str: %s\n", ef_vi_version_str()); while( (c = getopt (argc, argv, "n:s:wbvptcd")) != -1 ) switch( c ) { case 'n': cfg_iter = atoi(optarg); break; case 's': cfg_payload_len = atoi(optarg); break; case 'w': cfg_wait = 1; break; case 'v': cfg_use_vf = 1; break; case 'p': cfg_phys_mode = 1; break; case 't': cfg_disable_tx_push = 1; break; case 'c': cfg_precopy = 0; break; case '?': usage(); default: TEST(0); } argc -= optind; argv += optind; if( argc != 7 ) usage(); CL_CHK(parse_interface(argv[1], &ifindex)); CL_CHK(parse_host(argv[2], &sa_local.sin_addr)); sa_local.sin_port = htons(atoi(argv[3])); CL_CHK(parse_mac(argv[4], remote_mac)); CL_CHK(parse_host(argv[5], &sa_remote.sin_addr)); sa_remote.sin_port = htons(atoi(argv[6])); if( cfg_payload_len > MAX_UDP_PAYLEN ) { fprintf(stderr, "WARNING: UDP payload length %d is larged than standard " "MTU\n", cfg_payload_len); } for( t = the_tests; t != the_tests + NUM_TESTS; ++t ) if( ! strcmp(argv[0], t->name) ) break; if( t == the_tests + NUM_TESTS ) usage(); do_init(ifindex); printf("# udp payload len: %d\n", cfg_payload_len); printf("# iterations: %d\n", cfg_iter); printf("# frame len: %d\n", tx_frame_len); if( ! cfg_precopy ) printf("# copy on critical path\n"); t->fn(&vi); return 0; }
request::request(const int id, const std::string& r) { m_error = 0; m_error_text = ""; m_method = ""; m_path = ""; m_host = ""; m_identifier = ""; m_if_modified_since = 0; m_port = 80; m_request_lines = sammy::utils::split_string(r, '\n'); if(m_request_lines.size() == 0) { m_error = 1; m_error_text = "Request data empty."; return; } parse_header(); for(unsigned int i = 1; i < m_request_lines.size(); ++i) { // Find the line type of the request, to route it to the correct parse function const auto& current_line = m_request_lines.at(i); const auto colon_pos = current_line.find(": "); if(colon_pos == std::string::npos) { continue; } const std::string line_type = current_line.substr(0, colon_pos); const std::string line_data = current_line.substr(colon_pos + 2); if(line_type == "Host") { parse_host(line_data); continue; } if(line_type == "Cookie") { parse_cookies(line_data); continue; } if(line_type == "Referer") { parse_referer(line_data); continue; } if(line_type == "If-Modified-Since") { parse_if_modified_since(line_data); continue; } } parse_post_data(); if(m_method.size() == 0 || m_path.size() == 0 || m_host.size() == 0) { m_error = 1; m_error_text = "Method, path or host empty."; return; } m_identifier = sammy::utils::sha256(std::to_string(id)); }
void* do_proxy(void* thr_param) { int sockfd_client = *((int*)thr_param); free(thr_param); // obtain header char req[BUFSIZE]; char req_cp[BUFSIZE]; recv(sockfd_client, req, BUFSIZE, 0); printf("***Reading client request\n"); printf("<<<\n"); printf("%s", req); printf("<<<\n\n"); // find host and port strcpy(req_cp, req); int port; char* host_name = parse_host(req_cp, &port); if(host_name == NULL) { fprintf(stderr, "***No host field\n"); close(sockfd_client); return NULL; } printf("***Host name : %s\n", host_name); printf("***Port : %d\n", port); printf("***DNS retrieve..."); struct addrinfo *result; int error = getaddrinfo(host_name, NULL, NULL, &result); if(error != 0) { fflush(stdout); fprintf(stderr, "\n***No such host : %s\n", host_name); close(sockfd_client); return NULL; } printf("ok\n"); struct sockaddr_in *serv_addr = (struct sockaddr_in *)result->ai_addr; serv_addr->sin_port = htons(port); // Connect to server char server_ip[100] = {0,}; inet_ntop(AF_INET, &serv_addr->sin_addr, server_ip, 100); printf("***Connecting to server : %s...", server_ip); fflush(stdout); int sockfd_server = socket(AF_INET, SOCK_STREAM, 0); if(connect(sockfd_server, (struct sockaddr *)serv_addr, sizeof(struct sockaddr_in))<0) { perror("***Error in connecting to server\n"); close(sockfd_server); close(sockfd_client); freeaddrinfo(result); return NULL; } freeaddrinfo(result); printf("ok\n"); /* Send message to server */ int n = write(sockfd_server, req, strlen(req)); if(n < 0) { perror("***Error writing to socket\n"); close(sockfd_server); close(sockfd_client); return NULL; } /* Read server response */ char buffer[1024 * 32] = {0,}; int is_chunked_encoding = 0; int is_only_1_byte_size = 0; char only_1_byte_size; int content_len = 0; int count_recv = 0; int chunked_skip_size = 0; int remaind = 0; int header_data_size = 1024*1024; char* header_data = malloc(header_data_size); memset(header_data, 0, header_data_size); int nheader_data = 0; int body_data_size = 1024*1024*10; char* body_data = malloc(body_data_size); memset(body_data, 0, body_data_size); int nbody_data = 0; int exist_contents_len = 0; do { // recieve from remote host memset((char*)buffer, 0, sizeof(buffer)); n = recv(sockfd_server, buffer, sizeof(buffer), 0); // printf("****** n : %d\n", n); /* printf(">>>>>>>>>>>>>>>>>\n"); printf("%s", buffer); printf(">>>>>>>>>>>>>>>>>\n"); */ if(n > 0) { // 청크드 인코딩의 사이즈 읽을때 1 바이트 만 남아 1바이트 저장한 경우 if(is_only_1_byte_size) { char temp[1024 * 32] = {0,}; // 32K temp[0] = only_1_byte_size; memcpy(temp+1, buffer, n); memcpy(buffer, temp, n+1); n++; is_only_1_byte_size = 1; } char* body = buffer; // if this is the first time we are here // meaning: we are reading the http response header if(count_recv++ == 0) { // read Content-Length const char* p = strstr(buffer, "Content-Length:"); if(p!= NULL) { sscanf(p, "Content-Length: %d", &content_len); printf("***Content-Length: %d\n", content_len); exist_contents_len = 1; } p = strstr(buffer, "Transfer-Encoding: chunked"); if(p != NULL) { is_chunked_encoding = 1; printf("***chunked encoding !!\n"); } body = strstr(buffer, "\r\n\r\n") + 4; nheader_data = body-buffer; memcpy(header_data, buffer, nheader_data); // printf("%s\n\n\n\n", header_data); // remove Transfer-Encoding field char* ptr = strstr(header_data, "Transfer-Encoding: chunked"); if(ptr != NULL) { char* header_cp = malloc(header_data_size); memset(header_cp, 0, header_data_size); const char* pp = strchr(ptr, '\n'); int size_front = ptr-header_data; int size_rear = nheader_data - (pp+1 - header_data); memcpy(header_cp, header_data, size_front); memcpy(header_cp+size_front, pp+1, size_rear); memset(header_data, 0, header_data_size); nheader_data = size_front + size_rear; memcpy(header_data, header_cp, nheader_data); free(header_cp); printf("***Remove Transfer-Encoding: chunked Field...ok\n"); // printf("%s\n\n\n\n", header_data); } } // --------------------- // Body 처리 // --------------------- //printf("%s", buffer); //printf("%s", body); if(content_len == 0) { if(is_chunked_encoding) // chunked encoding 처리 { //printf("\n********************************************************\n"); //fwrite(buffer, 1, n, stdout); //printf("\n********************************************************\n"); int chunk_size = 0; const char* pchunk = body; // 직전에 스킵 못한 만큼 버린다. if(chunked_skip_size > 0) { pchunk += chunked_skip_size; chunked_skip_size = 0; } // 직전에 다 읽지 못한 나머지 읽어 처리 if(remaind > 0) { if(remaind > n) { // printf("@@@@@@@@@@@@ copy 0\n"); memcpy(body_data + nbody_data, pchunk, n); nbody_data += n; remaind -= n; continue; } // printf("@@@@@@@@@@@@ copy 1\n"); memcpy(body_data + nbody_data, pchunk, remaind); nbody_data += remaind; pchunk += remaind; remaind = 0; int cur_pos = pchunk - buffer; if(cur_pos >= n) continue; //pchunk = strstr(pchunk, "\n") + 1; pchunk += 2; } // Loop 돌며 chunk 단위로 처리 while(1) { // 1 바이트 만 남았을 경우 (최소 2바이트가 남아 있어야 청크 사이즈를 알수 있다. if(n - (pchunk - buffer) == 1) { // 한바이트 저장하고 다시 recv 받은것과 같이 처리한다. is_only_1_byte_size = 1; only_1_byte_size = *pchunk; break; } sscanf(pchunk, "%X", &chunk_size); // printf("***nrecv : %d pos : %d\n", n, pchunk - buffer); // printf("***chunk size : %d ( %x )\n", chunk_size, chunk_size); if(chunk_size == 0) break; if(chunk_size <= 15) pchunk += 3; else if(chunk_size <= 255) pchunk += 4; else if(chunk_size <= 4095) pchunk += 5; else if(chunk_size <= 65535) pchunk += 6; else pchunk += 7; //pchunk = strstr(pchunk, "\n") + 1; int cur_pos = pchunk - buffer; if(cur_pos >= n) // 청크가 짤려있을 경우 { chunked_skip_size = cur_pos - n; remaind = chunk_size; break; } if(cur_pos + chunk_size > n) // 청크가 짤려있을 경우 { remaind = chunk_size; chunk_size = n - cur_pos; remaind -= chunk_size; // printf("@@@@@@@@@@@@ copy 2 copy size : %d\n", chunk_size); memcpy(body_data + nbody_data, pchunk, chunk_size); nbody_data += chunk_size; //printf("%s", pchunk); break; } else // 청크가 버퍼에 온전히 있을 경우 { remaind = 0; // printf("@@@@@@@@@@@@ copy 3\n"); memcpy(body_data + nbody_data, pchunk, chunk_size); nbody_data += chunk_size; pchunk += chunk_size; pchunk += 2; cur_pos = pchunk - buffer; if(cur_pos >= n) { chunked_skip_size = cur_pos - n; break; } } } } else // 청크드 인코딩이 아닌경우 { // printf("%s", body); // printf("@@@@@@@@@@@@ copy 4\n"); memcpy(body_data + nbody_data, body, strlen(body)); nbody_data += strlen(body); } } else // Content-Length 가 헤더에 있을 경우 { int header_size = body - buffer; int nbody = n - header_size; int nwrite = nbody; // printf("@@@@@@@@@@@@ copy 5\n"); memcpy(body_data + nbody_data, body, nbody); nbody_data += nbody; content_len -= nwrite; if(content_len <= 0) break; } } } while(n > 0); if(!exist_contents_len) { // insert Content-Lengt field char* p = strstr(header_data, "\r\n\r\n"); sprintf(p, "\nContent-Length: %d\r\n\r\n", nbody_data); nheader_data = strlen(header_data); printf("***Insert Content-Length Field...ok\n"); } printf(">>>\n"); printf("%s", header_data); // printf("---------------------------\n\n"); // printf("%s", body_data); // printf("***** nheader_data : %d\n", nheader_data); // printf("***** nbody_data : %d\n", nbody_data); write(sockfd_client, header_data, nheader_data); write(sockfd_client, body_data, nbody_data); free(header_data); free(body_data); close(sockfd_server); close(sockfd_client); printf(">>>\n\n"); return NULL; }
bool parse_url(char const* input, url_t* url, url_t const* base, bool* errors) { enum state_t { state_scheme_start, state_scheme, state_no_scheme, state_relative_or_authority, state_path_or_authority, state_relative, state_relative_slash, state_authority_slashes, state_authority_ignore_slashes, state_authority, state_host, state_port, state_file, state_file_slash, state_file_host, state_path_start, state_path, state_non_relative_path, state_query, state_fragment, }; size_t length = strlen(input); if (!length) return false; for (size_t i = 0; i < length; ++i) { if (input[i] < 0x00 || input[i] > 0x7E) { // no unicode support return false; } if (input[i] == 0x0D || input[i] == 0x0A || input[i] == 0x09) { // no tab or newline return false; } } bool s_errors = false; if (errors) { *errors = false; } else { errors = &s_errors; } if (input[0] <= 0x20 || input[length - 1] <= 0x20) { // leading or trailing C0-controls and space *errors = true; while (*input <= 0x20) { ++input; --length; } while (length && input[length - 1] <= 0x20) { --length; } } state_t state = state_scheme_start; reset_url(url); bool at_flag = false; bool bracket_flag = false; std::string buffer; char const* ptr = input; while (true) { switch (state) { case state_scheme_start: if (std::isalpha(*ptr)) { buffer.push_back(std::tolower(*ptr)); state = state_scheme; } else { state = state_no_scheme; --ptr; } break; case state_scheme: if (std::isalnum(*ptr) || *ptr == '+' || *ptr == '-' || *ptr == '.') { buffer.push_back(std::tolower(*ptr)); } else if (*ptr == ':') { url->scheme = buffer; url->is_special = (url->scheme == "ftp" || url->scheme == "gopher" || url->scheme == "http" || url->scheme == "https" || url->scheme == "ws" || url->scheme == "wss" || url->scheme == "file"); buffer.clear(); if (url->scheme == "file") { if (ptr[1] != '/' || ptr[2] != '/') { *errors = true; } state = state_file; } else if (url->is_special) { if (base && base->scheme == url->scheme) { state = state_relative_or_authority; } else { state = state_authority_slashes; } } else if (ptr[1] == '/') { state = state_path_or_authority; ++ptr; } else { url->non_relative = true; url->path.push_back(""); state = state_non_relative_path; } } else { buffer.clear(); ptr = input - 1; state = state_no_scheme; } break; case state_no_scheme: if (!base || (base->non_relative && *ptr != '#')) { return false; } else if (base->non_relative && *ptr == '#') { copy_url(url, base, c_scheme | c_path | c_query); url->non_relative = true; state = state_fragment; } else if (base->scheme != "file") { state = state_relative; --ptr; } else { state = state_file; --ptr; } break; case state_relative_or_authority: if (ptr[0] == '/' && ptr[1] == '/') { state = state_authority_ignore_slashes; ++ptr; } else { *errors = true; state = state_relative; --ptr; } break; case state_path_or_authority: if (*ptr == '/') { state = state_authority; } else { state = state_path; --ptr; } break; case state_relative: copy_url(url, base, c_scheme); switch (*ptr) { case 0: copy_url(url, base, c_username | c_password | c_host | c_port | c_path | c_query); break; case '/': state = state_relative_slash; break; case '?': copy_url(url, base, c_username | c_password | c_host | c_port | c_path); state = state_query; break; case '#': copy_url(url, base, c_username | c_password | c_host | c_port | c_path | c_query); state = state_fragment; break; default: if (url->is_special && *ptr == '\\') { *errors = true; state = state_relative_slash; } else { copy_url(url, base, c_username | c_password | c_host | c_port | c_path); if (url->path.size()) { url->path.pop_back(); } state = state_path; --ptr; } } break; case state_relative_slash: if (*ptr == '/' || (url->is_special && *ptr == '\\')) { if (*ptr == '\\') { *errors = true; } state = state_authority_ignore_slashes; } else { copy_url(url, base, c_username | c_password | c_host | c_port); state = state_path; --ptr; } break; case state_authority_slashes: if (ptr[0] == '/' && ptr[1] == '/') { state = state_authority_ignore_slashes; ++ptr; } else { *errors = true; state = state_authority_ignore_slashes; --ptr; } break; case state_authority_ignore_slashes: if (*ptr != '/' && *ptr != '\\') { state = state_authority; --ptr; } else { *errors = true; } break; case state_authority: if (*ptr == '@') { *errors = true; if (at_flag) { buffer = "%40" + buffer; } at_flag = true; bool password = false; for (char chr : buffer) { if (chr == ':') { password = true; } else if (password) { percent_encode<encode_userinfo>(url->password, chr); } else { percent_encode<encode_userinfo>(url->username, chr); } } buffer.clear(); } else if (*ptr == 0 || *ptr == '/' || *ptr == '?' || *ptr == '#' || (url->is_special && *ptr == '\\')) { ptr -= buffer.size() + 1; buffer.clear(); state = state_host; } else { buffer.push_back(*ptr); } break; case state_host: if (*ptr == ':' && !bracket_flag) { if (url->is_special && buffer.empty()) { return false; } if (!parse_host(buffer, url, errors)) { return false; } buffer.clear(); state = state_port; } else if (*ptr == 0 || *ptr == '/' || *ptr == '?' || *ptr == '#' || (url->is_special && *ptr == '\\')) { --ptr; if (url->is_special && buffer.empty()) { return false; } if (!parse_host(buffer, url, errors)) { return false; } buffer.clear(); state = state_path_start; } else { if (*ptr == '[') { bracket_flag = true; } else if (*ptr == ']') { bracket_flag = false; } buffer.push_back(*ptr); } break; case state_port: if (std::isdigit(*ptr)) { buffer.push_back(*ptr); } else if (*ptr == 0 || *ptr == '/' || *ptr == '?' || *ptr == '#' || (url->is_special && *ptr == '\\')) { if (buffer.size() > 5) return false; int length, port; if (sscanf(buffer.c_str(), "%d%n", &port, &length) != 1 || static_cast<size_t>(length) != buffer.size() || port > 65535) { return false; } url->port = (port == scheme_port(url->scheme.c_str()) ? 0 : port); buffer.clear(); state = state_path_start; --ptr; } else { return false; } break; case state_file: url->scheme = "file"; url->is_special = true; switch (*ptr) { case 0: if (base && base->scheme == "file") { copy_url(url, base, c_host | c_path | c_query); } break; case '\\': *errors = true; // fall through case '/': state = state_file_slash; break; case '?': if (base && base->scheme == "file") { copy_url(url, base, c_host | c_path); } state = state_query; break; case '#': if (base && base->scheme == "file") { copy_url(url, base, c_host | c_path | c_query); } state = state_fragment; break; default: if (base && base->scheme == "file" && (!std::isalpha(ptr[0]) || (ptr[1] != ':' && ptr[1] != '|') || ptr[2] == 0 || (ptr[2] != '/' && ptr[2] != '\\' && ptr[2] != '?' && ptr[2] != '#'))) { copy_url(url, base, c_host | c_path); pop_path(url->path); } else if (base && base->scheme == "file") { return false; } state = state_path; --ptr; } break; case state_file_slash: if (*ptr == '/' || *ptr == '\\') { if (*ptr == '\\') *errors = true; state = state_file_host; } else { if (base && base->scheme == "file" && base->path.size() && is_normalized_drive(base->path[0])) { url->path.push_back(base->path[0]); } state = state_path; --ptr; } break; case state_file_host: if (*ptr == 0 || *ptr == '/' || *ptr == '\\' || *ptr == '?' || *ptr == '#') { --ptr; if (is_drive(buffer)) { *errors = true; state = state_path; } else if (buffer.empty()) { state = state_path_start; } else { if (!parse_host(buffer, url, errors)) { return false; } if (url->host == "localhost") { url->host.clear(); } buffer.clear(); state = state_path_start; } } else { buffer.push_back(*ptr); } break; case state_path_start: if (url->is_special && *ptr == '\\') { *errors = true; } state = state_path; if (*ptr != '/' && (!url->is_special || *ptr != '\\')) { --ptr; } break; case state_path: if (*ptr == 0 || *ptr == '/' || (url->is_special && *ptr == '\\') || *ptr == '?' || *ptr == '#') { if (url->is_special && *ptr == '\\') { *errors = true; } if (buffer == "..") { pop_path(url->path); if (*ptr != '/' && (!url->is_special || *ptr != '\\')) { url->path.push_back(""); } } else if (buffer == "." && *ptr != '/' && (!url->is_special || *ptr != '\\')) { url->path.push_back(""); } else if (buffer != ".") { if (url->scheme == "file" && url->path.empty() && is_drive(buffer)) { if (url->host.size()) *errors = true; url->host.clear(); buffer[1] = ':'; } url->path.push_back(buffer); } buffer.clear(); if (*ptr == '?') { state = state_query; } else if (*ptr == '#') { state = state_fragment; } } else { if (!url_code_point(*ptr) && *ptr != '%') { *errors = true; } else if (*ptr == '%' && (!std::isxdigit(ptr[1]) || !std::isxdigit(ptr[2]))) { *errors = true; } if (*ptr == '%' && ptr[1] == '2' && (ptr[2] == 'e' || ptr[2] == 'E')) { buffer.push_back('.'); ptr += 2; } else { percent_encode<encode_default>(buffer, *ptr); } } break; case state_non_relative_path: if (*ptr == '?') { state = state_query; } else if (*ptr == '#') { state = state_fragment; } else { if (*ptr != 0 && !url_code_point(*ptr) && *ptr != '%') { *errors = true; } else if (*ptr == '%' && (!std::isxdigit(ptr[1]) || !std::isxdigit(ptr[2]))) { *errors = true; } if (*ptr) { percent_encode<encode_simple>(url->path[0], *ptr); } } break; case state_query: if (*ptr == '#') { state = state_fragment; } else { if (*ptr != 0 && !url_code_point(*ptr) && *ptr != '%') { *errors = true; } else if (*ptr == '%' && (!std::isxdigit(ptr[1]) || !std::isxdigit(ptr[2]))) { *errors = true; } if (*ptr) { percent_encode<encode_query>(url->query, *ptr); } } break; case state_fragment: if (*ptr != 0 && !url_code_point(*ptr) && *ptr != '%') { *errors = true; } else if (*ptr == '%' && (!std::isxdigit(ptr[1]) || !std::isxdigit(ptr[2]))) { *errors = true; } if (*ptr) { url->query.push_back(*ptr); } break; } if (ptr < input + length) { ++ptr; } else { break; } } return true; }
int main(int argc, char **argv) { char *dev, *capfile, *bpf_prog; extern char *optarg; extern int optind; extern char *__progname; int ch, dontfork_flag, r; pcap_t *pcap = NULL; struct sockaddr_storage dest, src; socklen_t destlen, srclen; #ifdef NF9 int opt =0; #endif bpf_prog = NULL; dev = capfile = NULL; dontfork_flag = 0; memset(&dest, '\0', sizeof(dest)); memset(&src, '\0', sizeof(src)); destlen = 0; srclen = 0; #ifdef NF9 while ((ch = getopt(argc, argv, "hdDi:n:r:S:s:v:m:p:e:")) != -1) { #else while ((ch = getopt(argc, argv, "hdDi:n:r:S:v:")) != -1) { #endif /*NF9*/ switch (ch) { case 'h': usage(); return (0); case 'S': if (strcasecmp(optarg, "any") == 0) { direction = 0; break; } if (strcasecmp(optarg, "in") == 0) { direction = PF_IN; break; } if (strcasecmp(optarg, "out") == 0) { direction = PF_OUT; break; } usage(); return (0); case 'D': verbose_flag = 1; /* FALLTHROUGH */ case 'd': dontfork_flag = 1; break; case 'i': if (capfile != NULL || dev != NULL) { fprintf(stderr, "Packet source already specified.\n\n"); usage(); exit(1); } dev = optarg; break; case 'n': /* Will exit on failure */ destlen = sizeof(dest); parse_hostport(optarg, (struct sockaddr *)&dest, &destlen); break; case 'r': if (capfile != NULL || dev != NULL) { fprintf(stderr, "Packet source already specified.\n\n"); usage(); exit(1); } capfile = optarg; dontfork_flag = 1; break; case 's': /* Will exit on failure */ srclen = sizeof(src); parse_host(optarg, (struct sockaddr *)&src, &srclen); break; case 'v': switch((export_version = atoi(optarg))) { case 1: case 5: #ifdef NF9 case NF9_VERSION: #endif /*NF9*/ break; default: fprintf(stderr, "Invalid NetFlow version\n"); exit(1); } break; #ifdef NF9 case 'm': { opt= atoi(optarg); if(opt>=0) refresh_minutes_interval=opt; } break; case 'p': { opt= atoi(optarg); if(opt>0) refresh_packets_interval=opt; } break; case 'e': source_id = atoi(optarg); break; #endif /*NF9*/ default: fprintf(stderr, "Invalid commandline option.\n"); usage(); exit(1); } } if (capfile == NULL && dev == NULL) dev = DEFAULT_INTERFACE; /* join remaining arguments (if any) into bpf program */ bpf_prog = argv_join(argc - optind, argv + optind); /* Will exit on failure */ setup_packet_capture(&pcap, dev, capfile, bpf_prog); /* Netflow send socket */ if (dest.ss_family != 0 && src.ss_family != 0) netflow_socket = connsock_bind((struct sockaddr *)&dest, destlen, (struct sockaddr *)&src, srclen); else if (dest.ss_family != 0) netflow_socket = connsock((struct sockaddr *)&dest, destlen); else { fprintf(stderr, "No export target defined\n"); if (!verbose_flag) exit(1); } if (dontfork_flag) { if (!verbose_flag) drop_privs(); openlog(__progname, LOG_PID|LOG_PERROR, LOG_DAEMON); } else { daemon(0, 0); openlog(__progname, LOG_PID, LOG_DAEMON); if (pidfile(NULL) == -1) { syslog(LOG_WARNING, "Couldn't write pidfile: %s", strerror(errno)); } /* Close and reopen syslog to pickup chrooted /dev/log */ closelog(); openlog(__progname, LOG_PID, LOG_DAEMON); drop_privs(); signal(SIGINT, sighand_exit); signal(SIGTERM, sighand_exit); } if (dev != NULL) syslog(LOG_NOTICE, "%s listening on %s", __progname, dev); /* Main processing loop */ gettimeofday(&start_time, NULL); r = pcap_loop(pcap, -1, packet_cb, NULL); if (r == -1) { syslog(LOG_ERR, "pcap_dispatch: %s", pcap_geterr(pcap)); exit(1); } if (r == 0 && capfile == NULL) syslog(LOG_NOTICE, "Exiting on pcap EOF"); exit(0); }
int main(int argc, char* argv[]) { const char* interface; test_t* t; int c; printf("# ef_vi_version_str: %s\n", ef_vi_version_str()); while( (c = getopt (argc, argv, "n:s:wfbvVpta:A:")) != -1 ) switch( c ) { case 'n': cfg_iter = atoi(optarg); break; case 's': cfg_payload_len = atoi(optarg); break; case 'w': cfg_eventq_wait = 1; break; case 'f': cfg_fd_wait = 1; break; case 'v': cfg_use_vf = 1; break; case 'V': cfg_use_vport = 1; break; case 'p': cfg_phys_mode = 1; break; case 't': cfg_disable_tx_push = 1; break; case 'a': cfg_tx_align = atoi(optarg); break; case 'A': cfg_rx_align = atoi(optarg); break; case '?': usage(); default: TEST(0); } argc -= optind; argv += optind; if( argc != 7 ) usage(); interface = argv[1]; CL_CHK(parse_host(argv[2], &sa_local.sin_addr)); sa_local.sin_port = htons(atoi(argv[3])); CL_CHK(parse_mac(argv[4], remote_mac)); CL_CHK(parse_host(argv[5], &sa_remote.sin_addr)); sa_remote.sin_port = htons(atoi(argv[6])); if( cfg_payload_len > MAX_UDP_PAYLEN ) { fprintf(stderr, "WARNING: UDP payload length %d is larged than standard " "MTU\n", cfg_payload_len); } for( t = the_tests; t != the_tests + NUM_TESTS; ++t ) if( ! strcmp(argv[0], t->name) ) break; if( t == the_tests + NUM_TESTS ) usage(); printf("# udp payload len: %d\n", cfg_payload_len); printf("# iterations: %d\n", cfg_iter); do_init(interface); printf("# frame len: %d\n", tx_frame_len); printf("# rx align: %d\n", cfg_rx_align); printf("# tx align: %d\n", cfg_tx_align); t->fn(); /* Free all ef_vi resources we allocated above. This isn't * necessary as the process is about to exit which will free up all * resources. It is just to serve as an example of how to free up * ef_vi resources without exiting the process. */ do_free(); return 0; }