forked from LINBIT/csync2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
conn.c
643 lines (529 loc) · 15.2 KB
/
conn.c
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
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
/*
* csync2 - cluster synchronization tool, 2nd generation
* Copyright (C) 2004 - 2015 LINBIT Information Technologies GmbH
* http://www.linbit.com; see also AUTHORS
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "csync2.h"
#include <stdarg.h>
#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <unistd.h>
#include <netdb.h>
#include <errno.h>
#ifdef HAVE_LIBGNUTLS
# include <gnutls/gnutls.h>
# include <gnutls/x509.h>
#endif
int conn_fd_in = -1;
int conn_fd_out = -1;
int conn_clisok = 0;
#ifdef HAVE_LIBGNUTLS
int csync_conn_usessl = 0;
static gnutls_session_t conn_tls_session;
static gnutls_certificate_credentials_t conn_x509_cred;
#endif
static const char *__response[] = {
[CR_OK_CMD_FINISHED] = "OK (cmd_finished).",
[CR_OK_DATA_FOLLOWS] = "OK (data_follows).",
[CR_OK_SEND_DATA] = "OK (send_data).",
[CR_OK_NOT_FOUND] = "OK (not_found).",
[CR_OK_PATH_NOT_FOUND] = "OK (path_not_found).",
[CR_OK_CU_LATER] = "OK (cu_later).",
[CR_OK_ACTIVATING_SSL] = "OK (activating_ssl).",
/* CR_ERROR: all sorts of strings; often strerror(errno) */
/* more specific errors: */
[CR_ERR_CONN_CLOSED] = "Connection closed.",
[CR_ERR_ALSO_DIRTY_HERE] = "File is also marked dirty here!",
[CR_ERR_PARENT_DIR_MISSING] = "Parent dir missing.",
[CR_ERR_GROUP_LIST_ALREADY_SET] = "Group list already set!",
[CR_ERR_IDENTIFICATION_FAILED] = "Identification failed!",
[CR_ERR_PERM_DENIED_FOR_SLAVE] = "Permission denied for slave!",
[CR_ERR_PERM_DENIED] = "Permission denied!",
[CR_ERR_SSL_EXPECTED] = "SSL encrypted connection expected!",
[CR_ERR_UNKNOWN_COMMAND] = "Unkown command!",
[CR_ERR_WIN32_EIO_CREATE_DIR] = "Win32 I/O Error on CreateDirectory()",
};
static const int __response_size = sizeof(__response)/sizeof(__response[0]);
const char *conn_response(unsigned i)
{
if (i < __response_size
&& __response[i]
&& __response[i][0])
return __response[i];
csync_fatal("BUG! No such response: %u\n", i);
return NULL;
}
static const unsigned int response_len(unsigned i)
{
static unsigned int __response_len[sizeof(__response)/sizeof(__response[0])];
static int initialized;
if (!initialized) {
unsigned int j;
for (j = 0; j < __response_size; j++)
__response_len[j] = strlen(__response[j] ?: "");
initialized = 1;
}
return (i < __response_size) ? __response_len[i] : 0;
}
enum connection_response conn_response_to_enum(const char *response)
{
unsigned int i, len;
for (i = 0; i < __response_size; i++) {
len = response_len(i);
if (len && !strncmp(__response[i], response, len))
return i;
}
/* may be a new OK code? */
if (!strncmp(response, "OK (", 4))
return CR_OK;
else
return CR_ERROR;
}
static void csync_client_bind(int sfd, struct addrinfo *peer_ai)
{
struct addrinfo hints;
struct addrinfo *result, *rp;
int s;
if (!bind_to_myhostname)
return;
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_family = peer_ai->ai_family;
hints.ai_socktype = SOCK_STREAM;
s = getaddrinfo(bind_to_myhostname ? myhostname : NULL, 0, &hints, &result);
if (s != 0) {
csync_debug(1, "Cannot prepare local socket for bind, getaddrinfo: %s\n", gai_strerror(s));
return;
}
for (rp = result; rp != NULL; rp = rp->ai_next) {
if (bind(sfd, rp->ai_addr, rp->ai_addrlen) == 0)
break; /* Success */
}
if (rp != NULL) {
char hbuf[NI_MAXHOST], sbuf[NI_MAXSERV];
if (getnameinfo(rp->ai_addr, rp->ai_addrlen,
hbuf, sizeof(hbuf), sbuf, sizeof(sbuf),
NI_NUMERICHOST | NI_NUMERICSERV) == 0)
csync_debug(1, "Bound to %s:%s as %s.\n",
hbuf, sbuf, myhostname);
else
/* WTF, is failure even possible here?
* Anyways, bind() did not report an error. */
csync_debug(1, "Bound local socket as %s.\n", myhostname);
} else
/* So bind() failed. Ignore, and try to connect anyways.
* Maybe it still works, maybe identification paranoia of the
* peer will kick us out. */
csync_debug(1, "Local socket bind() to %s failed; ignored.\n", myhostname);
freeaddrinfo(result); /* No longer needed */
}
/* getaddrinfo stuff mostly copied from its manpage */
int conn_connect(const char *peername)
{
struct addrinfo hints;
struct addrinfo *result, *rp;
int save_errno = 0;
int sfd = -1, s;
/* Obtain address(es) matching host/port */
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_family = AF_UNSPEC; /* Allow IPv4 or IPv6 */
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = 0;
hints.ai_protocol = 0; /* Any protocol */
s = getaddrinfo(peername, csync_port, &hints, &result);
if (s != 0) {
csync_debug(1, "Cannot resolve peername, getaddrinfo: %s\n", gai_strerror(s));
return -1;
}
/* getaddrinfo() returns a list of address structures.
Try each address until we successfully connect(2).
If socket(2) (or connect(2)) fails, we (close the socket
and) try the next address. */
for (rp = result; rp != NULL; rp = rp->ai_next) {
sfd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
if (sfd == -1)
continue;
/* If called with -N somehostname, try to bind to that name.
* If that fails, ignore, and try the connect anyways. */
csync_client_bind(sfd, rp);
if (connect(sfd, rp->ai_addr, rp->ai_addrlen) != -1)
break; /* Success */
save_errno = errno;
close(sfd);
sfd = -1;
}
if (sfd != -1) {
char hbuf[NI_MAXHOST], sbuf[NI_MAXSERV];
if (getnameinfo(rp->ai_addr, rp->ai_addrlen,
hbuf, sizeof(hbuf), sbuf, sizeof(sbuf),
NI_NUMERICHOST | NI_NUMERICSERV) == 0)
csync_debug(1, "Connect to %s:%s (%s).\n",
hbuf, sbuf, peername);
else
/* WTF, is failure even possible here? */
csync_debug(1, "Connect to <?>:%s (%s).\n",
csync_port, peername);
}
freeaddrinfo(result); /* No longer needed */
if (sfd == -1 && save_errno)
errno = save_errno;
return sfd;
}
int conn_open(const char *peername)
{
int on = 1;
conn_fd_in = conn_connect(peername);
if (conn_fd_in < 0) {
csync_debug(1, "Can't create socket: %s\n", strerror(errno));
return -1;
}
if (setsockopt(conn_fd_in, IPPROTO_TCP, TCP_NODELAY, &on, sizeof(on) ) < 0) {
csync_debug(2, "Can't set TCP_NODELAY option on TCP socket.\n");
close(conn_fd_in); conn_fd_in = -1;
return -1;
}
conn_fd_out = conn_fd_in;
conn_clisok = 1;
#ifdef HAVE_LIBGNUTLS
csync_conn_usessl = 0;
#endif
return 0;
}
int conn_set(int infd, int outfd)
{
int on = 1;
conn_fd_in = infd;
conn_fd_out = outfd;
conn_clisok = 1;
#ifdef HAVE_LIBGNUTLS
csync_conn_usessl = 0;
#endif
// when running in server mode, this has been done already
// in csync2.c with more restrictive error handling..
// FIXME don't even try in "ssh" mode
if ( setsockopt(conn_fd_out, IPPROTO_TCP, TCP_NODELAY, &on, (socklen_t) sizeof(on)) < 0 )
csync_debug(2, "Can't set TCP_NODELAY option on TCP socket.\n");
return 0;
}
#ifdef HAVE_LIBGNUTLS
static void ssl_log(int level, const char* msg)
{ csync_debug(level, "%s", msg); }
int conn_activate_ssl(int server_role)
{
gnutls_alert_description_t alrt;
char *ssl_keyfile;
char *ssl_certfile;
int err;
if (csync_conn_usessl)
return 0;
ASPRINTF(&ssl_keyfile, "%s/csync2_ssl_key.pem", systemdir);
ASPRINTF(&ssl_certfile, "%s/csync2_ssl_cert.pem", systemdir);
gnutls_global_init();
gnutls_global_set_log_function(ssl_log);
gnutls_global_set_log_level(10);
gnutls_certificate_allocate_credentials(&conn_x509_cred);
err = gnutls_certificate_set_x509_key_file(conn_x509_cred, ssl_certfile, ssl_keyfile, GNUTLS_X509_FMT_PEM);
if(err != GNUTLS_E_SUCCESS) {
gnutls_certificate_free_credentials(conn_x509_cred);
gnutls_global_deinit();
csync_fatal(
"SSL: failed to use key file %s and/or certificate file %s: %s (%s)\n",
ssl_keyfile,
ssl_certfile,
gnutls_strerror(err),
gnutls_strerror_name(err)
);
}
if(server_role) {
gnutls_certificate_free_cas(conn_x509_cred);
if(gnutls_certificate_set_x509_trust_file(conn_x509_cred, ssl_certfile, GNUTLS_X509_FMT_PEM) < 1) {
gnutls_certificate_free_credentials(conn_x509_cred);
gnutls_global_deinit();
csync_fatal(
"SSL: failed to use certificate file %s as CA.\n",
ssl_certfile
);
}
} else
gnutls_certificate_free_ca_names(conn_x509_cred);
gnutls_init(&conn_tls_session, (server_role ? GNUTLS_SERVER : GNUTLS_CLIENT));
gnutls_priority_set_direct(conn_tls_session, "PERFORMANCE", NULL);
gnutls_credentials_set(conn_tls_session, GNUTLS_CRD_CERTIFICATE, conn_x509_cred);
if(server_role) {
gnutls_certificate_send_x509_rdn_sequence(conn_tls_session, 0);
gnutls_certificate_server_set_request(conn_tls_session, GNUTLS_CERT_REQUIRE);
}
gnutls_transport_set_ptr2(
conn_tls_session,
(gnutls_transport_ptr_t)(long)conn_fd_in,
(gnutls_transport_ptr_t)(long)conn_fd_out
);
err = gnutls_handshake(conn_tls_session);
switch(err) {
case GNUTLS_E_SUCCESS:
break;
case GNUTLS_E_WARNING_ALERT_RECEIVED:
alrt = gnutls_alert_get(conn_tls_session);
fprintf(
csync_debug_out,
"SSL: warning alert received from peer: %d (%s).\n",
alrt, gnutls_alert_get_name(alrt)
);
break;
case GNUTLS_E_FATAL_ALERT_RECEIVED:
alrt = gnutls_alert_get(conn_tls_session);
fprintf(
csync_debug_out,
"SSL: fatal alert received from peer: %d (%s).\n",
alrt, gnutls_alert_get_name(alrt)
);
default:
gnutls_bye(conn_tls_session, GNUTLS_SHUT_RDWR);
gnutls_deinit(conn_tls_session);
gnutls_certificate_free_credentials(conn_x509_cred);
gnutls_global_deinit();
csync_fatal(
"SSL: handshake failed: %s (%s)\n",
gnutls_strerror(err),
gnutls_strerror_name(err)
);
}
csync_conn_usessl = 1;
return 0;
}
int conn_check_peer_cert(const char *peername, int callfatal)
{
const gnutls_datum_t *peercerts;
unsigned npeercerts;
int i, cert_is_ok = -1;
if (!csync_conn_usessl)
return 1;
peercerts = gnutls_certificate_get_peers(conn_tls_session, &npeercerts);
if(peercerts == NULL || npeercerts == 0) {
if (callfatal)
csync_fatal("Peer did not provide an SSL X509 cetrificate.\n");
csync_debug(1, "Peer did not provide an SSL X509 cetrificate.\n");
return 0;
}
{
char certdata[2*peercerts[0].size + 1];
for (i=0; i<peercerts[0].size; i++)
sprintf(&certdata[2*i], "%02X", peercerts[0].data[i]);
certdata[2*i] = 0;
SQL_BEGIN("Checking peer x509 certificate.",
"SELECT certdata FROM x509_cert WHERE peername = '%s'",
url_encode(peername))
{
if (!strcmp(SQL_V(0), certdata))
cert_is_ok = 1;
else
cert_is_ok = 0;
} SQL_END;
if (cert_is_ok < 0) {
csync_debug(1, "Adding peer x509 certificate to db: %s\n", certdata);
SQL("Adding peer x509 sha1 hash to database.",
"INSERT INTO x509_cert (peername, certdata) VALUES ('%s', '%s')",
url_encode(peername), url_encode(certdata));
return 1;
}
csync_debug(2, "Peer x509 certificate is: %s\n", certdata);
if (!cert_is_ok) {
if (callfatal)
csync_fatal("Peer did provide a wrong SSL X509 cetrificate.\n");
csync_debug(1, "Peer did provide a wrong SSL X509 cetrificate.\n");
return 0;
}
}
return 1;
}
#else
int conn_check_peer_cert(const char *peername, int callfatal)
{
return 1;
}
#endif /* HAVE_LIBGNUTLS */
int conn_close()
{
if ( !conn_clisok ) return -1;
#ifdef HAVE_LIBGNUTLS
if ( csync_conn_usessl ) {
gnutls_bye(conn_tls_session, GNUTLS_SHUT_RDWR);
gnutls_deinit(conn_tls_session);
gnutls_certificate_free_credentials(conn_x509_cred);
gnutls_global_deinit();
}
#endif
if ( conn_fd_in != conn_fd_out) close(conn_fd_in);
close(conn_fd_out);
conn_fd_in = -1;
conn_fd_out = -1;
conn_clisok = 0;
return 0;
}
static inline int READ(void *buf, size_t count)
{
#ifdef HAVE_LIBGNUTLS
if (csync_conn_usessl)
return gnutls_record_recv(conn_tls_session, buf, count);
else
#endif
return read(conn_fd_in, buf, count);
}
static inline int WRITE(const void *buf, size_t count)
{
static int n, total;
#ifdef HAVE_LIBGNUTLS
if (csync_conn_usessl)
return gnutls_record_send(conn_tls_session, buf, count);
else
#endif
{
total = 0;
while (count > total) {
n = write(conn_fd_out, ((char *) buf) + total, count - total);
if (n >= 0)
total += n;
else {
if (errno == EINTR)
continue;
else
return -1;
}
}
return total;
}
}
int conn_raw_read(void *buf, size_t count)
{
static char buffer[512];
static int buf_start=0, buf_end=0;
if ( buf_start == buf_end ) {
if (count > 128)
return READ(buf, count);
else {
buf_start = 0;
buf_end = READ(buffer, 512);
if (buf_end < 0) { buf_end=0; return -1; }
}
}
if ( buf_start < buf_end ) {
size_t real_count = buf_end - buf_start;
if ( real_count > count ) real_count = count;
memcpy(buf, buffer+buf_start, real_count);
buf_start += real_count;
return real_count;
}
return 0;
}
struct conn_debug_buf {
char *pos;
size_t rlen;
};
static void buf_printf(struct conn_debug_buf *b, const char *fmt, ...)
{
va_list ap;
int c;
if (b->rlen <= 0)
return;
va_start(ap, fmt);
c = vsnprintf(b->pos, b->rlen, fmt, ap);
va_end(ap);
if (c >= b->rlen) {
b->pos[b->rlen - 1] = '\0';
c = b->rlen;
}
if (c >= 0) {
b->rlen -= c;
b->pos += c;
}
}
void conn_debug(const char *name, const char*buf, size_t count)
{
char buffer[1024];
struct conn_debug_buf b = {
.pos = buffer,
.rlen = sizeof(buffer)
};
int i;
if ( csync_debug_level < 3 ) return;
if (csync_server_child_pid)
buf_printf(&b, "<%d> ", csync_server_child_pid);
buf_printf(&b, "%s> ", name);
for (i=0; i<count; i++) {
switch (buf[i]) {
case '\n':
buf_printf(&b, "\\n");
break;
case '\r':
buf_printf(&b, "\\r");
break;
default:
if (buf[i] < 32 || buf[i] >= 127)
buf_printf(&b, "\\%03o", buf[i]);
else
buf_printf(&b, "%c", buf[i]);
break;
}
}
fprintf(csync_debug_out, "%s\n", buffer);
}
int conn_read(void *buf, size_t count)
{
int pos, rc;
for (pos=0; pos < count; pos+=rc) {
rc = conn_raw_read(buf+pos, count-pos);
if (rc <= 0) return pos;
}
conn_debug("Peer", buf, pos);
return pos;
}
int conn_write(const void *buf, size_t count)
{
conn_debug("Local", buf, count);
return WRITE(buf, count);
}
void conn_printf(const char *fmt, ...)
{
char dummy, *buffer;
va_list ap;
int size;
va_start(ap, fmt);
size = vsnprintf(&dummy, 1, fmt, ap);
buffer = alloca(size+1);
va_end(ap);
va_start(ap, fmt);
vsnprintf(buffer, size+1, fmt, ap);
va_end(ap);
conn_write(buffer, size);
}
size_t conn_gets(char *s, size_t size)
{
size_t i=0;
while (i<size-1) {
int rc = conn_raw_read(s+i, 1);
if (rc != 1) break;
if (s[i++] == '\n') break;
}
s[i] = 0;
conn_debug("Peer", s, i);
if (i > 1 && s[i-1] != '\n')
csync_fatal("Received line too long for buffer size (%u), giving up.\n", size);
return i;
}