Skip to content
Snippets Groups Projects
http.c 52.1 KiB
Newer Older
  • Learn to ignore specific revisions
  •     conn->bytecount = http->readbytecount + http->writebytecount;
    
      if(0 == (http->readbytecount + conn->headerbytecount)) {
        /* nothing was read from the HTTP server, this can't be right
           so we return an error here */
    
        failf(data, "Empty reply from server");
    
    void Curl_http_auth_stage(struct SessionHandle *data,
                              int stage)
    {
      if(stage == 401)
        data->state.authwant = data->set.httpauth;
      else if(stage == 407)
        data->state.authwant = data->set.proxyauth;
      else
        return; /* bad input stage */
      data->state.authstage = stage;
      data->state.authavail = CURLAUTH_NONE;
    }
    
    
    CURLcode Curl_http(struct connectdata *conn)
    
      struct SessionHandle *data=conn->data;
      char *buf = data->state.buffer; /* this is a short cut to the buffer */
    
      CURLcode result=CURLE_OK;
    
      struct HTTP *http;
      struct Cookie *co=NULL; /* no cookies from start */
      char *ppath = conn->ppath; /* three previous function arguments */
      char *host = conn->name;
    
      const char *te = ""; /* tranfer-encoding */
    
    Daniel Stenberg's avatar
    Daniel Stenberg committed
      char *request;
    
      bool authdone=TRUE; /* if the authentication phase is done */
      Curl_HttpReq httpreq;  /* type of HTTP request */
    
      if(!conn->proto.http) {
        /* Only allocate this struct if we don't already have it! */
    
        http = (struct HTTP *)malloc(sizeof(struct HTTP));
        if(!http)
          return CURLE_OUT_OF_MEMORY;
        memset(http, 0, sizeof(struct HTTP));
        conn->proto.http = http;
      }
    
      else
        http = conn->proto.http;
    
      /* We default to persistant connections */
      conn->bits.close = FALSE;
    
    
      if ( (conn->protocol&(PROT_HTTP|PROT_FTP)) &&
    
           data->set.upload) {
        data->set.httpreq = HTTPREQ_PUT;
    
    Daniel Stenberg's avatar
    Daniel Stenberg committed
      }
    
    Daniel Stenberg's avatar
    Daniel Stenberg committed
      request = data->set.customrequest?
        data->set.customrequest:
        (data->set.no_body?(char *)"HEAD":
    
         ((HTTPREQ_POST == data->set.httpreq) ||
    
    Daniel Stenberg's avatar
    Daniel Stenberg committed
          (HTTPREQ_POST_FORM == data->set.httpreq))?(char *)"POST":
         (HTTPREQ_PUT == data->set.httpreq)?(char *)"PUT":(char *)"GET");
    
    Daniel Stenberg's avatar
    Daniel Stenberg committed
      
      /* The User-Agent string has been built in url.c already, because it might
         have been used in the proxy connect, but if we have got a header with
    
         the user-agent string specified, we erase the previously made string
    
    Daniel Stenberg's avatar
    Daniel Stenberg committed
         here. */
    
      if(checkheaders(data, "User-Agent:") && conn->allocptr.uagent) {
        free(conn->allocptr.uagent);
        conn->allocptr.uagent=NULL;
    
      /* setup the authentication headers */
    
      result = http_auth_headers(conn, request, ppath, &authdone);
    
      Curl_safefree(conn->allocptr.ref);
      if(data->change.referer && !checkheaders(data, "Referer:"))
    
        conn->allocptr.ref = aprintf("Referer: %s\015\012", data->change.referer);
    
      else
        conn->allocptr.ref = NULL;
    
      Curl_safefree(conn->allocptr.cookie);
      if(data->set.cookie && !checkheaders(data, "Cookie:"))
    
        conn->allocptr.cookie = aprintf("Cookie: %s\015\012", data->set.cookie);
    
    Daniel Stenberg's avatar
    Daniel Stenberg committed
    
    
      if(!conn->bits.upload_chunky && (data->set.httpreq != HTTPREQ_GET)) {
        /* not a chunky transfer but data is to be sent */
    
        ptr = checkheaders(data, "Transfer-Encoding:");
    
        if(ptr) {
          /* Some kind of TE is requested, check if 'chunked' is chosen */
          if(Curl_compareheader(ptr, "Transfer-Encoding:", "chunked"))
            /* we have been told explicitly to upload chunky so deal with it! */
            conn->bits.upload_chunky = TRUE;
        }
      }
    
    
        /* RFC2616 section 4.4:
           Messages MUST NOT include both a Content-Length header field and a
           non-identity transfer-coding. If the message does include a non-
           identity transfer-coding, the Content-Length MUST be ignored. */
    
    
        if(!checkheaders(data, "Transfer-Encoding:")) {
          te = "Transfer-Encoding: chunked\r\n";
        }
    
        else {
          /* The "Transfer-Encoding:" header was already added. */
          te = "";
        }
    
      ptr = checkheaders(data, "Host:");
      if(ptr) {
        /* If we have a given custom Host: header, we extract the host name
           in order to possibly use it for cookie reasons later on. */
        char *start = ptr+strlen("Host:");
        while(*start && isspace((int)*start ))
          start++;
        ptr = start; /* start host-scanning here */
    
    
        /* scan through the string to find the end (space or colon) */
        while(*ptr && !isspace((int)*ptr) && !(':'==*ptr))
    
          ptr++;
        
        if(ptr != start) {
          int len=ptr-start;
          conn->allocptr.cookiehost = malloc(len+1);
          if(!conn->allocptr.cookiehost)
            return CURLE_OUT_OF_MEMORY;
          memcpy(conn->allocptr.cookiehost, start, len);
          conn->allocptr.cookiehost[len]=0;
        }
      }    
      else {
    
        /* if ptr_host is already set, it is almost OK since we only re-use
           connections to the very same host and port, but when we use a HTTP
           proxy we have a persistant connect and yet we must change the Host:
           header! */
    
        if(conn->allocptr.host)
          free(conn->allocptr.host);
    
        /* When building Host: headers, we must put the host name within
           [brackets] if the host name is a plain IPv6-address. RFC2732-style. */
           
    
        if(((conn->protocol&PROT_HTTPS) && (conn->remote_port == PORT_HTTPS)) ||
           (!(conn->protocol&PROT_HTTPS) && (conn->remote_port == PORT_HTTP)) )
    
          /* If (HTTPS on port 443) OR (non-HTTPS on port 80) then don't include
             the port number in the host string */
    
          conn->allocptr.host = aprintf("Host: %s%s%s\r\n",
                                        conn->bits.ipv6_ip?"[":"",
                                        host,
                                        conn->bits.ipv6_ip?"]":"");
    
          conn->allocptr.host = aprintf("Host: %s%s%s:%d\r\n",
                                        conn->bits.ipv6_ip?"[":"",
                                        host,
                                        conn->bits.ipv6_ip?"]":"",
    
    
        if(!conn->allocptr.host)
          /* without Host: we can't make a nice request */
          return CURLE_OUT_OF_MEMORY;
    
    Daniel Stenberg's avatar
    Daniel Stenberg committed
    
    
        Curl_share_lock(data, CURL_LOCK_DATA_COOKIE, CURL_LOCK_ACCESS_SINGLE);
    
        co = Curl_cookie_getlist(data->cookies,
                                 conn->allocptr.cookiehost?
                                 conn->allocptr.cookiehost:host, ppath,
                                 (bool)(conn->protocol&PROT_HTTPS?TRUE:FALSE));
    
        Curl_share_unlock(data, CURL_LOCK_DATA_COOKIE);
    
          !data->set.tunnel_thru_httpproxy &&
          !(conn->protocol&PROT_HTTPS))  {
        /* The path sent to the proxy is in fact the entire URL */
        ppath = data->change.url;
      }
      if(HTTPREQ_POST_FORM == data->set.httpreq) {
        /* we must build the whole darned post sequence first, so that we have
           a size of the whole shebang before we start to send it */
         result = Curl_getFormData(&http->sendit, data->set.httppost,
                                   &http->postsize);
         if(CURLE_OK != result) {
           /* Curl_getFormData() doesn't use failf() */
           failf(data, "failed creating formpost data");
           return result;
         }
      }
    
    
    
    Daniel Stenberg's avatar
    Daniel Stenberg committed
      if(!checkheaders(data, "Pragma:"))
    
        http->p_pragma = "Pragma: no-cache\r\n";
    
    Daniel Stenberg's avatar
    Daniel Stenberg committed
    
      if(!checkheaders(data, "Accept:"))
    
        http->p_accept = "Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, */*\r\n";
    
    Daniel Stenberg's avatar
    Daniel Stenberg committed
    
    
      if(( (HTTPREQ_POST == data->set.httpreq) ||
           (HTTPREQ_POST_FORM == data->set.httpreq) ||
           (HTTPREQ_PUT == data->set.httpreq) ) &&
    
        /**********************************************************************
         * Resuming upload in HTTP means that we PUT or POST and that we have
         * got a resume_from value set. The resume value has already created
         * a Range: header that will be passed along. We need to "fast forward"
         * the file the given number of bytes and decrease the assume upload
         * file size before we continue this venture in the dark lands of HTTP.
         *********************************************************************/
       
    
          /*
           * This is meant to get the size of the present remote-file by itself.
           * We don't support this now. Bail out!
           */
    
          /* do we still game? */
    
          off_t passed=0;
    
    
          /* Now, let's read off the proper amount of bytes from the
             input. If we knew it was a proper file we could've just
             fseek()ed but we only have a stream here */
          do {
    
            off_t readthisamountnow = (conn->resume_from - passed);
            off_t actuallyread;
    
    
            if(readthisamountnow > BUFSIZE)
              readthisamountnow = BUFSIZE;
    
            actuallyread =
    
              data->set.fread(data->state.buffer, 1, (size_t)readthisamountnow,
    
    
            passed += actuallyread;
            if(actuallyread != readthisamountnow) {
    
              failf(data, "Could only read %Od bytes from the input",
    
                    passed);
              return CURLE_READ_ERROR;
            }
    
          } while(passed != conn->resume_from); /* loop until done */
    
    
          /* now, decrease the size of the read */
    
          if(data->set.infilesize>0) {
            data->set.infilesize -= conn->resume_from;
    
              failf(data, "File already completely uploaded");
    
              return CURLE_PARTIAL_FILE;
            }
          }
          /* we've passed, proceed as normal */
        }
      }
    
        /*
         * A range is selected. We use different headers whether we're downloading
         * or uploading and we always let customized headers override our internal
         * ones if any such are specified.
         */
    
        if((data->set.httpreq == HTTPREQ_GET) &&
    
          /* if a line like this was already allocated, free the previous one */
          if(conn->allocptr.rangeline)
            free(conn->allocptr.rangeline);
    
          conn->allocptr.rangeline = aprintf("Range: bytes=%s\r\n", conn->range);
    
        else if((data->set.httpreq != HTTPREQ_GET) &&
    
            /* This is because "resume" was selected */
    
            off_t total_expected_size= conn->resume_from + data->set.infilesize;
            conn->allocptr.rangeline =
    	    aprintf("Content-Range: bytes %s%Od/%Od\r\n",
    		    conn->range, total_expected_size-1,
    		    total_expected_size);
    
          }
          else {
            /* Range was selected and then we just pass the incoming range and 
               append total size */
    
            conn->allocptr.rangeline =
    	    aprintf("Content-Range: bytes %s/%Od\r\n",
    		    conn->range, data->set.infilesize);
    
        /* Use 1.1 unless the use specificly asked for 1.0 */
        const char *httpstring=
          data->set.httpversion==CURL_HTTP_VERSION_1_0?"1.0":"1.1";
    
    
        struct curl_slist *headers=data->set.headers;
    
    
        /* initialize a dynamic send-buffer */
        req_buffer = add_buffer_init();
    
    
        result =
          add_bufferf(req_buffer,
                      "%s " /* GET/HEAD/POST/PUT */
                      "%s HTTP/%s\r\n" /* path + HTTP version */
                      "%s" /* proxyuserpwd */
                      "%s" /* userpwd */
                      "%s" /* range */
                      "%s" /* user agent */
                      "%s" /* cookie */
                      "%s" /* host */
                      "%s" /* pragma */
                      "%s" /* accept */
                      "%s" /* accept-encoding */
                      "%s" /* referer */
                      "%s",/* transfer-encoding */
    
                    (conn->bits.httpproxy && conn->allocptr.proxyuserpwd)?
                    conn->allocptr.proxyuserpwd:"",
    
                    conn->allocptr.userpwd?conn->allocptr.userpwd:"",
    
                    (conn->bits.use_range && conn->allocptr.rangeline)?
    
                    (data->set.useragent && *data->set.useragent && conn->allocptr.uagent)?
    
                    (conn->allocptr.cookie?conn->allocptr.cookie:""), /* Cookie: <data> */
                    (conn->allocptr.host?conn->allocptr.host:""), /* Host: host */
    
                    http->p_pragma?http->p_pragma:"",
                    http->p_accept?http->p_accept:"",
    
                    (data->set.encoding && *data->set.encoding && conn->allocptr.accept_encoding)?
                    conn->allocptr.accept_encoding:"", /* 08/28/02 jhrg */
    
                    (data->change.referer && conn->allocptr.ref)?conn->allocptr.ref:"" /* Referer: <data> <CRLF> */,
                    te
    
    Daniel Stenberg's avatar
    Daniel Stenberg committed
    
    
    Daniel Stenberg's avatar
    Daniel Stenberg committed
        if(co) {
          int count=0;
    
          struct Cookie *store=co;
    
    Daniel Stenberg's avatar
    Daniel Stenberg committed
          /* now loop through all cookies that matched */
          while(co) {
    
                add_bufferf(req_buffer, "Cookie: ");
    
              add_bufferf(req_buffer,
                          "%s%s=%s", count?"; ":"", co->name, co->value);
    
    Daniel Stenberg's avatar
    Daniel Stenberg committed
            }
            co = co->next; /* next cookie please */
          }
          if(count) {
    
    Daniel Stenberg's avatar
    Daniel Stenberg committed
          }
    
          Curl_cookie_freelist(store); /* free the cookie list */
    
    Daniel Stenberg's avatar
    Daniel Stenberg committed
          co=NULL;
        }
    
    
    Daniel Stenberg's avatar
    Daniel Stenberg committed
          struct tm *thistime;
    
    
          /* Phil Karn (Fri, 13 Apr 2001) pointed out that the If-Modified-Since
           * header family should have their times set in GMT as RFC2616 defines:
           * "All HTTP date/time stamps MUST be represented in Greenwich Mean Time
           * (GMT), without exception. For the purposes of HTTP, GMT is exactly
           * equal to UTC (Coordinated Universal Time)." (see page 20 of RFC2616).
           */
    
    
    Daniel Stenberg's avatar
    Daniel Stenberg committed
    #ifdef HAVE_GMTIME_R
    
    Daniel Stenberg's avatar
    Daniel Stenberg committed
          /* thread-safe version */
          struct tm keeptime;
    
          thistime = (struct tm *)gmtime_r(&data->set.timevalue, &keeptime);
    
    Daniel Stenberg's avatar
    Daniel Stenberg committed
    #else
    
          thistime = gmtime(&data->set.timevalue);
    
    Daniel Stenberg's avatar
    Daniel Stenberg committed
    #endif
    
    Daniel Stenberg's avatar
    Daniel Stenberg committed
    
    
    #ifdef HAVE_STRFTIME
    
    Daniel Stenberg's avatar
    Daniel Stenberg committed
          /* format: "Tue, 15 Nov 1994 12:45:26 GMT" */
    
          strftime(buf, BUFSIZE-1, "%a, %d %b %Y %H:%M:%S GMT", thistime);
    
    Daniel Stenberg's avatar
    Daniel Stenberg committed
    #else
    
    Daniel Stenberg's avatar
    Daniel Stenberg committed
          /* TODO: Right, we *could* write a replacement here */
    
    Daniel Stenberg's avatar
    Daniel Stenberg committed
          strcpy(buf, "no strftime() support");
    #endif
    
          case CURL_TIMECOND_IFMODSINCE:
    
    Daniel Stenberg's avatar
    Daniel Stenberg committed
          default:
    
            add_bufferf(req_buffer,
                        "If-Modified-Since: %s\r\n", buf);
    
    Daniel Stenberg's avatar
    Daniel Stenberg committed
            break;
    
          case CURL_TIMECOND_IFUNMODSINCE:
    
            add_bufferf(req_buffer,
                        "If-Unmodified-Since: %s\r\n", buf);
    
    Daniel Stenberg's avatar
    Daniel Stenberg committed
            break;
    
          case CURL_TIMECOND_LASTMOD:
    
            add_bufferf(req_buffer,
                        "Last-Modified: %s\r\n", buf);
    
          ptr = strchr(headers->data, ':');
    
          if(ptr) {
            /* we require a colon for this to be a true header */
    
            ptr++; /* pass the colon */
    
              ptr++;
    
            if(*ptr) {
              /* only send this if the contents was non-blank */
    
    
              add_bufferf(req_buffer, "%s\r\n", headers->data);
    
          headers = headers->next;
    
        http->postdata = NULL;  /* nothing to post at this point */
        Curl_pgrsSetUploadSize(data, 0); /* upload size is 0 atm */
    
        if(!authdone)
          /* until the auth is done, pretend we only do GET */
          httpreq = HTTPREQ_GET;
        else
          httpreq = data->set.httpreq;
    
        switch(httpreq) {
    
          if(Curl_FormInit(&http->form, http->sendit)) {
    
            failf(data, "Internal HTTP POST error!");
    
            return CURLE_HTTP_POST_ERROR;
    
          /* set the read function to read from the generated form data */
          conn->fread = (curl_read_callback)Curl_FormReader;
          conn->fread_in = &http->form;
    
    Daniel Stenberg's avatar
    Daniel Stenberg committed
    
    
          if(!conn->bits.upload_chunky)
            /* only add Content-Length if not uploading chunked */
            add_bufferf(req_buffer,
                        "Content-Length: %d\r\n", http->postsize);
    
          if(!checkheaders(data, "Expect:")) {
            /* if not disabled explicitly we add a Expect: 100-continue
               to the headers which actually speeds up post operations (as
               there is one packet coming back from the web server) */
            add_bufferf(req_buffer,
                        "Expect: 100-continue\r\n");
    
          if(!checkheaders(data, "Content-Type:")) {
    
            /* Get Content-Type: line from Curl_FormReadOneLine, which happens
               to always be the first line. We can know this for sure since
    
               we always build the formpost linked list the same way!
    
               The Content-Type header line also contains the MIME boundary
               string etc why disabling this header is likely to not make things
               work, but we support it anyway.
            */
            char contentType[256];
            int linelength=0;
    
            linelength = Curl_FormReadOneLine (contentType,
                                               sizeof(contentType),
                                               1,
                                               (FILE *)&http->form);
            if(linelength == -1) {
    
              failf(data, "Could not get Content-Type header line!");
    
              return CURLE_HTTP_POST_ERROR;
            }
            add_buffer(req_buffer, contentType, linelength);
          }
    
    
          /* make the request end in a true CRLF */
          add_buffer(req_buffer, "\r\n", 2);
    
    
          /* set upload size to the progress meter */
    
          Curl_pgrsSetUploadSize(data, http->postsize);
    
    Daniel Stenberg's avatar
    Daniel Stenberg committed
    
    
          /* fire away the whole request to the server */
    
          result = add_buffer_send(req_buffer, conn, 
    
                                   &data->info.request_size);
          if(result)
            failf(data, "Failed sending POST request");
          else
            /* setup variables for the upcoming transfer */
    
            result = Curl_Transfer(conn, FIRSTSOCKET, -1, TRUE,
    
            Curl_formclean(http->sendit); /* free that whole lot */
    
    Daniel Stenberg's avatar
    Daniel Stenberg committed
          }
    
          break;
    
        case HTTPREQ_PUT: /* Let's PUT the data to the server! */
    
    Daniel Stenberg's avatar
    Daniel Stenberg committed
    
    
          if((data->set.infilesize>0) && !conn->bits.upload_chunky)
            /* only add Content-Length if not uploading chunked */
    
                        "Content-Length: %Od\r\n", /* file size */
    
          /* set the upload size to the progress meter */
    
          Curl_pgrsSetUploadSize(data, (double)data->set.infilesize);
    
    Daniel Stenberg's avatar
    Daniel Stenberg committed
    
    
          /* this sends the buffer and frees all the buffer resources */
    
          result = add_buffer_send(req_buffer, conn,
    
            failf(data, "Failed sending POST request");
    
            result = Curl_Transfer(conn, FIRSTSOCKET, -1, TRUE,
    
    Daniel Stenberg's avatar
    Daniel Stenberg committed
          if(result)
            return result;
    
        case HTTPREQ_POST:
          /* this is the simple POST, using x-www-form-urlencoded style */
    
          /* store the size of the postfields */
          postsize = data->set.postfieldsize?
            data->set.postfieldsize:
            (data->set.postfields?strlen(data->set.postfields):0);
          
    
          if(!conn->bits.upload_chunky) {
            /* We only set Content-Length and allow a custom Content-Length if
               we don't upload data chunked, as RFC2616 forbids us to set both
               kinds of headers (Transfer-Encoding: chunked and Content-Length) */
    
            if(!checkheaders(data, "Content-Length:"))
              /* we allow replacing this header, although it isn't very wise to
                 actually set your own */
    
              add_bufferf(req_buffer, "Content-Length: %d\r\n", postsize);
    
          if(!checkheaders(data, "Content-Type:"))
            add_bufferf(req_buffer,
                        "Content-Type: application/x-www-form-urlencoded\r\n");
    
          add_buffer(req_buffer, "\r\n", 2);
    
    
            if(postsize < (100*1024)) {
              /* The post data is less than 100K, then append it to the header.
                 This limit is no magic limit but only set to prevent really huge
                 POSTs to get the data duplicated with malloc() and family. */
    
              if(!conn->bits.upload_chunky)
                /* We're not sending it 'chunked', append it to the request
                   already now to reduce the number if send() calls */
                add_buffer(req_buffer, data->set.postfields, postsize);
              else {
                /* Append the POST data chunky-style */
                add_bufferf(req_buffer, "%x\r\n", postsize);
                add_buffer(req_buffer, data->set.postfields, postsize);
                add_buffer(req_buffer, "\r\n0\r\n", 5); /* end of a chunked
                                                           transfer stream */
              }
    
              /* A huge POST coming up, do data separate from the request */
    
              http->postsize = postsize;
              http->postdata = data->set.postfields;
    
              conn->fread = (curl_read_callback)readmoredata;
              conn->fread_in = (void *)conn;
    
              /* set the upload size to the progress meter */
              Curl_pgrsSetUploadSize(data, http->postsize);
            }
    
            /* set the upload size to the progress meter */
    
            Curl_pgrsSetUploadSize(data, (double)data->set.infilesize);
    
            /* set the pointer to mark that we will send the post body using
               the read callback */
            http->postdata = (char *)&http->postdata;
          }
          /* issue the request */
    
          result = add_buffer_send(req_buffer, conn,
    
                                   &data->info.request_size);
    
          if(result)
            failf(data, "Failed sending HTTP POST request");
    
              Curl_Transfer(conn, FIRSTSOCKET, -1, TRUE,
    
                            http->postdata?&http->writebytecount:NULL);
    
          /* issue the request */
    
          result = add_buffer_send(req_buffer, conn,
    
          if(result)
            failf(data, "Failed sending HTTP request");
          else
            /* HTTP GET/HEAD download: */
    
            result = Curl_Transfer(conn, FIRSTSOCKET, -1, TRUE,
    
                                   http->postdata?&http->writebytecount:NULL);
    
    Daniel Stenberg's avatar
    Daniel Stenberg committed
        if(result)
          return result;
    
    Daniel Stenberg's avatar
    Daniel Stenberg committed
    
    
      return CURLE_OK;
    
    Daniel Stenberg's avatar
    Daniel Stenberg committed
    }