aboutsummaryrefslogtreecommitdiff
path: root/src/microhttpd/mhd_send.c
blob: 9ed2a8041fb81d9d0af09e33472e85624b7f01dd (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
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
/*
  This file is part of libmicrohttpd
  Copyright (C) 2019 ng0 <ng0@n0.is>

  This library is free software; you can redistribute it and/or
  modify it under the terms of the GNU Lesser General Public
  License as published by the Free Software Foundation; either
  version 2.1 of the License, or (at your option) any later version.

  This library is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  Lesser General Public License for more details.

  You should have received a copy of the GNU Lesser General Public
  License along with this library; if not, write to the Free Software
  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

 */

/**
 * @file microhttpd/mhd_send.c
 * @brief Implementation of send() wrappers.
 * @author ng0 <ng0@n0.is>
 */

/* TODO: sendfile() wrapper, in connection.c */

/* Worth considering for future improvements and additions:
 * NetBSD has no sendfile or sendfile64. The way to work
 * with this seems to be to mmap the file and write(2) as
 * large a chunk as possible to the socket. Alternatively,
 * use madvise(..., MADV_SEQUENTIAL). */

/* Functions to be used in: send_param_adapter, MHD_send_
 * and every place where sendfile(), sendfile64(), setsockopt()
 * are used. */

#include "mhd_send.h"

/**
 * Set TCP_NODELAY flag on socket and save the
 * #sk_tcp_nodelay_on state.
 *
 * @param connection the MHD_Connection structure
 * @param value the state to set, boolean
 */
void
MHD_send_socket_state_nodelay_ (struct MHD_Connection *connection,
                                bool value)
{
#if TCP_NODELAY
  const MHD_SCKT_OPT_BOOL_ state_val = value ? 1 : 0;

  if (0 == setsockopt (connection->socket_fd,
                       IPPROTO_TCP,
                       TCP_NODELAY,
                       (const void *) &state_val,
                       sizeof (state_val)))
    {
      connection->sk_tcp_nodelay_on = value;
    }
#endif
}

void
MHD_setsockopt_ (struct MHD_Connection *connection,
                 int optname,
                 bool value,
                 bool state_store)
{
  const MHD_SCKT_OPT_BOOL_ state_val = value ? 1 : 0;

  if (0 == setsockopt (connection->socket_fd,
                       IPPROTO_TCP,
                       optname,
                       (const void *) &state_val,
                       sizeof (state_val)))
    {
      connection->sk_tcp_nodelay_on = state_store;
    }
}

/**
 * Set TCP_NOCORK or TCP_NODELAY flag on socket and save the
 * #sk_tcp_nodelay_on state.
 *
 * @param connection the MHD_Connection structure
 * @param cork_value the state to set, boolean
 * @param cork_state the boolean value passed to #sk_tcp_nodelay_on
 * @param nodelay_value the state to set, boolean
 * @param nodelay_state the boolean value passed to #sk_tcp_nodelay_on
 */
void
MHD_send_socket_state_cork_nodelay_ (struct MHD_Connection *connection,
                                     bool cork_value,
                                     bool cork_state,
                                     bool nodelay_value,
                                     bool nodelay_state)
{
#if TCP_CORK && TCP_NODELAY
  const MHD_SCKT_OPT_BOOL_ cork_state_val = cork_value ? 1 : 0;
  const MHD_SCKT_OPT_BOOL_ nodelay_state_val = nodelay_value ? 1 : 0;

  if (0 == setsockopt (connection->socket_fd,
                       IPPROTO_TCP,
                       TCP_CORK,
                       (const void *) &cork_state_val,
                       sizeof (cork_state_val)))
    {
      connection->sk_tcp_nodelay_on = cork_state;
    }
  else if (0 == setsockopt (connection->socket_fd,
                            IPPROTO_TCP,
                            TCP_NODELAY,
                            (const void *) &nodelay_state_val,
                            sizeof (nodelay_state_val)))
    {
      connection->sk_tcp_nodelay_on = nodelay_state;
    }
#endif
}

/**
 * Set TCP_NOPUSH flag on socket and save the
 * #sk_tcp_nodelay_on state.
 *
 * @param connection the #MHD_Connection structure
 * @param value the state to set, boolean
 * @param state_store the boolean value passed to #sk_tcp_nodelay_on
 */
void
MHD_send_socket_state_nopush_ (struct MHD_Connection *connection,
                               bool value,
                               bool state_store)
{
#if TCP_NOPUSH
  const MHD_SCKT_OPT_BOOL_ state_val = value ? 1 : 0;

  if (0 == setsockopt (connection->socket_fd,
                       IPPROTO_TCP,
                       TCP_NOPUSH,
                       (const void *) &state_val,
                       sizeof (state_val)))
    {
      /* When TRUE above, this is usually FALSE, but
       * not always. We can't use the negation of
       * value for that reason. */
      connection->sk_tcp_nodelay_on = state_store;
    }
#endif
}

/**
 * Send buffer on connection, and remember the current state of
 * the socket options; only call setsockopt when absolutely
 * necessary.
 *
 * @param connection the MHD_Connection structure
 * @param buffer content of the buffer to send
 * @param buffer_size the size of the buffer (in bytes)
 * @param options the #MHD_SendSocketOptions enum,
 *         #MHD_SSO_NO_CORK: definitely no corking (use NODELAY, or explicitly disable cork),
 *         #MHD_SSO_MAY_CORK: should enable corking (use MSG_MORE, or explicitly enable cork),
 *         #MHD_SSO_HDR_CORK: consider tcpi_snd_mss and consider not corking for the header
 *         part if the size of the header is close to the MSS.
 *         Only used if we are NOT doing 100 Continue and are still sending the
 *         header (provided in full as the buffer to #MHD_send_on_connection_ or as
 *         the header to #MHD_send_on_connection2_).
 * @return sum of the number of bytes sent from both buffers or
 *         -1 on error
 */
ssize_t
MHD_send_on_connection_ (struct MHD_Connection *connection,
                         const char *buffer,
                         size_t buffer_size,
                         enum MHD_SendSocketOptions options)
{
  bool want_cork;
  bool have_cork;
  bool have_more;
  bool use_corknopush;
  bool using_tls = false;
  MHD_socket s = connection->socket_fd;
  ssize_t ret;
  const MHD_SCKT_OPT_BOOL_ off_val = 0;
  const MHD_SCKT_OPT_BOOL_ on_val = 1;

  /* error handling from send_param_adapter() */
  if ((MHD_INVALID_SOCKET == s) || (MHD_CONNECTION_CLOSED == connection->state))
  {
    return MHD_ERR_NOTCONN_;
  }

  /* from send_param_adapter() */
  if (buffer_size > MHD_SCKT_SEND_MAX_SIZE_)
    buffer_size = MHD_SCKT_SEND_MAX_SIZE_; /* return value limit */

  /* Get socket options, change/set options if necessary. */
  switch (options)
  {
  /* No corking */
  case MHD_SSO_NO_CORK:
    want_cork = false;
    break;
  /* Do corking, consider MSG_MORE instead if available. */
  case MHD_SSO_MAY_CORK:
    want_cork = true;
    break;
  /* Cork the header. */
  case MHD_SSO_HDR_CORK:
    want_cork = (buffer_size <= 1024) // && (buffer_size <= 1220);
    break;
  }

  /* ! could be avoided by redefining the variable. */
  have_cork = ! connection->sk_tcp_nodelay_on;

#ifdef MSG_MORE
  have_more = true;
#else
  have_more = false;
#endif

#if TCP_NODELAY
  use_corknopush = false;
#elif TCP_CORK
  use_corknopush = true;
#elif TCP_NOPUSH
  use_corknopush = true;
#endif

#ifdef HTTPS_SUPPORT
  using_tls = (0 != (connection->daemon->options & MHD_USE_TLS));
#endif

#if TCP_CORK
  /* When we have CORK, we can have NODELAY on the same system,
   * at least since Linux 2.2 and both can be combined since
   * Linux 2.5.71. For more details refer to tcp(7) on Linux.
   * No other system in 2019-06 has TCP_CORK. */
  if ((! using_tls) && (use_corknopush) && (have_cork && ! want_cork))
    {
      MHD_send_socket_state_cork_nodelay_ (connection,
                                           false,
                                           true,
                                           true,
                                           true);
    }
#elif TCP_NOPUSH
  /* TCP_NOPUSH on FreeBSD is equal to cork on Linux, with the
   * exception that we know that TCP_NOPUSH will definitely
   * exist and we can disregard TCP_NODELAY unless requested. */
  if ((! using_tls) && (use_corknopush) && (have_cork && ! want_cork))
    {
      MHD_send_socket_state_nopush_ (connection, true, false);
    }
#endif
#if TCP_NODELAY
  if ((! using_tls) && (! use_corknopush) && (! have_cork && want_cork))
    {
      MHD_setsockopt_ (connection, TCP_NODELAY, false, false);
    }
#endif

#ifdef HTTPS_SUPPORT

  if (using_tls)
  {
    if (want_cork && ! have_cork)
    {
      gnutls_record_cork (connection->tls_session);
      connection->sk_tcp_nodelay_on = false;
    }
    if (buffer_size > SSIZE_MAX)
      buffer_size = SSIZE_MAX;
    ret = gnutls_record_send (connection->tls_session,
                              buffer,
                              buffer_size);
    if ( (GNUTLS_E_AGAIN == ret) ||
         (GNUTLS_E_INTERRUPTED == ret) )
    {
#ifdef EPOLL_SUPPORT
      if (GNUTLS_E_AGAIN == ret)
        connection->epoll_state &= ~MHD_EPOLL_STATE_WRITE_READY;
#endif
      return MHD_ERR_AGAIN_;
    }
    if (ret < 0)
    {
      /* Likely 'GNUTLS_E_INVALID_SESSION' (client communication
         disrupted); interpret as a hard error */
      return MHD_ERR_NOTCONN_;
    }
#ifdef EPOLL_SUPPORT
    /* Unlike non-TLS connections, do not reset "write-ready" if
     * sent amount smaller than provided amount, as TLS
     * connections may break data into smaller parts for sending. */
#endif /* EPOLL_SUPPORT */

    if (! want_cork && have_cork)
    {
      (void) gnutls_record_uncork (connection->tls_session, 0);
      connection->sk_tcp_nodelay_on = true;
    }
  }
  else
#endif
  {
    /* plaintext transmission */
#if MSG_MORE
    ret = send (s,
                buffer,
                buffer_size,
                MAYBE_MSG_NOSIGNAL | (want_cork ? MSG_MORE : 0));
#else
    ret = send (connection->socket_fd, buffer, buffer_size, MAYBE_MSG_NOSIGNAL);
#endif

    if (0 > ret)
    {
      const int err = MHD_socket_get_error_ ();

      if (MHD_SCKT_ERR_IS_EAGAIN_ (err))
      {
#if EPOLL_SUPPORT
        /* EAGAIN, no longer write-ready */
        connection->epoll_state &= ~MHD_EPOLL_STATE_WRITE_READY;
#endif /* EPOLL_SUPPORT */
        return MHD_ERR_AGAIN_;
      }
      if (MHD_SCKT_ERR_IS_EINTR_ (err))
        return MHD_ERR_AGAIN_;
      if (MHD_SCKT_ERR_IS_ (err, MHD_SCKT_ECONNRESET_))
        return MHD_ERR_CONNRESET_;
      /* Treat any other error as hard error. */
      return MHD_ERR_NOTCONN_;
    }
#if EPOLL_SUPPORT
    else if (buffer_size > (size_t) ret)
      connection->epoll_state &= ~MHD_EPOLL_STATE_WRITE_READY;
#endif /* EPOLL_SUPPORT */
  }
#if TCP_CORK
  if ((! using_tls) && (use_corknopush) && (! have_cork && want_cork && ! have_more))
    {
      MHD_send_socket_state_cork_nodelay_ (connection,
                                           true,
                                           false,
                                           false,
                                           false);
    }
#elif TCP_NOPUSH
  /* We don't have MSG_MORE. The OS which implement NOPUSH implement
   * it in a similar way to TCP_CORK on Linux. This means we can just
   * disregard the else branch for TCP_NODELAY which we had to use
   * for the TCP_CORK case here.
   * XXX: Verify this statement and finetune if necessary for
   * other systems, as only FreeBSD was checked. */
  if ((! using_tls) && (use_corknopush) && (have_cork && ! want_cork))
  {
    MHD_send_socket_state_nopush_ (connection, true, false);
  }
#endif

#if TCP_NODELAY
  if ((! using_tls) && (! use_corknopush) && (have_cork && ! want_cork))
    {
      MHD_setsockopt_ (connection, TCP_NODELAY, true, true);
    }
#endif

  return ret;
}


/**
 * Send header followed by buffer on connection.
 * Uses writev if possible to send both at once
 * and returns the sum of the number of bytes sent from
 * both buffers, or -1 on error;
 * if writev is unavailable, this call MUST only send from 'header'
 * (as we cannot handle the case that the first write
 * succeeds and the 2nd fails!).
 *
 * @param connection the MHD_Connection structure
 * @param header content of header to send
 * @param header_size the size of the header (in bytes)
 * @param buffer content of the buffer to send
 * @param buffer_size the size of the buffer (in bytes)
 * @return sum of the number of bytes sent from both buffers or
 *         -1 on error
 */
ssize_t
MHD_send_on_connection2_ (struct MHD_Connection *connection,
                          const char *header,
                          size_t header_size,
                          const char *buffer,
                          size_t buffer_size)
{
#if defined(HAVE_SENDMSG) || defined(HAVE_WRITEV)
  MHD_socket s = connection->socket_fd;
  bool have_cork;
  bool have_more;
  int iovcnt;
  int eno;
  const MHD_SCKT_OPT_BOOL_ off_val = 0;
  struct iovec vector[2];

  have_cork = ! connection->sk_tcp_nodelay_on;
#if TCP_NODELAY
  use_corknopush = false;
#elif TCP_CORK
  use_corknopush = true;
#elif TCP_NOPUSH
  use_corknopush = true;
#endif

#if TCP_NODELAY
  if ((! use_corknopush) && (! have_cork && want_cork))
    {
      MHD_setsockopt_ (connection, TCP_NODELAY, false, false);
    }
#endif

  vector[0].iov_base = header;
  vector[0].iov_len = strlen (header);
  vector[1].iov_base = buffer;
  vector[1].iov_len = strlen (buffer);

#if HAVE_SENDMSG
  struct msghdr msg;
  msg.msg_iov = vector;
  memset(&msg, 0, sizeof(buffer + header));
  ret = sendmsg (s, vector, MAYBE_MSG_NOSIGNAL);
#elif HAVE_WRITEV
  iovcnt = sizeof (vector) / sizeof (struct iovec);
  ret = writev (s, vector, iovcnt);
#endif

#if TCP_CORK
  if (use_corknopush)
  {
    eno;

    eno = errno;
    if ((ret == header_len + buffer_len) && have_cork)
      {
        // Response complete, definitely uncork!
        MHD_setsockopt_ (connection, TCP_CORK, false, true);
      }
    errno = eno;
  }
  return ret;
#elif TCP_NOPUSH
  if (use_corknopush)
    {
      eno;

      eno = errno;
      if (ret == header_len + buffer_len)
        {
          /* Response complete, set NOPUSH to off */
          MHD_setsockopt_ (connection, TCP_NOPUSH, false, false);
        }
      errno = eno;
    }
  return ret;
#endif

#else
  return MHD_send_on_connection_ (connection,
                                  header,
                                  header_size,
                                  MHD_SSO_HDR_CORK);
#endif
}