/* Returns timeout in ms. 0 or negative number means the timeout has already triggered */ long Curl_pp_state_timeout(struct pingpong *pp) { struct connectdata *conn = pp->conn; struct Curl_easy *data=conn->data; long timeout_ms; /* in milliseconds */ long timeout2_ms; /* in milliseconds */ long response_time= (data->set.server_response_timeout)? data->set.server_response_timeout: pp->response_time; /* if CURLOPT_SERVER_RESPONSE_TIMEOUT is set, use that to determine remaining time, or use pp->response because SERVER_RESPONSE_TIMEOUT is supposed to govern the response for any given server response, not for the time from connect to the given server response. */ /* Without a requested timeout, we only wait 'response_time' seconds for the full response to arrive before we bail out */ timeout_ms = response_time - Curl_tvdiff(Curl_tvnow(), pp->response); /* spent time */ if(data->set.timeout) { /* if timeout is requested, find out how much remaining time we have */ timeout2_ms = data->set.timeout - /* timeout time */ Curl_tvdiff(Curl_tvnow(), conn->now); /* spent time */ /* pick the lowest number */ timeout_ms = CURLMIN(timeout_ms, timeout2_ms); } return timeout_ms; }
/* Returns timeout in ms. 0 or negative number means the timeout has already triggered */ long Curl_pp_state_timeout(struct pingpong *pp) { struct connectdata *conn = pp->conn; struct SessionHandle *data=conn->data; long timeout_ms=360000; /* in milliseconds */ if(data->set.server_response_timeout ) /* if CURLOPT_SERVER_RESPONSE_TIMEOUT is set, use that to determine remaining time. Also, use pp->response because SERVER_RESPONSE_TIMEOUT is supposed to govern the response for any given server response, not for the time from connect to the given server response. */ timeout_ms = data->set.server_response_timeout - /* timeout time */ Curl_tvdiff(Curl_tvnow(), pp->response); /* spent time */ else if(data->set.timeout) /* if timeout is requested, find out how much remaining time we have */ timeout_ms = data->set.timeout - /* timeout time */ Curl_tvdiff(Curl_tvnow(), conn->now); /* spent time */ else /* Without a requested timeout, we only wait 'response_time' seconds for the full response to arrive before we bail out */ timeout_ms = pp->response_time - Curl_tvdiff(Curl_tvnow(), pp->response); /* spent time */ return timeout_ms; }
/* * Curl_timeleft() returns the amount of milliseconds left allowed for the * transfer/connection. If the value is negative, the timeout time has already * elapsed. * * The start time is stored in progress.t_startsingle - as set with * Curl_pgrsTime(..., TIMER_STARTSINGLE); * * If 'nowp' is non-NULL, it points to the current time. * 'duringconnect' is FALSE if not during a connect, as then of course the * connect timeout is not taken into account! * * @unittest: 1303 */ long Curl_timeleft(struct SessionHandle *data, struct timeval *nowp, bool duringconnect) { int timeout_set = 0; long timeout_ms = duringconnect?DEFAULT_CONNECT_TIMEOUT:0; struct timeval now; /* if a timeout is set, use the most restrictive one */ if(data->set.timeout > 0) timeout_set |= 1; if(duringconnect && (data->set.connecttimeout > 0)) timeout_set |= 2; switch (timeout_set) { case 1: timeout_ms = data->set.timeout; break; case 2: timeout_ms = data->set.connecttimeout; break; case 3: if(data->set.timeout < data->set.connecttimeout) timeout_ms = data->set.timeout; else timeout_ms = data->set.connecttimeout; break; default: /* use the default */ if(!duringconnect) /* if we're not during connect, there's no default timeout so if we're at zero we better just return zero and not make it a negative number by the math below */ return 0; break; } if(!nowp) { now = Curl_tvnow(); nowp = &now; } /* subtract elapsed time */ if(duringconnect) /* since this most recent connect started */ timeout_ms -= Curl_tvdiff(*nowp, data->progress.t_startsingle); else /* since the entire operation started */ timeout_ms -= Curl_tvdiff(*nowp, data->progress.t_startop); if(!timeout_ms) /* avoid returning 0 as that means no timeout! */ return -1; return timeout_ms; }
CURLcode Curl_speedcheck(struct SessionHandle *data, struct timeval now) { if((data->progress.current_speed >= 0) && data->set.low_speed_time && (Curl_tvlong(data->state.keeps_speed) != 0) && (data->progress.current_speed < data->set.low_speed_limit)) { long howlong = Curl_tvdiff(now, data->state.keeps_speed); /* We are now below the "low speed limit". If we are below it for "low speed time" seconds we consider that enough reason to abort the download. */ if( (howlong/1000) > data->set.low_speed_time) { /* we have been this slow for long enough, now die */ failf(data, "Operation too slow. " "Less than %d bytes/sec transfered the last %d seconds", data->set.low_speed_limit, data->set.low_speed_time); return CURLE_OPERATION_TIMEOUTED; } Curl_expire(data, howlong); } else { /* we keep up the required speed all right */ data->state.keeps_speed = now; } return CURLE_OK; }
/* * Curl_is_resolved() is called repeatedly to check if a previous name resolve * request has completed. It should also make sure to time-out if the * operation seems to take too long. */ CURLcode Curl_is_resolved(struct connectdata *conn, struct Curl_dns_entry **entry) { struct SessionHandle *data = conn->data; struct thread_data *td = (struct thread_data*) conn->async.os_specific; int done = 0; *entry = NULL; if (!td) { DEBUGASSERT(td); return CURLE_COULDNT_RESOLVE_HOST; } Curl_mutex_acquire(td->tsd.mtx); done = td->tsd.done; Curl_mutex_release(td->tsd.mtx); if (done) { getaddrinfo_complete(conn); if (td->poll_interval != 0) Curl_expire(conn->data, 0); Curl_destroy_thread_data(&conn->async); if(!conn->async.dns) { failf(data, "Could not resolve host: %s; %s", conn->host.name, Curl_strerror(conn, conn->async.status)); return CURLE_COULDNT_RESOLVE_HOST; } *entry = conn->async.dns; } else { /* poll for name lookup done with exponential backoff up to 250ms */ int elapsed; elapsed = Curl_tvdiff(Curl_tvnow(), data->progress.t_startsingle); if (elapsed < 0) { elapsed = 0; } if (td->poll_interval == 0) { /* Start at 1ms poll interval */ td->poll_interval = 1; } else if (elapsed >= td->interval_end) { /* Back-off exponentially if last interval expired */ td->poll_interval *= 2; } if (td->poll_interval > 250) td->poll_interval = 250; td->interval_end = elapsed + td->poll_interval; Curl_expire(conn->data, td->poll_interval); } return CURLE_OK; }
/* * Helper read-from-socket functions. Does the same as Curl_read() but it * blocks until all bytes amount of buffersize will be read. No more, no less. * * This is STUPID BLOCKING behaviour which we frown upon, but right now this * is what we have... */ int Curl_blockread_all(struct connectdata *conn, /* connection data */ curl_socket_t sockfd, /* read from this socket */ char *buf, /* store read data here */ ssize_t buffersize, /* max amount to read */ ssize_t *n, /* amount bytes read */ long conn_timeout) /* timeout for data wait relative to conn->created */ { ssize_t nread; ssize_t allread = 0; int result; struct timeval tvnow; long conntime; *n = 0; for(;;) { tvnow = Curl_tvnow(); /* calculating how long connection is establishing */ conntime = Curl_tvdiff(tvnow, conn->created); if(conntime > conn_timeout) { /* we already got the timeout */ result = CURLE_OPERATION_TIMEDOUT; break; } if(Curl_socket_ready(sockfd, CURL_SOCKET_BAD, (int)(conn_timeout - conntime)) <= 0) { result = ~CURLE_OK; break; } result = Curl_read_plain(sockfd, buf, buffersize, &nread); if(CURLE_AGAIN == result) continue; else if(result) break; if(buffersize == nread) { allread += nread; *n = allread; result = CURLE_OK; break; } if(!nread) { result = ~CURLE_OK; break; } buffersize -= nread; buf += nread; allread += nread; } return result; }
/* * Curl_resolver_is_resolved() is called repeatedly to check if a previous * name resolve request has completed. It should also make sure to time-out if * the operation seems to take too long. */ CURLcode Curl_resolver_is_resolved(struct connectdata *conn, struct Curl_dns_entry **entry) { struct Curl_easy *data = conn->data; struct thread_data *td = (struct thread_data*) conn->async.os_specific; int done = 0; *entry = NULL; if(!td) { DEBUGASSERT(td); return CURLE_COULDNT_RESOLVE_HOST; } Curl_mutex_acquire(td->tsd.mtx); done = td->tsd.done; Curl_mutex_release(td->tsd.mtx); if(done) { getaddrinfo_complete(conn); if(!conn->async.dns) { CURLcode result = resolver_error(conn); destroy_async_data(&conn->async); return result; } destroy_async_data(&conn->async); *entry = conn->async.dns; } else { /* poll for name lookup done with exponential backoff up to 250ms */ long elapsed = Curl_tvdiff(Curl_tvnow(), data->progress.t_startsingle); if(elapsed < 0) elapsed = 0; if(td->poll_interval == 0) /* Start at 1ms poll interval */ td->poll_interval = 1; else if(elapsed >= td->interval_end) /* Back-off exponentially if last interval expired */ td->poll_interval *= 2; if(td->poll_interval > 250) td->poll_interval = 250; td->interval_end = elapsed + td->poll_interval; Curl_expire(conn->data, td->poll_interval); } return CURLE_OK; }
CURLcode Curl_speedcheck(struct Curl_easy *data, struct timeval now) { if((data->progress.current_speed >= 0) && data->set.low_speed_time && (Curl_tvlong(data->state.keeps_speed) != 0) && (data->progress.current_speed < data->set.low_speed_limit)) { long howlong = Curl_tvdiff(now, data->state.keeps_speed); long nextcheck = (data->set.low_speed_time * 1000) - howlong; /* We are now below the "low speed limit". If we are below it for "low speed time" seconds we consider that enough reason to abort the download. */ if(nextcheck <= 0) { /* we have been this slow for long enough, now die */ failf(data, "Operation too slow. " "Less than %ld bytes/sec transferred the last %ld seconds", data->set.low_speed_limit, data->set.low_speed_time); return CURLE_OPERATION_TIMEDOUT; } else { /* wait complete low_speed_time */ Curl_expire_latest(data, nextcheck); } } else { /* we keep up the required speed all right */ data->state.keeps_speed = now; if(data->set.low_speed_limit) /* if there is a low speed limit enabled, we set the expire timer to make this connection's speed get checked again no later than when this time is up */ Curl_expire_latest(data, data->set.low_speed_time*1000); } return CURLE_OK; }
int Curl_resolv_timeout(struct connectdata *conn, const char *hostname, int port, struct Curl_dns_entry **entry, long timeoutms) { #ifdef USE_ALARM_TIMEOUT #ifdef HAVE_SIGACTION struct sigaction keep_sigact; /* store the old struct here */ volatile bool keep_copysig = FALSE; /* wether old sigact has been saved */ struct sigaction sigact; #else #ifdef HAVE_SIGNAL void (*keep_sigact)(int); /* store the old handler here */ #endif /* HAVE_SIGNAL */ #endif /* HAVE_SIGACTION */ volatile long timeout; volatile unsigned int prev_alarm = 0; struct SessionHandle *data = conn->data; #endif /* USE_ALARM_TIMEOUT */ int rc; *entry = NULL; #ifdef USE_ALARM_TIMEOUT if (data->set.no_signal) /* Ignore the timeout when signals are disabled */ timeout = 0; else timeout = timeoutms; if(!timeout) /* USE_ALARM_TIMEOUT defined, but no timeout actually requested */ return Curl_resolv(conn, hostname, port, entry); if(timeout < 1000) /* The alarm() function only provides integer second resolution, so if we want to wait less than one second we must bail out already now. */ return CURLRESOLV_TIMEDOUT; /************************************************************* * Set signal handler to catch SIGALRM * Store the old value to be able to set it back later! *************************************************************/ #ifdef HAVE_SIGACTION sigaction(SIGALRM, NULL, &sigact); keep_sigact = sigact; keep_copysig = TRUE; /* yes, we have a copy */ sigact.sa_handler = alarmfunc; #ifdef SA_RESTART /* HPUX doesn't have SA_RESTART but defaults to that behaviour! */ sigact.sa_flags &= ~SA_RESTART; #endif /* now set the new struct */ sigaction(SIGALRM, &sigact, NULL); #else /* HAVE_SIGACTION */ /* no sigaction(), revert to the much lamer signal() */ #ifdef HAVE_SIGNAL keep_sigact = signal(SIGALRM, alarmfunc); #endif #endif /* HAVE_SIGACTION */ /* alarm() makes a signal get sent when the timeout fires off, and that will abort system calls */ prev_alarm = alarm(curlx_sltoui(timeout/1000L)); /* This allows us to time-out from the name resolver, as the timeout will generate a signal and we will siglongjmp() from that here. This technique has problems (see alarmfunc). This should be the last thing we do before calling Curl_resolv(), as otherwise we'd have to worry about variables that get modified before we invoke Curl_resolv() (and thus use "volatile"). */ if(sigsetjmp(curl_jmpenv, 1)) { /* this is coming from a siglongjmp() after an alarm signal */ failf(data, "name lookup timed out"); rc = CURLRESOLV_ERROR; goto clean_up; } #else #ifndef CURLRES_ASYNCH if(timeoutms) infof(conn->data, "timeout on name lookup is not supported\n"); #else (void)timeoutms; /* timeoutms not used with an async resolver */ #endif #endif /* USE_ALARM_TIMEOUT */ /* Perform the actual name resolution. This might be interrupted by an * alarm if it takes too long. */ rc = Curl_resolv(conn, hostname, port, entry); #ifdef USE_ALARM_TIMEOUT clean_up: if(!prev_alarm) /* deactivate a possibly active alarm before uninstalling the handler */ alarm(0); #ifdef HAVE_SIGACTION if(keep_copysig) { /* we got a struct as it looked before, now put that one back nice and clean */ sigaction(SIGALRM, &keep_sigact, NULL); /* put it back */ } #else #ifdef HAVE_SIGNAL /* restore the previous SIGALRM handler */ signal(SIGALRM, keep_sigact); #endif #endif /* HAVE_SIGACTION */ /* switch back the alarm() to either zero or to what it was before minus the time we spent until now! */ if(prev_alarm) { /* there was an alarm() set before us, now put it back */ unsigned long elapsed_ms = Curl_tvdiff(Curl_tvnow(), conn->created); /* the alarm period is counted in even number of seconds */ unsigned long alarm_set = prev_alarm - elapsed_ms/1000; if(!alarm_set || ((alarm_set >= 0x80000000) && (prev_alarm < 0x80000000)) ) { /* if the alarm time-left reached zero or turned "negative" (counted with unsigned values), we should fire off a SIGALRM here, but we won't, and zero would be to switch it off so we never set it to less than 1! */ alarm(1); rc = CURLRESOLV_TIMEDOUT; failf(data, "Previous alarm fired off!"); } else alarm((unsigned int)alarm_set); } #endif /* USE_ALARM_TIMEOUT */ return rc; }
/* * Curl_resolver_wait_resolv() * * waits for a resolve to finish. This function should be avoided since using * this risk getting the multi interface to "hang". * * If 'entry' is non-NULL, make it point to the resolved dns entry * * Returns CURLE_COULDNT_RESOLVE_HOST if the host was not resolved, and * CURLE_OPERATION_TIMEDOUT if a time-out occurred. */ CURLcode Curl_resolver_wait_resolv(struct connectdata *conn, struct Curl_dns_entry **entry) { CURLcode result = CURLE_OK; struct Curl_easy *data = conn->data; long timeout; struct timeval now = Curl_tvnow(); struct Curl_dns_entry *temp_entry; if(entry) *entry = NULL; /* clear on entry */ timeout = Curl_timeleft(data, &now, TRUE); if(timeout < 0) { /* already expired! */ connclose(conn, "Timed out before name resolve started"); return CURLE_OPERATION_TIMEDOUT; } if(!timeout) timeout = CURL_TIMEOUT_RESOLVE * 1000; /* default name resolve timeout */ /* Wait for the name resolve query to complete. */ while(!result) { struct timeval *tvp, tv, store; long timediff; int itimeout; int timeout_ms; itimeout = (timeout > (long)INT_MAX) ? INT_MAX : (int)timeout; store.tv_sec = itimeout/1000; store.tv_usec = (itimeout%1000)*1000; tvp = ares_timeout((ares_channel)data->state.resolver, &store, &tv); /* use the timeout period ares returned to us above if less than one second is left, otherwise just use 1000ms to make sure the progress callback gets called frequent enough */ if(!tvp->tv_sec) timeout_ms = (int)(tvp->tv_usec/1000); else timeout_ms = 1000; waitperform(conn, timeout_ms); result = Curl_resolver_is_resolved(conn, &temp_entry); if(result || conn->async.done) break; if(Curl_pgrsUpdate(conn)) result = CURLE_ABORTED_BY_CALLBACK; else { struct timeval now2 = Curl_tvnow(); timediff = Curl_tvdiff(now2, now); /* spent time */ timeout -= timediff?timediff:1; /* always deduct at least 1 */ now = now2; /* for next loop */ } if(timeout < 0) result = CURLE_OPERATION_TIMEDOUT; } if(result) /* failure, so we cancel the ares operation */ ares_cancel((ares_channel)data->state.resolver); /* Operation complete, if the lookup was successful we now have the entry in the cache. */ if(entry) *entry = conn->async.dns; if(result) /* close the connection, since we can't return failure here without cleaning up this connection properly. TODO: remove this action from here, it is not a name resolver decision. */ connclose(conn, "c-ares resolve failed"); return result; }
CURLcode Curl_is_connected(struct connectdata *conn, curl_socket_t sockfd, bool *connected) { int rc; struct SessionHandle *data = conn->data; *connected = FALSE; /* a very negative world view is best */ if(data->set.timeout || data->set.connecttimeout) { /* there is a timeout set */ /* Evaluate in milliseconds how much time that has passed */ long has_passed = Curl_tvdiff(Curl_tvnow(), data->progress.start); /* subtract the most strict timeout of the ones */ if(data->set.timeout && data->set.connecttimeout) { if (data->set.timeout < data->set.connecttimeout) has_passed -= data->set.timeout*1000; else has_passed -= data->set.connecttimeout*1000; } else if(data->set.timeout) has_passed -= data->set.timeout*1000; else has_passed -= data->set.connecttimeout*1000; if(has_passed > 0 ) { /* time-out, bail out, go home */ failf(data, "Connection time-out"); return CURLE_OPERATION_TIMEOUTED; } } if(conn->bits.tcpconnect) { /* we are connected already! */ *connected = TRUE; return CURLE_OK; } /* check for connect without timeout as we want to return immediately */ rc = waitconnect(sockfd, 0); if(0 == rc) { if (verifyconnect(sockfd)) { /* we are connected, awesome! */ *connected = TRUE; return CURLE_OK; } /* nope, not connected for real */ failf(data, "Connection failed"); return CURLE_COULDNT_CONNECT; } else if(1 != rc) { int error = Curl_ourerrno(); failf(data, "Failed connect to %s:%d, errno: %d", conn->hostname, conn->port, error); return CURLE_COULDNT_CONNECT; } /* * If the connection phase is "done" here, we should attempt to connect * to the "next address" in the Curl_hostaddr structure that we resolved * before. But we don't have that struct around anymore and we can't just * keep a pointer since the cache might in fact have gotten pruned by the * time we want to read this... Alas, we don't do this yet. */ return CURLE_OK; }
/* This is a function that locks and waits until the name resolve operation has completed. If 'entry' is non-NULL, make it point to the resolved dns entry Return CURLE_COULDNT_RESOLVE_HOST if the host was not resolved, and CURLE_OPERATION_TIMEDOUT if a time-out occurred. */ CURLcode Curl_wait_for_resolv(struct connectdata *conn, struct Curl_dns_entry **entry) { CURLcode rc=CURLE_OK; struct SessionHandle *data = conn->data; struct timeval now = Curl_tvnow(); bool timedout = FALSE; long timeout = 300; /* default name resolve timeout in seconds */ long elapsed = 0; /* time taken so far */ /* now, see if there's a connect timeout or a regular timeout to use instead of the default one */ if(conn->data->set.connecttimeout) timeout = conn->data->set.connecttimeout; else if(conn->data->set.timeout) timeout = conn->data->set.timeout; /* Wait for the name resolve query to complete. */ while (1) { int nfds=0; fd_set read_fds, write_fds; struct timeval *tvp, tv, store; int count; store.tv_sec = (int)(timeout - elapsed); store.tv_usec = 0; FD_ZERO(&read_fds); FD_ZERO(&write_fds); nfds = ares_fds(data->state.areschannel, &read_fds, &write_fds); if (nfds == 0) break; tvp = ares_timeout(data->state.areschannel, &store, &tv); count = select(nfds, &read_fds, &write_fds, NULL, tvp); if (count < 0 && errno != EINVAL) break; else if(!count) { /* timeout */ timedout = TRUE; break; } ares_process(data->state.areschannel, &read_fds, &write_fds); elapsed = Curl_tvdiff(Curl_tvnow(), now)/1000; /* spent time */ } /* Operation complete, if the lookup was successful we now have the entry in the cache. */ if(entry) *entry = conn->async.dns; if(!conn->async.dns) { /* a name was not resolved */ if(timedout || (conn->async.status == ARES_ETIMEOUT)) { failf(data, "Resolving host timed out: %s", conn->name); rc = CURLE_OPERATION_TIMEDOUT; } else if(conn->async.done) { failf(data, "Could not resolve host: %s (%s)", conn->name, ares_strerror(conn->async.status)); rc = CURLE_COULDNT_RESOLVE_HOST; } else rc = CURLE_OPERATION_TIMEDOUT; /* close the connection, since we can't return failure here without cleaning up this connection properly */ Curl_disconnect(conn); } return rc; }
CURLcode Curl_telnet(struct connectdata *conn, bool *done) { CURLcode code; struct SessionHandle *data = conn->data; curl_socket_t sockfd = conn->sock[FIRSTSOCKET]; #ifdef USE_WINSOCK HMODULE wsock2; WSOCK2_FUNC close_event_func; WSOCK2_FUNC create_event_func; WSOCK2_FUNC event_select_func; WSOCK2_FUNC enum_netevents_func; WSAEVENT event_handle; WSANETWORKEVENTS events; HANDLE stdin_handle; HANDLE objs[2]; DWORD obj_count; DWORD wait_timeout; DWORD waitret; DWORD readfile_read; #else int interval_ms; struct pollfd pfd[2]; #endif ssize_t nread; bool keepon = TRUE; char *buf = data->state.buffer; struct TELNET *tn; *done = TRUE; /* uncontionally */ code = init_telnet(conn); if(code) return code; tn = (struct TELNET *)data->reqdata.proto.telnet; code = check_telnet_options(conn); if(code) return code; #ifdef USE_WINSOCK /* ** This functionality only works with WinSock >= 2.0. So, ** make sure have it. */ code = check_wsock2(data); if (code) return code; /* OK, so we have WinSock 2.0. We need to dynamically */ /* load ws2_32.dll and get the function pointers we need. */ wsock2 = LoadLibrary("WS2_32.DLL"); if (wsock2 == NULL) { failf(data,"failed to load WS2_32.DLL (%d)", ERRNO); return CURLE_FAILED_INIT; } /* Grab a pointer to WSACreateEvent */ create_event_func = GetProcAddress(wsock2,"WSACreateEvent"); if (create_event_func == NULL) { failf(data,"failed to find WSACreateEvent function (%d)", ERRNO); FreeLibrary(wsock2); return CURLE_FAILED_INIT; } /* And WSACloseEvent */ close_event_func = GetProcAddress(wsock2,"WSACloseEvent"); if (close_event_func == NULL) { failf(data,"failed to find WSACloseEvent function (%d)", ERRNO); FreeLibrary(wsock2); return CURLE_FAILED_INIT; } /* And WSAEventSelect */ event_select_func = GetProcAddress(wsock2,"WSAEventSelect"); if (event_select_func == NULL) { failf(data,"failed to find WSAEventSelect function (%d)", ERRNO); FreeLibrary(wsock2); return CURLE_FAILED_INIT; } /* And WSAEnumNetworkEvents */ enum_netevents_func = GetProcAddress(wsock2,"WSAEnumNetworkEvents"); if (enum_netevents_func == NULL) { failf(data,"failed to find WSAEnumNetworkEvents function (%d)", ERRNO); FreeLibrary(wsock2); return CURLE_FAILED_INIT; } /* We want to wait for both stdin and the socket. Since ** the select() function in winsock only works on sockets ** we have to use the WaitForMultipleObjects() call. */ /* First, create a sockets event object */ event_handle = (WSAEVENT)create_event_func(); if (event_handle == WSA_INVALID_EVENT) { failf(data,"WSACreateEvent failed (%d)", SOCKERRNO); FreeLibrary(wsock2); return CURLE_FAILED_INIT; } /* The get the Windows file handle for stdin */ stdin_handle = GetStdHandle(STD_INPUT_HANDLE); /* Create the list of objects to wait for */ objs[0] = event_handle; objs[1] = stdin_handle; /* Tell winsock what events we want to listen to */ if(event_select_func(sockfd, event_handle, FD_READ|FD_CLOSE) == SOCKET_ERROR) { close_event_func(event_handle); FreeLibrary(wsock2); return 0; } /* If stdin_handle is a pipe, use PeekNamedPipe() method to check it, else use the old WaitForMultipleObjects() way */ if(GetFileType(stdin_handle) == FILE_TYPE_PIPE) { /* Don't wait for stdin_handle, just wait for event_handle */ obj_count = 1; /* Check stdin_handle per 100 milliseconds */ wait_timeout = 100; } else { obj_count = 2; wait_timeout = INFINITE; } /* Keep on listening and act on events */ while(keepon) { waitret = WaitForMultipleObjects(obj_count, objs, FALSE, wait_timeout); switch(waitret) { case WAIT_TIMEOUT: { unsigned char outbuf[2]; int out_count = 0; ssize_t bytes_written; char *buffer = buf; while(1) { if(!PeekNamedPipe(stdin_handle, NULL, 0, NULL, &readfile_read, NULL)) { keepon = FALSE; break; } nread = readfile_read; if(!nread) break; if(!ReadFile(stdin_handle, buf, sizeof(data->state.buffer), &readfile_read, NULL)) { keepon = FALSE; break; } nread = readfile_read; while(nread--) { outbuf[0] = *buffer++; out_count = 1; if(outbuf[0] == CURL_IAC) outbuf[out_count++] = CURL_IAC; Curl_write(conn, conn->sock[FIRSTSOCKET], outbuf, out_count, &bytes_written); } } } break; case WAIT_OBJECT_0 + 1: { unsigned char outbuf[2]; int out_count = 0; ssize_t bytes_written; char *buffer = buf; if(!ReadFile(stdin_handle, buf, sizeof(data->state.buffer), &readfile_read, NULL)) { keepon = FALSE; break; } nread = readfile_read; while(nread--) { outbuf[0] = *buffer++; out_count = 1; if(outbuf[0] == CURL_IAC) outbuf[out_count++] = CURL_IAC; Curl_write(conn, conn->sock[FIRSTSOCKET], outbuf, out_count, &bytes_written); } } break; case WAIT_OBJECT_0: if(enum_netevents_func(sockfd, event_handle, &events) != SOCKET_ERROR) { if(events.lNetworkEvents & FD_READ) { /* This reallu OUGHT to check its return code. */ (void)Curl_read(conn, sockfd, buf, BUFSIZE - 1, &nread); telrcv(conn, (unsigned char *)buf, nread); fflush(stdout); /* Negotiate if the peer has started negotiating, otherwise don't. We don't want to speak telnet with non-telnet servers, like POP or SMTP. */ if(tn->please_negotiate && !tn->already_negotiated) { negotiate(conn); tn->already_negotiated = 1; } } if(events.lNetworkEvents & FD_CLOSE) { keepon = FALSE; } } break; } } /* We called WSACreateEvent, so call WSACloseEvent */ if (close_event_func(event_handle) == FALSE) { infof(data,"WSACloseEvent failed (%d)", SOCKERRNO); } /* "Forget" pointers into the library we're about to free */ create_event_func = NULL; close_event_func = NULL; event_select_func = NULL; enum_netevents_func = NULL; /* We called LoadLibrary, so call FreeLibrary */ if (!FreeLibrary(wsock2)) infof(data,"FreeLibrary(wsock2) failed (%d)", ERRNO); #else pfd[0].fd = sockfd; pfd[0].events = POLLIN; pfd[1].fd = 0; pfd[1].events = POLLIN; interval_ms = 1 * 1000; while (keepon) { switch (Curl_poll(pfd, 2, interval_ms)) { case -1: /* error, stop reading */ keepon = FALSE; continue; case 0: /* timeout */ break; default: /* read! */ if(pfd[1].revents & POLLIN) { /* read from stdin */ unsigned char outbuf[2]; int out_count = 0; ssize_t bytes_written; char *buffer = buf; nread = read(0, buf, 255); while(nread--) { outbuf[0] = *buffer++; out_count = 1; if(outbuf[0] == CURL_IAC) outbuf[out_count++] = CURL_IAC; Curl_write(conn, conn->sock[FIRSTSOCKET], outbuf, out_count, &bytes_written); } } if(pfd[0].revents & POLLIN) { /* This OUGHT to check the return code... */ (void)Curl_read(conn, sockfd, buf, BUFSIZE - 1, &nread); /* if we receive 0 or less here, the server closed the connection and we bail out from this! */ if (nread <= 0) { keepon = FALSE; break; } telrcv(conn, (unsigned char *)buf, nread); /* Negotiate if the peer has started negotiating, otherwise don't. We don't want to speak telnet with non-telnet servers, like POP or SMTP. */ if(tn->please_negotiate && !tn->already_negotiated) { negotiate(conn); tn->already_negotiated = 1; } } } if(data->set.timeout) { struct timeval now; /* current time */ now = Curl_tvnow(); if(Curl_tvdiff(now, conn->created) >= data->set.timeout) { failf(data, "Time-out"); code = CURLE_OPERATION_TIMEDOUT; keepon = FALSE; } } } #endif /* mark this as "no further transfer wanted" */ Curl_setup_transfer(conn, -1, -1, FALSE, NULL, -1, NULL); return code; }
CURLcode Curl_ConnectHTTPProxyTunnel(struct connectdata *conn, int tunnelsocket, char *hostname, int remote_port) { int httperror=0; int subversion=0; struct SessionHandle *data=conn->data; CURLcode result; int res; int nread; /* total size read */ int perline; /* count bytes per line */ bool keepon=TRUE; ssize_t gotbytes; char *ptr; int timeout = 3600; /* default timeout in seconds */ struct timeval interval; fd_set rkeepfd; fd_set readfd; char *line_start; #define SELECT_OK 0 #define SELECT_ERROR 1 #define SELECT_TIMEOUT 2 int error = SELECT_OK; infof(data, "Establish HTTP proxy tunnel to %s:%d\n", hostname, remote_port); /* OK, now send the connect request to the proxy */ result = Curl_sendf(tunnelsocket, conn, "CONNECT %s:%d HTTP/1.0\015\012" "%s" "%s" "\r\n", hostname, remote_port, (conn->bits.proxy_user_passwd)?conn->allocptr.proxyuserpwd:"", (data->set.useragent?conn->allocptr.uagent:"") ); if(result) { failf(data, "Failed sending CONNECT to proxy"); return result; } /* Now, read the full reply we get from the proxy */ if(data->set.timeout) { /* if timeout is requested, find out how much remaining time we have */ timeout = data->set.timeout - /* timeout time */ Curl_tvdiff(Curl_tvnow(), conn->now)/1000; /* spent time */ if(timeout <=0 ) { failf(data, "Transfer aborted due to timeout"); return -SELECT_TIMEOUT; /* already too little time */ } } FD_ZERO (&readfd); /* clear it */ FD_SET (tunnelsocket, &readfd); /* read socket */ /* get this in a backup variable to be able to restore it on each lap in the select() loop */ rkeepfd = readfd; ptr=data->state.buffer; line_start = ptr; nread=0; perline=0; keepon=TRUE; while((nread<BUFSIZE) && (keepon && !error)) { readfd = rkeepfd; /* set every lap */ interval.tv_sec = timeout; interval.tv_usec = 0; switch (select (tunnelsocket+1, &readfd, NULL, NULL, &interval)) { case -1: /* select() error, stop reading */ error = SELECT_ERROR; failf(data, "Transfer aborted due to select() error"); break; case 0: /* timeout */ error = SELECT_TIMEOUT; failf(data, "Transfer aborted due to 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, "Connection 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 */ int i; nread += gotbytes; for(i = 0; i < gotbytes; ptr++, i++) { perline++; /* amount of bytes in this line so far */ if(*ptr=='\n') { /* a newline is CRLF in ftp-talk, so the CR is ignored as the line isn't really terminated until the LF comes */ /* output debug output if that is requested */ if(data->set.verbose) { fputs("< ", data->set.err); fwrite(line_start, perline, 1, data->set.err); /* no need to output LF here, it is part of the data */ } if('\r' == line_start[0]) { /* end of headers */ keepon=FALSE; break; /* breaks out of loop, not switch */ } if(2 == sscanf(line_start, "HTTP/1.%d %d", &subversion, &httperror)) { ; } perline=0; /* line starts over here */ line_start = ptr+1; } } } break; } /* switch */ } /* while there's buffer left and loop is requested */ if(error) return CURLE_READ_ERROR; if(200 != httperror) { if(407 == httperror) /* Added Nov 6 1998 */ failf(data, "Proxy requires authorization!"); else failf(data, "Received error code %d from proxy", httperror); return CURLE_READ_ERROR; } infof (data, "Proxy replied to CONNECT request\n"); return CURLE_OK; }
CURLcode Curl_connecthost(struct connectdata *conn, /* context */ struct Curl_dns_entry *remotehost, /* use this one */ int port, /* connect to this */ curl_socket_t *sockconn, /* the connected socket */ Curl_ipconnect **addr, /* the one we used */ bool *connected) /* really connected? */ { struct SessionHandle *data = conn->data; int rc; curl_socket_t sockfd= CURL_SOCKET_BAD; int aliasindex=0; char *hostname; struct timeval after; struct timeval before = Curl_tvnow(); #ifdef ENABLE_IPV6 struct addrinfo *ai; #endif /************************************************************* * Figure out what maximum time we have left *************************************************************/ long timeout_ms=300000; /* milliseconds, default to five minutes */ *connected = FALSE; /* default to not connected */ if(data->set.timeout || data->set.connecttimeout) { double has_passed; /* Evaluate in milliseconds how much time that has passed */ has_passed = Curl_tvdiff(Curl_tvnow(), data->progress.start); #ifndef min #define min(a, b) ((a) < (b) ? (a) : (b)) #endif /* get the most strict timeout of the ones converted to milliseconds */ if(data->set.timeout && data->set.connecttimeout) { if (data->set.timeout < data->set.connecttimeout) timeout_ms = data->set.timeout*1000; else timeout_ms = data->set.connecttimeout*1000; } else if(data->set.timeout) timeout_ms = data->set.timeout*1000; else timeout_ms = data->set.connecttimeout*1000; /* subtract the passed time */ timeout_ms -= (long)has_passed; if(timeout_ms < 0) { /* a precaution, no need to continue if time already is up */ failf(data, "Connection time-out"); return CURLE_OPERATION_TIMEOUTED; } } hostname = data->change.proxy?conn->proxyhost:conn->hostname; infof(data, "About to connect() to %s port %d\n", hostname, port); #ifdef ENABLE_IPV6 /* * Connecting with a getaddrinfo chain */ for (ai = remotehost->addr; ai; ai = ai->ai_next, aliasindex++) { sockfd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol); if (sockfd == CURL_SOCKET_BAD) continue; #else /* * Connecting with old style IPv4-only support */ /* This is the loop that attempts to connect to all IP-addresses we know for the given host. One by one. */ for(rc=-1, aliasindex=0; rc && (struct in_addr *)remotehost->addr->h_addr_list[aliasindex]; aliasindex++) { struct sockaddr_in serv_addr; /* create an IPv4 TCP socket */ sockfd = socket(AF_INET, SOCK_STREAM, 0); if(CURL_SOCKET_BAD == sockfd) { failf(data, "couldn't create socket"); return CURLE_COULDNT_CONNECT; /* big time error */ } /* nasty address work before connect can be made */ memset((char *) &serv_addr, '\0', sizeof(serv_addr)); memcpy((char *)&(serv_addr.sin_addr), (struct in_addr *)remotehost->addr->h_addr_list[aliasindex], sizeof(struct in_addr)); serv_addr.sin_family = remotehost->addr->h_addrtype; serv_addr.sin_port = htons((unsigned short)port); #endif if(conn->data->set.device) { /* user selected to bind the outgoing socket to a specified "device" before doing connect */ CURLcode res = bindlocal(conn, sockfd); if(res) return res; } /* set socket non-blocking */ Curl_nonblock(sockfd, TRUE); /* do not use #ifdef within the function arguments below, as connect() is a defined macro on some platforms and some compilers don't like to mix #ifdefs with macro usage! (AmigaOS is one such platform) */ #ifdef ENABLE_IPV6 rc = connect(sockfd, ai->ai_addr, ai->ai_addrlen); #else rc = connect(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)); #endif if(-1 == rc) { int error=Curl_ourerrno(); switch (error) { case EINPROGRESS: case EWOULDBLOCK: #if defined(EAGAIN) && EAGAIN != EWOULDBLOCK /* On some platforms EAGAIN and EWOULDBLOCK are the * same value, and on others they are different, hence * the odd #if */ case EAGAIN: #endif /* asynchronous connect, wait for connect or timeout */ if(data->state.used_interface == Curl_if_multi) /* don't hang when doing multi */ timeout_ms = 0; rc = waitconnect(sockfd, timeout_ms); break; default: /* unknown error, fallthrough and try another address! */ failf(data, "Failed to connect to %s IP number %d: %d", hostname, aliasindex+1, error); break; } } /* The '1 == rc' comes from the waitconnect(), and not from connect(). We can be sure of this since connect() cannot return 1. */ if((1 == rc) && (data->state.used_interface == Curl_if_multi)) { /* Timeout when running the multi interface, we return here with a CURLE_OK return code. */ rc = 0; break; } if(0 == rc) { if (verifyconnect(sockfd)) { /* we are connected, awesome! */ *connected = TRUE; /* this is a true connect */ break; } /* nope, not connected for real */ rc = -1; } /* connect failed or timed out */ sclose(sockfd); sockfd = -1; /* get a new timeout for next attempt */ after = Curl_tvnow(); timeout_ms -= Curl_tvdiff(after, before); if(timeout_ms < 0) { failf(data, "connect() timed out!"); return CURLE_OPERATION_TIMEOUTED; } before = after; } if (sockfd == CURL_SOCKET_BAD) { /* no good connect was made */ *sockconn = -1; failf(data, "Connect failed"); return CURLE_COULDNT_CONNECT; } /* leave the socket in non-blocking mode */ /* store the address we use */ if(addr) { #ifdef ENABLE_IPV6 *addr = ai; #else *addr = (struct in_addr *)remotehost->addr->h_addr_list[aliasindex]; #endif } /* allow NULL-pointers to get passed in */ if(sockconn) *sockconn = sockfd; /* the socket descriptor we've connected */ return CURLE_OK; }
CURLcode Curl_connecthost(struct connectdata *conn, /* context */ const struct Curl_dns_entry *remotehost, curl_socket_t *sockconn, /* the connected socket */ Curl_addrinfo **addr, /* the one we used */ bool *connected) /* really connected? */ { struct SessionHandle *data = conn->data; curl_socket_t sockfd = CURL_SOCKET_BAD; int aliasindex; int num_addr; Curl_addrinfo *ai; Curl_addrinfo *curr_addr; struct timeval after; struct timeval before = Curl_tvnow(); /************************************************************* * Figure out what maximum time we have left *************************************************************/ long timeout_ms; long timeout_per_addr; DEBUGASSERT(sockconn); *connected = FALSE; /* default to not connected */ /* get the timeout left */ timeout_ms = Curl_timeleft(conn, &before, TRUE); if(timeout_ms < 0) { /* a precaution, no need to continue if time already is up */ failf(data, "Connection time-out"); return CURLE_OPERATION_TIMEDOUT; } Curl_expire(data, timeout_ms); /* Max time for each address */ num_addr = Curl_num_addresses(remotehost->addr); timeout_per_addr = timeout_ms / num_addr; ai = remotehost->addr; /* Below is the loop that attempts to connect to all IP-addresses we * know for the given host. One by one until one IP succeeds. */ if(data->state.used_interface == Curl_if_multi) /* don't hang when doing multi */ timeout_per_addr = 0; /* * Connecting with a Curl_addrinfo chain */ for (curr_addr = ai, aliasindex=0; curr_addr; curr_addr = curr_addr->ai_next, aliasindex++) { /* start connecting to the IP curr_addr points to */ sockfd = singleipconnect(conn, curr_addr, timeout_per_addr, connected); if(sockfd != CURL_SOCKET_BAD) break; /* get a new timeout for next attempt */ after = Curl_tvnow(); timeout_ms -= Curl_tvdiff(after, before); if(timeout_ms < 0) { failf(data, "connect() timed out!"); return CURLE_OPERATION_TIMEDOUT; } before = after; } /* end of connect-to-each-address loop */ *sockconn = sockfd; /* the socket descriptor we've connected */ if(sockfd == CURL_SOCKET_BAD) { /* no good connect was made */ failf(data, "couldn't connect to host"); return CURLE_COULDNT_CONNECT; } /* leave the socket in non-blocking mode */ /* store the address we use */ if(addr) *addr = curr_addr; data->info.numconnects++; /* to track the number of connections made */ return CURLE_OK; }
CURLcode Curl_is_connected(struct connectdata *conn, int sockindex, bool *connected) { int rc; struct SessionHandle *data = conn->data; CURLcode code = CURLE_OK; curl_socket_t sockfd = conn->sock[sockindex]; long allow = DEFAULT_CONNECT_TIMEOUT; long allow_total = 0; long has_passed; curlassert(sockindex >= FIRSTSOCKET && sockindex <= SECONDARYSOCKET); *connected = FALSE; /* a very negative world view is best */ /* Evaluate in milliseconds how much time that has passed */ has_passed = Curl_tvdiff(Curl_tvnow(), data->progress.t_startsingle); /* subtract the most strict timeout of the ones */ if(data->set.timeout && data->set.connecttimeout) { if (data->set.timeout < data->set.connecttimeout) allow_total = allow = data->set.timeout*1000; else allow = data->set.connecttimeout*1000; } else if(data->set.timeout) { allow_total = allow = data->set.timeout*1000; } else if(data->set.connecttimeout) { allow = data->set.connecttimeout*1000; } if(has_passed > allow ) { /* time-out, bail out, go home */ failf(data, "Connection time-out after %ld ms", has_passed); return CURLE_OPERATION_TIMEOUTED; } if(conn->bits.tcpconnect) { /* we are connected already! */ Curl_expire(data, allow_total); *connected = TRUE; return CURLE_OK; } Curl_expire(data, allow); /* check for connect without timeout as we want to return immediately */ rc = waitconnect(sockfd, 0); if(WAITCONN_CONNECTED == rc) { int error; if (verifyconnect(sockfd, &error)) { /* we are connected, awesome! */ *connected = TRUE; return CURLE_OK; } /* nope, not connected for real */ data->state.os_errno = error; infof(data, "Connection failed\n"); if(trynextip(conn, sockindex, connected)) { code = CURLE_COULDNT_CONNECT; } } else if(WAITCONN_TIMEOUT != rc) { int error = 0; /* nope, not connected */ if (WAITCONN_FDSET_ERROR == rc) { (void)verifyconnect(sockfd, &error); data->state.os_errno = error; infof(data, "%s\n",Curl_strerror(conn,error)); } else infof(data, "Connection failed\n"); if(trynextip(conn, sockindex, connected)) { error = Curl_sockerrno(); data->state.os_errno = error; failf(data, "Failed connect to %s:%d; %s", conn->host.name, conn->port, Curl_strerror(conn,error)); code = CURLE_COULDNT_CONNECT; } } /* * If the connection failed here, we should attempt to connect to the "next * address" for the given host. */ return code; }
CURLcode Curl_connecthost(struct connectdata *conn, /* context */ const struct Curl_dns_entry *remotehost, bool *connected) /* really connected? */ { struct SessionHandle *data = conn->data; struct timeval after; struct timeval before = Curl_tvnow(); int i; /************************************************************* * Figure out what maximum time we have left *************************************************************/ long timeout_ms; *connected = FALSE; /* default to not connected */ /* get the timeout left */ timeout_ms = Curl_timeleft(data, &before, TRUE); if(timeout_ms < 0) { /* a precaution, no need to continue if time already is up */ failf(data, "Connection time-out"); return CURLE_OPERATION_TIMEDOUT; } conn->num_addr = Curl_num_addresses(remotehost->addr); conn->tempaddr[0] = remotehost->addr; conn->tempaddr[1] = remotehost->addr; /* Below is the loop that attempts to connect to all IP-addresses we * know for the given host. * One by one, for each protocol, until one IP succeeds. */ for(i=0; i<2; i++) { curl_socket_t sockfd = CURL_SOCKET_BAD; Curl_addrinfo *ai = conn->tempaddr[i]; int family = i ? AF_INET6 : AF_INET; /* find first address for this address family, if any */ while(ai && ai->ai_family != family) ai = ai->ai_next; /* * Connecting with a Curl_addrinfo chain */ while(ai) { CURLcode res; /* Max time for the next connection attempt */ conn->timeoutms_per_addr = ai->ai_next == NULL ? timeout_ms : timeout_ms / 2; /* start connecting to the IP curr_addr points to */ res = singleipconnect(conn, ai, &sockfd, connected); if(res) return res; if(sockfd != CURL_SOCKET_BAD) break; /* get a new timeout for next attempt */ after = Curl_tvnow(); timeout_ms -= Curl_tvdiff(after, before); if(timeout_ms < 0) { failf(data, "connect() timed out!"); return CURLE_OPERATION_TIMEDOUT; } before = after; /* next addresses */ do { ai = ai->ai_next; } while(ai && ai->ai_family != family); } /* end of connect-to-each-address loop */ conn->tempsock[i] = sockfd; conn->tempaddr[i] = ai; } if((conn->tempsock[0] == CURL_SOCKET_BAD) && (conn->tempsock[1] == CURL_SOCKET_BAD)) { /* no good connect was made */ failf(data, "couldn't connect to %s at %s:%ld", conn->bits.proxy?"proxy":"host", conn->bits.proxy?conn->proxy.name:conn->host.name, conn->port); return CURLE_COULDNT_CONNECT; } /* leave the socket in non-blocking mode */ data->info.numconnects++; /* to track the number of connections made */ return CURLE_OK; }
/* * This function is called after the TCP connect has completed. Setup the TLS * layer and do all necessary magic. */ CURLcode Curl_gtls_connect(struct connectdata *conn, int sockindex) { const int cert_type_priority[] = { GNUTLS_CRT_X509, 0 }; struct SessionHandle *data = conn->data; gnutls_session session; int rc; unsigned int cert_list_size; const gnutls_datum *chainp; unsigned int verify_status; gnutls_x509_crt x509_cert; char certbuf[256]; /* big enough? */ size_t size; unsigned int algo; unsigned int bits; time_t clock; const char *ptr; void *ssl_sessionid; size_t ssl_idsize; /* GnuTLS only supports TLSv1 (and SSLv3?) */ if(data->set.ssl.version == CURL_SSLVERSION_SSLv2) { failf(data, "GnuTLS does not support SSLv2"); return CURLE_SSL_CONNECT_ERROR; } /* allocate a cred struct */ rc = gnutls_certificate_allocate_credentials(&conn->ssl[sockindex].cred); if(rc < 0) { failf(data, "gnutls_cert_all_cred() failed: %s", gnutls_strerror(rc)); return CURLE_SSL_CONNECT_ERROR; } if(data->set.ssl.CAfile) { /* set the trusted CA cert bundle file */ rc = gnutls_certificate_set_x509_trust_file(conn->ssl[sockindex].cred, data->set.ssl.CAfile, GNUTLS_X509_FMT_PEM); if(rc < 0) { infof(data, "error reading ca cert file %s (%s)\n", data->set.ssl.CAfile, gnutls_strerror(rc)); } } /* Initialize TLS session as a client */ rc = gnutls_init(&conn->ssl[sockindex].session, GNUTLS_CLIENT); if(rc) { failf(data, "gnutls_init() failed: %d", rc); return CURLE_SSL_CONNECT_ERROR; } /* convenient assign */ session = conn->ssl[sockindex].session; /* Use default priorities */ rc = gnutls_set_default_priority(session); if(rc < 0) return CURLE_SSL_CONNECT_ERROR; /* Sets the priority on the certificate types supported by gnutls. Priority is higher for types specified before others. After specifying the types you want, you must append a 0. */ rc = gnutls_certificate_type_set_priority(session, cert_type_priority); if(rc < 0) return CURLE_SSL_CONNECT_ERROR; /* put the anonymous credentials to the current session */ rc = gnutls_credentials_set(session, GNUTLS_CRD_CERTIFICATE, conn->ssl[sockindex].cred); /* set the connection handle (file descriptor for the socket) */ gnutls_transport_set_ptr(session, (gnutls_transport_ptr)conn->sock[sockindex]); /* This might be a reconnect, so we check for a session ID in the cache to speed up things */ if(!Curl_ssl_getsessionid(conn, &ssl_sessionid, &ssl_idsize)) { /* we got a session id, use it! */ gnutls_session_set_data(session, ssl_sessionid, ssl_idsize); /* Informational message */ infof (data, "SSL re-using session ID\n"); } do { rc = gnutls_handshake(session); if((rc == GNUTLS_E_AGAIN) || (rc == GNUTLS_E_INTERRUPTED)) { long timeout_ms; long has_passed; if(data->set.timeout || data->set.connecttimeout) { /* get the most strict timeout of the ones converted to milliseconds */ if(data->set.timeout && (data->set.timeout>data->set.connecttimeout)) timeout_ms = data->set.timeout*1000; else timeout_ms = data->set.connecttimeout*1000; } else timeout_ms = DEFAULT_CONNECT_TIMEOUT; /* Evaluate in milliseconds how much time that has passed */ has_passed = Curl_tvdiff(Curl_tvnow(), data->progress.t_startsingle); /* subtract the passed time */ timeout_ms -= has_passed; if(timeout_ms < 0) { /* a precaution, no need to continue if time already is up */ failf(data, "SSL connection timeout"); return CURLE_OPERATION_TIMEOUTED; } rc = Curl_select(conn->sock[sockindex], conn->sock[sockindex], (int)timeout_ms); if(rc > 0) /* reabable or writable, go loop*/ continue; else if(0 == rc) { /* timeout */ failf(data, "SSL connection timeout"); return CURLE_OPERATION_TIMEDOUT; } else { /* anything that gets here is fatally bad */ failf(data, "select on SSL socket, errno: %d", Curl_ourerrno()); return CURLE_SSL_CONNECT_ERROR; } } else break; } while(1); if (rc < 0) { failf(data, "gnutls_handshake() failed: %d", rc); /* gnutls_perror(ret); */ return CURLE_SSL_CONNECT_ERROR; } /* This function will return the peer's raw certificate (chain) as sent by the peer. These certificates are in raw format (DER encoded for X.509). In case of a X.509 then a certificate list may be present. The first certificate in the list is the peer's certificate, following the issuer's certificate, then the issuer's issuer etc. */ chainp = gnutls_certificate_get_peers(session, &cert_list_size); if(!chainp) { if(data->set.ssl.verifyhost) { failf(data, "failed to get server cert"); return CURLE_SSL_PEER_CERTIFICATE; } infof(data, "\t common name: WARNING couldn't obtain\n"); } /* This function will try to verify the peer's certificate and return its status (trusted, invalid etc.). The value of status should be one or more of the gnutls_certificate_status_t enumerated elements bitwise or'd. To avoid denial of service attacks some default upper limits regarding the certificate key size and chain size are set. To override them use gnutls_certificate_set_verify_limits(). */ rc = gnutls_certificate_verify_peers2(session, &verify_status); if (rc < 0) { failf(data, "server cert verify failed: %d", rc); return CURLE_SSL_CONNECT_ERROR; } /* verify_status is a bitmask of gnutls_certificate_status bits */ if(verify_status & GNUTLS_CERT_INVALID) { if (data->set.ssl.verifypeer) { failf(data, "server certificate verification failed. CAfile: %s", data->set.ssl.CAfile?data->set.ssl.CAfile:"none"); return CURLE_SSL_CACERT; } else infof(data, "\t server certificate verification FAILED\n"); } else infof(data, "\t server certificate verification OK\n"); /* initialize an X.509 certificate structure. */ gnutls_x509_crt_init(&x509_cert); /* convert the given DER or PEM encoded Certificate to the native gnutls_x509_crt_t format */ gnutls_x509_crt_import(x509_cert, chainp, GNUTLS_X509_FMT_DER); size=sizeof(certbuf); rc = gnutls_x509_crt_get_dn_by_oid(x509_cert, GNUTLS_OID_X520_COMMON_NAME, 0, /* the first and only one */ FALSE, certbuf, &size); if(rc) { infof(data, "error fetching CN from cert:%s\n", gnutls_strerror(rc)); } /* This function will check if the given certificate's subject matches the given hostname. This is a basic implementation of the matching described in RFC2818 (HTTPS), which takes into account wildcards, and the subject alternative name PKIX extension. Returns non zero on success, and zero on failure. */ rc = gnutls_x509_crt_check_hostname(x509_cert, conn->host.name); if(!rc) { if (data->set.ssl.verifyhost > 1) { failf(data, "SSL: certificate subject name (%s) does not match " "target host name '%s'", certbuf, conn->host.dispname); gnutls_x509_crt_deinit(x509_cert); return CURLE_SSL_PEER_CERTIFICATE; } else infof(data, "\t common name: %s (does not match '%s')\n", certbuf, conn->host.dispname); } else infof(data, "\t common name: %s (matched)\n", certbuf); /* Show: - ciphers used - subject - start date - expire date - common name - issuer */ /* public key algorithm's parameters */ algo = gnutls_x509_crt_get_pk_algorithm(x509_cert, &bits); infof(data, "\t certificate public key: %s\n", gnutls_pk_algorithm_get_name(algo)); /* version of the X.509 certificate. */ infof(data, "\t certificate version: #%d\n", gnutls_x509_crt_get_version(x509_cert)); size = sizeof(certbuf); gnutls_x509_crt_get_dn(x509_cert, certbuf, &size); infof(data, "\t subject: %s\n", certbuf); clock = gnutls_x509_crt_get_activation_time(x509_cert); showtime(data, "start date", clock); clock = gnutls_x509_crt_get_expiration_time(x509_cert); showtime(data, "expire date", clock); size = sizeof(certbuf); gnutls_x509_crt_get_issuer_dn(x509_cert, certbuf, &size); infof(data, "\t issuer: %s\n", certbuf); gnutls_x509_crt_deinit(x509_cert); /* compression algorithm (if any) */ ptr = gnutls_compression_get_name(gnutls_compression_get(session)); /* the *_get_name() says "NULL" if GNUTLS_COMP_NULL is returned */ infof(data, "\t compression: %s\n", ptr); /* the name of the cipher used. ie 3DES. */ ptr = gnutls_cipher_get_name(gnutls_cipher_get(session)); infof(data, "\t cipher: %s\n", ptr); /* the MAC algorithms name. ie SHA1 */ ptr = gnutls_mac_get_name(gnutls_mac_get(session)); infof(data, "\t MAC: %s\n", ptr); if(!ssl_sessionid) { /* this session was not previously in the cache, add it now */ /* get the session ID data size */ gnutls_session_get_data(session, NULL, &ssl_idsize); ssl_sessionid = malloc(ssl_idsize); /* get a buffer for it */ if(ssl_sessionid) { /* extract session ID to the allocated buffer */ gnutls_session_get_data(session, ssl_sessionid, &ssl_idsize); /* store this session id */ return Curl_ssl_addsessionid(conn, ssl_sessionid, ssl_idsize); } } return CURLE_OK; }
/* ====================================================== */ CURLcode Curl_SSLConnect(struct connectdata *conn, int sockindex) { CURLcode retcode = CURLE_OK; #ifdef USE_SSLEAY struct SessionHandle *data = conn->data; int err; long lerr; int what; char * str; SSL_METHOD *req_method; SSL_SESSION *ssl_sessionid=NULL; ASN1_TIME *certdate; curl_socket_t sockfd = conn->sock[sockindex]; struct ssl_connect_data *connssl = &conn->ssl[sockindex]; /* mark this is being ssl enabled from here on out. */ connssl->use = TRUE; if(!ssl_seeded || data->set.ssl.random_file || data->set.ssl.egdsocket) { /* Make funny stuff to get random input */ random_the_seed(data); ssl_seeded = TRUE; } /* check to see if we've been told to use an explicit SSL/TLS version */ switch(data->set.ssl.version) { default: case CURL_SSLVERSION_DEFAULT: /* we try to figure out version */ req_method = SSLv23_client_method(); break; case CURL_SSLVERSION_TLSv1: req_method = TLSv1_client_method(); break; case CURL_SSLVERSION_SSLv2: req_method = SSLv2_client_method(); break; case CURL_SSLVERSION_SSLv3: req_method = SSLv3_client_method(); break; } connssl->ctx = SSL_CTX_new(req_method); if(!connssl->ctx) { failf(data, "SSL: couldn't create a context!"); return CURLE_OUT_OF_MEMORY; } #ifdef SSL_CTRL_SET_MSG_CALLBACK if (data->set.fdebug) { SSL_CTX_callback_ctrl(connssl->ctx, SSL_CTRL_SET_MSG_CALLBACK, ssl_tls_trace); SSL_CTX_ctrl(connssl->ctx, SSL_CTRL_SET_MSG_CALLBACK_ARG, 0, conn); } #endif /* OpenSSL contains code to work-around lots of bugs and flaws in various SSL-implementations. SSL_CTX_set_options() is used to enabled those work-arounds. The man page for this option states that SSL_OP_ALL enables ll the work-arounds and that "It is usually safe to use SSL_OP_ALL to enable the bug workaround options if compatibility with somewhat broken implementations is desired." */ SSL_CTX_set_options(connssl->ctx, SSL_OP_ALL); #if 0 /* * Not sure it's needed to tell SSL_connect() that socket is * non-blocking. It doesn't seem to care, but just return with * SSL_ERROR_WANT_x. */ if (data->state.used_interface == Curl_if_multi) SSL_CTX_ctrl(connssl->ctx, BIO_C_SET_NBIO, 1, NULL); #endif if(data->set.cert) { if(!cert_stuff(conn, connssl->ctx, data->set.cert, data->set.cert_type, data->set.key, data->set.key_type)) { /* failf() is already done in cert_stuff() */ return CURLE_SSL_CERTPROBLEM; } } if(data->set.ssl.cipher_list) { if(!SSL_CTX_set_cipher_list(connssl->ctx, data->set.ssl.cipher_list)) { failf(data, "failed setting cipher list"); return CURLE_SSL_CIPHER; } } if (data->set.ssl.CAfile || data->set.ssl.CApath) { /* tell SSL where to find CA certificates that are used to verify the servers certificate. */ if (!SSL_CTX_load_verify_locations(connssl->ctx, data->set.ssl.CAfile, data->set.ssl.CApath)) { if (data->set.ssl.verifypeer) { /* Fail if we insist on successfully verifying the server. */ failf(data,"error setting certificate verify locations:\n" " CAfile: %s\n CApath: %s\n", data->set.ssl.CAfile ? data->set.ssl.CAfile : "none", data->set.ssl.CApath ? data->set.ssl.CApath : "none"); return CURLE_SSL_CACERT; } else { /* Just continue with a warning if no strict certificate verification is required. */ infof(data, "error setting certificate verify locations," " continuing anyway:\n"); } } else { /* Everything is fine. */ infof(data, "successfully set certificate verify locations:\n"); } infof(data, " CAfile: %s\n" " CApath: %s\n", data->set.ssl.CAfile ? data->set.ssl.CAfile : "none", data->set.ssl.CApath ? data->set.ssl.CApath : "none"); } /* SSL always tries to verify the peer, this only says whether it should * fail to connect if the verification fails, or if it should continue * anyway. In the latter case the result of the verification is checked with * SSL_get_verify_result() below. */ SSL_CTX_set_verify(connssl->ctx, data->set.ssl.verifypeer?SSL_VERIFY_PEER:SSL_VERIFY_NONE, cert_verify_callback); /* give application a chance to interfere with SSL set up. */ if(data->set.ssl.fsslctx) { retcode = (*data->set.ssl.fsslctx)(data, connssl->ctx, data->set.ssl.fsslctxp); if(retcode) { failf(data,"error signaled by ssl ctx callback"); return retcode; } } /* Lets make an SSL structure */ connssl->handle = SSL_new(connssl->ctx); SSL_set_connect_state(connssl->handle); connssl->server_cert = 0x0; if(!conn->bits.reuse) { /* We're not re-using a connection, check if there's a cached ID we can/should use here! */ if(!Get_SSL_Session(conn, &ssl_sessionid)) { /* we got a session id, use it! */ SSL_set_session(connssl->handle, ssl_sessionid); /* Informational message */ infof (data, "SSL re-using session ID\n"); } } /* pass the raw socket into the SSL layers */ SSL_set_fd(connssl->handle, sockfd); while(1) { fd_set writefd; fd_set readfd; struct timeval interval; long timeout_ms; /* Find out if any timeout is set. If not, use 300 seconds. Otherwise, figure out the most strict timeout of the two possible one and then how much time that has elapsed to know how much time we allow for the connect call */ if(data->set.timeout || data->set.connecttimeout) { long has_passed; /* Evaluate in milliseconds how much time that has passed */ has_passed = Curl_tvdiff(Curl_tvnow(), data->progress.start); /* get the most strict timeout of the ones converted to milliseconds */ if(data->set.timeout && (data->set.timeout>data->set.connecttimeout)) timeout_ms = data->set.timeout*1000; else timeout_ms = data->set.connecttimeout*1000; /* subtract the passed time */ timeout_ms -= has_passed; if(timeout_ms < 0) { /* a precaution, no need to continue if time already is up */ failf(data, "SSL connection timeout"); return CURLE_OPERATION_TIMEOUTED; } } else /* no particular time-out has been set */ timeout_ms= DEFAULT_CONNECT_TIMEOUT; FD_ZERO(&writefd); FD_ZERO(&readfd); err = SSL_connect(connssl->handle); /* 1 is fine 0 is "not successful but was shut down controlled" <0 is "handshake was not successful, because a fatal error occurred" */ if(1 != err) { int detail = SSL_get_error(connssl->handle, err); if(SSL_ERROR_WANT_READ == detail) FD_SET(sockfd, &readfd); else if(SSL_ERROR_WANT_WRITE == detail) FD_SET(sockfd, &writefd); else { /* untreated error */ unsigned long errdetail; char error_buffer[120]; /* OpenSSL documents that this must be at least 120 bytes long. */ CURLcode rc; const char *cert_problem = NULL; errdetail = ERR_get_error(); /* Gets the earliest error code from the thread's error queue and removes the entry. */ switch(errdetail) { case 0x1407E086: /* 1407E086: SSL routines: SSL2_SET_CERTIFICATE: certificate verify failed */ /* fall-through */ case 0x14090086: /* 14090086: SSL routines: SSL3_GET_SERVER_CERTIFICATE: certificate verify failed */ cert_problem = "SSL certificate problem, verify that the CA cert is" " OK. Details:\n"; rc = CURLE_SSL_CACERT; break; default: rc = CURLE_SSL_CONNECT_ERROR; break; } /* detail is already set to the SSL error above */ /* If we e.g. use SSLv2 request-method and the server doesn't like us * (RST connection etc.), OpenSSL gives no explanation whatsoever and * the SO_ERROR is also lost. */ if (CURLE_SSL_CONNECT_ERROR == rc && errdetail == 0) { failf(data, "Unknown SSL protocol error in connection to %s:%d ", conn->host.name, conn->port); return rc; } /* Could be a CERT problem */ #ifdef HAVE_ERR_ERROR_STRING_N /* OpenSSL 0.9.6 and later has a function named ERRO_error_string_n() that takes the size of the buffer as a third argument */ ERR_error_string_n(errdetail, error_buffer, sizeof(error_buffer)); #else ERR_error_string(errdetail, error_buffer); #endif failf(data, "%s%s", cert_problem ? cert_problem : "", error_buffer); return rc; } } else /* we have been connected fine, get out of the connect loop */ break; interval.tv_sec = (int)(timeout_ms/1000); timeout_ms -= interval.tv_sec*1000; interval.tv_usec = timeout_ms*1000; while(1) { what = select(sockfd+1, &readfd, &writefd, NULL, &interval); if(what > 0) /* reabable or writable, go loop in the outer loop */ break; else if(0 == what) { /* timeout */ failf(data, "SSL connection timeout"); return CURLE_OPERATION_TIMEDOUT; } else { #if !defined(WIN32) && defined(EINTR) /* For platforms without EINTR all errnos are bad */ if (errno == EINTR) continue; /* retry the select() */ #endif /* anything other than the unimportant EINTR is fatally bad */ failf(data, "select on SSL socket, errno: %d", Curl_ourerrno()); return CURLE_SSL_CONNECT_ERROR; } } /* while()-loop for the select() */ } /* while()-loop for the SSL_connect() */ /* Informational message */ infof (data, "SSL connection using %s\n", SSL_get_cipher(connssl->handle)); if(!ssl_sessionid) { /* Since this is not a cached session ID, then we want to stach this one in the cache! */ Store_SSL_Session(conn, connssl); } /* Get server's certificate (note: beware of dynamic allocation) - opt */ /* major serious hack alert -- we should check certificates * to authenticate the server; otherwise we risk man-in-the-middle * attack */ connssl->server_cert = SSL_get_peer_certificate(connssl->handle); if(!connssl->server_cert) { failf(data, "SSL: couldn't get peer certificate!"); return CURLE_SSL_PEER_CERTIFICATE; } infof (data, "Server certificate:\n"); str = X509_NAME_oneline(X509_get_subject_name(connssl->server_cert), NULL, 0); if(!str) { failf(data, "SSL: couldn't get X509-subject!"); X509_free(connssl->server_cert); return CURLE_SSL_CONNECT_ERROR; } infof(data, "\t subject: %s\n", str); CRYPTO_free(str); certdate = X509_get_notBefore(connssl->server_cert); Curl_ASN1_UTCTIME_output(conn, "\t start date: ", certdate); certdate = X509_get_notAfter(connssl->server_cert); Curl_ASN1_UTCTIME_output(conn, "\t expire date: ", certdate); if(data->set.ssl.verifyhost) { retcode = verifyhost(conn, connssl->server_cert); if(retcode) { X509_free(connssl->server_cert); return retcode; } } str = X509_NAME_oneline(X509_get_issuer_name(connssl->server_cert), NULL, 0); if(!str) { failf(data, "SSL: couldn't get X509-issuer name!"); retcode = CURLE_SSL_CONNECT_ERROR; } else { infof(data, "\t issuer: %s\n", str); CRYPTO_free(str); /* We could do all sorts of certificate verification stuff here before deallocating the certificate. */ lerr = data->set.ssl.certverifyresult= SSL_get_verify_result(connssl->handle); if(data->set.ssl.certverifyresult != X509_V_OK) { if(data->set.ssl.verifypeer) { /* We probably never reach this, because SSL_connect() will fail and we return earlyer if verifypeer is set? */ failf(data, "SSL certificate verify result: %s (%ld)", X509_verify_cert_error_string(lerr), lerr); retcode = CURLE_SSL_PEER_CERTIFICATE; } else infof(data, "SSL certificate verify result: %s (%ld)," " continuing anyway.\n", X509_verify_cert_error_string(err), lerr); } else infof(data, "SSL certificate verify ok.\n"); } X509_free(connssl->server_cert); #else /* USE_SSLEAY */ (void)conn; (void)sockindex; #endif return retcode; }
CURLcode Curl_is_connected(struct connectdata *conn, int sockindex, bool *connected) { struct Curl_easy *data = conn->data; CURLcode result = CURLE_OK; time_t allow; int error = 0; struct curltime now; int rc; int i; DEBUGASSERT(sockindex >= FIRSTSOCKET && sockindex <= SECONDARYSOCKET); *connected = FALSE; /* a very negative world view is best */ if(conn->bits.tcpconnect[sockindex]) { /* we are connected already! */ *connected = TRUE; return CURLE_OK; } now = Curl_tvnow(); for(i = 0; i<2; i++) { const int other = i ^ 1; if(conn->tempsock[i] == CURL_SOCKET_BAD) continue; #ifdef mpeix /* Call this function once now, and ignore the results. We do this to "clear" the error state on the socket so that we can later read it reliably. This is reported necessary on the MPE/iX operating system. */ (void)verifyconnect(conn->tempsock[i], NULL); #endif /* check socket for connect */ rc = SOCKET_WRITABLE(conn->tempsock[i], 0); if(rc == 0) { /* no connection yet */ error = 0; if(curlx_tvdiff(now, conn->connecttime) >= conn->timeoutms_per_addr) { infof(data, "After %ldms connect time, move on!\n", conn->timeoutms_per_addr); error = ETIMEDOUT; } /* should we try another protocol family? */ if(i == 0 && conn->tempaddr[1] == NULL && curlx_tvdiff(now, conn->connecttime) >= HAPPY_EYEBALLS_TIMEOUT) { trynextip(conn, sockindex, 1); } } else if(rc == CURL_CSELECT_OUT || conn->bits.tcp_fastopen) { if(verifyconnect(conn->tempsock[i], &error)) { /* we are connected with TCP, awesome! */ /* use this socket from now on */ conn->sock[sockindex] = conn->tempsock[i]; conn->ip_addr = conn->tempaddr[i]; conn->tempsock[i] = CURL_SOCKET_BAD; /* close the other socket, if open */ if(conn->tempsock[other] != CURL_SOCKET_BAD) { Curl_closesocket(conn, conn->tempsock[other]); conn->tempsock[other] = CURL_SOCKET_BAD; } /* see if we need to do any proxy magic first once we connected */ result = Curl_connected_proxy(conn, sockindex); if(result) return result; conn->bits.tcpconnect[sockindex] = TRUE; *connected = TRUE; if(sockindex == FIRSTSOCKET) Curl_pgrsTime(data, TIMER_CONNECT); /* connect done */ Curl_updateconninfo(conn, conn->sock[sockindex]); Curl_verboseconnect(conn); return CURLE_OK; } infof(data, "Connection failed\n"); } else if(rc & CURL_CSELECT_ERR) (void)verifyconnect(conn->tempsock[i], &error); /* * The connection failed here, we should attempt to connect to the "next * address" for the given host. But first remember the latest error. */ if(error) { data->state.os_errno = error; SET_SOCKERRNO(error); if(conn->tempaddr[i]) { CURLcode status; char ipaddress[MAX_IPADR_LEN]; Curl_printable_address(conn->tempaddr[i], ipaddress, MAX_IPADR_LEN); infof(data, "connect to %s port %ld failed: %s\n", ipaddress, conn->port, Curl_strerror(conn, error)); conn->timeoutms_per_addr = conn->tempaddr[i]->ai_next == NULL ? allow : allow / 2; status = trynextip(conn, sockindex, i); if(status != CURLE_COULDNT_CONNECT || conn->tempsock[other] == CURL_SOCKET_BAD) /* the last attempt failed and no other sockets remain open */ result = status; } } } /* * Now that we've checked whether we are connected, check whether we've * already timed out. * * First figure out how long time we have left to connect */ allow = Curl_timeleft(data, &now, TRUE); if(allow < 0) { /* time-out, bail out, go home */ failf(data, "Connection timeout after %ld ms", Curl_tvdiff(now, data->progress.t_startsingle)); return CURLE_OPERATION_TIMEDOUT; } if(result) { /* no more addresses to try */ const char *hostname; /* if the first address family runs out of addresses to try before the happy eyeball timeout, go ahead and try the next family now */ if(conn->tempaddr[1] == NULL) { result = trynextip(conn, sockindex, 1); if(!result) return result; } if(conn->bits.socksproxy) hostname = conn->socks_proxy.host.name; else if(conn->bits.httpproxy) hostname = conn->http_proxy.host.name; else if(conn->bits.conn_to_host) hostname = conn->conn_to_host.name; else hostname = conn->host.name; failf(data, "Failed to connect to %s port %ld after %ld ms: %s", hostname, conn->port, Curl_tvdiff(now, data->progress.t_startsingle), Curl_strerror(conn, error)); } return result; }
/* * Curl_wait_for_resolv() waits for a resolve to finish. This function should * be avoided since using this risk getting the multi interface to "hang". * * If 'entry' is non-NULL, make it point to the resolved dns entry * * Returns CURLE_COULDNT_RESOLVE_HOST if the host was not resolved, and * CURLE_OPERATION_TIMEDOUT if a time-out occurred. */ CURLcode Curl_wait_for_resolv(struct connectdata *conn, struct Curl_dns_entry **entry) { CURLcode rc=CURLE_OK; struct SessionHandle *data = conn->data; long timeout = CURL_TIMEOUT_RESOLVE; /* default name resolve timeout */ /* now, see if there's a connect timeout or a regular timeout to use instead of the default one */ if(conn->data->set.connecttimeout) timeout = conn->data->set.connecttimeout; else if(conn->data->set.timeout) timeout = conn->data->set.timeout; /* We convert the number of seconds into number of milliseconds here: */ if(timeout < 2147483) /* maximum amount of seconds that can be multiplied with 1000 and still fit within 31 bits */ timeout *= 1000; else timeout = 0x7fffffff; /* ridiculous amount of time anyway */ /* Wait for the name resolve query to complete. */ while (1) { int nfds=0; fd_set read_fds, write_fds; struct timeval *tvp, tv, store; int count; struct timeval now = Curl_tvnow(); long timediff; store.tv_sec = (int)timeout/1000; store.tv_usec = (timeout%1000)*1000; FD_ZERO(&read_fds); FD_ZERO(&write_fds); nfds = ares_fds(data->state.areschannel, &read_fds, &write_fds); if (nfds == 0) /* no file descriptors means we're done waiting */ break; tvp = ares_timeout(data->state.areschannel, &store, &tv); count = select(nfds, &read_fds, &write_fds, NULL, tvp); if (count < 0 && errno != EINVAL) break; ares_process(data->state.areschannel, &read_fds, &write_fds); timediff = Curl_tvdiff(Curl_tvnow(), now); /* spent time */ timeout -= timediff?timediff:1; /* always deduct at least 1 */ if (timeout < 0) { /* our timeout, so we cancel the ares operation */ ares_cancel(data->state.areschannel); break; } } /* Operation complete, if the lookup was successful we now have the entry in the cache. */ if(entry) *entry = conn->async.dns; if(!conn->async.dns) { /* a name was not resolved */ if((timeout < 0) || (conn->async.status == ARES_ETIMEOUT)) { failf(data, "Resolving host timed out: %s", conn->host.dispname); rc = CURLE_OPERATION_TIMEDOUT; } else if(conn->async.done) { failf(data, "Could not resolve host: %s (%s)", conn->host.dispname, ares_strerror(conn->async.status)); rc = CURLE_COULDNT_RESOLVE_HOST; } else rc = CURLE_OPERATION_TIMEDOUT; /* close the connection, since we can't return failure here without cleaning up this connection properly */ conn->bits.close = TRUE; } return rc; }
CURLcode Curl_proxyCONNECT(struct connectdata *conn, int sockindex, const char *hostname, unsigned short remote_port) { int subversion=0; struct SessionHandle *data=conn->data; struct SingleRequest *k = &data->req; CURLcode result; long timeout = data->set.timeout?data->set.timeout:PROXY_TIMEOUT; /* in milliseconds */ curl_socket_t tunnelsocket = conn->sock[sockindex]; curl_off_t cl=0; bool closeConnection = FALSE; bool chunked_encoding = FALSE; long check; #define SELECT_OK 0 #define SELECT_ERROR 1 #define SELECT_TIMEOUT 2 int error = SELECT_OK; if(conn->tunnel_state[sockindex] == TUNNEL_COMPLETE) return CURLE_OK; /* CONNECT is already completed */ conn->bits.proxy_connect_closed = FALSE; do { if(TUNNEL_INIT == conn->tunnel_state[sockindex]) { /* BEGIN CONNECT PHASE */ char *host_port; Curl_send_buffer *req_buffer; infof(data, "Establish HTTP proxy tunnel to %s:%hu\n", hostname, remote_port); if(data->req.newurl) { /* This only happens if we've looped here due to authentication reasons, and we don't really use the newly cloned URL here then. Just free() it. */ free(data->req.newurl); data->req.newurl = NULL; } /* initialize a dynamic send-buffer */ req_buffer = Curl_add_buffer_init(); if(!req_buffer) return CURLE_OUT_OF_MEMORY; host_port = aprintf("%s:%hu", hostname, remote_port); if(!host_port) { free(req_buffer); return CURLE_OUT_OF_MEMORY; } /* Setup the proxy-authorization header, if any */ result = Curl_http_output_auth(conn, "CONNECT", host_port, TRUE); free(host_port); if(CURLE_OK == result) { char *host=(char *)""; const char *proxyconn=""; const char *useragent=""; const char *http = (conn->proxytype == CURLPROXY_HTTP_1_0) ? "1.0" : "1.1"; char *hostheader= /* host:port with IPv6 support */ aprintf("%s%s%s:%hu", conn->bits.ipv6_ip?"[":"", hostname, conn->bits.ipv6_ip?"]":"", remote_port); if(!hostheader) { free(req_buffer); return CURLE_OUT_OF_MEMORY; } if(!Curl_checkheaders(data, "Host:")) { host = aprintf("Host: %s\r\n", hostheader); if(!host) { free(hostheader); free(req_buffer); return CURLE_OUT_OF_MEMORY; } } if(!Curl_checkheaders(data, "Proxy-Connection:")) proxyconn = "Proxy-Connection: Keep-Alive\r\n"; if(!Curl_checkheaders(data, "User-Agent:") && data->set.str[STRING_USERAGENT]) useragent = conn->allocptr.uagent; result = Curl_add_bufferf(req_buffer, "CONNECT %s HTTP/%s\r\n" "%s" /* Host: */ "%s" /* Proxy-Authorization */ "%s" /* User-Agent */ "%s", /* Proxy-Connection */ hostheader, http, host, conn->allocptr.proxyuserpwd? conn->allocptr.proxyuserpwd:"", useragent, proxyconn); if(host && *host) free(host); free(hostheader); if(CURLE_OK == result) result = Curl_add_custom_headers(conn, req_buffer); if(CURLE_OK == result) /* CRLF terminate the request */ result = Curl_add_bufferf(req_buffer, "\r\n"); if(CURLE_OK == result) { /* Send the connect request to the proxy */ /* BLOCKING */ result = Curl_add_buffer_send(req_buffer, conn, &data->info.request_size, 0, sockindex); } req_buffer = NULL; if(result) failf(data, "Failed sending CONNECT to proxy"); } Curl_safefree(req_buffer); if(result) return result; conn->tunnel_state[sockindex] = TUNNEL_CONNECT; /* now we've issued the CONNECT and we're waiting to hear back, return and get called again polling-style */ return CURLE_OK; } /* END CONNECT PHASE */ { /* BEGIN NEGOTIATION PHASE */ size_t nread; /* total size read */ int perline; /* count bytes per line */ int keepon=TRUE; ssize_t gotbytes; char *ptr; char *line_start; ptr=data->state.buffer; line_start = ptr; nread=0; perline=0; keepon=TRUE; while((nread<BUFSIZE) && (keepon && !error)) { /* if timeout is requested, find out how much remaining time we have */ check = timeout - /* timeout time */ Curl_tvdiff(Curl_tvnow(), conn->now); /* spent time */ if(check <= 0) { failf(data, "Proxy CONNECT aborted due to timeout"); error = SELECT_TIMEOUT; /* already too little time */ break; } /* loop every second at least, less if the timeout is near */ switch (Curl_socket_ready(tunnelsocket, CURL_SOCKET_BAD, check<1000L?check:1000)) { case -1: /* select() error, stop reading */ error = SELECT_ERROR; failf(data, "Proxy CONNECT aborted due to select/poll error"); break; case 0: /* timeout */ break; default: DEBUGASSERT(ptr+BUFSIZE-nread <= data->state.buffer+BUFSIZE+1); result = Curl_read(conn, tunnelsocket, ptr, BUFSIZE-nread, &gotbytes); if(result==CURLE_AGAIN) continue; /* go loop yourself */ else if(result) keepon = FALSE; else if(gotbytes <= 0) { keepon = FALSE; if(data->set.proxyauth && data->state.authproxy.avail) { /* proxy auth was requested and there was proxy auth available, then deem this as "mere" proxy disconnect */ conn->bits.proxy_connect_closed = TRUE; } else { 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. */ int i; nread += gotbytes; if(keepon > TRUE) { /* This means we are currently ignoring a response-body */ nread = 0; /* make next read start over in the read buffer */ ptr=data->state.buffer; if(cl) { /* A Content-Length based body: simply count down the counter and make sure to break out of the loop when we're done! */ cl -= gotbytes; if(cl<=0) { keepon = FALSE; break; } } else { /* chunked-encoded body, so we need to do the chunked dance properly to know when the end of the body is reached */ CHUNKcode r; ssize_t tookcareof=0; /* now parse the chunked piece of data so that we can properly tell when the stream ends */ r = Curl_httpchunk_read(conn, ptr, gotbytes, &tookcareof); if(r == CHUNKE_STOP) { /* we're done reading chunks! */ infof(data, "chunk reading DONE\n"); keepon = FALSE; /* we did the full CONNECT treatment, go COMPLETE */ conn->tunnel_state[sockindex] = TUNNEL_COMPLETE; } else infof(data, "Read %zd bytes of chunk, continue\n", tookcareof); } } else for(i = 0; i < gotbytes; ptr++, i++) { perline++; /* amount of bytes in this line so far */ if(*ptr == 0x0a) { char letter; int writetype; /* convert from the network encoding */ result = Curl_convert_from_network(data, line_start, perline); /* Curl_convert_from_network calls failf if unsuccessful */ if(result) return result; /* output debug if that is requested */ if(data->set.verbose) Curl_debug(data, CURLINFO_HEADER_IN, line_start, (size_t)perline, conn); /* send the header to the callback */ writetype = CLIENTWRITE_HEADER; if(data->set.include_header) writetype |= CLIENTWRITE_BODY; result = Curl_client_write(conn, writetype, line_start, perline); data->info.header_size += (long)perline; data->req.headerbytecount += (long)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 */ nread = 0; /* make next read start over in the read buffer */ ptr=data->state.buffer; if((407 == k->httpcode) && !data->state.authproblem) { /* If we get a 407 response code with content length when we have no auth problem, we must ignore the whole response-body */ keepon = 2; if(cl) { infof(data, "Ignore %" FORMAT_OFF_T " bytes of response-body\n", cl); /* remove the remaining chunk of what we already read */ cl -= (gotbytes - i); if(cl<=0) /* if the whole thing was already read, we are done! */ keepon=FALSE; } else if(chunked_encoding) { CHUNKcode r; /* We set ignorebody true here since the chunked decoder function will acknowledge that. Pay attention so that this is cleared again when this function returns! */ k->ignorebody = TRUE; infof(data, "%zd bytes of chunk left\n", gotbytes-i); if(line_start[1] == '\n') { /* this can only be a LF if the letter at index 0 was a CR */ line_start++; i++; } /* now parse the chunked piece of data so that we can properly tell when the stream ends */ r = Curl_httpchunk_read(conn, line_start+1, gotbytes -i, &gotbytes); if(r == CHUNKE_STOP) { /* we're done reading chunks! */ infof(data, "chunk reading DONE\n"); keepon = FALSE; /* we did the full CONNECT treatment, go to COMPLETE */ conn->tunnel_state[sockindex] = TUNNEL_COMPLETE; } else infof(data, "Read %zd bytes of chunk, continue\n", gotbytes); } else { /* without content-length or chunked encoding, we can't keep the connection alive since the close is the end signal so we bail out at once instead */ keepon=FALSE; } } else { keepon = FALSE; if(200 == data->info.httpproxycode) { if(gotbytes - (i+1)) failf(data, "Proxy CONNECT followed by %zd bytes " "of opaque data. Data ignored (known bug #39)", gotbytes - (i+1)); } } /* we did the full CONNECT treatment, go to COMPLETE */ conn->tunnel_state[sockindex] = TUNNEL_COMPLETE; 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(checkprefix("Content-Length:", line_start)) { cl = curlx_strtoofft(line_start + strlen("Content-Length:"), NULL, 10); } else if(Curl_compareheader(line_start, "Connection:", "close")) closeConnection = TRUE; else if(Curl_compareheader(line_start, "Transfer-Encoding:", "chunked")) { infof(data, "CONNECT responded chunked\n"); chunked_encoding = TRUE; /* init our chunky engine */ Curl_httpchunk_init(conn); } else if(Curl_compareheader(line_start, "Proxy-Connection:", "close")) closeConnection = TRUE; else if(2 == sscanf(line_start, "HTTP/1.%d %d", &subversion, &k->httpcode)) { /* 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 */ if(Curl_pgrsUpdate(conn)) return CURLE_ABORTED_BY_CALLBACK; } /* while there's buffer left and loop is requested */ if(error) return CURLE_RECV_ERROR; if(data->info.httpproxycode != 200) { /* Deal with the possibly already received authenticate headers. 'newurl' is set to a new URL if we must loop. */ result = Curl_http_auth_act(conn); if(result) return result; if(conn->bits.close) /* the connection has been marked for closure, most likely in the Curl_http_auth_act() function and thus we can kill it at once below */ closeConnection = TRUE; } if(closeConnection && data->req.newurl) { /* Connection closed by server. Don't use it anymore */ Curl_closesocket(conn, conn->sock[sockindex]); conn->sock[sockindex] = CURL_SOCKET_BAD; break; } } /* END NEGOTIATION PHASE */ /* If we are supposed to continue and request a new URL, which basically * means the HTTP authentication is still going on so if the tunnel * is complete we start over in INIT state */ if(data->req.newurl && (TUNNEL_COMPLETE == conn->tunnel_state[sockindex])) { conn->tunnel_state[sockindex] = TUNNEL_INIT; infof(data, "TUNNEL_STATE switched to: %d\n", conn->tunnel_state[sockindex]); } } while(data->req.newurl); if(200 != data->req.httpcode) { failf(data, "Received HTTP code %d from proxy after CONNECT", data->req.httpcode); if(closeConnection && data->req.newurl) conn->bits.proxy_connect_closed = TRUE; if(data->req.newurl) { /* this won't be used anymore for the CONNECT so free it now */ free(data->req.newurl); data->req.newurl = NULL; } /* to back to init state */ conn->tunnel_state[sockindex] = TUNNEL_INIT; return CURLE_RECV_ERROR; } conn->tunnel_state[sockindex] = TUNNEL_COMPLETE; /* 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"); data->req.ignorebody = FALSE; /* put it (back) to non-ignore state */ conn->bits.rewindaftersend = FALSE; /* make sure this isn't set for the document request */ return CURLE_OK; }
/* * Curl_wait_for_resolv() waits for a resolve to finish. This function should * be avoided since using this risk getting the multi interface to "hang". * * If 'entry' is non-NULL, make it point to the resolved dns entry * * Returns CURLE_COULDNT_RESOLVE_HOST if the host was not resolved, and * CURLE_OPERATION_TIMEDOUT if a time-out occurred. */ CURLcode Curl_wait_for_resolv(struct connectdata *conn, struct Curl_dns_entry **entry) { CURLcode rc=CURLE_OK; struct SessionHandle *data = conn->data; long timeout; struct timeval now = Curl_tvnow(); /* now, see if there's a connect timeout or a regular timeout to use instead of the default one */ if(conn->data->set.connecttimeout) timeout = conn->data->set.connecttimeout; else if(conn->data->set.timeout) timeout = conn->data->set.timeout; else timeout = CURL_TIMEOUT_RESOLVE * 1000; /* default name resolve timeout */ /* Wait for the name resolve query to complete. */ while(1) { struct timeval *tvp, tv, store; long timediff; int itimeout; itimeout = (timeout > (long)INT_MAX) ? INT_MAX : (int)timeout; store.tv_sec = itimeout/1000; store.tv_usec = (itimeout%1000)*1000; tvp = ares_timeout(data->state.areschannel, &store, &tv); /* use the timeout period ares returned to us above */ ares_waitperform(conn, (int)(tvp->tv_sec * 1000 + tvp->tv_usec/1000)); if(conn->async.done) break; timediff = Curl_tvdiff(Curl_tvnow(), now); /* spent time */ timeout -= timediff?timediff:1; /* always deduct at least 1 */ if(timeout < 0) { /* our timeout, so we cancel the ares operation */ ares_cancel(data->state.areschannel); break; } } /* Operation complete, if the lookup was successful we now have the entry in the cache. */ if(entry) *entry = conn->async.dns; if(!conn->async.dns) { /* a name was not resolved */ if((timeout < 0) || (conn->async.status == ARES_ETIMEOUT)) { failf(data, "Resolving host timed out: %s", conn->host.dispname); rc = CURLE_COULDNT_RESOLVE_HOST; } else if(conn->async.done) { failf(data, "Could not resolve host: %s (%s)", conn->host.dispname, ares_strerror(conn->async.status)); rc = CURLE_COULDNT_RESOLVE_HOST; } else rc = CURLE_OPERATION_TIMEDOUT; /* close the connection, since we can't return failure here without cleaning up this connection properly */ conn->bits.close = TRUE; } return rc; }
/* * Curl_resolver_wait_resolv() * * waits for a resolve to finish. This function should be avoided since using * this risk getting the multi interface to "hang". * * If 'entry' is non-NULL, make it point to the resolved dns entry * * Returns CURLE_COULDNT_RESOLVE_HOST if the host was not resolved, and * CURLE_OPERATION_TIMEDOUT if a time-out occurred. */ CURLcode Curl_resolver_wait_resolv(struct connectdata *conn, struct Curl_dns_entry **entry) { CURLcode rc=CURLE_OK; struct SessionHandle *data = conn->data; long timeout; struct timeval now = Curl_tvnow(); struct Curl_dns_entry *temp_entry; timeout = Curl_timeleft(data, &now, TRUE); if(!timeout) timeout = CURL_TIMEOUT_RESOLVE * 1000; /* default name resolve timeout */ /* Wait for the name resolve query to complete. */ for(;;) { struct timeval *tvp, tv, store; long timediff; int itimeout; int timeout_ms; itimeout = (timeout > (long)INT_MAX) ? INT_MAX : (int)timeout; store.tv_sec = itimeout/1000; store.tv_usec = (itimeout%1000)*1000; tvp = ares_timeout((ares_channel)data->state.resolver, &store, &tv); /* use the timeout period ares returned to us above if less than one second is left, otherwise just use 1000ms to make sure the progress callback gets called frequent enough */ if(!tvp->tv_sec) timeout_ms = (int)(tvp->tv_usec/1000); else timeout_ms = 1000; waitperform(conn, timeout_ms); Curl_resolver_is_resolved(conn,&temp_entry); if(conn->async.done) break; if(Curl_pgrsUpdate(conn)) { rc = CURLE_ABORTED_BY_CALLBACK; timeout = -1; /* trigger the cancel below */ } else { struct timeval now2 = Curl_tvnow(); timediff = Curl_tvdiff(now2, now); /* spent time */ timeout -= timediff?timediff:1; /* always deduct at least 1 */ now = now2; /* for next loop */ } if(timeout < 0) { /* our timeout, so we cancel the ares operation */ ares_cancel((ares_channel)data->state.resolver); break; } } /* Operation complete, if the lookup was successful we now have the entry in the cache. */ if(entry) *entry = conn->async.dns; if(!conn->async.dns) { /* a name was not resolved */ if((timeout < 0) || (conn->async.status == ARES_ETIMEOUT)) { if(conn->bits.proxy) { failf(data, "Resolving proxy timed out: %s", conn->proxy.dispname); rc = CURLE_COULDNT_RESOLVE_PROXY; } else { failf(data, "Resolving host timed out: %s", conn->host.dispname); rc = CURLE_COULDNT_RESOLVE_HOST; } } else if(conn->async.done) { if(conn->bits.proxy) { failf(data, "Could not resolve proxy: %s (%s)", conn->proxy.dispname, ares_strerror(conn->async.status)); rc = CURLE_COULDNT_RESOLVE_PROXY; } else { failf(data, "Could not resolve host: %s (%s)", conn->host.dispname, ares_strerror(conn->async.status)); rc = CURLE_COULDNT_RESOLVE_HOST; } } else rc = CURLE_OPERATION_TIMEDOUT; /* close the connection, since we can't return failure here without cleaning up this connection properly */ conn->bits.close = TRUE; } return rc; }
CURLcode Curl_telnet(struct connectdata *conn) { CURLcode code; struct SessionHandle *data = conn->data; curl_socket_t sockfd = conn->sock[FIRSTSOCKET]; #if defined(WIN32) || defined(WIN64) HMODULE wsock2; WSOCK2_FUNC close_event_func; WSOCK2_FUNC create_event_func; WSOCK2_FUNC event_select_func; WSOCK2_FUNC enum_netevents_func; WSAEVENT event_handle; WSANETWORKEVENTS events; HANDLE stdin_handle; HANDLE objs[2]; DWORD waitret; DWORD readfile_read; #else fd_set readfd; fd_set keepfd; #endif ssize_t nread; bool keepon = TRUE; char *buf = data->state.buffer; struct TELNET *tn; code = init_telnet(conn); if(code) return code; tn = (struct TELNET *)conn->proto.telnet; code = check_telnet_options(conn); if(code) return code; #if defined(WIN32) || defined(WIN64) /* ** This functionality only works with WinSock >= 2.0. So, ** make sure have it. */ code = check_wsock2(data); if (code) return code; /* OK, so we have WinSock 2.0. We need to dynamically */ /* load ws2_32.dll and get the function pointers we need. */ wsock2 = LoadLibrary("WS2_32.DLL"); if (wsock2 == NULL) { failf(data,"failed to load WS2_32.DLL (%d)",GetLastError()); return CURLE_FAILED_INIT; } /* Grab a pointer to WSACreateEvent */ create_event_func = GetProcAddress(wsock2,"WSACreateEvent"); if (create_event_func == NULL) { failf(data,"failed to find WSACreateEvent function (%d)", GetLastError()); FreeLibrary(wsock2); return CURLE_FAILED_INIT; } /* And WSACloseEvent */ close_event_func = GetProcAddress(wsock2,"WSACloseEvent"); if (create_event_func == NULL) { failf(data,"failed to find WSACloseEvent function (%d)", GetLastError()); FreeLibrary(wsock2); return CURLE_FAILED_INIT; } /* And WSAEventSelect */ event_select_func = GetProcAddress(wsock2,"WSAEventSelect"); if (event_select_func == NULL) { failf(data,"failed to find WSAEventSelect function (%d)", GetLastError()); FreeLibrary(wsock2); return CURLE_FAILED_INIT; } /* And WSAEnumNetworkEvents */ enum_netevents_func = GetProcAddress(wsock2,"WSAEnumNetworkEvents"); if (enum_netevents_func == NULL) { failf(data,"failed to find WSAEnumNetworkEvents function (%d)", GetLastError()); FreeLibrary(wsock2); return CURLE_FAILED_INIT; } /* We want to wait for both stdin and the socket. Since ** the select() function in winsock only works on sockets ** we have to use the WaitForMultipleObjects() call. */ /* First, create a sockets event object */ event_handle = (WSAEVENT)create_event_func(); if (event_handle == WSA_INVALID_EVENT) { failf(data,"WSACreateEvent failed (%d)",WSAGetLastError()); FreeLibrary(wsock2); return CURLE_FAILED_INIT; } /* The get the Windows file handle for stdin */ stdin_handle = GetStdHandle(STD_INPUT_HANDLE); /* Create the list of objects to wait for */ objs[0] = stdin_handle; objs[1] = event_handle; /* Tell winsock what events we want to listen to */ if(event_select_func(sockfd, event_handle, FD_READ|FD_CLOSE) == SOCKET_ERROR) { close_event_func(event_handle); FreeLibrary(wsock2); return 0; } /* Keep on listening and act on events */ while(keepon) { waitret = WaitForMultipleObjects(2, objs, FALSE, INFINITE); switch(waitret - WAIT_OBJECT_0) { case 0: { unsigned char outbuf[2]; int out_count = 0; ssize_t bytes_written; char *buffer = buf; if(!ReadFile(stdin_handle, buf, sizeof(data->state.buffer), &readfile_read, NULL)) { keepon = FALSE; break; } nread = readfile_read; while(nread--) { outbuf[0] = *buffer++; out_count = 1; if(outbuf[0] == CURL_IAC) outbuf[out_count++] = CURL_IAC; Curl_write(conn, conn->sock[FIRSTSOCKET], outbuf, out_count, &bytes_written); } } break; case 1: if(enum_netevents_func(sockfd, event_handle, &events) != SOCKET_ERROR) { if(events.lNetworkEvents & FD_READ) { /* This reallu OUGHT to check its return code. */ (void)Curl_read(conn, sockfd, buf, BUFSIZE - 1, &nread); telrcv(conn, (unsigned char *)buf, nread); fflush(stdout); /* Negotiate if the peer has started negotiating, otherwise don't. We don't want to speak telnet with non-telnet servers, like POP or SMTP. */ if(tn->please_negotiate && !tn->already_negotiated) { negotiate(conn); tn->already_negotiated = 1; } } if(events.lNetworkEvents & FD_CLOSE) { keepon = FALSE; } } break; } } /* We called WSACreateEvent, so call WSACloseEvent */ if (close_event_func(event_handle) == FALSE) { infof(data,"WSACloseEvent failed (%d)",WSAGetLastError()); } /* "Forget" pointers into the library we're about to free */ create_event_func = NULL; close_event_func = NULL; event_select_func = NULL; enum_netevents_func = NULL; /* We called LoadLibrary, so call FreeLibrary */ if (!FreeLibrary(wsock2)) infof(data,"FreeLibrary(wsock2) failed (%d)",GetLastError()); #else FD_ZERO (&readfd); /* clear it */ FD_SET (sockfd, &readfd); FD_SET (0, &readfd); keepfd = readfd; while (keepon) { struct timeval interval; readfd = keepfd; /* set this every lap in the loop */ interval.tv_sec = 1; interval.tv_usec = 0; switch (select (sockfd + 1, &readfd, NULL, NULL, &interval)) { case -1: /* error, stop reading */ keepon = FALSE; continue; case 0: /* timeout */ break; default: /* read! */ if(FD_ISSET(0, &readfd)) { /* read from stdin */ unsigned char outbuf[2]; int out_count = 0; ssize_t bytes_written; char *buffer = buf; nread = read(0, buf, 255); while(nread--) { outbuf[0] = *buffer++; out_count = 1; if(outbuf[0] == CURL_IAC) outbuf[out_count++] = CURL_IAC; Curl_write(conn, conn->sock[FIRSTSOCKET], outbuf, out_count, &bytes_written); } } if(FD_ISSET(sockfd, &readfd)) { /* This OUGHT to check the return code... */ (void)Curl_read(conn, sockfd, buf, BUFSIZE - 1, &nread); /* if we receive 0 or less here, the server closed the connection and we bail out from this! */ if (nread <= 0) { keepon = FALSE; break; } telrcv(conn, (unsigned char *)buf, nread); /* Negotiate if the peer has started negotiating, otherwise don't. We don't want to speak telnet with non-telnet servers, like POP or SMTP. */ if(tn->please_negotiate && !tn->already_negotiated) { negotiate(conn); tn->already_negotiated = 1; } } } if(data->set.timeout) { struct timeval now; /* current time */ now = Curl_tvnow(); if(Curl_tvdiff(now, conn->created)/1000 >= data->set.timeout) { failf(data, "Time-out"); code = CURLE_OPERATION_TIMEOUTED; keepon = FALSE; } } } #endif /* mark this as "no further transfer wanted" */ Curl_Transfer(conn, -1, -1, FALSE, NULL, -1, NULL); return code; }
/* this function does a BLOCKING SSL/TLS (re-)handshake */ static CURLcode handshake(struct connectdata *conn, gnutls_session session, int sockindex, bool duringconnect) { struct SessionHandle *data = conn->data; int rc; do { rc = gnutls_handshake(session); if((rc == GNUTLS_E_AGAIN) || (rc == GNUTLS_E_INTERRUPTED)) { long timeout_ms = DEFAULT_CONNECT_TIMEOUT; long has_passed; if(duringconnect && data->set.connecttimeout) timeout_ms = data->set.connecttimeout*1000; if(data->set.timeout) { /* get the strictest timeout of the ones converted to milliseconds */ if((data->set.timeout*1000) < timeout_ms) timeout_ms = data->set.timeout*1000; } /* Evaluate in milliseconds how much time that has passed */ has_passed = Curl_tvdiff(Curl_tvnow(), data->progress.t_startsingle); /* subtract the passed time */ timeout_ms -= has_passed; if(timeout_ms < 0) { /* a precaution, no need to continue if time already is up */ failf(data, "SSL connection timeout"); return CURLE_OPERATION_TIMEOUTED; } rc = Curl_select(conn->sock[sockindex], conn->sock[sockindex], (int)timeout_ms); if(rc > 0) /* reabable or writable, go loop*/ continue; else if(0 == rc) { /* timeout */ failf(data, "SSL connection timeout"); return CURLE_OPERATION_TIMEDOUT; } else { /* anything that gets here is fatally bad */ failf(data, "select on SSL socket, errno: %d", Curl_sockerrno()); return CURLE_SSL_CONNECT_ERROR; } } else break; } while(1); if (rc < 0) { failf(data, "gnutls_handshake() failed: %s", gnutls_strerror(rc)); return CURLE_SSL_CONNECT_ERROR; } return CURLE_OK; }
static CURLcode telnet_do(struct connectdata *conn, bool *done) { CURLcode result; struct SessionHandle *data = conn->data; curl_socket_t sockfd = conn->sock[FIRSTSOCKET]; #ifdef USE_WINSOCK HMODULE wsock2; WSOCK2_FUNC close_event_func; WSOCK2_FUNC create_event_func; WSOCK2_FUNC event_select_func; WSOCK2_FUNC enum_netevents_func; WSAEVENT event_handle; WSANETWORKEVENTS events; HANDLE stdin_handle; HANDLE objs[2]; DWORD obj_count; DWORD wait_timeout; DWORD waitret; DWORD readfile_read; int err; #else int interval_ms; struct pollfd pfd[2]; int poll_cnt; curl_off_t total_dl = 0; curl_off_t total_ul = 0; #endif ssize_t nread; struct timeval now; bool keepon = TRUE; char *buf = data->state.buffer; struct TELNET *tn; *done = TRUE; /* unconditionally */ result = init_telnet(conn); if(result) return result; tn = (struct TELNET *)data->req.protop; result = check_telnet_options(conn); if(result) return result; #ifdef USE_WINSOCK /* ** This functionality only works with WinSock >= 2.0. So, ** make sure have it. */ result = check_wsock2(data); if(result) return result; /* OK, so we have WinSock 2.0. We need to dynamically */ /* load ws2_32.dll and get the function pointers we need. */ wsock2 = LoadLibrary(TEXT("WS2_32.DLL")); if(wsock2 == NULL) { failf(data, "failed to load WS2_32.DLL (%d)", ERRNO); return CURLE_FAILED_INIT; } /* Grab a pointer to WSACreateEvent */ create_event_func = GetProcAddress(wsock2, "WSACreateEvent"); if(create_event_func == NULL) { failf(data, "failed to find WSACreateEvent function (%d)", ERRNO); FreeLibrary(wsock2); return CURLE_FAILED_INIT; } /* And WSACloseEvent */ close_event_func = GetProcAddress(wsock2, "WSACloseEvent"); if(close_event_func == NULL) { failf(data, "failed to find WSACloseEvent function (%d)", ERRNO); FreeLibrary(wsock2); return CURLE_FAILED_INIT; } /* And WSAEventSelect */ event_select_func = GetProcAddress(wsock2, "WSAEventSelect"); if(event_select_func == NULL) { failf(data, "failed to find WSAEventSelect function (%d)", ERRNO); FreeLibrary(wsock2); return CURLE_FAILED_INIT; } /* And WSAEnumNetworkEvents */ enum_netevents_func = GetProcAddress(wsock2, "WSAEnumNetworkEvents"); if(enum_netevents_func == NULL) { failf(data, "failed to find WSAEnumNetworkEvents function (%d)", ERRNO); FreeLibrary(wsock2); return CURLE_FAILED_INIT; } /* We want to wait for both stdin and the socket. Since ** the select() function in winsock only works on sockets ** we have to use the WaitForMultipleObjects() call. */ /* First, create a sockets event object */ event_handle = (WSAEVENT)create_event_func(); if(event_handle == WSA_INVALID_EVENT) { failf(data, "WSACreateEvent failed (%d)", SOCKERRNO); FreeLibrary(wsock2); return CURLE_FAILED_INIT; } /* Tell winsock what events we want to listen to */ if(event_select_func(sockfd, event_handle, FD_READ|FD_CLOSE) == SOCKET_ERROR) { close_event_func(event_handle); FreeLibrary(wsock2); return CURLE_OK; } /* The get the Windows file handle for stdin */ stdin_handle = GetStdHandle(STD_INPUT_HANDLE); /* Create the list of objects to wait for */ objs[0] = event_handle; objs[1] = stdin_handle; /* If stdin_handle is a pipe, use PeekNamedPipe() method to check it, else use the old WaitForMultipleObjects() way */ if(GetFileType(stdin_handle) == FILE_TYPE_PIPE || data->set.is_fread_set) { /* Don't wait for stdin_handle, just wait for event_handle */ obj_count = 1; /* Check stdin_handle per 100 milliseconds */ wait_timeout = 100; } else { obj_count = 2; wait_timeout = 1000; } /* Keep on listening and act on events */ while(keepon) { waitret = WaitForMultipleObjects(obj_count, objs, FALSE, wait_timeout); switch(waitret) { case WAIT_TIMEOUT: { for(;;) { if(data->set.is_fread_set) { /* read from user-supplied method */ result = (int)data->state.fread_func(buf, 1, BUFSIZE - 1, data->state.in); if(result == CURL_READFUNC_ABORT) { keepon = FALSE; result = CURLE_READ_ERROR; break; } if(result == CURL_READFUNC_PAUSE) break; if(result == 0) /* no bytes */ break; readfile_read = result; /* fall thru with number of bytes read */ } else { /* read from stdin */ if(!PeekNamedPipe(stdin_handle, NULL, 0, NULL, &readfile_read, NULL)) { keepon = FALSE; result = CURLE_READ_ERROR; break; } if(!readfile_read) break; if(!ReadFile(stdin_handle, buf, sizeof(data->state.buffer), &readfile_read, NULL)) { keepon = FALSE; result = CURLE_READ_ERROR; break; } } result = send_telnet_data(conn, buf, readfile_read); if(result) { keepon = FALSE; break; } } } break; case WAIT_OBJECT_0 + 1: { if(!ReadFile(stdin_handle, buf, sizeof(data->state.buffer), &readfile_read, NULL)) { keepon = FALSE; result = CURLE_READ_ERROR; break; } result = send_telnet_data(conn, buf, readfile_read); if(result) { keepon = FALSE; break; } } break; case WAIT_OBJECT_0: events.lNetworkEvents = 0; if(SOCKET_ERROR == enum_netevents_func(sockfd, event_handle, &events)) { if((err = SOCKERRNO) != EINPROGRESS) { infof(data, "WSAEnumNetworkEvents failed (%d)", err); keepon = FALSE; result = CURLE_READ_ERROR; } break; } if(events.lNetworkEvents & FD_READ) { /* read data from network */ result = Curl_read(conn, sockfd, buf, BUFSIZE - 1, &nread); /* read would've blocked. Loop again */ if(result == CURLE_AGAIN) break; /* returned not-zero, this an error */ else if(result) { keepon = FALSE; break; } /* returned zero but actually received 0 or less here, the server closed the connection and we bail out */ else if(nread <= 0) { keepon = FALSE; break; } result = telrcv(conn, (unsigned char *) buf, nread); if(result) { keepon = FALSE; break; } /* Negotiate if the peer has started negotiating, otherwise don't. We don't want to speak telnet with non-telnet servers, like POP or SMTP. */ if(tn->please_negotiate && !tn->already_negotiated) { negotiate(conn); tn->already_negotiated = 1; } } if(events.lNetworkEvents & FD_CLOSE) { keepon = FALSE; } break; } if(data->set.timeout) { now = Curl_tvnow(); if(Curl_tvdiff(now, conn->created) >= data->set.timeout) { failf(data, "Time-out"); result = CURLE_OPERATION_TIMEDOUT; keepon = FALSE; } } } /* We called WSACreateEvent, so call WSACloseEvent */ if(!close_event_func(event_handle)) { infof(data, "WSACloseEvent failed (%d)", SOCKERRNO); } /* "Forget" pointers into the library we're about to free */ create_event_func = NULL; close_event_func = NULL; event_select_func = NULL; enum_netevents_func = NULL; /* We called LoadLibrary, so call FreeLibrary */ if(!FreeLibrary(wsock2)) infof(data, "FreeLibrary(wsock2) failed (%d)", ERRNO); #else pfd[0].fd = sockfd; pfd[0].events = POLLIN; if(data->set.is_fread_set) { poll_cnt = 1; interval_ms = 100; /* poll user-supplied read function */ } else { /* really using fread, so infile is a FILE* */ pfd[1].fd = fileno((FILE *)data->state.in); pfd[1].events = POLLIN; poll_cnt = 2; interval_ms = 1 * 1000; } while(keepon) { switch (Curl_poll(pfd, poll_cnt, interval_ms)) { case -1: /* error, stop reading */ keepon = FALSE; continue; case 0: /* timeout */ pfd[0].revents = 0; pfd[1].revents = 0; /* fall through */ default: /* read! */ if(pfd[0].revents & POLLIN) { /* read data from network */ result = Curl_read(conn, sockfd, buf, BUFSIZE - 1, &nread); /* read would've blocked. Loop again */ if(result == CURLE_AGAIN) break; /* returned not-zero, this an error */ else if(result) { keepon = FALSE; break; } /* returned zero but actually received 0 or less here, the server closed the connection and we bail out */ else if(nread <= 0) { keepon = FALSE; break; } total_dl += nread; Curl_pgrsSetDownloadCounter(data, total_dl); result = telrcv(conn, (unsigned char *)buf, nread); if(result) { keepon = FALSE; break; } /* Negotiate if the peer has started negotiating, otherwise don't. We don't want to speak telnet with non-telnet servers, like POP or SMTP. */ if(tn->please_negotiate && !tn->already_negotiated) { negotiate(conn); tn->already_negotiated = 1; } } nread = 0; if(poll_cnt == 2) { if(pfd[1].revents & POLLIN) { /* read from in file */ nread = read(pfd[1].fd, buf, BUFSIZE - 1); } } else { /* read from user-supplied method */ nread = (int)data->state.fread_func(buf, 1, BUFSIZE - 1, data->state.in); if(nread == CURL_READFUNC_ABORT) { keepon = FALSE; break; } if(nread == CURL_READFUNC_PAUSE) break; } if(nread > 0) { result = send_telnet_data(conn, buf, nread); if(result) { keepon = FALSE; break; } total_ul += nread; Curl_pgrsSetUploadCounter(data, total_ul); } else if(nread < 0) keepon = FALSE; break; } /* poll switch statement */ if(data->set.timeout) { now = Curl_tvnow(); if(Curl_tvdiff(now, conn->created) >= data->set.timeout) { failf(data, "Time-out"); result = CURLE_OPERATION_TIMEDOUT; keepon = FALSE; } } if(Curl_pgrsUpdate(conn)) { result = CURLE_ABORTED_BY_CALLBACK; break; } } #endif /* mark this as "no further transfer wanted" */ Curl_setup_transfer(conn, -1, -1, FALSE, NULL, -1, NULL); return result; }
CURLcode Curl_connecthost(struct connectdata *conn, /* context */ const struct Curl_dns_entry *remotehost, /* use this one */ curl_socket_t *sockconn, /* the connected socket */ Curl_addrinfo **addr, /* the one we used */ bool *connected) /* really connected? */ { struct SessionHandle *data = conn->data; curl_socket_t sockfd = CURL_SOCKET_BAD; int aliasindex; int num_addr; Curl_addrinfo *ai; Curl_addrinfo *curr_addr; struct timeval after; struct timeval before = Curl_tvnow(); /************************************************************* * Figure out what maximum time we have left *************************************************************/ long timeout_ms= DEFAULT_CONNECT_TIMEOUT; long timeout_per_addr; *connected = FALSE; /* default to not connected */ if(data->set.timeout || data->set.connecttimeout) { long has_passed; /* Evaluate in milliseconds how much time that has passed */ has_passed = Curl_tvdiff(Curl_tvnow(), data->progress.t_startsingle); #ifndef min #define min(a, b) ((a) < (b) ? (a) : (b)) #endif /* get the most strict timeout of the ones converted to milliseconds */ if(data->set.timeout && data->set.connecttimeout) { if (data->set.timeout < data->set.connecttimeout) timeout_ms = data->set.timeout*1000; else timeout_ms = data->set.connecttimeout*1000; } else if(data->set.timeout) timeout_ms = data->set.timeout*1000; else timeout_ms = data->set.connecttimeout*1000; /* subtract the passed time */ timeout_ms -= has_passed; if(timeout_ms < 0) { /* a precaution, no need to continue if time already is up */ failf(data, "Connection time-out"); return CURLE_OPERATION_TIMEOUTED; } } Curl_expire(data, timeout_ms); /* Max time for each address */ num_addr = Curl_num_addresses(remotehost->addr); timeout_per_addr = timeout_ms / num_addr; ai = remotehost->addr; /* Below is the loop that attempts to connect to all IP-addresses we * know for the given host. One by one until one IP succeeds. */ if(data->state.used_interface == Curl_if_multi) /* don't hang when doing multi */ timeout_per_addr = 0; /* * Connecting with a Curl_addrinfo chain */ for (curr_addr = ai, aliasindex=0; curr_addr; curr_addr = curr_addr->ai_next, aliasindex++) { /* start connecting to the IP curr_addr points to */ sockfd = singleipconnect(conn, curr_addr, timeout_per_addr, connected); if(sockfd != CURL_SOCKET_BAD) break; /* get a new timeout for next attempt */ after = Curl_tvnow(); timeout_ms -= Curl_tvdiff(after, before); if(timeout_ms < 0) { failf(data, "connect() timed out!"); return CURLE_OPERATION_TIMEOUTED; } before = after; } /* end of connect-to-each-address loop */ if (sockfd == CURL_SOCKET_BAD) { /* no good connect was made */ *sockconn = CURL_SOCKET_BAD; failf(data, "couldn't connect to host"); return CURLE_COULDNT_CONNECT; } /* leave the socket in non-blocking mode */ /* store the address we use */ if(addr) *addr = curr_addr; /* allow NULL-pointers to get passed in */ if(sockconn) *sockconn = sockfd; /* the socket descriptor we've connected */ data->info.numconnects++; /* to track the number of connections made */ return CURLE_OK; }
CURLcode Curl_connecthost(struct connectdata *conn, /* context */ struct Curl_dns_entry *remotehost, /* use this one */ int port, /* connect to this */ int *sockconn, /* the connected socket */ Curl_ipconnect **addr, /* the one we used */ bool *connected) /* really connected? */ { struct SessionHandle *data = conn->data; int rc; int sockfd=-1; int aliasindex=0; char *hostname; struct timeval after; struct timeval before = Curl_tvnow(); /************************************************************* * Figure out what maximum time we have left *************************************************************/ long timeout_ms=300000; /* milliseconds, default to five minutes */ *connected = FALSE; /* default to not connected */ if(data->set.timeout || data->set.connecttimeout) { double has_passed; /* Evaluate in milliseconds how much time that has passed */ has_passed = Curl_tvdiff(Curl_tvnow(), data->progress.start); #ifndef min #define min(a, b) ((a) < (b) ? (a) : (b)) #endif /* get the most strict timeout of the ones converted to milliseconds */ if(data->set.timeout && data->set.connecttimeout) { if (data->set.timeout < data->set.connecttimeout) timeout_ms = data->set.timeout*1000; else timeout_ms = data->set.connecttimeout*1000; } else if(data->set.timeout) timeout_ms = data->set.timeout*1000; else timeout_ms = data->set.connecttimeout*1000; /* subtract the passed time */ timeout_ms -= (long)has_passed; if(timeout_ms < 0) { /* a precaution, no need to continue if time already is up */ failf(data, "Connection time-out"); return CURLE_OPERATION_TIMEOUTED; } } hostname = data->change.proxy?conn->proxyhost:conn->hostname; infof(data, "About to connect() to %s%s%s:%d\n", conn->bits.ipv6_ip?"[":"", hostname, conn->bits.ipv6_ip?"]":"", port); #ifdef ENABLE_IPV6 /* * Connecting with IPv6 support is so much easier and cleanly done */ { struct addrinfo *ai; port =0; /* prevent compiler warning */ for (ai = remotehost->addr; ai; ai = ai->ai_next, aliasindex++) { sockfd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol); if (sockfd < 0) continue; if(conn->data->set.device) { /* user selected to bind the outgoing socket to a specified "device" before doing connect */ CURLcode res = bindlocal(conn, sockfd); if(res) return res; } /* set socket non-blocking */ Curl_nonblock(sockfd, TRUE); rc = connect(sockfd, ai->ai_addr, ai->ai_addrlen); if(-1 == rc) { int error=Curl_ourerrno(); switch (error) { case EINPROGRESS: case EWOULDBLOCK: #if defined(EAGAIN) && EAGAIN != EWOULDBLOCK /* On some platforms EAGAIN and EWOULDBLOCK are the * same value, and on others they are different, hence * the odd #if */ case EAGAIN: #endif case EINTR: /* asynchronous connect, wait for connect or timeout */ if(data->state.used_interface == Curl_if_multi) /* don't hang when doing multi */ timeout_ms = 0; rc = waitconnect(sockfd, timeout_ms); break; case ECONNREFUSED: /* no one listening */ default: /* unknown error, fallthrough and try another address! */ failf(data, "Failed connect to %s: %d", hostname, error); break; } } if(0 == rc) { /* we might be connected, if the socket says it is OK! Ask it! */ int err; err = socketerror(sockfd); if ((0 == err) || (EISCONN == err)) { /* we are connected, awesome! */ *connected = TRUE; /* this is truly a connect */ break; } failf(data, "socket error: %d", err); /* we are _not_ connected, it was a false alert, continue please */ } else if(2 == rc) /* waitconnect() returned error */ ; else if(data->state.used_interface == Curl_if_multi) { /* When running the multi interface, we bail out here */ rc = 0; break; } /* connect failed or timed out */ sclose(sockfd); sockfd = -1; /* get a new timeout for next attempt */ after = Curl_tvnow(); timeout_ms -= Curl_tvdiff(after, before); if(timeout_ms < 0) { failf(data, "connect() timed out!"); return CURLE_OPERATION_TIMEOUTED; } before = after; continue; } if (sockfd < 0) return CURLE_COULDNT_CONNECT; /* leave the socket in non-blocking mode */ if(addr) *addr = ai; /* the address we ended up connected to */ } #else /* * Connecting with IPv4-only support */ if(!remotehost->addr->h_addr_list[0]) { /* If there is no addresses in the address list, then we return error right away */ failf(data, "no address available"); return CURLE_COULDNT_CONNECT; } /* create an IPv4 TCP socket */ sockfd = socket(AF_INET, SOCK_STREAM, 0); if(-1 == sockfd) { failf(data, "couldn't create socket"); return CURLE_COULDNT_CONNECT; /* big time error */ } if(conn->data->set.device) { /* user selected to bind the outgoing socket to a specified "device" before doing connect */ CURLcode res = bindlocal(conn, sockfd); if(res) return res; } /* Convert socket to non-blocking type */ Curl_nonblock(sockfd, TRUE); /* This is the loop that attempts to connect to all IP-addresses we know for the given host. One by one. */ for(rc=-1, aliasindex=0; rc && (struct in_addr *)remotehost->addr->h_addr_list[aliasindex]; aliasindex++) { struct sockaddr_in serv_addr; /* do this nasty work to do the connect */ memset((char *) &serv_addr, '\0', sizeof(serv_addr)); memcpy((char *)&(serv_addr.sin_addr), (struct in_addr *)remotehost->addr->h_addr_list[aliasindex], sizeof(struct in_addr)); serv_addr.sin_family = remotehost->addr->h_addrtype; serv_addr.sin_port = htons((unsigned short)port); rc = connect(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)); if(-1 == rc) { int error=Curl_ourerrno(); switch (error) { case EINPROGRESS: case EWOULDBLOCK: #if defined(EAGAIN) && EAGAIN != EWOULDBLOCK /* On some platforms EAGAIN and EWOULDBLOCK are the * same value, and on others they are different, hence * the odd #if */ case EAGAIN: #endif /* asynchronous connect, wait for connect or timeout */ if(data->state.used_interface == Curl_if_multi) /* don't hang when doing multi */ timeout_ms = 0; rc = waitconnect(sockfd, timeout_ms); break; default: /* unknown error, fallthrough and try another address! */ failf(data, "Failed to connect to %s IP number %d: %d", hostname, aliasindex+1, error); break; } } /* The '1 == rc' comes from the waitconnect(), and not from connect(). We can be sure of this since connect() cannot return 1. */ if((1 == rc) && (data->state.used_interface == Curl_if_multi)) { /* Timeout when running the multi interface, we return here with a CURLE_OK return code. */ rc = 0; break; } if(0 == rc) { int err = socketerror(sockfd); if ((0 == err) || (EISCONN == err)) { /* we are connected, awesome! */ *connected = TRUE; /* this is a true connect */ break; } /* nope, not connected for real */ rc = -1; } if(0 != rc) { /* get a new timeout for next attempt */ after = Curl_tvnow(); timeout_ms -= Curl_tvdiff(after, before); if(timeout_ms < 0) { failf(data, "Connect timeout on IP number %d", aliasindex+1); break; } before = after; continue; /* try next address */ } break; } if(0 != rc) { /* no good connect was made */ sclose(sockfd); *sockconn = -1; failf(data, "Connect failed"); return CURLE_COULDNT_CONNECT; } /* leave the socket in non-blocking mode */ if(addr) /* this is the address we've connected to */ *addr = (struct in_addr *)remotehost->addr->h_addr_list[aliasindex]; #endif /* allow NULL-pointers to get passed in */ if(sockconn) *sockconn = sockfd; /* the socket descriptor we've connected */ return CURLE_OK; }