File: p_ce.c

package info (click to toggle)
freediameter 1.6.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 7,072 kB
  • sloc: ansic: 75,214; yacc: 3,154; lex: 1,939; cpp: 1,583; xml: 795; php: 486; makefile: 463; python: 443; sql: 337; sh: 243; perl: 105
file content (1149 lines) | stat: -rw-r--r-- 43,000 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
/*********************************************************************************************************
* Software License Agreement (BSD License)                                                               *
* Author: Sebastien Decugis <sdecugis@freediameter.net>							 *
*													 *
* Copyright (c) 2023, WIDE Project and NICT								 *
* All rights reserved.											 *
* 													 *
* Redistribution and use of this software in source and binary forms, with or without modification, are  *
* permitted provided that the following conditions are met:						 *
* 													 *
* * Redistributions of source code must retain the above 						 *
*   copyright notice, this list of conditions and the 							 *
*   following disclaimer.										 *
*    													 *
* * 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.								 *
* 													 *
* * Neither the name of the WIDE Project or NICT nor the 						 *
*   names of its contributors may be used to endorse or 						 *
*   promote products derived from this software without 						 *
*   specific prior written permission of WIDE Project and 						 *
*   NICT.												 *
* 													 *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT OWNER OR CONTRIBUTORS 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 "fdcore-internal.h"

/* This file contains code to handle Capabilities Exchange messages (CER and CEA) and election process */

/* Save a connection as peer's principal */
static int set_peer_cnx(struct fd_peer * peer, struct cnxctx **cnx)
{
	CHECK_PARAMS( peer->p_cnxctx == NULL );
	
	/* Save the connection in peer */
	peer->p_cnxctx = *cnx;
	*cnx = NULL;
	
	/* Set the events to be sent to the PSM */
	CHECK_FCT( fd_cnx_recv_setaltfifo(peer->p_cnxctx, peer->p_events) );
	
	/* Read the credentials if possible */
	if (fd_cnx_getTLS(peer->p_cnxctx)) {
		CHECK_FCT( fd_cnx_getcred(peer->p_cnxctx, &peer->p_hdr.info.runtime.pir_cert_list, &peer->p_hdr.info.runtime.pir_cert_list_size) );
	}
	
	/* Read the endpoints, maybe used to reconnect to the peer later */
	CHECK_FCT( fd_cnx_getremoteeps(peer->p_cnxctx, &peer->p_hdr.info.pi_endpoints) );
	
	/* Read the protocol */
	peer->p_hdr.info.runtime.pir_proto = fd_cnx_getproto(peer->p_cnxctx);
	
	return 0;
}

/* Delete the peer connection, and cleanup associated information */
void fd_p_ce_clear_cnx(struct fd_peer * peer, struct cnxctx ** cnx_kept)
{
	peer->p_hdr.info.runtime.pir_cert_list = NULL;
	peer->p_hdr.info.runtime.pir_cert_list_size = 0;
	peer->p_hdr.info.runtime.pir_proto = 0;
	
	if (peer->p_cnxctx) {
		if (cnx_kept != NULL) {
			*cnx_kept = peer->p_cnxctx;
		} else {
			fd_cnx_destroy(peer->p_cnxctx);
		}
		peer->p_cnxctx = NULL;
	}
}

/* Election: compare the Diameter Ids by lexical order, return true if the election is won */
static __inline__ int election_result(struct fd_peer * peer)
{
	int ret = (strcasecmp(peer->p_hdr.info.pi_diamid, fd_g_config->cnf_diamid) < 0);
	if (ret) {
		TRACE_DEBUG(INFO, "Election WON against peer '%s'", peer->p_hdr.info.pi_diamid);
	} else {
		TRACE_DEBUG(INFO, "Election LOST against peer '%s'", peer->p_hdr.info.pi_diamid);
	}
	return ret;
}

/* Add AVPs about local information in a CER or CEA */
static int add_CE_info(struct msg *msg, struct cnxctx * cnx, int isi_tls, int isi_none)
{
	struct dict_object * dictobj = NULL;
	struct avp * avp = NULL;
	union avp_value val;
	struct fd_list *li;
	
	/* Add the Origin-* AVPs */
	CHECK_FCT( fd_msg_add_origin ( msg, 1 ) );
	
	/* Find the model for Host-IP-Address AVP */
	CHECK_FCT(  fd_dict_search( fd_g_config->cnf_dict, DICT_AVP, AVP_BY_NAME, "Host-IP-Address", &dictobj, ENOENT )  );
		
	/* Add the AVP(s) -- not sure what is the purpose... We could probably only add the primary one ? */
	for (li = fd_g_config->cnf_endpoints.next; li != &fd_g_config->cnf_endpoints; li = li->next) {
		struct fd_endpoint * ep = (struct fd_endpoint *)li;
		CHECK_FCT( fd_msg_avp_new ( dictobj, 0, &avp ) );
		CHECK_FCT( fd_msg_avp_value_encode ( &ep->ss, avp ) );
		CHECK_FCT( fd_msg_avp_add( msg, MSG_BRW_LAST_CHILD, avp ) );
	}
	
	/* Vendor-Id, Product-Name, and Firmware-Revision AVPs */
	CHECK_FCT( fd_dict_search( fd_g_config->cnf_dict, DICT_AVP, AVP_BY_NAME, "Vendor-Id", &dictobj, ENOENT )  );
	CHECK_FCT( fd_msg_avp_new ( dictobj, 0, &avp ) );
	val.u32 = MY_VENDOR_ID;
	CHECK_FCT( fd_msg_avp_setvalue( avp, &val ) );
	CHECK_FCT( fd_msg_avp_add( msg, MSG_BRW_LAST_CHILD, avp ) );
	
	CHECK_FCT( fd_dict_search( fd_g_config->cnf_dict, DICT_AVP, AVP_BY_NAME, "Product-Name", &dictobj, ENOENT )  );
	CHECK_FCT( fd_msg_avp_new ( dictobj, 0, &avp ) );
	val.os.data = (unsigned char *)FD_PROJECT_NAME;
	val.os.len = strlen(FD_PROJECT_NAME);
	CHECK_FCT( fd_msg_avp_setvalue( avp, &val ) );
	CHECK_FCT( fd_msg_avp_add( msg, MSG_BRW_LAST_CHILD, avp ) );
	
	CHECK_FCT( fd_dict_search( fd_g_config->cnf_dict, DICT_AVP, AVP_BY_NAME, "Firmware-Revision", &dictobj, ENOENT )  );
	CHECK_FCT( fd_msg_avp_new ( dictobj, 0, &avp ) );
	val.u32 = (uint32_t)(FD_PROJECT_VERSION_MAJOR * 10000 + FD_PROJECT_VERSION_MINOR * 100 + FD_PROJECT_VERSION_REV);
	CHECK_FCT( fd_msg_avp_setvalue( avp, &val ) );
	CHECK_FCT( fd_msg_avp_add( msg, MSG_BRW_LAST_CHILD, avp ) );
	
	
	/* Add the Inband-Security-Id AVP if needed */
	if (isi_tls || isi_none) {
		CHECK_FCT( fd_dict_search( fd_g_config->cnf_dict, DICT_AVP, AVP_BY_NAME, "Inband-Security-Id", &dictobj, ENOENT )  );
		
		if (isi_none) {
			CHECK_FCT( fd_msg_avp_new ( dictobj, 0, &avp ) );
			val.u32 = ACV_ISI_NO_INBAND_SECURITY;
			CHECK_FCT( fd_msg_avp_setvalue( avp, &val ) );
			CHECK_FCT( fd_msg_avp_add( msg, MSG_BRW_LAST_CHILD, avp ) );
		}
		
		if (isi_tls) {
			CHECK_FCT( fd_msg_avp_new ( dictobj, 0, &avp ) );
			val.u32 = ACV_ISI_TLS;
			CHECK_FCT( fd_msg_avp_setvalue( avp, &val ) );
			CHECK_FCT( fd_msg_avp_add( msg, MSG_BRW_LAST_CHILD, avp ) );
		}
	}
	
	/* List of local applications */
	{
		struct dict_object * dictobj_auth = NULL;
		struct dict_object * dictobj_acct = NULL;
		struct dict_object * dictobj_vid = NULL;
		
		CHECK_FCT( fd_dict_search( fd_g_config->cnf_dict, DICT_AVP, AVP_BY_NAME, "Vendor-Specific-Application-Id", &dictobj, ENOENT )  );
		CHECK_FCT( fd_dict_search( fd_g_config->cnf_dict, DICT_AVP, AVP_BY_NAME, "Vendor-Id", &dictobj_vid, ENOENT )  );
		CHECK_FCT( fd_dict_search( fd_g_config->cnf_dict, DICT_AVP, AVP_BY_NAME, "Auth-Application-Id", &dictobj_auth, ENOENT )  );
		CHECK_FCT( fd_dict_search( fd_g_config->cnf_dict, DICT_AVP, AVP_BY_NAME, "Acct-Application-Id", &dictobj_acct, ENOENT )  );
		
		for (li = fd_g_config->cnf_apps.next; li != &fd_g_config->cnf_apps; li = li->next) {
			struct fd_app * a = (struct fd_app *)(li);

			if (a->flags.auth) {
				CHECK_FCT( fd_msg_avp_new ( dictobj_auth, 0, &avp ) );
				val.u32 = a->appid;
				CHECK_FCT( fd_msg_avp_setvalue( avp, &val ) );
				if (a->vndid != 0) {
					struct avp * avp2 = NULL;
					CHECK_FCT( fd_msg_avp_new ( dictobj, 0, &avp2 ) );
					CHECK_FCT( fd_msg_avp_add( avp2, MSG_BRW_LAST_CHILD, avp ) );
					avp = avp2;
					CHECK_FCT( fd_msg_avp_new ( dictobj_vid, 0, &avp2 ) );
					val.u32 = a->vndid;
					CHECK_FCT( fd_msg_avp_setvalue( avp2, &val ) );
					CHECK_FCT( fd_msg_avp_add( avp, MSG_BRW_LAST_CHILD, avp2 ) );
				}
				CHECK_FCT( fd_msg_avp_add( msg, MSG_BRW_LAST_CHILD, avp ) );
			}
			if (a->flags.acct) {
				CHECK_FCT( fd_msg_avp_new ( dictobj_acct, 0, &avp ) );
				val.u32 = a->appid;
				CHECK_FCT( fd_msg_avp_setvalue( avp, &val ) );
				if (a->vndid != 0) {
					struct avp * avp2 = NULL;
					CHECK_FCT( fd_msg_avp_new ( dictobj, 0, &avp2 ) );
					CHECK_FCT( fd_msg_avp_add( avp2, MSG_BRW_LAST_CHILD, avp ) );
					avp = avp2;
					CHECK_FCT( fd_msg_avp_new ( dictobj_vid, 0, &avp2 ) );
					val.u32 = a->vndid;
					CHECK_FCT( fd_msg_avp_setvalue( avp2, &val ) );
					CHECK_FCT( fd_msg_avp_add( avp, MSG_BRW_LAST_CHILD, avp2 ) );
				}
				CHECK_FCT( fd_msg_avp_add( msg, MSG_BRW_LAST_CHILD, avp ) );
			}
		}
		
		/* do not forget the relay application */
		if (! fd_g_config->cnf_flags.no_fwd) {
			CHECK_FCT( fd_msg_avp_new ( dictobj_auth, 0, &avp ) );
			val.u32 = AI_RELAY;
			CHECK_FCT( fd_msg_avp_setvalue( avp, &val ) );
			CHECK_FCT( fd_msg_avp_add( msg, MSG_BRW_LAST_CHILD, avp ) );
		}
	}
	
	/* Add the list of supported vendors */
	{
		uint32_t * array = fd_dict_get_vendorid_list(fd_g_config->cnf_dict);
		if (array) {
			int i = 0;
			CHECK_FCT( fd_dict_search( fd_g_config->cnf_dict, DICT_AVP, AVP_BY_NAME, "Supported-Vendor-Id", &dictobj, ENOENT )  );
			
			while (array[i] != 0) {
				CHECK_FCT( fd_msg_avp_new ( dictobj, 0, &avp ) );
				val.u32 = array[i];
				CHECK_FCT( fd_msg_avp_setvalue( avp, &val ) );
				CHECK_FCT( fd_msg_avp_add( msg, MSG_BRW_LAST_CHILD, avp ) );
				i++;
			}
			
			free(array);
		}
	}
	
	return 0;
}

/* Remove any information saved from a previous CER/CEA exchange */
static void cleanup_remote_CE_info(struct fd_peer * peer)
{
	/* free linked information */
	free(peer->p_hdr.info.runtime.pir_realm);
	free(peer->p_hdr.info.runtime.pir_prodname);
	while (!FD_IS_LIST_EMPTY(&peer->p_hdr.info.runtime.pir_apps)) {
		struct fd_list * li = peer->p_hdr.info.runtime.pir_apps.next;
		fd_list_unlink(li);
		free(li);
	}
	/* note: pir_cert_list needs not be freed (belongs to gnutls) */
	
	/* cleanup the area */
	memset(&peer->p_hdr.info.runtime, 0, sizeof(peer->p_hdr.info.runtime));
	
	/* reinit the list */
	fd_list_init(&peer->p_hdr.info.runtime.pir_apps, peer);

	/* Remove previously advertised endpoints */
	fd_ep_clearflags( &peer->p_hdr.info.pi_endpoints, EP_FL_ADV );
}

/* Extract information sent by the remote peer and save it in our peer structure */
static int save_remote_CE_info(struct msg * msg, struct fd_peer * peer, struct fd_pei * error, uint32_t *rc)
{
	struct avp * avp = NULL;
	int app_count = 0;
	
	cleanup_remote_CE_info(peer);
	
	CHECK_FCT( fd_msg_browse( msg, MSG_BRW_FIRST_CHILD, &avp, NULL) );
	
	/* Loop on all AVPs and save what we are interested into */
	while (avp) {
		struct avp_hdr * hdr;

		CHECK_FCT(  fd_msg_avp_hdr( avp, &hdr )  );

		if (hdr->avp_flags & AVP_FLAG_VENDOR) {
			/* Ignore all vendor-specific AVPs in CER/CEA because we don't support any currently */
			LOG_A("Ignored a vendor-specific AVP in CER / CEA");
			goto next;
		}

		switch (hdr->avp_code) {
			case AC_RESULT_CODE: /* Result-Code */
				if (hdr->avp_value == NULL) {
					/* This is a sanity check */
					LOG_F("Ignored an AVP (code %x) with unset value in CER/CEA", hdr->avp_code);
					ASSERT(0); /* To check if this really happens, and understand why... */
					goto next;
				}
				
				if (rc)
					*rc = hdr->avp_value->u32;
				break;
		
			case AC_ORIGIN_HOST: /* Origin-Host */
				if (hdr->avp_value == NULL) {
					/* This is a sanity check */
					LOG_F("Ignored an AVP (code %x) with unset value in CER/CEA", hdr->avp_code);
					ASSERT(0); /* To check if this really happens, and understand why... */
					goto next;
				}
				
				/* We check that the value matches what we know, otherwise disconnect the peer */
				if (fd_os_almostcasesrch(hdr->avp_value->os.data, hdr->avp_value->os.len, 
							peer->p_hdr.info.pi_diamid, peer->p_hdr.info.pi_diamidlen, NULL)) {
					TRACE_DEBUG(INFO, "Received a message with Origin-Host set to '%.*s' while expecting '%s'", 
							(int)hdr->avp_value->os.len, hdr->avp_value->os.data, peer->p_hdr.info.pi_diamid);
					error->pei_errcode = "DIAMETER_AVP_NOT_ALLOWED";
					error->pei_message = "Your Origin-Host value does not match my configuration.";
					error->pei_avp = avp;
					return EINVAL;
				}

				break;
		
			case AC_ORIGIN_REALM: /* Origin-Realm */
				if (hdr->avp_value == NULL) {
					/* This is a sanity check */
					LOG_F("Ignored an AVP (code %x) with unset value in CER/CEA", hdr->avp_code);
					ASSERT(0); /* To check if this really happens, and understand why... */
					goto next;
				}
				
				/* In case of multiple AVPs */
				if (peer->p_hdr.info.runtime.pir_realm) {
					TRACE_DEBUG(INFO, "Multiple instances of the Origin-Realm AVP");
					error->pei_errcode = "DIAMETER_AVP_OCCURS_TOO_MANY_TIMES";
					error->pei_message = "I found several Origin-Realm AVPs";
					error->pei_avp = avp;
					return EINVAL;
				}
				
				/* If the octet string contains a \0 */
				if (!fd_os_is_valid_DiameterIdentity(hdr->avp_value->os.data, hdr->avp_value->os.len)) {
					error->pei_errcode = "DIAMETER_INVALID_AVP_VALUE";
					error->pei_message = "Your Origin-Realm contains invalid characters.";
					error->pei_avp = avp;
					return EINVAL;
				}
				
				/* Origin-Realm is empty */
				if (hdr->avp_value->os.len == 0) {
					error->pei_errcode = "DIAMETER_INVALID_AVP_VALUE";
					error->pei_message = "Your Origin-Realm is empty.";
					error->pei_avp = avp;
					return EINVAL;
				}

				/* Save the value */
				CHECK_MALLOC(  peer->p_hdr.info.runtime.pir_realm = os0dup( hdr->avp_value->os.data, hdr->avp_value->os.len )  );
				peer->p_hdr.info.runtime.pir_realmlen = hdr->avp_value->os.len;
				break;

			case AC_HOST_IP_ADDRESS: /* Host-IP-Address */
				if (hdr->avp_value == NULL) {
					/* This is a sanity check */
					LOG_F("Ignored an AVP (code %x) with unset value in CER/CEA", hdr->avp_code);
					ASSERT(0); /* To check if this really happens, and understand why... */
					goto next;
				}
				{
					sSS	ss;

					/* Get the sockaddr value */
					memset(&ss, 0, sizeof(ss));
					CHECK_FCT_DO( fd_msg_avp_value_interpret( avp, &ss),
						{
							/* in case of error, assume the AVP value was wrong */
							error->pei_errcode = "DIAMETER_INVALID_AVP_VALUE";
							error->pei_avp = avp;
							return EINVAL;
						} );

					/* Save this endpoint in the list as advertised */
					CHECK_FCT( fd_ep_add_merge( &peer->p_hdr.info.pi_endpoints, (sSA *)&ss, sizeof(sSS), EP_FL_ADV ) );
				}
				break;

			case AC_VENDOR_ID: /* Vendor-Id */
				if (hdr->avp_value == NULL) {
					/* This is a sanity check */
					LOG_F("Ignored an AVP (code %x) with unset value in CER/CEA", hdr->avp_code);
					ASSERT(0); /* To check if this really happens, and understand why... */
					goto next;
				}
				
				/* In case of multiple AVPs */
				if (peer->p_hdr.info.runtime.pir_vendorid) {
					TRACE_DEBUG(INFO, "Multiple instances of the Vendor-Id AVP");
					error->pei_errcode = "DIAMETER_AVP_OCCURS_TOO_MANY_TIMES";
					error->pei_message = "I found several Vendor-Id AVPs";
					error->pei_avp = avp;
					return EINVAL;
				}
				
				peer->p_hdr.info.runtime.pir_vendorid = hdr->avp_value->u32;
				break;

			case AC_PRODUCT_NAME: /* Product-Name */
				if (hdr->avp_value == NULL) {
					/* This is a sanity check */
					LOG_F("Ignored an AVP (code %x) with unset value in CER/CEA", hdr->avp_code);
					ASSERT(0); /* To check if this really happens, and understand why... */
					goto next;
				}
				
				/* In case of multiple AVPs */
				if (peer->p_hdr.info.runtime.pir_prodname) {
					TRACE_DEBUG(INFO, "Multiple instances of the Product-Name AVP");
					error->pei_errcode = "DIAMETER_AVP_OCCURS_TOO_MANY_TIMES";
					error->pei_message = "I found several Product-Name AVPs";
					error->pei_avp = avp;
					return EINVAL;
				}

				CHECK_MALLOC( peer->p_hdr.info.runtime.pir_prodname = calloc( hdr->avp_value->os.len + 1, 1 )  );
				memcpy(peer->p_hdr.info.runtime.pir_prodname, hdr->avp_value->os.data, hdr->avp_value->os.len);
				break;

			case AC_ORIGIN_STATE_ID: /* Origin-State-Id */
				if (hdr->avp_value == NULL) {
					/* This is a sanity check */
					LOG_F("Ignored an AVP (code %x) with unset value in CER/CEA", hdr->avp_code);
					ASSERT(0); /* To check if this really happens, and understand why... */
					goto next;
				}
				
				/* In case of multiple AVPs */
				if (peer->p_hdr.info.runtime.pir_orstate) {
					TRACE_DEBUG(INFO, "Multiple instances of the Origin-State-Id AVP");
					error->pei_errcode = "DIAMETER_AVP_OCCURS_TOO_MANY_TIMES";
					error->pei_message = "I found several Origin-State-Id AVPs";
					error->pei_avp = avp;
					return EINVAL;
				}
				
				peer->p_hdr.info.runtime.pir_orstate = hdr->avp_value->u32;
				break;

			case AC_SUPPORTED_VENDOR_ID: /* Supported-Vendor-Id */
				if (hdr->avp_value == NULL) {
					/* This is a sanity check */
					LOG_F("Ignored an AVP (code %x) with unset value in CER/CEA", hdr->avp_code);
					ASSERT(0); /* To check if this really happens, and understand why... */
					goto next;
				}
				
				TRACE_DEBUG(FULL, "'%s' claims support for a subset of vendor %d features.", peer->p_hdr.info.pi_diamid, hdr->avp_value->u32);
				/* not that it makes a difference for us... 
				 -- if an application actually needs this info, we could save it somewhere.
				*/
				break;

			case AC_VENDOR_SPECIFIC_APPLICATION_ID: /* Vendor-Specific-Application-Id (grouped)*/
				{
					struct avp * inavp = NULL;
					vendor_id_t vid = 0;
					application_id_t auth_aid = 0;
					application_id_t acct_aid = 0;
					int invalid=0;

					/* get the first child AVP */
					CHECK_FCT(  fd_msg_browse(avp, MSG_BRW_FIRST_CHILD, &inavp, NULL)  );

					while (inavp) {
						struct avp_hdr * inhdr;
						CHECK_FCT(  fd_msg_avp_hdr( inavp, &inhdr )  );

						if (inhdr->avp_flags & AVP_FLAG_VENDOR) {
							LOG_A("Ignored a vendor AVP inside Vendor-Specific-Application-Id AVP");
							goto innext;
						}

						if (inhdr->avp_value == NULL) {
							/* This is a sanity check */
							LOG_F("Ignored an AVP (code %x) with unset value in CER/CEA", hdr->avp_code);
							ASSERT(0); /* To check if this really happens, and understand why... */
							goto innext;
						}
						switch (inhdr->avp_code) {
							case AC_VENDOR_ID: /* Vendor-Id */
#ifndef WORKAROUND_ACCEPT_INVALID_VSAI
								if (vid != 0)
									invalid++; /* We already had one such AVP. This is invalid according to RFC6733 but not RFC3588 (but there is an erratum) */
#endif /* WORKAROUND_ACCEPT_INVALID_VSAI */
								vid = inhdr->avp_value->u32;
								break;
							case AC_AUTH_APPLICATION_ID: /* Auth-Application-Id */
								if (auth_aid != 0)
									invalid++; /* We already had one such AVP */
#ifndef WORKAROUND_ACCEPT_INVALID_VSAI
								if (acct_aid != 0)
									invalid++; /* Only 1 *-Application-Id AVP is allowed */
#endif /* WORKAROUND_ACCEPT_INVALID_VSAI */
								auth_aid = inhdr->avp_value->u32;
								break;
							case AC_ACCT_APPLICATION_ID: /* Acct-Application-Id */
								if (acct_aid != 0)
									invalid++; /* We already had one such AVP */
#ifndef WORKAROUND_ACCEPT_INVALID_VSAI
								if (auth_aid != 0)
									invalid++; /* Only 1 *-Application-Id AVP is allowed */
#endif /* WORKAROUND_ACCEPT_INVALID_VSAI */
								acct_aid = inhdr->avp_value->u32;
								break;
							/* ignore other AVPs */
						}
						
						if (invalid) {
							TRACE_DEBUG(FULL, "Invalid Vendor-Specific-Application-Id AVP received");
							error->pei_errcode = "DIAMETER_INVALID_AVP_VALUE";
							error->pei_avp = avp;
							return EINVAL;
						}

					innext:			
						/* Go to next in AVP */
						CHECK_FCT( fd_msg_browse(inavp, MSG_BRW_NEXT, &inavp, NULL) );
					}
					
					/* Add entry in the list */
					if (auth_aid) {
						CHECK_FCT( fd_app_merge(&peer->p_hdr.info.runtime.pir_apps, auth_aid, vid, 1, 0) );
					}
					if (acct_aid) {
						CHECK_FCT( fd_app_merge(&peer->p_hdr.info.runtime.pir_apps, acct_aid, vid, 0, 1) );
					}
				}
				break;

			case AC_AUTH_APPLICATION_ID: /* Auth-Application-Id */
				if (hdr->avp_value == NULL) {
					/* This is a sanity check */
					LOG_F("Ignored an AVP (code %x) with unset value in CER/CEA", hdr->avp_code);
					ASSERT(0); /* To check if this really happens, and understand why... */
					goto next;
				}
				
				if (hdr->avp_value->u32 == AI_RELAY) {
					peer->p_hdr.info.runtime.pir_relay = 1;
				} else {
					CHECK_FCT( fd_app_merge(&peer->p_hdr.info.runtime.pir_apps, hdr->avp_value->u32, 0, 1, 0) );
				}
				break;

			case AC_ACCT_APPLICATION_ID: /* Acct-Application-Id */
				if (hdr->avp_value == NULL) {
					/* This is a sanity check */
					LOG_F("Ignored an AVP (code %x) with unset value in CER/CEA", hdr->avp_code);
					ASSERT(0); /* To check if this really happens, and understand why... */
					goto next;
				}
				
				if (hdr->avp_value->u32 == AI_RELAY) {
					/* Not clear if the relay application can be inside this AVP... */
					peer->p_hdr.info.runtime.pir_relay = 1;
				} else {
					CHECK_FCT( fd_app_merge(&peer->p_hdr.info.runtime.pir_apps, hdr->avp_value->u32, 0, 0, 1) );
				}
				break;

			case AC_FIRMWARE_REVISION: /* Firmware-Revision */
				if (hdr->avp_value == NULL) {
					/* This is a sanity check */
					LOG_F("Ignored an AVP (code %x) with unset value in CER/CEA", hdr->avp_code);
					ASSERT(0); /* To check if this really happens, and understand why... */
					goto next;
				}
				
				peer->p_hdr.info.runtime.pir_firmrev = hdr->avp_value->u32;
				break;

			case AC_INBAND_SECURITY_ID: /* Inband-Security-Id */
				if (hdr->avp_value == NULL) {
					/* This is a sanity check */
					LOG_F("Ignored an AVP (code %x) with unset value in CER/CEA", hdr->avp_code);
					ASSERT(0); /* To check if this really happens, and understand why... */
					goto next;
				}
				if (hdr->avp_value->u32 >= 32 ) {
					error->pei_errcode = "DIAMETER_INVALID_AVP_VALUE";
					error->pei_message = "I don't support this Inband-Security-Id value (yet).";
					error->pei_avp = avp;
					return EINVAL;
				}
				peer->p_hdr.info.runtime.pir_isi |= (1 << hdr->avp_value->u32);
				break;
		}

next:			
		/* Go to next AVP */
		CHECK_FCT( fd_msg_browse(avp, MSG_BRW_NEXT, &avp, NULL) );
	}
	
	app_count = fd_app_count(&peer->p_hdr.info.runtime.pir_apps);
	if (app_count > 0 || peer->p_hdr.info.runtime.pir_relay) {
		fd_log_notice("peer %s supports %d application%s%s", peer ? peer->p_hdr.info.pi_diamid : "<unknown>", app_count, app_count == 1 ? "" : "s", peer->p_hdr.info.runtime.pir_relay ? " but is a relay" : "");
	} else {
		fd_log_error("peer %s supports NO applications%s", peer ? peer->p_hdr.info.pi_diamid : "<unknown>", peer->p_hdr.info.runtime.pir_relay ? " but is a relay" : "");
	}
	return 0;
}

/* Create a CER message for sending */ 
static int create_CER(struct fd_peer * peer, struct cnxctx * cnx, struct msg ** cer)
{
	int isi_tls = 0;
	int isi_none = 0;
	
	/* Find CER dictionary object and create an instance */
	CHECK_FCT( fd_msg_new ( fd_dict_cmd_CER, MSGFL_ALLOC_ETEID, cer ) );
	
	/* Do we need Inband-Security-Id AVPs ? If we're already using TLS, we don't... */
	if (!fd_cnx_getTLS(cnx)) {
		isi_none = peer->p_hdr.info.config.pic_flags.sec & PI_SEC_NONE; /* we add it even if the peer does not use the old mechanism, it is impossible to distinguish */

		if (peer->p_hdr.info.config.pic_flags.sec & PI_SEC_TLS_OLD) {
			if (fd_g_config->cnf_sec_data.tls_disabled) {
				LOG_N("TLS disabled locally, so Inband-Security-Id (TLS) not included for peer %s", peer->p_hdr.info.pi_diamid);
			} else {
				isi_tls  = 1;
			}
		}
	}
	
	/* Add the information about the local peer */
	CHECK_FCT( add_CE_info(*cer, cnx, isi_tls, isi_none) );
	
	/* Done! */
	return 0;
}


/* Continue with the initiator side */
static int to_waitcea(struct fd_peer * peer, struct cnxctx * cnx)
{
	/* We sent a CER on the connection, set the event queue so that we receive the CEA */
	CHECK_FCT( set_peer_cnx(peer, &cnx) );
	
	/* Change state and reset the timer */
	CHECK_FCT( fd_psm_change_state(peer, STATE_WAITCEA) );
	fd_psm_next_timeout(peer, 0, CEA_TIMEOUT);
	
	return 0;
}

/* Reject an incoming connection attempt */
static void receiver_reject(struct cnxctx ** recv_cnx, struct msg ** cer, struct fd_pei * error)
{
	struct msg_hdr * hdr = NULL;
	
	/* Create and send the CEA with appropriate error code */
	CHECK_FCT_DO( fd_msg_new_answer_from_req ( fd_g_config->cnf_dict, cer, MSGFL_ANSW_ERROR ), goto destroy );
	CHECK_FCT_DO( fd_msg_rescode_set(*cer, error->pei_errcode, error->pei_message, error->pei_avp, 0 ), goto destroy );
	CHECK_FCT_DO(  fd_msg_hdr( *cer, &hdr ), goto destroy  );
	if (hdr->msg_flags & CMD_FLAG_ERROR) {
		/* Generic error format, just add the origin AVPs */
		CHECK_FCT_DO( fd_msg_add_origin ( *cer, 1 ), goto destroy );
	} else {
		/* Add other AVPs to be compliant with the ABNF */
		CHECK_FCT_DO( add_CE_info(*cer, *recv_cnx, 0, 0), goto destroy );
	}
	CHECK_FCT_DO( fd_out_send(cer, *recv_cnx, NULL, 0), goto destroy );
	
	if (error->pei_avp_free) {
		fd_msg_free(error->pei_avp);
	}
	
	/* And now destroy this connection */
destroy:
	fd_cnx_destroy(*recv_cnx);
	*recv_cnx = NULL;
	if (*cer) {
		fd_hook_call(HOOK_MESSAGE_DROPPED, *cer, NULL, "An error occurred while rejecting this CER.", fd_msg_pmdl_get(*cer));
		fd_msg_free(*cer);
		*cer = NULL;
	}
}

/* We have established a new connection to the remote peer, send CER and eventually process the election */
int fd_p_ce_handle_newcnx(struct fd_peer * peer, struct cnxctx * initiator)
{
	struct msg * cer = NULL;
	
	/* Send CER on the new connection */
	CHECK_FCT( create_CER(peer, initiator, &cer) );
	CHECK_FCT( fd_out_send(&cer, initiator, peer, 0) );
	
	/* Are we doing an election ? */
	if (fd_peer_getstate(peer) == STATE_WAITCNXACK_ELEC) {
		if (election_result(peer)) {
			/* Close initiator connection */
			fd_cnx_destroy(initiator);

			LOG_D("%s: Election lost on outgoing connection, closing and answering CEA on incoming connection.", peer->p_hdr.info.pi_diamid);
			
			/* Process with the receiver side */
			CHECK_FCT( fd_p_ce_process_receiver(peer) );

		} else {
			struct fd_pei pei;
			memset(&pei, 0, sizeof(pei));
			pei.pei_errcode = "ELECTION_LOST";
			pei.pei_message = "Please answer my CER instead, you won the election.";
			LOG_D("%s: Election lost on incoming connection, closing and waiting for CEA on outgoing connection.", peer->p_hdr.info.pi_diamid);

			/* Answer an ELECTION LOST to the receiver side */
			receiver_reject(&peer->p_receiver, &peer->p_cer, &pei);
			CHECK_FCT( to_waitcea(peer, initiator) );
		}
	} else {
		/* No election (yet) */
		CHECK_FCT( to_waitcea(peer, initiator) );
	}
	
	return 0;
}

/* We have received a Capabilities Exchange message on the peer connection */
int fd_p_ce_msgrcv(struct msg ** msg, int req, struct fd_peer * peer)
{
	uint32_t rc = 0;
	int st = STATE_NEW;
	struct fd_pei pei;
	
	TRACE_ENTRY("%p %p", msg, peer);
	CHECK_PARAMS( msg && *msg && CHECK_PEER(peer) );
	
	/* The only valid situation where we are called is in WAITCEA and we receive a CEA (we may have won an election) */
	
	/* Note : to implement Capabilities Update, we would need to change here */
	
	/* If it is a CER, just reply an error */
	if (req) {
		/* Create the error message */
		CHECK_FCT( fd_msg_new_answer_from_req ( fd_g_config->cnf_dict, msg, MSGFL_ANSW_ERROR ) );
		
		/* Set the error code */
		CHECK_FCT( fd_msg_rescode_set(*msg, "DIAMETER_UNABLE_TO_COMPLY", "No CER allowed in current state", NULL, 1 ) );

		/* msg now contains an answer message to send back */
		CHECK_FCT_DO( fd_out_send(msg, NULL, peer, 0), /* In case of error the message has already been dumped */ );
	}
	
	/* If the state is not WAITCEA, just discard the message */
	if (req || ((st = fd_peer_getstate(peer)) != STATE_WAITCEA)) {
		if (*msg) {
			/* In such case, just discard the message */
			char buf[128];
			snprintf(buf, sizeof(buf), "Received while peer state machine was in state %s.", STATE_STR(st));
			fd_hook_call(HOOK_MESSAGE_DROPPED, *msg, peer, buf, fd_msg_pmdl_get(*msg));

			CHECK_FCT_DO( fd_msg_free(*msg), /* continue */);
			*msg = NULL;
		}
		
		return 0;
	}
	
	memset(&pei, 0, sizeof(pei));
	
	/* Save info from the CEA into the peer */
	CHECK_FCT_DO( save_remote_CE_info(*msg, peer, &pei, &rc), 
		{
			fd_hook_call(HOOK_PEER_CONNECT_FAILED, *msg, peer, "An error occurred while processing incoming CEA.", NULL);
			goto cleanup;
		} );
	
	/* Check the Result-Code */
	switch (rc) {
		case ER_DIAMETER_SUCCESS:
			/* Log success */
			fd_hook_call(HOOK_PEER_CONNECT_SUCCESS, *msg, peer, NULL, NULL);
			
			/* Dispose of the message, we don't need it anymore */
			CHECK_FCT_DO( fd_msg_free(*msg), /* continue */ );
			*msg = NULL;
			
			/* No problem, we can continue */
			break;
			
		case ER_DIAMETER_TOO_BUSY:
			/* Retry later */
			fd_hook_call(HOOK_PEER_CONNECT_FAILED, *msg, peer, "Remote peer is too busy", NULL);
			fd_psm_cleanup(peer, 0);
			fd_psm_next_timeout(peer, 0, 300);
			return 0;
		
		case ER_ELECTION_LOST:
			/* Ok, just wait for a little while for the CER to be processed on the other connection. */
			TRACE_DEBUG(FULL, "Peer %s replied a CEA with Result-Code AVP ELECTION_LOST, waiting for events.", peer->p_hdr.info.pi_diamid);
			return 0;
		
		default:
			/* In any other case, we abort all attempts to connect to this peer */
			fd_hook_call(HOOK_PEER_CONNECT_FAILED, *msg, peer, "CEA with unexpected error code", NULL);
			return EINVAL;
	}
	
	
	/* Handshake if needed, start clear otherwise */
	if ( ! fd_cnx_getTLS(peer->p_cnxctx) ) {
		int todo = peer->p_hdr.info.config.pic_flags.sec & peer->p_hdr.info.runtime.pir_isi ;
		/* Special case: if the peer did not send a ISI AVP */
		if (peer->p_hdr.info.runtime.pir_isi == 0)
			todo = peer->p_hdr.info.config.pic_flags.sec;
		
		if (todo == PI_SEC_NONE) {
			/* Ok for clear connection */
			TRACE_DEBUG(INFO, "No TLS protection negotiated with peer '%s'.", peer->p_hdr.info.pi_diamid);
			CHECK_FCT( fd_cnx_start_clear(peer->p_cnxctx, 1) );
			
		} else if (fd_g_config->cnf_sec_data.tls_disabled) {
			LOG_E("Clear connection with remote peer '%s' is not (explicitly) allowed, and TLS is disabled. Giving up...", peer->p_hdr.info.pi_diamid);
			fd_hook_call(HOOK_PEER_CONNECT_FAILED, NULL, peer, "TLS is disabled and peer is not configured for IPsec", NULL);
			goto cleanup;
			
		} else {
			fd_psm_change_state(peer, STATE_OPEN_HANDSHAKE);
			CHECK_FCT_DO( fd_cnx_handshake(peer->p_cnxctx, GNUTLS_CLIENT, ALGO_HANDSHAKE_3436, peer->p_hdr.info.config.pic_priority, NULL),
				{
					/* Handshake failed ...  */
					fd_hook_call(HOOK_PEER_CONNECT_FAILED, NULL, peer, "TLS handshake failed after CER/CEA exchange", NULL);
					goto cleanup;
				} );

			/* Retrieve the credentials */
			CHECK_FCT( fd_cnx_getcred(peer->p_cnxctx, &peer->p_hdr.info.runtime.pir_cert_list, &peer->p_hdr.info.runtime.pir_cert_list_size) );
		}
	}
	
	/* Move to next state */
	if (peer->p_flags.pf_cnx_pb) {
		fd_psm_change_state(peer, STATE_REOPEN );
		CHECK_FCT( fd_p_dw_reopen(peer) );
	} else {
		fd_psm_change_state(peer, STATE_OPEN );
		fd_psm_next_timeout(peer, 1, peer->p_hdr.info.config.pic_twtimer ?: fd_g_config->cnf_timer_tw);
	}
	
	return 0;
	
cleanup:
	fd_p_ce_clear_cnx(peer, NULL);

	/* Send the error to the peer */
	CHECK_FCT( fd_event_send(peer->p_events, FDEVP_CNX_ERROR, 0, NULL) );

	return 0;
}

/* Check if enough processing peers are connected to allow connections by other peers */
static int sufficient_processing_peers(void) {
	int processing_peers_count = 0;
	struct fd_list * li;

	CHECK_FCT( pthread_rwlock_rdlock(&fd_g_activ_peers_rw) );
	for (li = fd_g_activ_peers.next; li != &fd_g_activ_peers; li = li->next) {
		struct fd_peer * p = (struct fd_peer *)li->o;

		TRACE_DEBUG(FULL, "comparing '%s' against processing peers pattern", p->p_hdr.info.pi_diamid);
		if (regexec(&fd_g_config->cnf_processing_peers_pattern_regex, p->p_hdr.info.pi_diamid, 0, NULL, 0) == 0) {
			processing_peers_count++;
		}
	}
	CHECK_FCT( pthread_rwlock_unlock(&fd_g_activ_peers_rw) );

	TRACE_DEBUG(FULL, "%d processing peers found", processing_peers_count);
	return (processing_peers_count >= fd_g_config->cnf_processing_peers_minimum);
}

/* Handle the receiver side to go to OPEN or OPEN_NEW state (any election is resolved) */
int fd_p_ce_process_receiver(struct fd_peer * peer)
{
	struct fd_pei pei;
	struct msg * msg = NULL;
	int isi = 0;
	int fatal = 0;
	int tls_sync=0;
	
	TRACE_ENTRY("%p", peer);
	
	CHECK_FCT_DO( set_peer_cnx(peer, &peer->p_receiver),
		{
			fd_hook_call(HOOK_PEER_CONNECT_FAILED, NULL, peer, "Error saving the incoming connection in the peer structure", NULL);
			return __ret__;
		} );
	msg = peer->p_cer;
	peer->p_cer = NULL;
	
	memset(&pei, 0, sizeof(pei));
	
	/* Parse the content of the received CER */
	CHECK_FCT_DO( save_remote_CE_info(msg, peer, &pei, NULL), goto error_abort );
	
	/* Validate the realm if needed */
	if (peer->p_hdr.info.config.pic_realm) {
		size_t len = strlen(peer->p_hdr.info.config.pic_realm);
		if (fd_os_almostcasesrch(peer->p_hdr.info.config.pic_realm, len, peer->p_hdr.info.runtime.pir_realm, peer->p_hdr.info.runtime.pir_realmlen, NULL)) {
			TRACE_DEBUG(INFO, "Rejected CER from peer '%s', realm mismatch with configured value (returning DIAMETER_UNKNOWN_PEER).", peer->p_hdr.info.pi_diamid);
			pei.pei_errcode = "DIAMETER_UNKNOWN_PEER"; /* maybe AVP_NOT_ALLOWED would be better fit? */
			goto error_abort;
		}
	}
	
	/* Save the credentials if handshake already occurred */
	if ( fd_cnx_getTLS(peer->p_cnxctx) ) {
		CHECK_FCT( fd_cnx_getcred(peer->p_cnxctx, &peer->p_hdr.info.runtime.pir_cert_list, &peer->p_hdr.info.runtime.pir_cert_list_size) );
	}
	
	/* Validate the peer if needed */
	if (peer->p_flags.pf_responder) {
		int res = fd_peer_validate( peer );
		if (res < 0) {
			TRACE_DEBUG(INFO, "Rejected CER from peer '%s', validation failed (returning DIAMETER_UNKNOWN_PEER).", peer->p_hdr.info.pi_diamid);
			pei.pei_errcode = "DIAMETER_UNKNOWN_PEER";
			goto error_abort;
		}
		CHECK_FCT( res );
	}
	
	/* Check peer type and if enough processing peers are already connected */
	if (fd_g_config->cnf_processing_peers_minimum > 0) {
		if (regexec(&fd_g_config->cnf_processing_peers_pattern_regex, peer->p_hdr.info.pi_diamid, 0, NULL, 0) != 0) {
			/* peer is not a processing peer */
			if (!sufficient_processing_peers()) {
				pei.pei_errcode = "DIAMETER_TOO_BUSY";
				goto error_abort;
			}
		}
	}

	/* Check if we have common applications */
	if ( fd_g_config->cnf_flags.no_fwd && (! peer->p_hdr.info.runtime.pir_relay) ) {
		int got_common;
		CHECK_FCT( fd_app_check_common( &fd_g_config->cnf_apps, &peer->p_hdr.info.runtime.pir_apps, &got_common) );
		if (!got_common) {
			TRACE_DEBUG(INFO, "No common application with peer '%s', sending DIAMETER_NO_COMMON_APPLICATION", peer->p_hdr.info.pi_diamid);
			pei.pei_errcode = "DIAMETER_NO_COMMON_APPLICATION";
			fatal = 1;
			goto error_abort;
		}
	}
	
	/* Do we agree on ISI ? */
	if ( ! fd_cnx_getTLS(peer->p_cnxctx) ) {
		
		/* In case of responder, the validate callback must have set the config.pic_flags.sec value already */
	
		/* First case: we are not using old mechanism: ISI are deprecated, we ignore it. */
		if ( ! (peer->p_hdr.info.config.pic_flags.sec & PI_SEC_TLS_OLD)) {
			/* Just check then that the peer configuration allows for IPsec protection */
			if (peer->p_hdr.info.config.pic_flags.sec & PI_SEC_NONE) {
				isi = PI_SEC_NONE;
			} else {
				/* otherwise, we should have already been protected. Reject */
				TRACE_DEBUG(INFO, "Non TLS-protected CER/CEA exchanges are not allowed with this peer, rejecting.");
			}
		} else {
			/* The old mechanism is allowed with this peer. Now, look into the ISI AVP values */
			
			/* In case no ISI was present anyway: */
			if (!peer->p_hdr.info.runtime.pir_isi) {
				TRACE_DEBUG(INFO, "Inband-Security-Id AVP is missing in received CER.");
				if (peer->p_hdr.info.config.pic_flags.sec & PI_SEC_NONE) {
					isi = PI_SEC_NONE;
					TRACE_DEBUG(INFO, "IPsec protection allowed by configuration, allowing this mechanism to be used.");
				} else {
					/* otherwise, we should have already been protected. Reject */
					TRACE_DEBUG(INFO, "Rejecting the peer connection (please allow IPsec here or configure TLS in the remote peer).");
				}
			} else {
				/* OK, the remote peer did send the ISI AVP. */
				if ((peer->p_hdr.info.config.pic_flags.sec & PI_SEC_NONE) && (peer->p_hdr.info.runtime.pir_isi & PI_SEC_NONE)) {
					/* We have allowed IPsec */
					isi = PI_SEC_NONE;
				} else if (fd_g_config->cnf_sec_data.tls_disabled) {
					/* We can agree on TLS */
					TRACE_DEBUG(INFO, "Remote peer is not allowed for IPsec and TLS is disabled.");;
				} else if (peer->p_hdr.info.runtime.pir_isi & PI_SEC_TLS_OLD) {
					/* We can agree on TLS */
					isi = PI_SEC_TLS_OLD;
				} else {
					TRACE_DEBUG(INFO, "Remote peer requested IPsec protection, but local configuration forbids it.");
				}
			}
		}
	
		/* If we did not find an agreement */
		if (!isi) {
			TRACE_DEBUG(INFO, "No common security mechanism with '%s', sending DIAMETER_NO_COMMON_SECURITY", peer->p_hdr.info.pi_diamid);
			pei.pei_errcode = "DIAMETER_NO_COMMON_SECURITY";
			fatal = 1;
			goto error_abort;
		}
		
		/* Do not send the ISI IPsec if we are using the new mechanism */
		if ((isi == PI_SEC_NONE) && (! (peer->p_hdr.info.config.pic_flags.sec & PI_SEC_TLS_OLD)))
			isi = 0;
	} else if (peer->p_hdr.info.runtime.pir_isi & PI_SEC_TLS_OLD) {
		/* Seem some weird peers are sending the Inband-Security-Id AVP on the secure port... No harm */
		isi = PI_SEC_TLS_OLD;
	}
	
	/* Reply a CEA */
	CHECK_FCT( fd_msg_new_answer_from_req ( fd_g_config->cnf_dict, &msg, 0 ) );
	CHECK_FCT( fd_msg_rescode_set(msg, "DIAMETER_SUCCESS", NULL, NULL, 0 ) );
	CHECK_FCT( add_CE_info(msg, peer->p_cnxctx, isi & PI_SEC_TLS_OLD, isi & PI_SEC_NONE) );
	
	/* The connection is complete, but we may still need TLS handshake */
	fd_hook_call(HOOK_PEER_CONNECT_SUCCESS, msg, peer, NULL, NULL);
	
	CHECK_FCT( fd_out_send(&msg, peer->p_cnxctx, peer, 0 ) );
	
	/* Handshake if needed */
	if (isi & PI_SEC_TLS_OLD) {
		fd_psm_change_state(peer, STATE_OPEN_HANDSHAKE);
		CHECK_FCT_DO( fd_cnx_handshake(peer->p_cnxctx, GNUTLS_SERVER, ALGO_HANDSHAKE_3436, peer->p_hdr.info.config.pic_priority, NULL),
			{
				/* Handshake failed ...  */
				fd_hook_call(HOOK_PEER_CONNECT_FAILED, NULL, peer, "TLS handshake failed after CER/CEA exchange", NULL);
				goto cleanup;
			} );
		
		/* Retrieve the credentials */
		CHECK_FCT_DO( fd_cnx_getcred(peer->p_cnxctx, &peer->p_hdr.info.runtime.pir_cert_list, &peer->p_hdr.info.runtime.pir_cert_list_size),
			{
				/* Error ...  */
				fd_hook_call(HOOK_PEER_CONNECT_FAILED, NULL, peer, "Unable to retrieve remote credentials after TLS handshake", NULL);
				goto cleanup;
			} );
		
		
		/* Call second validation callback if needed */
		if (peer->p_cb2) {
			TRACE_DEBUG(FULL, "Calling second validation callback for %s", peer->p_hdr.info.pi_diamid);
			CHECK_FCT_DO( (*peer->p_cb2)( &peer->p_hdr.info ),
				{
					fd_hook_call(HOOK_PEER_CONNECT_FAILED, NULL, peer, "Validation callback rejected the peer after handshake", NULL);
					CHECK_FCT( fd_psm_terminate( peer, "DO_NOT_WANT_TO_TALK_TO_YOU" ) );
					return 0;
				}  );
		}
		tls_sync = 1;
	} else {
		if ( ! fd_cnx_getTLS(peer->p_cnxctx) ) {
			TRACE_DEBUG(INFO, "No TLS protection negotiated with peer '%s'.", peer->p_hdr.info.pi_diamid);
			CHECK_FCT( fd_cnx_start_clear(peer->p_cnxctx, 1) );
		}
	}
		
	/* Move to OPEN or REOPEN state */
	if (peer->p_flags.pf_cnx_pb) {
		fd_psm_change_state(peer, STATE_REOPEN );
		CHECK_FCT( fd_p_dw_reopen(peer) );
	} else {
		if ((!tls_sync) && (fd_cnx_is_unordered_delivery_supported(peer->p_cnxctx))) {
			fd_psm_change_state(peer, STATE_OPEN_NEW );
			/* send DWR */
			CHECK_FCT( fd_p_dw_timeout(peer) );
		} else {

			fd_psm_change_state(peer, STATE_OPEN );
			fd_psm_next_timeout(peer, 1, peer->p_hdr.info.config.pic_twtimer ?: fd_g_config->cnf_timer_tw);
		}
	}
	
	return 0;

error_abort:
	if (pei.pei_errcode) {
		/* Send the error */
		fd_hook_call(HOOK_PEER_CONNECT_FAILED, msg, peer, pei.pei_message ?: pei.pei_errcode, NULL);
		receiver_reject(&peer->p_cnxctx, &msg, &pei);
	} else {
		char buf[1024];
		snprintf(buf, sizeof(buf), "Unexpected error occurred while processing incoming connection from '%s'.", peer->p_hdr.info.pi_diamid);
		fd_hook_call(HOOK_PEER_CONNECT_FAILED, msg, peer, buf, NULL);
	}
	
cleanup:
	if (msg) {
		fd_msg_free(msg);
	}
	fd_p_ce_clear_cnx(peer, NULL);

	/* Send the error to the peer */
	CHECK_FCT( fd_event_send(peer->p_events, fatal ? FDEVP_TERMINATE : FDEVP_CNX_ERROR, 0, NULL) );

	return 0;
}

/* We have received a CER on a new connection for this peer */
int fd_p_ce_handle_newCER(struct msg ** msg, struct fd_peer * peer, struct cnxctx ** cnx, int valid)
{
	struct fd_pei pei;
	int cur_state = fd_peer_getstate(peer);
	memset(&pei, 0, sizeof(pei));
	
	switch (cur_state) {
		case STATE_CLOSED:
			peer->p_receiver = *cnx;
			*cnx = NULL;
			peer->p_cer = *msg;
			*msg = NULL;
			CHECK_FCT( fd_p_ce_process_receiver(peer) );
			break;

		case STATE_WAITCNXACK:
			/* Save the parameters in the peer, move to STATE_WAITCNXACK_ELEC */
			peer->p_receiver = *cnx;
			*cnx = NULL;
			peer->p_cer = *msg;
			*msg = NULL;
			CHECK_FCT( fd_psm_change_state(peer, STATE_WAITCNXACK_ELEC) );
			break;
			
		case STATE_WAITCEA:
			if (election_result(peer)) {
				
				/* Close initiator connection (was already set as principal) */
				LOG_D("%s: Election lost on outgoing connection, closing and answering CEA on incoming connection.", peer->p_hdr.info.pi_diamid);
				fd_p_ce_clear_cnx(peer, NULL);
				
				/* and go on with the receiver side */
				peer->p_receiver = *cnx;
				*cnx = NULL;
				peer->p_cer = *msg;
				*msg = NULL;
				CHECK_FCT( fd_p_ce_process_receiver(peer) );

			} else {

				/* Answer an ELECTION LOST to the receiver side and continue */
				pei.pei_errcode = "ELECTION_LOST";
				pei.pei_message = "Please answer my CER instead, you won the election.";
				LOG_D("%s: Election lost on incoming connection, closing and waiting for CEA on outgoing connection.", peer->p_hdr.info.pi_diamid);
				receiver_reject(cnx, msg, &pei);
			}
			break;

		default:
			pei.pei_errcode = "DIAMETER_UNABLE_TO_COMPLY"; /* INVALID COMMAND? in case of Capabilities-Updates? */
			pei.pei_message = "Invalid state to receive a new connection attempt.";
			LOG_E("%s: Rejecting new connection attempt while our state machine is in state '%s'", peer->p_hdr.info.pi_diamid, STATE_STR(cur_state));
			receiver_reject(cnx, msg, &pei);
	}
				
	return 0;
}