| 651 | } |
| 652 | |
| 653 | static inline SOCKET DoConnectImpl(const struct addrinfo* res, const TInstant& deadLine) { |
| 654 | const struct addrinfo* addr0 = res; |
| 655 | |
| 656 | while (res) { |
| 657 | TSocketHolder s(socket(res->ai_family, res->ai_socktype, res->ai_protocol)); |
| 658 | |
| 659 | if (s.Closed()) { |
| 660 | res = Iterate(res, addr0, LastSystemError()); |
| 661 | |
| 662 | continue; |
| 663 | } |
| 664 | |
| 665 | SetNonBlock(s, true); |
| 666 | |
| 667 | if (connect(s, res->ai_addr, (int)res->ai_addrlen)) { |
| 668 | int err = LastSystemError(); |
| 669 | |
| 670 | if (err == EINPROGRESS || err == EAGAIN || err == EWOULDBLOCK) { |
| 671 | /* |
| 672 | * must wait |
| 673 | */ |
| 674 | struct pollfd p = { |
| 675 | (SOCKET)s, |
| 676 | POLLOUT, |
| 677 | 0}; |
| 678 | |
| 679 | const ssize_t n = PollD(&p, 1, deadLine); |
| 680 | |
| 681 | /* |
| 682 | * timeout occured |
| 683 | */ |
| 684 | if (n < 0) { |
| 685 | ythrow TSystemError(-(int)n) << "can not connect"; |
| 686 | } |
| 687 | |
| 688 | CheckedGetSockOpt(s, SOL_SOCKET, SO_ERROR, err, "socket error"); |
| 689 | |
| 690 | if (!err) { |
| 691 | return s.Release(); |
| 692 | } |
| 693 | } |
| 694 | |
| 695 | res = Iterate(res, addr0, err); |
| 696 | |
| 697 | continue; |
| 698 | } |
| 699 | |
| 700 | return s.Release(); |
| 701 | } |
| 702 | |
| 703 | ythrow yexception() << "something went wrong: nullptr at addrinfo"; |
| 704 | } |
| 705 | |
| 706 | static inline SOCKET DoConnect(const struct addrinfo* res, const TInstant& deadLine) { |
| 707 | TSocketHolder ret(DoConnectImpl(res, deadLine)); |
no test coverage detected