File: ClntTransMgr.cpp

package info (click to toggle)
dibbler 1.0.1-2
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 13,352 kB
  • sloc: cpp: 60,323; ansic: 12,235; sh: 11,951; yacc: 3,418; lex: 969; makefile: 940; perl: 319; xml: 116; python: 74
file content (1560 lines) | stat: -rw-r--r-- 50,135 bytes parent folder | download | duplicates (3)
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
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
/*
 * Dibbler - a portable DHCPv6
 *
 * authors: Tomasz Mrugalski <thomson@klub.com.pl>
 *          Marek Senderski <msend@o2.pl>
 * changes: Krzysztof Wnuk <keczi@poczta.onet.pl>
 *          Michal Kowalczuk <michal@kowalczuk.eu>
 *
 * released under GNU GPL v2 only licence
 *
 */

#include <iostream>
#include <string>

#include "ClntTransMgr.h"
#include "ClntAddrMgr.h"
#include "ClntCfgMgr.h"
#include "ClntCfgPD.h"
#include "ClntMsgAdvertise.h"
#include "ClntMsgRequest.h"
#include "ClntMsgRenew.h"
#include "ClntMsgRebind.h"
#include "ClntMsgReply.h"
#include "ClntMsgRelease.h"
#include "ClntMsgSolicit.h"
#include "ClntMsgInfRequest.h"
#include "ClntMsgDecline.h"
#include "ClntMsgConfirm.h"
#include "ClntMsgReconfigure.h"
#include "Container.h"
#include "DHCPConst.h"
#include "Logger.h"

using namespace std;

TClntTransMgr * TClntTransMgr::Instance = 0;

void TClntTransMgr::instanceCreate(const std::string& config)
{
    if (Instance) {
        Log(Crit) << "ClntTransMgr instance already exists. Internal code error!" << LogEnd;
        return;
    }
    Instance = new TClntTransMgr(config);
}

TClntTransMgr &TClntTransMgr::instance()
{
    if (!Instance) {
        Log(Crit) << "Error: ClntTransMgr not initialized. Trying to recover." << LogEnd;
        instanceCreate(CLNTTRANSMGR_FILE);
    }
    return *Instance;
}

TClntTransMgr::TClntTransMgr(const std::string& config)
  :IsDone(true), Shutdown(true), CtrlIface_(-1)
{
    // should we set REUSE option during binding sockets?
#ifdef MOD_CLNT_BIND_REUSE
    BindReuse = true;
#else
    BindReuse = false;
#endif

    if (this->BindReuse)
        Log(Debug) << "Bind reuse enabled (multiple instances allowed)." << LogEnd;
    else
        Log(Debug) << "Bind reuse disabled (multiple instances not allowed)." << LogEnd;

    if (!this->openLoopbackSocket()) {
        return;
    }

    SPtr<TClntCfgIface> iface;
    ClntCfgMgr().firstIface();
    while(iface=ClntCfgMgr().getIface()) {
        if (!populateAddrMgr(iface))
            return;

        if (!this->openSockets(iface)) {
            return;
        }
    }

    checkDB();
    ClntIfaceMgr().dump();

    Shutdown = false;
    IsDone = false;
}

bool TClntTransMgr::populateAddrMgr(SPtr<TClntCfgIface> iface)
{
    // create IAs in AddrMgr corresponding to those specified in CfgMgr.
    SPtr<TClntCfgIA> ia;
    iface->firstIA();
    while(ia = iface->getIA()) {
        if (ClntAddrMgr().getIA(ia->getIAID()))
            continue; // there is such IA already - read from disk cache (client-AddrMgr.xml)
        SPtr<TAddrIA> addrIA = new TAddrIA(iface->getName(), iface->getID(), IATYPE_IA,
                                           SPtr<TIPv6Addr>(), SPtr<TDUID>(),
                                           ia->getT1(), ia->getT2(), ia->getIAID());
        ClntAddrMgr().addIA(addrIA);
    }

    SPtr<TClntCfgTA> ta;
    iface->firstTA();
    if ( (ta = iface->getTA()) &&  (!ClntAddrMgr().getTA(ta->getIAID())))
    {
        // if there is such TA already, then skip adding it
        SPtr<TAddrIA> addrTA = new TAddrIA(iface->getName(), iface->getID(), IATYPE_TA,
                                           SPtr<TIPv6Addr>(), SPtr<TDUID>(),
                                           DHCPV6_INFINITY, DHCPV6_INFINITY,
                                           ta->getIAID());
        ClntAddrMgr().addTA(addrTA);
    }

    SPtr<TClntCfgPD> pd;
    iface->firstPD();
    while (pd = iface->getPD()) {
        if (ClntAddrMgr().getPD(pd->getIAID()))
            continue; // there is such IA already - read from disk cache (client-AddrMgr.xml)
        SPtr<TAddrIA> addrPD = new TAddrIA(iface->getName(), iface->getID(), IATYPE_PD,
                                           SPtr<TIPv6Addr>(), SPtr<TDUID>(),
                                           pd->getT1(), pd->getT2(),
                                           pd->getIAID());
        ClntAddrMgr().addPD(addrPD);
    }

    return true;
}

bool TClntTransMgr::openSockets(SPtr<TClntCfgIface> iface) {

    if (iface->noConfig())       
        return true;
    
    // open socket
    SPtr<TIfaceIface> realIface = ClntIfaceMgr().getIfaceByID(iface->getID());
    if (!realIface) {
            Log(Error) << "Interface " << iface->getFullName()
                           << " not present in system." << LogEnd;
        return false;
    }
    if (!realIface->flagUp()) {
        Log(Error) << "Interface " << realIface->getFullName()
                   << " is down. Unable to open socket." << LogEnd;
        return false;
    }
    if (!realIface->flagRunning()) {
        Log(Error) << "Interface " << realIface->getFullName()
                   << " is not running." << LogEnd;
        return false;
    }
    
    // get link-local address
    char* llAddr;
    realIface->firstLLAddress();
    llAddr=realIface->getLLAddress();
    if (!llAddr) {
        Log(Error) << "Interface " << realIface->getFullName()
                   << " does not have link-layer address. Weird." << LogEnd;
        return false;
    }

    // By default, we use the first link-local address on the interface
    SPtr<TIPv6Addr> addr = new TIPv6Addr(llAddr);

    // However, if the user specified bind-to address, we'll use that instead.
    if (iface->getBindToAddr()) {
        addr = iface->getBindToAddr();
        Log(Debug) << "Using bind-to address " << addr->getPlain() << " on interface "
                   << iface->getFullName() << LogEnd;
    }

    // it's very important to open unicast socket first as it will be used for
    // unicast communication
    if (iface->getUnicast()) {
        Log(Notice) << "Creating socket for unicast communication on " << iface->getFullName()
                    << LogEnd;
        SPtr<TIPv6Addr> anyaddr = new TIPv6Addr("::", true); // don't bind to a specific address
        if (!realIface->addSocket(anyaddr, DHCPCLIENT_PORT, false, this->BindReuse)) {
            Log(Crit) << "Unicast socket creation (addr=" << anyaddr->getPlain() << ") on " 
                      << iface->getFullName() << " interface failed." << LogEnd;
            return false;
        }

    }

    Log(Notice) << "Creating socket (addr=" << *addr << ") on " 
                << iface->getFullName() << " interface." << LogEnd;
    if (!realIface->addSocket(addr,DHCPCLIENT_PORT,true, this->BindReuse)) {
        Log(Crit) << "Socket creation (addr=" << *addr << ") on " 
                  << iface->getFullName() << " interface failed." << LogEnd;
        return false;
    }

    if (llAddr) {
        char buf[48];
        inet_ntop6(llAddr,buf);
        CtrlIface_ = realIface->getID();
        strncpy(CtrlAddr_, buf, 48);
    } 

    return true;
}

/** this function removes expired addresses from interface and from database
 *  It must be called before AddrMgr::doDuties() is called.
 */
void TClntTransMgr::removeExpired() {

    /// @todo: call notify-script when address/prefix is expired
    TNotifyScriptParams params;

    if (ClntAddrMgr().getValidTimeout())
        return;

    SPtr<TAddrIA> ptrIA;
    SPtr<TAddrAddr> ptrAddr;
    SPtr<TIfaceIface> ptrIface;

    // are there any expired IA_NAs?
    ClntAddrMgr().firstIA();
    while (ptrIA = ClntAddrMgr().getIA()) {
        if (ptrIA->getValidTimeout())
            continue;

        ptrIA->firstAddr();
        while (ptrAddr = ptrIA->getAddr()) {
            if (ptrAddr->getValidTimeout())
                continue;
            ptrIface = ClntIfaceMgr().getIfaceByID(ptrIA->getIfindex());
            Log(Warning) << "Address " << ptrAddr->get()->getPlain() << " assigned to the "
                         << ptrIface->getFullName()
                         << " interface (in IA_NA " << ptrIA->getIAID() <<") has expired." << LogEnd;

            // remove that address from the physical interace
            ptrIface->delAddr(ptrAddr->get(), ptrIface->getPrefixLength());

	    // Note: Technically, removing address here is not needed, as it will
	    // be removed in AddrMgr::doDuties() anyway
	    ptrIA->delAddr(ptrAddr->get());
	    Log(Info) << "Expired address " << ptrAddr->get()->getPlain()
		      << " from IA " << ptrIA->getIAID()
		      << " has been removed from addrDB." << LogEnd;
        }

	// if there are no more addresses in this IA, declare it freed
	if (!ptrIA->countAddr()) {
	    Log(Debug) << "The IA_NA (with IAID=" << ptrIA->getIAID() << ") has expired. " << LogEnd;
	    SPtr<TClntCfgIface> cfgIface = ClntCfgMgr().getIface(ptrIA->getIfindex());
	    if (cfgIface) {
		SPtr<TClntCfgIA> cfgIA = cfgIface->getIA(ptrIA->getIAID());
		if (cfgIA) {
		    cfgIA->setState(STATE_NOTCONFIGURED);
		}
	    } else {
		// something is terribly wrong here
	    }
	}
    }

    // are there any expired IA_TAs?
    ClntAddrMgr().firstTA();
    while (ptrIA = ClntAddrMgr().getTA()) {
        if (ptrIA->getValidTimeout())
            continue;

        ptrIA->firstAddr();
        while (ptrAddr = ptrIA->getAddr()) {
            if (ptrAddr->getValidTimeout())
                continue;
            ptrIface = ClntIfaceMgr().getIfaceByID(ptrIA->getIfindex());
            Log(Warning) << "Temporary address " << ptrAddr->get()->getPlain() << " assigned to the "
                         << ptrIface->getFullName()
                         << " interface (in IA_TA " << ptrIA->getIAID() <<") has expired." << LogEnd;

            // remove that address from the physical interace
            ptrIface->delAddr(ptrAddr->get(), ptrIface->getPrefixLength());

	    // Note: Technically, removing address here is not needed, as it will
	    // be removed in AddrMgr::doDuties() anyway
	    ptrIA->delAddr(ptrAddr->get());
	    Log(Info) << "Expired temporary address " << ptrAddr->get()->getPlain()
		      << " from IA " << ptrIA->getIAID()
		      << " has been removed from addrDB." << LogEnd;
        }

	// if there are no more addresses in this IA, declare it freed
	if (!ptrIA->countAddr()) {
	    Log(Debug) << "The IA_TA (with IAID=" << ptrIA->getIAID() << ") has expired. " << LogEnd;
	    SPtr<TClntCfgIface> cfgIface = ClntCfgMgr().getIface(ptrIA->getIfindex());
	    if (cfgIface) {
                cfgIface->firstTA();
		SPtr<TClntCfgTA> cfgTA = cfgIface->getTA();
		if (cfgTA) {
		    cfgTA->setState(STATE_NOTCONFIGURED);
		}
	    } else {
		// something is terribly wrong here
	    }
	}
    }

    // are there any expired IA_PDs?
    SPtr<TAddrIA> ptrPD;
    SPtr<TAddrPrefix> ptrPrefix;
    ClntAddrMgr().firstPD();
    while (ptrPD = ClntAddrMgr().getPD()) {
        if (ptrPD->getValidTimeout())
            continue;

        ptrPD->firstPrefix();
        while (ptrPrefix = ptrPD->getPrefix()) {
            if (ptrPrefix->getValidTimeout())
                continue;
            ptrIface = ClntIfaceMgr().getIfaceByID(ptrPD->getIfindex());
            Log(Warning) << "Prefix " << ptrPrefix->get()->getPlain() << " obtained on the "
                         << ptrIface->getFullName()
                         << " interface (in IA_PD " << ptrPD->getIAID() <<") has expired." << LogEnd;

            // remove that address from the physical interace
	    ClntIfaceMgr().delPrefix(ptrPD->getIfindex(), ptrPrefix->get(), ptrPrefix->getLength(),
                &params);

	    // Note: Technically, removing address here is not needed, as it will
	    // be removed in AddrMgr::doDuties() anyway
	    ptrPD->delPrefix(ptrPrefix);
	    Log(Info) << "Expired prefix " << ptrPrefix->get()->getPlain() << "/" << ptrPrefix->getLength()
		      << " from IA_PD " << ptrPD->getIAID()
		      << " has been removed from addrDB." << LogEnd;
        }

	// if there are no more addresses in this IA, declare it freed
	if (!ptrPD->countPrefix()) {
	    Log(Debug) << "The IA_PD (with IAID=" << ptrPD->getIAID() << ") has expired. " << LogEnd;
	    SPtr<TClntCfgIface> cfgIface = ClntCfgMgr().getIface(ptrPD->getIfindex());
	    if (cfgIface) {
		SPtr<TClntCfgPD> cfgPD = cfgIface->getPD(ptrPD->getIAID());
		if (cfgPD) {
		    cfgPD->setState(STATE_NOTCONFIGURED);
		}
	    } else {
		// something is terribly wrong here
	    }
	}
    }

}

/** 
 * checks if loaded Address database is sane (i.e. does not reffer to non-existing interface)
 * 
 */
void TClntTransMgr::checkDB()
{
    SPtr<TClntCfgIface> iface;
    SPtr <TAddrIA> ptrIA;
    SPtr<TAddrAddr> ptrAddr;

    ClntAddrMgr().doDuties();
    ClntAddrMgr().firstIA();
    while ( ptrIA = ClntAddrMgr().getIA()) {
        iface = ClntCfgMgr().getIface( ptrIA->getIfindex() );
        if (!iface) {
            Log(Warning) << "IA (iaid=" << ptrIA->getIAID() 
                         << ") loaded from old file, but currently there is no iface with ifindex="
                                 << ptrIA->getIfindex();
            // IA with non-existent iface, purge iface
            ptrIA->firstAddr();
            while (ptrAddr = ptrIA->getAddr())
                ptrIA->delAddr( ptrAddr->get() );
            ptrIA->setState(STATE_NOTCONFIGURED);
            ClntAddrMgr().delIA(ptrIA->getIAID());
        }
    }
}

bool TClntTransMgr::openLoopbackSocket() {
    SPtr<TIfaceIface> ptrIface;

    if (!this->BindReuse)
        return true;

#ifndef WIN32
    SPtr<TIfaceIface> loopback;
    ClntIfaceMgr().firstIface();
    while (ptrIface=ClntIfaceMgr().getIface()) {
        if (!ptrIface->flagLoopback()) {
            continue;
            }
            loopback = ptrIface;
            break;
    }
    if (!loopback) {
           Log(Crit) << "Loopback interface not found!" << LogEnd;
           return false;
    }

    SPtr<TIPv6Addr> loopAddr = new TIPv6Addr("::", true);
    Log(Notice) << "Creating control (" << *loopAddr << ") socket on the " << loopback->getName() 
                << "/" << loopback->getID() << " interface." << LogEnd;

    if (!loopback->addSocket(loopAddr,DHCPCLIENT_PORT, false, true)) {
        Log(Crit) << "Proper socket creation failed." << LogEnd;
        return false;
    }
#endif
    return true;
}

/*
 * this method is called, when no message has been received, but some
 * action should be taken, e.g. RENEW transmission
 */
void TClntTransMgr::doDuties()
{
    // for each message on list, let it do its duties, if timeout is reached
    SPtr <TClntMsg> msg;
    Transactions.first();
    while(msg=Transactions.get())
    {
        if ((!msg->getTimeout())&&(!msg->isDone())) {
            Log(Info) << "Processing msg (" << msg->getName() << ",transID=0x"
                 << hex << msg->getTransID() << dec << ",opts:";
            SPtr<TOpt> ptrOpt;
            msg->firstOption();
            while (ptrOpt = msg->getOption()) {
                Log(Cont) << " " << ptrOpt->getOptType();
            }
            Log(Cont) << ")" << LogEnd;
            msg->doDuties();
        }
    }

    // now delete messages which are marked as done
    Transactions.first();
    while (msg = Transactions.get() ) {
        if (msg->isDone())
            Transactions.del();
    }

    if (ClntCfgMgr().inactiveMode())
    {
        SPtr<TClntCfgIface> x;
        x = ClntCfgMgr().checkInactiveIfaces();
        if (x) {
            if (!populateAddrMgr(x)) {
                Log(Error)<< "Call to populateAddrMgr() ended with error"
                          << " Following operation may be unstable!" << LogEnd;
            }
            if (!openSockets(x)) {
                Log(Crit) << "Attempt to bind activated interfaces failed."
                          << " Following operation may be unstable!" << LogEnd;
            }
        }
    }

    removeExpired();
    ClntAddrMgr().doDuties();

    ClntAddrMgr().dump();
    ClntIfaceMgr().dump();
    ClntCfgMgr().dump();

    if (!this->Shutdown && !this->IsDone) {

        // did we switched links lately?
        // are there any IAs to confirm?
        checkConfirm();
        
        // are there any tentative addrs?
        checkDecline();

        // are there any IAs or TAs to configure?
        checkSolicit();

        //is there any IA in Address manager, which has not sufficient number 
        //of addresses
        checkRequest();

        // are there any aging IAs or PDs?
        checkRenew();

        //Maybe we require only infromations concernig link
        checkInfRequest();

#ifdef MOD_REMOTE_AUTOCONF
        checkRemoteSolicits();
#endif

    } 
    
    // This method launch the DNS update, so the checkDecline has to be done before to ensure the ip address is valid
    ClntIfaceMgr().doDuties();

    if (this->Shutdown && !Transactions.count())
        this->IsDone = true;
}

void TClntTransMgr::shutdown()
{
    SPtr<TAddrIA> ptrFirstIA;
    SPtr<TAddrIA> ptrNextIA;
    SPtr<TAddrIA> ta;
    SPtr<TAddrIA> pd;
    SPtr<TClntCfgIface> iface;
    List(TAddrIA) releasedIAs;
    List(TAddrIA) releasedPDs;

    Transactions.clear(); // delete all transactions
    this->Shutdown = true;
    Log(Notice) << "Shutting down entire client." << LogEnd;
        
    // delete all weird-state/innormal-state and address-free IAs 
    ClntAddrMgr().firstIA();
    while (ptrFirstIA = ClntAddrMgr().getIA()) {
        if ( (ptrFirstIA->getState() != STATE_CONFIGURED && ptrFirstIA->getState() != STATE_INPROCESS) ||
            !ptrFirstIA->countAddr() )
            ClntAddrMgr().delIA(ptrFirstIA->getIAID()); 
    }

    // normal IAs are to be released
    while (ClntAddrMgr().countIA()) {
        // clear the list
        releasedIAs.clear();

        // get first IA
        ClntAddrMgr().firstIA();
        ptrFirstIA = ClntAddrMgr().getIA();
        releasedIAs.append(ptrFirstIA);
        ClntAddrMgr().delIA( ptrFirstIA->getIAID() );

        // find similar IAs 
        while (ptrNextIA = ClntAddrMgr().getIA()) {
            if ((*(ptrFirstIA->getDUID())==*(ptrNextIA->getDUID())) &&
                (ptrFirstIA->getIfindex() == ptrNextIA->getIfindex() ) ) 
            {
                // IA serviced via this same server, add it do the list
                releasedIAs.append(ptrNextIA);

                // delete addressess from IfaceMgr
                SPtr<TAddrAddr> ptrAddr;
                SPtr<TIfaceIface> ptrIface;
                ptrIface = ClntIfaceMgr().getIfaceByID(ptrNextIA->getIfindex());
                if (!ptrIface) {
                            Log(Error) << "Unable to find " << ptrNextIA->getIfindex()
                               << " interface while releasing address." << LogEnd;
                    break;
                }
                ptrNextIA->firstAddr();

                // delete IA from AddrMgr
                ClntAddrMgr().delIA( ptrNextIA->getIAID() );
            }
        }

        ta.reset();
        if (releasedIAs.count()) { 
            // check if there are TA to release
            releasedIAs.first();
            iface = ClntCfgMgr().getIface(releasedIAs.get()->getIfindex());
            if (iface && iface->countTA()) {
                iface->firstTA();
                SPtr<TClntCfgTA> cfgTA = iface->getTA();
                ta = ClntAddrMgr().getTA(cfgTA->getIAID());
                cfgTA->setState(STATE_DISABLED);
            }
        }

        pd.reset();
        ClntAddrMgr().firstPD();
        while (pd = ClntAddrMgr().getPD()) {
            releasedPDs.append(pd);
            SPtr<TClntCfgPD> cfgPD = ClntCfgMgr().getPD(pd->getIAID());
            if (cfgPD)
                cfgPD->setState(STATE_DISABLED);
        }
        sendRelease(releasedIAs, ta, releasedPDs);
    }

    // now check if there are any TA left
    ClntCfgMgr().firstIface();
    while (iface = ClntCfgMgr().getIface()) {
        if (iface->countTA()) {
            iface->firstTA();
            SPtr<TClntCfgTA> cfgTA = iface->getTA();
            ta = ClntAddrMgr().getTA(cfgTA->getIAID());
            releasedIAs.clear();
            if (!ta) {
                Log(Warning) << "Unable to find TA(taid=" << cfgTA->getIAID() <<"). " << LogEnd;
                continue;
            }
            if (cfgTA->getState()==STATE_CONFIGURED) {
                this->sendRelease(releasedIAs, ta, releasedPDs);
                cfgTA->setState(STATE_DISABLED);
            }
        }

    }

    // are there any PDs left to release?
    pd.reset();
    ClntAddrMgr().firstPD();
    releasedIAs.clear();
    releasedPDs.clear();
    while (pd = ClntAddrMgr().getPD()) {
        releasedPDs.append(pd);
        SPtr<TClntCfgPD> cfgPD = ClntCfgMgr().getPD(pd->getIAID());
        if (cfgPD)
            cfgPD->setState(STATE_DISABLED);
    }
    if (releasedPDs.count())
        this->sendRelease(releasedIAs, SPtr<TAddrIA>(), releasedPDs);
    
    //CHANGED:the following two lines are uncommented.
    doDuties(); // just to send RELEASE msg
    Transactions.clear(); // delete all transactions

    // clean up options
    ClntIfaceMgr().removeAllOpts();
}

void TClntTransMgr::relayMsg(SPtr<TClntMsg> msgAnswer)
{
    SPtr<TIfaceIface> ifaceQuestion;
    SPtr<TIfaceIface> ifaceAnswer;

    // is message valid?
    if (!msgAnswer->check())
        return ;

    if (msgAnswer->getType() == RECONFIGURE_MSG) {
        handleReconfigure(msgAnswer);
        return;
    }

#ifdef MOD_REMOTE_AUTOCONF
    if (neighborInfoGet(msgAnswer->getTransID())) {
        processRemoteReply(msgAnswer);
        return;
    }
#endif 
    
    // find which message this is answer for
    bool found = false;
    SPtr<TClntMsg> msgQuestion;
    Transactions.first();
    while(msgQuestion=(Ptr*)Transactions.get()) {
        if (msgQuestion->getTransID()==msgAnswer->getTransID()) {
            found =true;
            if (msgQuestion->getIface()!=msgAnswer->getIface()) {
                ifaceQuestion = ClntIfaceMgr().getIfaceByID(msgQuestion->getIface());
                ifaceAnswer   = ClntIfaceMgr().getIfaceByID(msgAnswer->getIface());
                Log(Warning) << "Reply for transaction 0x" << hex << msgQuestion->getTransID() << dec
                             << " sent on " << ifaceQuestion->getFullName() << " was received on interface " 
                             << ifaceAnswer->getFullName() << "." << LogEnd;
                // return; // don't return, just fix interface ID
                // useful, when sending thru eth0, but receiving via loopback
                msgAnswer->setIface(msgQuestion->getIface());
            }

            handleResponse(msgQuestion, msgAnswer);
            break;
        }
    }

    if (!found) 
    {
        if (!Shutdown)
            Log(Warning) << "Message with wrong transID (0x" << hex << msgAnswer->getTransID() << dec
                         << ") received. Ignoring." << LogEnd;
        else
            Log(Debug) << "Message with transID=0x" << hex << msgAnswer->getTransID() << dec
                       << " received, but ignored during shutdown." << LogEnd;
    } 
    ClntCfgMgr().dump();
    ClntAddrMgr().dump();
}

/// processes received RECONFIGURE message
///
/// Verifies that received message is valid. Depending on received option, it will
/// send RENEW, INF-REQUEST or REBIND message
///
/// @param reconfMsg pointer to received reconfigure message
///
void TClntTransMgr::handleReconfigure(SPtr<TClntMsg> reconfMsg) {
    // see if there is reconfigure-msg option. If not, drop message.
    // if yes, send specific message, e.g. call sendRenew(), sendRebind() or sendInfRequest()

    if(!ClntCfgMgr().getReconfigure()) {
        Log(Notice) << "Client is not configured to support reconfigure message." << LogEnd;
        return;
    }

    /// @todo: check authentication here

    /// @todo: server may tell client to send, RENEW, REBIND or INF-REQUEST
    Log(Notice) << "Received RECONFIGURE, sending RENEW." << LogEnd;
    sendRenew();
}

/** 
 * handle response
 * 
 * @param question 
 * @param answer 
 * 
 * @return 
 */
bool TClntTransMgr::handleResponse(SPtr<TClntMsg> question, SPtr<TClntMsg> answer)
{
    // pre-handling hooks can be added here

    // handle actual response
    question->answer(answer);

    // post-handling hooks can be added here
    SPtr<TMsg> q = (Ptr*) question;
    SPtr<TMsg> a = (Ptr*) answer;
    ClntIfaceMgr().notifyScripts(ClntCfgMgr().getScript(), q, a);

    if ( (question->getType()==REQUEST_MSG || question->getType()==SOLICIT_MSG) &&
         (answer->getType()==REPLY_MSG) ) {
        // we got actual configuration complete here	
    }

    return true;
}

unsigned long TClntTransMgr::getTimeout()
{
    unsigned long timeout = DHCPV6_INFINITY;
    unsigned long tmp;

    if (this->IsDone) 
        return 0;

    // AddrMgr timeout
    timeout = ClntAddrMgr().getTimeout();
    tmp     = ClntAddrMgr().getTentativeTimeout();
    if (timeout > tmp)
        timeout = tmp;
    // Uncomment for timeout debugging
    //Log(Debug) << "Timeout after AddrMgr=" << timeout << LogEnd;

    if (timeout == 0) {
	ClntAddrMgr().getTimeout();
    }

    // IfaceMgr (Lifetime option) timeout
    tmp = ClntIfaceMgr().getTimeout();
    if (timeout > tmp)
        timeout = tmp;
    // Uncomment for timeout debugging
    // Log(Debug) << "Timeout after IfaceMgr=" << timeout << LogEnd;

    // Messages timeout
    SPtr<TClntMsg> ptrMsg;
    Transactions.first();
    tmp = DHCPV6_INFINITY;
    while(ptrMsg=Transactions.get())
    {
        if (tmp > ptrMsg->getTimeout())
            tmp = ptrMsg->getTimeout();
    }
    if (timeout > tmp)
        timeout = tmp;

    if (ClntCfgMgr().inactiveIfacesCnt()) {
        if (timeout>INACTIVE_MODE_INTERVAL)
            timeout=INACTIVE_MODE_INTERVAL;
    }

    return timeout;
}

void TClntTransMgr::stop()
{
}

/**
 * Note: requestOptions list MUST NOT contain server DUID.
 */
void TClntTransMgr::sendRequest(TOptList requestOptions, int iface)
{
    sortAdvertiseLst();

    for (TOptList::iterator opt= requestOptions.begin();
         opt!=requestOptions.end(); ++opt)
    {
        if (!allowOptInMsg(REQUEST_MSG, (*opt)->getOptType()) ||
	    (*opt)->getOptType() == OPTION_AUTH)
            opt = requestOptions.erase(opt);
    }
    SPtr<TClntMsg> ptr = new TClntMsgRequest(requestOptions, iface);
    Transactions.append( (Ptr*)ptr );
}

void TClntTransMgr::sendRenew()
{
    // Find all IAs
    List(TAddrIA) iaLst;
    SPtr<TAddrIA> ia;
    SPtr<TAddrIA> iaPattern;
    ClntAddrMgr().firstIA();

    // Need to be fixed:?? how to deal with mutiple network interfaces.
    while (ia = ClntAddrMgr().getIA() ) {
        iaLst.append(ia);
        ia->setState(STATE_INPROCESS);
    }

    // Find all PDs
    List(TAddrIA) pdLst;
    ClntAddrMgr().firstPD();
    while (ia = ClntAddrMgr().getPD()) 
    {
        pdLst.append(ia);
        ia->setState(STATE_INPROCESS);
    }

    if (iaLst.count() + pdLst.count() == 0) {
	// there are no IAs or PD to refresh. Just do nothing.
	return;
    }
	 
    Log(Info) << "Generating RENEW for " << iaLst.count() << " IA(s) and " << pdLst.count() << " PD(s). " << LogEnd;
    SPtr <TClntMsg> ptrRenew = new TClntMsgRenew(iaLst, pdLst);
    Transactions.append(ptrRenew);
}


// Send RELEASE message
void TClntTransMgr::sendRelease( List(TAddrIA) IALst, SPtr<TAddrIA> ta, List(TAddrIA) pdLst)
{
    if ( !IALst.count() && !ta && !pdLst.count() ) {
        Log(Error) << "Unable to send RELEASE with empty IA list, PD list and no TA." << LogEnd;
        return;
    }

    // find interface and srv address
    int iface;
    SPtr<TIPv6Addr> addr;
    SPtr<TAddrIA> ptrIA;
    if (IALst.count()) {
            IALst.first();
            ptrIA = IALst.get();
            iface = ptrIA->getIfindex();
            addr  = ptrIA->getSrvAddr();
    } else if (pdLst.count()) {
            pdLst.first();
            ptrIA = pdLst.get();
            iface = ptrIA->getIfindex();
            addr  = ptrIA->getSrvAddr();
    } else if (ta) {
            iface = ta->getIfindex();
            addr  = ta->getSrvAddr();
    } else {
            Log(Error) << "Unable to send RELEASE message. No IA, PD or TA defined." << LogEnd;
            return;
    }

    SPtr<TClntCfgIface> ptrIface = ClntCfgMgr().getIface(iface);
    if (!ptrIface) {
            Log(Error) << "Unable to find interface with ifindex=" << iface << LogEnd;
            return;
    }
        
    Log(Notice) << "Creating RELEASE for " << IALst.count() << " IA(s), " 
                << pdLst.count() << " PD(s), "
                << (ta?" and TA":" (no TA)") << " on the " << ptrIface->getFullName() 
                << " interface." << LogEnd;

    SPtr<TClntMsg> ptr = new TClntMsgRelease(iface, addr, IALst, ta, pdLst);
    Transactions.append( ptr );
}

// Send REBIND message
void TClntTransMgr::sendRebind(TOptList requestOptions, int iface) {

    for (TOptList::iterator opt= requestOptions.begin();
         opt!=requestOptions.end(); ++opt)
    {
        if (!allowOptInMsg(REBIND_MSG, (*opt)->getOptType()))
            opt = requestOptions.erase(opt);
    }

    SPtr<TClntMsg> ptr =  new TClntMsgRebind(requestOptions, iface);
    if (!ptr->isDone())
        Transactions.append( ptr );
}

void TClntTransMgr::sendInfRequest(TOptList requestOptions, int iface) {

    for (TOptList::iterator opt= requestOptions.begin();
         opt!=requestOptions.end(); ++opt)
    {
        if (!allowOptInMsg(INFORMATION_REQUEST_MSG, (*opt)->getOptType()))
            opt = requestOptions.erase(opt);
    }

    SPtr<TClntMsg> ptr = new TClntMsgInfRequest(requestOptions,iface);
    if (!ptr->isDone())
        Transactions.append( ptr );    
}

// should we send SOLICIT ?
void TClntTransMgr::checkSolicit() {

    //For every iface, every group in iface in ClntCfgMgr 
    //Enumerate IA's from this group
    SPtr<TClntCfgIface> iface;
    ClntCfgMgr().firstIface();
    while( (iface=ClntCfgMgr().getIface()) )
    {
        if (iface->noConfig())
            continue;

        if (iface->stateless())
            continue;

        // step 1: check if there are any IA to be configured
        List(TClntCfgIA) iaLst; // list of IA requiring configuration
        SPtr<TClntCfgIA> cfgIA;
    
        iface->firstIA();
        while(cfgIA=iface->getIA())
        {
            // These not assigned in AddrMgr and configurable and not in 
            // trasaction group and pass to constructor of Solicit message
            if(cfgIA->getState()==STATE_NOTCONFIGURED)
                iaLst.append(cfgIA);
        }

        // step 2: check if TA has to be configured
        SPtr<TClntCfgTA> ta;
        if (iface->countTA() ) {
            iface->firstTA();
            ta = iface->getTA();
            if (ta->getState()!=STATE_NOTCONFIGURED)
                ta.reset();
        }

        // step 3: check if there are any PD to be configured
        List(TClntCfgPD) pdLst;
        SPtr<TClntCfgPD> pd;

        iface->firstPD();
        while ( pd = iface->getPD() ) {
            if (pd->getState()==STATE_NOTCONFIGURED) {
                pdLst.append(pd);
            }
        }

        //Are there any IA, TA or PD which should be configured?
        if (iaLst.count() || ta || pdLst.count()) {
            Log(Info) << "Creating SOLICIT message with " << iaLst.count()
                      << " IA(s), " << (ta?"1":"no") << " TA and " << pdLst.count()
                      << " PD(s)";
            if (iface->getRapidCommit()) {
                Log(Cont) << " (with rapid-commit)";
            } 
            Log(Cont) << " on " << iface->getFullName() <<" interface." << LogEnd;
            Transactions.append(new TClntMsgSolicit(iface->getID(),
                                                    SPtr<TIPv6Addr>(), iaLst, ta, pdLst, 
                                                    iface->getRapidCommit()));
	    
	    // state of certain IAs has changed. Let's log it.
	    ClntAddrMgr().dump();
	    ClntCfgMgr().dump();
        }

    }//for every iface
}

void TClntTransMgr::checkConfirm()
{
    SPtr<TAddrIA> ptrIA;
    SPtr<TClntCfgIface> iface;
    SPtr<TClntCfgIA> cfgIA;
    List(TAddrIA) IALst;

    ClntCfgMgr().firstIface();
    while(iface=ClntCfgMgr().getIface())
    {
        IALst.clear();
        iface->firstIA();
        while (cfgIA = iface->getIA()) {
            ClntAddrMgr().firstIA();
            while(ptrIA=ClntAddrMgr().getIA())
            {
                if (ptrIA->getState()!=STATE_CONFIRMME)	
                    continue;
                if (ptrIA->getIfindex()==iface->getID())
                {
                    IALst.append(ptrIA);
                    ptrIA->setState(STATE_INPROCESS);
                    cfgIA->setState(STATE_INPROCESS);
                }
            }
        }           

        if (IALst.count()) {
            Log(Info) << "Creating CONFIRM: " << IALst.count() << " IA(s) on " << iface->getFullName() << LogEnd;
            Transactions.append(
                new TClntMsgConfirm(iface->getID(), IALst));

	    // state of certain IAs has changed. Let's log it.
	    ClntAddrMgr().dump();
	    ClntCfgMgr().dump();
        }
    }
}

void TClntTransMgr::checkInfRequest()
{
    SPtr<TClntCfgIface> iface;
    ClntCfgMgr().firstIface();
    while( (iface=ClntCfgMgr().getIface()) )
    {
        if (iface->noConfig())
            continue;

        SPtr<TClntIfaceIface> ifaceIface = (Ptr*)ClntIfaceMgr().getIfaceByID(iface->getID());
        if (!ifaceIface) {
            Log(Error) << "Interface with ifindex=" << iface->getID() << " not found." << LogEnd;
            continue;
        }
        if (!ifaceIface->getTimeout()) {
            if (iface->getDNSServerState()  == STATE_CONFIGURED) 
                iface->setDNSServerState(STATE_NOTCONFIGURED);
            if (iface->getDomainState()     == STATE_CONFIGURED) 
                iface->setDomainState(STATE_NOTCONFIGURED);
            if (iface->getNTPServerState()  == STATE_CONFIGURED) 
                iface->setNTPServerState(STATE_NOTCONFIGURED);
            if (iface->getTimezoneState()   == STATE_CONFIGURED) 
                iface->setTimezoneState (STATE_NOTCONFIGURED);
            if (iface->getSIPServerState()  == STATE_CONFIGURED) 
                iface->setSIPServerState(STATE_NOTCONFIGURED);
            if (iface->getSIPDomainState()  == STATE_CONFIGURED) 
                iface->setSIPDomainState(STATE_NOTCONFIGURED);
            if (iface->getFQDNState()       == STATE_CONFIGURED) 
                iface->setFQDNState(STATE_NOTCONFIGURED);
            if (iface->getNISServerState()  == STATE_CONFIGURED) 
                iface->setNISServerState(STATE_NOTCONFIGURED);
            if (iface->getNISDomainState()  == STATE_CONFIGURED) 
                iface->setNISDomainState(STATE_NOTCONFIGURED);
            if (iface->getNISPServerState() == STATE_CONFIGURED) 
                iface->setNISPServerState(STATE_NOTCONFIGURED);
            if (iface->getNISPDomainState() == STATE_CONFIGURED) 
                iface->setNISPDomainState(STATE_NOTCONFIGURED);
            if (iface->getKeyGenerationState() == STATE_CONFIGURED) 
                iface->setKeyGenerationState(STATE_NOTCONFIGURED);
        }

        if ( (iface->getDNSServerState()     == STATE_NOTCONFIGURED) ||
             (iface->getDomainState()        == STATE_NOTCONFIGURED) ||
             (iface->getNTPServerState()     == STATE_NOTCONFIGURED) ||
             (iface->getTimezoneState()      == STATE_NOTCONFIGURED) ||
             (iface->getSIPServerState()     == STATE_NOTCONFIGURED) ||
             (iface->getSIPDomainState()     == STATE_NOTCONFIGURED) ||
             (iface->getFQDNState()          == STATE_NOTCONFIGURED) ||
             (iface->getNISServerState()     == STATE_NOTCONFIGURED) ||
             (iface->getNISDomainState()     == STATE_NOTCONFIGURED) ||
             (iface->getNISPServerState()    == STATE_NOTCONFIGURED) ||
             (iface->getNISPDomainState()    == STATE_NOTCONFIGURED)
         )
        {
            Log(Info) << "Creating INFORMATION-REQUEST message on "
                      << iface->getFullName() << " interface." << LogEnd;
            Transactions.append(new TClntMsgInfRequest(iface));
        }
    }
}

void TClntTransMgr::checkRenew()
{
    // are there any IAs which require RENEW?
    if (ClntAddrMgr().getT1Timeout() > 0 ) 
        return;

    // TENTATIVE_YES, there are. Find them!
    
    // Find all IAs
    List(TAddrIA) iaLst;
    SPtr<TAddrIA> ia;
    SPtr<TAddrIA> iaPattern;
    ClntAddrMgr().firstIA();

    // Need to be fixed:?? how to deal with mutiple network interfaces.
    while (ia = ClntAddrMgr().getIA() ) 
    {
        if ( (ia->getT1Timeout()!=0) || 
             (ia->getState()!=STATE_CONFIGURED) ||
             (ia->getTentative()==ADDRSTATUS_UNKNOWN) )
            continue;
        
        if (!iaPattern) {
            iaPattern = ia;
            iaLst.append(ia);
            ia->setState(STATE_INPROCESS);
            continue;
        }

        if ( (ia->getIfindex() == iaPattern->getIfindex()) &&
             (ia->getDUID()  == iaPattern->getDUID()) )
        {
                iaLst.append(ia);
                ia->setState(STATE_INPROCESS);
        }
    }

    // Find all PDs
    List(TAddrIA) pdLst;
    ClntAddrMgr().firstPD();
    while (ia = ClntAddrMgr().getPD()) {
        if ( (ia->getT1Timeout()!=0) || 
             (ia->getState()!=STATE_CONFIGURED) )
            continue;
        
        if (!iaPattern) {
            iaPattern = ia;
            pdLst.append(ia);
            ia->setState(STATE_INPROCESS);
            continue;
        }

        if ( (ia->getIfindex() == iaPattern->getIfindex()) &&
             (ia->getDUID()  == iaPattern->getDUID()) )
        {
                pdLst.append(ia);
                ia->setState(STATE_INPROCESS);
        }
    }

    if (iaLst.count() + pdLst.count() == 0) {
        // there are no IAs or PD to refresh. Just do nothing.
        return;
    }
         
    Log(Info) << "Generating RENEW for " << iaLst.count() << " IA(s) and " << pdLst.count() << " PD(s). " << LogEnd;
    SPtr <TClntMsg> ptrRenew = new TClntMsgRenew(iaLst, pdLst);
    Transactions.append(ptrRenew);

    // state of certain IAs has changed. Let's log it.
    ClntAddrMgr().dump();
    ClntCfgMgr().dump();
}

void TClntTransMgr::checkDecline()
{
    //Find any tentative address and remove them from address manager
    //Group declined addresses and IAs by server and send Decline
    //Find first IA with tentative addresses
    SPtr<TAddrIA> firstIA;
    SPtr<TAddrIA> ptrIA;
    do
    {
        firstIA=SPtr<TAddrIA>(); // NULL
        TContainer<SPtr<TAddrIA> > declineIALst;

        ClntAddrMgr().firstIA();
        while((ptrIA=ClntAddrMgr().getIA())&&(!firstIA))
        {
            if (ptrIA->getTentative()==ADDRSTATUS_YES)
                firstIA=ptrIA;
        }
        if (firstIA)
        {
            declineIALst.append(firstIA);
            while(ptrIA=ClntAddrMgr().getIA())
            {
                if ((ptrIA->getTentative()==ADDRSTATUS_YES)&&
                    (*ptrIA->getDUID()==*firstIA->getDUID()))
                {
                    declineIALst.append(ptrIA);
                }

            }
            //Here should be send decline for all tentative addresses in IAs
            SPtr<TClntMsgDecline> decline = 
                new TClntMsgDecline(firstIA->getIfindex(), SPtr<TIPv6Addr>(), declineIALst);
            Transactions.append( (Ptr*) decline);

            // decline sent, now remove those addrs from IfaceMgr
            SPtr<TIfaceIface> ptrIface = ClntIfaceMgr().getIfaceByID(firstIA->getIfindex());
            SPtr<TDUID> duid;

            declineIALst.first();
            while (ptrIA = declineIALst.get() ) {
                SPtr<TAddrAddr> ptrAddr;
                ptrIA->firstAddr();
                Log(Info) << "Sending DECLINE for IA(IAID=" << ptrIA->getIAID() << ")" << LogEnd;

                while ( ptrAddr= ptrIA->getAddr() ) {
                    if (ptrAddr->getTentative() == ADDRSTATUS_YES) {
                        Log(Cont) << ptrAddr->get()->getPlain() << " ";

                        /// @todo: check result
                        // remove this address from interface
                        ptrIface->delAddr(ptrAddr->get(), ptrAddr->getPrefix());

                        /// @todo: check result
                        // remove this address from addrDB
                        ptrIA->delAddr(ptrAddr->get());
                    }
                }
                Log(Cont) << LogEnd;
                duid = ptrIA->getDUID();
                ptrIA->setTentative();
            }

            // create REQUEST message
            SPtr<TClntMsgRequest> request;
            request = new TClntMsgRequest(declineIALst, duid, firstIA->getIfindex() );
            Transactions.append( (Ptr*) request);

	    // state of certain IAs has changed. Let's log it.
	    ClntAddrMgr().dump();
	    ClntCfgMgr().dump();
        }
    } while(firstIA);
}

void TClntTransMgr::checkRequest()
{
    /// @todo: Reimplement check request support.
    return;

    SPtr<TAddrIA> ia;
    SPtr<TClntCfgIA> cfgIA;
    SPtr<TDUID> duid;
    List(TAddrIA) requestIALst;
    int ifaceID = 0;

    requestIALst.clear();
    ClntAddrMgr().firstIA();
    while( ia=ClntAddrMgr().getIA() ) {

        cfgIA = ClntCfgMgr().getIA(ia->getIAID());
        if (!cfgIA) {
            Log(Error) << "Internal sanity check failed. Unable to find IA (iaid=" << ia->getIAID()
                       << ") in the CfgMgr." << LogEnd;
            continue;
        }

        // find all IAs which should be configured:
        if ( (cfgIA->getState()!=STATE_CONFIGURED) )
            continue;

        // this IA is being serviced by different server
        if ( (duid) && ia->getDUID() && !((*ia->getDUID()) == (*duid)) ) {
            continue;
        }

        // if we have found one IA, following ones must be on the same interface
        if ( ifaceID && (ia->getIfindex()!=ifaceID) ) {
            continue;
        }

        // do we have enough addresses?
        // cfgIA - specified in conf file, ia - actually asigned by the server
        if ( ia->countAddr() >= cfgIA->countAddr() ) 
            continue;
        
        Log(Info) << "IA (iaid=" << ia->getIAID() << ") is configured to get " 
                  << cfgIA->countAddr() << " addr, but server provided " << ia->countAddr() 
                  << ", REQUEST will be sent." << LogEnd;

        requestIALst.append(ia);
        ia->setState(STATE_INPROCESS);
        duid = ia->getDUID();
        ifaceID = ia->getIfindex();
    }

    if (requestIALst.count()) {
        // create REQUEST message
        SPtr<TClntMsgRequest> request;
        request = new TClntMsgRequest( requestIALst, duid, ifaceID );
        Transactions.append( (Ptr*) request);
    } 
}

bool TClntTransMgr::isDone()
{
    return IsDone;
}

char* TClntTransMgr::getCtrlAddr() {
    return CtrlAddr_;
}

int  TClntTransMgr::getCtrlIface() {
    return CtrlIface_;
}

TClntTransMgr::~TClntTransMgr() {
    Log(Debug) << "ClntTransMgr cleanup." << LogEnd;
}

void TClntTransMgr::addAdvertise(SPtr<TMsg> advertise)
{
    AdvertiseLst.append( advertise );
}

void TClntTransMgr::firstAdvertise()
{
    AdvertiseLst.first();
}

SPtr<TMsg> TClntTransMgr::getAdvertise()
{
    return AdvertiseLst.get();
}

SPtr<TOpt> TClntTransMgr::getAdvertiseDUID()
{
    if (!AdvertiseLst.count())
        return TOptPtr(); // NULL
    AdvertiseLst.first();
    SPtr<TMsg> msg = AdvertiseLst.get();
    return msg->getOption(OPTION_SERVERID);
}

void TClntTransMgr::delFirstAdvertise()
{
    AdvertiseLst.first();
    AdvertiseLst.delFirst();
} 

int TClntTransMgr::getAdvertiseLstCount()
{
    return AdvertiseLst.count();
}

int TClntTransMgr::getMaxPreference()
{
    if (AdvertiseLst.count() == 0)
        return -1;
    int max = 0;
    
    SPtr<TClntMsgAdvertise> ptr;
    AdvertiseLst.first();
    while ( ptr = (Ptr*) AdvertiseLst.get() ) {
        if ( max < ptr->getPreference() )
            max = ptr->getPreference();
    }
    return max;
}

void TClntTransMgr::printLst(List(TMsg) lst)
{
    SPtr<TMsg> x;
    SPtr<TClntMsgAdvertise> adv;
    lst.first();
    bool first = true;
    while (x = lst.get()) {
        adv = (Ptr*) x;
        Log(Debug) << "Advertise from " << adv->getInfo() << ".";
        if (first) {
            Log(Cont) << "[using this]";
            first = false;
        }
        Log(Cont) << LogEnd;
    }
}

void TClntTransMgr::sortAdvertiseLst()
{
    // we'll store all ADVERTISE here 
    List(TMsg) sorted;

    // sort ADVERTISE by the PREFERENCE value
    SPtr<TClntMsgAdvertise> ptr;
    while (AdvertiseLst.count()) {
        int max = getMaxPreference();
        AdvertiseLst.first();
        while ( ptr = (Ptr*) AdvertiseLst.get() ) {
            if (ptr->getPreference() == max) 
                break;
        }
        
        // did we find it? Then append it on the end of sorted list, and delete from this new.
        if (ptr) {
            sorted.append( (Ptr*) ptr );
            AdvertiseLst.del();
        }
    }

    // now copy sorted list to AnswersLst
    AdvertiseLst = sorted;

}

void TClntTransMgr::printAdvertiseLst() {
    printLst(AdvertiseLst);
}

/// @brief checks/updates loaded database (regarding interface names/indexes)
///
///
/// @return true if sanitization was successful, false if it failed
bool TClntTransMgr::sanitizeAddrDB() {

    // Those two maps will hold current interface names/ifindexes
    TAddrMgr::NameToIndexMapping currentNameToIndex;
    TAddrMgr::IndexToNameMapping currentIndexToName;

    // Let's get name->index and index->name maps first
    ClntIfaceMgr().firstIface();
    while (SPtr<TIfaceIface> iface = ClntIfaceMgr().getIface()) {
        currentNameToIndex.insert(make_pair(iface->getName(), iface->getID()));
        currentIndexToName.insert(make_pair(iface->getID(), iface->getName()));
    }

    // Ok, let's iterate over all loaded entries in Ifa

    return ClntAddrMgr().updateInterfacesInfo(currentNameToIndex,
                                              currentIndexToName);
}


#ifdef MOD_REMOTE_AUTOCONF
SPtr<TClntTransMgr::TNeighborInfo> TClntTransMgr::neighborInfoGet(SPtr<TIPv6Addr> addr) {
    for (TNeighborInfoLst::iterator it=Neighbors.begin(); it!=Neighbors.end(); ++it) {
        if ( (*(*it)->srvAddr) == *addr)
            return *it;
    }
    return 0;
}

SPtr<TClntTransMgr::TNeighborInfo> TClntTransMgr::neighborInfoGet(int transid) {
  for (TNeighborInfoLst::iterator it=Neighbors.begin(); it!=Neighbors.end(); ++it) {
      if ( (*it)->transid == transid)
          return *it;
  }

  return 0;
}

bool TClntTransMgr::updateNeighbors(int ifindex, SPtr<TOptAddrLst> neighbors) {
  neighbors->firstAddr();

  SPtr<TIPv6Addr> addr;
  while (addr=neighbors->getAddr()) {
      SPtr<TNeighborInfo> info;
      info = neighborInfoGet(addr);
      if (info)
          continue; // this neighbor is already known
      neighborAdd(ifindex, addr);
  }

  return true;
}

SPtr<TClntTransMgr::TNeighborInfo> TClntTransMgr::neighborAdd(int ifindex, SPtr<TIPv6Addr> addr) {
    SPtr<TNeighborInfo> info = new TNeighborInfo(addr);
    info->srvAddr = addr;
    info->ifindex = ifindex;

    Log(Debug) << "New information about neighbor " << addr->getPlain() << " added." << LogEnd;
    Neighbors.push_back(info);

    // it's too early to send remote solicit.
    // we will send it once global address is received
    // sendRemoteSolicit(info); 

    return info;
}

bool TClntTransMgr::checkRemoteSolicits() {
    bool status = true;

    if (!ClntAddrMgr().getPreferredAddr()) {
        // There are no preferred (non-tentative) addresses. Skipping remote solicit.
        return false;
    }

    // There is preferred address: " << ClntAddrMgr().getPreferredAddr()->getPlain()
    
    for (TNeighborInfoLst::iterator it=Neighbors.begin(); it!=Neighbors.end(); ++it) {
        if ( (*it)->state != TNeighborInfo::NeighborInfoState_Added)
            continue; 
        
        status = sendRemoteSolicit(*it) && status;
        (*it)->state = TNeighborInfo::NeighborInfoState_Sent;
    }

    return status;
}

bool TClntTransMgr::sendRemoteSolicit(SPtr<TNeighborInfo> neighbor) {
    Log(Debug) << "Sending remote Solicit to " << neighbor->srvAddr->getPlain() << LogEnd;

    SPtr<TClntCfgIface> iface;
    ClntCfgMgr().firstIface();
    while( (iface=ClntCfgMgr().getIface()) )
    {
        if (iface->getID() == neighbor->ifindex)
            break;
    }
    if (!iface) {
        Log(Error) << "Unable to find interface with ifindex=" << neighbor->ifindex 
                   << ". Remote solicit failed." << LogEnd;
        return false;
    }

    List(TClntCfgIA) iaLst; // list of IA requiring configuration
    SPtr<TClntCfgIA> cfgIA;
    iface->firstIA();
    while (cfgIA=iface->getIA()) {
        iaLst.append(cfgIA);
    }

    // ignore TA & PD
    Log(Info) << "Creating remote SOLICIT to be transmitted to " << neighbor->srvAddr->getPlain() << LogEnd;
    SPtr<TClntCfgTA> ta; // use empty pointer
    List(TClntCfgPD) pdLst; // use empty list

    SPtr<TClntMsg> solicit = new TClntMsgSolicit(neighbor->ifindex, neighbor->srvAddr,
                                                 iaLst, ta, pdLst,
                                                 true /*rapid-commit */, 
                                                 true /* remote autoconf*/);
    neighbor->transid = solicit->getTransID();
    Transactions.append(solicit);

    return true;
}

bool TClntTransMgr::processRemoteReply(SPtr<TClntMsg> reply) {

    Log(Debug) << "Processing remote REPLY to remote SOLICIT." << LogEnd;
    int xid = reply->getTransID();
    SPtr<TNeighborInfo> neigh = neighborInfoGet(xid);
    if (!neigh) {
        Log(Error) << "Failed to match transmitted remote SOLICIT. Seems like bogus remote REPLY." << LogEnd;
        return false;
    }

    SPtr<TClntMsgReply> rpl = (Ptr*) reply;
    neigh->reply = reply;
    neigh->rcvdAddr = rpl->getFirstAddr();
    neigh->state = TNeighborInfo::NeighborInfoState_Received;

    Transactions.first();
    SPtr<TClntMsg> sol;
    while (sol = Transactions.get() ) {
        if (sol->getTransID() == neigh->transid)
            sol->isDone(true);
    }

    return ClntIfaceMgr().notifyRemoteScripts(neigh->rcvdAddr, neigh->srvAddr, reply->getIface() );
}

#endif