comparison dbutil.c @ 1022:4121ca987e6a

connect_remote() is now always non-blocking
author Matt Johnston <matt@ucc.asn.au>
date Sat, 14 Feb 2015 09:56:11 +0800
parents 24135c8e1d46
children a00303a7d247 d3925ed45a85
comparison
equal deleted inserted replaced
1021:24135c8e1d46 1022:4121ca987e6a
433 /* Connect via TCP to a host. Connection will try ipv4 or ipv6, will 433 /* Connect via TCP to a host. Connection will try ipv4 or ipv6, will
434 * return immediately if nonblocking is set. On failure, if errstring 434 * return immediately if nonblocking is set. On failure, if errstring
435 * wasn't null, it will be a newly malloced error message */ 435 * wasn't null, it will be a newly malloced error message */
436 436
437 /* TODO: maxfd */ 437 /* TODO: maxfd */
438 int connect_remote(const char* remotehost, const char* remoteport, 438 int connect_remote(const char* remotehost, const char* remoteport, char ** errstring) {
439 int nonblocking, char ** errstring) {
440 439
441 struct addrinfo *res0 = NULL, *res = NULL, hints; 440 struct addrinfo *res0 = NULL, *res = NULL, hints;
442 int sock; 441 int sock;
443 int err; 442 int err;
444 443
473 if (sock < 0) { 472 if (sock < 0) {
474 err = errno; 473 err = errno;
475 continue; 474 continue;
476 } 475 }
477 476
478 if (nonblocking) { 477 setnonblocking(sock);
479 setnonblocking(sock);
480 478
481 #if defined(__linux__) && defined(TCP_DEFER_ACCEPT) 479 #if defined(__linux__) && defined(TCP_DEFER_ACCEPT)
482 set_piggyback_ack(sock); 480 set_piggyback_ack(sock);
483 #endif 481 #endif
484 }
485 482
486 if (connect(sock, res->ai_addr, res->ai_addrlen) < 0) { 483 if (connect(sock, res->ai_addr, res->ai_addrlen) < 0) {
487 if (errno == EINPROGRESS && nonblocking) { 484 if (errno == EINPROGRESS) {
488 TRACE(("Connect in progress")) 485 TRACE(("Connect in progress"))
489 break; 486 break;
490 } else { 487 } else {
491 err = errno; 488 err = errno;
492 close(sock); 489 close(sock);
496 } 493 }
497 494
498 break; /* Success */ 495 break; /* Success */
499 } 496 }
500 497
501 if (sock < 0 && !(errno == EINPROGRESS && nonblocking)) { 498 if (sock < 0 && !(errno == EINPROGRESS)) {
502 /* Failed */ 499 /* Failed */
503 if (errstring != NULL && *errstring == NULL) { 500 if (errstring != NULL && *errstring == NULL) {
504 int len; 501 int len;
505 len = 20 + strlen(strerror(err)); 502 len = 20 + strlen(strerror(err));
506 *errstring = (char*)m_malloc(len); 503 *errstring = (char*)m_malloc(len);