aboutsummaryrefslogtreecommitdiffstats
path: root/library/cpp/http/fetch_gpl/httpagent.h
blob: b77c246c4f1fe2f9919647779c7cd2d8477b781c (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
#pragma once

#include <library/cpp/http/fetch/httpagent.h>

template <class TSockHndl = TSimpleSocketHandler,
          class TDnsClient = TIpResolver,
          class TErrorLogger = TSslSocketBase::TFakeLogger,
          class TTimer = TNoTimer,
          template <class, class> class TSslSocketImpl = TSslSocketHandler>
class THttpsAgent: public TTimer {
public:
    typedef TSslSocketImpl<TSockHndl, TErrorLogger> TSocket;
    THttpsAgent()
        : Socket(new TSocket)
        , Scheme(0)
        , Persistent(0)
        , Timeout(TDuration::MicroSeconds(150))
        , Hostheader(nullptr)
        , Footer(nullptr)
        , pHostBeg(nullptr)
        , pHostEnd(nullptr)
        , AltFooter(nullptr)
        , PostData(nullptr)
        , PostDataLen(0)
        , Method(nullptr)
        , MethodLen(0)
        , HostheaderLen(0)
    {
        SetIdentification("YandexSomething/1.0", "webadmin@yandex.ru");
    }

    ~THttpsAgent() {
        Disconnect();
        delete[] Hostheader;
        delete[] Footer;
    }

    void SetIdentification(const char* userAgent, const char* httpFrom) {
        Y_VERIFY(Socket.Get(), "HttpsAgent: socket is picked out. Can't use until a valid socket is set");
        delete[] Footer;
        size_t len = userAgent ? strlen(userAgent) + 15 : 0;
        len += httpFrom ? strlen(httpFrom) + 9 : 0;
        len += 3;
        Footer = new char[len];
        if (userAgent)
            strcat(strcat(strcpy(Footer, "User-Agent: "), userAgent), "\r\n");
        if (httpFrom)
            strcat(strcat(strcat(Footer, "From: "), httpFrom), "\r\n");
    }

    void SetUserAgentFooter(const char* altFooter) {
        AltFooter = altFooter;
    }

    void SetPostData(const char* postData, size_t postDataLen) {
        PostData = postData;
        PostDataLen = postDataLen;
    }

    void SetMethod(const char* method, size_t methodLen) {
        Method = method;
        MethodLen = methodLen;
    }

    // deprecated
    ui32 GetIp() const {
        return Addrs.GetV4Addr().first;
    }

    int GetScheme() const {
        return Scheme;
    }

    void SetTimeout(TDuration tim) {
        Timeout = tim;
    }

    void SetConnectTimeout(TDuration timeout) {
        ConnectTimeout = timeout;
    }

    int Disconnected() {
        return !Persistent || !Socket.Get() || !Socket->Good();
    }

    int SetHost(const char* hostname, TIpPort port, int scheme = THttpURL::SchemeHTTP) {
        TStringBuf host{hostname};
        if (host.StartsWith('[') && host.EndsWith(']')) {
            TString tmp = ToString(host.Skip(1).Chop(1));
            TSockAddrInet6 sa(tmp.data(), port);
            NAddr::IRemoteAddrRef addr = new NAddr::TIPv6Addr(sa);
            SetHost(hostname, port, {addr}, scheme);
            return 0;
        }
        TAddrList addrs = DnsClient.Resolve(hostname, port);
        if (!addrs.size()) {
            return 1;
        }
        SetHost(hostname, port, addrs, scheme);
        return 0;
    }

    int SetHost(const char* hostname, TIpPort port, const TAddrList& addrs, int scheme = THttpURL::SchemeHTTP) {
        Disconnect();
        Addrs = addrs;
        Scheme = scheme;
        size_t reqHostheaderLen = strlen(hostname) + 20;
        if (HostheaderLen < reqHostheaderLen) {
            delete[] Hostheader;
            Hostheader = new char[(HostheaderLen = reqHostheaderLen)];
        }
        if (Scheme == THttpURL::SchemeHTTPS && port == 443 || port == 80)
            sprintf(Hostheader, "Host: %s\r\n", hostname);
        else
            sprintf(Hostheader, "Host: %s:%u\r\n", hostname, port);
        pHostBeg = strchr(Hostheader, ' ') + 1;
        pHostEnd = strchr(pHostBeg, '\r');
        // convert hostname to lower case since some web server don't like
        // uppper case (Task ROBOT-562)
        for (char* p = pHostBeg; p < pHostEnd; p++)
            *p = tolower(*p);
        SocketCtx.Host = pHostBeg;
        SocketCtx.HostLen = pHostEnd - pHostBeg;
        return 0;
    }

    // deprecated v4-only version
    int SetHost(const char* hostname, TIpPort port, ui32 ip, int scheme = THttpURL::SchemeHTTP, TIpPort connPort = 0) {
        connPort = connPort ? connPort : port;
        return SetHost(hostname, port, TAddrList::MakeV4Addr(ip, connPort), scheme);
    }

    void SetHostHeader(const char* host) {
        size_t reqHostheaderLen = strlen(host) + 20;
        if (HostheaderLen < reqHostheaderLen) {
            delete[] Hostheader;
            Hostheader = new char[(HostheaderLen = reqHostheaderLen)];
        }
        sprintf(Hostheader, "Host: %s\r\n", host);
        pHostBeg = strchr(Hostheader, ' ') + 1;
        pHostEnd = strchr(pHostBeg, '\r');
        SocketCtx.Host = pHostBeg;
        SocketCtx.HostLen = pHostEnd - pHostBeg;
    }

    void SetSocket(TSocket* s) {
        Y_VERIFY(s, "HttpsAgent: socket handler is null");
        SocketCtx.FreeBuffers();
        if (s->HasSsl())
            SocketCtx.AllocBuffers();
        Socket.Reset(s);
    }

    void SetPersistent(const bool value) {
        Persistent = value;
    }

    TSocket* PickOutSocket() {
        SocketCtx.FreeBuffers();
        SocketCtx.CachedSession.Destroy();
        return Socket.Release();
    }

    void Disconnect() {
        if (Socket.Get())
            Socket->Disconnect();
        SocketCtx.FreeBuffers();
        SocketCtx.CachedSession.Destroy();
    }

    ssize_t read(void* buffer, size_t buflen) {
        Y_VERIFY(Socket.Get(), "HttpsAgent: socket is picked out. Can't use until a valid socket is set");
        ssize_t ret = Socket->read(&SocketCtx, buffer, buflen);
        TTimer::OnAfterRecv();
        return ret;
    }

    int RequestGet(const char* url, const char* const* headers, int persistent = 1, bool head_request = false) {
        Y_VERIFY(Socket.Get(), "HttpsAgent: socket is picked out. Can't use until a valid socket is set");
        if (!Addrs.size())
            return HTTP_DNS_FAILURE;
        char message[MessageMax];
        ssize_t messlen = 0;
        if (Method) {
            strncpy(message, Method, MethodLen);
            message[MethodLen] = ' ';
            messlen = MethodLen + 1;
        } else if (PostData) {
            strcpy(message, "POST ");
            messlen = 5;
        } else if (head_request) {
            strcpy(message, "HEAD ");
            messlen = 5;
        } else {
            strcpy(message, "GET ");
            messlen = 4;
        }
#define _AppendMessage(mes) messlen += Min(MessageMax - messlen, \
                                           (ssize_t)strlcpy(message + messlen, (mes), MessageMax - messlen))
        _AppendMessage(url);
        _AppendMessage(" HTTP/1.1\r\n");
        _AppendMessage(Hostheader);
        _AppendMessage("Connection: ");
        _AppendMessage(persistent ? "Keep-Alive\r\n" : "Close\r\n");
        while (headers && *headers)
            _AppendMessage(*headers++);
        if (AltFooter)
            _AppendMessage(AltFooter);
        else
            _AppendMessage(Footer);
        _AppendMessage("\r\n");
#undef _AppendMessage
        if (messlen >= MessageMax)
            return HTTP_HEADER_TOO_LARGE;

        if (!Persistent)
            Socket->Disconnect(&SocketCtx);
        Persistent = persistent;
        int connected = Socket->Good();
        SocketCtx.FreeBuffers();
        if (Scheme == THttpURL::SchemeHTTPS) {
            SocketCtx.AllocBuffers();
        }

        bool success = false;
        Y_SCOPE_EXIT(&success, this) { if (!success) { this->SocketCtx.FreeBuffers(); }; };

        TTimer::OnBeforeSend();
        for (int attempt = !connected; attempt < 2; attempt++) {
            const auto connectTimeout = ConnectTimeout ? ConnectTimeout : Timeout;
            if (!Socket->Good() && Socket->Connect(&SocketCtx, Addrs, connectTimeout , Scheme == THttpURL::SchemeHTTPS, true)) {
                return SocketCtx.SslError ? HTTP_SSL_ERROR : HTTP_CONNECT_FAILED;
            } else { // We successfully connected
                connected = true;
            }

            int sendOk = Socket->send(&SocketCtx, message, messlen);
            if (sendOk && PostData && PostDataLen)
                sendOk = Socket->send(&SocketCtx, PostData, PostDataLen);
            if (!sendOk) {
                int err = errno;
                Socket->Disconnect(&SocketCtx);
                errno = err;
                continue;
            }
            TTimer::OnAfterSend();

            if (!Socket->peek(&SocketCtx)) {
                int err = errno;
                Socket->Disconnect(&SocketCtx);
                if (err == EINTR) {
                    errno = err;
                    return HTTP_INTERRUPTED;
                }
                if (err == ETIMEDOUT) {
                    errno = err;
                    return HTTP_TIMEDOUT_WHILE_BYTES_RECEIVING;
                }
            } else {
                TTimer::OnBeforeRecv();
                if (!persistent) {
                    Socket->shutdown();
                }
                success = true;
                return 0;
            }
        }
        return SocketCtx.SslError ? HTTP_SSL_ERROR : (connected ? HTTP_CONNECTION_LOST : HTTP_CONNECT_FAILED);
    }

    ui16 CertCheckErrors() const {
        return SocketCtx.CertErrors;
    }

protected:
    THolder<TSocket> Socket;
    typename TSocket::TSocketCtx SocketCtx;
    TIpResolverWrapper<TDnsClient> DnsClient;
    TAddrList Addrs;
    int Scheme;
    int Persistent;
    TDuration Timeout;
    TDuration ConnectTimeout;
    char *Hostheader, *Footer, *pHostBeg, *pHostEnd;
    const char* AltFooter; // alternative footer can be set by the caller
    const char* PostData;
    size_t PostDataLen;
    const char* Method;
    size_t MethodLen;
    unsigned short HostheaderLen;
    static const ssize_t MessageMax = 65536;
};