aboutsummaryrefslogtreecommitdiffstats
path: root/library/cpp/neh/asio/tcp_socket_impl.h
blob: 44f8f42d87e64a84d6e1d72e36ecee2499b1ec39 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
#pragma once

#include "asio.h"
#include "io_service_impl.h"

#include <sys/uio.h>

#if defined(_bionic_)
#   define IOV_MAX 1024
#endif

namespace NAsio {
    // ownership/keep-alive references:
    // Handlers <- TOperation...(TFdOperation) <- TPollFdEventHandler <- TIOService

    class TSocketOperation: public TFdOperation {
    public:
        TSocketOperation(TTcpSocket::TImpl& s, TPollType pt, TInstant deadline);

    protected:
        TTcpSocket::TImpl& S_;
    };

    class TOperationConnect: public TSocketOperation {
    public:
        TOperationConnect(TTcpSocket::TImpl& s, TTcpSocket::TConnectHandler h, TInstant deadline)
            : TSocketOperation(s, PollWrite, deadline)
            , H_(h)
        {
        }

        bool Execute(int errorCode) override {
            H_(errorCode, *this);

            return true;
        }

        TTcpSocket::TConnectHandler H_;
    };

    class TOperationConnectFailed: public TSocketOperation {
    public:
        TOperationConnectFailed(TTcpSocket::TImpl& s, TTcpSocket::TConnectHandler h, int errorCode, TInstant deadline)
            : TSocketOperation(s, PollWrite, deadline)
            , H_(h)
            , ErrorCode_(errorCode)
        {
            Speculative_ = true;
        }

        bool Execute(int errorCode) override {
            Y_UNUSED(errorCode);
            H_(ErrorCode_, *this);

            return true;
        }

        TTcpSocket::TConnectHandler H_;
        int ErrorCode_;
    };

    class TOperationWrite: public TSocketOperation {
    public:
        TOperationWrite(TTcpSocket::TImpl& s, NAsio::TTcpSocket::TSendedData& buffs, TTcpSocket::TWriteHandler h, TInstant deadline)
            : TSocketOperation(s, PollWrite, deadline)
            , H_(h)
            , Buffs_(buffs)
            , Written_(0)
        {
            Speculative_ = true;
        }

        //return true, if not need write more data
        bool Execute(int errorCode) override;

    private:
        TTcpSocket::TWriteHandler H_;
        NAsio::TTcpSocket::TSendedData Buffs_;
        size_t Written_;
    };

    class TOperationWriteVector: public TSocketOperation {
    public:
        TOperationWriteVector(TTcpSocket::TImpl& s, TContIOVector* v, TTcpSocket::TWriteHandler h, TInstant deadline)
            : TSocketOperation(s, PollWrite, deadline)
            , H_(h)
            , V_(*v)
            , Written_(0)
        {
            Speculative_ = true;
        }

        //return true, if not need write more data
        bool Execute(int errorCode) override;

    private:
        TTcpSocket::TWriteHandler H_;
        TContIOVector& V_;
        size_t Written_;
    };

    class TOperationReadSome: public TSocketOperation {
    public:
        TOperationReadSome(TTcpSocket::TImpl& s, void* buff, size_t size, TTcpSocket::TReadHandler h, TInstant deadline)
            : TSocketOperation(s, PollRead, deadline)
            , H_(h)
            , Buff_(static_cast<char*>(buff))
            , Size_(size)
        {
        }

        //return true, if not need read more data
        bool Execute(int errorCode) override;

    protected:
        TTcpSocket::TReadHandler H_;
        char* Buff_;
        size_t Size_;
    };

    class TOperationRead: public TOperationReadSome {
    public:
        TOperationRead(TTcpSocket::TImpl& s, void* buff, size_t size, TTcpSocket::TReadHandler h, TInstant deadline)
            : TOperationReadSome(s, buff, size, h, deadline)
            , Read_(0)
        {
        }

        bool Execute(int errorCode) override;

    private:
        size_t Read_;
    };

    class TOperationPoll: public TSocketOperation {
    public:
        TOperationPoll(TTcpSocket::TImpl& s, TPollType pt, TTcpSocket::TPollHandler h, TInstant deadline)
            : TSocketOperation(s, pt, deadline)
            , H_(h)
        {
        }

        bool Execute(int errorCode) override {
            H_(errorCode, *this);

            return true;
        }

    private:
        TTcpSocket::TPollHandler H_;
    };

    template <class T>
    class TOperationCancel: public TNoneOperation {
    public:
        TOperationCancel(T* s)
            : TNoneOperation()
            , S_(s)
        {
            Speculative_ = true;
        }

        ~TOperationCancel() override {
        }

    private:
        bool Execute(int errorCode) override {
            Y_UNUSED(errorCode);
            if (!errorCode && S_->Fd() != INVALID_SOCKET) {
                S_->GetIOServiceImpl().CancelFdOp(S_->Fd());
            }
            return true;
        }

        TIntrusivePtr<T> S_;
    };

    class TTcpSocket::TImpl: public TNonCopyable, public TThrRefBase {
    public:
        typedef TTcpSocket::TSendedData TSendedData;

        TImpl(TIOService::TImpl& srv) noexcept
            : Srv_(srv)
        {
        }

        ~TImpl() override {
            DBGOUT("TSocket::~TImpl()");
        }

        void Assign(SOCKET fd, TEndpoint ep) {
            TSocketHolder(fd).Swap(S_);
            RemoteEndpoint_ = ep;
        }

        void AsyncConnect(const TEndpoint& ep, TTcpSocket::TConnectHandler h, TInstant deadline) {
            TSocketHolder s(socket(ep.SockAddr()->sa_family, SOCK_STREAM, 0));

            if (Y_UNLIKELY(s == INVALID_SOCKET || Srv_.HasAbort())) {
                throw TSystemError() << TStringBuf("can't create socket");
            }

            SetNonBlock(s);

            int err;
            do {
                err = connect(s, ep.SockAddr(), (int)ep.SockAddrLen());
                if (Y_LIKELY(err)) {
                    err = LastSystemError();
                }
#if defined(_freebsd_)
                if (Y_UNLIKELY(err == EINTR)) {
                    err = EINPROGRESS;
                }
            } while (0);
#elif defined(_linux_)
            } while (Y_UNLIKELY(err == EINTR));
#else
            } while (0);
#endif

            RemoteEndpoint_ = ep;
            S_.Swap(s);

            DBGOUT("AsyncConnect(): " << err);
            if (Y_LIKELY(err == EINPROGRESS || err == EWOULDBLOCK || err == 0)) {
                Srv_.ScheduleOp(new TOperationConnect(*this, h, deadline)); //set callback
            } else {
                Srv_.ScheduleOp(new TOperationConnectFailed(*this, h, err, deadline)); //set callback
            }
        }

        inline void AsyncWrite(TSendedData& d, TTcpSocket::TWriteHandler h, TInstant deadline) {
            Srv_.ScheduleOp(new TOperationWrite(*this, d, h, deadline));
        }

        inline void AsyncWrite(TContIOVector* v, TTcpSocket::TWriteHandler h, TInstant deadline) {
            Srv_.ScheduleOp(new TOperationWriteVector(*this, v, h, deadline));
        }

        inline void AsyncRead(void* buff, size_t size, TTcpSocket::TReadHandler h, TInstant deadline) {
            Srv_.ScheduleOp(new TOperationRead(*this, buff, size, h, deadline));
        }

        inline void AsyncReadSome(void* buff, size_t size, TTcpSocket::TReadHandler h, TInstant deadline) {
            Srv_.ScheduleOp(new TOperationReadSome(*this, buff, size, h, deadline));
        }

        inline void AsyncPollWrite(TTcpSocket::TPollHandler h, TInstant deadline) {
            Srv_.ScheduleOp(new TOperationPoll(*this, TOperationPoll::PollWrite, h, deadline));
        }

        inline void AsyncPollRead(TTcpSocket::TPollHandler h, TInstant deadline) {
            Srv_.ScheduleOp(new TOperationPoll(*this, TOperationPoll::PollRead, h, deadline));
        }

        inline void AsyncCancel() {
            if (Y_UNLIKELY(Srv_.HasAbort())) {
                return;
            }
            Srv_.ScheduleOp(new TOperationCancel<TTcpSocket::TImpl>(this));
        }

        inline bool SysCallHasResult(ssize_t& n, TErrorCode& ec) noexcept {
            if (n >= 0) {
                return true;
            }

            int errn = LastSystemError();
            if (errn == EINTR) {
                return false;
            }

            ec.Assign(errn);
            n = 0;
            return true;
        }

        size_t WriteSome(TContIOVector& iov, TErrorCode& ec) noexcept {
            for (;;) {
                ssize_t n = writev(S_, (const iovec*)iov.Parts(), Min(IOV_MAX, (int)iov.Count()));
                DBGOUT("WriteSome(): n=" << n);
                if (SysCallHasResult(n, ec)) {
                    return n;
                }
            }
        }

        size_t WriteSome(const void* buff, size_t size, TErrorCode& ec) noexcept {
            for (;;) {
                ssize_t n = send(S_, (char*)buff, size, 0);
                DBGOUT("WriteSome(): n=" << n);
                if (SysCallHasResult(n, ec)) {
                    return n;
                }
            }
        }

        size_t ReadSome(void* buff, size_t size, TErrorCode& ec) noexcept {
            for (;;) {
                ssize_t n = recv(S_, (char*)buff, size, 0);
                DBGOUT("ReadSome(): n=" << n);
                if (SysCallHasResult(n, ec)) {
                    return n;
                }
            }
        }

        inline void Shutdown(TTcpSocket::TShutdownMode mode, TErrorCode& ec) {
            if (shutdown(S_, mode)) {
                ec.Assign(LastSystemError());
            }
        }

        TIOService::TImpl& GetIOServiceImpl() const noexcept {
            return Srv_;
        }

        inline SOCKET Fd() const noexcept {
            return S_;
        }

        TEndpoint RemoteEndpoint() const {
            return RemoteEndpoint_;
        }

    private:
        TIOService::TImpl& Srv_;
        TSocketHolder S_;
        TEndpoint RemoteEndpoint_;
    };
}