Пример #1
0
void EasyP2P::on_message(int sock, string message)
{
	append_buf(sock, message);

	switch (get_state(sock)) {
		case EasyP2PState::NICK:
		{
			string result;
			if ( !read_until(message, "\n", result, 0) ) {
				need_buf(sock, message, true);
				return;
			}

			regex r(R"(^(\w+)\s+)");
			smatch m;
			if (!regex_search(result, m, r)) {
				string message = "Invalid nickname!";
				_scheduler.write_line(sock, message);
				return;
			}

			auto nick = m[1];
			if (_n2s.find(nick) != _n2s.end()) {
				string message = "ALready exist!";
				_scheduler.write_line(sock, message);
				return;
			}

			_n2s[nick] = sock;
			_s2n[sock] = nick;
			_scheduler.write_line(sock, "Nickname OK!");
			_scheduler.write_line(sock, "You can type cmd now!");
			set_state(sock, EasyP2PState::CMD);

			break;
		}
		case EasyP2PState::CMD:
		{
			string result;
			regex r(R"(^\w+\s+(\w+))");

			while (true) {
				if ( !read_until(message, "\n", result, 0) ) {
					need_buf(sock, message, true);
					return;
				}

				if ( result.find("list") == 0 ) {
					on_list(sock);
				}
				else if ( result.find("info ") == 0 ) {
Пример #2
0
UExpression Map::create(Reader *r) {
  r->pop_token();

  auto without_curly_close = without(closeTypes, TokenType::CurlyClose);

  std::list<UExpression> l;
  read_until(r, TokenType::CurlyClose, without_curly_close, l);

  if (l.size() % 2 == 1) {
    throw ReaderException("Map entries should be even");
  }

  return make_unique<Map>(l);
}
Пример #3
0
 fc::http::reply parse_reply() {
    fc::http::reply rep;
    try {
      fc::vector<char> line(1024*8);
      int s = read_until( line.data(), line.data()+line.size(), ' ' ); // HTTP/1.1
      s = read_until( line.data(), line.data()+line.size(), ' ' ); // CODE
      rep.status = fc::lexical_cast<int>(fc::string(line.data()));
      s = read_until( line.data(), line.data()+line.size(), '\n' ); // DESCRIPTION
      
      while( (s = read_until( line.data(), line.data()+line.size(), '\n' )) > 1 ) {
        fc::http::header h;
        char* end = line.data();
        while( *end != ':' )++end;
        h.key = fc::string(line.data(),end);
        ++end; // skip ':'
        ++end; // skip space
        char* skey = end;
        while( *end != '\r' ) ++end;
        h.val = fc::string(skey,end);
        rep.headers.push_back(h);
        if( h.key == "Content-Length" ) {
           rep.body.resize( fc::lexical_cast<int>( fc::string(h.val) ) );
        }
      }
      if( rep.body.size() ) {
        //slog( "Reading body size %d", rep.body.size() );
        sock.read( rep.body.data(), rep.body.size() );
      }
      return rep;
    } catch ( ... ) {
      elog( "%s", fc::except_str().c_str() );
      sock.close();
      FC_THROW_REPORT( "Error parsing reply" );
      rep.status = http::reply::InternalServerError;
      return rep;
    } 
 }
Пример #4
0
char * clienttest(char *host, char *request) {
    int clientfd;
    char *port = "80";
    char *result;

    // Open the socket and set it up
    clientfd = Open_clientfd(host, port);
    // Write an http request to end-server
    Rio_writen(clientfd, request, strlen(request));
    // Read response from end-server until ending html tag encountered
    result = read_until(clientfd, "</html>\0");
    // Close the connection and return the end-server's response
    // Fputs(result, stdout);
    Close(clientfd);
    return result;
}
Пример #5
0
void ClientParser::send(std::vector<std::string> commands) {

  if( commands.size() != 2 ) {
    std::cout << "Error: Bad send params" << std::endl;
    return;
  }

  // Get User
  auto user = commands.front();

  // Get Subject
  auto subject = commands.at(1);

  // Get Message
  std::cout << "- Type your message. End with a blank line -" << std::endl;

  std::string message;

  while(true) {
    std::string buffer;
    getline(std::cin, buffer);

    if( buffer.empty() ) {
      break;
    }

    message += buffer += "\n";
  }

  // Send Request
  auto client = Client::get_instance();

  bool status = client->send_request( Request::put(user, subject, message) );

  if( !status ) {
    std::cout << "Error: Request could not send to the server!";
  }

  // Read Request
  auto response = client->read_until('\n');

  if( is_error(response) ) {
    std::cout << response;
    return;
  }

}
Пример #6
0
void servertest(char *port) {
    char *request, *hostname, *response, *client_ip_address;
    struct sockaddr_in clientaddr;
    struct hostent *hp;
    int clientlen, connfd;

    // start listening and enter infinite listening loop
    int listenfd = Open_listenfd(port);
    while (1) {
        // accept a connection
        clientlen = sizeof(clientaddr);
        connfd = Accept(listenfd, (SA *)&clientaddr, &clientlen);
        // get some information from the client
        hp = Gethostbyaddr((const char *)&clientaddr.sin_addr.s_addr,
            sizeof(clientaddr.sin_addr.s_addr), AF_INET);
        client_ip_address = inet_ntoa(clientaddr.sin_addr);
        // read the request from the end-user
        request = read_until(connfd, "\r\n\r\n\0");
        // Store the hostname from the request
        hostname = parseRequest(request);
        // printf("S-Parse result:%s", hostname);
        if (hostname) {
            // Pass on the client's request
            response = clienttest(hostname, request);
            // printf("S-Response result:\n%s\n", response);
            //check that the response isn't empty (end-server responded)

            // respond to the end-user
            Rio_writen(connfd, response, strlen(response));
            // writeLogEntry (only if there was a response)
            if (strcmp(response, "") != 0) {
               writeLogEntry(client_ip_address, hostname, strlen(response));
               // printf("S-Wrote log.\n");
            }
        }
        // Finished, close connection
        Close(connfd);
        // Free the buffers except
        // client_ip_address is statically managed by inet_ntoa
        free(request);
        free(hostname);
        free(response);
    }
}
Пример #7
0
void ClientParser::read(std::vector<std::string> commands) {

  if( commands.size() != 2 ) {
    std::cout << "Error: Bad read params" << std::endl;
    return;
  }

  // Get User
  auto user = commands.front();

  // Get Index
  int index = safe_stoi( commands.at(1) );

  if( index < 1 ) {
    std::cout << "Error: Bad read params" << std::endl;
    return;
  }


  // Send Request
  auto client = Client::get_instance();

  bool status = client->send_request( Request::get( user, index ) );

  if( !status ) {
    std::cout << "Error: Request could not send to the server!";
  }

  // Read Request
  auto response = client->read_until('\n');

  if( is_error(response) ) {
    std::cout << response;
    return;
  }

  std::cout << utils::split( response ).at(1) << std::endl;

  int byte_count = std::stoi( utils::split( response ).back() );

  std::cout << client->read_for( byte_count ) << std::endl;

}
Пример #8
0
void
field_type<string>::read
  (
  istream& is,
  const matrix_separators *ap_matsep 
  )
  {
  char endchar[2];
  endchar[1] = '\0';

  var().erase();

  if (is_followed_by(is,'\"',false)) 
    endchar[0] = '\"';
  else
    endchar[0] = ap_matsep->m_field_sep;

  read_until(is,endchar,var());
  is.putback(endchar[0]); // Feld-Ende-Zeichen nicht entnehmen
  }
Пример #9
0
void serialDriver::execute(SDFFHWcommandManager* hwc_manager){
    for (size_t i=0; i<hwc_manager->get_command_count(SDFF_CMDclass_SERIAL); i++) {
        SDFFcommand* hc=hwc_manager->get_command(SDFF_CMDclass_SERIAL, i);
        if (sequencer::SDFFserialOpenCommand* c=dynamic_cast<sequencer::SDFFserialOpenCommand*>(hc)) {
            open(c->get_com_port(), c->get_baudrate(), c->get_databits(), c->get_parity(), c->get_stopbits(), c->get_handshaking());
        } else if (sequencer::SDFFserialCloseCommand* c=dynamic_cast<sequencer::SDFFserialCloseCommand*>(hc)) {
            close(c->get_com_port());
        } else if (sequencer::SDFFserialSendCommand* c=dynamic_cast<sequencer::SDFFserialSendCommand*>(hc)) {
            write(c->get_com_port(), c->get_text());
        } else if (sequencer::SDFFserialReadCommand* c=dynamic_cast<sequencer::SDFFserialReadCommand*>(hc)) {
            std::string res="";
            if (c->get_byte_count()<=0) {
                res=read_until(c->get_com_port(), c->get_end_char());
            } else {
                res=read(c->get_com_port(), c->get_byte_count());
            }
            c->set_result(res);
        }
    }
}
Пример #10
0
void AdminLogin(void) {
	char buf[100];

	zero(buf, 100);
	print("Admin Password: "******"[-] Admin access granted\n");
		return;
	}

	print("[-] Admin access denied\n");
	ADMIN_ACCESS = 0;

	return;
}
Пример #11
0
int TipWaitress(int sock) {
	char buf[100];
	int rnd;

	sendit(sock, "But it's not all bad.  The waitress just showed up with your ");
	rnd = rand() % MAX_DRINK1;
	sendit(sock, drink1[rnd]);
	rnd = rand() % MAX_DRINK2;
	sendit(sock, drink2[rnd]);
	sendit(sock, "Would you like to tip $1 (y/n)? ");
	read_until(sock, buf, 99);
	if (buf[0] == 'y' || buf[0] == 'Y') {
		rnd = rand() % MAX_TIPS;
		sendit(sock, tips[rnd]);
		return(1);
	}

	rnd = rand() % MAX_NOTIPS;
	sendit(sock, notips[rnd]);
	return(0);
}
Пример #12
0
void ClientSession::ignoreResponse()
{
    boost::asio::streambuf buffer;
    
    boost::system::error_code ec;
    
    read_until(socket_, buffer, "\r\n\r\n", ec);
    if(!ec)
    {
        
        ;
        
    }
    else
    {
        commander->insertText("Error - Connection Closed");
        output->connected = false;
        close();
    }
    
}
Пример #13
0
void ReadMessage(void) {
    char id[4];
    int id_val;

    // read in the ID:
    zero(id, 4);
    print("ID: ");
    if (read_until(id, '\n', 4) == -1) {
        _terminate(-1);
    }
    if (strlen(id) == 0) {
        return;
    }

    if (!isdigits(id)) {
        return;
    }
    id_val = atoi(id);

    if (id_val > USERS[CURRENT_USER].top_message) {
        print("[-] Message ID out of range\n");
        return;
    }

    if (USERS[CURRENT_USER].messages[id_val][0] == '\0') {
        print("[-] Message ID not found\n");
        return;
    }

    // print the message
    print("***********************************\n");
    print(id);
    print(":  ");
    print(USERS[CURRENT_USER].messages[id_val]);
    print("\n");
    print("***********************************\n");
    USERS[CURRENT_USER].msg_read[id_val] = 1;

    return;
}
Пример #14
0
void conn::game_thread(std::shared_ptr<tcp::socket> socket, bool &gameover, bots & bots, bot::team_id &id,
        boost::mutex & state_mutex, bot::field_size &field_width, bot::field_size &field_height,
        int &win_width, int &win_height, bool &connected) {

    superbots superbots(bots);

    boost::asio::streambuf buf;
    while(!gameover) {

        superbots.ejecutar(5);

        for(auto b : bots.team_bots(id)) {
            std::stringstream stream;
            stream << "move " << b->get_x() << " " << b->get_y() << " " << b->get_next_direction();
            send(*socket, stream.str());
        }

        read_until(*socket, buf, "\n");

        std::string data;
        std::istream is(&buf);
        std::getline(is, data);

        std::istringstream stream(data);

        std::string command;
        stream >> command;

        if(command == "welcome") {
            stream >> id;
            superbots.set_team(id);

            stream >> field_width;
            stream >> field_height;
            bots.set_size(field_width, field_height);
            MYscreen.set_screen(win_width, win_height, field_width, field_height);
            connected = true;
        }
        else if(command == "state") {
Пример #15
0
	void bdecode_recursive(InIt& in, InIt end, entry& ret, bool& err, int depth)
	{
		if (depth >= 100)
		{
			err = true;
			return;
		}

		if (in == end)
		{
			err = true;
			return;
		}
		switch (*in)
		{

		// ----------------------------------------------
		// integer
		case 'i':
			{
			++in; // 'i' 
			std::string val = read_until(in, end, 'e', err);
			if (err) return;
			BOOST_ASSERT(*in == 'e');
			++in; // 'e' 
			ret = entry(entry::int_t);
			char* end_pointer;
#if defined WIN32 && !defined _MINGW
			ret.integer() = _strtoi64(val.c_str(), &end_pointer, 10);
#else
			ret.integer() = strtoll(val.c_str(), &end_pointer, 10);
#endif
			if (end_pointer == val.c_str())
			{
				err = true;
				return;
			}
			} break;

		// ----------------------------------------------
		// list
		case 'l':
			{
			ret = entry(entry::list_t);
			++in; // 'l'
			while (*in != 'e')
			{
				ret.list().push_back(entry());
				entry& e = ret.list().back();
				bdecode_recursive(in, end, e, err, depth + 1);
				if (err)
				{
					return;
				}
				if (in == end)
				{
					err = true;
					return;
				}
			}
			BOOST_ASSERT(*in == 'e');
			++in; // 'e'
			} break;

		// ----------------------------------------------
		// dictionary
		case 'd':
			{
			ret = entry(entry::dictionary_t);
			++in; // 'd'
			while (*in != 'e')
			{
				entry key;
				bdecode_recursive(in, end, key, err, depth + 1);
				if (err || key.type() != entry::string_t)
				{
					return;
				}
				entry& e = ret[key.string()];
				bdecode_recursive(in, end, e, err, depth + 1);
				if (err)
				{
					return;
				}
				if (in == end)
				{
					err = true;
					return;
				}
			}
			BOOST_ASSERT(*in == 'e');
			++in; // 'e'
			} break;

		// ----------------------------------------------
		// string
		default:
			if (is_digit((unsigned char)*in))
			{
				std::string len_s = read_until(in, end, ':', err);
				if (err)
				{
					return;
				}
				BOOST_ASSERT(*in == ':');
				++in; // ':'
				int len = std::atoi(len_s.c_str());
				ret = entry(entry::string_t);
				read_string(in, end, len, ret.string(), err);
				if (err)
				{
					return;
				}
			}
			else
			{
				err = true;
				return;
			}
		}
	}
Пример #16
0
		void bdecode_recursive(InIt& in, InIt end, entry& ret)
		{
			if (in == end) throw invalid_encoding();
			switch (*in)
			{

			// ----------------------------------------------
			// integer
			case 'i':
				{
				++in; // 'i' 
				std::string val = read_until(in, end, 'e');
				assert(*in == 'e');
				++in; // 'e' 
				ret = entry(entry::int_t);
				ret.integer() = boost::lexical_cast<entry::integer_type>(val);
				} break;

			// ----------------------------------------------
			// list
			case 'l':
				{
				ret = entry(entry::list_t);
				++in; // 'l'
				while (*in != 'e')
				{
					ret.list().push_back(entry());
					entry& e = ret.list().back();
					bdecode_recursive(in, end, e);
					if (in == end) throw invalid_encoding();
				}
				assert(*in == 'e');
				++in; // 'e'
				} break;

			// ----------------------------------------------
			// dictionary
			case 'd':
				{
				ret = entry(entry::dictionary_t);
				++in; // 'd'
				while (*in != 'e')
				{
					entry key;
					bdecode_recursive(in, end, key);
					entry& e = ret[key.string()];
					bdecode_recursive(in, end, e);
					if (in == end) throw invalid_encoding();
				}
				assert(*in == 'e');
				++in; // 'e'
				} break;

			// ----------------------------------------------
			// string
			default:
				if (isdigit(*in))
				{
					std::string len_s = read_until(in, end, ':');
					assert(*in == ':');
					++in; // ':'
					int len = std::atoi(len_s.c_str());
					ret = entry(entry::string_t);
					ret.string() = read_string(in, end, len);
				}
				else
				{
					throw invalid_encoding();
				}
			}
		}
Пример #17
0
int wx_bdecode(wxFileInputStream &file, wxDataInputStream &data, entry &ret, int depth)
{
	char myByte;
	wxString padding(wxT(""));
	if (depth >= 100)
	{
		return 0;
	}
	if (file.Eof())
	{
		return 0;
	}
	switch(file.Peek())
	{
		case 'i':
			{
				if (file.Peek() == 'i') data.Read8();
				ret = entry(entry::int_t);
				std::string val = read_until(file, data, 'e');
				ret.integer() = boost::lexical_cast<entry::integer_type>(val);
				if (file.Peek() == 'e') data.Read8();
				wxLogMessage(wxT("num: ")+wxString(val.c_str(), wxConvUTF8));
			}
			break;

		case 'l':
			{
				if (file.Peek() == 'l') data.Read8();
				ret = entry(entry::list_t);
				while (file.Peek() != 'e')
				{
					ret.list().push_back(entry());
					entry& list = ret.list().back();
					wx_bdecode(file, data, list, depth + 1);
				}
				if (file.Peek() == 'e') data.Read8();
			}
			break;

		case 'd':
			{
				if (file.Peek() == 'd') data.Read8();
				ret = entry(entry::dictionary_t);
				while (file.Peek() != 'e')
				{
					entry key;
					wx_bdecode(file, data, key, depth + 1);
					if (key.type() != entry::string_t)
					{
						return 0;
					}

					entry dict;
					wx_bdecode(file, data, dict, depth + 1);
					ret.dict().insert(std::pair<std::string, entry>(key.string(), dict));
				}
				if (file.Peek() == 'e')  data.Read8();
			}
			break;

		default:
			if(isdigit(file.Peek()))
			{
				ret = entry(entry::string_t);
				std::string len_s = read_until(file, data, ':');
				if (file.Peek() == ':') data.Read8();
				int len = std::atoi(len_s.c_str());
				read_string(file, data, len, ret.string());
			}
			else
			{
				return 0;
			}
			break;
	}// switch
}
Пример #18
0
bool AParser::read_quoted_text(std::string& in) {
	return consume('"') && read_until(in, '"') && consume('"');
}
Пример #19
0
ssize_t
http_parse_request (int fd, Http_request **request_)
{
  Http_request *request;
  char *data;
  size_t len;
  ssize_t n;

  *request_ = NULL;

  request = malloc (sizeof (Http_request));
  if (request == NULL)
    {
      log_error ("http_parse_request: out of memory");
      return -1;
    }

  request->method = -1;
  request->uri = NULL;
  request->major_version = -1;
  request->minor_version = -1;
  request->header = NULL;

  n = read_until (fd, ' ', &data);
  if (n <= 0)
    {
      free (request);
      return n;
    }
  request->method = http_string_to_method (data, n - 1);
  if (request->method == -1)
    {
      log_error ("http_parse_request: expected an HTTP method");
      free (data);
      free (request);
      return -1;
    }
  data[n - 1] = 0;
  log_verbose ("http_parse_request: method = \"%s\"", data);
  free (data);
  len = n;

  n = read_until (fd, ' ', &data);
  if (n <= 0)
    {
      free (request);
      return n;
    }
  data[n - 1] = 0;
  request->uri = data;
  len += n;
  log_verbose ("http_parse_request: uri = \"%s\"", request->uri);

  n = read_until (fd, '/', &data);
  if (n <= 0)
    {
      http_destroy_request (request);
      return n;
    }
  else if (n != 5 || memcmp (data, "HTTP", 4) != 0)
    {
      log_error ("http_parse_request: expected \"HTTP\"");
      free (data);
      http_destroy_request (request);
      return -1;
    }
  free (data);
  len = n;

  n = read_until (fd, '.', &data);
  if (n <= 0)
    {
      http_destroy_request (request);
      return n;
    }
  data[n - 1] = 0;
  request->major_version = atoi (data);
  log_verbose ("http_parse_request: major version = %d",
	       request->major_version);
  free (data);
  len += n;

  n = read_until (fd, '\r', &data);
  if (n <= 0)
    {
      http_destroy_request (request);
      return n;
    }
  data[n - 1] = 0;
  request->minor_version = atoi (data);
  log_verbose ("http_parse_request: minor version = %d",
	       request->minor_version);
  free (data);
  len += n;

  n = read_until (fd, '\n', &data);
  if (n <= 0)
    {
      http_destroy_request (request);
      return n;
    }
  free (data);
  if (n != 1)
    {
      log_error ("http_parse_request: invalid line ending");
      http_destroy_request (request);
      return -1;
    }
  len += n;

  n = parse_header (fd, &request->header);
  if (n <= 0)
    {
      http_destroy_request (request);
      return n;
    }
  len += n;

  *request_ = request;
 return len;
}
Пример #20
0
region* read_map_data (char* file_name)
{
    FILE* file = fopen(file_name, "r");
    if (file == NULL) {
        fprintf(stderr, "Error reading file: %s\n", file_name);
        exit(EXIT_FAILURE);
    }

    /* init global vars */
    parens = malloc(sizeof(Stack));
    init (parens);
    line_number = 1;
    

    int c;
    c = skip_blanks(file);
    ungetc(c, file);
    if (c == EOF) return NULL;
    

    // Initialize the array of regions
    region* regions = malloc(sizeof(region)*DEFAULT_REGION_SIZE);
    int region_size = DEFAULT_REGION_SIZE;
    int region_index = 0;
    Boolean min_max_set = FALSE;
    bbox r_box;
    //Add dummy values to get rid of warning;
    r_box.min_x = 0;
    r_box.max_x = 0;
    r_box.min_y = 0;
    r_box.max_y = 0;


    while ((c = getc(file)) != EOF) {
        if (c == '{') { // Create new region
            push(parens, '{'); // add to stack

            c = skip_blanks(file);
            ungetc(c, file);
            char* buffer = malloc(sizeof(char)*DEFAULT_BUFFER_SIZE);
            if (buffer == NULL) {
                fprintf(stderr, "Error mallocing buffer\n");
                exit(EXIT_FAILURE);
            }

            int name_size = read_until(file, &buffer, DEFAULT_BUFFER_SIZE, ',');

            /* Make sure buffer can hold info */
            if (region_index >= region_size) { // Realloc if necessary
                region* temp_regions = realloc(regions, sizeof(region)*region_size*2);
                if (temp_regions == NULL) {
                    fprintf(stderr, "Problem reallocing regions buffer\n");
                    exit(EXIT_FAILURE);
                }
                regions = temp_regions;
                region_size *= 2;
            }

            // Store the name in memory, free the buffer
            regions[region_index].name = malloc(sizeof(char)*(name_size));
            if (regions[region_index].name == NULL) {
                fprintf(stderr, "Error mallocing name in region\n");
                exit(EXIT_FAILURE);
            }

            strcpy(regions[region_index].name, buffer);
            free (buffer);

            c = skip_blanks(file);
            if (!check_parens(c))
                exit(EXIT_FAILURE);

            regions[region_index].polygons = malloc(sizeof(polygon)*DEFAULT_POLYGON_SIZE);
            int polygon_size = DEFAULT_POLYGON_SIZE; // Keeps track of buffer size for polgyons
            int polygon_index = 0;
            bbox p_box;
            // Add dummy values to prevent warning
            p_box.min_x = 0;
            p_box.max_x = 0;
            p_box.min_y = 0;
            p_box.max_y = 0;
            Boolean p_min_max_set = FALSE;

            // Now read all the polygons
            while (c != '}') {
                if (c == '[') {
                    push(parens, '[');
                    // Create new polygon to go inside of region
                    c = skip_blanks(file);

                    if (polygon_index >= polygon_size) {
                        // Buffer is out of space, reallocate
                        polygon* temp_polygons = realloc(regions[region_index].polygons,
                                sizeof(polygon)*polygon_size*2);

                        if (temp_polygons == NULL){
                            fprintf(stderr, "Problem reallocing polygon buffer\n");
                            exit(EXIT_FAILURE);
                        }
                        else {
                            regions[region_index].polygons = temp_polygons;
                            polygon_size *= 2;
                        }
                    }

                    regions[region_index].polygons[polygon_index].vertices = 
                        malloc(sizeof(point)*DEFAULT_NUM_POINTS);

                    int vertices_size = DEFAULT_NUM_POINTS;
                    int vertices_index = 0;

                    while (c != ']') {
                        if (c == '(') {
                            push(parens, '(');
                            // Create new point to go inside polygon
                            // read until ')'
                            buffer = malloc(sizeof(char)*DEFAULT_BUFFER_SIZE);
                            if (buffer == NULL) {
                                fprintf(stderr, "ERROR MALLOCING\n");
                                exit(EXIT_FAILURE);
                            }
                            read_until(file, &buffer, DEFAULT_BUFFER_SIZE, ')');

                            // reached end of point, save it to the polygon
                            if (vertices_index >= vertices_size) { //Buffer is out of space, reallocate
                                point* temp_vertices = realloc(regions[region_index].
                                        polygons[polygon_index].vertices, sizeof(point)*vertices_size*2);

                                if (temp_vertices == NULL) {
                                    fprintf(stderr, "Problem reallocing vertices buffer\n");
                                    exit(EXIT_FAILURE);
                                }
                                else {
                                    regions[region_index].polygons[polygon_index].vertices = temp_vertices;
                                    vertices_size *= 2;
                                }
                            }

                            // Parse point of format "1.0,1.0" into x and y floats
                            char* pCh = strtok(buffer, ",");
                            char* pEnd;
                            double x = strtod(pCh, &pEnd);
                            pCh = strtok(NULL, ",");
                            double y = strtod(pCh, &pEnd);

                            if (debug) fprintf(debug_file, 
                                    "Storing point (%.2f,%.2f) in r_%d, p_%d v_%d\n",
                                    x,y,region_index,polygon_index,vertices_index);
                            regions[region_index].polygons[polygon_index].vertices[vertices_index].x = x;
                            regions[region_index].polygons[polygon_index].vertices[vertices_index].y = y;

                            if (!min_max_set) {
                                r_box.min_x = x;
                                r_box.max_x = x;
                                r_box.min_y = y;
                                r_box.max_y = y;
                                min_max_set = TRUE;
                            }
                            else { /* Update bounding box max and mins for current region */
                                if (x < r_box.min_x)
                                    r_box.min_x = x;
                                if (x > r_box.max_x)
                                    r_box.max_x = x;
                                if (y < r_box.min_y)
                                    r_box.min_y = y;
                                if (y > r_box.max_y)
                                    r_box.max_y = y;
                            }

                            if (!p_min_max_set) {
                                p_min_max_set = TRUE;
                                p_box.min_x = x;
                                p_box.max_x = x;
                                p_box.min_y = y;
                                p_box.max_y = y;
                            }
                            else {
                                if (x < p_box.min_x)
                                    p_box.min_x = x;
                                if (x > p_box.max_x)
                                    p_box.max_x = x;
                                if (y < p_box.min_y)
                                    p_box.min_y = y;
                                if (y > p_box.max_y)
                                    p_box.max_y = y;
                            }

                            free (buffer);
                            vertices_index++;
                        } // end if (
                        c = getc(file);
                            if (!check_parens(c))
                                exit(EXIT_FAILURE);
                    } // end while != ]
                    //reached end of polygon, save it now to region

                    regions[region_index].polygons[polygon_index].box.max_x = p_box.max_x;
                    regions[region_index].polygons[polygon_index].box.min_x = p_box.min_x;
                    regions[region_index].polygons[polygon_index].box.max_y = p_box.max_y;
                    regions[region_index].polygons[polygon_index].box.min_y = p_box.min_y;
                    p_min_max_set = FALSE;
                    regions[region_index].polygons[polygon_index].num_vertices = vertices_index;
                    polygon_index++;
                }// end if [

                c = getc(file);
                if (!check_parens(c))
                    exit(EXIT_FAILURE);
            } // end while != 
            // Copy the actual max's and min's to the region
            regions[region_index].box.max_x = r_box.max_x;
            regions[region_index].box.min_x = r_box.min_x;
            regions[region_index].box.max_y = r_box.max_y;
            regions[region_index].box.min_y = r_box.min_y;
            min_max_set = FALSE;

            //reached end of region, save it
            regions[region_index].num_polygons = polygon_index;
            region_index++;
        } // end if
        if (c == '\n')
            line_number++;
    }// end while

    return regions;
}
Пример #21
0
static ssize_t
parse_header (int fd, Http_header **header)
{
  unsigned char buf[2];
  char *data;
  Http_header *h;
  size_t len;
  ssize_t n;

  *header = NULL;

  n = read_all (fd, buf, 2);
  if (n <= 0)
    return n;
  if (buf[0] == '\r' && buf[1] == '\n')
    return n;

  h = malloc (sizeof (Http_header));
  if (h == NULL)
    {
      log_error ("parse_header: malloc failed");
      return -1;
    }
  *header = h;
  h->name = NULL;
  h->value = NULL;

  n = read_until (fd, ':', &data);
  if (n <= 0)
    return n;
  data = realloc (data, n + 2);
  if (data == NULL)
    {
      log_error ("parse_header: realloc failed");
      return -1;
    }
  memmove (data + 2, data, n);
  memcpy (data, buf, 2);
  n += 2;
  data[n - 1] = 0;
  h->name = data;
  len = n;

  n = read_until (fd, '\r', &data);
  if (n <= 0)
    return n;
  data[n - 1] = 0;
  h->value = data;
  len += n;

  n = read_until (fd, '\n', &data);
  if (n <= 0)
    return n;
  free (data);
  if (n != 1)
    {
      log_error ("parse_header: invalid line ending");
      return -1;
    }
  len += n;

  log_verbose ("parse_header: %s:%s", h->name, h->value);

  n = parse_header (fd, &h->next);
  if (n <= 0)
    return n;
  len += n;

  return len;
}
Пример #22
0
		void bdecode_recursive(InIt& in, InIt end, entry& ret, bool& err, int depth)
		{
			if (depth >= 100)
			{
				err = true;
				return;
			}

			if (in == end)
			{
				err = true;
				return;
			}
			switch (*in)
			{

			// ----------------------------------------------
			// integer
			case 'i':
				{
				++in; // 'i' 
				std::string val = read_until(in, end, 'e', err);
				if (err) return;
				TORRENT_ASSERT(*in == 'e');
				++in; // 'e' 
				ret = entry(entry::int_t);
				ret.integer() = boost::lexical_cast<entry::integer_type>(val);
				} break;

			// ----------------------------------------------
			// list
			case 'l':
				{
				ret = entry(entry::list_t);
				++in; // 'l'
				while (*in != 'e')
				{
					ret.list().push_back(entry());
					entry& e = ret.list().back();
					bdecode_recursive(in, end, e, err, depth + 1);
					if (err) return;
					if (in == end)
					{
						err = true;
						return;
					}
				}
				TORRENT_ASSERT(*in == 'e');
				++in; // 'e'
				} break;

			// ----------------------------------------------
			// dictionary
			case 'd':
				{
				ret = entry(entry::dictionary_t);
				++in; // 'd'
				while (*in != 'e')
				{
					entry key;
					bdecode_recursive(in, end, key, err, depth + 1);
					if (err) return;
					entry& e = ret[key.string()];
					bdecode_recursive(in, end, e, err, depth + 1);
					if (err) return;
					if (in == end)
					{
						err = true;
						return;
					}
				}
				TORRENT_ASSERT(*in == 'e');
				++in; // 'e'
				} break;

			// ----------------------------------------------
			// string
			default:
				if (isdigit((unsigned char)*in))
				{
					std::string len_s = read_until(in, end, ':', err);
					if (err) return;
					TORRENT_ASSERT(*in == ':');
					++in; // ':'
					int len = std::atoi(len_s.c_str());
					ret = entry(entry::string_t);
					read_string(in, end, len, ret.string(), err);
					if (err) return;
				}
				else
				{
					err = true;
					return;
				}
			}
		}
Пример #23
0
void PlayBlackjack(int sock) {
	int done = 0;
	char buf[100];
	int bet;
	char dealer[21];
	int dealer_hand_value;
	char player[21];
	int player_hand_value;
	int player_cards;
	int dealer_cards;

	while (!done) {

		// start with empty hands
		bzero(dealer, 21);
		bzero(player, 21);

		// print out current cash
		snprintf(buf, 99, "You have $%d\n", cash);
		sendit(sock, buf);

		// take bets
		bet = -1;
		while (bet < 0 || bet > MAX_BET) {
			sendit(sock, "How much would you like to bet (-1 to exit)? ");
			read_until(sock, buf, 99);
			bet = atoi(buf);
			if (bet == -1) {
				return;
			}
			if (bet < 0 || bet > MAX_BET) {
				snprintf(buf, 99, "Table limit is $%d.  Bet again.\n", MAX_BET);
				sendit(sock, buf);
			}
			if (bet == 0) {
				sendit(sock, "Well, I suppose we can let a noob blackjack player learn the ropes without risking any money.  Don't tell my pit boss.\n");
			}
			if (bet > cash) {
				snprintf(buf, 99, "No lines of credit in this casino.  Bet again.\n", MAX_BET);
				sendit(sock, buf);
				bet = -1;
			}
		} 

		// deal inital hand
		player[0] = (rand() % 13)+1;
		dealer[0] = (rand() % 13)+1;
		player[1] = (rand() % 13)+1;
		dealer[1] = (rand() % 13)+1;

		// calc inital hand values
		player_hand_value = CalculateHandValue(player);
		dealer_hand_value = CalculateHandValue(dealer);

		// print out the hands
		sendit(sock, "Dealer: "); PrintHand(sock, dealer, 1); sendit(sock, "\n");
		sendit(sock, "Player: "); PrintHand(sock, player, 0); sendit(sock, "\n");

		player_cards = 2;
		while (player_cards <= 21) {
			// hit or stand
			sendit(sock, "Hit or Stand (H/S)? ");
			read_until(sock, buf, 99);
			if (buf[0] == 'H') {
				player[player_cards++] = (rand() % 13)+1;
				// print out the hand
				sendit(sock, "Player: "); PrintHand(sock, player, 0); sendit(sock, "\n");
			} else if (buf[0] == 'S') {
				break;
			}
				
			// see if busted or win
			player_hand_value = CalculateHandValue(player);
			if (player_hand_value > 21) {
				break;
			} //else if (player_hand_value == 21) {
//				break;
//			}
		}

		dealer_cards = 2;
		while (player_hand_value <= 21 && dealer_cards < 21) {
			// dealer hit or stand
			if (dealer_hand_value < 17) {
				sendit(sock, "Dealer hits\n");
				dealer[dealer_cards++] = (rand() % 13)+1;

				// print out the hand
				sendit(sock, "Dealer: "); PrintHand(sock, dealer, 0); sendit(sock, "\n");
			} else {
				sendit(sock, "Dealer stands\n");
				sendit(sock, "Dealer: "); PrintHand(sock, dealer, 0); sendit(sock, "\n");
				break;
			}

			// see if busted
			dealer_hand_value = CalculateHandValue(dealer);
			if (dealer_hand_value > 21) {
				break;
			} else if (dealer_hand_value == 21) {
				break;
			}
		}

		// see who won
		if (player_hand_value == 21 && dealer_hand_value != 21) {
			sendit(sock, "You win!\n\n");
			cash += bet;
			winnings[total_bets++] = bet;
		} else if (dealer_hand_value == 21 && player_hand_value != 21) {
			sendit(sock, "You lose!\n");
			if (bet == 127 && TipWaitress(sock)) {
				bet++;
			}
			cash -= bet;
			winnings[total_bets++] = 0-bet;
		} else if (player_hand_value > 21) {
			sendit(sock, "You lose!\n\n");
			if (bet == 127 && TipWaitress(sock)) {
				bet++;
			}
			cash -= bet;
			winnings[total_bets++] = 0-bet;
		} else if (dealer_hand_value > 21) {
			sendit(sock, "You win!\n\n");
			cash += bet;
			winnings[total_bets++] = bet;
		} else if (player_hand_value > dealer_hand_value) {
			sendit(sock, "You win!\n\n");
			cash += bet;
			winnings[total_bets++] = bet;
		} else if (player_hand_value == dealer_hand_value) {
			sendit(sock, "It's a draw.\n\n");
		} else if (player_hand_value < dealer_hand_value) {
			sendit(sock, "You lose!\n\n");
			if (bet == 127 && TipWaitress(sock)) {
				bet++;
			}
			cash -= bet;
			winnings[total_bets++] = 0-bet;
		}

		//PrintWinnings(sock);

		if (total_bets == MAX_WINNINGS) {
			sendit(sock, "The pit boss is tired of you flirting with the waitresses...you're outta here\n");
			break;
		}

		if (cash <= 0) {
			break;
		}
	}
}
Пример #24
0
/* Parse the data section of VCD */
static void parse_contents(FILE *file, const struct sr_dev_inst *sdi, struct context *ctx)
{
	GString *token = g_string_sized_new(32);
	
	uint64_t prev_timestamp = 0;
	uint64_t prev_values = 0;
	
	/* Read one space-delimited token at a time. */
	while (read_until(file, NULL, 'N') && read_until(file, token, 'W'))
	{
		if (token->str[0] == '#' && g_ascii_isdigit(token->str[1]))
		{
			/* Numeric value beginning with # is a new timestamp value */
			uint64_t timestamp;
			timestamp = strtoull(token->str + 1, NULL, 10);
			
			if (ctx->downsample > 1)
				timestamp /= ctx->downsample;
			
			/* Skip < 0 => skip until first timestamp.
			 * Skip = 0 => don't skip
			 * Skip > 0 => skip until timestamp >= skip.
			 */
			if (ctx->skip < 0)
			{
				ctx->skip = timestamp;
				prev_timestamp = timestamp;
			}
			else if (ctx->skip > 0 && timestamp < (uint64_t)ctx->skip)
			{
				prev_timestamp = ctx->skip;
			}
			else if (timestamp == prev_timestamp)
			{
				/* Ignore repeated timestamps (e.g. sigrok outputs these) */
			}
			else
			{
				if (ctx->compress != 0 && timestamp - prev_timestamp > ctx->compress)
				{
					/* Compress long idle periods */
					prev_timestamp = timestamp - ctx->compress;
				}
			
				sr_dbg("New timestamp: %" PRIu64, timestamp);
			
				/* Generate samples from prev_timestamp up to timestamp - 1. */
				send_samples(sdi, prev_values, timestamp - prev_timestamp);
				prev_timestamp = timestamp;
			}
		}
		else if (token->str[0] == '$' && token->len > 1)
		{
			/* This is probably a $dumpvars, $comment or similar.
			 * $dump* contain useful data, but other tags will be skipped until $end. */
			if (g_strcmp0(token->str, "$dumpvars") == 0 ||
			    g_strcmp0(token->str, "$dumpon") == 0 ||
			    g_strcmp0(token->str, "$dumpoff") == 0 ||
			    g_strcmp0(token->str, "$end") == 0)
			{
				/* Ignore, parse contents as normally. */
			}
			else
			{
				/* Skip until $end */
				read_until(file, NULL, '$');
			}
		}
		else if (strchr("bBrR", token->str[0]) != NULL)
		{
			/* A vector value. Skip it and also the following identifier. */
			read_until(file, NULL, 'N');
			read_until(file, NULL, 'W');
		}
		else if (strchr("01xXzZ", token->str[0]) != NULL)
		{
			/* A new 1-bit sample value */
			int i, bit;
			GSList *l;
			struct probe *probe;

			bit = (token->str[0] == '1');
		
			g_string_erase(token, 0, 1);
			if (token->len == 0)
			{
				/* There was a space between value and identifier.
				 * Read in the rest.
				 */
				read_until(file, NULL, 'N');
				read_until(file, token, 'W');
			}
			
			for (i = 0, l = ctx->probes; i < ctx->probecount && l; i++, l = l->next)
			{
				probe = l->data;

				if (g_strcmp0(token->str, probe->identifier) == 0)
				{
					sr_dbg("Probe %d new value %d.", i, bit);
				
					/* Found our probe */
					if (bit)
						prev_values |= (1 << i);
					else
						prev_values &= ~(1 << i);
					
					break;
				}
			}
			
			if (i == ctx->probecount)
			{
				sr_dbg("Did not find probe for identifier '%s'.", token->str);
			}
		}
		else
		{
			sr_warn("Skipping unknown token '%s'.", token->str);
		}
		
		g_string_truncate(token, 0);
	}
	
	g_string_free(token, TRUE);
}
Пример #25
0
		void bdecode_recursive(InIt& in, InIt end, entry& ret, bool& err, int depth)
		{
			if (depth >= 100)
			{
				err = true;
				return;
			}

			if (in == end)
			{
				err = true;
#ifdef TORRENT_DEBUG
				ret.m_type_queried = false;
#endif
				return;
			}
			switch (*in)
			{

			// ----------------------------------------------
			// integer
			case 'i':
				{
				++in; // 'i'
				std::string val = read_until(in, end, 'e', err);
				if (err) return;
				TORRENT_ASSERT(*in == 'e');
				++in; // 'e'
				ret = entry(entry::int_t);
				char* end_pointer;
				ret.integer() = strtoll(val.c_str(), &end_pointer, 10);
#ifdef TORRENT_DEBUG
				ret.m_type_queried = false;
#endif
				if (end_pointer == val.c_str())
				{
					err = true;
					return;
				}
				} break;

			// ----------------------------------------------
			// list
			case 'l':
				{
				ret = entry(entry::list_t);
				++in; // 'l'
				while (*in != 'e')
				{
					ret.list().push_back(entry());
					entry& e = ret.list().back();
					bdecode_recursive(in, end, e, err, depth + 1);
					if (err)
					{
#ifdef TORRENT_DEBUG
						ret.m_type_queried = false;
#endif
						return;
					}
					if (in == end)
					{
						err = true;
#ifdef TORRENT_DEBUG
						ret.m_type_queried = false;
#endif
						return;
					}
				}
#ifdef TORRENT_DEBUG
				ret.m_type_queried = false;
#endif
				TORRENT_ASSERT(*in == 'e');
				++in; // 'e'
				} break;

			// ----------------------------------------------
			// dictionary
			case 'd':
				{
				ret = entry(entry::dictionary_t);
				++in; // 'd'
				while (*in != 'e')
				{
					entry key;
					bdecode_recursive(in, end, key, err, depth + 1);
					if (err || key.type() != entry::string_t)
					{
#ifdef TORRENT_DEBUG
						ret.m_type_queried = false;
#endif
						return;
					}
					entry& e = ret[key.string()];
					bdecode_recursive(in, end, e, err, depth + 1);
					if (err)
					{
#ifdef TORRENT_DEBUG
						ret.m_type_queried = false;
#endif
						return;
					}
					if (in == end)
					{
						err = true;
#ifdef TORRENT_DEBUG
						ret.m_type_queried = false;
#endif
						return;
					}
				}
#ifdef TORRENT_DEBUG
				ret.m_type_queried = false;
#endif
				TORRENT_ASSERT(*in == 'e');
				++in; // 'e'
				} break;

			// ----------------------------------------------
			// string
			default:
				if (is_digit(boost::uint8_t(*in)))
				{
					std::string len_s = read_until(in, end, ':', err);
					if (err)
					{
#ifdef TORRENT_DEBUG
						ret.m_type_queried = false;
#endif
						return;
					}
					TORRENT_ASSERT(*in == ':');
					++in; // ':'
					int len = atoi(len_s.c_str());
					ret = entry(entry::string_t);
					read_string(in, end, len, ret.string(), err);
					if (err)
					{
#ifdef TORRENT_DEBUG
						ret.m_type_queried = false;
#endif
						return;
					}
				}
				else
				{
					err = true;
#ifdef TORRENT_DEBUG
					ret.m_type_queried = false;
#endif
					return;
				}
#ifdef TORRENT_DEBUG
				ret.m_type_queried = false;
#endif
			}
		}
Пример #26
0
ssize_t
http_parse_response (int fd, Http_response **response_)
{
  Http_response *response;
  char *data;
  size_t len;
  ssize_t n;

  *response_ = NULL;

  response = malloc (sizeof (Http_response));
  if (response == NULL)
    {
      log_error ("http_parse_response: out of memory");
      return -1;
    }

  response->major_version = -1;
  response->minor_version = -1;
  response->status_code = -1;
  response->status_message = NULL;
  response->header = NULL;

  n = read_until (fd, '/', &data);
  if (n <= 0)
    {
      free (response);
      return n;
    }
  else if (n != 5 || memcmp (data, "HTTP", 4) != 0)
    {
      log_error ("http_parse_response: expected \"HTTP\"");
      free (data);
      free (response);
      return -1;
    }
  free (data);
  len = n;

  n = read_until (fd, '.', &data);
  if (n <= 0)
    {
      free (response);
      return n;
    }
  data[n - 1] = 0;
  response->major_version = atoi (data);
  log_verbose ("http_parse_response: major version = %d",
	       response->major_version);
  free (data);
  len += n;

  n = read_until (fd, ' ', &data);
  if (n <= 0)
    {
      free (response);
      return n;
    }
  data[n - 1] = 0;
  response->minor_version = atoi (data);
  log_verbose ("http_parse_response: minor version = %d",
	       response->minor_version);
  free (data);
  len += n;

  n = read_until (fd, ' ', &data);
  if (n <= 0)
    {
      free (response);
      return n;
    }
  data[n - 1] = 0;
  response->status_code = atoi (data);
  log_verbose ("http_parse_response: status code = %d",
	       response->status_code);
  free (data);
  len += n;

  n = read_until (fd, '\r', &data);
  if (n <= 0)
    {
      free (response);
      return n;
    }
  data[n - 1] = 0;
  response->status_message = data;
  log_verbose ("http_parse_response: status message = \"%s\"",
	       response->status_message);
  len += n;

  n = read_until (fd, '\n', &data);
  if (n <= 0)
    {
      http_destroy_response (response);
      return n;
    }
  free (data);
  if (n != 1)
    {
      log_error ("http_parse_request: invalid line ending");
      http_destroy_response (response);
      return -1;
    }
  len += n;

  n = parse_header (fd, &response->header);
  if (n <= 0)
    {
      http_destroy_response (response);
      return n;
    }
  len += n;

  *response_ = response;
  return len;
}
Пример #27
0
void do_config(void) {
    read_until(read_fd, pattern, sizeof(pattern), '\n');
}
Пример #28
0
int main(void) {
	users_t users[MAX_USERS];
	char buf[100];
	int done = 0;

//	BusyWork();

	// set a global pointer for easier function access
	USERS = users;

	// init some vars
	ADMIN_ACCESS = 0;
	CURRENT_USER = -1;
	NUM_USERS = 0;
	zero((char *)USERS, sizeof(users_t)*MAX_USERS);

	while (!done) {
		if (ADMIN_ACCESS) {
			zero(buf, 100);
			PrintAdminMenu();
			if (read_until(buf, '\n', 100) == -1) {
				_terminate(-1);
			}
			if (strlen(buf) > 1) {
				print("[-] Invalid choice\n");
				continue;
			}
			switch (buf[0]) {
				case '1':
					SendBroadcastMessage();
					break;

				case '2':
					ADMIN_ACCESS = 0;
					break;

				case '3':
					print("Exiting...\n");
					done = 1;
					break;

				default:
					continue;
			}
		} else if (CURRENT_USER == -1) {
			zero(buf, 100);
			PrintLoggedOutMenu();
			if (read_until(buf, '\n', 100) == -1) {
				_terminate(-1);
			}
			if (strlen(buf) > 1) {
				print("[-] Invalid choice\n");
				continue;
			}
			switch (buf[0]) {
				case '1':
					CreateUser();
					break;
				case '2':
					Login();
					break;
				case '3':
					print("Exiting...\n");
					_terminate(0);
					break;
				default:
					print("[-] Invalid choice\n");
					continue;
			}
		} else {
			zero(buf, 100);
			PrintNewMessages();
			PrintLoggedInMenu();
			if (read_until(buf, '\n', 100) == -1) {
				_terminate(-1);
			}
			if (strlen(buf) > 1) {
				print("[-] Invalid choice\n");
				continue;
			}
			switch (buf[0]) {
				case '1':
					SendMessage();
					break;
				case '2':
					ReadMessage();
					break;
				case '3':
					ListMessages();
					break;
				case '4':
					DeleteMessage();
					break;
				case '5':
					CURRENT_USER = -1;
					print("Logging out...\n");
					break;
				case '6':
					print("Exiting...\n");
					_terminate(0);
					break;
				case 'a':
					AdminLogin();
					break;
				default:
					print("[-] Invalid choice\n");
					continue;
			}
		}
	}

	return(0);
}
Пример #29
0
	boost::tuple<int, int> http_parser::incoming(
		buffer::const_interval recv_buffer, bool& error)
	{
		TORRENT_ASSERT(recv_buffer.left() >= m_recv_buffer.left());
		boost::tuple<int, int> ret(0, 0);
		int start_pos = m_recv_buffer.left();

		// early exit if there's nothing new in the receive buffer
		if (start_pos == recv_buffer.left()) return ret;
		m_recv_buffer = recv_buffer;

		if (m_state == error_state)
		{
			error = true;
			return ret;
		}

		char const* pos = recv_buffer.begin + m_recv_pos;

restart_response:

		if (m_state == read_status)
		{
			TORRENT_ASSERT(!m_finished);
			char const* newline = std::find(pos, recv_buffer.end, '\n');
			// if we don't have a full line yet, wait.
			if (newline == recv_buffer.end)
			{
				boost::get<1>(ret) += m_recv_buffer.left() - start_pos;
				return ret;
			}

			if (newline == pos)
			{
				m_state = error_state;
				error = true;
				return ret;
			}

			char const* line_end = newline;
			if (pos != line_end && *(line_end - 1) == '\r') --line_end;

			char const* line = pos;
			++newline;
			int incoming = int(newline - pos);
			m_recv_pos += incoming;
			boost::get<1>(ret) += newline - (m_recv_buffer.begin + start_pos);
			pos = newline;

			m_protocol = read_until(line, ' ', line_end);
			if (m_protocol.substr(0, 5) == "HTTP/")
			{
				m_status_code = atoi(read_until(line, ' ', line_end).c_str());
				m_server_message = read_until(line, '\r', line_end);
			}
			else
			{
				m_method = m_protocol;
				std::transform(m_method.begin(), m_method.end(), m_method.begin(), &to_lower);
				// the content length is assumed to be 0 for requests
				m_content_length = 0;
				m_protocol.clear();
				m_path = read_until(line, ' ', line_end);
				m_protocol = read_until(line, ' ', line_end);
				m_status_code = 0;
			}
			m_state = read_header;
			start_pos = pos - recv_buffer.begin;
		}

		if (m_state == read_header)
		{
			TORRENT_ASSERT(!m_finished);
			char const* newline = std::find(pos, recv_buffer.end, '\n');
			std::string line;

			while (newline != recv_buffer.end && m_state == read_header)
			{
				// if the LF character is preceeded by a CR
				// charachter, don't copy it into the line string.
				char const* line_end = newline;
				if (pos != line_end && *(line_end - 1) == '\r') --line_end;
				line.assign(pos, line_end);
				++newline;
				m_recv_pos += newline - pos;
				pos = newline;

				std::string::size_type separator = line.find(':');
				if (separator == std::string::npos)
				{
					if (m_status_code == 100)
					{
						// for 100 Continue, we need to read another response header
						// before reading the body
						m_state = read_status;
						goto restart_response;
					}
					// this means we got a blank line,
					// the header is finished and the body
					// starts.
					m_state = read_body;
					// if this is a request (not a response)
					// we're done once we reach the end of the headers
//					if (!m_method.empty()) m_finished = true;
					// the HTTP header should always be < 2 GB
					TORRENT_ASSERT(m_recv_pos < INT_MAX);
					m_body_start_pos = int(m_recv_pos);
					break;
				}

				std::string name = line.substr(0, separator);
				std::transform(name.begin(), name.end(), name.begin(), &to_lower);
				++separator;
				// skip whitespace
				while (separator < line.size()
					&& (line[separator] == ' ' || line[separator] == '\t'))
					++separator;
				std::string value = line.substr(separator, std::string::npos);
				m_header.insert(std::make_pair(name, value));

				if (name == "content-length")
				{
					m_content_length = strtoll(value.c_str(), 0, 10);
				}
				else if (name == "content-range")
				{
					bool success = true;
					char const* ptr = value.c_str();

					// apparently some web servers do not send the "bytes"
					// in their content-range. Don't treat it as an error
					// if we can't find it, just assume the byte counters
					// start immediately
					if (string_begins_no_case("bytes ", ptr)) ptr += 6;
					char* end;
					m_range_start = strtoll(ptr, &end, 10);
					if (end == ptr) success = false;
					else if (*end != '-') success = false;
					else
					{
						ptr = end + 1;
						m_range_end = strtoll(ptr, &end, 10);
						if (end == ptr) success = false;
					}

					if (!success || m_range_end < m_range_start)
					{
						m_state = error_state;
						error = true;
						return ret;
					}
					// the http range is inclusive
					m_content_length = m_range_end - m_range_start + 1;
				}
				else if (name == "transfer-encoding")
				{
					m_chunked_encoding = string_begins_no_case("chunked", value.c_str());
				}

				TORRENT_ASSERT(m_recv_pos <= recv_buffer.left());
				newline = std::find(pos, recv_buffer.end, '\n');
			}
			boost::get<1>(ret) += newline - (m_recv_buffer.begin + start_pos);
		}

		if (m_state == read_body)
		{
			int incoming = recv_buffer.end - pos;

			if (m_chunked_encoding && (m_flags & dont_parse_chunks) == 0)
			{
				if (m_cur_chunk_end == -1)
					m_cur_chunk_end = m_body_start_pos;

				while (m_cur_chunk_end <= m_recv_pos + incoming && !m_finished && incoming > 0)
				{
					size_type payload = m_cur_chunk_end - m_recv_pos;
					if (payload > 0)
					{
						TORRENT_ASSERT(payload < INT_MAX);
						m_recv_pos += payload;
						boost::get<0>(ret) += int(payload);
						incoming -= int(payload);
					}
					buffer::const_interval buf(recv_buffer.begin + m_cur_chunk_end, recv_buffer.end);
					size_type chunk_size;
					int header_size;
					if (parse_chunk_header(buf, &chunk_size, &header_size))
					{
						if (chunk_size > 0)
						{
							std::pair<size_type, size_type> chunk_range(m_cur_chunk_end + header_size
								, m_cur_chunk_end + header_size + chunk_size);
							m_chunked_ranges.push_back(chunk_range);
						}
						m_cur_chunk_end += header_size + chunk_size;
						if (chunk_size == 0)
						{
							m_finished = true;
							TORRENT_ASSERT(m_content_length < 0 || m_recv_pos - m_body_start_pos
								- m_chunk_header_size == m_content_length);
						}
						header_size -= m_partial_chunk_header;
						m_partial_chunk_header = 0;
//						fprintf(stderr, "parse_chunk_header(%d, -> %d, -> %d) -> %d\n"
//							"  incoming = %d\n  m_recv_pos = %d\n  m_cur_chunk_end = %d\n"
//							"  content-length = %d\n"
//							, buf.left(), int(chunk_size), header_size, 1, incoming, int(m_recv_pos)
//							, m_cur_chunk_end, int(m_content_length));
					}
					else
					{
						m_partial_chunk_header += incoming;
						header_size = incoming;
						
//						fprintf(stderr, "parse_chunk_header(%d, -> %d, -> %d) -> %d\n"
//							"  incoming = %d\n  m_recv_pos = %d\n  m_cur_chunk_end = %d\n"
//							"  content-length = %d\n"
//							, buf.left(), int(chunk_size), header_size, 0, incoming, int(m_recv_pos)
//							, m_cur_chunk_end, int(m_content_length));
					}
					m_chunk_header_size += header_size;
					m_recv_pos += header_size;
					boost::get<1>(ret) += header_size;
					incoming -= header_size;
				}
				if (incoming > 0)
				{
					m_recv_pos += incoming;
					boost::get<0>(ret) += incoming;
//					incoming = 0;
				}
			}
			else
			{
				size_type payload_received = m_recv_pos - m_body_start_pos + incoming;
				if (payload_received > m_content_length
					&& m_content_length >= 0)
				{
					TORRENT_ASSERT(m_content_length - m_recv_pos + m_body_start_pos < INT_MAX);
					incoming = int(m_content_length - m_recv_pos + m_body_start_pos);
				}

				TORRENT_ASSERT(incoming >= 0);
				m_recv_pos += incoming;
				boost::get<0>(ret) += incoming;
			}

			if (m_content_length >= 0
				&& !m_chunked_encoding
				&& m_recv_pos - m_body_start_pos >= m_content_length)
			{
				m_finished = true;
			}
		}
		return ret;
	}
Пример #30
0
static struct ebt_mac_wormhash *create_wormhash(const char *arg)
{
	const char *pc = arg;
	const char *anchor;
	char *endptr;
	struct ebt_mac_wormhash *workcopy, *result, *h;
	unsigned char mac[6];
	unsigned char ip[4];
	int nmacs = 0;
	int i;
	char token[4];

	if (!(workcopy = new_wormhash(1024))) {
		ebt_print_memory();
	}
	while (1) {
		/* remember current position, we'll need it on error */
		anchor = pc;

		/* collect MAC; all its bytes are followed by ':' (colon),
		 * except for the last one which can be followed by 
		 * ',' (comma), '=' or '\0' */
		for (i = 0; i < 5; i++) {
			if (read_until(&pc, ":", token, 2) < 0
			    || token[0] == 0) {
				ebt_print_error("MAC parse error: %.20s", anchor);
				return NULL;
			}
			mac[i] = strtol(token, &endptr, 16);
			if (*endptr) {
				ebt_print_error("MAC parse error: %.20s", anchor);
				return NULL;
			}
			pc++;
		}
		if (read_until(&pc, "=,", token, 2) == -2 || token[0] == 0) {
			ebt_print_error("MAC parse error: %.20s", anchor);
			return NULL;
		}
		mac[i] = strtol(token, &endptr, 16);
		if (*endptr) {
			ebt_print_error("MAC parse error: %.20s", anchor);
			return NULL;
		}
		if (*pc == '=') {
			/* an IP follows the MAC; collect similarly to MAC */
			pc++;
			anchor = pc;
			for (i = 0; i < 3; i++) {
				if (read_until(&pc, ".", token, 3) < 0 || token[0] == 0) {
					ebt_print_error("IP parse error: %.20s", anchor);
					return NULL;
				}
				ip[i] = strtol(token, &endptr, 10);
				if (*endptr) {
					ebt_print_error("IP parse error: %.20s", anchor);
					return NULL;
				}
				pc++;
			}
			if (read_until(&pc, ",", token, 3) == -2 || token[0] == 0) {
				ebt_print_error("IP parse error: %.20s", anchor);
				return NULL;
			}
			ip[3] = strtol(token, &endptr, 10);
			if (*endptr) {
				ebt_print_error("IP parse error: %.20s", anchor);
				return NULL;
			}
			if (*(uint32_t*)ip == 0) {
				ebt_print_error("Illegal IP 0.0.0.0");
				return NULL;
			}
		} else {
			/* no IP, we set it to 0.0.0.0 */
			memset(ip, 0, 4);
		}

		/* we have collected MAC and IP, so we add an entry */
		memcpy(((char *) workcopy->pool[nmacs].cmp) + 2, mac, 6);
		workcopy->pool[nmacs].ip = *(const uint32_t *) ip;
		nmacs++;

		/* re-allocate memory if needed */
		if (*pc && nmacs >= workcopy->poolsize) {
			if (!(h = new_wormhash(nmacs * 2))) {
				ebt_print_memory();
			}
			copy_wormhash(h, workcopy);
			free(workcopy);
			workcopy = h;
		}

		/* check if end of string was reached */
		if (!*pc) {
			break;
		}

		/* now `pc' points to comma if we are here; */
		/* increment this to the next char */
		/* but first assert :-> */
		if (*pc != ',') {
			ebt_print_error("Something went wrong; no comma...\n");
			return NULL;
		}
		pc++;

		/* again check if end of string was reached; */
		/* we allow an ending comma */
		if (!*pc) {
			break;
		}
	}
	if (!(result = new_wormhash(nmacs))) {
		ebt_print_memory();
	}
	copy_wormhash(result, workcopy);
	free(workcopy);
	qsort(&result->pool, result->poolsize,
			sizeof(struct ebt_mac_wormhash_tuple), fcmp);
	index_table(result);
	return result;
}