Skip to content
url.c 161 KiB
Newer Older
    /* Now, build <protocol>_proxy and check for such a one to use */
    while(*protop)
      *envp++ = (char)tolower((int)*protop++);
    /* read the protocol proxy: */
    prox=curl_getenv(proxy_env);
    /*
     * We don't try the uppercase version of HTTP_PROXY because of
     * security reasons:
     *
     * When curl is used in a webserver application
     * environment (cgi or php), this environment variable can
     * be controlled by the web server user by setting the
     * http header 'Proxy:' to some value.
     *
     * This can cause 'internal' http/ftp requests to be
     * arbitrarily redirected by any external attacker.
     */
    if(!prox && !Curl_raw_equal("http_proxy", proxy_env)) {
      /* There was no lowercase variable, try the uppercase version: */
      Curl_strntoupper(proxy_env, proxy_env, sizeof(proxy_env));
      prox=curl_getenv(proxy_env);
    }
    if(prox && *prox) { /* don't count "" strings */
      proxy = prox; /* use this */
    }
    else {
      proxy = curl_getenv("all_proxy"); /* default proxy to use */
      if(!proxy)
        proxy=curl_getenv("ALL_PROXY");
    }
  } /* if(!check_noproxy(conn->host.name, no_proxy)) - it wasn't specified
       non-proxy */

#else /* !CURL_DISABLE_HTTP */

  (void)conn;
/*
 * If this is supposed to use a proxy, we need to figure out the proxy
 * host name, so that we can re-use an existing connection
 * that may exist registered to the same proxy host.
 * proxy will be freed before this function returns.
 */
static CURLcode parse_proxy(struct SessionHandle *data,
                            struct connectdata *conn, char *proxy)
{
  char *prox_portno;
  char *endofprot;

  /* We use 'proxyptr' to point to the proxy name from now on... */
  char *portptr;
  char *atsign;

  /* We do the proxy host string parsing here. We want the host name and the
   * port name. Accept a protocol:// prefix, even though it should just be
   * ignored.
   */

  /* Skip the protocol part if present */

  /* Is there a username and password given in this proxy url? */
  atsign = strchr(proxyptr, '@');
  if(atsign) {
    char proxyuser[MAX_CURL_USER_LENGTH];
    char proxypasswd[MAX_CURL_PASSWORD_LENGTH];
    proxypasswd[0] = 0;

    if(1 <= sscanf(proxyptr,
                   "%" MAX_CURL_USER_LENGTH_TXT"[^:@]:"
                   "%" MAX_CURL_PASSWORD_LENGTH_TXT "[^@]",
                   proxyuser, proxypasswd)) {
      CURLcode res = CURLE_OK;

      /* found user and password, rip them out.  note that we are
         unescaping them, as there is otherwise no way to have a
         username or password with reserved characters like ':' in
         them. */
      Curl_safefree(conn->proxyuser);
      conn->proxyuser = curl_easy_unescape(data, proxyuser, 0, NULL);

      if(!conn->proxyuser)
        Curl_safefree(conn->proxypasswd);
        conn->proxypasswd = curl_easy_unescape(data, proxypasswd, 0, NULL);
        if(!conn->proxypasswd)
          res = CURLE_OUT_OF_MEMORY;
        conn->bits.proxy_user_passwd = TRUE; /* enable it */
        atsign = strdup(atsign+1); /* the right side of the @-letter */

        if(atsign) {
          free(proxy); /* free the former proxy string */
          proxy = proxyptr = atsign; /* now use this instead */
        }
        else
          res = CURLE_OUT_OF_MEMORY;
        free(proxy); /* free the allocated proxy string */
        return res;
  }

  /* start scanning for port number at this point */
  portptr = proxyptr;

  /* detect and extract RFC2732-style IPv6-addresses */
  if(*proxyptr == '[') {
    char *ptr = ++proxyptr; /* advance beyond the initial bracket */
    while(*ptr && (ISXDIGIT(*ptr) || (*ptr == ':') || (*ptr == '%') ||
                   (*ptr == '.')))
      ptr++;
    if(*ptr == ']') {
      /* yeps, it ended nicely with a bracket as well */
      *ptr++ = 0;
    } else
      infof(data, "Invalid IPv6 address format\n");
    portptr = ptr;
    /* Note that if this didn't end with a bracket, we still advanced the
     * proxyptr first, but I can't see anything wrong with that as no host
     * name nor a numeric can legally start with a bracket.
     */
  }

  /* Get port number off proxy.server.com:1080 */
  prox_portno = strchr(portptr, ':');
    *prox_portno = 0x0; /* cut off number from host name */
    prox_portno ++;
    /* now set the local port number */
Yang Tse's avatar
Yang Tse committed
    conn->port = strtol(prox_portno, NULL, 10);
  else {
    /* without a port number after the host name, some people seem to use
       a slash so we strip everything from the first slash */
    atsign = strchr(proxyptr, '/');
    if(atsign)
      *atsign = 0x0; /* cut off path part from host name */

    if(data->set.proxyport)
      /* None given in the proxy string, then get the default one if it is
         given */
      conn->port = data->set.proxyport;
  }

  /* now, clone the cleaned proxy host name */
  conn->proxy.rawalloc = strdup(proxyptr);
  conn->proxy.name = conn->proxy.rawalloc;
  free(proxy);
  if(!conn->proxy.rawalloc)
    return CURLE_OUT_OF_MEMORY;

  return CURLE_OK;
}

/*
 * Extract the user and password from the authentication string
 */
static CURLcode parse_proxy_auth(struct SessionHandle *data,
                                 struct connectdata *conn)
{
  char proxyuser[MAX_CURL_USER_LENGTH]="";
  char proxypasswd[MAX_CURL_PASSWORD_LENGTH]="";

  if(data->set.str[STRING_PROXYUSERNAME] != NULL) {
    strncpy(proxyuser, data->set.str[STRING_PROXYUSERNAME],
            MAX_CURL_USER_LENGTH);
    proxyuser[MAX_CURL_USER_LENGTH-1] = '\0';   /*To be on safe side*/
  }
  if(data->set.str[STRING_PROXYPASSWORD] != NULL) {
    strncpy(proxypasswd, data->set.str[STRING_PROXYPASSWORD],
            MAX_CURL_PASSWORD_LENGTH);
    proxypasswd[MAX_CURL_PASSWORD_LENGTH-1] = '\0'; /*To be on safe side*/
  }

  conn->proxyuser = curl_easy_unescape(data, proxyuser, 0, NULL);
  if(!conn->proxyuser)
    return CURLE_OUT_OF_MEMORY;
  conn->proxypasswd = curl_easy_unescape(data, proxypasswd, 0, NULL);
  if(!conn->proxypasswd)
    return CURLE_OUT_OF_MEMORY;

  return CURLE_OK;
}
 * Parse a user name and password in the URL and strip it out of the host name
 * Inputs: data->set.use_netrc (CURLOPT_NETRC)
 *         conn->host.name
 * Outputs: (almost :- all currently undefined)
 *          conn->bits.user_passwd  - non-zero if non-default passwords exist
 *          user                    - non-zero length if defined
 *          passwd                  -   ditto
 *          conn->host.name         - remove user name and password
static CURLcode parse_url_userpass(struct SessionHandle *data,
                                   struct connectdata *conn,
                                   char *user, char *passwd)
  /* At this point, we're hoping all the other special cases have
   * been taken care of, so conn->host.name is at most
   *    [user[:password]]@]hostname
   *
   * We need somewhere to put the embedded details, so do that first.
   */
  char *ptr=strchr(conn->host.name, '@');
  char *userpass = conn->host.name;

  user[0] =0;   /* to make everything well-defined */
  passwd[0]=0;
  /* We will now try to extract the
   * possible user+password pair in a string like:
   * ftp://user:password@ftp.my.site:8021/README */
  if(ptr != NULL) {
    /* there's a user+password given here, to the left of the @ */
    conn->host.name = ++ptr;
    /* So the hostname is sane.  Only bother interpreting the
     * results if we could care.  It could still be wasted
     * work because it might be overtaken by the programmatically
     * set user/passwd, but doing that first adds more cases here :-(
     */
    conn->bits.userpwd_in_url = TRUE;
    if(data->set.use_netrc != CURL_NETRC_REQUIRED) {
      /* We could use the one in the URL */

      conn->bits.user_passwd = TRUE; /* enable user+password */

      if(*userpass != ':') {
        /* the name is given, get user+password */
        sscanf(userpass, "%" MAX_CURL_USER_LENGTH_TXT "[^:@]:"
               "%" MAX_CURL_PASSWORD_LENGTH_TXT "[^@]",
               user, passwd);
      }
      else
        /* no name given, get the password only */
        sscanf(userpass, ":%" MAX_CURL_PASSWORD_LENGTH_TXT "[^@]", passwd);

      if(user[0]) {
        char *newname=curl_easy_unescape(data, user, 0, NULL);
        if(!newname)
          return CURLE_OUT_OF_MEMORY;
        if(strlen(newname) < MAX_CURL_USER_LENGTH)
          strcpy(user, newname);

        /* if the new name is longer than accepted, then just use
           the unconverted name, it'll be wrong but what the heck */
        free(newname);
      }
      if(passwd[0]) {
        /* we have a password found in the URL, decode it! */
        char *newpasswd=curl_easy_unescape(data, passwd, 0, NULL);
        if(!newpasswd)
          return CURLE_OUT_OF_MEMORY;
        if(strlen(newpasswd) < MAX_CURL_PASSWORD_LENGTH)
          strcpy(passwd, newpasswd);

        free(newpasswd);
/*************************************************************
 * Figure out the remote port number and fix it in the URL
 *
 * No matter if we use a proxy or not, we have to figure out the remote
 * port number of various reasons.
 *
 * To be able to detect port number flawlessly, we must not confuse them
 * IPv6-specified addresses in the [0::1] style. (RFC2732)
 *
 * The conn->host.name is currently [user:passwd@]host[:port] where host
 * could be a hostname, IPv4 address or IPv6 address.
 *
 * The port number embedded in the URL is replaced, if necessary.
 *************************************************************/
static CURLcode parse_remote_port(struct SessionHandle *data,
                                  struct connectdata *conn)
{
  char *portptr;
  char endbracket;
  /* Note that at this point, the IPv6 address cannot contain any scope
     suffix as that has already been removed in the parseurlandfillconn()
     function */
  if((1 == sscanf(conn->host.name, "[%*45[0123456789abcdefABCDEF:.]%c",
     (']' == endbracket)) {
    /* this is a RFC2732-style specified IP-address */
    conn->bits.ipv6_ip = TRUE;
    conn->host.name++; /* skip over the starting bracket */
    portptr = strchr(conn->host.name, ']');
    if(portptr) {
      *portptr++ = '\0'; /* zero terminate, killing the bracket */
      if(':' != *portptr)
        portptr = NULL; /* no port number available */
    }
  }
  else
    portptr = strrchr(conn->host.name, ':');
  if(data->set.use_port && data->state.allow_port) {
    /* if set, we use this and ignore the port possibly given in the URL */
    conn->remote_port = (unsigned short)data->set.use_port;
    if(portptr)
      *portptr = '\0'; /* cut off the name there anyway - if there was a port
                      number - since the port number is to be ignored! */
    if(conn->bits.httpproxy) {
      /* we need to create new URL with the new port number */
      char *url;
      char type[12]="";

      if(conn->bits.type_set)
        snprintf(type, sizeof(type), ";type=%c",
                 data->set.prefer_ascii?'A':
                 (data->set.ftp_list_only?'D':'I'));
       * This synthesized URL isn't always right--suffixes like ;type=A are
       * stripped off. It would be better to work directly from the original
       * URL and simply replace the port part of it.
      url = aprintf("%s://%s%s%s:%hu%s%s%s", conn->handler->scheme,
                    conn->bits.ipv6_ip?"[":"", conn->host.name,
                    conn->bits.ipv6_ip?"]":"", conn->remote_port,
                    data->state.slash_removed?"/":"", data->state.path,
                    type);
      if(data->change.url_alloc)
        free(data->change.url);
      data->change.url = url;
      data->change.url_alloc = TRUE;
    }
  else if(portptr) {
    /* no CURLOPT_PORT given, extract the one from the URL */
    port=strtoul(portptr+1, &rest, 10);  /* Port number must be decimal */
    if(rest != (portptr+1) && *rest == '\0') {
      /* The colon really did have only digits after it,
       * so it is either a port number or a mistake */
      if(port > 0xffff) {   /* Single unix standard says port numbers are
                              * 16 bits long */
        failf(data, "Port number too large: %lu", port);
        return CURLE_URL_MALFORMAT;
      }
      *portptr = '\0'; /* cut off the name there */
Yang Tse's avatar
 
Yang Tse committed
      conn->remote_port = curlx_ultous(port);
    else if(!port)
      /* Browser behavior adaptation. If there's a colon with no digits after,
         just cut off the name there which makes us ignore the colon and just
         use the default port. Firefox and Chrome both do that. */
      *portptr = '\0';
  }
  return CURLE_OK;
}

/*
 * Override a user name and password from the URL with that in the
 * CURLOPT_USERPWD option or a .netrc file, if applicable.
 */
static void override_userpass(struct SessionHandle *data,
                              struct connectdata *conn,
                              char *user, char *passwd)
{
  if(data->set.str[STRING_USERNAME] != NULL) {
    strncpy(user, data->set.str[STRING_USERNAME], MAX_CURL_USER_LENGTH);
    user[MAX_CURL_USER_LENGTH-1] = '\0';   /*To be on safe side*/
  }
  if(data->set.str[STRING_PASSWORD] != NULL) {
    strncpy(passwd, data->set.str[STRING_PASSWORD], MAX_CURL_PASSWORD_LENGTH);
    passwd[MAX_CURL_PASSWORD_LENGTH-1] = '\0'; /*To be on safe side*/
  }

  conn->bits.netrc = FALSE;
  if(data->set.use_netrc != CURL_NETRC_IGNORED) {
    if(Curl_parsenetrc(conn->host.name,
                       user, passwd,
                       data->set.str[STRING_NETRC_FILE])) {
      infof(data, "Couldn't find host %s in the "
            DOT_CHAR "netrc file; using defaults\n",
            conn->host.name);
    }
    else {
      /* set bits.netrc TRUE to remember that we got the name from a .netrc
         file, so that it is safe to use even if we followed a Location: to a
         different host or similar. */
      conn->bits.netrc = TRUE;

      conn->bits.user_passwd = TRUE; /* enable user+password */
    }
  }
}

/*
 * Set password so it's available in the connection.
 */
static CURLcode set_userpass(struct connectdata *conn,
                             const char *user, const char *passwd)
{
  /* If our protocol needs a password and we have none, use the defaults */
  if( (conn->protocol & (PROT_FTP|PROT_IMAP)) &&
       !conn->bits.user_passwd) {

    conn->user = strdup(CURL_DEFAULT_USER);
Yang Tse's avatar
 
Yang Tse committed
    if(conn->user)
      conn->passwd = strdup(CURL_DEFAULT_PASSWORD);
    else
      conn->passwd = NULL;
    /* This is the default password, so DON'T set conn->bits.user_passwd */
  }
  else {
    /* store user + password, zero-length if not set */
    conn->user = strdup(user);
Yang Tse's avatar
 
Yang Tse committed
    if(conn->user)
      conn->passwd = strdup(passwd);
    else
      conn->passwd = NULL;
  }
  if(!conn->user || !conn->passwd)
    return CURLE_OUT_OF_MEMORY;

  return CURLE_OK;
}

/*************************************************************
 * Resolve the address of the server or proxy
 *************************************************************/
static CURLcode resolve_server(struct SessionHandle *data,
                               struct connectdata *conn,
                               bool *async)
{
  CURLcode result=CURLE_OK;
  long timeout_ms = Curl_timeleft(conn, NULL, TRUE);

  /*************************************************************
   * Resolve the name of the server or proxy
   *************************************************************/
  if(conn->bits.reuse) {
    /* We're reusing the connection - no need to resolve anything */
    *async = FALSE;

    if(conn->bits.proxy)
      fix_hostname(data, conn, &conn->host);
  }
  else {
    /* this is a fresh connect */
    int rc;
    struct Curl_dns_entry *hostaddr;

    /* set a pointer to the hostname we display */
    fix_hostname(data, conn, &conn->host);

    if(!conn->proxy.name || !*conn->proxy.name) {
      /* If not connecting via a proxy, extract the port from the URL, if it is
       * there, thus overriding any defaults that might have been set above. */
      conn->port =  conn->remote_port; /* it is the same port */

      /* Resolve target host right on */
      rc = Curl_resolv_timeout(conn, conn->host.name, (int)conn->port,
                               &hostaddr, timeout_ms);
      if(rc == CURLRESOLV_PENDING)
        *async = TRUE;

      else if (rc == CURLRESOLV_TIMEDOUT)
        result = CURLE_OPERATION_TIMEDOUT;

      else if(!hostaddr) {
        failf(data, "Couldn't resolve host '%s'", conn->host.dispname);
        result =  CURLE_COULDNT_RESOLVE_HOST;
        /* don't return yet, we need to clean up the timeout first */
      }
    }
    else {
      /* This is a proxy that hasn't been resolved yet. */

      /* IDN-fix the proxy name */
      fix_hostname(data, conn, &conn->proxy);

      /* resolve proxy */
      rc = Curl_resolv_timeout(conn, conn->proxy.name, (int)conn->port,
                               &hostaddr, timeout_ms);
      else if (rc == CURLRESOLV_TIMEDOUT)
        result = CURLE_OPERATION_TIMEDOUT;

      else if(!hostaddr) {
        failf(data, "Couldn't resolve proxy '%s'", conn->proxy.dispname);
        result = CURLE_COULDNT_RESOLVE_PROXY;
        /* don't return yet, we need to clean up the timeout first */
      }
    }
    DEBUGASSERT(conn->dns_entry == NULL);
    conn->dns_entry = hostaddr;
  }

  return result;
}

/*
 * Cleanup the connection just allocated before we can move along and use the
 * previously existing one.  All relevant data is copied over and old_conn is
 * ready for freeing once this function returns.
 */
static void reuse_conn(struct connectdata *old_conn,
                       struct connectdata *conn)
{
  if(old_conn->proxy.rawalloc)
    free(old_conn->proxy.rawalloc);

  /* free the SSL config struct from this connection struct as this was
     allocated in vain and is targeted for destruction */
  Curl_free_ssl_config(&old_conn->ssl_config);

  conn->data = old_conn->data;

  /* get the user+password information from the old_conn struct since it may
   * be new for this request even when we re-use an existing connection */
  conn->bits.user_passwd = old_conn->bits.user_passwd;
  if(conn->bits.user_passwd) {
    /* use the new user name and password though */
    Curl_safefree(conn->user);
    Curl_safefree(conn->passwd);
    conn->user = old_conn->user;
    conn->passwd = old_conn->passwd;
    old_conn->user = NULL;
    old_conn->passwd = NULL;
  }

  conn->bits.proxy_user_passwd = old_conn->bits.proxy_user_passwd;
  if(conn->bits.proxy_user_passwd) {
    /* use the new proxy user name and proxy password though */
    Curl_safefree(conn->proxyuser);
    Curl_safefree(conn->proxypasswd);
    conn->proxyuser = old_conn->proxyuser;
    conn->proxypasswd = old_conn->proxypasswd;
    old_conn->proxyuser = NULL;
    old_conn->proxypasswd = NULL;
  }

  /* host can change, when doing keepalive with a proxy ! */
  if(conn->bits.proxy) {
    free(conn->host.rawalloc);
    conn->host=old_conn->host;
  }
  else
    free(old_conn->host.rawalloc); /* free the newly allocated name buffer */

  /* re-use init */
  conn->bits.reuse = TRUE; /* yes, we're re-using here */

  Curl_safefree(old_conn->user);
  Curl_safefree(old_conn->passwd);
  Curl_safefree(old_conn->proxyuser);
  Curl_safefree(old_conn->proxypasswd);
  Curl_llist_destroy(old_conn->send_pipe, NULL);
  Curl_llist_destroy(old_conn->recv_pipe, NULL);
  Curl_llist_destroy(old_conn->pend_pipe, NULL);
  Curl_llist_destroy(old_conn->done_pipe, NULL);
  Curl_safefree(old_conn->master_buffer);
}

/**
 * create_conn() sets up a new connectdata struct, or re-uses an already
 * existing one, and resolves host name.
 *
 * if this function returns CURLE_OK and *async is set to TRUE, the resolve
 * response will be coming asynchronously. If *async is FALSE, the name is
 * already resolved.
 *
 * @param data The sessionhandle pointer
 * @param in_connect is set to the next connection data pointer
 * @param async is set TRUE when an async DNS resolution is pending
 * @see setup_conn()
 *
 * *NOTE* this function assigns the conn->data pointer!
 */

static CURLcode create_conn(struct SessionHandle *data,
                            struct connectdata **in_connect,
                            bool *async)
{
  CURLcode result=CURLE_OK;
  struct connectdata *conn;
  struct connectdata *conn_temp = NULL;
  size_t urllen;
  char user[MAX_CURL_USER_LENGTH];
  char passwd[MAX_CURL_PASSWORD_LENGTH];
  bool reuse;
  char *proxy = NULL;
  /*************************************************************
   * Check input data
   *************************************************************/

  if(!data->change.url)
    return CURLE_URL_MALFORMAT;

  /* First, split up the current URL in parts so that we can use the
     parts for checking against the already present connections. In order
     to not have to modify everything at once, we allocate a temporary
     connection data struct and fill in for comparison purposes. */
  conn = allocate_conn(data);
  if(!conn)
    return CURLE_OUT_OF_MEMORY;

  /* We must set the return variable as soon as possible, so that our
     parent can cleanup any possible allocs we may have done before
     any failure */
  *in_connect = conn;

  /* This initing continues below, see the comment "Continue connectdata
   * initialization here" */

  /***********************************************************
   * We need to allocate memory to store the path in. We get the size of the
   * full URL to be sure, and we need to make it at least 256 bytes since
   * other parts of the code will rely on this fact
   ***********************************************************/
#define LEAST_PATH_ALLOC 256
  urllen=strlen(data->change.url);
  if(urllen < LEAST_PATH_ALLOC)
    urllen=LEAST_PATH_ALLOC;

  /*
   * We malloc() the buffers below urllen+2 to make room for to possibilities:
   * 1 - an extra terminating zero
   * 2 - an extra slash (in case a syntax like "www.host.com?moo" is used)
   */

  Curl_safefree(data->state.pathbuffer);
  data->state.pathbuffer = malloc(urllen+2);
    return CURLE_OUT_OF_MEMORY; /* really bad error */
  data->state.path = data->state.pathbuffer;
  conn->host.rawalloc = malloc(urllen+2);
  if(NULL == conn->host.rawalloc)
    return CURLE_OUT_OF_MEMORY;

  conn->host.name = conn->host.rawalloc;
  conn->host.name[0] = 0;

  result = parseurlandfillconn(data, conn, &prot_missing);
  /*************************************************************
   * No protocol part in URL was used, add it!
   *************************************************************/
    /* We're guessing prefixes here and if we're told to use a proxy or if
       we're gonna follow a Location: later or... then we need the protocol
       part added so that we have a valid URL. */
    char *reurl;

    reurl = aprintf("%s://%s", conn->handler->scheme, data->change.url);

    if(!reurl) {
      Curl_safefree(proxy);
      return CURLE_OUT_OF_MEMORY;
    }

    data->change.url = reurl;
    data->change.url_alloc = TRUE; /* free this later */
  }

  /*************************************************************
   * Parse a user name and password in the URL and strip it out
   * of the host name
   *************************************************************/
  result = parse_url_userpass(data, conn, user, passwd);
  if(result != CURLE_OK)
    return result;

  /*************************************************************
   * Extract the user and password from the authentication string
   *************************************************************/
  if(conn->bits.proxy_user_passwd) {
    result = parse_proxy_auth(data, conn);
  }

  /*************************************************************
   * Detect what (if any) proxy to use
   *************************************************************/
    proxy = strdup(data->set.str[STRING_PROXY]);
    /* if global proxy is set, this is it */
    if(NULL == proxy) {
      failf(data, "memory shortage");
      return CURLE_OUT_OF_MEMORY;
    }
  }

  if(data->set.str[STRING_NOPROXY] &&
     check_noproxy(conn->host.name, data->set.str[STRING_NOPROXY])) {
    if(proxy) {
      free(proxy);  /* proxy is in exception list */
      proxy = NULL;
    }
  }
    free(proxy);  /* Don't bother with an empty proxy string */
  }
  /* proxy must be freed later unless NULL */
  if(proxy) {
    long bits = conn->protocol & (PROT_HTTPS|PROT_SSL);
    if((conn->proxytype == CURLPROXY_HTTP) ||
       (conn->proxytype == CURLPROXY_HTTP_1_0)) {
      /* force this connection's protocol to become HTTP */
      conn->protocol = PROT_HTTP | bits;
      conn->bits.httpproxy = TRUE;
    }
    conn->bits.proxy = TRUE;
  }
  else {
    /* we aren't using the proxy after all... */
    conn->bits.proxy = FALSE;
    conn->bits.httpproxy = FALSE;
    conn->bits.proxy_user_passwd = FALSE;
    conn->bits.tunnel_proxy = FALSE;

  /***********************************************************************
   * If this is supposed to use a proxy, we need to figure out the proxy
   * host name, so that we can re-use an existing connection
   * that may exist registered to the same proxy host.
   ***********************************************************************/
    result = parse_proxy(data, conn, proxy);
    /* parse_proxy has freed the proxy string, so don't try to use it again */
    proxy = NULL;
#endif /* CURL_DISABLE_PROXY */
  /*************************************************************
   * Setup internals depending on protocol. Needs to be done after
   * we figured out what/if proxy to use.
   *************************************************************/
  result = setup_connection_internals(conn);
  if(result != CURLE_OK) {
    Curl_safefree(proxy);
    return result;
  }

  conn->recv[FIRSTSOCKET] = Curl_recv_plain;
  conn->send[FIRSTSOCKET] = Curl_send_plain;
  conn->recv[SECONDARYSOCKET] = Curl_recv_plain;
  conn->send[SECONDARYSOCKET] = Curl_send_plain;
  /***********************************************************************
   * file: is a special case in that it doesn't need a network connection
   ***********************************************************************/
#ifndef CURL_DISABLE_FILE
  if(conn->protocol & PROT_FILE) {
    bool done;
    /* this is supposed to be the connect function so we better at least check
       that the file is present here! */
    DEBUGASSERT(conn->handler->connect_it);
    result = conn->handler->connect_it(conn, &done);
    /* Setup a "faked" transfer that'll do nothing */
    if(CURLE_OK == result) {
      conn->data = data;
      conn->bits.tcpconnect = TRUE; /* we are "connected */
      /*
       * Setup whatever necessary for a resumed transfer
       */
      result = setup_range(data);
      if(result) {
        DEBUGASSERT(conn->handler->done);
        /* we ignore the return code for the protocol-specific DONE */
        (void)conn->handler->done(conn, result, FALSE);
        return result;
      Curl_setup_transfer(conn, -1, -1, FALSE, NULL, /* no download */
                          -1, NULL); /* no upload */
  /*************************************************************
   * If the protocol is using SSL and HTTP proxy is used, we set
   * the tunnel_proxy bit.
   *************************************************************/
  if((conn->protocol&PROT_SSL) && conn->bits.httpproxy)
    conn->bits.tunnel_proxy = TRUE;
  /*************************************************************
   * Figure out the remote port number and fix it in the URL
   *************************************************************/
  result = parse_remote_port(data, conn);
  if(result != CURLE_OK)
    return result;
  /*************************************************************
   * Check for an overridden user name and password, then set it
   * for use
   *************************************************************/
  override_userpass(data, conn, user, passwd);
  result = set_userpass(conn, user, passwd);
  if(result != CURLE_OK)
    return result;
  /* Get a cloned copy of the SSL config situation stored in the
     connection struct. But to get this going nicely, we must first make
     sure that the strings in the master copy are pointing to the correct
     strings in the session handle strings array!

     Keep in mind that the pointers in the master copy are pointing to strings
     that will be freed as part of the SessionHandle struct, but all cloned
     copies will be separately allocated.
  */
  data->set.ssl.CApath = data->set.str[STRING_SSL_CAPATH];
  data->set.ssl.CAfile = data->set.str[STRING_SSL_CAFILE];
  data->set.ssl.CRLfile = data->set.str[STRING_SSL_CRLFILE];
  data->set.ssl.issuercert = data->set.str[STRING_SSL_ISSUERCERT];
  data->set.ssl.random_file = data->set.str[STRING_SSL_RANDOM_FILE];
  data->set.ssl.egdsocket = data->set.str[STRING_SSL_EGDSOCKET];
  data->set.ssl.cipher_list = data->set.str[STRING_SSL_CIPHER_LIST];

  if(!Curl_clone_ssl_config(&data->set.ssl, &conn->ssl_config))
    return CURLE_OUT_OF_MEMORY;

  /*************************************************************
   * Check the current list of connections to see if we can
   * re-use an already existing one or if we have to create a
   * new one.
   *************************************************************/

  /* reuse_fresh is TRUE if we are told to use a new connection by force, but
     we only acknowledge this option if this is not a re-used connection
     already (which happens due to follow-location or during a HTTP
     authentication phase). */
  if(data->set.reuse_fresh && !data->state.this_is_a_follow)
    reuse = ConnectionExists(data, conn, &conn_temp);

  if(reuse) {
    /*
     * We already have a connection for this, we got the former connection
     * in the conn_temp variable and thus we need to cleanup the one we
     * just allocated before we can move along and use the previously
     * existing one.
     */
    reuse_conn(conn, conn_temp);
    free(conn);          /* we don't need this anymore */
    conn = conn_temp;
    *in_connect = conn;
    infof(data, "Re-using existing connection! (#%ld) with host %s\n",
          conn->proxy.name?conn->proxy.dispname:conn->host.dispname);
    /* copy this IP address to the common buffer for the easy handle so that
       the address can actually survice the removal of this connection. strcpy
       is safe since the target buffer is big enough to hold the largest
       possible IP address */
    strcpy(data->info.ip, conn->ip_addr_str);

  }
  else {
    /*
     * This is a brand new connection, so let's store it in the connection
     * cache of ours!
     */
    ConnectionStore(data, conn);
  }

  /*
   * Setup whatever necessary for a resumed transfer
   */
  /* Continue connectdata initialization here. */

  /*
   * Inherit the proper values from the urldata struct AFTER we have arranged
  conn->fread_func = data->set.fread_func;
  conn->seek_func = data->set.seek_func;
  conn->seek_client = data->set.seek_client;
Daniel Stenberg's avatar
Daniel Stenberg committed
  /*************************************************************
   * Resolve the address of the server or proxy
Daniel Stenberg's avatar
Daniel Stenberg committed
   *************************************************************/
  result = resolve_server(data, conn, async);
/* setup_conn() is called after the name resolve initiated in
 * create_conn() is all done.
 * setup_conn() also handles reused connections
 * conn->data MUST already have been setup fine (in create_conn)
static CURLcode setup_conn(struct connectdata *conn,
  struct SessionHandle *data = conn->data;
    /* There's nothing in this function to setup if we're only doing
       a file:// transfer */
  }
  *protocol_done = FALSE; /* default to not done */
Daniel Stenberg's avatar
Daniel Stenberg committed

  /* set proxy_connect_closed to false unconditionally already here since it
     is used strictly to provide extra information to a parent function in the
     case of proxy CONNECT failures and we must make sure we don't have it
     lingering set from a previous invoke */
  conn->bits.proxy_connect_closed = FALSE;

  /*
   * Set user-agent. Used for HTTP, but since we can attempt to tunnel