Logo Search packages:      
Sourcecode: parser version File versions  Download package

File_read_http_result pa_internal_file_read_http ( Request_charsets &  charsets,
const String file_spec,
bool  as_text,
HashStringValue options,
bool  transcode_text_result 
)

Todo:
build .cookies field. use ^file.tables.SET-COOKIES.menu{ for now

Definition at line 396 of file pa_http.C.

References String::append(), Value::as_string(), String::change_case(), Array< T >::count(), Hash< K, V >::count(), String::cstr(), Array< T >::get(), Hash< K, V >::get(), Value::get_hash(), Value::get_table(), VHash::hash(), Value::is_string(), String::L_UNSPECIFIED, String::L_URI, String::length(), MAX_STRING, String::mid(), Charset::NAME_CSTR(), pa_get_valid_file_options_count(), String::pos(), Hash< K, V >::put(), String::split(), and STRING_NOT_FOUND.

                                                                {
      File_read_http_result result;
      char host[MAX_STRING]; 
      const char* uri; 
      short port;
      const char* method="GET";
      HashStringValue* form=0;
      const char* body_cstr=0;
      int timeout_secs=2;
      bool fail_on_status_ne_200=true;
      bool omit_post_charset=false;
      Value* vheaders=0;
      Value* vcookies=0;
      Value* vbody=0;
      Charset *asked_remote_charset=0;
      const char* user_cstr=0;
      const char* password_cstr=0;

      if(options) {
            int valid_options=pa_get_valid_file_options_count(*options);

            if(Value* vmethod=options->get(HTTP_METHOD_NAME)) {
                  valid_options++;
                  method=vmethod->as_string().cstr();
            }
            if(Value* vform=options->get(HTTP_FORM_NAME)) {
                  valid_options++;
                  form=vform->get_hash(); 
            } 
            if(vbody=options->get(HTTP_BODY_NAME)) {
                  valid_options++;
            } 
            if(Value* vtimeout=options->get(HTTP_TIMEOUT_NAME)) {
                  valid_options++;
                  timeout_secs=vtimeout->as_int(); 
            } 
            if(vheaders=options->get(HTTP_HEADERS_NAME)) {
                  valid_options++;
            } 
            if(vcookies=options->get(HTTP_COOKIES_NAME)) {
                  valid_options++;
            } 
            if(Value* vany_status=options->get(HTTP_ANY_STATUS_NAME)) {
                  valid_options++;
                  fail_on_status_ne_200=!vany_status->as_bool(); 
            }
            if(Value* vomit_post_charset=options->get(HTTP_OMIT_POST_CHARSET)){
                  valid_options++;
                  omit_post_charset=vomit_post_charset->as_bool();
            }
            if(Value* vcharset_name=options->get(PA_CHARSET_NAME)) {
                  asked_remote_charset=&::charsets.get(vcharset_name->as_string().
                        change_case(charsets.source(), String::CC_UPPER));
            } 
            if(Value* vuser=options->get(HTTP_USER)) {
                  valid_options++;
                  user_cstr=vuser->as_string().cstr();
            } 
            if(Value* vpassword=options->get(HTTP_PASSWORD)) {
                  valid_options++;
                  password_cstr=vpassword->as_string().cstr();
            }

            if(valid_options!=options->count())
                  throw Exception(PARSER_RUNTIME,
                        0,
                        "invalid option passed");
      }
      if(!asked_remote_charset) // defaulting to $request:charset
            asked_remote_charset=&charsets.source();

      bool method_is_get=strcmp(method, "GET")==0;
      if(vbody){
            if(method_is_get)
                  throw Exception(PARSER_RUNTIME,
                        0,
                        "you can not use $."HTTP_BODY_NAME" option with method GET");

            if(form)
                  throw Exception(PARSER_RUNTIME,
                        0,
                        "you can not use options $."HTTP_BODY_NAME" and $."HTTP_FORM_NAME" together");
      }

      //preparing request
      String& connect_string=*new String;
      // not in ^sql{... L_SQL ...} spirit, but closer to ^file::load one
      connect_string.append(file_spec, String::L_URI); // tainted pieces -> URI pieces

      String request_head_and_body;
      {
            // influence URLencoding of tainted pieces to String::L_URI lang
            Temp_client_charset temp(charsets, *asked_remote_charset);

            const char* connect_string_cstr=connect_string.cstr(String::L_UNSPECIFIED, 0, &charsets); 

            const char* current=connect_string_cstr;
            if(strncmp(current, "http://", 7)!=0)
                  throw Exception(PARSER_RUNTIME, 
                        &connect_string, 
                        "does not start with http://"); //never
            current+=7;

            strncpy(host, current, sizeof(host)-1);  host[sizeof(host)-1]=0;
            char* host_uri=lsplit(host, '/'); 
            uri=host_uri?current+(host_uri-1-host):"/"; 
            char* port_cstr=lsplit(host, ':'); 
            char* error_pos=0;
            port=port_cstr?(short)strtol(port_cstr, &error_pos, 0):80;

            bool uri_has_query_string=strchr(uri, '?')!=0;

            // making request head
            String head;
            head << method << " " << uri;
            if(form && method_is_get)
                  head << (uri_has_query_string?"&":"?") << pa_form2string(*form, charsets);

            head <<" HTTP/1.0" CRLF "host: "<< host << CRLF;

            if(form && !method_is_get) { // POST
                  head << "content-type: " << HTTP_CONTENT_TYPE_FORM_URLENCODED;
                  if(!omit_post_charset)
                        head << "; charset=" << asked_remote_charset->NAME_CSTR() << ";";
                  head << CRLF;
                  body_cstr=pa_form2string(*form, charsets);
            }  else if (vbody) {
                  body_cstr=vbody->as_string().cstr(String::L_UNSPECIFIED, 0, &charsets);
                  // needed for transcoded $.body[] first of all
                  body_cstr=Charset::transcode(
                        String::C(body_cstr, strlen(body_cstr)),
                        charsets.source(),
                        *asked_remote_charset
                  );
            }

            // http://www.ietf.org/rfc/rfc2617.txt
            if(const String* authorization_field_value=basic_authorization_field(user_cstr, password_cstr))
                  head<<"authorization: "<<*authorization_field_value<<CRLF;

            bool user_agent_specified=false;
            bool content_type_specified=false;
            if(vheaders && !vheaders->is_string()) { // allow empty
                  if(HashStringValue *headers=vheaders->get_hash()) {
                        Http_pass_header_info info={&charsets, &head, false};
                        headers->for_each<Http_pass_header_info*>(http_pass_header, &info); 
                        user_agent_specified=info.user_agent_specified;
                        content_type_specified=info.content_type_specified;
                  } else
                        throw Exception(PARSER_RUNTIME, 
                              &connect_string,
                              "headers param must be hash"); 
            };
            if(!user_agent_specified) // defaulting
                  head << "user-agent: " DEFAULT_USER_AGENT CRLF;

            if(form && !method_is_get && content_type_specified) // POST + form + content-type was specified
                  throw Exception(PARSER_RUNTIME,
                        &connect_string,
                        "$.content-type can't be specified with method POST"); 

            if(vcookies && !vcookies->is_string()){ // allow empty
                  if(HashStringValue* cookies=vcookies->get_hash()) {
                        head << "cookie: ";
                        Http_pass_header_info info={&charsets, &head, false};
                        cookies->for_each<Http_pass_header_info*>(http_pass_cookie, &info); 
                        head << CRLF;
                  } else
                        throw Exception(PARSER_RUNTIME, 
                              &connect_string,
                              "cookies param must be hash"); 
            }

            if(body_cstr) {
                  head << "content-length: " << format(strlen(body_cstr), "%u") << CRLF;
            }

            const char* head_cstr=head.cstr(String::L_UNSPECIFIED, 0, &charsets);

            // head + end of header
            request_head_and_body << head_cstr << CRLF;

            // body
            if(body_cstr)
                  request_head_and_body << body_cstr;
      }
      
      //sending request
      char* response;
      size_t response_size;
      int status_code=http_request(response, response_size,
            host, port, request_head_and_body.cstr(), 
            timeout_secs, fail_on_status_ne_200); 
      
      //processing results    
      char* raw_body; size_t raw_body_size;
      char* headers_end_at;
      find_headers_end(response, 
            headers_end_at,
            raw_body);
      raw_body_size=response_size-(raw_body-response);
      
      result.headers=new HashStringValue;
      VHash* vtables=new VHash;
      result.headers->put(HTTP_TABLES_NAME, vtables);
      Charset* real_remote_charset=0; // undetected, yet

      if(headers_end_at) {
            *headers_end_at=0;
            const String header_block(String::C(response, headers_end_at-response), true);
            
            ArrayString aheaders;
            HashStringValue& tables=vtables->hash();

            size_t pos_after=0;
            header_block.split(aheaders, pos_after, "\n"); 
            
            //processing headers
            size_t aheaders_count=aheaders.count();
            for(size_t i=1; i<aheaders_count; i++) {
                  const String& line=*aheaders.get(i);
                  size_t pos=line.pos(':'); 
                  if(pos==STRING_NOT_FOUND || pos<1)
                        throw Exception("http.response", 
                              &connect_string,
                              "bad response from host - bad header \"%s\"", line.cstr());
                  const String::Body HEADER_NAME=line.mid(0, pos).change_case(charsets.source(), String::CC_UPPER);
                  const String& HEADER_VALUE=line.mid(pos+1, line.length()).trim(String::TRIM_BOTH, " \t\r");
                  if(as_text && HEADER_NAME==HTTP_CONTENT_TYPE)
                        real_remote_charset=detect_charset(charsets.source(), HEADER_VALUE);

                  // tables
                  {
                        Value *valready=(Value *)tables.get(HEADER_NAME);
                        bool existed=valready!=0;
                        Table *table;
                        if(existed) {
                              // second+ appearence
                              table=valready->get_table();
                        } else {
                              // first appearence
                              Table::columns_type columns=new ArrayString(1);
                              *columns+=new String("value");
                              table=new Table(columns);
                        }
                        // this string becomes next row
                        ArrayString& row=*new ArrayString(1);
                        row+=&HEADER_VALUE;
                        *table+=&row;
                        // not existed before? add it
                        if(!existed)
                              tables.put(HEADER_NAME, new VTable(table));
                  }

                  result.headers->put(HEADER_NAME, new VString(HEADER_VALUE));
            }
      }

      if(as_text && raw_body_size>=3 && strncmp(raw_body, "\xEF\xBB\xBF", 3)==0){
            // skip UTF-8 signature: EF BB BF  (BOM code)
            raw_body+=3;
            raw_body_size-=3;
      }

      // output response
      String::C real_body=String::C(raw_body, raw_body_size);

      if(as_text && transcode_text_result && raw_body_size) { // raw_body_size must be checked because transcode returns CONST string in case length==0, which contradicts hacking few lines below
            // defaulting to used-asked charset [it's never empty!]
            if(!real_remote_charset)
                  real_remote_charset=asked_remote_charset;

            real_body=Charset::transcode(real_body, *real_remote_charset, charsets.source());

      }

      result.str=const_cast<char *>(real_body.str); // hacking a little
      result.length=real_body.length;

      result.headers->put(file_status_name, new VInt(status_code));

      return result;
}


Generated by  Doxygen 1.6.0   Back to index