| 1 |
// Copyright 2022 gRPC Authors |
| 2 |
// |
| 3 |
// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 |
// you may not use this file except in compliance with the License. |
| 5 |
// You may obtain a copy of the License at |
| 6 |
// |
| 7 |
// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 |
// |
| 9 |
// Unless required by applicable law or agreed to in writing, software |
| 10 |
// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 |
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 |
// See the License for the specific language governing permissions and |
| 13 |
// limitations under the License. |
| 14 |
|
| 15 |
#include "test/core/event_engine/posix/posix_engine_test_utils.h" |
| 16 |
|
| 17 |
#include <errno.h> |
| 18 |
#include <fcntl.h> |
| 19 |
#include <poll.h> |
| 20 |
#include <stdlib.h> |
| 21 |
#include <sys/socket.h> |
| 22 |
|
| 23 |
#include <grpc/support/log.h> |
| 24 |
|
| 25 |
namespace grpc_event_engine { |
| 26 |
namespace posix_engine { |
| 27 |
|
| 28 |
using ResolvedAddress = |
| 29 |
grpc_event_engine::experimental::EventEngine::ResolvedAddress; |
| 30 |
|
| 31 |
// Creates a client socket and blocks until it connects to the specified |
| 32 |
// server address. The function abort fails upon encountering errors. |
| 33 |
int ConnectToServerOrDie(const ResolvedAddress& server_address) { |
| 34 |
int client_fd; |
| 35 |
int one = 1; |
| 36 |
int flags; |
| 37 |
|
| 38 |
client_fd = socket(AF_INET6, SOCK_STREAM, 0); |
| 39 |
setsockopt(client_fd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)); |
| 40 |
// Make fd non-blocking. |
| 41 |
flags = fcntl(client_fd, F_GETFL, 0); |
| 42 |
fcntl(client_fd, F_SETFL, flags | O_NONBLOCK); |
| 43 |
|
| 44 |
if (connect(client_fd, const_cast<struct sockaddr*>(server_address.address()), |
| 45 |
server_address.size()) == -1) { |
| 46 |
if (errno == EINPROGRESS) { |
| 47 |
struct pollfd pfd; |
| 48 |
pfd.fd = client_fd; |
| 49 |
pfd.events = POLLOUT; |
| 50 |
pfd.revents = 0; |
| 51 |
if (poll(&pfd, 1, -1) == -1) { |
| 52 |
gpr_log(GPR_ERROR, "poll() failed during connect; errno=%d", errno); |
| 53 |
abort(); |
| 54 |
} |
| 55 |
} else { |
| 56 |
gpr_log(GPR_ERROR, "Failed to connect to the server (errno=%d)", errno); |
| 57 |
abort(); |
| 58 |
} |
| 59 |
} |
| 60 |
return client_fd; |
| 61 |
} |
| 62 |
|
| 63 |
} // namespace posix_engine |
| 64 |
} // namespace grpc_event_engine |