summaryrefslogtreecommitdiffstats
path: root/cnd/src/cnd_iproute2.cpp
blob: 5fa750a63aa3ac64a7892226f3f74d10f2705b20 (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
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
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
/* Copyright (c) 2010, Code Aurora Forum. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of Code Aurora nor
 *       the names of its contributors may be used to endorse or promote
 *       products derived from this software without specific prior written
 *       permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NON-INFRINGEMENT ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 */

/*============================================================================
  FILE:         cnd_iproute2.cpp

  OVERVIEW:     This program is an interface to make the necessary calls to
                iproute2 in order to set up and take down routing tables.
                These calls are made indirectly over the command line by using
                a call to the C++ system() function. For each routing device
                visible to the kernel, cnd_iproute2 allows one table. Each
                table contains one entry, a default path to the inputted
                routing device. A source address or network prefix is also
                required in order to instantiate a table, so that packets from
                that ip address are routed through the device. A gateway
                address can also be inputted optionally for a newly added
                routing table.

  DEPENDENCIES: None
============================================================================*/

/*----------------------------------------------------------------------------
 * Include Files
 * -------------------------------------------------------------------------*/
#include "cnd_iproute2.h"
#include <utils/Log.h>
#include <sys/types.h>
#include <cstdarg>
#include <map>
#include <set>

using namespace std;

/*----------------------------------------------------------------------------
 * Preprocessor Definitions and Constants
 * -------------------------------------------------------------------------*/
#undef LOG_TAG
#define LOG_TAG "CND_IPROUTE2"


/*----------------------------------------------------------------------------
 * Type Declarations
 * -------------------------------------------------------------------------*/
// List of all actions supported from iproute2. Should match defintions
// defined below prefixed with ACTIONS
enum Cmd_line_actions
{
  ACTIONS_ADD_ENUM,
  ACTIONS_DELETE_ENUM,
  ACTIONS_FLUSH_ENUM,
  ACTIONS_REPLACE_ENUM,
  ACTIONS_SHOW_ENUM
};

// Comparator function for use in the map of active interfaces.
struct routingTableMapComparator {
  bool operator() (const uint8_t *string1, const uint8_t *string2) const
  {
    if (string1 && string2) {
        return (strcmp((char *)string1, (char *)string2) < 0);
    }
    return false;
  }
};

class CustomRouteInfo;
class RoutingTableInfo;

/*----------------------------------------------------------------------------
 * Static Variable Definitions
 * -------------------------------------------------------------------------*/
// Commands to begin the command line string
static const uint8_t *ROUTING_CMD                = (uint8_t *)"ip route";
static const uint8_t *RULE_CMD                   = (uint8_t *)"ip rule";

// List of all actions supported from iproute2. These should match values in
// above enumeration 'Cmd_line_actions'
static const uint8_t *ACTIONS_ADD_STR            = (uint8_t *)"add";
static const uint8_t *ACTIONS_DELETE_STR         = (uint8_t *)"delete";
static const uint8_t *ACTIONS_FLUSH_STR          = (uint8_t *)"flush";
static const uint8_t *ACTIONS_REPLACE_STR        = (uint8_t *)"replace";
static const uint8_t *ACTIONS_SHOW_STR           = (uint8_t *)"show";

// Keywords used to refine calls to iproute2
static const uint8_t *CMD_LINE_DEVICE_NAME       = (uint8_t *)"dev";
static const uint8_t *CMD_LINE_GATEWAY_ADDRESS   = (uint8_t *)"via";
static const uint8_t *CMD_LINE_PRIORITY_NUMBER   = (uint8_t *)"priority";
static const uint8_t *CMD_LINE_SOURCE_PREFIX     = (uint8_t *)"from";
static const uint8_t *CMD_LINE_TABLE_NUMBER      = (uint8_t *)"table";

// Keywords that refer to specific routes or tables
static const uint8_t *ALL_TABLES                 = (uint8_t *)"all";
static const uint8_t *CACHED_ENTRIES             = (uint8_t *)"cache";
static const uint8_t *DEFAULT_ADDRESS            = (uint8_t *)"default";
static const uint8_t *SCOPE_GLOBAL               = (uint8_t *)"global";
static const uint8_t *SCOPE_KEYWORD              = (uint8_t *)"scope";
static const uint8_t *SCOPE_LINK                 = (uint8_t *)"link";

// Table #1 is the first usable routing table
static const int32_t MIN_TABLE_NUMBER            = 1;

// Table #253 is the 'defined' default routing table, which should not
// be overwritten
static const int32_t MAX_TABLE_NUMBER            = 252;

// Priority number 32766 diverts packets to the main table (Table #254)
static const int32_t MAX_PRIORITY_NUMBER         = 32765;

// Max number of digits in a table number is 3
static const int32_t MAX_DIGITS_TABLE_NUMBER     = 3;

// Max number of digits in a priority number is 5
static const int32_t MAX_DIGITS_PRIORITY_NUMBER  = 5;

cnd_iproute2* cnd_iproute2::instancePtr = NULL;

/*----------------------------------------------------------------------------
 * Global Data Definitions
 * -------------------------------------------------------------------------*/
// Set of all table numbers currently being used. Cannot contain more than
// MAX_TABLE_NUMBER - MIN_TABLE_NUMBER elements
set<int32_t> tableNumberSet;

// Maps the name of a device to its corresponding routing characteristics
map<uint8_t*, RoutingTableInfo*, routingTableMapComparator> routingTableMap;

// Maps destination address of any custom entries created in the main table with
// its corresponding routing table characteristics.
map<uint8_t*, CustomRouteInfo*, routingTableMapComparator> customRouteMap;

// If a packet does not have an associated rule, it will go to the main
// routing table and be routed to the following device by default
uint8_t *defaultDevice;

/*-------------------------------------------------------------------------
 * Declaration for a non-member method.
 *-----------------------------------------------------------------------*/
void flushCache
(
  void
);

uint8_t *cmdLineActionEnumToString
(
  Cmd_line_actions commandAction
);

uint8_t *storeRoutingInformation
(
  uint8_t *parameterPtr
);

bool modifyCustomRouteInMainTable
(
  uint8_t *destinationAddress,
  uint8_t *deviceName,
  uint8_t *gatewayAddress,
  Cmd_line_actions commandAction
);

bool modifyDefaultRoute
(
  uint8_t *deviceName,
  Cmd_line_actions commandAction
);

bool modifyRoutingTable
(
  uint8_t *deviceName,
  uint8_t *sourcePrefix,
  uint8_t *gatewayAddress,
  Cmd_line_actions commandAction
);

bool modifyRule
(
  RoutingTableInfo *currentDevice,
  Cmd_line_actions commandAction
);

bool cmdLineCaller
(
  const uint8_t* cmdLineFirstWord,
  ...
);

/*-------------------------------------------------------------------------
 * Class Definitions
 *-----------------------------------------------------------------------*/
/** Stores information needed to create a custom entry in the
 *  main table. This allows the calling class to delete that
 *  entry without needing to keep track of any characteristics
 *  of the device other than its name.
 */
class CustomRouteInfo
{
  private:
    uint8_t *deviceName;
    uint8_t *gatewayAddress;
    uint8_t *destinationAddress;

  public:
    CustomRouteInfo
    (
      uint8_t *deviceName,
      uint8_t *gatewayAddress,
      uint8_t *destinationAddress
    )
    {
      CustomRouteInfo::deviceName = storeRoutingInformation(deviceName);

      if (NULL != gatewayAddress)
      {
        CustomRouteInfo::gatewayAddress =
          storeRoutingInformation(gatewayAddress);
      }

      else
      {
        CustomRouteInfo::gatewayAddress = NULL;
      }

      CustomRouteInfo::destinationAddress =
        storeRoutingInformation(destinationAddress);
    }

    ~CustomRouteInfo()
    {
      delete [] CustomRouteInfo::deviceName;
      if (NULL != CustomRouteInfo::gatewayAddress)
      {
        delete [] CustomRouteInfo::gatewayAddress;
      }
      if (NULL != CustomRouteInfo::destinationAddress)
      {
        delete [] CustomRouteInfo::destinationAddress;
      }
    }

    uint8_t* getDestinationAddress(void)
    {
      return destinationAddress;
    }

    uint8_t* getDeviceName(void)
    {
      return deviceName;
    }

    uint8_t* getGatewayAddress(void)
    {
      return gatewayAddress;
    }

    void setDeviceName(uint8_t *deviceName)
    {
      if (NULL != CustomRouteInfo::deviceName)
      {
        delete [] CustomRouteInfo::deviceName;
      }

      CustomRouteInfo::deviceName = storeRoutingInformation(deviceName);
    }

    void setGatewayAddress(uint8_t *gatewayAddress)
    {
      if (NULL != CustomRouteInfo::gatewayAddress)
      {
        delete [] CustomRouteInfo::gatewayAddress;
      }

      CustomRouteInfo::gatewayAddress = storeRoutingInformation(gatewayAddress);
    }
};

/** Stores information needed to create a routing table and a rule. This
 *  allows the calling class to delete that table without needing to
 *  keep track of any characteristics of the device other than its name.
 *  Assumes that there can only be 1 rule associated with any defined
 *  table.
 */
class RoutingTableInfo
{
  private:
    // Variables relating to the routing table
    int32_t tableNumber;
    uint8_t *deviceName;
    uint8_t *gatewayAddress;

    // Variables relating to the corresponding rule.
    uint8_t *sourcePrefix;
    int32_t priorityNumber;

  public:
    RoutingTableInfo
    (
      uint8_t *deviceName,
      int32_t tableNumber,
      uint8_t *gatewayAddress,
      uint8_t *sourcePrefix,
      int32_t priorityNumber
    )
    {
      RoutingTableInfo::deviceName = storeRoutingInformation(deviceName);
      RoutingTableInfo::tableNumber = tableNumber;
      if (NULL != gatewayAddress)
      {
        RoutingTableInfo::gatewayAddress = storeRoutingInformation(gatewayAddress);
      }

      else
      {
        RoutingTableInfo::gatewayAddress = NULL;
      }

      RoutingTableInfo::sourcePrefix = storeRoutingInformation(sourcePrefix);
      RoutingTableInfo::priorityNumber = priorityNumber;
    }

    ~RoutingTableInfo()
    {
      delete [] RoutingTableInfo::deviceName;
      delete [] RoutingTableInfo::sourcePrefix;
      if (NULL != RoutingTableInfo::gatewayAddress)
      {
        delete [] RoutingTableInfo::gatewayAddress;
      }
    }

    uint8_t* getDeviceName(void)
    {
      return deviceName;
    }

    uint8_t* getGatewayAddress(void)
    {
      return gatewayAddress;
    }

    int32_t getPriorityNumber(void)
    {
      return priorityNumber;
    }

    uint8_t* getSourcePrefix(void)
    {
      return sourcePrefix;
    }

    int32_t getTableNumber(void)
    {
      return tableNumber;
    }

    void setGatewayAddress(uint8_t *gatewayAddress)
    {
      if (NULL != RoutingTableInfo::gatewayAddress)
      {
        delete [] RoutingTableInfo::gatewayAddress;
      }

      RoutingTableInfo::gatewayAddress = storeRoutingInformation(gatewayAddress);
    }

    void setSourcePrefix(uint8_t *sourcePrefix)
    {
      delete [] RoutingTableInfo::sourcePrefix;
      RoutingTableInfo::sourcePrefix = storeRoutingInformation(sourcePrefix);
    }
};

/*----------------------------------------------------------------------------
 * FUNCTION      getInstance

   DESCRIPTION   Returns a pointer to an instance of the cnd_iproute2 such
                 that only 1 instance can be open at a time.

 * DEPENDENCIES  None

 * RETURN VALUE  cnd_iproute2*

 * SIDE EFFECTS  None
 *--------------------------------------------------------------------------*/
cnd_iproute2* cnd_iproute2::getInstance
(
  void
)
{
  if(NULL == instancePtr)
  {
    instancePtr = new cnd_iproute2;
  }

  return instancePtr;
}

/*----------------------------------------------------------------------------
 * FUNCTION      cmdLineActionEnumToString

 * DESCRIPTION   Helper function to converts values of Cmd_line_actions enum
                 to a string.

 * DEPENDENCIES  None

 * RETURN VALUE  uint8_t*

 * SIDE EFFECTS  None
 *--------------------------------------------------------------------------*/
uint8_t *cmdLineActionEnumToString
(
  Cmd_line_actions commandAction
)
{
  switch(commandAction)
  {
    case ACTIONS_ADD_ENUM:
      return (uint8_t *)ACTIONS_ADD_STR;
      break;
    case ACTIONS_DELETE_ENUM:
      return (uint8_t *)ACTIONS_DELETE_STR;
      break;
    case ACTIONS_FLUSH_ENUM:
      return (uint8_t *)ACTIONS_FLUSH_STR;
      break;
    case ACTIONS_REPLACE_ENUM:
      return (uint8_t *)ACTIONS_REPLACE_STR;
      break;
    case ACTIONS_SHOW_ENUM:
      return (uint8_t *)ACTIONS_SHOW_STR;
      break;
    default:
      LOGE("Unsupported conversion of command action to string");
      return NULL;
  }
}
/*----------------------------------------------------------------------------
 * FUNCTION      flushCache

 * DESCRIPTION   Flushes the cache after routing table entries are changed

 * DEPENDENCIES  None

 * RETURN VALUE  None

 * SIDE EFFECTS  None
 *--------------------------------------------------------------------------*/
void flushCache
(
  void
)
{
  if (!cmdLineCaller(ROUTING_CMD,
                     cmdLineActionEnumToString(ACTIONS_FLUSH_ENUM),
                     CACHED_ENTRIES,
                     NULL))
  {
    LOGW("Attempt to flush the routing cache failed.");
  }
}

/*----------------------------------------------------------------------------
 * FUNCTION      storeRoutingInformation

 * DESCRIPTION   Copies inputted pointer to permanent storage, returning a
                 pointer to the newly allocated space.

 * DEPENDENCIES  None

 * RETURN VALUE  Returns pointer to newly allocated memory in heap.

 * SIDE EFFECTS  None
 *--------------------------------------------------------------------------*/
uint8_t *storeRoutingInformation
(
  uint8_t *parameterPtr
)
{
  if(NULL == parameterPtr)
  {
    LOGE("storeRoutingInformation: Parameter is null.");
    return NULL;
  }

  uint8_t *memCopyPtr = new (nothrow) uint8_t[strlen((char*)parameterPtr) + 1];

  if (NULL == memCopyPtr)
  {
    LOGE("storeRoutingInformation: unable to allocate memory");
    return NULL;
  }

  int newByteLength = strlen((char *)parameterPtr) * sizeof(uint8_t);

  memcpy(memCopyPtr, parameterPtr, newByteLength + 1);
  memCopyPtr[newByteLength] = '\0';

  return memCopyPtr;
}

/*----------------------------------------------------------------------------
 * FUNCTION      modifyCustomRouteInMainTable

 * DESCRIPTION   Adds or deletes a custom route in the main table given the name
                 of the device associated with this route. This custom route
                 will route all packets to an inputted destination address of a
                 host through the inputted device name, possibly using an
                 optional gateway address.

 * DEPENDENCIES  commandAction should be either ADD OR DELETE

 * RETURN VALUE  bool - True if function is successful. False otherwise.

 * SIDE EFFECTS  None
 *--------------------------------------------------------------------------*/
bool modifyCustomRouteInMainTable
(
  uint8_t *destinationAddress,
  uint8_t *deviceName,
  uint8_t *gatewayAddress,
  Cmd_line_actions commandAction
)
{
  CustomRouteInfo *currentDevice;
  map<uint8_t*, RoutingTableInfo*>::iterator routingTableMapIter;
  map<uint8_t*, CustomRouteInfo*>::iterator customRouteMapIter;

  if (NULL == destinationAddress)
  {
    LOGE("Null destination address was passed while modifying a custom route " \
         "in the main table");
    return false;
  }

  switch(commandAction)
  {
    case ACTIONS_ADD_ENUM:
    {
      LOGI("Adding a custom route in the main table to destination %s",
           destinationAddress);

      if (NULL == deviceName)
      {
        LOGE("Null device name was passed when adding a custom route");
        return false;
      }

      if (NULL == gatewayAddress)
      {
        LOGI("A null gateway address was passed when adding the entry to %s",
             destinationAddress);
      }

      routingTableMapIter = routingTableMap.find(deviceName);

      if ((routingTableMapIter != routingTableMap.end()) &&
          (NULL == routingTableMapIter->second))
      {
        LOGW("Routing table information has been corrupted for %s table",
             deviceName);
      }

      else if (routingTableMapIter != routingTableMap.end())
      {
        LOGI("A separate routing table exists for %s. This table will not be " \
             "updated.", deviceName);
      }

      customRouteMapIter = customRouteMap.find(destinationAddress);

      if ((customRouteMapIter != customRouteMap.end()) &&
          (NULL == customRouteMapIter->second))
      {
        LOGW("Custom route in main table information has been corrupted for %s",
             destinationAddress);
      }

      else if (customRouteMapIter != customRouteMap.end())
      {
        CustomRouteInfo *existingDevice = customRouteMapIter->second;

        uint8_t *existingGateway = existingDevice->getGatewayAddress();

        // If interface name has changed for a particular destination, must
        // delete and add back the custom entry. A simple 'replace' command
        // will not remove the old entry. Any changes to the gateway address
        // will be picked up when a new entry is added
        if (0 != strcmp((char *)existingDevice->getDeviceName(),
                        (char *)deviceName))
        {
            commandAction = ACTIONS_REPLACE_ENUM;

            existingDevice->setDeviceName(deviceName);
            existingDevice->setGatewayAddress(gatewayAddress);

            break;
        }

        // Because the gateway address is an optional parameter, must account
        // for cases where the gateway address changes from null to non-null or
        // vice-versa
        else if ( !((NULL == existingGateway) && (NULL == gatewayAddress)) &&
                   ((NULL == gatewayAddress) || (NULL == existingGateway) ||
                    (0 != strcmp((char *)existingGateway,
                                 (char *)gatewayAddress))) )
        {
          commandAction = ACTIONS_REPLACE_ENUM;

          existingDevice->setGatewayAddress(gatewayAddress);

          break;
        }

        else {
          if (NULL == gatewayAddress)
          {
            LOGI("Adding duplicate custom route in main table with device %s," \
                 "destination address %s.", deviceName, destinationAddress);
            return true;
          }

          else {
            LOGI("Adding duplicate custom route in main table with device %s," \
                 "destination %s, gateway %s",
                 deviceName, destinationAddress, gatewayAddress);
            return true;
          }
        }
      }
      else {
        LOGI("Device '%s' not found in a custom entry to main table",
             deviceName);
      }

      currentDevice = new CustomRouteInfo(deviceName,
                                          gatewayAddress,
                                          destinationAddress);

      if ((NULL == currentDevice) ||
          (NULL == currentDevice->getDeviceName()) ||
          (NULL == currentDevice->getDestinationAddress()))
      {
        LOGE("Failed to allocate new device information while adding custom " \
             "entry over interface %s to main table.", deviceName);
        return false;
      }

      break;
    }

    case ACTIONS_DELETE_ENUM:
    {
      LOGI("Deleting a custom route in the main table with destination %s",
           destinationAddress);

      if (customRouteMap.empty())
      {
        LOGE("Deleting a custom route in the main table when no route exists.");
        return false;
      }

      customRouteMapIter = customRouteMap.find(destinationAddress);

      if (customRouteMapIter == customRouteMap.end())
      {
        LOGE("Cannot delete custom route over %s that has not been created.",
             destinationAddress);
        return false;
      }

      currentDevice = customRouteMapIter->second;
      if (NULL == currentDevice)
      {
        LOGE("Deleting custom route over %s with a stored name and null value",
             destinationAddress);
        return false;
      }

      gatewayAddress = currentDevice->getGatewayAddress();
      deviceName = currentDevice->getDeviceName();
      break;
    }

    default:
    {
      LOGE("Unsupported command action found while modifying a custom route");
      return false;
    }
  }

  if (NULL == gatewayAddress)
  {
    cmdLineCaller(ROUTING_CMD,
                  cmdLineActionEnumToString(commandAction),
                  destinationAddress,
                  CMD_LINE_DEVICE_NAME,
                  deviceName,
                  SCOPE_KEYWORD,
                  SCOPE_LINK,
                  NULL);
  }

  else
  {
    cmdLineCaller(ROUTING_CMD,
                  cmdLineActionEnumToString(commandAction),
                  destinationAddress,
                  CMD_LINE_GATEWAY_ADDRESS,
                  gatewayAddress,
                  CMD_LINE_DEVICE_NAME,
                  deviceName,
                  SCOPE_KEYWORD,
                  SCOPE_GLOBAL,
                  NULL);
  }

  switch(commandAction)
  {
    case ACTIONS_ADD_ENUM:
    {
      customRouteMap.insert(make_pair(currentDevice->getDestinationAddress(),
                                      currentDevice));
      break;
    }

    case ACTIONS_DELETE_ENUM:
    {
      customRouteMap.erase(destinationAddress);
      delete currentDevice;

      break;
    }

    default:
      break;
  }

  flushCache();

  return true;
}
/*----------------------------------------------------------------------------
 * FUNCTION      modifyDefaultRoute

 * DESCRIPTION   Changes the default route given the name of the device that
                 will be the new default. The default case occurs if a packet
                 is sent from some source address not associated with a defined
                 table. When this occurs, the main table will route these
                 undefined source addresses to the gateway of the defined
                 default device. This function will add or delete that default
                 route in the main table. If a default route is being deleted,
                 no input is required for deviceName. The 'replace' command
                 will change the default entry already existing in the main
                 routing table, or add the entry if it does not exist.

 * DEPENDENCIES  commandAction should be either REPLACE OR DELETE

 * RETURN VALUE  bool - True if function is successful. False otherwise.

 * SIDE EFFECTS  None
 *--------------------------------------------------------------------------*/
bool modifyDefaultRoute
(
  uint8_t *deviceName,
  Cmd_line_actions commandAction
)
{
  uint8_t *gatewayAddress = NULL;

  switch(commandAction)
  {
    case ACTIONS_REPLACE_ENUM:
    {
      if (NULL == deviceName)
      {
        LOGE("A null device name was passed while replacing the default table");
        return false;
      }

      // Case where the default device known by cnd is the same as the new
      // device that is replacing it.
      if ((NULL != defaultDevice) &&
          (0 == strcmp((char *)defaultDevice, (char *)deviceName)))
      {
        LOGI("The new default interface %s is the same as the one known by cnd",
             deviceName);
      }

      LOGI("Replacing default routing table with %s", deviceName);

      bool foundMatchingEntry = false;
      map<uint8_t*, RoutingTableInfo*>::iterator routingTableMapIter;
      map<uint8_t*, CustomRouteInfo*>::iterator customRouteMapIter;

      routingTableMapIter = routingTableMap.find(deviceName);
      customRouteMapIter = customRouteMap.begin();

      if (routingTableMapIter != routingTableMap.end())
      {
        if (NULL == routingTableMapIter->second)
        {
          LOGW("Routing table for new default %s has corrupt stored values",
               deviceName);
        }

        else
        {
          LOGI("Routing table for new default %s found", deviceName);
          foundMatchingEntry = true;
          gatewayAddress = routingTableMapIter->second->getGatewayAddress();
        }
      }

      else
      {
        while (customRouteMapIter != customRouteMap.end())
        {
          uint8_t *destinationAddress = customRouteMapIter->first;
          CustomRouteInfo *currentDevice = customRouteMapIter->second;

          ++customRouteMapIter;

          if (NULL == destinationAddress)
          {
            LOGW("Entry in custom route map is corrupted");
            continue;
          }

          if (NULL == currentDevice)
          {
            LOGW("Value in custom route map with destination %s is corrupted",
                 destinationAddress);
            continue;
          }

          if (0 == strcmp((char *)currentDevice->getDeviceName(),
                          (char *)deviceName))
          {
            LOGI("Custom route for new default %s found", deviceName);
            foundMatchingEntry = true;
            gatewayAddress = currentDevice->getGatewayAddress();
            break;
          }
        }
      }

      if (!foundMatchingEntry)
      {
        LOGI("No routing tables or entries found for new default device %s",
             deviceName);
      }

      defaultDevice = storeRoutingInformation(deviceName);

      break;
    }

    case ACTIONS_DELETE_ENUM:
    {
      // The following case should only be entered if the default table is
      // being deleted when no tables exist
      if (NULL == defaultDevice)
      {
        LOGE("No stored default device; use deleteDefaultEntryFromMainTable.");
        return false;
      }

      LOGI("Deleting default routing table");

      break;
    }

    default:
    {
      LOGE("Unsupported command action found while changing the default table");
      return false;
    }
  }

  // These commands may fail if the kernel has already executed an operation on
  // its own. Treat a call to modify the main table as if was successful.
  if (NULL == gatewayAddress)
  {
    cmdLineCaller(ROUTING_CMD,
                  cmdLineActionEnumToString(commandAction),
                  DEFAULT_ADDRESS,
                  CMD_LINE_DEVICE_NAME,
                  defaultDevice,
                  NULL);
  }
  else
  {
    cmdLineCaller(ROUTING_CMD,
                  cmdLineActionEnumToString(commandAction),
                  DEFAULT_ADDRESS,
                  CMD_LINE_GATEWAY_ADDRESS,
                  gatewayAddress,
                  CMD_LINE_DEVICE_NAME,
                  defaultDevice,
                  NULL);
  }

  if (ACTIONS_DELETE_ENUM == commandAction)
  {
    // After a deletion, there should be no default device defined in the main
    // routing table
    if (NULL != defaultDevice)
    {
      delete [] defaultDevice;
      defaultDevice = NULL;
    }
  }

  flushCache();

  return true;
}

/*----------------------------------------------------------------------------
 * FUNCTION      modifyRoutingTable

 * DESCRIPTION   Adds or deletes a routing table given the name of the device
                 This routing table has one route, which will route all packets
                 to the device with the inputted name. This route can
                 optionally be set up to send packets through an inputted
                 gateway address. Once the table has been modified,
                 modifyRoutingTable will call another function to create or
                 delete a rule that maps some source address' packets to this
                 table.

 * DEPENDENCIES  commandAction should be either ADD OR DELETE

 * RETURN VALUE  bool - True if function is successful. False otherwise.

 * SIDE EFFECTS  None
 *--------------------------------------------------------------------------*/
bool modifyRoutingTable
(
  uint8_t *deviceName,
  uint8_t *sourcePrefix,
  uint8_t *gatewayAddress,
  Cmd_line_actions commandAction
)
{
  int32_t tableNumber;
  int32_t priorityNumber;

  RoutingTableInfo *currentDevice;
  map<uint8_t*, RoutingTableInfo*>::iterator routingTableMapIter;
  set<int32_t>::iterator tableNumberSetIter;

  if (NULL == deviceName)
  {
    LOGE("A null device name was passed while modifying a routing table");
    return false;
  }

  switch(commandAction)
  {
    case ACTIONS_ADD_ENUM:
    {
      LOGI("Adding a routing table for interface %s", deviceName);

      if (NULL == sourcePrefix)
      {
        LOGE("A null source prefix was passed when adding the %s table",
             deviceName);
        return false;
      }

      if (NULL == gatewayAddress)
      {
        LOGI("A null gateway address was passed when adding the %s table",
             deviceName);
      }

      routingTableMapIter = routingTableMap.find(deviceName);

      if ((routingTableMapIter != routingTableMap.end()) &&
          (NULL == routingTableMapIter->second))
      {
        LOGW("Adding duplicate routing table with corrupt device information");
        routingTableMap.erase(deviceName);
      }

      // If a call to add a routing table overwrites an existing table, the
      // new source and gateway addresses will overwrite the old ones.
      // However, calls to add a duplicate table, where the source and
      // gateway addresses do not change, are ignored and will simply return
      // true.
      else if (routingTableMapIter != routingTableMap.end())
      {
        RoutingTableInfo *existingDevice = routingTableMapIter->second;

        int isNewSourcePrefix = strcmp((char *)existingDevice->getSourcePrefix(),
                                       (char *)sourcePrefix);

        uint8_t *existingGateway = existingDevice->getGatewayAddress();

        // Because the gateway address is an optional parameter, must account
        // for cases where the gateway address changes from null to non-null or
        // vice-versa
        if ( !((NULL == existingGateway) && (NULL == gatewayAddress)) &&
              ((NULL == gatewayAddress) || (NULL == existingGateway) ||
               (0 != strcmp((char *)existingGateway,
                            (char *)gatewayAddress))) )
        {
          // Replace active table and rule with changes to gateway address and
          // possibly the source prefix, if it has changed.
          commandAction = ACTIONS_REPLACE_ENUM;

          modifyRule(existingDevice, ACTIONS_DELETE_ENUM);

          existingDevice->setGatewayAddress(gatewayAddress);

          if (0 != isNewSourcePrefix)
          {
            existingDevice->setSourcePrefix(sourcePrefix);
          }

          tableNumber = existingDevice->getTableNumber();

          break;
        }

        // Check for differences between source addresses. If a change in the
        // gateway address has already been detected, this step of modifying the
        // rule will be done implicitly.
        else if (0 != isNewSourcePrefix)
        {
          modifyRule(existingDevice, ACTIONS_DELETE_ENUM);
          existingDevice->setSourcePrefix(sourcePrefix);
          modifyRule(existingDevice, ACTIONS_ADD_ENUM);

          return true;
        }

        else {
          if (NULL == gatewayAddress)
          {
            LOGI("Adding a duplicate %s table with source %s.",
                 deviceName, sourcePrefix);
            return true;
          }

          else {
            LOGI("Adding a duplicate %s table with gateway %s and source %s.",
                 deviceName, sourcePrefix, gatewayAddress);
            return true;
          }
        }
      }

      else {
        LOGI("Device '%s' not found as an active interface", deviceName);
      }

      // Instantiating more than 252 tables simultaneously is an error
      if (MAX_TABLE_NUMBER - MIN_TABLE_NUMBER < tableNumberSet.size())
      {
        LOGE("Too many tables exist to add %s. %d tables are defined",
             deviceName, tableNumberSet.size());
        return false;
      }

      // Locate next available table number. If the previous check passed,
      // there must be a table number available
      for (int32_t nextTableNumber = MIN_TABLE_NUMBER;
           nextTableNumber < MAX_TABLE_NUMBER; nextTableNumber++)
      {
        tableNumberSetIter = tableNumberSet.find(nextTableNumber);
        if (tableNumberSetIter == tableNumberSet.end())
        {
          tableNumber = nextTableNumber;
          break;
        }
      }

      // Always map the same rule to the same table number. This allows the
      // reuse of priority numbers.
      priorityNumber = MAX_PRIORITY_NUMBER - tableNumber + 1;

      currentDevice = new RoutingTableInfo(deviceName,
                                           tableNumber,
                                           gatewayAddress,
                                           sourcePrefix,
                                           priorityNumber);

      if ((NULL == currentDevice) ||
          (NULL == currentDevice->getDeviceName()) ||
          (NULL == currentDevice->getSourcePrefix()))
      {
        LOGE("Failed to allocate new device information while adding table %s.",
             deviceName);
        return false;
      }

      break;
    }

    case ACTIONS_DELETE_ENUM:
    {
      LOGI("Deleting routing table for interface %s", deviceName);

      if (routingTableMap.empty())
      {
        LOGE("Deleting a table when no table exists.");
        return false;
      }

      routingTableMapIter = routingTableMap.find(deviceName);

      if (routingTableMapIter == routingTableMap.end())
      {
        LOGE("Cannot delete table %s that has not been created.", deviceName);
        return false;
      }

      currentDevice = routingTableMapIter->second;
      if (NULL == currentDevice)
      {
        LOGE("Deleting table with a stored name and null value");
        return false;
      }

      gatewayAddress = currentDevice->getGatewayAddress();
      tableNumber = currentDevice->getTableNumber();
      break;
    }

    default:
    {
      LOGE("Unsupported command action found while modifying a table");
      return false;
    }
  }

  // Convert table number int to string, null-terminating the result
  char tableNumberString[MAX_DIGITS_TABLE_NUMBER+1];
  int32_t numberOfDigits = snprintf(tableNumberString,
                                    MAX_DIGITS_TABLE_NUMBER+1,
                                    "%d",
                                    tableNumber);
  tableNumberString[numberOfDigits] = '\0';

  if (NULL == gatewayAddress)
  {
    cmdLineCaller(ROUTING_CMD,
                  cmdLineActionEnumToString(commandAction),
                  DEFAULT_ADDRESS,
                  CMD_LINE_DEVICE_NAME,
                  deviceName,
                  CMD_LINE_TABLE_NUMBER,
                  (uint8_t *)tableNumberString,
                  NULL);
  }
  else
  {
    cmdLineCaller(ROUTING_CMD,
                  cmdLineActionEnumToString(commandAction),
                  DEFAULT_ADDRESS,
                  CMD_LINE_GATEWAY_ADDRESS,
                  gatewayAddress,
                  CMD_LINE_DEVICE_NAME,
                  deviceName,
                  CMD_LINE_TABLE_NUMBER,
                  (uint8_t *)tableNumberString,
                  NULL);
  }

  switch(commandAction)
  {
    // This case should not break to account for common code with the replace
    // command.
    case ACTIONS_ADD_ENUM:
    {
      routingTableMap.insert(make_pair(currentDevice->getDeviceName(),currentDevice));
      tableNumberSet.insert(tableNumber);
    }

    case ACTIONS_REPLACE_ENUM:
    {
      // If there is no default entry, the new device should be the default.
      if (NULL == defaultDevice)
      {
        LOGI("Routing table added when no default exists. Adding new default.");
        modifyDefaultRoute(deviceName, ACTIONS_REPLACE_ENUM);
      }

      break;
    }

    case ACTIONS_DELETE_ENUM:
    {
      routingTableMap.erase(deviceName);
      tableNumberSet.erase(tableNumber);

      // If there are no more tables, then there should be no default device.
      if (0 == tableNumberSet.size())
      {
        LOGI("Removing default table after no devices are known to be up");
        modifyDefaultRoute(NULL, ACTIONS_DELETE_ENUM);
      }

      // If the default table has been deleted and another device is available,
      // set an arbitrary new device as the new default.
      else if (0 == strcmp((char *)defaultDevice,
                           (char *)currentDevice->getDeviceName()))
      {
        uint8_t *newDefaultName = routingTableMap.begin()->first;

        LOGI("Replacing old default device with %s", newDefaultName);
        modifyDefaultRoute(newDefaultName, ACTIONS_REPLACE_ENUM);
      }

      break;
    }

    default:
      break;
  }

  // There is no 'ip rule replace' command. When a gateway address is changed,
  // must delete the rule and add it back.
  if (ACTIONS_REPLACE_ENUM == commandAction) {
    commandAction = ACTIONS_ADD_ENUM;
  }

  bool modifyRuleRetValue = modifyRule(currentDevice, commandAction);

  // Delete device information that will no longer be used, if it is not
  // being stored elsewhere
  if (ACTIONS_DELETE_ENUM == commandAction)
  {
    delete currentDevice;
  }

  return modifyRuleRetValue;
}

/*----------------------------------------------------------------------------
 * FUNCTION      modifyRule

 * DESCRIPTION   Adds or deletes a rule given the actual device object of the
                 table associated with that rule. Every defined routing table
                 requires some rule to map packets from some given source
                 address to that routing table. This function takes an object
                 so that after a routing table has been removed, the source
                 prefix, table number, and priority number associated with that
                 table can still be accessed. This allows a call to be made to
                 iproute2 to delete the corresponding rule.

 * DEPENDENCIES  commandAction should be either ADD OR DELETE

 * RETURN VALUE  bool - True if function is successful. False otherwise.

 * SIDE EFFECTS  None
 *--------------------------------------------------------------------------*/
bool modifyRule
(
  RoutingTableInfo *currentDevice,
  Cmd_line_actions commandAction
)
{
  if (NULL == currentDevice)
  {
    LOGE("A null device was passed while modifying a rule");
    return false;
  }

  uint8_t* deviceName = currentDevice->getDeviceName();
  map<uint8_t*, RoutingTableInfo*>::iterator routingTableMapIter;
  routingTableMapIter = routingTableMap.find(deviceName);

  // If a rule is being added, its corresponding table should exist in the map
  // of all routing tables.
  if ((ACTIONS_ADD_ENUM == commandAction) &&
       (routingTableMapIter == routingTableMap.end()))
  {
    LOGE("Cannot %s a rule for nonexistant table %s",
         cmdLineActionEnumToString(commandAction),
         deviceName);
     return false;
  }

  int32_t tableNumber = currentDevice->getTableNumber();
  int32_t priorityNumber = currentDevice->getPriorityNumber();
  uint8_t *sourcePrefix = currentDevice->getSourcePrefix();

  // Convert table number & priority number ints to string, null-terminating
  // the results
  char tableNumberString[MAX_DIGITS_TABLE_NUMBER+1];
  char priorityNumberString[MAX_DIGITS_PRIORITY_NUMBER+1];

  int32_t numberOfDigits = snprintf(tableNumberString,
                                    MAX_DIGITS_TABLE_NUMBER+1,
                                    "%d",
                                    tableNumber);
  tableNumberString[numberOfDigits] = '\0';

  numberOfDigits = snprintf(priorityNumberString,
                            MAX_DIGITS_PRIORITY_NUMBER+1,
                            "%d",
                            priorityNumber);
  priorityNumberString[numberOfDigits] = '\0';

  cmdLineCaller(RULE_CMD,
                cmdLineActionEnumToString(commandAction),
                CMD_LINE_SOURCE_PREFIX,
                sourcePrefix,
                CMD_LINE_TABLE_NUMBER,
                (uint8_t *)tableNumberString,
                CMD_LINE_PRIORITY_NUMBER,
                (uint8_t *)priorityNumberString,
                NULL);

  flushCache();

  return true;
}

/*----------------------------------------------------------------------------
 * FUNCTION      cmdLineCaller

 * DESCRIPTION   Sends a call to iproute2 over the command line. This function
                 takes in a list of an arbitrary number of words, which is
                 parsed together into one final string. This string is sent
                 over the command line using the C routine 'system'. To see
                 the standard output of a failed command in the ADB logs, the
                 'logwrapper' utility must be used while instantiating the cnd
                 process.

 * DEPENDENCIES  Should not be any spaces in any inputted argument

 * RETURN VALUE  bool - True if function is successful. False otherwise.

 * SIDE EFFECTS  None
 *--------------------------------------------------------------------------*/
bool cmdLineCaller
(
  const uint8_t* cmdLineFirstWord,
  ...
)
{
  size_t byteLength = 0;
  size_t memLength;
  int32_t numberOfSpaces = 0;
  va_list cmdLineWordList;
  uint8_t *nextWord;
  char *cmdLineString;

  if (NULL == cmdLineFirstWord)
  {
    LOGE("No actual command passed to build a command line.");
    return false;
  }

  // Find length of overall command line string to determine how much
  // space to allocate for it
  byteLength = strlen((char *)cmdLineFirstWord);
  va_start(cmdLineWordList, cmdLineFirstWord);

  while((nextWord = va_arg(cmdLineWordList,uint8_t*)) != NULL)
  {
    byteLength += strlen((char *)nextWord);
    numberOfSpaces++;
  }

  va_end(cmdLineWordList);

  // Allocate command line string, which is number of bytes in inputted words
  // plus the null character, plus the number of white spaces.
  cmdLineString = new (nothrow) char[byteLength + numberOfSpaces + 1];

  if (NULL == cmdLineString)
  {
    LOGE("Could not allocate memory to build command line string.");
    return false;
  }

  memLength = strlcpy(cmdLineString,
                      (char *)cmdLineFirstWord,
                      strlen((char *)cmdLineFirstWord) * sizeof(uint8_t) + 1);
  if (memLength > strlen((char *)cmdLineFirstWord) * sizeof(uint8_t) + 1)
  {
    LOGE("Failure building first word of command line string.");
    delete [] cmdLineString;
    return false;
  }

  // Build command line string containing each inputted word.
  va_start(cmdLineWordList, cmdLineFirstWord);

  while((nextWord = va_arg(cmdLineWordList,uint8_t*)) != NULL)
  {
    // Add white space
    memLength = strlcat(cmdLineString,
                        " ",
                        strlen(cmdLineString) * sizeof(char) +
                        sizeof(uint8_t) + 1);
    if (memLength > strlen(cmdLineString) * sizeof(char) + sizeof(uint8_t) + 1)
    {
      LOGE("Failure adding whitespace to command line string.");
      delete [] cmdLineString;
      va_end(cmdLineWordList);
      return false;
    }

    // Add next word
    memLength = strlcat(cmdLineString,
                        (char *)nextWord,
                        strlen(cmdLineString) * sizeof(char) +
                        strlen((char *)nextWord) * sizeof(uint8_t) + 1);
    if (memLength > strlen(cmdLineString) * sizeof(char) +
                    strlen((char *)nextWord) * sizeof(uint8_t) + 1)
    {
      LOGE("Failure adding next word to command line string.");
      delete [] cmdLineString;
      va_end(cmdLineWordList);
      return false;
    }
  }

  va_end(cmdLineWordList);

  cmdLineString[byteLength + numberOfSpaces] = '\0';

  LOGI("Iproute2 will be called with: %s", cmdLineString);

  int cmdLineExitValue = system(cmdLineString);

  delete [] cmdLineString;

  if (0 != cmdLineExitValue)
  {
    LOGE("Command line call to iproute2 failed with exitvalue %d.",
         cmdLineExitValue);
    return false;
  }

  LOGI("Iproute2 successfully called.", cmdLineString);

  return true;
}


/*----------------------------------------------------------------------------
 * FUNCTION      addCustomEntryInMainTable

 * DESCRIPTION   Adds a custom entry to the main table to a specific destination
                 address over the given interface name

 * DEPENDENCIES  None

 * RETURN VALUE  bool - True if function is successful. False otherwise.

 * SIDE EFFECTS  None
 *--------------------------------------------------------------------------*/
bool cnd_iproute2::addCustomEntryInMainTable
(
  uint8_t *destinationAddress,
  uint8_t *deviceName,
  uint8_t *gatewayAddress
)
{
  return (modifyCustomRouteInMainTable(destinationAddress,
                                       deviceName,
                                       gatewayAddress,
                                       ACTIONS_ADD_ENUM));
}

/*----------------------------------------------------------------------------
 * FUNCTION      addRoutingTable

 * DESCRIPTION   Adds a routing table to the system that contains a single
                 default entry, a route to the device with the inputted name,
                 which will optionally route through an inputted gateway
                 address. It also adds a rule to route a given source network
                 prefix or address to the new table.

                 The parameter deviceName refers to the name of the device
                 whose table will be added (Such as wlan or wwan)
                 The parameter sourcePrefix refers to the source network prefix
                 or address that will be routed to the device (Such as
                 37.214.21/24 or 10.156.45.1)

 * DEPENDENCIES  None

 * RETURN VALUE  bool - True if function is successful. False otherwise.

 * SIDE EFFECTS  None
 *--------------------------------------------------------------------------*/
bool cnd_iproute2::addRoutingTable
(
  uint8_t *deviceName,
  uint8_t *sourcePrefix,
  uint8_t *gatewayAddress
)
{
  return (modifyRoutingTable(deviceName,
                             sourcePrefix,
                             gatewayAddress,
                             ACTIONS_ADD_ENUM));
}

/*----------------------------------------------------------------------------
 * FUNCTION      deleteRoutingTable

 * DESCRIPTION   Deletes a routing table from the system along with the rule
                 corresponding to that table.

 * DEPENDENCIES  The table must have already been added via the addRoutingTable
                 API.

 * RETURN VALUE  bool - True if function is successful. False otherwise.

 * SIDE EFFECTS  None
 *--------------------------------------------------------------------------*/
bool cnd_iproute2::deleteRoutingTable
(
  uint8_t *deviceName
)
{
  return (modifyRoutingTable(deviceName, NULL, NULL, ACTIONS_DELETE_ENUM));
}

/*----------------------------------------------------------------------------
 * FUNCTION      deleteCustomEntryInMainTable

 * DESCRIPTION   Deletes a custom entry from the main table that has already
                 been added via addCustomEntryToMainTable

 * DEPENDENCIES  None

 * RETURN VALUE  bool - True if function is successful. False otherwise.

 * SIDE EFFECTS  None
 *--------------------------------------------------------------------------*/
bool cnd_iproute2::deleteCustomEntryInMainTable
(
  uint8_t *destinationAddress
)
{
  return (modifyCustomRouteInMainTable(destinationAddress,
                                       NULL,
                                       NULL,
                                       ACTIONS_DELETE_ENUM));
}

/*----------------------------------------------------------------------------
 * FUNCTION      deleteDeviceCustomEntriesInMainTable

 * DESCRIPTION   Deletes all custom entries from the main table that route
                 through the inputted interface name. These routes must have
                 already been added via addCustomEntryToMainTable

 * DEPENDENCIES  None

 * RETURN VALUE  bool - True if function is successful. False otherwise.

 * SIDE EFFECTS  None
 *--------------------------------------------------------------------------*/
bool cnd_iproute2::deleteDeviceCustomEntriesInMainTable
(
  uint8_t *deviceName
)
{
  if (NULL == deviceName)
  {
    LOGE("Null device name was passed when adding a custom route");
    return false;
  }

  LOGI("Deleting custom routes in the main table through interface %s",
       deviceName);

  if (customRouteMap.empty())
  {
    LOGE("Deleting a custom route in the main table when no route exists.");
    return false;
  }

  bool returnValue = true;
  bool foundMatchingEntry = false;

  map<uint8_t*, CustomRouteInfo*>::iterator customRouteMapIter;

  customRouteMapIter = customRouteMap.begin();

  while (customRouteMapIter != customRouteMap.end())
  {
    uint8_t *destinationAddress = customRouteMapIter->first;
    CustomRouteInfo *currentDevice = customRouteMapIter->second;

    ++customRouteMapIter;

    if (NULL == destinationAddress)
    {
      LOGW("Entry in currentDevice is corrupted.");
      continue;
    }

    if (NULL == currentDevice)
    {
      LOGW("Entry in currentDevice with destination %s is corrupted",
           destinationAddress);
      continue;
    }

    if (0 == strcmp((char *)currentDevice->getDeviceName(), (char *)deviceName))
    {
      foundMatchingEntry = true;
      returnValue = modifyCustomRouteInMainTable(destinationAddress,
                                                 NULL,
                                                 NULL,
                                                 ACTIONS_DELETE_ENUM);
    }
  }

  if (!foundMatchingEntry)
  {
    LOGE("No entry was found with interface name %s.", deviceName);
    return false;
  }

  return returnValue;
}

/*----------------------------------------------------------------------------
 * FUNCTION      deleteDefaultEntryInMainTable

 * DESCRIPTION   Deletes the default entry in the main table for the inputted
                 interface name.

 * DEPENDENCIES  None

 * RETURN VALUE  bool - True if function is successful. False otherwise.

 * SIDE EFFECTS  None
 *--------------------------------------------------------------------------*/
bool cnd_iproute2::deleteDefaultEntryInMainTable
(
  uint8_t *deviceName
)
{
  LOGI("Deleting %s interface from main table.", deviceName);

  if (!cmdLineCaller(ROUTING_CMD,
                     cmdLineActionEnumToString(ACTIONS_DELETE_ENUM),
                     DEFAULT_ADDRESS,
                     CMD_LINE_DEVICE_NAME,
                     deviceName,
                     NULL))
  {
    return false;
  }

  flushCache();

  return true;
}

/*----------------------------------------------------------------------------
 * FUNCTION      replaceDefaultEntryInMainTable

 * DESCRIPTION   Changes the default device where packets are routed to. If
                 some source address does not match an already defined rule,
                 packets from that source address will be routed through the
                 main table to some default device. This function replaces the
                 default route to direct traffic to an inputted, already
                 defined device. A routing table associated with this device
                 must have been added through addRoutingTable() before it can
                 be the default.

 * DEPENDENCIES  The new default table must have already been added via the
                 addRoutingTable API.

 * RETURN VALUE  bool - True if function is successful. False otherwise.

 * SIDE EFFECTS  None
 *--------------------------------------------------------------------------*/
bool cnd_iproute2::replaceDefaultEntryInMainTable
(
  uint8_t *deviceName
)
{
  return (modifyDefaultRoute(deviceName, ACTIONS_REPLACE_ENUM));
}

/*----------------------------------------------------------------------------
 * FUNCTION      showAllRoutingTables

 * DESCRIPTION   Displays the contents of all routing tables for debugging
                 purposes.

 * DEPENDENCIES  None

 * RETURN VALUE  bool - True if function is successful. False otherwise.

 * SIDE EFFECTS  None
 *--------------------------------------------------------------------------*/
bool cnd_iproute2::showAllRoutingTables
(
  void
)
{
  return cmdLineCaller(ROUTING_CMD,
                       cmdLineActionEnumToString(ACTIONS_SHOW_ENUM),
                       CMD_LINE_TABLE_NUMBER,
                       ALL_TABLES,
                       NULL);
}

/*----------------------------------------------------------------------------
 * FUNCTION      showRoutingTable

 * DESCRIPTION   Displays the contents of the routing table associated with
                 the inputted device name.

 * DEPENDENCIES  None

 * RETURN VALUE  bool - True if function is successful. False otherwise.

 * SIDE EFFECTS  None
 *--------------------------------------------------------------------------*/
bool cnd_iproute2::showRoutingTable
(
  uint8_t *deviceName
)
{
  if (NULL == deviceName)
  {
    LOGE("A null device name was passed while displaying a table.");
    return false;
  }

  return cmdLineCaller(ROUTING_CMD,
                       cmdLineActionEnumToString(ACTIONS_SHOW_ENUM),
                       CMD_LINE_TABLE_NUMBER,
                       deviceName,
                       NULL);
}

/*----------------------------------------------------------------------------
 * FUNCTION      showRoutingTable

 * DESCRIPTION   Displays the rules associated with all tables for debugging
                 purposes.

 * DEPENDENCIES  None

 * RETURN VALUE  bool - True if function is successful. False otherwise.

 * SIDE EFFECTS  None
 *--------------------------------------------------------------------------*/
bool cnd_iproute2::showRules
(
  void
)
{
  return cmdLineCaller(RULE_CMD,
                       cmdLineActionEnumToString(ACTIONS_SHOW_ENUM),
                       NULL);
}