blob: 7e0675dcffa031dde4529615e583742a2fd3be27 [file] [log] [blame]
Paul Stewartf65320c2011-10-13 14:34:52 -07001// Copyright (c) 2011 The Chromium OS 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
5#ifndef SHILL_ASYNC_CONNECTION_
6#define SHILL_ASYNC_CONNECTION_
7
8#include <string>
9
10#include <base/callback_old.h>
11#include <base/memory/scoped_ptr.h>
12
13#include "shill/refptr_types.h"
14
15namespace shill {
16
17class EventDispatcher;
18class IOHandler;
19class IPAddress;
20class Sockets;
21
22// The AsyncConnection class implements an asynchronous
23// outgoing TCP connection. When passed an IPAddress and
24// port, and it will notify the caller when the connection
25// is made. It can also be passed an interface name to
26// bind the local side of the connection.
27class AsyncConnection {
28 public:
29 // If non-empty |interface_name| specifies an local interface from which
30 // to originate the connection.
31 AsyncConnection(const std::string &interface_name,
32 EventDispatcher *dispatcher,
33 Sockets *sockets,
34 Callback2<bool, int>::Type *callback);
35 virtual ~AsyncConnection();
36
37 // Open a connection given an IP address and port (in host order).
38 // When the connection completes, |callback| will be called with the
39 // a boolean (indicating success if true) and an fd of the opened socket
40 // (in the success case). If successful, ownership of this open fd is
41 // passed to the caller on execution of the callback.
42 //
43 // This function (Start) returns true if the connection is in progress,
44 // or if the connection has immediately succeeded (the callback will be
45 // called in this case). On success the callback may be called before
46 // Start() returns to its caller. On failure to start the connection,
47 // this function returns false, but does not execute the callback.
48 //
49 // Calling Start() on an AsyncConnection that is already Start()ed is
50 // an error.
51 virtual bool Start(const IPAddress &address, int port);
52
53 // Stop the open connection, closing any fds that are still owned.
54 // Calling Stop() on an unstarted or Stop()ped AsyncConnection is
55 // a no-op.
56 virtual void Stop();
57
58 std::string error() const { return error_; }
59
60 private:
61 friend class AsyncConnectionTest;
62
63 void OnConnectCompletion(int fd);
64
65 std::string interface_name_;
66 EventDispatcher *dispatcher_;
67 Sockets *sockets_;
68 Callback2<bool, int>::Type *callback_;
69 std::string error_;
70 int fd_;
71 scoped_ptr<Callback1<int>::Type> connect_completion_callback_;
72 scoped_ptr<IOHandler> connect_completion_handler_;
73
74 DISALLOW_COPY_AND_ASSIGN(AsyncConnection);
75};
76
77} // namespace shill
78
79#endif // SHILL_ASYNC_CONNECTION_