summaryrefslogtreecommitdiff
path: root/cesar/cp/av/cco/action/src/cco_action.c
blob: 6ed05a7047d834be8a9c772a11dec9d03378f339 (plain)
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
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
/* Cesar project {{{
 *
 * Copyright (C) 2008 Spidcom
 *
 * <<<Licence>>>
 *
 * }}} */
/**
 * \file    cp/av/cco/action/src/cco_action.c
 * \brief   CCo Action functions.
 * \ingroup cp_av_cco_action
 *
 */
#include <string.h>
#include "common/std.h"
#include "common/defs/homeplugAV.h"

#include "lib/set.h"
#include "lib/utils.h"
#include "lib/rnd.h"
#include "lib/slab.h"

#include "common/defs/ethernet.h"

#include "cl/cl_mactotei.h"

#include "mac/common/timings.h"

#include "cp/defs.h"
#include "cp/cp.h"
#include "cp/fsm/fsm.h"
#include "cp/msg/msg.h"

#include "cp/cco/action/cco_action.h"
#include "cp/av/cco/action/cco_action.h"
#include "cp/sta/mgr/sta_mgr.h"
#include "cp/sta/mgr/net.h"
#include "cp/sta/mgr/sta.h"
#include "cp/beacon/beacon.h"
#include "cp/av/beacon/discover.h"
#include "cp/sta/core/core.h"
#include "cp/beacon/beacon.h"
#include "cp/cco/region/region.h"
#include "cp/av/cco/region/region.h"
#include "cp/cco/bw/bw.h"
#include "cp/av/cco/bw/bw.h"
#include "cp/av/beacon/beacon.h"

#include "cp/inc/context.h"
#include "cp/inc/trace.h"
#include "cp/cco/action/inc/cco_action.h"
#include "cp/av/cco/action/inc/cco_action.h"

#include "bsu/bsu.h"

/**
 * Progam a timer to post a cco__nek_change event
 * \param  ctx  the module context.
 */
static void
cp_av_cco_action_nek_change_timer_program (cp_t *ctx)
{
    /* Prepare next change. */
    cp_fsm_event_t *event =
        cp_fsm_event_bare_new (ctx, CP_FSM_EVENT_TYPE_cco__nek_change);
    cp_sta_core_gen_timed_event (ctx, &ctx->cco_action.nek_change,
                                 event, HPAV_NEK_CHANGE_MS);
}

/**
 * Choose a SNID between the ones available.
 * \param  ctx  the CP context.
 */
static cp_snid_t
cp_av_cco_action_snid_choose (cp_t *ctx)
{
    u16 flags;
    u16 table [16];
    uint nb_elem;
    uint i;
    dbg_assert (ctx);

    // Get the present flags.
    flags = ~cp_sta_mgr_get_present_snids (ctx);

    // fill the table.
    for (i = 0, nb_elem = 0; i < 16; i++)
    {
        if ((flags >> i) & true)
        {
            table[nb_elem] = i;
            nb_elem ++;
        }
    }


    // Chose the new SNID.
    i = lib_rnd32 (&ctx->rnd) % nb_elem;

    return table[i];
}

/**
 * Function to sort the station in the CCo selection set.
 * \param  left  the left node.
 * \param  right  the right node.
 */
static inline bool
cp_av_cco_action_cco_selection__less (heap_node_t *left, heap_node_t *right)
{
    cp_sta_t *stal;
    cp_sta_t *star;

    dbg_assert (left);
    dbg_assert (right);

    stal = PARENT_OF (cp_sta_t, cco_selection_node, left);
    star = PARENT_OF (cp_sta_t, cco_selection_node, right);

    if (stal->cco_cap > star->cco_cap)
        return true;
    return false;
}


/**
 * Search for an available TEI in the AVLN list.
 * \param  ctx  the module context.
 * \return  return the TEI found.
 *
 */
cp_tei_t
cp_av_cco_action_tei_compute (cp_t *ctx)
{
    uint row;
    uint tei;
    uint i;
    dbg_assert (ctx);

    for (i = MAC_TEI_STA_MIN; MAC_TEI_IS_STA (i); i++)
    {
        row = i / CP_CCO_ACTION_TEI_FLAGS_ROW_SIZE_BITS;
        tei = ctx->cco_action.tei_flags[row] >>
            ((i % CP_CCO_ACTION_TEI_FLAGS_ROW_SIZE_BITS)- 1);
        if ((tei & true) == false)
        {
            tei = i;
            cp_av_cco_action_tei_in_use (ctx, tei);
            break;
        }
        else
            tei = MAC_TEI_UNASSOCIATED;
    }

    // No TEI are available.
    return tei;
}

void
cp_av_cco_action_tei_in_use (cp_t *ctx, cp_tei_t tei)
{
    uint row;

    dbg_assert (ctx);
    dbg_assert (MAC_TEI_IS_STA (tei));

    row = tei / CP_CCO_ACTION_TEI_FLAGS_ROW_SIZE_BITS;

    ctx->cco_action.tei_flags[row] |= (1 << ((tei
         % CP_CCO_ACTION_TEI_FLAGS_ROW_SIZE_BITS) - 1));
}

void
cp_av_cco_action_tei_clear (cp_t *ctx)
{
    dbg_assert (ctx);

    memset (&ctx->cco_action.tei_flags, 0,
            sizeof (uint) * CP_CCO_ACTION_TEI_FLAGS_ROW);
}

/**
 * Start common operations.
 * \param  ctx  the CP context.
 *
 * This should promote the station as CCo.
 * Program the nek change timer.
 * Untrack the old CCo.
 * Update beacon module.
 * Initialise the discover procedure.
 */
static void
cp_av_cco_action_cco_start_common (cp_t *ctx)
{
    /* Set the CCo status in the station own data. */
    cp_sta_own_data_set_authenticated_status (ctx, true);
    cp_sta_own_data_set_cco_status (ctx, true);
    // Program the timer to change the NEKs.
    cp_av_cco_action_nek_change_timer_program (ctx);
    cp_beacon_process_untracked_avln (ctx);
    cp_net_t *net = cp_sta_mgr_get_our_avln (ctx);
    bsu_update_nid_snid (ctx->bsu, cp_net_get_nid (ctx, net),
                         cp_net_get_snid (ctx, net));
    cp_beacon_cco_update_beacon_data (ctx);
    cp_beacon_reconfigure_timer (ctx, true);
    cp_av_beacon_discover_init (ctx);
}

/**
 * Start to act as a CCo coming from the unassociated state.
 * \param  ctx  the module context.
 *
 * This function shall:
 *   - Choose a TEI if the station don't have one yet.
 *   - Create and set our AVLN in the station manager.
 *   - Generate the current NEK and order to change it.
 *   - Clear schedules and set the network mode to CSMA_ONLY.
 *   - Set the station's CCo and authenticate status.
 *   - Program the NEK change timer.
 *   - Clear tracking data.
 *   - Update the beacon for BSU.
 *   - Initialise the discover procedure context.
 */
static void
cp_av_cco_action_start (cp_t *ctx)
{
    cp_tei_t tei;
    cp_net_t *net;
    cp_nid_t nid;
    cp_snid_t snid;
    dbg_assert (ctx);
    /* Verify if the station does not already have a TEI. */
    snid = cp_sta_own_data_get_snid (ctx);
    nid = cp_sta_own_data_get_nid (ctx);
    if (!cp_sta_own_data_get_tei(ctx))
    {
        tei = cp_av_cco_action_tei_compute (ctx);
        cp_sta_own_data_set_tei (ctx, tei);
        /* Clear the AVLN. */
        cp_sta_mgr_remove_avln (ctx, snid, nid);
    }
    /* Set our AVLN. */
    net = cp_sta_mgr_add_avln (ctx, snid, nid);
    cp_sta_mgr_set_our_avln (ctx, net);
    cp_cco_action_gen_nek_now (ctx);
    /* Reinitialise schedules and regions. */
    cp_cco_region_alloc_clean (ctx, &ctx->region.region_list);
    cp_av_cco_region_default (ctx);
    cp_cco_bw_alloc_clean (ctx, &ctx->bw.alloc_list);
    cp_av_cco_bw_schedules_default (ctx);
    /* Set network mode as CSMA only mode. */
    cp_net_set_nm (ctx, net, MAC_NM_CSMA_ONLY);
    /* Set hybrid mode to Full hybrid mode. */
    cp_sta_own_data_t *own = cp_sta_mgr_get_sta_own_data (ctx);
    own->hybrid_mode = MAC_COEXISTENCE_HYBRID_DELIMITERS_MODE;
    cp_av_cco_action_cco_start_common (ctx);
}

/**
 * Stop acting as a CCo and become a simple station.
 * \param  ctx  the module context.
 *
 * This function shall:
 *   - Change the station CCo status.
 *   - Stop the NEK timer.
 *   - Clear the TEI table attribution.
 *   - Clear the CCo selection context (handover).
 *   - Reconfigure becon timer.
 *   - Update the beacon to act as a STA.
 *   - Uninitialise discover procedure.
 */
static void
cp_av_cco_action_stop (cp_t *ctx)
{
    dbg_assert (ctx);
    /* Change the CCo status to false, the station leave the CCo status. */
    cp_sta_own_data_set_cco_status (ctx, false);
    /* Stop the timer for the NEK generation keys. */
    cp_sta_core_stop_timed_or_cyclic_event (ctx, &ctx->cco_action.nek_change);
    /* clear the TEI list. */
    cp_av_cco_action_tei_clear (ctx);
    cp_av_cco_action_cco_selection__clear (ctx);
    cp_beacon_reconfigure_timer (ctx, false);
    cp_av_beacon_sta_update_beacon_data (ctx);
    cp_av_beacon_discover_uninit (ctx);
}


/**
 * initialisation of CCo action module.
 * \param  ctx  the module context.
 *
 */
void
cp_av_cco_action_init (cp_t *ctx)
{
    dbg_assert (ctx);

    memset (&ctx->cco_action, 0, sizeof (cp_cco_action_t));

    /* Initialise the SET. */
    heap_init (&ctx->cco_action.selection_heap,
              cp_av_cco_action_cco_selection__less);
    /* Create default region. */
    cp_av_cco_region_default (ctx);
}

/**
 * Uninitialisation of CCo action module.
 * \param  ctx  the module context.
 *
 */
void
cp_av_cco_action_uninit (cp_t *ctx)
{
    dbg_assert (ctx);

    cp_av_cco_action_cco_selection__clear (ctx);
}

void
cp_av_cco_action_ucco_start (cp_t *ctx)
{
    dbg_assert (ctx);
    cp_av_cco_action_start (ctx);
}

void
cp_av_cco_action_ucco_stop (cp_t *ctx)
{
    dbg_assert (ctx);
    cp_av_cco_action_stop (ctx);
    cp_sta_own_data_set_authenticated_status (ctx, false);
    /* Set our AVLN as null. */
    cp_sta_mgr_set_our_avln (ctx, NULL);
    /* Leave our TEI. */
    cp_sta_own_data_set_tei (ctx, MAC_TEI_UNASSOCIATED);
    cp_fsm_trigger_new_event (ctx, bare, assoc_cco_leave);
}

void
cp_av_cco_action_ucco__to_cco (cp_t *ctx)
{
    dbg_assert (ctx);
    cp_fsm_trigger_new_event (ctx, bare, assoc_become_cco);
}

void
cp_av_cco_action_cco__to_ucco (cp_t *ctx)
{
    dbg_assert (ctx);
    cp_fsm_trigger_new_event (ctx, bare, assoc_become_ucco);
}

void
cp_av_cco_action_cco__unassoc_start (cp_t *ctx)
{
    dbg_assert (ctx);
    /* Take a snid. */
    cp_snid_t snid = cp_av_cco_action_snid_choose (ctx);
    cp_sta_own_data_set_snid (ctx, snid);
    bsu_power_on (ctx->bsu, snid);
    cp_av_cco_action_start (ctx);
    cp_fsm_trigger_new_event (ctx, bare, assoc_become_cco);
}

void
cp_av_cco_action_cco__assoc_start (cp_t *ctx)
{
    cp_av_cco_action_cco_start_common (ctx);
    /* Clear tracking data. */
    cp_fsm_trigger_new_event (ctx, bare, assoc_become_cco);
}

void
cp_av_cco_action_cco__assoc_stop (cp_t *ctx)
{
    cp_av_cco_action_stop (ctx);
    cp_fsm_trigger_new_event (ctx, bare, assoc_become_sta);
}

void
cp_av_cco_action_cco__unassoc_stop (cp_t *ctx)
{
    dbg_assert (ctx);
    cp_av_cco_action_stop (ctx);
    cp_fsm_trigger_new_event (ctx, bare, assoc_cco_leave);
}

/**
 * Change the SNID.
 * \param  ctx  the module context.
 *
 *  It shall request the SNIDs in use from the station manager to choose
 * one randomly in the available SNIDs
 */
void
cp_av_cco_action_cco__cco_snid_conflict (cp_t *ctx)
{
    cp_snid_t snid;
    dbg_assert (ctx);

    snid = cp_av_cco_action_snid_choose (ctx);

    // Provide the SNID to the beacon module.
    cp_beacon_change_snid (ctx, snid);
}

/**
 * manage explicit leave request of a station.
 * \param  ctx  the module context.
 * \param  sta  provided by the garbage function to send a CC_LEAVE_IND.
 *
 * Remove the station from the station manager.
 * \warn It does not release the reference of the station provided
 * in parameters.
 */
void
cp_av_cco_action_tei_expired (cp_t *ctx, cp_sta_t *sta)
{
    cp_mme_peer_t peer;
    cp_net_t *net;

    dbg_assert (ctx);

    /* Get the network of the station. */
    net = cp_sta_mgr_get_our_avln (ctx);

    cp_sta_get_peer (sta, &peer);

    cp_msg_cc_leave_ind_send (ctx, &peer,
                              CP_MSG_CC_LEAVE_IND_REASON_TEI_LEASE_EXPIRED,
                              cp_net_get_nid(ctx, net));
    CP_TRACE (CCO_TEI_EXPIRED, TRACE_U64 (peer.mac), peer.tei);

    cp_av_cco_action_cco_sta_leave_send_tei_map (ctx, sta);
    cp_sta_mgr_release_station (ctx, cp_sta_get_tei (sta));
}

/**
 * perform garbage actions of CCo's responsibility.
 * \param  ctx  the module context.
 */
void
cp_av_cco_action_garbage (cp_t *ctx)
{
    cp_sta_t *sta;
    cp_sta_t *sta_next;
    cp_net_t *net;
    dbg_assert (ctx);

    if (cp_sta_own_data_get_tei (ctx))
    {
        net = cp_sta_mgr_get_our_avln (ctx);

        sta = cp_net_sta_get_first (ctx, net, CP_NET_STA_ASSOC);
        while (sta)
        {
            slab_addref (sta);
            sta_next = cp_net_sta_get_next (ctx, net, sta);
            u32 date_ms = cp_sta_core_get_date_ms (ctx);
            if (less_mod2p32(sta->tei_lease_date_ms, date_ms)
                || less_mod2p32 (sta->expired_date_ms, date_ms))
            {
                // Remove the node from the tei lease.
                cp_av_cco_action_tei_expired (ctx, sta);
            }
            slab_release (sta);
            sta = sta_next;
        }

        cp_sta_mgr__assoc__timeout (ctx, cp_sta_core_get_date_ms (ctx));
    }
}

/**
 * generate a new NEK value.
 * \param  ctx  the module context.
 *
 *   NEK shall be used no more than 1 hour, so must be changed after 1
 * hour  for that purpose, NEK expiration date is checked at every occurrence
 * of  the global garbage collector timer and if current NEK expiration
 * date reached,  a new NEK value shall be generated by calling this function
 */
void
cp_av_cco_action_cco__cco_nek_change (cp_t *ctx)
{
    dbg_assert (ctx);
    cp_secu_generate_key (ctx, lib_rnd32 (&ctx->rnd),
                          CP_SECU_PBKDF1_ITERATION_NEK,
                          &ctx->cco_action.nek_new);

    /* Prepare next change. */
    cp_av_cco_action_nek_change_timer_program (ctx);
    /* POST the FSM event. */
    cp_fsm_post_new_event (ctx, bare, cco_nek_change__nek_provide);
}

/**
 * Send the SET tei map IND to all the station with the TEI of the new one.
 * \param  ctx  the CP context.
 * \param  tei  the tei of the station which has joined the AVLN.
 * \param  mac  the station mac address.
 */
static void
cp_av_cco_action_send_set_tei_map_to_new_sta (cp_t *ctx, cp_tei_t tei,
                                           mac_t mac)
{
    cp_mme_tx_t *mme_tx;
    cp_sta_t *sta_list;
    cp_mme_peer_t *peer;
    cp_net_t *net;

    dbg_assert (ctx);
    dbg_assert (tei);
    dbg_assert (mac);

    // Send unicast.
    // It will send all the TEI MAP to the station just associated.
    net = cp_sta_mgr_get_our_avln (ctx);
    peer = &CP_MME_PEER (mac, tei);

    // +1 For our own station which is not in the AVLN.
    mme_tx = cp_msg_cc_set_tei_map_ind_send_begin (ctx, peer,
                CP_MSG_CC_SET_TEI_MAP_IND_MODE_UPDATE,
                cp_net_get_num_stas (ctx, net) + 1);

    // Add our station first.
    cp_msg_cc_set_tei_map_ind_send_sta (ctx, mme_tx,
                            cp_sta_own_data_get_tei(ctx),
                            cp_sta_own_data_get_mac_address (ctx),
                            CP_MSG_CC_SET_TEI_MAP_IND_STATUS_AUTHENTICATED);

    sta_list = cp_net_sta_get_first (ctx, net, CP_NET_STA_ASSOC);
    while (sta_list)
    {
        enum cp_msg_cc_set_tei_map_ind_status_t station_status;

        if (cp_sta_get_authenticated (ctx, sta_list))
        {
            station_status =
                CP_MSG_CC_SET_TEI_MAP_IND_STATUS_AUTHENTICATED;
        }
        else if (cp_sta_get_tei (sta_list))
        {
            station_status = CP_MSG_CC_SET_TEI_MAP_IND_STATUS_ASSOCIATED;
        }
        else
        {
            station_status =
                CP_MSG_CC_SET_TEI_MAP_IND_STATUS_DISASSOCIATED;
        }
        cp_msg_cc_set_tei_map_ind_send_sta (ctx, mme_tx,
                                            cp_sta_get_tei (sta_list),
                                            cp_sta_get_mac_address (sta_list),
                                            station_status);

        sta_list = cp_net_sta_get_next (ctx, net, sta_list);

    }
    cp_msg_cc_set_tei_map_ind_send_end (ctx, mme_tx);
}

/**
 * Send the SET TEI MAP to all the station of the NET.
 * \param  ctx  the CP context.
 * \param  tei  the new station tei.
 * \param  mac  the station mac address.
 */
static void
cp_av_cco_action_send_set_tei_map_to_all_sta (cp_t *ctx, cp_tei_t tei,
                                           mac_t mac)
{
    cp_mme_peer_t *peer;
    cp_mme_tx_t *mme_tx;
    dbg_assert (ctx);
    dbg_assert (tei);
    dbg_assert (mac);

    peer = &CP_MME_PEER_ALL_STA;
    mme_tx = cp_msg_cc_set_tei_map_ind_send_begin (ctx, peer,
                CP_MSG_CC_SET_TEI_MAP_IND_MODE_ADD, 1);

    cp_msg_cc_set_tei_map_ind_send_sta (ctx, mme_tx,
                tei, mac,
                CP_MSG_CC_SET_TEI_MAP_IND_STATUS_ASSOCIATED);

    cp_msg_cc_set_tei_map_ind_send_end (ctx, mme_tx);
}

/**
 * Assoc type join.
 * \param  ctx  the CP context.
 * \param  msg  the assoc MME message.
 * \param  assoc  the assoc data read from the MME.
 */
static void
cp_av_cco_action__assoc__join (cp_t *ctx, cp_mme_rx_t *msg,
                            cp_msg_cc_assoc_req_t *assoc)
{
    cp_net_t *net;
    cp_sta_t *sta;
    cp_tei_t tei = MAC_TEI_UNASSOCIATED;
    cp_msg_cc_assoc_cnf_t cnf;

    dbg_assert (ctx);
    dbg_assert (msg);
    dbg_assert (assoc);

    /* Add the station to the AVLN. */
    net = cp_sta_mgr_get_our_avln (ctx);

    cnf.nid = cp_net_get_nid (ctx, net);
    cnf.snid = cp_net_get_snid (ctx, net);

    /* Try to get the TEI from the STA manager if we already know it. */
    sta = cp_sta_mgr_sta_get_from_mac (ctx, msg->peer.mac);
    /* If the station is known. */
    if (sta)
    {
        /* If the station is currently in our AVLN/net. */
        if (net == cp_sta_get_net (sta))
        {
            // The station already exists get the TEI.
            tei = cp_sta_get_tei (sta);
        }
        /* Remove the station from the station manager and the mac store. */
        cp_sta_mgr_sta_remove (ctx, sta);
        slab_release (sta);
    }
    /* If the station has no TEI, try to generate one. */
    if (!MAC_TEI_IS_STA (tei))
    {
        /* Try to get a TEI. */
        tei = cp_av_cco_action_tei_compute (ctx);
    }

    /* If we manage to have a TEI, it's a success. */
    if (MAC_TEI_IS_STA (tei))
    {
        cnf.result = CP_MSG_CC_ASSOC_CNF_RESULT_SUCCESS;
        cnf.lease_time_min = CP_LEASE_ASSOC_MIN;
    }
    /* Otherwise, it's an error. */
    else
    {
        cnf.result =
            CP_MSG_CC_ASSOC_CNF_RESULT_FAILURE_TEMPORARY_RESSOURCE_EXHAUSTION;
    }

    /* Send the answer. */
    cnf.sta_tei = tei;
    cp_msg_cc_assoc_cnf_send (ctx, &msg->peer, &cnf);
    CP_TRACE (CCO_ASSOC, TRACE_U64 (msg->peer.mac), tei);

    if (tei)
    {
        /* Send TEI MAP to all STA except the new one (need to do it before
         * adding the new STA to the STA manager). */
        cp_av_cco_action_send_set_tei_map_to_all_sta (ctx, tei, msg->peer.mac);
        sta = cp_sta_mgr_sta_add (ctx, net, tei, msg->peer.mac);
        /* Add the TEI lease corresponding to an unassociated STA. */
        cp_sta_mgr_commit_to_dataplane (ctx);
        u32 date_ms = cp_sta_core_get_date_ms (ctx);
        sta->tei_lease_date_ms = date_ms +
            MAC_SEC_TO_MS(CP_LEASE_ASSOC_MIN * 60);

        /* Update the last request date in the sta. */
        cp_sta_set_assoc_confirmed (ctx, sta, false);
        sta->assoc_req_last_ms = cp_sta_core_get_date_ms (ctx);
        /* A new STA has joined an AVLN for the first time, generate an
         * event. */
        cp_fsm_event_t *event = cp_fsm_event_sta_new
            (ctx, CP_FSM_EVENT_TYPE_new_sta_associated, net,
             (cp_sta_t *) sta);
        cp_fsm_post (ctx, event);

        /* Release the reference on the station. */
        slab_release (sta);
    }
    if (!tei)
    {
        sta = cp_sta_mgr_sta_add (ctx, net, 0, msg->peer.mac);
        /* Release the reference on the station. */
        slab_release (sta);
    }
}

/**
 * Assoc type renew.
 * \param  ctx  the CP context.
 * \param  msg  the assoc MME message.
 * \param  assoc  the assoc data read from the MME.
 */
static void
cp_av_cco_action__assoc__renew (cp_t *ctx, cp_mme_rx_t *msg,
                            cp_msg_cc_assoc_req_t *assoc)
{
    cp_net_t *net;
    cp_sta_t *sta;
    cp_msg_cc_assoc_cnf_t cnf;

    dbg_assert (ctx);
    dbg_assert (msg);
    dbg_assert (assoc);

    /* Add the station to the AVLN. */
    net = cp_sta_mgr_get_our_avln (ctx);

    cnf.nid = cp_net_get_nid (ctx, net);
    cnf.snid = cp_net_get_snid (ctx, net);

    /* Renew the TEI. */
    sta = cp_sta_mgr_sta_get_assoc (ctx, net, msg->peer.tei);

    if (sta)
    {
        /* Renew the TEI. */
        u32 date_ms = cp_sta_core_get_date_ms (ctx);
        sta->tei_lease_date_ms = date_ms +
            MAC_SEC_TO_MS(CP_LEASE_AUTH_MIN * 60);
        cnf.result = CP_MSG_CC_ASSOC_CNF_RESULT_SUCCESS;
        cnf.sta_tei = cp_sta_get_tei (sta);
        cnf.lease_time_min = CP_LEASE_AUTH_MIN;

        slab_release (sta);
    }
    else
    {
        cnf.result = CP_MSG_CC_ASSOC_CNF_RESULT_FAILURE_OTHER_REASON;
        cnf.sta_tei = 0;
        cnf.lease_time_min = 0;
    }

    /* Send the answer. */
    cp_msg_cc_assoc_cnf_send (ctx, &msg->peer, &cnf);
    CP_TRACE (CCO_ASSOC_RENEW, TRACE_U64 (msg->peer.mac), msg->peer.tei);
}

/**
 * Static function part.
 * \param  ctx  the CP module context.
 * \param  assoc_req  the MME context.
 * \param  assoc  The mme in the processor format.
 */
static void
cp_av_cco_action_manage_sta_assoc_common (cp_t *ctx, cp_mme_rx_t *assoc_req,
                                       cp_msg_cc_assoc_req_t *assoc)
{
    dbg_assert (ctx);
    dbg_assert (assoc_req);
    dbg_assert (assoc);
    dbg_assert (ctx->mac_store);


    if (assoc->request_type == CP_MSG_CC_ASSOC_REQ_TYPE_NEW)
        cp_av_cco_action__assoc__join (ctx, assoc_req, assoc);
    else if (assoc->request_type == CP_MSG_CC_ASSOC_REQ_TYPE_RENEW)
        cp_av_cco_action__assoc__renew (ctx, assoc_req, assoc);
    else
        dbg_assert (assoc->request_type == CP_MSG_CC_ASSOC_REQ_TYPE_NB);
}

/**
 * manage association of a station.
 * \param  ctx  the module context.
 * \param  assoc_req  CM_ASSOC.REQ MME msg having being received
 */
void
cp_av_cco_action_cco__cc_assoc_req (cp_t *ctx, cp_mme_rx_t * assoc_req)
{
    cp_msg_cc_assoc_req_t assoc;

    dbg_assert (ctx);
    dbg_assert (assoc_req);

    /* Reading the data in the MME. */
    if (cp_msg_cc_assoc_req_receive(ctx, assoc_req, &assoc))
        cp_av_cco_action_manage_sta_assoc_common (ctx, assoc_req, &assoc);
}

static void
cp_av_cco_action_ucco__cc_assoc_req_common (
    cp_t *ctx, cp_mme_rx_t * assoc_req, cp_fsm_branch_t branch_ok,
    cp_fsm_branch_t branch_nok)
{
    cp_msg_cc_assoc_req_t assoc;
    dbg_assert (ctx);
    dbg_assert (assoc_req);
    dbg_assert (cp_sta_own_data_get_tei (ctx));
    dbg_assert (cp_sta_own_data_get_authenticated_status (ctx));
    dbg_assert (cp_sta_own_data_get_cco_status (ctx));
    /* Reading the data in the MME. */
    cp_msg_cc_assoc_req_receive(ctx, assoc_req, &assoc);
    /* The MME is not for the station, it shall answer to the source station
     * with a Failure for others reason. */
    if ((assoc.request_type == CP_MSG_CC_ASSOC_REQ_TYPE_NEW)
        && (assoc.nid == cp_sta_own_data_get_nid (ctx)))
    {
        /* Become CCo. */
        cp_av_cco_action_ucco__to_cco (ctx);
        /* Continue the association procedure. */
        cp_av_cco_action_manage_sta_assoc_common (ctx, assoc_req, &assoc);
        cp_fsm_branch_ (ctx, branch_ok);
    }
    else
        cp_fsm_branch_ (ctx, branch_nok);
}

void
cp_av_cco_action_ucco__cc_assoc_req (cp_t *ctx, cp_mme_rx_t * assoc_req)
{
    cp_av_cco_action_ucco__cc_assoc_req_common (
        ctx, assoc_req, CP_FSM_BRANCH (UCCO, CC_ASSOC_REQ, ok),
        CP_FSM_BRANCH (UCCO, CC_ASSOC_REQ, nok));
}

void
cp_av_cco_action_sc_ucco__cc_assoc_req (cp_t *ctx, cp_mme_rx_t * assoc_req)
{
    cp_av_cco_action_ucco__cc_assoc_req_common (
        ctx, assoc_req, CP_FSM_BRANCH (SC_UCCO, CC_ASSOC_REQ, ok),
        CP_FSM_BRANCH (SC_UCCO, CC_ASSOC_REQ, nok));
}

/**
 * manage authentication of a station.
 * \param  ctx  the module context.
 * \param  get_key_req  CM_GET_KEY.REQ MME msg having being decrypted
 */
void
cp_av_cco_action_cco__cm_get_key_req_pid0 (cp_t *ctx, cp_mme_rx_t * get_key_req)
{
    cp_msg_cm_get_key_req_t req;
    cp_msg_cm_get_key_cnf_t cnf;
    cp_net_t *net;
    cp_sta_t *sta;
    memset (&cnf, 0, sizeof (cp_msg_cm_get_key_cnf_t));
    cnf.eks = MAC_EKS_CLEAR;
    dbg_assert (ctx);
    dbg_assert (get_key_req);

    // get the data in the payload of the mme.
    if (cp_msg_cm_get_key_req_receive (ctx, get_key_req, &req)
        && (cp_secu_protocol_check
            (NULL, &get_key_req->prun,
             CP_SECU_PROTOCOL_RUN_CHECK_RESULT_NEW))
        && (req.key_type == CP_MSG_KEY_NEK)
        && MAC_TEI_IS_STA (get_key_req->peer.tei))
    {
        // Get the network.
        net = cp_sta_mgr_get_our_avln (ctx);
        // Get the station.
        sta = cp_sta_mgr_sta_get_assoc (ctx, net, get_key_req->peer.tei);

        if (sta)
        {
            uint nb_sta;
            cnf.result = CP_MSG_CM_GET_KEY_CNF_RESULT_KEY_GRANTED;
            cp_sta_set_assoc_confirmed (ctx, sta, true);

            if (req.key_type == CP_MSG_KEY_NEK)
            {
                uint i;
                uint index = bsu_nek_index_current (ctx->bsu);
                cnf.eks = ctx->mac_config->nek[index].eks;
                for (i = 0; i < COUNT (ctx->mac_config->nek[0].nek_enc); i++)
                    cnf.key.key[i] =
                        ctx->mac_config->nek[index].nek_enc[i];
            }

            /* Send the TEI map. */
            nb_sta = cp_net_get_num_stas (ctx, net);
            if (nb_sta)
            {
                cp_av_cco_action_send_set_tei_map_to_new_sta (ctx,
                                                           cp_sta_get_tei(sta),
                                                           get_key_req->peer.mac);
            }

            slab_release (sta);
        }
        else
            cnf.result = CP_MSG_CM_GET_KEY_CNF_RESULT_REQUEST_REFUSED;
    }
    // Refuse the request.
    else
        cnf.result = CP_MSG_CM_GET_KEY_CNF_RESULT_REQUEST_REFUSED;

    cnf.key_type = req.key_type;
    cnf.nid = req.nid;
    cp_secu_protocol_next (&get_key_req->prun, &ctx->rnd, true);
    cp_msg_cm_get_key_cnf_send (ctx, &get_key_req->peer, get_key_req->peks,
                                &get_key_req->prun, &cnf);
}

void
cp_av_cco_action_cco__cm_get_key_req_pid1 (cp_t *ctx, cp_mme_rx_t * get_key_req)
{
    dbg_assert (ctx);
    dbg_assert (get_key_req);

    cp_msg_cm_get_key_req_t req;
    cp_msg_cm_get_key_cnf_t cnf;
    memset (&cnf, 0, sizeof (cp_msg_cm_get_key_cnf_t));
    cnf.eks = MAC_EKS_CLEAR;

    if (cp_msg_cm_get_key_req_receive (ctx, get_key_req, &req)
        && (cp_secu_protocol_check
            (NULL, &get_key_req->prun,
             CP_SECU_PROTOCOL_RUN_CHECK_RESULT_NEW))
        && MAC_TEI_IS_STA (get_key_req->peer.tei))
    {
        if (req.key_type == CP_MSG_KEY_NEK)
        {
            cnf.result = CP_MSG_CM_GET_KEY_CNF_RESULT_KEY_GRANTED;

            uint i;
            uint index = bsu_nek_index_next (ctx->bsu);
            cnf.eks = ctx->mac_config->nek[index].eks;
            for (i = 0; i < COUNT (ctx->mac_config->nek[0].nek_enc); i++)
                cnf.key.key[i] =
                    ctx->mac_config->nek[index].nek_enc[i];
        }
        else
            cnf.result =
                CP_MSG_CM_GET_KEY_CNF_RESULT_UNSUPPORTED_METHOD_KEY_TYPE;
    }
    else
        cnf.result = CP_MSG_CM_GET_KEY_CNF_RESULT_REQUEST_REFUSED;

    cnf.key_type = req.key_type;
    cnf.nid = req.nid;
    cp_secu_protocol_next (&get_key_req->prun, &ctx->rnd, true);
    cp_msg_cm_get_key_cnf_send (ctx, &get_key_req->peer, get_key_req->peks,
                                &get_key_req->prun, &cnf);
}

void
cp_av_cco_action_cco_sta_leave_send_tei_map (cp_t *ctx, cp_sta_t *sta)
{
    cp_mme_peer_t *peer;
    cp_net_t *net = NULL;
    uint status;
    cp_mme_tx_t *mme;

    dbg_assert (ctx);
    dbg_assert (sta);

    // Send the TEI MAP to the station.
    net = cp_sta_mgr_get_our_avln (ctx);

    if (!cp_net_is_empty (ctx, net))
    {
        peer = &CP_MME_PEER_ALL_STA;

        if (cp_sta_get_authenticated (ctx, sta))
        {
            status = CP_MSG_CC_SET_TEI_MAP_IND_STATUS_AUTHENTICATED;
        }
        else if (cp_sta_get_tei (sta))
        {
            status = CP_MSG_CC_SET_TEI_MAP_IND_STATUS_ASSOCIATED;
        }
        else
            status = CP_MSG_CC_SET_TEI_MAP_IND_STATUS_DISASSOCIATED;

        mme = cp_msg_cc_set_tei_map_ind_send_begin (ctx, peer,
                 CP_MSG_CC_SET_TEI_MAP_IND_MODE_DELETE,
                 1);
        cp_msg_cc_set_tei_map_ind_send_sta (ctx, mme, cp_sta_get_tei (sta),
                                            cp_sta_get_mac_address (sta),
                                            status);
        cp_msg_cc_set_tei_map_ind_send_end (ctx, mme);
    }
}

void
cp_av_cco_action_cco__cc_leave_req (cp_t *ctx, cp_mme_rx_t *mme)
{
    cp_sta_t *sta;
    cp_net_t *net;
    bool res_read;
    enum cp_msg_cc_leave_req_reason_t reason_req;
    cp_nid_t nid;
    enum cp_msg_cc_leave_ind_reason_t reason_ind;


    dbg_assert (ctx);
    dbg_assert (mme);

    dbg_assert (mme->peer.tei);

    switch (mme->mmtype)
    {
    case CC_LEAVE_REQ:
        res_read = cp_msg_cc_leave_req_receive (ctx, mme, &reason_req);
        break;
    case CC_LEAVE_IND:
        res_read = cp_msg_cc_leave_ind_receive (ctx, mme, &reason_ind,
                                                &nid);
        break;
    default:
        dbg_assert_default ();
    }

    if (res_read)
    {
        net = cp_sta_mgr_get_our_avln (ctx);
        if (mme->mmtype == CC_LEAVE_REQ)
            cp_msg_cc_leave_cnf_send (ctx, &mme->peer);
        else
            cp_msg_cc_leave_rsp_send (ctx, &mme->peer);
        /* Get the station. */
        sta = cp_sta_mgr_sta_get_assoc (ctx, net, mme->peer.tei);
        if (sta)
        {
            cp_sta_mgr_release_station (ctx, cp_sta_get_tei (sta));
            cp_av_cco_action_cco_sta_leave_send_tei_map (ctx, sta);
            slab_release (sta);
        }
    }
}

void
cp_av_cco_action_drv_mac_stop (cp_t *ctx)
{
    dbg_assert (ctx);
    dbg_assert (cp_sta_own_data_get_cco_status (ctx));

    if (!cp_net_is_empty (ctx, cp_sta_mgr_get_our_avln (ctx))
        && (!cp_beacon_any_countdown_active (ctx)))
    {
        cp_sta_t *sta;
        cp_net_t *net;

        /* Clear the SET of cco selection. */
        cp_av_cco_action_cco_selection__clear (ctx);
        ctx->handover.reason = CP_HANDOVER_REASON_CCO_LEAVING;

        net = cp_sta_mgr_get_our_avln (ctx);
        for (sta = cp_net_sta_get_first (ctx, net, CP_NET_STA_ASSOC);
             sta;
             sta = cp_net_sta_get_next (ctx, net, sta))
        {
            if (cp_sta_get_authenticated (ctx, sta))
                cp_av_cco_action_cco_selection__mac_stop_sta_add (ctx, sta);
        }

        /* Trigger the event to start the handover CCo FSM. */
        cp_fsm_trigger_new_event (ctx, bare, CCO_HANDOVER_START);
        /* Trigger an event to change the Main FSM to go to the
         * CCO_LEAVING_HOIP state. */
        cp_fsm_trigger_new_event (ctx, bare, CCO_LEAVING_HANDOVER);
    }
    else if (cp_net_is_empty (ctx, cp_sta_mgr_get_our_avln (ctx))
             && (!cp_beacon_any_countdown_active (ctx)))
        cp_fsm_trigger_new_event (ctx, bare, cco__all_sta_leaved);
}

void
cp_av_cco_action_drv_mac_stop_suspend (cp_t *ctx)
{
    cp_beacon_cco_update_beacon_data (ctx);
    cp_av_cco_action_drv_mac_stop (ctx);
}

void
cp_av_cco_action_drv_mac_stop_ended (cp_t *ctx)
{
    dbg_assert (ctx);
    cp_av_cco_action_cco__assoc_stop (ctx);
    cp_fsm_trigger_new_event (ctx, bare, to_stop);
}

void
cp_av_cco_action_ucco__to_stop (cp_t *ctx)
{
    dbg_assert (ctx);
    cp_av_cco_action_ucco_stop (ctx);
    cp_fsm_trigger_new_event (ctx, bare, to_stop);
}

void
cp_av_cco_action_cco_selection__mac_stop_sta_add (cp_t *ctx, cp_sta_t *sta)
{
    dbg_assert (ctx);
    dbg_assert (sta);

    slab_addref (sta);
    heap_node_init (&sta->cco_selection_node);
    heap_insert (&ctx->cco_action.selection_heap,
                 &sta->cco_selection_node);
}


void
cp_av_cco_action_cco_selection__sta_add (cp_t *ctx, cp_net_t *net, cp_sta_t *sta)
{
    cp_sta_own_data_t *own;
    dbg_assert (ctx);
    dbg_assert (net);
    dbg_assert (sta);

    if ((net == cp_sta_mgr_get_our_avln (ctx))
        && (MAC_TEI_IS_STA (cp_sta_get_tei (sta)))
        && (cp_sta_get_authenticated (ctx, sta)))
    {
        own = cp_sta_mgr_get_sta_own_data (ctx);
        if (own->cco_prefered == false
            && sta->cco_cap > CP_CCO_LEVEL)
        {
            slab_addref (sta);
            heap_node_init (&sta->cco_selection_node);
            heap_insert (&ctx->cco_action.selection_heap,
                        &sta->cco_selection_node);
        }
    }
}

void
cp_av_cco_action_cco_selection__sta_remove (cp_t *ctx, cp_sta_t *sta)
{
    dbg_assert (ctx);
    dbg_assert (sta);

    dbg_assert (!heap_empty (&ctx->cco_action.selection_heap));

    heap_remove (&ctx->cco_action.selection_heap, &sta->cco_selection_node);
    heap_node_init (&sta->cco_selection_node);
    slab_release (sta);
}

void
cp_av_cco_action_cco_selection__clear (cp_t *ctx)
{
    cp_sta_t *sta;
    heap_node_t *node;

    dbg_assert (ctx);

    /* Verify the set. */
    while (!heap_empty (&ctx->cco_action.selection_heap))
    {
        node = heap_get_root (&ctx->cco_action.selection_heap);
        dbg_assert (node);

        sta = PARENT_OF (cp_sta_t, cco_selection_node, node);
        dbg_assert (sta);

        /* Remove the node from the heap. */
        heap_remove (&ctx->cco_action.selection_heap, &sta->cco_selection_node);
        heap_node_init (&sta->cco_selection_node);
        slab_release (sta);
    }
}

cp_sta_t *
cp_av_cco_action_cco_selection__selection (cp_t *ctx)
{
    cp_sta_own_data_t *own;
    cp_sta_t *sta = NULL;
    heap_node_t *node;
    dbg_assert (ctx);

    own = cp_sta_mgr_get_sta_own_data (ctx);

    if ((!own->cco_prefered)
        && (!heap_empty (&ctx->cco_action.selection_heap)))
    {
        node = heap_get_root (&ctx->cco_action.selection_heap);
        dbg_assert (node);

        sta = PARENT_OF (cp_sta_t, cco_selection_node, node);
        dbg_assert (sta);
        slab_addref (sta);
    }

    return sta;
}

void
cp_av_cco_action_sc__sc_cco__cc_assoc_req (cp_t *ctx, cp_mme_rx_t *mme)
{
    /* Check parameters. */
    dbg_assert (ctx);
    dbg_assert (mme);

    /* Check received MME.  */
    cp_msg_cc_assoc_req_t req;
    if (!cp_msg_cc_assoc_req_receive (ctx, mme, &req))
    {
        /* Error in the MME, do nothing. */
    }
    else
    {
        if (req.request_type == CP_MSG_CC_ASSOC_REQ_TYPE_NEW)
        {
            /* Request of association. */
            /* Peer is SC? */
            if (mme->peer.mac == ctx->sta_action.sc.peer.mac)
            {
                /* Ok, reply  */
                cp_av_cco_action__assoc__join (ctx, mme, &req);
                cp_sta_t *sta = cp_sta_mgr_sta_get_from_mac (ctx, ctx->sta_action.sc.peer.mac);
                ctx->sta_action.sc.peer.tei = cp_sta_get_tei (sta);
                slab_release (sta);
            }
            else
            {
                /* Deny assoc request. */
                cp_msg_cc_assoc_cnf_t cnf;
                cnf.result = CP_MSG_CC_ASSOC_CNF_RESULT_FAILURE_OTHER_REASON;
                /* Get our net. */
                cp_net_t *net = cp_sta_mgr_get_our_avln (ctx);
                /* Set NID/SNID. */
                cnf.nid = cp_net_get_nid (ctx, net);
                cnf.snid = cp_net_get_snid (ctx, net);
                /* No TEI for the STA. */
                cnf.sta_tei = 0;
                /* Lease default value. */
                cnf.lease_time_min = CP_LEASE_ASSOC_MIN;
                /* Send reply. */
                cp_msg_cc_assoc_cnf_send (ctx, &mme->peer, &cnf);
            }
        }
        else if (req.request_type == CP_MSG_CC_ASSOC_REQ_TYPE_RENEW)
            /* Renew is ok. */
            cp_av_cco_action__assoc__renew (ctx, mme, &req);
        else
            /* Should not occur. */
            dbg_assert (req.request_type == CP_MSG_CC_ASSOC_REQ_TYPE_NB);
    }
}

void
cp_av_cco_action_handover__ended (cp_t *ctx)
{
    cp_av_cco_action_cco_selection__clear (ctx);
    cp_av_cco_action_cco__assoc_stop (ctx);
}

/**
 * Last transaction ends try next STA.
 * \param  ctx  the module context.
 * \return  The next station to start a transaction with.
 */
static cp_sta_t*
cp_av_cco_action_nek_next_sta (cp_t *ctx)
{
    cp_sta_t *sta;
    cp_sta_t *sta_next;
    cp_net_t *net;
    dbg_assert (ctx);

    net = cp_sta_mgr_get_our_avln (ctx);

    if ((sta = cp_sta_mgr_sta_get_from_mac (ctx,
                                ctx->cco_action.eks_sta_current_peer.mac)))
    {
        sta_next = cp_net_sta_get_next (ctx, net, sta);

        if (sta_next)
        {
            cp_sta_get_peer (sta_next, &ctx->cco_action.eks_sta_current_peer);
            return sta_next;
        }
        return NULL;
    }

    return NULL;
}

/**
 * Request the station for the NEK change.
 * \param  ctx  the module context.
 * \param  sta  the station to start the NEK exchange.
 */
static void
cp_av_cco_action_nek_change_start_transaction (cp_t *ctx, cp_sta_t *sta)

{
    cp_msg_cm_set_key_req_t data;
    cp_fsm_event_t *event;

    dbg_assert (ctx);
    dbg_assert (sta);

    /* Get the station peer to send the MME. */
    cp_sta_get_peer (sta, &ctx->cco_action.eks_sta_current_peer);

    /* Initialise the protocol run. */
    cp_secu_protocol_run_new (&ctx->cco_action.eks_prun, 1,
                              &ctx->rnd);

    /* Fill the data structure with key type == NONCE_ONLY. */
    memset (&data, 0, sizeof (cp_msg_cm_set_key_req_t));
    data.key_type = CP_MSG_KEY_NONCE_ONLY;
    data.cco_cap = CP_CCO_LEVEL;
    data.nid = cp_sta_own_data_get_nid (ctx);

    /* Send the MME. */
    cp_msg_cm_set_key_req_send (ctx,
                                &ctx->cco_action.eks_sta_current_peer,
                                CP_MME_PEKS_NONE,
                                &ctx->cco_action.eks_prun,
                                &data);

    /* Start the timeout timer. */
    event = cp_fsm_event_bare_new (ctx, CP_FSM_EVENT_TYPE_cco_nek_change__nek_timeout);
    cp_sta_core_gen_timed_event(ctx,
                                &ctx->cco_action.eks_timer,
                                event,
                                CP_CCO_ACTION_EKS_TIMEOUT_MS);
}

void
cp_av_cco_action_cco__cco_nek_change__nek_provide (cp_t *ctx)
{
    cp_net_t *net;
    cp_sta_t *sta;
    dbg_assert (ctx);
    net = cp_sta_mgr_get_our_avln (ctx);
    sta = cp_net_sta_get_first (ctx, net, CP_NET_STA_ASSOC);
    /* If the current STA is not authenticated, it is not necessary to send
     * the MME. */
    while (sta && !cp_sta_get_authenticated (ctx, sta))
        sta = cp_net_sta_get_next (ctx, net, sta);
    if (sta)
    {
        cp_av_cco_action_nek_change_start_transaction (ctx, sta);
        slab_release (sta);
        /* Change branch. */
        cp_fsm_branch (ctx, CCO_NEK_CHANGE_IDLE, cco_nek_change__nek_provide, sta);
    }
    else
        cp_fsm_branch (ctx, CCO_NEK_CHANGE_IDLE, cco_nek_change__nek_provide, nosta);
}

void
cp_av_cco_action_cco__cco_nek_change__nek_timeout__wait (cp_t *ctx)
{
    cp_sta_t *sta;
    dbg_assert (ctx);

    /* Stop the time out timer. */
    cp_sta_core_stop_timed_or_cyclic_event (ctx, &ctx->cco_action.eks_timer);

    if ((sta = cp_av_cco_action_nek_next_sta (ctx)))
    {
        cp_av_cco_action_nek_change_start_transaction (ctx, sta);
        slab_release (sta);

        cp_fsm_branch (ctx, CCO_NEK_CHANGE_WAIT_STA_CNF,
                       cco_nek_change__nek_timeout, yes);
    }
    else
    {
        cp_fsm_branch (ctx, CCO_NEK_CHANGE_WAIT_STA_CNF,
                       cco_nek_change__nek_timeout, no);
    }
}

void
cp_av_cco_action_cco__cco_nek_change__timeout (cp_t *ctx)
{
    cp_sta_t *sta;
    dbg_assert (ctx);

    /* Stop the time out timer. */
    cp_sta_core_stop_timed_or_cyclic_event (ctx, &ctx->cco_action.eks_timer);

    if ((sta = cp_av_cco_action_nek_next_sta (ctx)))
    {
        cp_av_cco_action_nek_change_start_transaction (ctx, sta);
        slab_release (sta);

        cp_fsm_branch (ctx, CCO_NEK_CHANGE_PROCESS_CM_SET_KEY_CNF,
                       cco_nek_change__nek_timeout, yes);
    }
    else
    {
        cp_fsm_branch (ctx, CCO_NEK_CHANGE_PROCESS_CM_SET_KEY_CNF,
                       cco_nek_change__nek_timeout, no);
    }
}

void
cp_av_cco_action_cm_set_key_cnf_receive (cp_t *ctx, cp_mme_rx_t *mme)
{
    cp_msg_cm_set_key_cnf_t data;
    dbg_assert (ctx);
    dbg_assert (mme);

    /* Stop the time out timer. */
    cp_sta_core_stop_timed_or_cyclic_event (ctx, &ctx->cco_action.eks_timer);

    if ((cp_msg_cm_set_key_cnf_receive (ctx, mme, &data)
         && (cp_secu_protocol_check
             (&ctx->cco_action.eks_prun, &mme->prun,
              CP_SECU_PROTOCOL_RUN_CHECK_RESULT_NEXT)))
        && ((mme->prun.pid == 1) && (mme->prun.pmn == 2)))
    {
        uint i;
        cp_msg_cm_set_key_req_t data_req;
        cp_fsm_event_t *event;

        data_req.key_type = CP_MSG_KEY_NEK;
        data_req.cco_cap = CP_CCO_LEVEL;
        data_req.nid = cp_sta_own_data_get_nid (ctx);
        data_req.new_eks = bsu_nek_index_current (ctx->bsu);
        for (i = 0; i < COUNT (ctx->cco_action.nek_new.key); i++)
            data_req.new_key.key[i] = ctx->cco_action.nek_new.key[i];


        /* Prepare the EKS NEK exchange. */
        ctx->cco_action.eks_prun = mme->prun;
        cp_secu_protocol_next (&ctx->cco_action.eks_prun, &ctx->rnd,
                               false /* not last*/);

        cp_msg_cm_set_key_req_send (ctx,
                                    &ctx->cco_action.eks_sta_current_peer,
                                    CP_MME_PEKS_NMK,
                                    &ctx->cco_action.eks_prun,
                                    &data_req);

        /* Start the timeout timer. */
        event = cp_fsm_event_bare_new (
            ctx, CP_FSM_EVENT_TYPE_cco_nek_change__nek_timeout);
        cp_sta_core_gen_timed_event(ctx,
                                    &ctx->cco_action.eks_timer,
                                    event,
                                    CP_CCO_ACTION_EKS_TIMEOUT_MS);
    }
    /* Last message or error, try the next station.
     * If it was an error the STA is responsible to request the key when it
     * see the EKS bentry in the central beacon. */
    else
    {
        cp_sta_t *sta = cp_sta_mgr_sta_get_from_mac (ctx, mme->peer.mac);
        cp_net_t *net = cp_sta_mgr_get_our_avln (ctx);
        sta = cp_net_sta_get_next (ctx, net, sta);
        /* If the current STA is not authenticated, it is not necessary to send
         * the MME. */
        while (sta && !cp_sta_get_authenticated (ctx, sta))
            sta = cp_net_sta_get_next (ctx, net, sta);
        if (sta)
        {
            cp_av_cco_action_nek_change_start_transaction (ctx, sta);
            slab_release (sta);

            cp_fsm_branch (ctx, CCO_NEK_CHANGE_PROCESS_CM_SET_KEY_CNF,
                           CM_SET_KEY_CNF_PID1, ok_continue);
        }
        else
        {
            cp_fsm_branch (ctx, CCO_NEK_CHANGE_PROCESS_CM_SET_KEY_CNF,
                           CM_SET_KEY_CNF_PID1, end);
        }
    }
}

void
cp_av_cco_action_nek_change_prevent (cp_t *ctx)
{
    dbg_assert (ctx);

    /* If there is no new EKS then do not change it.
     * This disallow the stations to store a false nek in mac config. */
    if (cp_sta_own_data_get_cco_status (ctx))
    {
        cp_beacon_change_nek (ctx,
                              bsu_nek_index_next (ctx->bsu),
                              ctx->cco_action.nek_new,
                              false /* central beacon change.  */);
    }
}

void
cp_av_cco_action_cco__cc_discover_list_req (cp_t *ctx, cp_net_t *net,
                                         cp_sta_t *sta)
{
    dbg_assert (ctx);
    cp_mme_peer_t peer;
    cp_sta_get_peer (sta, &peer);
    cp_msg_cc_discover_list_req_send (ctx, &peer);
}

void
cp_av_cco_action_beacon_with_same_nid (
    cp_t *ctx, bsu_beacon_t *beacon, cp_net_t *net, cp_sta_t *sta)
{
    dbg_assert (beacon);

    /* If we have the highest mac address we do nothing. */
    if (beacon->bmis.mac_address.present)
        if (MAC_REVERSE (beacon->bmis.mac_address.mac_address) <
            MAC_REVERSE (cp_sta_own_data_get_mac_address (ctx)))
            return;

    /* To merge the two avlns we shut our network by turning the cco into
     * an unassociated sta. */
    cp_fsm_post_new_event (ctx, bare, cco_leave_merge_avln);
}