Skip to content
Snippets Groups Projects
http.c 63.1 KiB
Newer Older
  • Learn to ignore specific revisions
  •       case -1: /* select() error, stop reading */
            error = SELECT_ERROR;
            failf(data, "Proxy CONNECT aborted due to select() error");
            break;
          case 0: /* timeout */
            break;
          default:
            /*
             * This code previously didn't use the kerberos sec_read() code
             * to read, but when we use Curl_read() it may do so. Do confirm
             * that this is still ok and then remove this comment!
             */
            res= Curl_read(conn, tunnelsocket, ptr, BUFSIZE-nread, &gotbytes);
            if(res< 0)
              /* EWOULDBLOCK */
              continue; /* go loop yourself */
            else if(res)
              keepon = FALSE;
            else if(gotbytes <= 0) {
              keepon = FALSE;
              error = SELECT_ERROR;
              failf(data, "Proxy CONNECT aborted");
            }
            else {
              /*
               * We got a whole chunk of data, which can be anything from one byte
               * to a set of lines and possibly just a piece of the last line.
               *
               * TODO: To make this code work less error-prone, we need to make
               * sure that we read and create full lines before we compare them,
               * as there is really nothing that stops the proxy from delivering
               * the response lines in multiple parts, each part consisting of
               * only a little piece of the line(s).  */
              int i;
    
              nread += gotbytes;
              for(i = 0; i < gotbytes; ptr++, i++) {
                perline++; /* amount of bytes in this line so far */
                if(*ptr=='\n') {
                  char letter;
    
                  /* output debug output if that is requested */
                  if(data->set.verbose)
    
                    Curl_debug(data, CURLINFO_HEADER_IN, line_start, perline,
                               conn->host.dispname);
    
    
                  /* send the header to the callback */
                  writetype = CLIENTWRITE_HEADER;
    
                    writetype |= CLIENTWRITE_BODY;
    
                  result = Curl_client_write(data, writetype, line_start, perline);
                  if(result)
                    return result;
    
    
                  /* Newlines are CRLF, so the CR is ignored as the line isn't
    
                     really terminated until the LF comes. Treat a following CR
                     as end-of-headers as well.*/
    
                  if(('\r' == line_start[0]) ||
                     ('\n' == line_start[0])) {
    
                    /* end of response-headers from the proxy */
                    keepon=FALSE;
                    break; /* breaks out of for-loop, not switch() */
                  }
    
                  /* keep a backup of the position we are about to blank */
                  letter = line_start[perline];
                  line_start[perline]=0; /* zero terminate the buffer */
                  if((checkprefix("WWW-Authenticate:", line_start) &&
    
                      (401 == k->httpcode)) ||
    
                     (checkprefix("Proxy-authenticate:", line_start) &&
    
                      (407 == k->httpcode))) {
                    result = Curl_http_input_auth(conn, k->httpcode, line_start);
    
                    if(result)
                      return result;
                  }
                  else if(2 == sscanf(line_start, "HTTP/1.%d %d",
                                      &subversion,
    
                    /* store the HTTP code from the proxy */
    
                    data->info.httpproxycode = k->httpcode;
    
                  }
                  /* put back the letter we blanked out before */
                  line_start[perline]= letter;
    
                  perline=0; /* line starts over here */
                  line_start = ptr+1; /* this skips the zero byte we wrote */
    
            break;
          } /* switch */
        } /* while there's buffer left and loop is requested */
    
        if(data->info.httpproxycode != 200)
          /* Deal with the possibly already received authenticate
             headers. 'newurl' is set to a new URL if we must loop. */
          Curl_http_auth_act(conn);
    
      if(200 != k->httpcode) {
        failf(data, "Received HTTP code %d from proxy after CONNECT",
              k->httpcode);
    
        return CURLE_RECV_ERROR;
    
      /* If a proxy-authorization header was used for the proxy, then we should
         make sure that it isn't accidentally used for the document request
         after we've connected. So let's free and clear it here. */
      Curl_safefree(conn->allocptr.proxyuserpwd);
      conn->allocptr.proxyuserpwd = NULL;
    
      data->state.authproxy.done = TRUE;
    
      infof (data, "Proxy replied OK to CONNECT request\n");
    
    Daniel Stenberg's avatar
    Daniel Stenberg committed
     * Curl_http_connect() performs HTTP stuff to do at connect-time, called from
     * the generic Curl_connect().
    
    CURLcode Curl_http_connect(struct connectdata *conn)
    
    Daniel Stenberg's avatar
    Daniel Stenberg committed
    {
    
    
      data=conn->data;
    
      /* If we are not using a proxy and we want a secure connection,
       * perform SSL initialization & connection now.
       * If using a proxy with https, then we must tell the proxy to CONNECT
       * us to the host we want to talk to.  Only after the connect
       * has occured, can we start talking SSL
       */
    
        /* either SSL over proxy, or explicitly asked for */
    
        result = Curl_ConnectHTTPProxyTunnel(conn, FIRSTSOCKET,
    
    
      if(conn->protocol & PROT_HTTPS) {
        /* now, perform the SSL initialization for this socket */
    
        result = Curl_SSLConnect(conn, FIRSTSOCKET);
    
      if(conn->bits.user_passwd && !data->state.this_is_a_follow) {
    
        /* Authorization: is requested, this is not a followed location, get the
           original host name */
    
        if (data->state.auth_host)
          /* Free to avoid leaking memory on multiple requests*/
          free(data->state.auth_host);
    
    
        data->state.auth_host = strdup(conn->host.name);
    
    Daniel Stenberg's avatar
    Daniel Stenberg committed
    /*
     * Curl_http_done() gets called from Curl_done() after a single HTTP request
     * has been performed.
     */
    
    
    CURLcode Curl_http_done(struct connectdata *conn,
                            CURLcode status)
    
      struct HTTP *http;
    
    
      data=conn->data;
    
      http=conn->proto.http;
    
      /* set the proper values (possibly modified on POST) */
      conn->fread = data->set.fread; /* restore */
      conn->fread_in = data->set.in; /* restore */
    
    
      if(http->send_buffer) {
        send_buffer *buff = http->send_buffer;
    
        http->send_buffer = NULL; /* cleaer the pointer */
    
      if(HTTPREQ_POST_FORM == data->set.httpreq) {
    
        conn->bytecount = http->readbytecount + http->writebytecount;
    
        Curl_formclean(http->sendit); /* Now free that whole lot */
    
    Daniel Stenberg's avatar
    Daniel Stenberg committed
      }
    
      else if(HTTPREQ_PUT == data->set.httpreq)
        conn->bytecount = http->readbytecount + http->writebytecount;
    
         ((http->readbytecount +
           conn->headerbytecount -
           conn->deductheadercount)) <= 0) {
    
        /* If this connection isn't simply closed to be retried, AND nothing was
    
           read from the HTTP server (that counts), this can't be right so we
           return an error here */
    
        failf(data, "Empty reply from server");
    
    Daniel Stenberg's avatar
    Daniel Stenberg committed
    /*
     * Curl_http() gets called from the generic Curl_do() function when a HTTP
     * request is to be performed. This creates and sends a propperly constructed
     * HTTP request.
     */
    
    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;
    
      const char *te = ""; /* tranfer-encoding */
    
    Daniel Stenberg's avatar
    Daniel Stenberg committed
      char *request;
    
      Curl_HttpReq httpreq = data->set.httpreq;
    
      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)) &&
    
    Daniel Stenberg's avatar
    Daniel Stenberg committed
      }
    
      /* Now set the 'request' pointer to the proper request string */
      if(data->set.customrequest)
        request = data->set.customrequest;
      else {
        if(conn->bits.no_body)
          request = (char *)"HEAD";
        else {
          curlassert((httpreq > HTTPREQ_NONE) && (httpreq < HTTPREQ_LAST));
          switch(httpreq) {
          case HTTPREQ_POST:
          case HTTPREQ_POST_FORM:
            request = (char *)"POST";
            break;
          case HTTPREQ_PUT:
            request = (char *)"PUT";
            break;
    
          default: /* this should never happen */
    
          case HTTPREQ_GET:
            request = (char *)"GET";
            break;
          case HTTPREQ_HEAD:
            request = (char *)"HEAD";
            break;
          }
        }
      }
    
      /* The User-Agent string might have been allocated 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 = Curl_http_output_auth(conn, request, ppath, FALSE);
    
      if((!data->state.authhost.done || !data->state.authproxy.done ) &&
         (httpreq != HTTPREQ_GET)) {
    
        /* Until we are authenticated, we switch over to HEAD. Unless its a GET
           we want to do. The explanation for this is rather long and boring, but
           the point is that it can't be done otherwise without risking having to
           send the POST or PUT data multiple times. */
        httpreq = HTTPREQ_HEAD;
        request = (char *)"HEAD";
        conn->bits.no_body = TRUE;
    
        conn->bits.authprobe = TRUE; /* this is a request done to probe for
                                        authentication methods */
    
      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;
    
      if(data->set.cookie && !checkheaders(data, "Cookie:"))
    
    Daniel Stenberg's avatar
    Daniel Stenberg committed
    
    
      if(!conn->bits.upload_chunky && (httpreq != HTTPREQ_GET)) {
    
        /* not a chunky transfer yet, but data is to be sent */
    
        ptr = checkheaders(data, "Transfer-Encoding:");
    
        if(ptr) {
          /* Some kind of TE is requested, check if 'chunked' is chosen */
    
          conn->bits.upload_chunky =
            Curl_compareheader(ptr, "Transfer-Encoding:", "chunked");
          te = "";
    
      else if(conn->bits.upload_chunky) {
    
        /* 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";
        }
    
          conn->bits.upload_chunky = FALSE; /* transfer-encoding was disabled,
                                               so don't chunkify this! */
    
      ptr = checkheaders(data, "Host:");
    
      if(ptr && !data->state.this_is_a_follow) {
        /* If we have a given custom Host: header, we extract the host name in
           order to possibly use it for cookie reasons later on. We only allow the
           custom Host: header if this is NOT a redirect, as setting Host: in the
           redirected request is being out on thin ice. */
    
        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))
    
          size_t 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;
        }
    
        Curl_safefree(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
    
    
      if (conn->bits.httpproxy && !conn->bits.tunnel_proxy)  {
        /* Using a proxy but does not tunnel through it */
    
    
        /* The path sent to the proxy is in fact the entire URL. But if the remote
           host is a IDN-name, we must make sure that the request we produce only
           uses the encoded host name! */
        if(conn->host.dispname != conn->host.name) {
          char *url = data->change.url;
          char *ptr = strstr(url, conn->host.dispname);
          if(ptr) {
            /* This is where the display name starts in the URL, now replace this
               part with the encoded name. TODO: This method of replacing the host
               name is rather crude as I believe there's a slight risk that the
               user has entered a user name or password that contain the host name
               string. */
            size_t currlen = strlen(conn->host.dispname);
            size_t newlen = strlen(conn->host.name);
            size_t urllen = strlen(url);
    
            newurl = malloc(urllen + newlen - currlen + 1);
    
            if(newurl) {
              /* copy the part before the host name */
              memcpy(newurl, url, ptr - url);
              /* append the new host name instead of the old */
              memcpy(newurl + (ptr - url), conn->host.name, newlen);
              /* append the piece after the host name */
              memcpy(newurl + newlen + (ptr - url),
                     ptr + currlen, /* copy the trailing zero byte too */
                     urllen - (ptr-url) - currlen + 1);
              if(data->change.url_alloc)
                free(data->change.url);
              data->change.url = newurl;
              data->change.url_alloc = TRUE;
            }
            else
              return CURLE_OUT_OF_MEMORY;
    
        /* 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: */*\r\n";
    
    Daniel Stenberg's avatar
    Daniel Stenberg committed
    
    
      if(( (HTTPREQ_POST == httpreq) ||
           (HTTPREQ_POST_FORM == httpreq) ||
           (HTTPREQ_PUT == 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? */
    
          curl_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 {
    
            size_t readthisamountnow = (size_t)(conn->resume_from - passed);
    
            size_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 %" FORMAT_OFF_T
    
                    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 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);
    
            /* This is because "resume" was selected */
    
            curl_off_t total_expected_size=
              conn->resume_from + data->set.infilesize;
    
            conn->allocptr.rangeline =
    
    	    aprintf("Content-Range: bytes %s%" FORMAT_OFF_T
                        "/%" FORMAT_OFF_T "\r\n",
    
    		    conn->range, total_expected_size-1,
    		    total_expected_size);
    
            /* Range was selected and then we just pass the incoming range and
    
            conn->allocptr.rangeline =
    
    	    aprintf("Content-Range: bytes %s/%" FORMAT_OFF_T "\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;
    
        curl_off_t postsize; /* off_t type to be able to hold a large file size */
    
    
        /* 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" /* host */
                      "%s" /* pragma */
                      "%s" /* accept */
                      "%s" /* accept-encoding */
                      "%s" /* referer */
                      "%s",/* transfer-encoding */
    
                    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.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:"",
                    (data->change.referer && conn->allocptr.ref)?conn->allocptr.ref:"" /* Referer: <data> */,
    
    Daniel Stenberg's avatar
    Daniel Stenberg committed
    
    
        if(data->cookies || addcookies) {
          struct Cookie *co=NULL; /* no cookies from start */
          int count=0;
    
          if(data->cookies) {
            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);
          }
    
          if(co) {
            struct Cookie *store=co;
            /* now loop through all cookies that matched */
            while(co) {
              if(co->value) {
                if(0 == count) {
                  result = add_bufferf(req_buffer, "Cookie: ");
                  if(result)
                    break;
                }
                result = add_bufferf(req_buffer,
                                     "%s%s=%s", count?"; ":"",
                                     co->name, co->value);
    
              co = co->next; /* next cookie please */
    
    Daniel Stenberg's avatar
    Daniel Stenberg committed
            }
    
            Curl_cookie_freelist(store); /* free the cookie list */
    
    Daniel Stenberg's avatar
    Daniel Stenberg committed
          }
    
          if(addcookies && (CURLE_OK == result)) {
            if(!count)
              result = add_bufferf(req_buffer, "Cookie: ");
            if(CURLE_OK == result) {
              result = add_bufferf(req_buffer, "%s%s",
                                   count?"; ":"",
                                   addcookies);
              count++;
            }
          }
          if(count && (CURLE_OK == result))
            result = add_buffer(req_buffer, "\r\n", 2);
    
    
    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:
    
            result = add_bufferf(req_buffer,
                                 "If-Modified-Since: %s\r\n", buf);
    
    Daniel Stenberg's avatar
    Daniel Stenberg committed
            break;
    
          case CURL_TIMECOND_IFUNMODSINCE:
    
            result = add_bufferf(req_buffer,
                                 "If-Unmodified-Since: %s\r\n", buf);
    
    Daniel Stenberg's avatar
    Daniel Stenberg committed
            break;
    
          case CURL_TIMECOND_LASTMOD:
    
            result = add_bufferf(req_buffer,
                                 "Last-Modified: %s\r\n", buf);
    
    Daniel Stenberg's avatar
    Daniel Stenberg committed
            break;
          }
    
          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 */
    
    
              result = add_bufferf(req_buffer, "%s\r\n", headers->data);
              if(result)
                return result;
    
          headers = headers->next;
    
        http->postdata = NULL;  /* nothing to post at this point */
        Curl_pgrsSetUploadSize(data, 0); /* upload size is 0 atm */
    
        /* If 'authdone' is FALSE, we must not set the write socket index to the
           Curl_transfer() call below, as we're not ready to actually upload any
           data yet. */
    
          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 */
    
            result = add_bufferf(req_buffer,
                                 "Content-Length: %" FORMAT_OFF_T "\r\n",
                                 http->postsize);
            if(result)
              return result;
          }
    
          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) */
    
            result = add_bufferf(req_buffer,
                                 "Expect: 100-continue\r\n");
            if(result)
              return result;
    
          if(!checkheaders(data, "Content-Type:")) {
    
    Daniel Stenberg's avatar
    Daniel Stenberg committed
            /* Get Content-Type: line from Curl_formpostheader.
    
    
               The Content-Type header line also contains the MIME boundary
               string etc why disabling this header is likely to not make things
    
    Daniel Stenberg's avatar
    Daniel Stenberg committed
               work, but we support disabling it anyway.
    
            size_t linelength=0;
    
            contentType = Curl_formpostheader((void *)&http->form,
                                              &linelength);
            if(!contentType) {
    
              failf(data, "Could not get Content-Type header line!");
    
            result = add_buffer(req_buffer, contentType, linelength);
            if(result)
              return result;
    
          /* make the request end in a true CRLF */
    
          result = add_buffer(req_buffer, "\r\n", 2);
          if(result)
            return result;
    
          /* 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,
    
                                   FIRSTSOCKET,
                                   &http->writebytecount);
    
            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 */
    
            result = add_bufferf(req_buffer,
                                 "Content-Length: %" FORMAT_OFF_T "\r\n", /* size */
                                 data->set.infilesize );
            if(result)
              return result;
          }
    
    Daniel Stenberg's avatar
    Daniel Stenberg committed
          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) */
    
            result = add_bufferf(req_buffer,
                                 "Expect: 100-continue\r\n");
            if(result)
              return result;
    
    Daniel Stenberg's avatar
    Daniel Stenberg committed
            data->set.expect100header = TRUE;
          }
    
    
          result = add_buffer(req_buffer, "\r\n", 2); /* end of headers */
          if(result)
            return result;
    
          /* set the upload size to the progress meter */
    
          Curl_pgrsSetUploadSize(data, 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,
    
                                   FIRSTSOCKET,
                                   &http->writebytecount);
    
    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?(curl_off_t)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 */
    
              result = add_bufferf(req_buffer,
                                   "Content-Length: %" FORMAT_OFF_T"\r\n",
                                   postsize);
              if(result)
                return result;
            }
    
          if(!checkheaders(data, "Content-Type:")) {
            result = add_bufferf(req_buffer,
                                 "Content-Type: application/x-www-form-urlencoded\r\n");
            if(result)
              return result;
          }
    
            if((data->state.authhost.done || data->state.authproxy.done )
               && (postsize < (100*1024))) {
    
    Daniel Stenberg's avatar
    Daniel Stenberg committed
              /* If we're not done with the authentication phase, we don't expect
                 to actually send off any data yet. Hence, we delay the sending of
                 the body until we receive that friendly 100-continue response */
    
              /* 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. */
    
    
    Daniel Stenberg's avatar
    Daniel Stenberg committed
              result = add_buffer(req_buffer, "\r\n", 2); /* end of headers! */
    
    Daniel Stenberg's avatar
    Daniel Stenberg committed
    
    
                /* We're not sending it 'chunked', append it to the request
                   already now to reduce the number if send() calls */
    
                result = add_buffer(req_buffer, data->set.postfields,
                                    (size_t)postsize);
              }
    
              else {
                /* Append the POST data chunky-style */
    
                result = add_bufferf(req_buffer, "%x\r\n", (int)postsize);
                if(CURLE_OK == result)
                  result = add_buffer(req_buffer, data->set.postfields,
                                      (size_t)postsize);
                if(CURLE_OK == result)
                  result = add_buffer(req_buffer,
                                      "\r\n0\r\n\r\n", 7); /* 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);
    
    Daniel Stenberg's avatar
    Daniel Stenberg committed
    
    
              if(!checkheaders(data, "Expect:")) {
    
    Daniel Stenberg's avatar
    Daniel Stenberg committed
                /* 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");
                data->set.expect100header = TRUE;
              }
    
              add_buffer(req_buffer, "\r\n", 2); /* end of headers! */
    
    Daniel Stenberg's avatar
    Daniel Stenberg committed
            add_buffer(req_buffer, "\r\n", 2); /* end of headers! */
    
    
            /* set the upload size to the progress meter */
    
            Curl_pgrsSetUploadSize(data, 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);
    
        default:
          add_buffer(req_buffer, "\r\n", 2);
    
          /* 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
    }