Coverage Report

Created: 2026-10-31 06:20

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/dovecot/src/lib/connection.c
Line
Count
Source
1
/* Copyright (c) Dovecot authors, see top-level COPYING file */
2
3
#include "lib.h"
4
#include "str.h"
5
#include "ioloop.h"
6
#include "istream.h"
7
#include "istream-unix.h"
8
#include "ostream.h"
9
#include "ostream-unix.h"
10
#include "iostream.h"
11
#include "net.h"
12
#include "strescape.h"
13
#include "llist.h"
14
#include "time-util.h"
15
#include "connection.h"
16
17
#include <unistd.h>
18
19
void connection_set_handshake_ready(struct connection *conn)
20
0
{
21
0
  i_assert(conn->handshake_finished.tv_sec == 0);
22
0
  conn->handshake_finished = ioloop_timeval;
23
0
  if (conn->v.handshake_ready != NULL)
24
0
    conn->v.handshake_ready(conn);
25
0
}
26
27
bool connection_handshake_received(struct connection *conn)
28
0
{
29
0
  return conn->handshake_finished.tv_sec != 0;
30
0
}
31
32
static void connection_closed(struct connection *conn,
33
            enum connection_disconnect_reason reason)
34
0
{
35
0
  conn->disconnect_reason = reason;
36
0
  conn->v.destroy(conn);
37
0
}
38
39
static void connection_idle_timeout(struct connection *conn)
40
0
{
41
0
  connection_closed(conn, CONNECTION_DISCONNECT_IDLE_TIMEOUT);
42
0
}
43
44
static void connection_connect_timeout(struct connection *conn)
45
0
{
46
0
  connection_closed(conn, CONNECTION_DISCONNECT_CONNECT_TIMEOUT);
47
0
}
48
49
static int connection_flush_callback(struct connection *conn)
50
0
{
51
0
  int ret;
52
0
  stream_flush_callback_t *callback = conn->flush_callback;
53
0
  if (conn->flush_callback != NULL) {
54
0
    ret = callback(conn->flush_context);
55
0
  } else {
56
0
    ret = o_stream_flush(conn->output);
57
0
  }
58
0
  if (ret < 0) {
59
0
    e_error(conn->event, "write(%s) failed: %s", conn->name,
60
0
      o_stream_get_error(conn->output));
61
0
  } else if (o_stream_get_buffer_used_size(conn->output) <=
62
0
       conn->list->set.output_throttle_size / 3) {
63
    /* resume connection reading */
64
0
    e_debug(conn->event, "Output buffer has flushed enough - "
65
0
      "resuming input");
66
0
    connection_input_resume(conn);
67
0
    o_stream_unset_flush_callback(conn->output);
68
0
    if (callback != NULL)
69
0
      o_stream_set_flush_callback(conn->output, *callback,
70
0
                conn->flush_context);
71
0
    conn->flush_context = NULL;
72
0
    conn->flush_callback = NULL;
73
0
  }
74
0
  return ret;
75
0
}
76
77
static inline bool connection_output_throttle(struct connection *conn)
78
0
{
79
  /* not enabled */
80
0
  if (conn->list->set.output_throttle_size != 0 &&
81
0
      !conn->output->closed &&
82
0
      o_stream_get_buffer_used_size(conn->output) >=
83
0
      conn->list->set.output_throttle_size) {
84
0
    conn->flush_callback =
85
0
      o_stream_get_flush_callback(conn->output, &conn->flush_context);
86
0
    o_stream_set_flush_callback(conn->output,
87
0
              connection_flush_callback, conn);
88
0
    e_debug(conn->event, "Output buffer has reached throttle limit - "
89
0
      "halting input");
90
0
    connection_input_halt(conn);
91
0
    return TRUE;
92
0
  }
93
0
  return FALSE;
94
0
}
95
96
static int connection_input_parse_lines(struct connection *conn)
97
0
{
98
0
  const char *line;
99
0
  struct istream *input;
100
0
  struct ostream *output;
101
0
  int ret = 0;
102
103
0
  input = conn->input;
104
0
  output = conn->output;
105
0
  i_stream_ref(input);
106
0
  if (output != NULL) {
107
0
    o_stream_ref(output);
108
0
    o_stream_cork(output);
109
0
  }
110
0
  while (!input->closed && (line = i_stream_next_line(input)) != NULL) {
111
0
    T_BEGIN {
112
0
      if (!connection_handshake_received(conn) &&
113
0
          conn->v.handshake_line != NULL) {
114
0
        ret = conn->v.handshake_line(conn, line);
115
0
        if (ret > 0)
116
0
          connection_set_handshake_ready(conn);
117
0
        else if (ret == 0)
118
          /* continue reading */
119
0
          ret = 1;
120
0
        else
121
0
          conn->disconnect_reason =
122
0
            CONNECTION_DISCONNECT_HANDSHAKE_FAILED;
123
0
      } else {
124
0
        ret = conn->v.input_line(conn, line);
125
0
      }
126
0
    } T_END;
127
    /* If throttled, stop reading */
128
0
    if (ret > 0 && connection_output_throttle(conn))
129
0
      ret = 0;
130
0
    if (ret <= 0)
131
0
      break;
132
0
    if (conn->input != input) {
133
      /* Input handler changed the istream (and maybe
134
         ostream?) Restart reading using the new streams. */
135
0
      break;
136
0
    }
137
0
  }
138
0
  if (output != NULL) {
139
0
    o_stream_uncork(output);
140
0
    o_stream_unref(&output);
141
0
  }
142
0
  if (ret < 0 && !input->closed) {
143
0
    enum connection_disconnect_reason reason =
144
0
      conn->disconnect_reason;
145
0
    if (reason == CONNECTION_DISCONNECT_NOT)
146
0
      reason = CONNECTION_DISCONNECT_DEINIT;
147
0
    connection_closed(conn, reason);
148
0
  }
149
0
  if (input->closed)
150
0
    ret = -1;
151
0
  i_stream_unref(&input);
152
0
  return ret;
153
0
}
154
155
void connection_input_default(struct connection *conn)
156
0
{
157
0
  int ret;
158
159
0
  if (!connection_handshake_received(conn) &&
160
0
      conn->v.handshake != NULL) {
161
0
    if ((ret = conn->v.handshake(conn)) < 0) {
162
0
      connection_closed(
163
0
        conn, CONNECTION_DISCONNECT_HANDSHAKE_FAILED);
164
0
      return;
165
0
    } else if (ret == 0) {
166
0
      return;
167
0
    } else {
168
0
      connection_set_handshake_ready(conn);
169
0
    }
170
0
  }
171
172
0
  switch (connection_input_read(conn)) {
173
0
  case -1:
174
0
    return;
175
0
  case 0: /* allow calling this function for buffered input */
176
0
  case 1:
177
0
    break;
178
0
  default:
179
0
    i_unreached();
180
0
  }
181
182
0
  while (connection_input_parse_lines(conn) > 0) ;
183
0
}
184
185
int connection_verify_version(struct connection *conn,
186
            const char *service_name,
187
            unsigned int major_version,
188
            unsigned int minor_version)
189
0
{
190
0
  i_assert(!conn->version_received);
191
192
0
  if (strcmp(service_name, conn->list->set.service_name_in) != 0) {
193
0
    e_error(conn->event, "Received wrong socket type. "
194
0
      "We want '%s', but received '%s' (wrong socket path?)",
195
0
      conn->list->set.service_name_in, service_name);
196
0
    return -1;
197
0
  }
198
199
0
  if (major_version != conn->list->set.major_version) {
200
0
    e_error(conn->event, "Socket supports major version %u, "
201
0
      "but we support only %u (mixed old and new binaries?)",
202
0
      major_version, conn->list->set.major_version);
203
0
    return -1;
204
0
  }
205
206
0
  conn->minor_version = minor_version;
207
0
  conn->version_received = TRUE;
208
0
  return 0;
209
0
}
210
211
int connection_handshake_args_default(struct connection *conn,
212
              const char *const *args)
213
0
{
214
0
  unsigned int major_version, minor_version;
215
216
0
  if (conn->version_received)
217
0
    return 1;
218
219
  /* VERSION <tab> service_name <tab> major version <tab> minor version */
220
0
  if (str_array_length(args) != 4 ||
221
0
      strcmp(args[0], "VERSION") != 0 ||
222
0
      str_to_uint(args[2], &major_version) < 0 ||
223
0
      str_to_uint(args[3], &minor_version) < 0) {
224
0
    e_error(conn->event, "didn't reply with a valid VERSION line: %s",
225
0
      t_strarray_join(args, "\t"));
226
0
    return -1;
227
0
  }
228
229
0
  if (connection_verify_version(conn, args[1],
230
0
              major_version, minor_version) < 0)
231
0
    return -1;
232
0
  return 1;
233
0
}
234
235
int connection_input_line_default(struct connection *conn, const char *line)
236
0
{
237
0
  const char *const *args;
238
239
0
  args = t_strsplit_tabescaped(line);
240
0
  if (args[0] == NULL && !conn->list->set.allow_empty_args_input) {
241
0
    e_error(conn->event, "Unexpectedly received empty line");
242
0
    return -1;
243
0
  }
244
245
0
  if (!connection_handshake_received(conn) &&
246
0
      (conn->v.handshake_args != connection_handshake_args_default ||
247
0
       conn->list->set.major_version != 0)) {
248
0
    int ret;
249
0
    if ((ret = conn->v.handshake_args(conn, args)) == 0)
250
0
      ret = 1; /* continue reading */
251
0
    else if (ret > 0)
252
0
      connection_set_handshake_ready(conn);
253
0
    else {
254
0
      conn->disconnect_reason =
255
0
        CONNECTION_DISCONNECT_HANDSHAKE_FAILED;
256
0
    }
257
0
    return ret;
258
0
  } else if (!connection_handshake_received(conn)) {
259
    /* we don't do handshakes */
260
0
    connection_set_handshake_ready(conn);
261
0
  }
262
263
  /* version must be handled though, by something */
264
0
  i_assert(conn->version_received);
265
266
0
  return conn->v.input_args(conn, args);
267
0
}
268
269
void connection_input_halt(struct connection *conn)
270
0
{
271
0
  io_remove(&conn->io);
272
0
  timeout_remove(&conn->to);
273
0
}
274
275
static void
276
connection_input_resume_full(struct connection *conn, bool set_io_pending)
277
0
{
278
0
  i_assert(!conn->disconnected);
279
280
0
  if (conn->io != NULL) {
281
    /* do nothing */
282
0
  } else if (conn->input != NULL && !conn->input->closed) {
283
0
    conn->io = io_add_istream_to(conn->ioloop, conn->input,
284
0
               *conn->v.input, conn);
285
0
    if (set_io_pending)
286
0
      io_set_pending(conn->io);
287
0
  } else if (conn->fd_in != -1) {
288
0
    conn->io = io_add_to(conn->ioloop, conn->fd_in, IO_READ,
289
0
             *conn->v.input, conn);
290
0
    if (set_io_pending)
291
0
      io_set_pending(conn->io);
292
0
  }
293
0
  if (conn->input_idle_timeout_secs != 0 && conn->to == NULL) {
294
0
    conn->to = timeout_add_to(conn->ioloop,
295
0
            conn->input_idle_timeout_secs*1000,
296
0
            *conn->v.idle_timeout, conn);
297
0
  }
298
0
}
299
300
void connection_input_resume(struct connection *conn)
301
0
{
302
0
  connection_input_resume_full(conn, TRUE);
303
0
}
304
305
static void connection_update_property_label(struct connection *conn)
306
0
{
307
0
  const char *label;
308
309
0
  if (conn->remote_ip.family == 0) {
310
0
    if (conn->remote_uid == (uid_t)-1)
311
0
      label = NULL;
312
0
    else if (conn->remote_pid != (pid_t)-1) {
313
0
      label = t_strdup_printf("pid=%ld,uid=%ld",
314
0
            (long)conn->remote_pid,
315
0
            (long)conn->remote_uid);
316
0
    } else {
317
0
      label = t_strdup_printf("uid=%ld",
318
0
            (long)conn->remote_uid);
319
0
    }
320
0
  } else if (conn->remote_ip.family == AF_INET6) {
321
0
    label = t_strdup_printf("[%s]:%u",
322
0
          net_ip2addr(&conn->remote_ip),
323
0
          conn->remote_port);
324
0
  } else {
325
0
    label = t_strdup_printf("%s:%u",
326
0
          net_ip2addr(&conn->remote_ip),
327
0
          conn->remote_port);
328
0
  }
329
330
0
  i_assert(label != NULL || conn->property_label == NULL);
331
0
  if (conn->property_label != NULL &&
332
0
      strcmp(conn->property_label, label) != 0) {
333
0
    e_debug(conn->event, "Updated peer address to %s", label);
334
0
  }
335
336
0
  i_free(conn->property_label);
337
0
  conn->property_label = i_strdup(label);
338
0
}
339
340
static void connection_update_label(struct connection *conn)
341
0
{
342
0
  bool unix_socket = conn->unix_socket ||
343
0
    (conn->remote_ip.family == 0 && conn->remote_uid != (uid_t)-1);
344
0
  string_t *label;
345
346
0
  label = t_str_new(64);
347
0
  if (conn->base_name != NULL)
348
0
    str_append(label, conn->base_name);
349
0
  if (conn->property_label != NULL) {
350
0
    if (str_len(label) == 0)
351
0
      str_append(label, conn->property_label);
352
0
    else {
353
0
      str_append(label, " (");
354
0
      str_append(label, conn->property_label);
355
0
      str_append(label, ")");
356
0
    }
357
0
  }
358
0
  if (str_len(label) == 0) {
359
0
    if (conn->fd_in >= 0 &&
360
0
        (conn->fd_in == conn->fd_out || conn->fd_out < 0))
361
0
      str_printfa(label, "fd=%d", conn->fd_in);
362
0
    else if (conn->fd_in < 0 && conn->fd_out >= 0)
363
0
      str_printfa(label, "fd=%d", conn->fd_out);
364
0
    else if (conn->fd_in >= 0 && conn->fd_out >= 0) {
365
0
      str_printfa(label, "fd_in=%d,fd_out=%d",
366
0
            conn->fd_in, conn->fd_out);
367
0
    }
368
0
  }
369
0
  if (unix_socket && str_len(label) > 0)
370
0
    str_insert(label, 0, "unix:");
371
0
  if (conn->list->set.log_connection_id) {
372
0
    if (str_len(label) > 0)
373
0
      str_append_c(label, ' ');
374
0
    str_printfa(label, "[%u]", conn->id);
375
0
  }
376
377
0
  i_free(conn->label);
378
0
  conn->label = i_strdup(str_c(label));
379
0
}
380
381
static const char *
382
connection_create_stream_name(struct connection *conn, int fd)
383
0
{
384
0
  string_t *name;
385
386
0
  name = t_str_new(64);
387
0
  str_append(name, "(conn");
388
0
  if (conn->unix_socket ||
389
0
      (conn->remote_ip.family == 0 && conn->remote_uid != (uid_t)-1))
390
0
    str_append(name, ":unix");
391
0
  if (conn->base_name != NULL) {
392
0
    str_append_c(name, ':');
393
0
    str_append(name, conn->base_name);
394
0
  } else if (conn->property_label != NULL) {
395
0
    str_append_c(name, ':');
396
0
    str_append(name, conn->property_label);
397
0
  } else if (fd >= 0) {
398
0
    str_printfa(name, ":fd=%d", fd);
399
0
  }
400
0
  if (conn->list->set.log_connection_id) {
401
0
    if (str_len(name) == 5)
402
0
      str_append_c(name, ':');
403
0
    else
404
0
      str_append_c(name, ',');
405
0
    str_printfa(name, "id=%u", conn->id);
406
0
  }
407
0
  str_append_c(name, ')');
408
409
0
  return str_c(name);
410
0
}
411
412
static void connection_update_stream_names(struct connection *conn)
413
0
{
414
0
  if (conn->input != NULL) {
415
0
    i_stream_set_name(
416
0
      conn->input,
417
0
      connection_create_stream_name(conn, conn->fd_in));
418
0
  }
419
0
  if (conn->output != NULL) {
420
0
    o_stream_set_name(
421
0
      conn->output,
422
0
      connection_create_stream_name(conn, conn->fd_out));
423
0
  }
424
0
}
425
426
void connection_update_event(struct connection *conn)
427
0
{
428
0
  string_t *prefix;
429
430
0
  prefix = t_str_new(64);
431
0
  str_append(prefix, "conn");
432
0
  if (strlen(conn->label) > 0) {
433
0
    str_append_c(prefix, ' ');
434
0
    str_append(prefix, conn->label);
435
0
  }
436
0
  str_append(prefix, ": ");
437
0
  event_set_append_log_prefix(conn->event, str_c(prefix));
438
439
0
  if (conn->local_ip.family > 0) {
440
0
    event_add_str(conn->event, conn->list->set.client ?
441
0
            "source_ip" : "local_ip",
442
0
            net_ip2addr(&conn->local_ip));
443
0
  }
444
0
  if (conn->local_port > 0) {
445
0
    event_add_int(conn->event, conn->list->set.client ?
446
0
            "source_port" : "local_port",
447
0
            conn->local_port);
448
0
  }
449
450
0
  if (conn->remote_ip.family > 0) {
451
0
    event_add_str(conn->event, conn->list->set.client ?
452
0
            "dest_ip" : "remote_ip",
453
0
            net_ip2addr(&conn->remote_ip));
454
0
  }
455
0
  if (conn->remote_port > 0) {
456
0
    event_add_int(conn->event, conn->list->set.client ?
457
0
            "dest_port" : "remote_port",
458
0
            conn->remote_port);
459
0
  }
460
461
0
  if (conn->remote_pid != (pid_t)-1)
462
0
    event_add_int(conn->event, "remote_pid", conn->remote_pid);
463
0
  if (conn->remote_uid != (uid_t)-1)
464
0
    event_add_int(conn->event, "remote_uid", conn->remote_uid);
465
0
  if (conn->remote_gid != (gid_t)-1)
466
0
    event_add_int(conn->event, "remote_gid", conn->remote_gid);
467
0
}
468
469
void connection_update_properties(struct connection *conn)
470
0
{
471
0
  int fd = (conn->fd_in < 0 ? conn->fd_out : conn->fd_in);
472
0
  struct net_unix_cred cred;
473
474
0
  if (conn->remote_ip.family != 0) {
475
    /* remote IP was already set */
476
0
  } else if (conn->unix_peer_checked) {
477
    /* already checked */
478
0
  } else if (fd < 0) {
479
    /* not connected yet - wait */
480
0
  } else {
481
0
    if (net_getpeername(fd, &conn->remote_ip,
482
0
            &conn->remote_port) == 0) {
483
      /* either TCP or UNIX socket connection */
484
0
      errno = 0;
485
0
    }
486
487
0
    if (conn->remote_ip.family != 0) {
488
      /* TCP connection */
489
0
      i_assert(conn->remote_port != 0);
490
0
    } else if (errno == ENOTSOCK) {
491
      /* getpeername() already found out this can't be a UNIX
492
         socket connection */
493
0
    } else if (net_getunixcred(fd, &cred) == 0) {
494
0
      conn->remote_pid = cred.pid;
495
0
      conn->remote_uid = cred.uid;
496
0
      conn->remote_gid = cred.gid;
497
0
      conn->have_unix_credentials = TRUE;
498
0
    }
499
0
    conn->unix_peer_checked = TRUE;
500
0
  }
501
502
0
  connection_update_property_label(conn);
503
0
  connection_update_label(conn);
504
0
  connection_update_stream_names(conn);
505
0
  connection_update_event(conn);
506
507
0
  conn->name = (conn->base_name != NULL ?
508
0
          conn->base_name : conn->property_label);
509
0
}
510
511
static void connection_init_streams(struct connection *conn)
512
0
{
513
0
  const struct connection_settings *set = &conn->list->set;
514
515
  /* If we're reconnecting, the iostreams still exist */
516
0
  if (conn->input != NULL) {
517
0
    i_assert(conn->input->closed);
518
0
    i_stream_destroy(&conn->input);
519
0
  }
520
0
  if (conn->output != NULL) {
521
0
    i_assert(conn->output->closed);
522
0
    o_stream_destroy(&conn->output);
523
0
  }
524
525
0
  i_assert(conn->io == NULL);
526
0
  i_assert(conn->to == NULL);
527
528
0
  i_zero(&conn->handshake_finished);
529
0
  conn->version_received = set->major_version == 0;
530
531
0
  if (set->input_max_size != 0) {
532
0
    if (conn->unix_socket)
533
0
      conn->input = i_stream_create_unix(conn->fd_in,
534
0
                 set->input_max_size);
535
0
    else
536
0
      conn->input = i_stream_create_fd(conn->fd_in,
537
0
               set->input_max_size);
538
0
    i_stream_switch_ioloop_to(conn->input, conn->ioloop);
539
0
  }
540
0
  if (set->output_max_size != 0) {
541
0
    if (conn->unix_socket)
542
0
      conn->output = o_stream_create_unix(conn->fd_out,
543
0
                  set->output_max_size);
544
0
    else
545
0
      conn->output = o_stream_create_fd(conn->fd_out,
546
0
                set->output_max_size);
547
0
    o_stream_set_no_error_handling(conn->output, TRUE);
548
0
    o_stream_set_finish_via_child(conn->output, FALSE);
549
0
    o_stream_switch_ioloop_to(conn->output, conn->ioloop);
550
0
  }
551
0
  connection_update_stream_names(conn);
552
553
0
  conn->disconnected = FALSE;
554
0
  i_assert(conn->to == NULL);
555
0
  connection_input_resume_full(conn, FALSE);
556
0
  i_assert(conn->to != NULL || conn->input_idle_timeout_secs == 0);
557
0
  if (set->major_version != 0 && !set->dont_send_version) {
558
0
    e_debug(conn->event, "Sending version handshake");
559
0
    o_stream_nsend_str(conn->output, t_strdup_printf(
560
0
      "VERSION\t%s\t%u\t%u\n", set->service_name_out,
561
0
      set->major_version, set->minor_version));
562
0
  }
563
0
}
564
565
void connection_streams_changed(struct connection *conn)
566
0
{
567
0
  const struct connection_settings *set = &conn->list->set;
568
569
0
  if (set->input_max_size != 0 && conn->io != NULL) {
570
0
    connection_input_halt(conn);
571
0
    connection_input_resume(conn);
572
0
  }
573
0
}
574
575
static void connection_client_connected(struct connection *conn, bool success)
576
0
{
577
0
  i_assert(conn->list->set.client);
578
579
0
  connection_update_properties(conn);
580
581
0
  conn->connect_finished = ioloop_timeval;
582
0
  conn->client_connect_succeeded = success;
583
584
0
  struct event_passthrough *e = event_create_passthrough(conn->event)->
585
0
    set_name("server_connection_connected");
586
0
  if (success) {
587
0
    e_debug(e->event(), "Client connected (fd=%d)",
588
0
      conn->fd_in);
589
0
  } else {
590
0
    e_debug(e->event(), "Client connection failed (fd=%d)",
591
0
      conn->fd_in);
592
0
  }
593
594
0
  if (success)
595
0
    connection_init_streams(conn);
596
0
  if (conn->v.client_connected != NULL)
597
0
    conn->v.client_connected(conn, success);
598
0
  if (!success) {
599
0
    connection_closed(conn, CONNECTION_DISCONNECT_CONN_CLOSED);
600
0
  }
601
0
}
602
603
static void
604
connection_init_full(struct connection_list *list, struct connection *conn,
605
         const char *name, int fd_in, int fd_out)
606
0
{
607
0
  if (conn->id == 0) {
608
0
    if (list->id_counter == 0)
609
0
      list->id_counter++;
610
0
    conn->id = list->id_counter++;
611
0
  }
612
613
0
  i_zero(&conn->connect_started);
614
0
  i_zero(&conn->connect_finished);
615
0
  conn->client_connect_succeeded = FALSE;
616
617
0
  if (conn->ioloop == NULL)
618
0
    conn->ioloop = current_ioloop;
619
0
  conn->fd_in = fd_in;
620
0
  conn->fd_out = fd_out;
621
0
  conn->disconnected = TRUE;
622
0
  conn->remote_uid = (uid_t)-1;
623
0
  conn->remote_gid = (gid_t)-1;
624
0
  conn->remote_pid = (pid_t)-1;
625
626
0
  i_free(conn->base_name);
627
0
  conn->base_name = i_strdup(name);
628
629
0
  if (list->set.input_idle_timeout_secs != 0 &&
630
0
      conn->input_idle_timeout_secs == 0) {
631
0
    conn->input_idle_timeout_secs =
632
0
      list->set.input_idle_timeout_secs;
633
0
  }
634
635
0
  if (conn->event == NULL)
636
0
    conn->event = event_create(conn->event_parent);
637
0
  if (list->set.debug)
638
0
    event_set_forced_debug(conn->event, TRUE);
639
640
  /* Use error iostreams until the client is connected.
641
     This way caller can rely on them always being non-NULL. */
642
0
  const char *conn_error = "connect() not finished yet";
643
0
  if (list->set.client && conn->input == NULL) {
644
0
    conn->input = i_stream_create_error_str(EINPROGRESS, "%s",
645
0
              conn_error);
646
0
  }
647
0
  if (list->set.client && conn->output == NULL) {
648
0
    conn->output = o_stream_create_error_str(EINPROGRESS, "%s",
649
0
               conn_error);
650
0
  }
651
652
0
  if (conn->list != NULL) {
653
0
    i_assert(conn->list == list);
654
0
  } else {
655
0
    conn->list = list;
656
0
    DLLIST_PREPEND(&list->connections, conn);
657
0
    list->connections_count++;
658
0
  }
659
660
0
  connection_update_properties(conn);
661
0
  connection_set_default_handlers(conn);
662
0
}
663
664
void connection_init(struct connection_list *list, struct connection *conn,
665
         const char *name)
666
0
{
667
0
  connection_init_full(list, conn, name, -1, -1);
668
0
}
669
670
void connection_init_server(struct connection_list *list,
671
          struct connection *conn, const char *name,
672
          int fd_in, int fd_out)
673
0
{
674
0
  i_assert(!list->set.client);
675
676
0
  connection_init_full(list, conn, name, fd_in, fd_out);
677
678
0
  struct event_passthrough *e = event_create_passthrough(conn->event)->
679
0
    set_name("client_connection_connected");
680
  /* fd_out differs from fd_in only for stdin/stdout. Keep the logging
681
     output nice and clean by logging only the fd_in. If it's 0, it'll
682
     also be obvious that fd_out=1. */
683
0
  e_debug(e->event(), "Server accepted connection (fd=%d)", fd_in);
684
685
0
  connection_init_streams(conn);
686
  /* Client has finished connecting to server, so record it
687
     here. */
688
0
  conn->connect_finished = ioloop_timeval;
689
690
0
  if (conn->v.init != NULL)
691
0
    conn->v.init(conn);
692
0
}
693
694
void connection_init_server_ip(struct connection_list *list,
695
             struct connection *conn, const char *name,
696
             int fd_in, int fd_out,
697
             const struct ip_addr *remote_ip,
698
             in_port_t remote_port)
699
0
{
700
0
  if (remote_ip != NULL && remote_ip->family != 0)
701
0
    conn->remote_ip = *remote_ip;
702
0
  if (remote_port != 0)
703
0
    conn->remote_port = remote_port;
704
705
0
  connection_init_server(list, conn, name, fd_in, fd_out);
706
0
}
707
708
void connection_init_client_fd(struct connection_list *list,
709
             struct connection *conn, const char *name,
710
             int fd_in, int fd_out)
711
0
{
712
0
  i_assert(list->set.client);
713
714
0
  connection_init_full(list, conn, name, fd_in, fd_out);
715
716
0
  struct event_passthrough *e = event_create_passthrough(conn->event)->
717
0
    set_name("server_connection_connected");
718
  /* fd_out differs from fd_in only for stdin/stdout. Keep the logging
719
     output nice and clean by logging only the fd_in. If it's 0, it'll
720
     also be obvious that fd_out=1. */
721
0
  e_debug(e->event(), "Client connected (fd=%d)", fd_in);
722
723
0
  if (conn->v.init != NULL)
724
0
    conn->v.init(conn);
725
0
  connection_client_connected(conn, TRUE);
726
0
}
727
728
void connection_init_client_ip_from(struct connection_list *list,
729
            struct connection *conn,
730
            const char *hostname,
731
            const struct ip_addr *ip, in_port_t port,
732
            const struct ip_addr *my_ip)
733
0
{
734
0
  const char *name = NULL;
735
736
0
  if (hostname != NULL)
737
0
    name = t_strdup_printf("%s:%u", hostname, port);
738
739
0
  i_assert(list->set.client);
740
741
0
  conn->remote_ip = *ip;
742
0
  conn->remote_port = port;
743
744
0
  if (my_ip != NULL)
745
0
    conn->local_ip = *my_ip;
746
0
  else
747
0
    i_zero(&conn->local_ip);
748
749
0
  connection_init(list, conn, name);
750
0
  if (hostname != NULL)
751
0
    event_add_str(conn->event, "dest_host", hostname);
752
0
  connection_update_event(conn);
753
754
0
  if (conn->v.init != NULL)
755
0
    conn->v.init(conn);
756
0
}
757
758
void connection_init_client_ip(struct connection_list *list,
759
             struct connection *conn, const char *hostname,
760
             const struct ip_addr *ip, in_port_t port)
761
0
{
762
0
  connection_init_client_ip_from(list, conn, hostname, ip, port, NULL);
763
0
}
764
765
void connection_init_client_unix(struct connection_list *list,
766
         struct connection *conn, const char *path)
767
0
{
768
0
  i_assert(list->set.client);
769
770
0
  conn->unix_socket = TRUE;
771
772
0
  connection_init(list, conn, path);
773
0
  event_add_str(conn->event, "socket_path", path);
774
775
0
  if (conn->v.init != NULL)
776
0
    conn->v.init(conn);
777
0
}
778
779
void connection_init_from_streams(struct connection_list *list,
780
          struct connection *conn, const char *name,
781
          struct istream *input, struct ostream *output)
782
0
{
783
0
  connection_init_full(list, conn, name,
784
0
           i_stream_get_fd(input), o_stream_get_fd(output));
785
786
0
  i_assert(conn->fd_in >= 0);
787
0
  i_assert(conn->fd_out >= 0);
788
0
  i_assert(conn->io == NULL);
789
0
  i_assert(conn->to == NULL);
790
791
0
  i_stream_destroy(&conn->input);
792
0
  conn->input = input;
793
0
  i_stream_ref(conn->input);
794
795
0
  o_stream_destroy(&conn->output);
796
0
  conn->output = output;
797
0
  o_stream_ref(conn->output);
798
0
  o_stream_set_no_error_handling(conn->output, TRUE);
799
800
0
  connection_update_stream_names(conn);
801
802
0
  conn->disconnected = FALSE;
803
0
  connection_input_resume_full(conn, FALSE);
804
805
0
  if (conn->v.client_connected != NULL)
806
0
    conn->v.client_connected(conn, TRUE);
807
0
}
808
809
static void connection_set_connect_error_streams(struct connection *conn)
810
0
{
811
0
  int stream_errno = errno;
812
0
  const char *error = t_strdup_printf("connect(%s) failed: %m",
813
0
              conn->name);
814
0
  i_stream_destroy(&conn->input);
815
0
  o_stream_destroy(&conn->output);
816
0
  conn->input = i_stream_create_error_str(stream_errno, "%s", error);
817
0
  conn->output = o_stream_create_error_str(stream_errno, "%s", error);
818
0
  errno = stream_errno;
819
0
}
820
821
static void connection_socket_connected(struct connection *conn)
822
0
{
823
0
  io_remove(&conn->io);
824
0
  timeout_remove(&conn->to);
825
826
0
  errno = net_geterror(conn->fd_in);
827
0
  if (errno != 0)
828
0
    connection_set_connect_error_streams(conn);
829
0
  connection_client_connected(conn, errno == 0);
830
0
}
831
832
int connection_client_connect_with_retries(struct connection *conn,
833
             unsigned int msecs)
834
0
{
835
0
  const struct connection_settings *set = &conn->list->set;
836
0
  int fd;
837
838
0
  i_assert(conn->list->set.client);
839
0
  i_assert(conn->fd_in == -1);
840
841
0
  e_debug(conn->event, "Connecting");
842
843
0
  if (conn->remote_port != 0) {
844
0
    fd = net_connect_ip(&conn->remote_ip, conn->remote_port,
845
0
            (conn->local_ip.family != 0 ?
846
0
             &conn->local_ip : NULL));
847
0
  } else if (msecs == 0) {
848
0
    fd = net_connect_unix(conn->base_name);
849
0
  } else {
850
0
    fd = net_connect_unix_with_retries(conn->base_name, msecs);
851
0
  }
852
0
  if (fd == -1) {
853
0
    connection_set_connect_error_streams(conn);
854
0
    return -1;
855
0
  }
856
0
  conn->fd_in = conn->fd_out = fd;
857
0
  conn->connect_started = ioloop_timeval;
858
0
  conn->disconnected = FALSE;
859
860
0
  if (conn->remote_port != 0 ||
861
0
      conn->list->set.delayed_unix_client_connected_callback) {
862
0
    connection_update_properties(conn);
863
0
    conn->io = io_add_to(conn->ioloop, conn->fd_out, IO_WRITE,
864
0
             connection_socket_connected, conn);
865
0
    e_debug(conn->event,
866
0
      "Waiting for connect (fd=%d) to finish for max %u msecs",
867
0
      fd, set->client_connect_timeout_msecs);
868
0
    if (set->client_connect_timeout_msecs != 0) {
869
0
      conn->to = timeout_add_to(conn->ioloop,
870
0
              set->client_connect_timeout_msecs,
871
0
              *conn->v.connect_timeout, conn);
872
0
    }
873
0
  } else {
874
0
    connection_client_connected(conn, TRUE);
875
0
  }
876
0
  return 0;
877
0
}
878
879
int connection_client_connect(struct connection *conn)
880
0
{
881
0
  return connection_client_connect_with_retries(conn,
882
0
    conn->list->set.unix_client_connect_msecs);
883
0
}
884
885
static void connection_client_connect_failed(struct connection *conn)
886
0
{
887
0
  timeout_remove(&conn->to);
888
0
  errno = conn->connect_failed_errno;
889
0
  conn->v.client_connected(conn, FALSE);
890
0
  connection_closed(conn, CONNECTION_DISCONNECT_CONN_CLOSED);
891
0
}
892
893
int connection_client_connect_async(struct connection *conn)
894
0
{
895
0
  i_assert(conn->v.client_connected != NULL);
896
897
0
  if (connection_client_connect(conn) < 0) {
898
0
    i_assert(conn->to == NULL);
899
0
    conn->connect_failed_errno = errno;
900
0
    conn->to = timeout_add_short(0, connection_client_connect_failed, conn);
901
0
    return -1;
902
0
  }
903
0
  return 0;
904
0
}
905
906
void connection_update_counters(struct connection *conn)
907
0
{
908
0
  if (conn->input != NULL)
909
0
    event_add_int(conn->event, "net_in_bytes", conn->input->v_offset);
910
0
  if (conn->output != NULL)
911
0
    event_add_int(conn->event, "net_out_bytes", conn->output->offset);
912
0
}
913
914
void connection_disconnect(struct connection *conn)
915
0
{
916
0
  if (conn->disconnected)
917
0
    return;
918
0
  connection_update_counters(conn);
919
  /* client connects to a Server, and Server gets connection from Client
920
   */
921
0
  const char *ename = conn->list->set.client ?
922
0
    "server_connection_disconnected" :
923
0
    "client_connection_disconnected";
924
925
0
  struct event_passthrough *e = event_create_passthrough(conn->event)->
926
0
    set_name(ename)->
927
0
    add_str("reason", connection_disconnect_reason(conn));
928
0
  e_debug(e->event(), "Disconnected: %s (fd=%d)",
929
0
    connection_disconnect_reason(conn), conn->fd_in);
930
931
0
  conn->last_input = 0;
932
0
  i_zero(&conn->last_input_tv);
933
0
  timeout_remove(&conn->to);
934
0
  io_remove(&conn->io);
935
0
  i_stream_close(conn->input);
936
0
  o_stream_close(conn->output);
937
0
  if (conn->fd_in == conn->fd_out)
938
0
    (void)shutdown(conn->fd_out, SHUT_RDWR);
939
0
  fd_close_maybe_stdio(&conn->fd_in, &conn->fd_out);
940
0
  conn->disconnected = TRUE;
941
0
}
942
943
void connection_deinit(struct connection *conn)
944
0
{
945
0
  i_assert(conn->list->connections_count > 0);
946
947
0
  conn->list->connections_count--;
948
0
  DLLIST_REMOVE(&conn->list->connections, conn);
949
950
0
  connection_disconnect(conn);
951
0
  i_stream_destroy(&conn->input);
952
0
  o_stream_destroy(&conn->output);
953
0
  i_free(conn->base_name);
954
0
  i_free(conn->label);
955
0
  i_free(conn->property_label);
956
0
  event_unref(&conn->event);
957
0
  conn->list = NULL;
958
0
}
959
960
int connection_input_read_stream(struct connection *conn,
961
         struct istream *input)
962
0
{
963
0
  conn->last_input = ioloop_time;
964
0
  conn->last_input_tv = ioloop_timeval;
965
0
  if (conn->to != NULL)
966
0
    timeout_reset(conn->to);
967
968
0
  switch (i_stream_read(input)) {
969
0
  case -2:
970
    /* buffer full */
971
0
    switch (conn->list->set.input_full_behavior) {
972
0
    case CONNECTION_BEHAVIOR_DESTROY:
973
0
      connection_closed(conn,
974
0
            CONNECTION_DISCONNECT_BUFFER_FULL);
975
0
      return -1;
976
0
    case CONNECTION_BEHAVIOR_ALLOW:
977
0
      return -2;
978
0
    }
979
0
    i_unreached();
980
0
  case -1:
981
    /* disconnected */
982
0
    if (input != conn->input) {
983
0
      i_stream_set_error(conn->input, input->stream_errno,
984
0
             "%s", i_stream_get_error(input));
985
0
    }
986
0
    connection_closed(conn, CONNECTION_DISCONNECT_CONN_CLOSED);
987
0
    return -1;
988
0
  case 0:
989
    /* nothing new read */
990
0
    return 0;
991
0
  default:
992
    /* something was read */
993
0
    return 1;
994
0
  }
995
0
}
996
997
int connection_input_read(struct connection *conn)
998
0
{
999
0
  return connection_input_read_stream(conn, conn->input);
1000
0
}
1001
1002
const char *connection_disconnect_reason(struct connection *conn)
1003
0
{
1004
0
  switch (conn->disconnect_reason) {
1005
0
  case CONNECTION_DISCONNECT_DEINIT:
1006
0
    return "Deinitializing";
1007
0
  case CONNECTION_DISCONNECT_CONNECT_TIMEOUT: {
1008
0
    unsigned int msecs =
1009
0
      conn->list->set.client_connect_timeout_msecs;
1010
0
    return t_strdup_printf("connect(%s) timed out in %u.%03u secs",
1011
0
               conn->name, msecs/1000, msecs%1000);
1012
0
  }
1013
0
  case CONNECTION_DISCONNECT_IDLE_TIMEOUT:
1014
0
    return "Idle timeout";
1015
0
  case CONNECTION_DISCONNECT_CONN_CLOSED:
1016
0
    if (!conn->client_connect_succeeded) {
1017
      /* connect() error is in the error istream */
1018
0
      i_assert(conn->input != NULL);
1019
0
      return i_stream_get_error(conn->input);
1020
0
    }
1021
    /* fall through */
1022
0
  case CONNECTION_DISCONNECT_NOT:
1023
0
  case CONNECTION_DISCONNECT_BUFFER_FULL:
1024
0
    return io_stream_get_disconnect_reason(conn->input, conn->output);
1025
0
  case CONNECTION_DISCONNECT_HANDSHAKE_FAILED:
1026
0
    return "Handshake failed";
1027
0
  }
1028
0
  i_unreached();
1029
0
}
1030
1031
const char *connection_input_timeout_reason(struct connection *conn)
1032
0
{
1033
0
  if (conn->last_input_tv.tv_sec != 0) {
1034
0
    long long diff = timeval_diff_msecs(&ioloop_timeval,
1035
0
                &conn->last_input_tv);
1036
0
    return t_strdup_printf("No input for %lld.%03lld secs",
1037
0
               diff/1000, diff%1000);
1038
0
  } else if (conn->connect_finished.tv_sec != 0) {
1039
0
    long long diff = timeval_diff_msecs(&ioloop_timeval,
1040
0
                &conn->connect_finished);
1041
0
    return t_strdup_printf(
1042
0
      "No input since connected %lld.%03lld secs ago",
1043
0
      diff/1000, diff%1000);
1044
0
  } else {
1045
0
    long long diff = timeval_diff_msecs(&ioloop_timeval,
1046
0
                &conn->connect_started);
1047
0
    return t_strdup_printf(
1048
0
      "connect(%s) timed out after %lld.%03lld secs",
1049
0
      conn->name, diff/1000, diff%1000);
1050
0
  }
1051
0
}
1052
1053
void connection_set_handlers(struct connection *conn,
1054
           const struct connection_vfuncs *vfuncs)
1055
0
{
1056
0
  connection_input_halt(conn);
1057
0
  i_assert(vfuncs->destroy != NULL);
1058
0
  conn->v = *vfuncs;
1059
0
        if (conn->v.input == NULL)
1060
0
                conn->v.input = connection_input_default;
1061
0
        if (conn->v.input_line == NULL)
1062
0
                conn->v.input_line = connection_input_line_default;
1063
0
        if (conn->v.handshake_args == NULL)
1064
0
                conn->v.handshake_args = connection_handshake_args_default;
1065
0
        if (conn->v.idle_timeout == NULL)
1066
0
                conn->v.idle_timeout = connection_idle_timeout;
1067
0
        if (conn->v.connect_timeout == NULL)
1068
0
                conn->v.connect_timeout = connection_connect_timeout;
1069
0
  if (!conn->disconnected)
1070
0
    connection_input_resume_full(conn, FALSE);
1071
0
}
1072
1073
void connection_set_default_handlers(struct connection *conn)
1074
0
{
1075
0
  connection_set_handlers(conn, &conn->list->v);
1076
0
}
1077
1078
void connection_switch_ioloop_to(struct connection *conn,
1079
         struct ioloop *ioloop)
1080
0
{
1081
0
  conn->ioloop = ioloop;
1082
0
  if (conn->io != NULL)
1083
0
    conn->io = io_loop_move_io_to(ioloop, &conn->io);
1084
0
  if (conn->to != NULL)
1085
0
    conn->to = io_loop_move_timeout_to(ioloop, &conn->to);
1086
0
  if (conn->input != NULL)
1087
0
    i_stream_switch_ioloop_to(conn->input, ioloop);
1088
0
  if (conn->output != NULL)
1089
0
    o_stream_switch_ioloop_to(conn->output, ioloop);
1090
0
}
1091
1092
void connection_switch_ioloop(struct connection *conn)
1093
0
{
1094
0
  connection_switch_ioloop_to(conn, current_ioloop);
1095
0
}
1096
1097
struct connection_list *
1098
connection_list_init(const struct connection_settings *set,
1099
         const struct connection_vfuncs *vfuncs)
1100
0
{
1101
0
  struct connection_list *list;
1102
1103
0
  i_assert(vfuncs->input != NULL ||
1104
0
     set->input_full_behavior != CONNECTION_BEHAVIOR_ALLOW);
1105
0
  i_assert(set->major_version == 0 ||
1106
0
     (set->service_name_in != NULL &&
1107
0
      set->service_name_out != NULL &&
1108
0
      set->output_max_size != 0));
1109
1110
0
  list = i_new(struct connection_list, 1);
1111
0
  list->set = *set;
1112
0
  list->v = *vfuncs;
1113
1114
0
  return list;
1115
0
}
1116
1117
void connection_list_deinit(struct connection_list **_list)
1118
0
{
1119
0
  struct connection_list *list = *_list;
1120
0
  struct connection *conn;
1121
1122
0
  if (list == NULL)
1123
0
    return;
1124
0
  *_list = NULL;
1125
1126
0
  while (list->connections != NULL) {
1127
0
    conn = list->connections;
1128
0
    connection_closed(conn, CONNECTION_DISCONNECT_DEINIT);
1129
0
    i_assert(conn != list->connections);
1130
0
  }
1131
0
  i_free(list);
1132
0
}
1133
1134
bool connection_is_valid_dns_name(const char *name)
1135
0
{
1136
0
  const char *p = name;
1137
0
  if (*name == '\0')
1138
0
    return FALSE;
1139
0
  if (strstr(name, "..") != NULL)
1140
0
    return FALSE;
1141
0
  for (; *p != '\0'; p++) {
1142
0
    if ((*p < '0' || *p > '9') &&
1143
0
        (*p < 'A' || *p > 'Z') &&
1144
0
        (*p < 'a' || *p > 'z') &&
1145
0
        *p != '.' && *p != '-' &&
1146
0
        *p != '_' && *p != ':')
1147
0
      return FALSE;
1148
0
  }
1149
0
  return p - name < 256; /* maximum length is 255 by RFC 952 */
1150
0
}