File: sync.c

package info (click to toggle)
milter-greylist 3.0-3.1
  • links: PTS
  • area: main
  • in suites: lenny
  • size: 920 kB
  • ctags: 787
  • sloc: ansic: 6,864; sh: 3,205; yacc: 736; lex: 321; makefile: 166
file content (1479 lines) | stat: -rw-r--r-- 33,094 bytes parent folder | download
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
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
/* $Id: sync.c,v 1.66.2.5 2006/11/07 05:12:12 manu Exp $ */

/*
 * Copyright (c) 2004 Emmanuel Dreyfus
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *        This product includes software developed by Emmanuel Dreyfus
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,  
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 * OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "config.h"

#ifdef HAVE_SYS_CDEFS_H
#include <sys/cdefs.h>
#ifdef __RCSID
__RCSID("$Id: sync.c,v 1.66.2.5 2006/11/07 05:12:12 manu Exp $");
#endif
#endif

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
#include <strings.h>
#include <pthread.h>
#include <syslog.h>
#include <sysexits.h>

#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#include "pending.h"
#include "sync.h"
#include "conf.h"
#include "autowhite.h"
#include "milter-greylist.h"

#define SYNC_PROTO_CURRENT 3

struct sync_master_sock {
	int runs;
	int sock;
};

struct sync_master_sock sync_master4 = { 0, -1 };
struct sync_master_sock sync_master6 = { 0, -1 };
struct peerlist peer_head;
pthread_rwlock_t peer_lock; /* For the peer list */
pthread_rwlock_t sync_lock; /* For all peer's sync queue */
pthread_cond_t sync_sleepflag;

static void sync_listen(char *, char *, struct sync_master_sock *);
static int local_addr(const struct sockaddr *sa, const socklen_t salen);
static int sync_queue_poke(struct peer *, struct sync *);
static struct sync * sync_queue_peek(struct peer *);
static int select_protocol(struct peer *, int, FILE *);
static void sync_vers(FILE *, int);

void
peer_init(void) {
	int error;

	LIST_INIT(&peer_head);
	if ((error = pthread_rwlock_init(&peer_lock, NULL)) != 0) {
		mg_log(LOG_ERR, 
		    "pthread_rwlock_init failed: %s", strerror(error));
		exit(EX_OSERR);
	}

	if ((error = pthread_rwlock_init(&sync_lock, NULL)) != 0) {
		mg_log(LOG_ERR, 
		    "pthread_rwlock_init failed: %s", strerror(error));
		exit(EX_OSERR);
	}

	if ((error = pthread_cond_init(&sync_sleepflag, NULL)) != 0) {
		mg_log(LOG_ERR, 
		    "pthread_cond_init failed: %s", strerror(error));
		exit(EX_OSERR);
	}

	return;
}

void 
peer_clear(void) {
	struct peer *peer;
	struct sync *sync;

	PEER_WRLOCK;

	while(!LIST_EMPTY(&peer_head)) {
		peer = LIST_FIRST(&peer_head);

		while((sync = sync_queue_peek(peer)) != NULL)
			sync_free(sync);
			
		if (peer->p_stream != NULL)
			fclose(peer->p_stream);

		LIST_REMOVE(peer, p_list);
		free(peer->p_name);
		free(peer);
	}

	PEER_UNLOCK;

	return;	
}

void 
peer_add(peername)
	char *peername;
{
	struct peer *peer;

	if ((peer = malloc(sizeof(*peer))) == NULL ||
	    (peer->p_name = strdup(peername)) == NULL) {
		mg_log(LOG_ERR, "cannot add peer: %s", strerror(errno));
		exit(EX_OSERR);
	}

	peer->p_qlen = 0;
	peer->p_stream = NULL;
	peer->p_flags = 0;
	TAILQ_INIT(&peer->p_deferred);

	PEER_WRLOCK;
	LIST_INSERT_HEAD(&peer_head, peer, p_list);
	PEER_UNLOCK;

	if (conf.c_debug)
		mg_log(LOG_DEBUG, "load peer %s", peer->p_name);

	return;
}

void
peer_create(pending)
	struct pending *pending;
{
	struct peer *peer;

	PEER_RDLOCK;
	if (LIST_EMPTY(&peer_head))
		goto out;

	LIST_FOREACH(peer, &peer_head, p_list) 
		sync_queue(peer, PS_CREATE, pending, -1); /* -1: unused */

out:
	PEER_UNLOCK;
	
	return;
}

void
peer_delete(pending, autowhite)
	struct pending *pending;
	time_t autowhite;
{
	struct peer *peer;

	PEER_RDLOCK;
	if (LIST_EMPTY(&peer_head))
		goto out;

	LIST_FOREACH(peer, &peer_head, p_list) 
		sync_queue(peer, PS_DELETE, pending, autowhite);

out:
	PEER_UNLOCK;
	
	return;
}

static int
sync_queue_poke(peer, sync)
	struct peer *peer;
	struct sync *sync;
{
	SYNC_WRLOCK;
	if (peer->p_qlen < SYNC_MAXQLEN) {
		TAILQ_INSERT_HEAD(&peer->p_deferred, sync, s_list);
		peer->p_qlen++;
		SYNC_UNLOCK;
		return 1;
	} else {
		SYNC_UNLOCK;
		return 0;
	}
}

static struct sync *
sync_queue_peek(peer)
	struct peer *peer;
{
	struct sync *sync;

	SYNC_WRLOCK;
	sync = TAILQ_FIRST(&peer->p_deferred);
	if (!TAILQ_EMPTY(&peer->p_deferred)) {
		TAILQ_REMOVE(&peer->p_deferred, sync, s_list);
		peer->p_qlen--;
	}
	SYNC_UNLOCK;
	return sync;
}

int
sync_send(peer, type, pending, autowhite) /* peer list is read-locked */
	struct peer *peer;
	peer_sync_t type;
	struct pending *pending;
	time_t autowhite;
{
	char sep[] = " \n\t\r";
	char *replystr;
	int replycode;
	char line[LINELEN + 1];
	char *cookie = NULL;
	char *keyw;
	char awstr[LINELEN + 1];
	int bw;

	if ((peer->p_stream == NULL) && (peer_connect(peer) != 0))
		return -1;

	*line = '\0';
	switch(type) {
	case PS_FLUSH:
		bw = snprintf(line, LINELEN, "flush addr %s\r\n",
		    pending->p_addr);
		break;
	case PS_CREATE:
		bw = snprintf(line, LINELEN, "add addr %s from %s "
		    "rcpt %s date %ld\r\n", pending->p_addr, 
			pending->p_from, pending->p_rcpt, 
			(long)pending->p_tv.tv_sec);
		break;
	default:
		if (peer->p_vers >= 2) {
			keyw = "del2";
			snprintf(awstr, LINELEN, " aw %ld", (long)autowhite);
		} else {
			keyw = "del";
			awstr[0] = '\0';
		}
		bw = snprintf(line, LINELEN, "%s addr %s from %s "
		    "rcpt %s date %ld%s\r\n", keyw, pending->p_addr, 
			pending->p_from, pending->p_rcpt, 
			(long)pending->p_tv.tv_sec, awstr);
		break;
	}

	if (bw > LINELEN) {
		mg_log(LOG_ERR, "closing connexion with peer %s: "
		    "send buffer would overflow (%d entries queued)", 
		    peer->p_name, peer->p_qlen);
		fclose(peer->p_stream);
		peer->p_stream = NULL;
		return -1;
	}

	bw = fprintf(peer->p_stream, "%s", line);
	if (bw != strlen(line)) {
		mg_log(LOG_ERR, "closing connexion with peer %s: "
		    "%s (%d entries queued) - I was unable to send "
		    "complete line \"%s\" - bytes written: %i", 
		    peer->p_name, strerror(errno), peer->p_qlen, 
		    line, bw);
		fclose(peer->p_stream);
		peer->p_stream = NULL;
		return -1;
	}

	fflush(peer->p_stream);

	/* 
	 * Check the return code 
	 */
	get_more:
	sync_waitdata(peer->p_socket);
	if (fgets(line, LINELEN, peer->p_stream) == NULL) {
		if (errno == EAGAIN) {
			if ( feof(peer->p_stream) ) {
				mg_log(LOG_ERR, "lost connexion with peer %s: "
		  		  "%s (%d entries queued)", 
				    peer->p_name, strerror(errno), peer->p_qlen);
				fclose(peer->p_stream);
				peer->p_stream = NULL;
				return -1;
			}
			goto get_more;
		}
		mg_log(LOG_ERR, "lost connexion with peer %s: "
		    "%s (%d entries queued)", 
		    peer->p_name, strerror(errno), peer->p_qlen);
		fclose(peer->p_stream);
		peer->p_stream = NULL;
		return -1;
	}

	/*
	 * On some systems, opening a stream on a socket introduce
	 * weird behavior: the in and out buffers get mixed up. 
	 * By calling fflush() after each read operation, we fix that
	 */
	fflush(peer->p_stream);

	if ((replystr = strtok_r(line, sep, &cookie)) == NULL) {
		mg_log(LOG_ERR, "Unexpected reply \"%s\" from %s, "
		    "closing connexion (%d entries queued)", 
		    line, peer->p_name, peer->p_qlen);
		fclose(peer->p_stream);
		peer->p_stream = NULL;
		return -1;
	}

	replycode = atoi(replystr);
	if (replycode != 201) {
		mg_log(LOG_ERR, "Unexpected reply \"%s\" from %s, "
		    "closing connexion (%d entries queued)", 
		    line, peer->p_name, peer->p_qlen);
		fclose(peer->p_stream);
		peer->p_stream = NULL;
		return -1;
	}

	if (conf.c_debug)
		mg_log(LOG_DEBUG, "sync one entry with %s", peer->p_name);

	return 0;
}

int
peer_connect(peer)	/* peer list is read-locked */
	struct peer *peer;
{
	struct servent *se;
#ifdef HAVE_GETADDRINFO
	struct addrinfo hints, *res0, *res;
	int err;
#else
	struct protoent *pe;
	int proto;
	sockaddr_t raddr;
	socklen_t raddrlen;
#endif
	sockaddr_t laddr;
	socklen_t laddrlen;
	char *laddrstr;
	int service;
	int s = -1;
	char *replystr;
	int replycode;
	FILE *stream;
	char sep[] = " \n\t\r";
	char line[LINELEN + 1];
	int param;
	char *cookie = NULL;

	if (peer->p_stream != NULL)
		mg_log(LOG_ERR, "peer_connect called and peer->p_stream != 0");

	if (conf.c_syncport != NULL) {
		service = htons(atoi(conf.c_syncport));
	} else {
		if ((se = getservbyname(MXGLSYNC_NAME, "tcp")) == NULL)
		    service = htons(atoi(MXGLSYNC_PORT));
		else
		    service = se->s_port;
	}

#ifdef HAVE_GETADDRINFO
	bzero(&hints, sizeof(hints));
	hints.ai_family = AF_UNSPEC;
	hints.ai_socktype = SOCK_STREAM;
	if ((err = getaddrinfo(peer->p_name, "0", &hints, &res0)) != 0) {
		mg_log(LOG_ERR, "cannot sync with peer %s, "
		    "getaddrinfo failed: %s (%d entries queued)",
		    peer->p_name, gai_strerror(err), peer->p_qlen);
		return -1;
	}

	for (res = res0; res; res = res->ai_next) {
		/*We only test an address family which kernel supports. */
		s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
		if (s == -1)
			continue;
		close(s);

		if (local_addr(res->ai_addr, res->ai_addrlen)) {
			peer->p_flags |= P_LOCAL;
			freeaddrinfo(res0);
			return -1;
		}
	}

	for (res = res0; res; res = res->ai_next) {
		s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
		if (s == -1)
			continue;

		switch (res->ai_family) {
		case AF_INET:
			SA4(res->ai_addr)->sin_port = service;
			if (conf.c_syncsrcaddr != NULL) {
				laddrstr = conf.c_syncsrcaddr;
			} else {
				laddrstr = "0.0.0.0";
				}
			break;
#ifdef AF_INET6
		case AF_INET6:
			SA6(res->ai_addr)->sin6_port = service;
			laddrstr = "::";
			break;
#endif
		default:
			mg_log(LOG_ERR, "cannot sync, unknown address family");
			close(s);
			s = -1;
			continue;
		}
		laddrlen = sizeof(laddr);
		if (ipfromstring(laddrstr, SA(&laddr), &laddrlen,
		    res->ai_family) == 1 &&
		    bind(s, SA(&laddr), laddrlen) == 0 &&
		    connect(s, res->ai_addr, res->ai_addrlen) == 0)
			break;
		close(s);
		s = -1;
	}
	freeaddrinfo(res0);
	if (s < 0) {
		mg_log(LOG_ERR,
		    "cannot sync with peer %s: %s (%d entries queued)",
		    peer->p_name, strerror(errno), peer->p_qlen);
		return -1;
	}
#else
	raddrlen = sizeof(raddr);
	if (ipfromstring(peer->p_name, SA(&raddr), &raddrlen,
	    AF_UNSPEC) != 1) {
		mg_log(LOG_ERR, "cannot sync, invalid address");
		return -1;
	}

	if (local_addr(SA(&raddr), raddrlen)) {
		peer->p_flags |= P_LOCAL;
		return -1;
	}

	switch (SA(&raddr)->sa_family) {
	case AF_INET:
		SA4(&raddr)->sin_port = service;
		if (conf.c_syncsrcaddr != NULL) {
			laddrstr = conf.c_syncsrcaddr;
		} else {
			laddrstr = "0.0.0.0";
			}
		break;
#ifdef AF_INET6
	case AF_INET6:
		SA6(&raddr)->sin6_port = service;
		laddrstr = "::";
		break;
#endif
	default:
		mg_log(LOG_ERR, "cannot sync, unknown address family");
		return -1;
	}

	if ((pe = getprotobyname("tcp")) == NULL)
		proto = 6;
	else
		proto = pe->p_proto;

	if ((s = socket(SA(&raddr)->sa_family, SOCK_STREAM, proto)) == -1) {
		mg_log(LOG_ERR, "cannot sync with peer %s, "
		    "socket failed: %s (%d entries queued)", 
		    peer->p_name, strerror(errno), peer->p_qlen);
		return -1;
	}

	laddrlen = sizeof(laddr);
	if (ipfromstring(laddrstr, SA(&laddr), &laddrlen,
	    SA(&raddr)->sa_family) != 1) {
		mg_log(LOG_ERR, "cannot sync, invalid address");
		close(s);
		return -1;
	}

	if (bind(s, SA(&laddr), laddrlen) != 0) {
		mg_log(LOG_ERR, "cannot sync with peer %s, "
		    "bind failed: %s (%d entries queued)",
		    peer->p_name, strerror(errno), peer->p_qlen);
		close(s);
		return -1;
	}

	if (connect(s, SA(&raddr), raddrlen) != 0) {
		mg_log(LOG_ERR, "cannot sync with peer %s, "
		    "connect failed: %s (%d entries queued)", 
		    peer->p_name, strerror(errno), peer->p_qlen);
		close(s);
		return -1;
	}
#endif

	param = O_NONBLOCK;
	if (fcntl(s, F_SETFL, param) != 0) {
		mg_log(LOG_ERR, "cannot set non blocking I/O with %s: %s",
		    peer->p_name, strerror(errno));
	}

	if ((stream = fdopen(s, "w+")) == NULL) {
		mg_log(LOG_ERR, "cannot sync with peer %s, "
		    "fdopen failed: %s (%d entries queued)", 
		    peer->p_name, strerror(errno), peer->p_qlen);
		close(s);
		return -1;
	}

	if (setvbuf(stream, NULL, _IOLBF, 0) != 0)
		mg_log(LOG_ERR, "cannot set line buffering with peer %s: %s", 
		    peer->p_name, strerror(errno));

	sync_waitdata(s);	
	if (fgets(line, LINELEN, stream) == NULL) {
		mg_log(LOG_ERR, "Lost connexion with peer %s: "
		    "%s (%d entries queued)", 
		    peer->p_name, strerror(errno), peer->p_qlen);
		goto bad;
	}

	/*
	 * On some systems, opening a stream on a socket introduce
	 * weird behavior: the in and out buffers get mixed up. 
	 * By calling fflush() after each read operation, we fix that
	 */
	fflush(stream);

	if ((replystr = strtok_r(line, sep, &cookie)) == NULL) {
		mg_log(LOG_ERR, "Unexpected reply \"%s\" from peer %s "
		    "closing connexion (%d entries queued)", 
		    line, peer->p_name, peer->p_qlen);
		goto bad;
	}

	replycode = atoi(replystr);
	if (replycode != 200) {
		mg_log(LOG_ERR, "Unexpected reply \"%s\" from peer %s "
		    "closing connexion (%d entries queued)", 
		    line, peer->p_name, peer->p_qlen);
		goto bad;
	}

	if ((peer->p_vers = select_protocol(peer, s, stream)) == 0)
		goto bad;	

	mg_log(LOG_INFO, "Connection to %s established, protocol version %d", 
	    peer->p_name, peer->p_vers);
	peer->p_stream = stream;
	peer->p_socket = s;

	return 0;

bad:
	fclose(stream);
	peer->p_stream = NULL;

	return -1;
}

void
sync_master_restart(void) {
	pthread_t tid;
	int empty;
	int error;

	PEER_RDLOCK;
	empty = LIST_EMPTY(&peer_head);
	PEER_UNLOCK;

	if (empty || sync_master4.runs || sync_master6.runs)
		return;

	if (conf.c_syncaddr != NULL) {
		if (strchr(conf.c_syncaddr, ':'))
		    sync_listen(conf.c_syncaddr, conf.c_syncport,
				&sync_master6);
		else
		    sync_listen(conf.c_syncaddr, conf.c_syncport,
				&sync_master4);
	} else {

#ifdef AF_INET6
		sync_listen("::", conf.c_syncport, &sync_master6);
#endif
		sync_listen("0.0.0.0", conf.c_syncport, &sync_master4);
	}


	if (!sync_master4.runs && !sync_master6.runs) {
		mg_log(LOG_ERR, "cannot start MX sync, socket failed: %s",
		    strerror(errno));
		exit(EX_OSERR);
	}
	if (sync_master6.runs) {
		if ((error = pthread_create(&tid, NULL, sync_master,
		    (void *)&sync_master6)) != 0) {
			mg_log(LOG_ERR, 
			    "Cannot run MX sync thread for IPv6: %s",
			    strerror(error));
			exit(EX_OSERR);
		}
		if ((error = pthread_detach(tid)) != 0) {
			mg_log(LOG_ERR, 
			    "pthread_detach failed for IPv6 MX sync: %s",
			    strerror(error));
			exit(EX_OSERR);
		}
	}
	if (sync_master4.runs) {
		if ((error = pthread_create(&tid, NULL, sync_master,
		    (void *)&sync_master4)) != 0) {
			mg_log(LOG_ERR, 
			    "Cannot run MX sync thread for IPv4: %s",
			    strerror(error));
			exit(EX_OSERR);
		}
		if ((error = pthread_detach(tid)) != 0) {
			mg_log(LOG_ERR, 
			    "pthread_detach failed for IPv4 MX sync: %s",
			    strerror(error));
			exit(EX_OSERR);
		}
	}
}

void *
sync_master(arg)
	void *arg;
{
	struct sync_master_sock *sms = arg;

	for (;;) {
		sockaddr_t raddr;
		socklen_t raddrlen;
		int fd;
		FILE *stream;
		pthread_t tid;
		struct peer *peer;
		char peerstr[IPADDRSTRLEN];
		int error;

		bzero((void *)&raddr, sizeof(raddr));
		raddrlen = sizeof(raddr);
		if ((fd = accept(sms->sock, SA(&raddr), &raddrlen)) == -1) {
			mg_log(LOG_ERR, "incoming connexion "
			    "failed: %s", strerror(errno));

			if (errno != ECONNABORTED)
				exit(EX_OSERR);
			continue;
		}
		unmappedaddr(SA(&raddr), &raddrlen);

		iptostring(SA(&raddr), raddrlen, peerstr, sizeof(peerstr));
		mg_log(LOG_INFO, "Incoming MX sync connexion from %s", 
		    peerstr);

		if ((stream = fdopen(fd, "w+")) == NULL) {
			mg_log(LOG_ERR, 
			    "incoming connexion from %s failed, "
			    "fdopen fail: %s", peerstr, strerror(errno));
			close(fd);
			exit(EX_OSERR);
		}

		if (setvbuf(stream, NULL, _IOLBF, 0) != 0)
			mg_log(LOG_ERR, "cannot set line buffering: %s", 
			    strerror(errno));	
		
		/*
		 * Check that the orginator IP is one of our peers
		 */
		PEER_RDLOCK;

		if (LIST_EMPTY(&peer_head)) {
			fprintf(stream, "105 No more peers, shutting down!\n");

			PEER_UNLOCK;
			fclose(stream);
			close(sms->sock);
			sms->sock = -1;
			sms->runs = 0;
			return NULL;
		}
			
		LIST_FOREACH(peer, &peer_head, p_list) {
#ifdef HAVE_GETADDRINFO
			struct addrinfo hints, *res0, *res;
			int err;
			int match = 0;

			bzero(&hints, sizeof(hints));
			hints.ai_flags = AI_PASSIVE;
			hints.ai_family = AF_UNSPEC;
			hints.ai_socktype = SOCK_STREAM;
			err = getaddrinfo(peer->p_name, "0", &hints, &res0);
			if (err != 0) {
				mg_log(LOG_ERR, "cannot resolve %s: %s",
				    peer->p_name, gai_strerror(err));
				continue;
			}
			for (res = res0; res; res = res->ai_next) {
				if (ip_equal(SA(&raddr), res->ai_addr)) {
					match = 1;
					break;
				}
			}
			freeaddrinfo(res0);
			if (match)
				break;
#else
			sockaddr_t addr;
			socklen_t addrlen;

			addrlen = sizeof(addr);
			if (ipfromstring(peer->p_name, SA(&addr), &addrlen,
			     AF_UNSPEC) != 1) {
				mg_log(LOG_ERR, "cannot resolve %s",
				    peer->p_name);
				continue;
			}
			if (ip_equal(SA(&raddr), SA(&addr)))
				break;
#endif
		}

		PEER_UNLOCK;

		if (peer == NULL) {
			mg_log(LOG_INFO, "Remote host %s is not a peer MX", 
			    peerstr);
			fprintf(stream, 
			    "106 You have no permission to talk, go away!\n");
			fclose(stream);
			continue;
		}

		if ((error = pthread_create(&tid, NULL, 
		    (void *(*)(void *))sync_server, (void *)stream)) != 0) {
			mg_log(LOG_ERR, "incoming connexion from %s failed, "
			    "pthread_create failed: %s", 
			    peerstr, strerror(error));
			fclose(stream);
			continue;
		}
		if ((error = pthread_detach(tid)) != 0) {
			mg_log(LOG_ERR, "incoming connexion from %s failed, "
			    "pthread_detach failed: %s",
			    peerstr, strerror(error));
			exit(EX_OSERR);
		}
	}

	/* NOTREACHED */
	mg_log(LOG_ERR, "sync_master quitted unexpectedly");
	return NULL;
}

static void
sync_listen(addr, port, sms)
        char *addr, *port;
	struct sync_master_sock *sms;
{
	struct protoent *pe;
	struct servent *se;
	int proto;
	sockaddr_t laddr;
	socklen_t laddrlen;
	int service;
	int optval;
	int s;

	sms->runs = 1;
	laddrlen = sizeof(laddr);
	if (ipfromstring(addr, SA(&laddr), &laddrlen, AF_UNSPEC) != 1) {
		sms->runs = 0;
		return;
	}

	if ((pe = getprotobyname("tcp")) == NULL)
		proto = 6;
	else
		proto = pe->p_proto;

	if (port != NULL)
		service = htons(atoi(port));
	else {
		if ((se = getservbyname(MXGLSYNC_NAME, "tcp")) == NULL)
		    service = htons(atoi(MXGLSYNC_PORT));
		else
		    service = se->s_port;
	}

	switch (SA(&laddr)->sa_family) {
	case AF_INET:
		SA4(&laddr)->sin_port = service;
		break;
#ifdef AF_INET6
	case AF_INET6:
		SA6(&laddr)->sin6_port = service;
		break;
#endif
	default:
		sms->runs = 0;
		return;
	}

	if ((s = socket(SA(&laddr)->sa_family, SOCK_STREAM, proto)) == -1) {
		sms->runs = 0;
		return;
	}

	optval = 1;
	if ((setsockopt(s, SOL_SOCKET, SO_REUSEADDR,
	    &optval, sizeof(optval))) != 0) {
		mg_log(LOG_ERR, "cannot set SO_REUSEADDR: %s",
		    strerror(errno));
	}

	optval = 1;
	if ((setsockopt(s, SOL_SOCKET, SO_KEEPALIVE,
	    &optval, sizeof(optval))) != 0) {
		mg_log(LOG_ERR, "cannot set SO_KEEPALIVE: %s",
		    strerror(errno));
	}

#ifdef IPV6_V6ONLY
	if (SA(&laddr)->sa_family == AF_INET6) {
		optval = 1;
		if ((setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY,
		    &optval, sizeof(optval))) != 0) {
			mg_log(LOG_ERR, "cannot set IPV6_V6ONLY: %s",
			    strerror(errno));
		}
	}
#endif

	if (bind(s, SA(&laddr), laddrlen) != 0) {
		mg_log(LOG_ERR, "cannot start MX sync, bind failed: %s",
		    strerror(errno));
		sms->runs = 0;
		close(s);
		return;
	}

	if (listen(s, MXGLSYNC_BACKLOG) != 0) {
		mg_log(LOG_ERR, "cannot start MX sync, listen failed: %s",
		    strerror(errno));
		sms->runs = 0;
		close(s);
		return;
	}

	sms->sock = s;
	return;
}

void
sync_server(arg) 
	void *arg;
{
	FILE *stream = arg;
	char sep[] = " \n\t\r";
	char *cmd;
	char *keyword;
	char *addrstr;
	char *from;
	char *rcpt;
	char from_clean[ADDRLEN + 1];
	char rcpt_clean[ADDRLEN + 1];
	char *datestr;
	char *awstr;
	char *cookie;
	char line[LINELEN + 1];
	peer_sync_t action;
	sockaddr_t addr;
	socklen_t addrlen;
	time_t date;
	time_t aw = time(NULL) + conf.c_autowhite_validity;

	fprintf(stream, "200 Yeah, what do you want?\n");
	fflush(stream);

	for (;;) {
		if ((fgets(line, LINELEN, stream)) == NULL)
			break;

		/*
		 * On some systems, opening a stream on a socket introduce
		 * weird behavior: the in and out buffers get mixed up. 
		 * By calling fflush() after each read operation, we fix that
		 */
		fflush(stream);

		/*
		 * Get the command { quit | help | add | del | del2 | flush }
		 */
		cookie = NULL;
		if ((cmd = strtok_r(line, sep, &cookie)) == NULL) {
			fprintf(stream, "101 No command\n");
			fflush(stream);
			continue;
		}

		if (strncmp(cmd, "quit", CMDLEN) == 0) {
			break;
		} else if ((strncmp(cmd, "help", CMDLEN)) == 0) {
			sync_help(stream);
			continue;
		} else if ((strncmp(cmd, "vers3", CMDLEN)) == 0) {
			sync_vers(stream, 3);
			continue;
		} else if ((strncmp(cmd, "vers2", CMDLEN)) == 0) {
			sync_vers(stream, 2);
			continue;
		} else if ((strncmp(cmd, "add", CMDLEN)) == 0) {
			action = PS_CREATE;
		} else if ((strncmp(cmd, "del2", CMDLEN)) == 0) {
			action = PS_DELETE;
			aw = -1;
		} else if ((strncmp(cmd, "del", CMDLEN)) == 0) {
			action = PS_DELETE;
		} else if ((strncmp(cmd, "flush", CMDLEN)) == 0) {
			action = PS_FLUSH;
		} else {
			fprintf(stream, "102 Invalid command \"%s\"\n", cmd);
			fflush(stream);
			continue;
		}

		/*
		 * get { "addr" ip_address }
		 */
		if ((keyword = strtok_r(NULL, sep, &cookie)) == NULL) {
			fprintf(stream, "103 Incomplete command\n");
			fflush(stream);
			continue;
		}

		if (strncmp(keyword, "addr", CMDLEN) != 0) {
			fprintf(stream, 
			    "104 Unexpected keyword \"%s\"\n", keyword);
			fflush(stream);
			continue;
		}

		if ((addrstr = strtok_r(NULL, sep, &cookie)) == NULL) {
			fprintf(stream, "103 Incomplete command\n");
			fflush(stream);
			continue;
		}
			
		addrlen = sizeof(addr);
		if (ipfromstring(addrstr, SA(&addr), &addrlen,
		    AF_UNSPEC) != 1) {
			fprintf(stream, "107 Invalid IP address\n");
			fflush(stream);
			continue;
		}	

		if (action == PS_FLUSH) {
			from = NULL;
			rcpt = NULL;
			date = 0;
			goto eol;
		}

		/*
		 * get { "from" email_address }
		 */
		if ((keyword = strtok_r(NULL, sep, &cookie)) == NULL) {
			fprintf(stream, "103 Incomplete command\n");
			fflush(stream);
			continue;
		}

		if (strncmp(keyword, "from", CMDLEN) != 0) {
			fprintf(stream, 
			    "104 Unexpected keyword \"%s\"\n", keyword);
			fflush(stream);
			continue;
		}

		if ((from = strtok_r(NULL, sep, &cookie)) == NULL) {
			fprintf(stream, "103 Incomplete command\n");
			fflush(stream);
			continue;
		}
		(void)strncpy_rmsp(from_clean, from, ADDRLEN);
		from = from_clean;

		/*
		 * get { "rcpt" email_address }
		 */
		if ((keyword = strtok_r(NULL, sep, &cookie)) == NULL) {
			fprintf(stream, "103 Incomplete command\n");
			fflush(stream);
			continue;
		}

		if (strncmp(keyword, "rcpt", CMDLEN) != 0) {
			fprintf(stream, 
			    "104 Unexpected keyword \"%s\"\n", keyword);
			fflush(stream);
			continue;
		}

		if ((rcpt = strtok_r(NULL, sep, &cookie)) == NULL) {
			fprintf(stream, "103 Incomplete command\n");
			fflush(stream);
			continue;
		}
		(void)strncpy_rmsp(rcpt_clean, rcpt, ADDRLEN);
		rcpt = rcpt_clean;

		/*
		 * get { "date" valid_date }
		 */
		if ((keyword = strtok_r(NULL, sep, &cookie)) == NULL) {
			fprintf(stream, "103 Incomplete command\n");
			fflush(stream);
			continue;
		}

		if (strncmp(keyword, "date", CMDLEN) != 0) {
			fprintf(stream, 
			    "104 Unexpected keyword \"%s\"\n", keyword);
			fflush(stream);
			continue;
		}

		if ((datestr = strtok_r(NULL, sep, &cookie)) == NULL) {
			fprintf(stream, "103 Incomplete command\n");
			fflush(stream);
			continue;
		}

		date = atoi(datestr);

		if (aw == -1) {
			/*
			 * get { "aw" valid_date }
			 */
			if ((keyword = strtok_r(NULL, sep, &cookie)) == NULL) {
				fprintf(stream, "103 Incomplete command\n");
				fflush(stream);
				continue;
			}

			if (strncmp(keyword, "aw", CMDLEN) != 0) {
				fprintf(stream, 
				    "104 Unexpected keyword \"%s\"\n", keyword);
				fflush(stream);
				continue;
			}

			if ((awstr = strtok_r(NULL, sep, &cookie)) == NULL) {
				fprintf(stream, "103 Incomplete command\n");
				fflush(stream);
				continue;
			}

			aw = atoi(awstr);
		}

		/* 
		 * Check nothing remains
		 */
eol:
		if ((keyword = strtok_r(NULL, sep, &cookie)) != NULL) {	
			fprintf(stream, 
			    "104 Unexpected keyword \"%s\"\n", keyword);
			fflush(stream);
			continue;
		}

		fprintf(stream, "201 All right, I'll do that\n");
		fflush(stream);

		if (action == PS_CREATE) {
			PENDING_WRLOCK;
			/* delay = -1 means unused: we supply the date */
			pending_get(SA(&addr), addrlen, from, rcpt, date);
			PENDING_UNLOCK;
		}
		if (action == PS_DELETE) {
			pending_del(SA(&addr), addrlen, from, rcpt, date);
			autowhite_add(SA(&addr), addrlen, from, 
			    rcpt, &aw, "(mxsync)");
		}
		if (action == PS_FLUSH) {
			pending_del_addr(SA(&addr), addrlen, NULL, 0);
			autowhite_del_addr(SA(&addr), addrlen);
		}

		/* Flush modifications to disk */
		dump_flush();
	}

	fprintf(stream, "202 Good bye\n");
	fclose(stream);

	return;

}

static void
sync_vers(stream, vers)
	FILE *stream;
	int vers;
{
	if (vers <= SYNC_PROTO_CURRENT) {
		fprintf(stream, 
		    "%d Yes, I speak version %d, what do you think?\n",
		    800 + vers, vers);
	} else {
		fprintf(stream, "108 Invalid vers%d command\n", vers);
	}
	fflush(stream);
	return;
}

void
sync_help(stream)
	FILE *stream;
{
	fprintf(stream, "203 Help? Sure, we have help here:\n");
	fprintf(stream, "203 \n");
	fprintf(stream, "203 Available commands are:\n");
	fprintf(stream, "203 help  -- displays this message\n");
	fprintf(stream, "203 quit  -- terminate connexion\n");
	fprintf(stream, "203 vers2 -- speak version 2 protocol\n");
	fprintf(stream, "203 vers3 -- speak version 3 protocol\n");
	fprintf(stream, 
	    "203 add addr <ip> from <email> rcpt <email> date <time>  "
	    "-- add en entry\n");
	fprintf(stream, 
	    "203 del addr <ip> from <email> rcpt <email> date <time>  "
	    "-- remove en entry\n");
	fprintf(stream, 
	    "203 del2 addr <ip> from <email> rcpt <email> date <time> "
	    "aw <time> -- remove en entry, adding it to autowhite with "
	    "given delay (version 2 only)\n");
	fprintf(stream, 
	    "203 flush addr <ip> -- remove anything about an ip "
	    " (version 3 only)\n");
	fflush(stream);

	return;
}

#define COM_TIMEOUT 3
int
sync_waitdata(fd)
	int fd;
{
	fd_set fdr, fde;
	struct timeval timeout;
	int retval;

	FD_ZERO(&fdr);
	FD_SET(fd, &fdr);

	FD_ZERO(&fde);
	FD_SET(fd, &fde);

	timeout.tv_sec = COM_TIMEOUT;
	timeout.tv_usec = 0;

	retval = select(fd + 1, &fdr, NULL, &fde, &timeout); 

	return retval;
}


void
sync_queue(peer, type, pending, autowhite)/* peer list must be read-locked */
	struct peer *peer;
	peer_sync_t type;
	struct pending *pending;
	time_t autowhite;
{
	int error;
	struct sync *sync;

	if (peer->p_flags & P_LOCAL)
		return;

	if ((sync = malloc(sizeof(*sync))) == NULL) {
		mg_log(LOG_ERR, "cannot allocate memory: %s", 
		    strerror(errno)); 
		exit(EX_OSERR);
	}

	sync->s_peer = peer;
	sync->s_type = type;
	sync->s_autowhite = autowhite;
	sync->s_pending = pending_ref(pending);

	/*
	 * If the queue has overflown, try to wakeup sync_sender to
	 * void it, but do not accept new entries anymore.
	 */
	if (!sync_queue_poke(peer, sync)) {
		mg_log(LOG_ERR, "peer %s queue overflow (%d entries), "
		    "discarding new entry", peer->p_name, peer->p_qlen);
		sync_free(sync);
	}

	if ((error = pthread_cond_signal(&sync_sleepflag)) != 0) {
		mg_log(LOG_ERR, 
		    "cannot wakeup sync_sender: %s", strerror(error));
		exit(EX_SOFTWARE);
	}
	return;
}

void
sync_free(sync)
	struct sync *sync;
{
	pending_free(sync->s_pending);
	free(sync);
}

void
sync_sender_start(void) {
	pthread_t tid;
	int error;

	if ((error = pthread_create(&tid, NULL, 
	    (void *(*)(void *))sync_sender, NULL)) != 0) {
		mg_log(LOG_ERR, "pthread_create failed: %s", strerror(error));
		exit(EX_OSERR);
	}
	if ((error = pthread_detach(tid)) != 0) {
		mg_log(LOG_ERR, "pthread_detach failed: %s", strerror(error));
		exit(EX_OSERR);
	}
	return;
}

/* ARGSUSED0 */
void
sync_sender(dontcare)
	void *dontcare;
{
	int done = 0;
	struct peer *peer;
	struct sync *sync;
	pthread_mutex_t mutex;
	struct timeval tv1, tv2, tv3;
	int error;

	if ((error = pthread_mutex_init(&mutex, NULL)) != 0) {
		mg_log(LOG_ERR, "pthread_mutex_init failed: %s", 
		    strerror(error));
		exit(EX_OSERR);
	}

	if ((error = pthread_mutex_lock(&mutex)) != 0) {
		mg_log(LOG_ERR, "pthread_mutex_lock failed: %s", 
		    strerror(error));
		exit(EX_OSERR);
	}

	for (;;) {
		if ((error = pthread_cond_wait(&sync_sleepflag, &mutex)) != 0)
			mg_log(LOG_ERR, "pthread_cond_wait failed: %s", 
			    strerror(error));
		if (conf.c_debug) {
			mg_log(LOG_DEBUG, "sync_sender running");
			gettimeofday(&tv1, NULL);
		}
		done = 0;

		PEER_RDLOCK;
		if (LIST_EMPTY(&peer_head))
			goto out;
			
		LIST_FOREACH(peer, &peer_head, p_list) {
			/* Don't try to sync with ourselves */
			if (peer->p_flags & P_LOCAL)
				continue;

			while ((sync = sync_queue_peek(peer)) != NULL ) {

				if (sync_send(sync->s_peer, sync->s_type, 
				    sync->s_pending, sync->s_autowhite) != 0) {
					if (!sync_queue_poke(peer, sync))
						sync_free(sync);

					break;
				}

				sync_free(sync);

				done++;
			}
		}
out:
		PEER_UNLOCK;

		if (conf.c_debug) {
			gettimeofday(&tv2, NULL);
			timersub(&tv2, &tv1, &tv3);
			mg_log(LOG_DEBUG, "sync_sender sleeping, "
			    "done %d entries in %ld.%06lds", done,
			    tv3.tv_sec, tv3.tv_usec);
		}
	}
}


static int
local_addr(sa, salen)
	const struct sockaddr *sa;
	const socklen_t salen;
{
	sockaddr_t addr;
	int	sfd, islocal;

	memcpy(&addr, sa, salen);
	switch(sa->sa_family) {
	case AF_INET:
		SA4(&addr)->sin_port = 0;
		break;

#ifdef AF_INET6
	case AF_INET6:
		SA6(&addr)->sin6_port = 0;
		break;
#endif

	default:
		mg_log(LOG_ERR, "local_addr: unsupported AF %d",
		    sa->sa_family);
		return -1;
		break;
	}

	if ((sfd = socket(sa->sa_family, SOCK_DGRAM, IPPROTO_UDP)) < 0) {
		mg_log(LOG_ERR, "local_addr: socket failed: %s",
		    strerror(errno));
		return -1;
	}

	if (bind(sfd, sa, salen) == -1) {
		if (errno != EADDRNOTAVAIL && 
#ifdef __FreeBSD__
		    errno != EINVAL &&
#endif
		    1) {
			mg_log(LOG_ERR, "local_addr: bind failed: %s",
			    strerror(errno));
			islocal = -1;
		} else {
			islocal = 0;
		}
	} else {
		islocal = 1;
	}

	close(sfd);

	return islocal;
}

static int 
select_protocol(peer, s, stream)
	struct peer *peer;
	int s;
	FILE *stream;
{
	char line[LINELEN + 1];
	int vers;
	char *replystr;
	int replycode;
	char sep[] = " \n\t\r";
	char *cookie = NULL;

	for (vers = SYNC_PROTO_CURRENT; vers > 1; vers--) {
		fprintf(stream, "vers%d\n", vers);

		fflush(stream);

		sync_waitdata(s);	
		if (fgets(line, LINELEN, stream) == NULL) {
			mg_log(LOG_ERR, "Lost connexion with peer %s: "
			    "%s (%d entries queued)", 
			    peer->p_name, strerror(errno), peer->p_qlen);
			return 0;
		}

		if ((replystr = strtok_r(line, sep, &cookie)) == NULL) {
			mg_log(LOG_ERR, "Unexpected reply \"%s\" from peer %s "
			    "closing connexion (%d entries queued)", 
			    line, peer->p_name, peer->p_qlen);
			return 0;
		}

		fflush(stream);

		replycode = atoi(replystr);
		if (replycode != 800 + vers) {
			mg_log(LOG_DEBUG, 
			    "peer %s answered code %d to command vers%d",
			    peer->p_name, replycode, vers);
		} else {
			return vers;
		}
	}

	return 1;
}

void
peer_flush(pending)
	struct pending *pending;
{
	struct peer *peer;

	PEER_RDLOCK;
	if (LIST_EMPTY(&peer_head))
		goto out;

	LIST_FOREACH(peer, &peer_head, p_list) {
		/* Unsupported before verseion 3 */
		if (peer->p_vers < 3)
			continue;
		sync_queue(peer, PS_FLUSH, pending, -1); /* -1: unused */
	}

out:
	PEER_UNLOCK;
	
	return;
}