summaryrefslogtreecommitdiffstats
path: root/cnd/src/cnd_iproute2.cpp
blob: 6596c928f63f1656a3f2c62d9d22df026b06fbb6 (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
/* 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, CneIproute2 allows one table. Each
                table contains one entry, a path to the gateway address of the
                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.


  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 "CNDIPROUTE2"

/*----------------------------------------------------------------------------
 * 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
};

/** 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 DeviceInfo
{
  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:
    DeviceInfo
    (
      uint8_t *deviceName,
      int32_t tableNumber,
      uint8_t *gatewayAddress,
      uint8_t *sourcePrefix,
      int32_t priorityNumber
    )
    {
      DeviceInfo::deviceName = deviceName;
      DeviceInfo::tableNumber = tableNumber;
      DeviceInfo::gatewayAddress = gatewayAddress;
      DeviceInfo::sourcePrefix = sourcePrefix;
      DeviceInfo::priorityNumber = priorityNumber;
    }

    DeviceInfo
    (
      uint8_t *deviceName,
      int32_t tableNumber,
      uint8_t *sourcePrefix,
      int32_t priorityNumber
    )
    {
      DeviceInfo::deviceName = deviceName;
      DeviceInfo::tableNumber = tableNumber;
      DeviceInfo::gatewayAddress = '\0';
      DeviceInfo::sourcePrefix = sourcePrefix;
      DeviceInfo::priorityNumber = priorityNumber;
    }

    ~DeviceInfo();

    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;
    }
};

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

// Maps the name of a device to its corresponding routing characteristics
map<uint8_t*, DeviceInfo*> deviceMap;

// 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
DeviceInfo *defaultDevice;

/*----------------------------------------------------------------------------
 * 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 'Cnd_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";

// 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;

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

uint8_t* cmdLineActionEnumToString
(
  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
(
  DeviceInfo *currentDevice,
  Cmd_line_actions commandAction
);

bool displayAllRoutingTables
(
  void
);

bool displayRoutingTable
(
  uint8_t *deviceName
);

bool displayRules
(
  void
);

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

/*----------------------------------------------------------------------------
 * 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 '\0';
  }
}
/*----------------------------------------------------------------------------
 * 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      modifyDefaultRoute

 * DESCRIPTION   Changes the default route given the name of the device that
                 will be either the new or old 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.

 * DEPENDENCIES  commandAction should be either ADD OR DELETE

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

 * SIDE EFFECTS  None
 *--------------------------------------------------------------------------*/
bool modifyDefaultRoute
(
  uint8_t *deviceName,
  Cmd_line_actions commandAction
)
{
  if ('\0' == deviceName)
  {
    LOGE("A null device name was passed while changing the default table. ");
    return false;
  }

  // If the upcoming command line call fails, revert to last default device
  DeviceInfo *lastDefaultDevice = defaultDevice;

  uint8_t *gatewayAddress;

  switch(commandAction)
  {
    case ACTIONS_ADD_ENUM:
    {
      LOGE("Cannot add a routing table directly. Most use 'replace'");
      return false;
    }
    case ACTIONS_REPLACE_ENUM:
    {
      // No need to perform function if the default device will not change
      if (('\0' != defaultDevice) &&
          (0 == strcmp((char *)defaultDevice->getDeviceName(),
                       (char *)deviceName)))
      {
        LOGW("The new default interface %s is the same as the old.",
             deviceName);
        return true;
      }

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

      map<uint8_t*, DeviceInfo*>::iterator deviceMapIter;
      deviceMapIter = deviceMap.find(deviceName);

      if (deviceMapIter == deviceMap.end())
      {
        LOGE("Cannot make the nonexistant table %s the default.",
             deviceName);
        return false;
      }

      defaultDevice = deviceMapIter->second;
      LOGI("Default device has a stored name of %s.", defaultDevice->getDeviceName());
      break;
    }

    case ACTIONS_DELETE_ENUM:
    {
      // The following case should only be entered if the default table is
      // being deleted when no tables exist
      if ('\0' == defaultDevice)
      {
        LOGE("Cannot delete a default table when none exists.");
        return false;
      }

      LOGI("Deleting default routing table");

      break;
    }

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

  gatewayAddress = defaultDevice->getGatewayAddress();

  if ('\0' == gatewayAddress)
  { 
    if (!cmdLineCaller(ROUTING_CMD,
                       cmdLineActionEnumToString(commandAction),
                       DEFAULT_ADDRESS,
                       CMD_LINE_DEVICE_NAME,
                       defaultDevice->getDeviceName(),
                       NULL))
    {
      defaultDevice = lastDefaultDevice;
      return false;
    }
  }
  else 
  {
    if (!cmdLineCaller(ROUTING_CMD,
                       cmdLineActionEnumToString(commandAction),
                       DEFAULT_ADDRESS,
                       CMD_LINE_GATEWAY_ADDRESS,
                       gatewayAddress,
                       CMD_LINE_DEVICE_NAME,
                       defaultDevice->getDeviceName(),
                       NULL))
    {
      defaultDevice = lastDefaultDevice;
      return false;
    }
  }

  if (ACTIONS_DELETE_ENUM == commandAction)
  {
    // After a deletion, there should be default device defined
    // in the main routing table
    defaultDevice = '\0';
  }

  flushCache();

  return true;
}

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

 * DESCRIPTION   Adds or deletes a routing table given the name of the device
                 associated with that table. This routing table has one route,
                 which will route all packets to some gateway address from
                 some inputted source 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
)
{
  if ('\0' == deviceName)
  {
    LOGE("A null device name was passed while modifying a routing table");
    return false;
  }

  int32_t tableNumber;
  int32_t priorityNumber;

  DeviceInfo *currentDevice;
  map<uint8_t*, DeviceInfo*>::iterator deviceMapIter;
  set<int32_t>::iterator tableNumberSetIter;

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

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

      if ('\0' == gatewayAddress)
      {
        LOGW("A null gateway address was passed when adding the %s table",
             deviceName);
        //return false;
      }

      deviceMapIter = deviceMap.find(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 not be
      // considered a fatal error.
      if (deviceMapIter != deviceMap.end())
      {
        DeviceInfo *existingDevice = deviceMapIter->second;

  //      if ((('\0' != (char *)existingDevice->getGatewayAddress()) && 
  //         ('\0' == (char *)gatewayAddress)) ||
  //         (('\0' == (char *)existingDevice->getGatewayAddress()) && 
  //          ('\0' != (char *)gatewayAddress)) ||
  //          (0 != strcmp((char *)existingDevice->getGatewayAddress(),
  //                       (char *)gatewayAddress)) ||

        //Check for differences between gateway addresses.
        if (0 != strcmp((char *)existingDevice->getSourcePrefix(),
                        (char *)sourcePrefix))
        {
          //Delete existing device with the same name
          modifyRoutingTable(deviceName, '\0', '\0', ACTIONS_DELETE_ENUM);

          //Delete default device that will be overwritten. New default will
          //be added later
          if (('\0' != defaultDevice) && (defaultDevice == existingDevice))
          {
            modifyDefaultRoute('\0', ACTIONS_DELETE_ENUM);
          }
        }

        else {
          if ('\0' == gatewayAddress)
          {
            LOGW("Adding a duplicate %s table with source %s",
                 deviceName, sourcePrefix);
            return true;
          }

          else {
            LOGW("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;

      if ('\0' == gatewayAddress)
      {
        currentDevice = new DeviceInfo(deviceName,
                                       tableNumber,
                                       sourcePrefix,
                                       priorityNumber);
      }

      else
      {
        currentDevice = new DeviceInfo(deviceName,
                                       tableNumber,
                                       gatewayAddress,
                                       sourcePrefix,
                                       priorityNumber);
      }

      break;
    }

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

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

      deviceMapIter = deviceMap.find(deviceName);

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

      currentDevice = deviceMapIter->second;
      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 ('\0' == gatewayAddress)
  {    
    if (!cmdLineCaller(ROUTING_CMD,
                       cmdLineActionEnumToString(commandAction),
                       DEFAULT_ADDRESS,
                       CMD_LINE_DEVICE_NAME,
                       deviceName,
                       CMD_LINE_TABLE_NUMBER,
                       (uint8_t *)tableNumberString,
                       NULL))
    {
      return false;
    }
  }
  else
  {
    if (!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))
    {
      return false;
    }
  }

  switch(commandAction)
  {
    case ACTIONS_ADD_ENUM:
    {
      deviceMap.insert(make_pair(deviceName, currentDevice));
      tableNumberSet.insert(tableNumber);

      // If there is no default table, the new device should be the default.
      if ('\0' == defaultDevice)
      {
        LOGI("Adding default table when no default exists");
        modifyDefaultRoute(deviceName, ACTIONS_REPLACE_ENUM);
      }

      break;
    }

    case ACTIONS_DELETE_ENUM:
    {
      deviceMap.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 when no devices are up");
        modifyDefaultRoute('\0', 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 (defaultDevice == currentDevice)
      {
        uint8_t *newDefaultName = deviceMap.begin()->first;

        LOGI("Replacing old default device with %s", newDefaultName);
        //modifyDefaultRoute('\0', ACTIONS_DELETE_ENUM);
        modifyDefaultRoute(newDefaultName, ACTIONS_REPLACE_ENUM);
      }

      break;
    }

    default:
      break;
  }

  return modifyRule(currentDevice, commandAction);
}

/*----------------------------------------------------------------------------
 * 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
(
  DeviceInfo *currentDevice,
  Cmd_line_actions commandAction
)
{
  if ('\0' == currentDevice)
  {
    LOGE("A null device was passed while modifying a rule");
    return false;
  }

  uint8_t* deviceName = currentDevice->getDeviceName();
  map<uint8_t*, DeviceInfo*>::iterator deviceMapIter;
  deviceMapIter = deviceMap.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) &&
      (deviceMapIter == deviceMap.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';

  if (!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))
  {
    return false;
  }

  flushCache();

  return true;
}

/*----------------------------------------------------------------------------
 * FUNCTION      displayAllRoutingTables

 * DESCRIPTION   Displays contents of all routing tables

 * DEPENDENCIES  None

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

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

/*----------------------------------------------------------------------------
 * FUNCTION      displayRoutingTable

 * DESCRIPTION   Displays contents of the inputted routing table

 * DEPENDENCIES  None

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

 * SIDE EFFECTS  None
 *--------------------------------------------------------------------------*/
bool displayRoutingTable
(
  uint8_t *deviceName
)
{
  if ('\0' == deviceName)
  {
    LOGE("A null argument was passed while displaying table %s.",
         deviceName);
    return false;
  }

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

/*----------------------------------------------------------------------------
 * FUNCTION      displayRules

 * DESCRIPTION   Displays all rules currently entered in the system

 * DEPENDENCIES  None

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

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

/*----------------------------------------------------------------------------
 * 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'. Two
                 readers are instantiated to monitor any standard error and
                 standard output messages sent out by iproute2. These messages
                 are then passed to the Android log.

 * 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 ('\0' == 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) &&
        (nextWord != '\0'))
  {
    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 (cmdLineString == '\0')
  {
    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) &&
        (*nextWord != '\0'))
  {
    //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;
      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;
      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      addRoutingTable

 * DESCRIPTION   Adds a routing table to the system that contains a single
                 default entry, a route to the gateway address of a device.
                 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
)
{
  if (!modifyRoutingTable(deviceName,
                          sourcePrefix,
                          gatewayAddress,
                          ACTIONS_ADD_ENUM))
  {
    return false;
  }

  return true;
}

/*----------------------------------------------------------------------------
 * FUNCTION      changeDefaultTable

 * 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  None

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

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

  return true;
}

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

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

 * DEPENDENCIES  None

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

 * SIDE EFFECTS  None
 *--------------------------------------------------------------------------*/
bool cnd_iproute2::deleteRoutingTable
(
  uint8_t *deviceName
)
{
  if (!modifyRoutingTable(deviceName, '\0', '\0', ACTIONS_DELETE_ENUM))
  {
    return false;
  }

  return true;
}

/*----------------------------------------------------------------------------
 * FUNCTION      deleteDefaultEntryFromMainTable

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

 * DEPENDENCIES  None

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

 * SIDE EFFECTS  None
 *--------------------------------------------------------------------------*/
bool cnd_iproute2::deleteDefaultEntryFromMainTable
(
  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      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 displayAllRoutingTables();
}

/*----------------------------------------------------------------------------
 * 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
)
{
  return displayRoutingTable(deviceName);
}

/*----------------------------------------------------------------------------
 * 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 displayRules();
}