blob: 20cc92bf593a6d14ccf9cf6e94f5a0ae5f7411fe [file] [log] [blame]
[email protected]2ef2b0e2014-07-09 21:12:341// Copyright 2014 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
tfarina4eb7aad82015-09-14 17:10:345#include "net/socket/socket_posix.h"
[email protected]2ef2b0e2014-07-09 21:12:346
7#include <errno.h>
8#include <netinet/in.h>
9#include <sys/socket.h>
dchengc7eeda422015-12-26 03:56:4810#include <utility>
[email protected]2ef2b0e2014-07-09 21:12:3411
12#include "base/callback_helpers.h"
tfarina060df7e2015-12-16 05:15:3213#include "base/files/file_util.h"
[email protected]2ef2b0e2014-07-09 21:12:3414#include "base/logging.h"
15#include "base/posix/eintr_wrapper.h"
ssid6d6b40102016-04-05 18:59:5616#include "base/trace_event/trace_event.h"
davidben28150272016-06-06 21:03:1217#include "build/build_config.h"
[email protected]2ef2b0e2014-07-09 21:12:3418#include "net/base/io_buffer.h"
19#include "net/base/ip_endpoint.h"
20#include "net/base/net_errors.h"
tfarina3d87d7cd2016-01-13 02:26:5921#include "net/base/sockaddr_storage.h"
xunjieli0b7f5b62016-12-06 20:43:4822#include "net/base/trace_constants.h"
[email protected]2ef2b0e2014-07-09 21:12:3423
24namespace net {
25
26namespace {
27
28int MapAcceptError(int os_error) {
29 switch (os_error) {
30 // If the client aborts the connection before the server calls accept,
31 // POSIX specifies accept should fail with ECONNABORTED. The server can
32 // ignore the error and just call accept again, so we map the error to
33 // ERR_IO_PENDING. See UNIX Network Programming, Vol. 1, 3rd Ed., Sec.
34 // 5.11, "Connection Abort before accept Returns".
35 case ECONNABORTED:
36 return ERR_IO_PENDING;
37 default:
38 return MapSystemError(os_error);
39 }
40}
41
42int MapConnectError(int os_error) {
43 switch (os_error) {
44 case EINPROGRESS:
45 return ERR_IO_PENDING;
46 case EACCES:
47 return ERR_NETWORK_ACCESS_DENIED;
48 case ETIMEDOUT:
49 return ERR_CONNECTION_TIMED_OUT;
50 default: {
51 int net_error = MapSystemError(os_error);
52 if (net_error == ERR_FAILED)
53 return ERR_CONNECTION_FAILED; // More specific than ERR_FAILED.
54 return net_error;
55 }
56 }
57}
58
59} // namespace
60
tfarina4eb7aad82015-09-14 17:10:3461SocketPosix::SocketPosix()
[email protected]2ef2b0e2014-07-09 21:12:3462 : socket_fd_(kInvalidSocket),
ssid5dd4fb32017-02-16 23:57:1763 accept_socket_watcher_(FROM_HERE),
64 read_socket_watcher_(FROM_HERE),
[email protected]2ef2b0e2014-07-09 21:12:3465 read_buf_len_(0),
ssid5dd4fb32017-02-16 23:57:1766 write_socket_watcher_(FROM_HERE),
[email protected]2ef2b0e2014-07-09 21:12:3467 write_buf_len_(0),
tfarina4eb7aad82015-09-14 17:10:3468 waiting_connect_(false) {}
[email protected]2ef2b0e2014-07-09 21:12:3469
tfarina4eb7aad82015-09-14 17:10:3470SocketPosix::~SocketPosix() {
[email protected]2ef2b0e2014-07-09 21:12:3471 Close();
72}
73
tfarina4eb7aad82015-09-14 17:10:3474int SocketPosix::Open(int address_family) {
[email protected]2ef2b0e2014-07-09 21:12:3475 DCHECK(thread_checker_.CalledOnValidThread());
76 DCHECK_EQ(kInvalidSocket, socket_fd_);
77 DCHECK(address_family == AF_INET ||
78 address_family == AF_INET6 ||
79 address_family == AF_UNIX);
80
81 socket_fd_ = CreatePlatformSocket(
82 address_family,
83 SOCK_STREAM,
84 address_family == AF_UNIX ? 0 : IPPROTO_TCP);
85 if (socket_fd_ < 0) {
86 PLOG(ERROR) << "CreatePlatformSocket() returned an error, errno=" << errno;
87 return MapSystemError(errno);
88 }
89
tfarina060df7e2015-12-16 05:15:3290 if (!base::SetNonBlocking(socket_fd_)) {
[email protected]2ef2b0e2014-07-09 21:12:3491 int rv = MapSystemError(errno);
92 Close();
93 return rv;
94 }
95
96 return OK;
97}
98
tfarina4eb7aad82015-09-14 17:10:3499int SocketPosix::AdoptConnectedSocket(SocketDescriptor socket,
100 const SockaddrStorage& address) {
[email protected]2ef2b0e2014-07-09 21:12:34101 DCHECK(thread_checker_.CalledOnValidThread());
102 DCHECK_EQ(kInvalidSocket, socket_fd_);
103
104 socket_fd_ = socket;
105
tfarina060df7e2015-12-16 05:15:32106 if (!base::SetNonBlocking(socket_fd_)) {
[email protected]2ef2b0e2014-07-09 21:12:34107 int rv = MapSystemError(errno);
108 Close();
109 return rv;
110 }
111
112 SetPeerAddress(address);
113 return OK;
114}
115
tfarina4eb7aad82015-09-14 17:10:34116SocketDescriptor SocketPosix::ReleaseConnectedSocket() {
cmasoneca100d52014-09-03 18:11:11117 StopWatchingAndCleanUp();
118 SocketDescriptor socket_fd = socket_fd_;
119 socket_fd_ = kInvalidSocket;
120 return socket_fd;
121}
122
tfarina4eb7aad82015-09-14 17:10:34123int SocketPosix::Bind(const SockaddrStorage& address) {
[email protected]2ef2b0e2014-07-09 21:12:34124 DCHECK(thread_checker_.CalledOnValidThread());
125 DCHECK_NE(kInvalidSocket, socket_fd_);
126
127 int rv = bind(socket_fd_, address.addr, address.addr_len);
128 if (rv < 0) {
129 PLOG(ERROR) << "bind() returned an error, errno=" << errno;
130 return MapSystemError(errno);
131 }
132
133 return OK;
134}
135
tfarina4eb7aad82015-09-14 17:10:34136int SocketPosix::Listen(int backlog) {
[email protected]2ef2b0e2014-07-09 21:12:34137 DCHECK(thread_checker_.CalledOnValidThread());
138 DCHECK_NE(kInvalidSocket, socket_fd_);
139 DCHECK_LT(0, backlog);
140
141 int rv = listen(socket_fd_, backlog);
142 if (rv < 0) {
143 PLOG(ERROR) << "listen() returned an error, errno=" << errno;
144 return MapSystemError(errno);
145 }
146
147 return OK;
148}
149
danakj655b66c2016-04-16 00:51:38150int SocketPosix::Accept(std::unique_ptr<SocketPosix>* socket,
tfarina4eb7aad82015-09-14 17:10:34151 const CompletionCallback& callback) {
[email protected]2ef2b0e2014-07-09 21:12:34152 DCHECK(thread_checker_.CalledOnValidThread());
153 DCHECK_NE(kInvalidSocket, socket_fd_);
154 DCHECK(accept_callback_.is_null());
155 DCHECK(socket);
156 DCHECK(!callback.is_null());
157
158 int rv = DoAccept(socket);
159 if (rv != ERR_IO_PENDING)
160 return rv;
161
162 if (!base::MessageLoopForIO::current()->WatchFileDescriptor(
163 socket_fd_, true, base::MessageLoopForIO::WATCH_READ,
164 &accept_socket_watcher_, this)) {
165 PLOG(ERROR) << "WatchFileDescriptor failed on accept, errno " << errno;
166 return MapSystemError(errno);
167 }
168
169 accept_socket_ = socket;
170 accept_callback_ = callback;
171 return ERR_IO_PENDING;
172}
173
tfarina4eb7aad82015-09-14 17:10:34174int SocketPosix::Connect(const SockaddrStorage& address,
175 const CompletionCallback& callback) {
[email protected]2ef2b0e2014-07-09 21:12:34176 DCHECK(thread_checker_.CalledOnValidThread());
177 DCHECK_NE(kInvalidSocket, socket_fd_);
178 DCHECK(!waiting_connect_);
179 DCHECK(!callback.is_null());
180
181 SetPeerAddress(address);
182
183 int rv = DoConnect();
184 if (rv != ERR_IO_PENDING)
185 return rv;
186
187 if (!base::MessageLoopForIO::current()->WatchFileDescriptor(
188 socket_fd_, true, base::MessageLoopForIO::WATCH_WRITE,
189 &write_socket_watcher_, this)) {
190 PLOG(ERROR) << "WatchFileDescriptor failed on connect, errno " << errno;
191 return MapSystemError(errno);
192 }
193
sdefresne8df022f2016-09-20 13:54:26194 // There is a race-condition in the above code if the kernel receive a RST
195 // packet for the "connect" call before the registration of the socket file
196 // descriptor to the message loop pump. On most platform it is benign as the
197 // message loop pump is awakened for that socket in an error state, but on
198 // iOS this does not happens. Check the status of the socket at this point
199 // and if in error, consider the connection as failed.
200 int os_error = 0;
201 socklen_t len = sizeof(os_error);
202 if (getsockopt(socket_fd_, SOL_SOCKET, SO_ERROR, &os_error, &len) == 0) {
203 // TCPSocketPosix expects errno to be set.
204 errno = os_error;
205 }
206
207 rv = MapConnectError(errno);
208 if (rv != OK && rv != ERR_IO_PENDING) {
209 write_socket_watcher_.StopWatchingFileDescriptor();
210 return rv;
211 }
212
[email protected]2ef2b0e2014-07-09 21:12:34213 write_callback_ = callback;
214 waiting_connect_ = true;
215 return ERR_IO_PENDING;
216}
217
tfarina4eb7aad82015-09-14 17:10:34218bool SocketPosix::IsConnected() const {
[email protected]2ef2b0e2014-07-09 21:12:34219 DCHECK(thread_checker_.CalledOnValidThread());
220
221 if (socket_fd_ == kInvalidSocket || waiting_connect_)
222 return false;
223
224 // Checks if connection is alive.
225 char c;
226 int rv = HANDLE_EINTR(recv(socket_fd_, &c, 1, MSG_PEEK));
227 if (rv == 0)
228 return false;
229 if (rv == -1 && errno != EAGAIN && errno != EWOULDBLOCK)
230 return false;
231
232 return true;
233}
234
tfarina4eb7aad82015-09-14 17:10:34235bool SocketPosix::IsConnectedAndIdle() const {
[email protected]2ef2b0e2014-07-09 21:12:34236 DCHECK(thread_checker_.CalledOnValidThread());
237
238 if (socket_fd_ == kInvalidSocket || waiting_connect_)
239 return false;
240
241 // Check if connection is alive and we haven't received any data
242 // unexpectedly.
243 char c;
244 int rv = HANDLE_EINTR(recv(socket_fd_, &c, 1, MSG_PEEK));
245 if (rv >= 0)
246 return false;
247 if (errno != EAGAIN && errno != EWOULDBLOCK)
248 return false;
249
250 return true;
251}
252
tfarina4eb7aad82015-09-14 17:10:34253int SocketPosix::Read(IOBuffer* buf,
254 int buf_len,
255 const CompletionCallback& callback) {
[email protected]2ef2b0e2014-07-09 21:12:34256 DCHECK(thread_checker_.CalledOnValidThread());
257 DCHECK_NE(kInvalidSocket, socket_fd_);
258 DCHECK(!waiting_connect_);
vitalybuka63b47542014-09-29 17:14:19259 CHECK(read_callback_.is_null());
[email protected]2ef2b0e2014-07-09 21:12:34260 // Synchronous operation not supported
261 DCHECK(!callback.is_null());
262 DCHECK_LT(0, buf_len);
263
264 int rv = DoRead(buf, buf_len);
265 if (rv != ERR_IO_PENDING)
266 return rv;
267
268 if (!base::MessageLoopForIO::current()->WatchFileDescriptor(
269 socket_fd_, true, base::MessageLoopForIO::WATCH_READ,
270 &read_socket_watcher_, this)) {
271 PLOG(ERROR) << "WatchFileDescriptor failed on read, errno " << errno;
272 return MapSystemError(errno);
273 }
274
275 read_buf_ = buf;
276 read_buf_len_ = buf_len;
277 read_callback_ = callback;
278 return ERR_IO_PENDING;
279}
280
tfarina4eb7aad82015-09-14 17:10:34281int SocketPosix::Write(IOBuffer* buf,
282 int buf_len,
283 const CompletionCallback& callback) {
[email protected]2ef2b0e2014-07-09 21:12:34284 DCHECK(thread_checker_.CalledOnValidThread());
285 DCHECK_NE(kInvalidSocket, socket_fd_);
286 DCHECK(!waiting_connect_);
vitalybuka63b47542014-09-29 17:14:19287 CHECK(write_callback_.is_null());
[email protected]2ef2b0e2014-07-09 21:12:34288 // Synchronous operation not supported
289 DCHECK(!callback.is_null());
290 DCHECK_LT(0, buf_len);
291
292 int rv = DoWrite(buf, buf_len);
293 if (rv == ERR_IO_PENDING)
294 rv = WaitForWrite(buf, buf_len, callback);
295 return rv;
296}
297
tfarina4eb7aad82015-09-14 17:10:34298int SocketPosix::WaitForWrite(IOBuffer* buf,
299 int buf_len,
300 const CompletionCallback& callback) {
[email protected]2ef2b0e2014-07-09 21:12:34301 DCHECK(thread_checker_.CalledOnValidThread());
302 DCHECK_NE(kInvalidSocket, socket_fd_);
303 DCHECK(write_callback_.is_null());
304 // Synchronous operation not supported
305 DCHECK(!callback.is_null());
306 DCHECK_LT(0, buf_len);
307
308 if (!base::MessageLoopForIO::current()->WatchFileDescriptor(
309 socket_fd_, true, base::MessageLoopForIO::WATCH_WRITE,
310 &write_socket_watcher_, this)) {
311 PLOG(ERROR) << "WatchFileDescriptor failed on write, errno " << errno;
312 return MapSystemError(errno);
313 }
314
315 write_buf_ = buf;
316 write_buf_len_ = buf_len;
317 write_callback_ = callback;
318 return ERR_IO_PENDING;
319}
320
tfarina4eb7aad82015-09-14 17:10:34321int SocketPosix::GetLocalAddress(SockaddrStorage* address) const {
[email protected]2ef2b0e2014-07-09 21:12:34322 DCHECK(thread_checker_.CalledOnValidThread());
323 DCHECK(address);
324
325 if (getsockname(socket_fd_, address->addr, &address->addr_len) < 0)
326 return MapSystemError(errno);
327 return OK;
328}
329
tfarina4eb7aad82015-09-14 17:10:34330int SocketPosix::GetPeerAddress(SockaddrStorage* address) const {
[email protected]2ef2b0e2014-07-09 21:12:34331 DCHECK(thread_checker_.CalledOnValidThread());
332 DCHECK(address);
333
334 if (!HasPeerAddress())
335 return ERR_SOCKET_NOT_CONNECTED;
336
337 *address = *peer_address_;
338 return OK;
339}
340
tfarina4eb7aad82015-09-14 17:10:34341void SocketPosix::SetPeerAddress(const SockaddrStorage& address) {
[email protected]2ef2b0e2014-07-09 21:12:34342 DCHECK(thread_checker_.CalledOnValidThread());
343 // |peer_address_| will be non-NULL if Connect() has been called. Unless
344 // Close() is called to reset the internal state, a second call to Connect()
345 // is not allowed.
346 // Please note that we don't allow a second Connect() even if the previous
347 // Connect() has failed. Connecting the same |socket_| again after a
348 // connection attempt failed results in unspecified behavior according to
349 // POSIX.
350 DCHECK(!peer_address_);
351 peer_address_.reset(new SockaddrStorage(address));
352}
353
tfarina4eb7aad82015-09-14 17:10:34354bool SocketPosix::HasPeerAddress() const {
[email protected]2ef2b0e2014-07-09 21:12:34355 DCHECK(thread_checker_.CalledOnValidThread());
356 return peer_address_ != NULL;
357}
358
tfarina4eb7aad82015-09-14 17:10:34359void SocketPosix::Close() {
[email protected]2ef2b0e2014-07-09 21:12:34360 DCHECK(thread_checker_.CalledOnValidThread());
361
cmasoneca100d52014-09-03 18:11:11362 StopWatchingAndCleanUp();
[email protected]2ef2b0e2014-07-09 21:12:34363
364 if (socket_fd_ != kInvalidSocket) {
365 if (IGNORE_EINTR(close(socket_fd_)) < 0)
366 PLOG(ERROR) << "close() returned an error, errno=" << errno;
367 socket_fd_ = kInvalidSocket;
368 }
[email protected]2ef2b0e2014-07-09 21:12:34369}
370
svaldez58804c42015-10-06 00:13:47371void SocketPosix::DetachFromThread() {
372 thread_checker_.DetachFromThread();
373}
374
tfarina4eb7aad82015-09-14 17:10:34375void SocketPosix::OnFileCanReadWithoutBlocking(int fd) {
xunjieli0b7f5b62016-12-06 20:43:48376 TRACE_EVENT0(kNetTracingCategory,
377 "SocketPosix::OnFileCanReadWithoutBlocking");
[email protected]2ef2b0e2014-07-09 21:12:34378 DCHECK(!accept_callback_.is_null() || !read_callback_.is_null());
379 if (!accept_callback_.is_null()) {
380 AcceptCompleted();
381 } else { // !read_callback_.is_null()
382 ReadCompleted();
383 }
384}
385
tfarina4eb7aad82015-09-14 17:10:34386void SocketPosix::OnFileCanWriteWithoutBlocking(int fd) {
[email protected]2ef2b0e2014-07-09 21:12:34387 DCHECK(!write_callback_.is_null());
388 if (waiting_connect_) {
389 ConnectCompleted();
390 } else {
391 WriteCompleted();
392 }
393}
394
danakj655b66c2016-04-16 00:51:38395int SocketPosix::DoAccept(std::unique_ptr<SocketPosix>* socket) {
[email protected]2ef2b0e2014-07-09 21:12:34396 SockaddrStorage new_peer_address;
397 int new_socket = HANDLE_EINTR(accept(socket_fd_,
398 new_peer_address.addr,
399 &new_peer_address.addr_len));
400 if (new_socket < 0)
401 return MapAcceptError(errno);
402
danakj655b66c2016-04-16 00:51:38403 std::unique_ptr<SocketPosix> accepted_socket(new SocketPosix);
[email protected]2ef2b0e2014-07-09 21:12:34404 int rv = accepted_socket->AdoptConnectedSocket(new_socket, new_peer_address);
405 if (rv != OK)
406 return rv;
407
dchengc7eeda422015-12-26 03:56:48408 *socket = std::move(accepted_socket);
[email protected]2ef2b0e2014-07-09 21:12:34409 return OK;
410}
411
tfarina4eb7aad82015-09-14 17:10:34412void SocketPosix::AcceptCompleted() {
[email protected]2ef2b0e2014-07-09 21:12:34413 DCHECK(accept_socket_);
414 int rv = DoAccept(accept_socket_);
415 if (rv == ERR_IO_PENDING)
416 return;
417
418 bool ok = accept_socket_watcher_.StopWatchingFileDescriptor();
419 DCHECK(ok);
420 accept_socket_ = NULL;
421 base::ResetAndReturn(&accept_callback_).Run(rv);
422}
423
tfarina4eb7aad82015-09-14 17:10:34424int SocketPosix::DoConnect() {
[email protected]2ef2b0e2014-07-09 21:12:34425 int rv = HANDLE_EINTR(connect(socket_fd_,
426 peer_address_->addr,
427 peer_address_->addr_len));
428 DCHECK_GE(0, rv);
429 return rv == 0 ? OK : MapConnectError(errno);
430}
431
tfarina4eb7aad82015-09-14 17:10:34432void SocketPosix::ConnectCompleted() {
[email protected]2ef2b0e2014-07-09 21:12:34433 // Get the error that connect() completed with.
434 int os_error = 0;
435 socklen_t len = sizeof(os_error);
436 if (getsockopt(socket_fd_, SOL_SOCKET, SO_ERROR, &os_error, &len) == 0) {
tfarina4eb7aad82015-09-14 17:10:34437 // TCPSocketPosix expects errno to be set.
[email protected]2ef2b0e2014-07-09 21:12:34438 errno = os_error;
439 }
440
441 int rv = MapConnectError(errno);
442 if (rv == ERR_IO_PENDING)
443 return;
444
445 bool ok = write_socket_watcher_.StopWatchingFileDescriptor();
446 DCHECK(ok);
447 waiting_connect_ = false;
448 base::ResetAndReturn(&write_callback_).Run(rv);
449}
450
tfarina4eb7aad82015-09-14 17:10:34451int SocketPosix::DoRead(IOBuffer* buf, int buf_len) {
[email protected]2ef2b0e2014-07-09 21:12:34452 int rv = HANDLE_EINTR(read(socket_fd_, buf->data(), buf_len));
453 return rv >= 0 ? rv : MapSystemError(errno);
454}
455
tfarina4eb7aad82015-09-14 17:10:34456void SocketPosix::ReadCompleted() {
dcheng08ea2af02014-08-25 23:38:09457 int rv = DoRead(read_buf_.get(), read_buf_len_);
[email protected]2ef2b0e2014-07-09 21:12:34458 if (rv == ERR_IO_PENDING)
459 return;
460
461 bool ok = read_socket_watcher_.StopWatchingFileDescriptor();
462 DCHECK(ok);
463 read_buf_ = NULL;
464 read_buf_len_ = 0;
465 base::ResetAndReturn(&read_callback_).Run(rv);
466}
467
tfarina4eb7aad82015-09-14 17:10:34468int SocketPosix::DoWrite(IOBuffer* buf, int buf_len) {
davidben28150272016-06-06 21:03:12469#if defined(OS_LINUX) || defined(OS_ANDROID)
470 // Disable SIGPIPE for this write. Although Chromium globally disables
471 // SIGPIPE, the net stack may be used in other consumers which do not do
472 // this. MSG_NOSIGNAL is a Linux-only API. On OS X, this is a setsockopt on
473 // socket creation.
474 int rv = HANDLE_EINTR(send(socket_fd_, buf->data(), buf_len, MSG_NOSIGNAL));
475#else
[email protected]2ef2b0e2014-07-09 21:12:34476 int rv = HANDLE_EINTR(write(socket_fd_, buf->data(), buf_len));
davidben28150272016-06-06 21:03:12477#endif
[email protected]2ef2b0e2014-07-09 21:12:34478 return rv >= 0 ? rv : MapSystemError(errno);
479}
480
tfarina4eb7aad82015-09-14 17:10:34481void SocketPosix::WriteCompleted() {
dcheng08ea2af02014-08-25 23:38:09482 int rv = DoWrite(write_buf_.get(), write_buf_len_);
[email protected]2ef2b0e2014-07-09 21:12:34483 if (rv == ERR_IO_PENDING)
484 return;
485
486 bool ok = write_socket_watcher_.StopWatchingFileDescriptor();
487 DCHECK(ok);
488 write_buf_ = NULL;
489 write_buf_len_ = 0;
490 base::ResetAndReturn(&write_callback_).Run(rv);
491}
492
tfarina4eb7aad82015-09-14 17:10:34493void SocketPosix::StopWatchingAndCleanUp() {
cmasoneca100d52014-09-03 18:11:11494 bool ok = accept_socket_watcher_.StopWatchingFileDescriptor();
495 DCHECK(ok);
496 ok = read_socket_watcher_.StopWatchingFileDescriptor();
497 DCHECK(ok);
498 ok = write_socket_watcher_.StopWatchingFileDescriptor();
499 DCHECK(ok);
500
501 if (!accept_callback_.is_null()) {
502 accept_socket_ = NULL;
503 accept_callback_.Reset();
504 }
505
506 if (!read_callback_.is_null()) {
507 read_buf_ = NULL;
508 read_buf_len_ = 0;
509 read_callback_.Reset();
510 }
511
512 if (!write_callback_.is_null()) {
513 write_buf_ = NULL;
514 write_buf_len_ = 0;
515 write_callback_.Reset();
516 }
517
518 waiting_connect_ = false;
519 peer_address_.reset();
520}
521
[email protected]2ef2b0e2014-07-09 21:12:34522} // namespace net