aboutsummaryrefslogtreecommitdiffstats
path: root/libccnx-transport-rta/ccnx/transport/transport_rta/connectors/test/test_connector_Forwarder_Metis.c
blob: 6fe9e3d28f26ea4a43b73703aeb4560f0f4aacd9 (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
/*
 * Copyright (c) 2017 Cisco and/or its affiliates.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at:
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 *
 * This test will setup a server socket so the Metis connector can connect to it.  We can
 * then see the packets the connector thinks it is sending to Metis.
 */

#define DEBUG 1
#include "../connector_Forwarder_Metis.c"

#include <parc/algol/parc_SafeMemory.h>
#include <parc/security/parc_Pkcs12KeyStore.h>
#include <parc/security/parc_Security.h>

#include <ccnx/api/control/cpi_ControlFacade.h>
#include <ccnx/api/control/controlPlaneInterface.h>
#include <ccnx/api/control/cpi_Forwarding.h>

#include <ccnx/transport/transport_rta/core/rta_Framework_Commands.c>
#include <ccnx/transport/transport_rta/core/rta_Framework_private.h>
#include <ccnx/transport/transport_rta/config/config_All.h>

#include <ccnx/common/codec/ccnxCodec_TlvPacket.h>
#include <ccnx/transport/test_tools/traffic_tools.h>

#include <ccnx/common/codec/schema_v1/ccnxCodecSchemaV1_FixedHeader.h>
#include <ccnx/common/codec/schema_v1/ccnxCodecSchemaV1_PacketEncoder.h>
#include <ccnx/common/codec/schema_v1/ccnxCodecSchemaV1_Types.h>
#include <ccnx/common/codec/schema_v1/testdata/v1_interest_nameA.h>
#include <ccnx/common/codec/schema_v1/testdata/v1_content_nameA_crc32c.h>
#include <ccnx/common/codec/schema_v1/testdata/v1_cpi_add_route_crc32c.h>

#include <ccnx/common/ccnx_WireFormatMessage.h>

// inet_pton
#include <arpa/inet.h>

#include <LongBow/unit-test.h>

static char keystorename[1024];
static const char keystorepass[] = "2398472983479234";

#ifndef INPORT_ANY
#define INPORT_ANY 0
#endif

typedef struct test_data {
    PARCRingBuffer1x1 *commandRingBuffer;
    PARCNotifier *commandNotifier;

    // we will bind to a random port, this is what we end up binding to
    // Its in host byte order
    uint16_t metis_port;

    // server_socket is a socket we listen to like the Metis forwarder, so
    // we can see all the traffic that comes out the bottom of the connector.
    int server_socket;

    // when we accept a client on the server socket, this is his socket
    int client_socket;

    RtaFramework *framework;
    CCNxTransportConfig *params;

    char keystoreName[1024];
    char keystorePassword[1024];
} TestData;

/*
 * @function setup_server
 * @abstract Bind to 127.0.0.1 on a random port, returns the socket and port
 * @discussion
 *   <#Discussion#>
 *
 * @param portOutput is the port bound to in host byte order
 * @return <#return#>
 */
static int
_setup_server(uint16_t *portOutput)
{
    struct sockaddr_in address;

    /* listen on 127.0.0.1 random port */
    address.sin_family = PF_INET;
    address.sin_port = INPORT_ANY;
    inet_pton(AF_INET, "127.0.0.1", &(address.sin_addr));

    int fd = socket(PF_INET, SOCK_STREAM, 0);
    assertFalse(fd < 0, "error on bind: (%d) %s", errno, strerror(errno));

    // Set non-blocking flag
    int flags = fcntl(fd, F_GETFL, NULL);
    assertTrue(flags != -1, "fcntl failed to obtain file descriptor flags (%d)\n", errno);
    int failure = fcntl(fd, F_SETFL, flags | O_NONBLOCK);
    assertFalse(failure, "fcntl failed to set file descriptor flags (%d)\n", errno);

    failure = bind(fd, (struct sockaddr *) &address, sizeof(struct sockaddr_in));
    assertFalse(failure, "error on bind: (%d) %s", errno, strerror(errno));

    failure = listen(fd, 16);
    assertFalse(failure, "error on listen: (%d) %s", errno, strerror(errno));

    socklen_t x = sizeof(address);
    failure = getsockname(fd, (struct sockaddr *) &address, &x);
    assertFalse(failure, "error on getsockname: (%d) %s", errno, strerror(errno));

    *portOutput = htons(address.sin_port);

    printf("test server setup on port %d\n", *portOutput);
    return fd;
}

static int
_accept_client(int server_socket)
{
    socklen_t addrlen;
    struct sockaddr_in address;
    int client_socket;

    addrlen = sizeof(struct sockaddr_in);
    client_socket = accept(server_socket, (struct sockaddr *) &address, &addrlen);
    assertFalse(client_socket < 0, "accept error: %s", strerror(errno));

    printf("%s accepted client on socket %d\n", __func__, client_socket);
    return client_socket;
}

static RtaConnection *
_openConnection(TestData *data, int stack_id, int fds[2])
{
    RtaCommandOpenConnection *openConnection = rtaCommandOpenConnection_Create(stack_id, fds[0], fds[1],
                                                                               ccnxConnectionConfig_GetJson(ccnxTransportConfig_GetConnectionConfig(data->params)));
    _rtaFramework_ExecuteOpenConnection(data->framework, openConnection);
    rtaCommandOpenConnection_Release(&openConnection);

    return rtaConnectionTable_GetByApiFd(data->framework->connectionTable, fds[0]);
}

static void
_createStack(TestData *data, int stack_id)
{
    RtaCommandCreateProtocolStack *createStack =
        rtaCommandCreateProtocolStack_Create(stack_id, ccnxTransportConfig_GetStackConfig(data->params));
    _rtaFramework_ExecuteCreateStack(data->framework, createStack);
    rtaCommandCreateProtocolStack_Release(&createStack);
}

static CCNxTransportConfig *
_createParams(int port, const char *keystore_name, const char *keystore_passwd)
{
    CCNxStackConfig *stackConfig;
    CCNxConnectionConfig *connConfig;

    assertNotNull(keystore_name, "Got null keystore name\n");
    assertNotNull(keystore_passwd, "Got null keystore passwd\n");

    stackConfig = apiConnector_ProtocolStackConfig(
        testingUpper_ProtocolStackConfig(
            metisForwarder_ProtocolStackConfig(
                protocolStack_ComponentsConfigArgs(ccnxStackConfig_Create(),
                                                   apiConnector_GetName(),
                                                   testingUpper_GetName(),
                                                   metisForwarder_GetName(), NULL))));

    connConfig = apiConnector_ConnectionConfig(
        testingUpper_ConnectionConfig(
            metisForwarder_ConnectionConfig(
                tlvCodec_ConnectionConfig(
                    ccnxConnectionConfig_Create()), port)));

    publicKeySigner_ConnectionConfig(connConfig, keystore_name, keystore_passwd);

    CCNxTransportConfig *result = ccnxTransportConfig_Create(stackConfig, connConfig);
    ccnxStackConfig_Release(&stackConfig);
    return result;
}

static TestData *
_commonSetup(void)
{
    parcSecurity_Init();

    TestData *data = parcMemory_AllocateAndClear(sizeof(TestData));
    assertNotNull(data, "parcMemory_AllocateAndClear(%zu) returned NULL", sizeof(TestData));
    memset(data, 0, sizeof(TestData));

    data->server_socket = _setup_server(&data->metis_port);

    //    printf("%s listening on port %u\n", __func__, data->metis_port);

    sprintf(data->keystoreName, "%s", keystorename);
    sprintf(data->keystorePassword, keystorepass);

    data->commandRingBuffer = parcRingBuffer1x1_Create(128, NULL);
    data->commandNotifier = parcNotifier_Create();
    data->framework = rtaFramework_Create(data->commandRingBuffer, data->commandNotifier);

    data->params = _createParams(data->metis_port, data->keystoreName, keystorepass);
    // we will always create stack #1 as the default stack
    _createStack(data, 1);
    return data;
}

static void
_commonTeardown(TestData *data)
{
    if (data != NULL) {
        if (data->server_socket > 0) {
            close(data->server_socket);
        }

        if (data->client_socket > 0) {
            close(data->client_socket);
        }

        ccnxTransportConfig_Destroy(&data->params);
        rtaFramework_Teardown(data->framework);

        parcRingBuffer1x1_Release(&data->commandRingBuffer);
        parcNotifier_Release(&data->commandNotifier);
        rtaFramework_Destroy(&data->framework);
        parcMemory_Deallocate((void **) &data);
    }
    parcSecurity_Fini();
}

// ======================================================
// helper functions

/**
 * Wait for a READ event on the specifid socket.  Has a 1 second timeout.
 *
 * @return true if READ event
 * @return false otherwise
 */
static bool
_waitForSelect(int fd)
{
    fd_set readset;
    FD_ZERO(&readset);
    FD_SET(fd, &readset);
    int result = select(fd + 1, &readset, NULL, NULL, &(struct timeval) { 1, 0 });
    assertFalse(result < 0, "Error on select: (%d) %s", errno, strerror(errno));
    assertFalse(result == 0, "Timeout waiting for connection attempt");
    assertTrue(FD_ISSET(fd, &readset), "server_socket was not set by select");

    return true;
}



static size_t
_sendPacketToConnectorV1(int fd, size_t payloadLength)
{
    // Setup the header
    uint8_t headerLength = 13;
    uint16_t packetLength = payloadLength + headerLength;
    uint8_t packetType = CCNxCodecSchemaV1Types_PacketType_Interest;

    CCNxCodecSchemaV1FixedHeader hdr = { .version = 1, .packetType = packetType, .packetLength = htons(packetLength), .headerLength = headerLength };

    // put header in packet and write the packet
    uint8_t packet[1024];
    memcpy(packet, &hdr, sizeof(hdr));

    // write out exactly the number of bytes we need
    size_t writeSize = packetLength;

    ssize_t nwritten = write(fd, packet, writeSize);
    assertTrue(nwritten == writeSize, "Wrong write size, expected %zu got %zd", writeSize, nwritten);
    return writeSize;
}

static RtaConnection *
setupConnectionAndClientSocket(TestData *data, int *apiSocketOuptut, int *clientSocketOutput)
{
    // Open a listener and accept the forwarders connection
    int fds[2];
    socketpair(PF_LOCAL, SOCK_STREAM, 0, fds);
    RtaConnection *conn = _openConnection(data, 1, fds);
    assertNotNull(conn, "Got null connection opening on stack 1");

    rtaFramework_NonThreadedStepCount(data->framework, 2);

    // we should now see a connection request
    _waitForSelect(data->server_socket);

    // accept the client and set a 1 second read timeout on the socket
    int client_fd = _accept_client(data->server_socket);
    struct timeval readTimeout = { 1, 0 };
    setsockopt(client_fd, SOL_SOCKET, SO_RCVTIMEO, (char *) &readTimeout, sizeof(readTimeout));

    *apiSocketOuptut = fds[0];
    *clientSocketOutput = client_fd;
    return conn;
}

// throw away the first control message
static void
_throwAwayControlMessage(PARCEventQueue *out)
{
    TransportMessage *control_tm = rtaComponent_GetMessage(out);
    assertNotNull(control_tm, "Did not receive a transport message out of the top of the connector");
    assertTrue(transportMessage_IsControl(control_tm),
               "transport message is not a control message")
    {
        ccnxTlvDictionary_Display(transportMessage_GetDictionary(control_tm), 0);
    }
    transportMessage_Destroy(&control_tm);
}

static void
_testReadPacketV1(size_t extraBytes)
{
    const int REMOTE = 0;
    const int STACK = 1;
    int fds[2];
    socketpair(PF_LOCAL, SOCK_STREAM, 0, fds);

    PARCEventScheduler *scheduler = parcEventScheduler_Create();
    FwdMetisState *fwd_state = connector_Fwd_Metis_CreateConnectionState(scheduler);

    // this replaces "_openSocket"
    fwd_state->fd = fds[STACK];

    _setupSocket(fwd_state);

    // Setup the header
    uint16_t packetLength = 24;
    uint8_t headerLength = 13;
    uint8_t packetType = CCNxCodecSchemaV1Types_PacketType_Interest;

    CCNxCodecSchemaV1FixedHeader hdr = { .version = 1, .packetType = packetType, .packetLength = htons(packetLength), .headerLength = headerLength };

    // put header in packet and write the packet
    uint8_t packet[1024];
    memcpy(packet, &hdr, sizeof(hdr));

    // write out exactly the number of bytes we need
    size_t firstWrite = packetLength;

    ssize_t nwritten = write(fds[REMOTE], packet, firstWrite + extraBytes);
    assertTrue(nwritten == firstWrite + extraBytes, "Wrong write size, expected %zu got %zd",
               firstWrite + extraBytes, nwritten);

    ReadReturnCode readCode = _readPacket(fwd_state);

    assertTrue(readCode == ReadReturnCode_Finished, "readCode should be %d got %d", ReadReturnCode_Finished, readCode);

    // should indicate there's nothing left to read of the header
    assertTrue(fwd_state->nextMessage.remainingReadLength == 0, "Remaining length should be 0 got %zu", fwd_state->nextMessage.remainingReadLength);

    // we should be at position "firstWrite" in the packet buffer
    assertNotNull(fwd_state->nextMessage.packet, "Packet buffer is null");
    assertTrue(parcBuffer_Position(fwd_state->nextMessage.packet) == firstWrite,
               "Wrong position, expected %zu got %zu", firstWrite, parcBuffer_Position(fwd_state->nextMessage.packet));

    // cleanup
    _fwdMetisState_Release(&fwd_state);
    parcEventScheduler_Destroy(&scheduler);
    close(fds[REMOTE]);
}



static void
_testReadFromMetisFromArray(TestData *data, size_t length, uint8_t buffer[length])
{
    // create our connection.  This will become part of the RTA framework, so will be
    // cleaned up in the teardown
    int api_fd;
    int client_fd;
    RtaConnection *conn = setupConnectionAndClientSocket(data, &api_fd, &client_fd);

    ssize_t nwritten = write(client_fd, buffer, length);
    assertTrue(nwritten == length, "Wrong write size, expected %zu got %zd", length, nwritten);

    FwdMetisState *fwd_state = (FwdMetisState *) rtaConnection_GetPrivateData(conn, FWD_METIS);;

    _readFromMetis(fwd_state, conn);

    // now crank the handle to pop those messages up the stack
    rtaFramework_NonThreadedStepCount(data->framework, 5);

    PARCEventQueue *out = rtaProtocolStack_GetPutQueue(rtaConnection_GetStack(conn), TESTING_UPPER, RTA_DOWN);
    _throwAwayControlMessage(out);

    // verify the wire format is what we wrote
    TransportMessage *test_tm = rtaComponent_GetMessage(out);
    assertNotNull(test_tm, "Did not receive a transport message out of the top of the connector");

    CCNxTlvDictionary *testDictionary = transportMessage_GetDictionary(test_tm);
    PARCBuffer *writeFormat = ccnxWireFormatMessage_GetWireFormatBuffer(testDictionary);
    assertNotNull(writeFormat,
                  "transport message does not have a wire format");

    PARCBuffer *truth = parcBuffer_Wrap(buffer, length, 0, length);
    assertTrue(parcBuffer_Equals(truth, writeFormat), "Wire format does not match expected")
    {
        printf("Expected:\n");
        parcBuffer_Display(truth, 3);
        printf("Received:\n");
        parcBuffer_Display(writeFormat, 3);
    }

    parcBuffer_Release(&truth);
    transportMessage_Destroy(&test_tm);
}


// ======================================================

LONGBOW_TEST_RUNNER(connector_Forwarder_Metis)
{
    LONGBOW_RUN_TEST_FIXTURE(Local);

    LONGBOW_RUN_TEST_FIXTURE(UpDirectionV1);
    LONGBOW_RUN_TEST_FIXTURE(DownDirectionV1);
}

// The Test Runner calls this function once before any Test Fixtures are run.
LONGBOW_TEST_RUNNER_SETUP(connector_Forwarder_Metis)
{
    parcMemory_SetInterface(&PARCSafeMemoryAsPARCMemory);

    snprintf(keystorename, 1024, "/tmp/keystore_%d.p12", getpid());

    // init + fini here so there's no memory imbalance
    parcSecurity_Init();
    parcPkcs12KeyStore_CreateFile(keystorename, keystorepass, "ccnxuser", 1024, 365);
    parcSecurity_Fini();

    return LONGBOW_STATUS_SUCCEEDED;
}

// The Test Runner calls this function once after all the Test Fixtures are run.
LONGBOW_TEST_RUNNER_TEARDOWN(connector_Forwarder_Metis)
{
    unlink(keystorename);
    return LONGBOW_STATUS_SUCCEEDED;
}

// ======================================================
LONGBOW_TEST_FIXTURE(Local)
{
    LONGBOW_RUN_TEST_CASE(Local, connector_Fwd_Metis_Init_Release);
    LONGBOW_RUN_TEST_CASE(Local, connector_Fwd_Metis_Opener_GoodPort);
    LONGBOW_RUN_TEST_CASE(Local, _fwdMetisState_Release);
    LONGBOW_RUN_TEST_CASE(Local, _readInEnvironmentConnectionSpecification);
}

LONGBOW_TEST_FIXTURE_SETUP(Local)
{
    longBowTestCase_SetClipBoardData(testCase, _commonSetup());
    return LONGBOW_STATUS_SUCCEEDED;
}

LONGBOW_TEST_FIXTURE_TEARDOWN(Local)
{
    _commonTeardown(longBowTestCase_GetClipBoardData(testCase));

    if (parcSafeMemory_ReportAllocation(STDOUT_FILENO) != 0) {
        printf("('%s' leaks memory by %d (allocs - frees)) ", longBowTestCase_GetName(testCase), parcMemory_Outstanding());
        return LONGBOW_STATUS_MEMORYLEAK;
    }
    return LONGBOW_STATUS_SUCCEEDED;
}

// ====================================================================

LONGBOW_TEST_CASE(Local, connector_Fwd_Metis_Init_Release)
{
    // nothing to do, just checking that memory is in balance in teardown
}

/**
 * Call the opener with the right port.  We should see a connection attempt on
 * the server socket and be able to accept it.
 */
LONGBOW_TEST_CASE(Local, connector_Fwd_Metis_Opener_GoodPort)
{
    TestData *data = longBowTestCase_GetClipBoardData(testCase);

    int fds[2];
    socketpair(PF_LOCAL, SOCK_STREAM, 0, fds);
    RtaConnection *conn = _openConnection(data, 1, fds);
    assertNotNull(conn, "Got null connection opening on stack 1");

    rtaFramework_NonThreadedStepCount(data->framework, 2);

    // we should now see a connection request
    _waitForSelect(data->server_socket);

    close(fds[1]);
}

/**
 * Make sure everything is released and file descriptor is closed
 */
LONGBOW_TEST_CASE(Local, _fwdMetisState_Release)
{
    const int REMOTE = 0;
    const int STACK = 1;
    int fds[2];
    socketpair(PF_LOCAL, SOCK_STREAM, 0, fds);

    PARCEventScheduler *scheduler = parcEventScheduler_Create();
    FwdMetisState *fwd_state = connector_Fwd_Metis_CreateConnectionState(scheduler);

    // this replaces "_openSocket"
    fwd_state->fd = fds[STACK];

    _setupSocket(fwd_state);


    _fwdMetisState_Release(&fwd_state);
    parcEventScheduler_Destroy(&scheduler);

    // ensure that fds[STACK] is closed by _fwdMetisState_Release
    uint8_t buffer[16];
    ssize_t nread = recv(fds[STACK], buffer, 16, 0);
    assertTrue(nread == -1 && errno == EBADF,
               "read from closed socket %d should be EBADF, got return %zd and errno (%d) %s",
               fds[STACK], nread, errno, strerror(errno));

    close(fds[REMOTE]);
}

LONGBOW_TEST_CASE(Local, _readInEnvironmentConnectionSpecification)
{
    char *oldEnv = getenv(FORWARDER_CONNECTION_ENV);
    setenv(FORWARDER_CONNECTION_ENV, "tcp://127.0.0.1:9999", 1);
    struct sockaddr_in addr_in;
    _readInEnvironmentConnectionSpecification(&addr_in);
    assertTrue(addr_in.sin_port == htons(9999), "Port specification incorrectly parsed");
    assertTrue(addr_in.sin_addr.s_addr == inet_addr("127.0.0.1"), "Address specification incorrectly parsed");;
    if (oldEnv) {
        setenv(FORWARDER_CONNECTION_ENV, oldEnv, 1);
    } else {
        unsetenv(FORWARDER_CONNECTION_ENV);
    }
}



// ====================================================================


LONGBOW_TEST_FIXTURE(UpDirectionV1)
{
    LONGBOW_RUN_TEST_CASE(UpDirectionV1, _readPacketHeader_ExactFit);
    LONGBOW_RUN_TEST_CASE(UpDirectionV1, _readPacketHeader_TwoReads);
    LONGBOW_RUN_TEST_CASE(UpDirectionV1, _setupNextPacket);

    LONGBOW_RUN_TEST_CASE(UpDirectionV1, _readPacket_PartialMessage);
    LONGBOW_RUN_TEST_CASE(UpDirectionV1, _readPacket_ExactlyOneMessage);
    LONGBOW_RUN_TEST_CASE(UpDirectionV1, _readPacket_MoreThanOneMessage);

    LONGBOW_RUN_TEST_CASE(UpDirectionV1, _readFromMetis_ThreeMessages);

    LONGBOW_RUN_TEST_CASE(UpDirectionV1, _readFromMetis_InterestV1);
    LONGBOW_RUN_TEST_CASE(UpDirectionV1, _readFromMetis_ContentObjectV1);
    LONGBOW_RUN_TEST_CASE(UpDirectionV1, _readFromMetis_ControlV1);

    LONGBOW_RUN_TEST_CASE(UpDirectionV1, _readPacketHeader_Error);
    LONGBOW_RUN_TEST_CASE(UpDirectionV1, _readPacketBody_Error);

    LONGBOW_RUN_TEST_CASE(UpDirectionV1, _readPacketHeader_Closed);
    LONGBOW_RUN_TEST_CASE(UpDirectionV1, _readPacketBody_Closed);
    LONGBOW_RUN_TEST_CASE(UpDirectionV1, _readFromMetis_Closed);
}

LONGBOW_TEST_FIXTURE_SETUP(UpDirectionV1)
{
    longBowTestCase_SetClipBoardData(testCase, _commonSetup());
    return LONGBOW_STATUS_SUCCEEDED;
}

LONGBOW_TEST_FIXTURE_TEARDOWN(UpDirectionV1)
{
    _commonTeardown(longBowTestCase_GetClipBoardData(testCase));

    if (parcSafeMemory_ReportAllocation(STDOUT_FILENO) != 0) {
        printf("('%s' leaks memory by %d (allocs - frees)) ", longBowTestCase_GetName(testCase), parcMemory_Outstanding());
        return LONGBOW_STATUS_MEMORYLEAK;
    }
    return LONGBOW_STATUS_SUCCEEDED;
}

/**
 * Put in exactly 8 bytes.
 * This should return NULL, but will set nextMessageLength to be the right thing.
 * Does not drain the buffer
 */
LONGBOW_TEST_CASE(UpDirectionV1, _readPacketHeader_ExactFit)
{
    const int REMOTE = 0;
    const int STACK = 1;
    int fds[2];
    socketpair(PF_LOCAL, SOCK_STREAM, 0, fds);

    PARCEventScheduler *scheduler = parcEventScheduler_Create();
    FwdMetisState *fwd_state = connector_Fwd_Metis_CreateConnectionState(scheduler);

    // this replaces "_openSocket"
    fwd_state->fd = fds[STACK];

    _setupSocket(fwd_state);

    // Setup the header
    uint16_t packetLength = 24;
    uint8_t headerLength = 13;
    uint8_t packetType = CCNxCodecSchemaV1Types_PacketType_Interest;

    CCNxCodecSchemaV1FixedHeader hdr = { .version = 1, .packetType = packetType, .packetLength = htons(packetLength), .headerLength = headerLength };

    // put header in packet and write the packet
    uint8_t packet[1024];
    size_t bufferReadLength = sizeof(hdr);
    memcpy(packet, &hdr, bufferReadLength);

    // write out exactly the number of bytes we need
    ssize_t nwritten = write(fds[REMOTE], packet, sizeof(CCNxCodecSchemaV1FixedHeader));
    assertTrue(nwritten == sizeof(CCNxCodecSchemaV1FixedHeader), "Wrong write size, expected %zu got %zd",
               sizeof(CCNxCodecSchemaV1FixedHeader), nwritten);

    // test the function
    ReadReturnCode readCode = _readPacketHeader(fwd_state);
    assertTrue(readCode == ReadReturnCode_Finished, "readCode should be %d got %d", ReadReturnCode_Finished, readCode);
    assertTrue(fwd_state->nextMessage.remainingReadLength == 0, "Remaining length should be 0 got %zu", fwd_state->nextMessage.remainingReadLength);

    // other properties are tested as part of _setupNextPacket

    // cleanup
    _fwdMetisState_Release(&fwd_state);
    parcEventScheduler_Destroy(&scheduler);
    close(fds[REMOTE]);
}

/*
 * Write the fixed header in two 4 byte writes
 */
LONGBOW_TEST_CASE(UpDirectionV1, _readPacketHeader_TwoReads)
{
    const int REMOTE = 0;
    const int STACK = 1;
    int fds[2];
    socketpair(PF_LOCAL, SOCK_STREAM, 0, fds);

    PARCEventScheduler *scheduler = parcEventScheduler_Create();
    FwdMetisState *fwd_state = connector_Fwd_Metis_CreateConnectionState(scheduler);

    // this replaces "_openSocket"
    fwd_state->fd = fds[STACK];

    _setupSocket(fwd_state);

    // Setup the header
    uint16_t packetLength = 24;
    uint8_t headerLength = 13;
    uint8_t packetType = CCNxCodecSchemaV1Types_PacketType_Interest;

    CCNxCodecSchemaV1FixedHeader hdr = {
        .version      = 1,
        .packetType   = packetType,
        .packetLength = htons(packetLength),
        .headerLength = headerLength
    };

    // put header in packet and write the packet
    uint8_t packet[1024];
    size_t bufferReadLength = sizeof(hdr);
    memcpy(packet, &hdr, bufferReadLength);

    // write out exactly the number of bytes we need
    size_t firstWrite = 4;
    size_t secondWrite = sizeof(CCNxCodecSchemaV1FixedHeader) - firstWrite;

    ssize_t nwritten = write(fds[REMOTE], packet, firstWrite);
    assertTrue(nwritten == firstWrite, "Wrong write size, expected %zu got %zd", firstWrite, nwritten);

    ReadReturnCode readCode = _readPacketHeader(fwd_state);
    assertTrue(readCode == ReadReturnCode_PartialRead, "readCode should be %d got %d", ReadReturnCode_PartialRead, readCode);

    nwritten = write(fds[REMOTE], packet + firstWrite, secondWrite);
    assertTrue(nwritten == secondWrite, "Wrong write size, expected %zu got %zd", secondWrite, nwritten);

    readCode = _readPacketHeader(fwd_state);
    assertTrue(readCode == ReadReturnCode_Finished, "readCode should be %d got %d", ReadReturnCode_Finished, readCode);

    assertTrue(fwd_state->nextMessage.remainingReadLength == 0, "Remaining length should be 0 got %zu", fwd_state->nextMessage.remainingReadLength);

    // other properties are tested as part of _setupNextPacket

    // cleanup
    _fwdMetisState_Release(&fwd_state);
    parcEventScheduler_Destroy(&scheduler);
    close(fds[REMOTE]);
}

LONGBOW_TEST_CASE(UpDirectionV1, _setupNextPacket)
{
    uint16_t packetLength = 24;
    uint8_t headerLength = 13;
    uint8_t packetType = CCNxCodecSchemaV1Types_PacketType_Interest;
    uint8_t version = 1;
    CCNxCodecSchemaV1FixedHeader hdr = { .version = version, .packetType = packetType, .packetLength = htons(packetLength), .headerLength = headerLength };

    // setup fwd_state->nextMessage like we just read a header
    PARCEventScheduler *scheduler = parcEventScheduler_Create();
    FwdMetisState *fwd_state = connector_Fwd_Metis_CreateConnectionState(scheduler);
    fwd_state->nextMessage.remainingReadLength = 0;
    memcpy(&fwd_state->nextMessage.fixedHeader, &hdr, sizeof(hdr));

    // this is the truth we will test against
    size_t nextMessageLength = packetLength;

    _setupNextPacket(fwd_state);

    size_t allocatedLength = parcBuffer_Capacity(fwd_state->nextMessage.packet);
    size_t position = parcBuffer_Position(fwd_state->nextMessage.packet);
    parcBuffer_Flip(fwd_state->nextMessage.packet);
    void *buffer = parcBuffer_Overlay(fwd_state->nextMessage.packet, 0);

    assertTrue(fwd_state->nextMessage.length == nextMessageLength, "Wrong packet length, expected %zu got %zu", nextMessageLength, fwd_state->nextMessage.length);
    assertTrue(fwd_state->nextMessage.packetType == packetType, "Wrong packetType, expected %u got %u", packetType, fwd_state->nextMessage.packetType);
    assertTrue(fwd_state->nextMessage.version == version, "Wrong version, expected %u got %u", version, fwd_state->nextMessage.version);
    assertTrue(allocatedLength == nextMessageLength, "Wrong packet buffer length, expected %zu got %zu", nextMessageLength, allocatedLength);

    // and make sure the beginning of the buffer is the fixed header
    assertTrue(position == sizeof(hdr), "Wrong write position, expected %zu got %zu", sizeof(hdr), position);
    assertTrue(memcmp(buffer, &hdr, sizeof(hdr)) == 0, "Beginning of buffer not the fixed header");

    // TODO: Finish me
    _fwdMetisState_Release(&fwd_state);
    parcEventScheduler_Destroy(&scheduler);
}

/**
 * Write the fixed header plus part of the message body.
 */
LONGBOW_TEST_CASE(UpDirectionV1, _readPacket_PartialMessage)
{
    const int REMOTE = 0;
    const int STACK = 1;
    int fds[2];
    socketpair(PF_LOCAL, SOCK_STREAM, 0, fds);

    PARCEventScheduler *scheduler = parcEventScheduler_Create();
    FwdMetisState *fwd_state = connector_Fwd_Metis_CreateConnectionState(scheduler);

    // this replaces "_openSocket"
    fwd_state->fd = fds[STACK];

    _setupSocket(fwd_state);

    // Setup the header
    uint16_t packetLength = 160;
    uint8_t headerLength = 13;
    uint8_t packetType = CCNxCodecSchemaV1Types_PacketType_Interest;
    uint8_t version = 1;
    CCNxCodecSchemaV1FixedHeader hdr = { .version = version, .packetType = packetType, .packetLength = htons(packetLength), .headerLength = headerLength };

    // put header in packet and write the packet
    uint8_t packet[1024];
    memcpy(packet, &hdr, sizeof(hdr));

    // write out exactly the number of bytes we need
    size_t firstWrite = 100;

    ssize_t nwritten = write(fds[REMOTE], packet, firstWrite);
    assertTrue(nwritten == firstWrite, "Wrong write size, expected %zu got %zd", firstWrite, nwritten);

    ReadReturnCode readCode = _readPacket(fwd_state);

    assertTrue(readCode == ReadReturnCode_PartialRead, "return value should be %d got %d", ReadReturnCode_PartialRead, readCode);

    // should indicate there's nothing left to read of the header
    assertTrue(fwd_state->nextMessage.remainingReadLength == 0, "Remaining length should be 0 got %zu", fwd_state->nextMessage.remainingReadLength);

    // we should be at position "firstWrite" in the packet buffer
    assertNotNull(fwd_state->nextMessage.packet, "Packet buffer is null");
    assertTrue(parcBuffer_Position(fwd_state->nextMessage.packet) == firstWrite,
               "Wrong position, expected %zu got %zu", firstWrite, parcBuffer_Position(fwd_state->nextMessage.packet));

    // cleanup
    _fwdMetisState_Release(&fwd_state);
    parcEventScheduler_Destroy(&scheduler);
    close(fds[REMOTE]);
}

/**
 * Write exactly one message
 */
LONGBOW_TEST_CASE(UpDirectionV1, _readPacket_ExactlyOneMessage)
{
    _testReadPacketV1(0);
}

/**
 * Write more than one message.
 */
LONGBOW_TEST_CASE(UpDirectionV1, _readPacket_MoreThanOneMessage)
{
    _testReadPacketV1(100);
}

/**
 * Make 3 messages pending on the read socket and make sure _readFromMetis delivers all
 * 3 up the stack.  _readFromMetis requires an RtaConnection, so we need a mock framework.
 */
LONGBOW_TEST_CASE(UpDirectionV1, _readFromMetis_ThreeMessages)
{
    TestData *data = longBowTestCase_GetClipBoardData(testCase);

    // create our connection.  This will become part of the RTA framework, so will be
    // cleaned up in the teardown
    int api_fd;
    int client_fd;
    RtaConnection *conn = setupConnectionAndClientSocket(data, &api_fd, &client_fd);

    // Write three wire format packets up the bottom of the connector
    const int loopCount = 3;
    size_t writeSizes[loopCount];

    for (int i = 0; i < loopCount; i++) {
        writeSizes[i] = _sendPacketToConnectorV1(client_fd, (i + 1) * 100);
    }

    FwdMetisState *fwd_state = (FwdMetisState *) rtaConnection_GetPrivateData(conn, FWD_METIS);;

    _readFromMetis(fwd_state, conn);

    // now crank the handle to pop those messages up the stack
    rtaFramework_NonThreadedStepCount(data->framework, 5);

    // now read the message out of the test component
    PARCEventQueue *out = rtaProtocolStack_GetPutQueue(rtaConnection_GetStack(conn), TESTING_UPPER, RTA_DOWN);

    // throw away the first control message
    _throwAwayControlMessage(out);

    // Now read the actual messages we want to test
    for (int i = 0; i < loopCount; i++) {
        TransportMessage *test_tm = rtaComponent_GetMessage(out);
        assertNotNull(test_tm, "Did not receive a transport message %d out of %d out of the top of the connector", i + 1, loopCount);

        assertTrue(transportMessage_IsInterest(test_tm),
                   "second transport message is not an interest")
        {
            ccnxTlvDictionary_Display(transportMessage_GetDictionary(test_tm), 0);
        }

        // Make sure the transport message has the right properties
        CCNxTlvDictionary *testDictionary = transportMessage_GetDictionary(test_tm);
        PARCBuffer *writeFormat = ccnxWireFormatMessage_GetWireFormatBuffer(testDictionary);
        assertNotNull(writeFormat,
                      "transport message does not have a wire format");

        assertTrue(parcBuffer_Remaining(writeFormat) == writeSizes[i],
                   "Raw format message wrong length, expected %zu got %zu",
                   writeSizes[i],
                   parcBuffer_Remaining(writeFormat));

        // cleanup
        transportMessage_Destroy(&test_tm);
    }

    // no extra cleanup, done in teardown
}

LONGBOW_TEST_CASE(UpDirectionV1, _readFromMetis_InterestV1)
{
    TestData *data = longBowTestCase_GetClipBoardData(testCase);
    _testReadFromMetisFromArray(data, sizeof(v1_interest_nameA), v1_interest_nameA);
}

LONGBOW_TEST_CASE(UpDirectionV1, _readFromMetis_ContentObjectV1)
{
    TestData *data = longBowTestCase_GetClipBoardData(testCase);
    _testReadFromMetisFromArray(data, sizeof(v1_content_nameA_crc32c), v1_content_nameA_crc32c);
}

LONGBOW_TEST_CASE(UpDirectionV1, _readFromMetis_ControlV1)
{
    TestData *data = longBowTestCase_GetClipBoardData(testCase);
    _testReadFromMetisFromArray(data, sizeof(v1_cpi_add_route_crc32c), v1_cpi_add_route_crc32c);
}

/*
 * read from a closed socket
 */
LONGBOW_TEST_CASE(UpDirectionV1, _readPacketHeader_Closed)
{
    const int REMOTE = 0;
    const int STACK = 1;
    int fds[2];
    socketpair(PF_LOCAL, SOCK_STREAM, 0, fds);

    PARCEventScheduler *scheduler = parcEventScheduler_Create();
    FwdMetisState *fwd_state = connector_Fwd_Metis_CreateConnectionState(scheduler);
    fwd_state->fd = fds[STACK];
    _setupSocket(fwd_state);

    // close remote side then try to write to it
    close(fds[REMOTE]);

    ReadReturnCode readCode = _readPacketHeader(fwd_state);

    _fwdMetisState_Release(&fwd_state);
    parcEventScheduler_Destroy(&scheduler);

    assertTrue(readCode == ReadReturnCode_Closed, "Wrong return code, expected %d got %d", ReadReturnCode_Closed, readCode);
}

LONGBOW_TEST_CASE(UpDirectionV1, _readPacketBody_Closed)
{
    const int REMOTE = 0;
    const int STACK = 1;
    int fds[2];
    socketpair(PF_LOCAL, SOCK_STREAM, 0, fds);

    PARCEventScheduler *scheduler = parcEventScheduler_Create();
    FwdMetisState *fwd_state = connector_Fwd_Metis_CreateConnectionState(scheduler);
    fwd_state->fd = fds[STACK];
    _setupSocket(fwd_state);

    ssize_t nwritten = write(fds[REMOTE], v1_interest_nameA, 8);
    assertTrue(nwritten == 8, "Wrong write size, expected 8 got %zd", nwritten);

    // read the header to setup the read of the body
    ReadReturnCode readCode;

    readCode = _readPacketHeader(fwd_state);
    assertTrue(readCode == ReadReturnCode_Finished, "Did not read entire header");

    // close remote side then try to write to it
    close(fds[REMOTE]);

    // now try 2nd read
    readCode = _readPacketBody(fwd_state);

    _fwdMetisState_Release(&fwd_state);
    parcEventScheduler_Destroy(&scheduler);

    assertTrue(readCode == ReadReturnCode_Closed, "Wrong return code, expected %d got %d", ReadReturnCode_Closed, readCode);
}

/*
 * Set the socket to -1 to cause and error
 */
LONGBOW_TEST_CASE(UpDirectionV1, _readPacketHeader_Error)
{
    const int REMOTE = 0;
    const int STACK = 1;
    int fds[2];
    socketpair(PF_LOCAL, SOCK_STREAM, 0, fds);

    PARCEventScheduler *scheduler = parcEventScheduler_Create();
    FwdMetisState *fwd_state = connector_Fwd_Metis_CreateConnectionState(scheduler);
    fwd_state->fd = fds[STACK];
    _setupSocket(fwd_state);

    fwd_state->fd = -1;

    // close remote side then try to write to it

    ReadReturnCode readCode = _readPacketHeader(fwd_state);

    _fwdMetisState_Release(&fwd_state);
    parcEventScheduler_Destroy(&scheduler);
    close(fds[STACK]);
    close(fds[REMOTE]);

    assertTrue(readCode == ReadReturnCode_Error, "Wrong return code, expected %d got %d", ReadReturnCode_Error, readCode);
}

/*
 * Set the socket to -1 to cause and error
 */
LONGBOW_TEST_CASE(UpDirectionV1, _readPacketBody_Error)
{
    const int REMOTE = 0;
    const int STACK = 1;
    int fds[2];
    socketpair(PF_LOCAL, SOCK_STREAM, 0, fds);

    PARCEventScheduler *scheduler = parcEventScheduler_Create();
    FwdMetisState *fwd_state = connector_Fwd_Metis_CreateConnectionState(scheduler);
    fwd_state->fd = fds[STACK];
    _setupSocket(fwd_state);

    ssize_t nwritten = write(fds[REMOTE], v1_interest_nameA, 8);
    assertTrue(nwritten == 8, "Wrong write size, expected 8 got %zd", nwritten);

    // read the header to setup the read of the body
    ReadReturnCode readCode;

    readCode = _readPacketHeader(fwd_state);
    assertTrue(readCode == ReadReturnCode_Finished, "Did not read entire header");

    // invalidate to cause an error
    fwd_state->fd = -1;

    // now try 2nd read
    readCode = _readPacketBody(fwd_state);

    _fwdMetisState_Release(&fwd_state);
    parcEventScheduler_Destroy(&scheduler);
    close(fds[STACK]);
    close(fds[REMOTE]);

    assertTrue(readCode == ReadReturnCode_Error, "Wrong return code, expected %d got %d", ReadReturnCode_Error, readCode);
}

/*
 * read from a closed socket.
 * This should generate a Notify message that the connection is closed
 */
LONGBOW_TEST_CASE(UpDirectionV1, _readFromMetis_Closed)
{
    TestData *data = longBowTestCase_GetClipBoardData(testCase);

    // create our connection.  This will become part of the RTA framework, so will be
    // cleaned up in the teardown
    int api_fd;
    int client_fd;
    RtaConnection *conn = setupConnectionAndClientSocket(data, &api_fd, &client_fd);
    FwdMetisState *fwd_state = (FwdMetisState *) rtaConnection_GetPrivateData(conn, FWD_METIS);;

    rtaFramework_NonThreadedStepCount(data->framework, 5);

    close(client_fd);

    _readFromMetis(fwd_state, conn);

    // now crank the handle to pop those messages up the stack
    rtaFramework_NonThreadedStepCount(data->framework, 5);

    // now read the message out of the test component
    PARCEventQueue *out = rtaProtocolStack_GetPutQueue(rtaConnection_GetStack(conn), TESTING_UPPER, RTA_DOWN);

    // throw away the first control message
    _throwAwayControlMessage(out);

    TransportMessage *test_tm = rtaComponent_GetMessage(out);
    assertNotNull(test_tm, "Did not receive a transport message out of the top of the connector");

    assertTrue(transportMessage_IsControl(test_tm),
               "second transport message is not a control")
    {
        ccnxTlvDictionary_Display(transportMessage_GetDictionary(test_tm), 0);
    }

    // Make sure the transport message has the right properties
    CCNxTlvDictionary *testDictionary = transportMessage_GetDictionary(test_tm);
    assertTrue(ccnxControlFacade_IsNotification(testDictionary), "Control message is not Notification")
    {
        ccnxTlvDictionary_Display(testDictionary, 3);
    }

    PARCJSON *json = ccnxControlFacade_GetJson(testDictionary);
    NotifyStatus *notify = notifyStatus_ParseJSON(json);
    assertTrue(notifyStatus_GetStatusCode(notify) == notifyStatusCode_CONNECTION_CLOSED,
               "Wrong code, expected %d got %d",
               notifyStatusCode_CONNECTION_CLOSED,
               notifyStatus_GetStatusCode(notify));
    notifyStatus_Release(&notify);

    // verify other properties
    assertFalse(fwd_state->isConnected, "Forwarder state should show connection closed");

    // cleanup
    transportMessage_Destroy(&test_tm);

    // no extra cleanup, done in teardown
}

LONGBOW_TEST_FIXTURE(DownDirectionV1)
{
    LONGBOW_RUN_TEST_CASE(DownDirectionV1, _queueMessageToMetis);
    LONGBOW_RUN_TEST_CASE(DownDirectionV1, _dequeueMessagesToMetis);
    LONGBOW_RUN_TEST_CASE(DownDirectionV1, _dequeueMessagesToMetis_TwoWrites);
    LONGBOW_RUN_TEST_CASE(DownDirectionV1, _dequeueMessagesToMetis_Closed);

    LONGBOW_RUN_TEST_CASE(DownDirectionV1, connector_Fwd_Metis_Downcall_Read_Interst);
    LONGBOW_RUN_TEST_CASE(DownDirectionV1, connector_Fwd_Metis_Downcall_Read_CPIRequest);
}

LONGBOW_TEST_FIXTURE_SETUP(DownDirectionV1)
{
    longBowTestCase_SetClipBoardData(testCase, _commonSetup());
    return LONGBOW_STATUS_SUCCEEDED;
}

LONGBOW_TEST_FIXTURE_TEARDOWN(DownDirectionV1)
{
    _commonTeardown(longBowTestCase_GetClipBoardData(testCase));

    if (parcSafeMemory_ReportAllocation(STDOUT_FILENO) != 0) {
        printf("('%s' leaks memory by %d (allocs - frees)) ", longBowTestCase_GetName(testCase), parcMemory_Outstanding());
        return LONGBOW_STATUS_MEMORYLEAK;
    }
    return LONGBOW_STATUS_SUCCEEDED;
}

/*
 * _queueMessageToMetis postconditions:
 * - increases the reference count to the wireFormat
 * - adds the reference to fwd_output buffer
 * - increments the debugging counter fwd_metis_references_queued
 */
LONGBOW_TEST_CASE(DownDirectionV1, _queueMessageToMetis)
{
    PARCEventScheduler *scheduler = parcEventScheduler_Create();
    FwdMetisState *fwd_state = connector_Fwd_Metis_CreateConnectionState(scheduler);
    PARCBuffer *wireFormat = parcBuffer_Wrap(v1_interest_nameA, sizeof(v1_interest_nameA), 0, sizeof(v1_interest_nameA));
    size_t expectedRefCount = parcObject_GetReferenceCount(wireFormat);

    _queueBufferMessageToMetis(wireFormat, fwd_state->metisOutputQueue);

    assertTrue(parcObject_GetReferenceCount(wireFormat) == expectedRefCount,
               "Did not get right ref count for wire format, expected %zu got %" PRIu64, expectedRefCount, parcObject_GetReferenceCount(wireFormat));
    assertTrue(parcEventBuffer_GetLength(fwd_state->metisOutputQueue) == parcBuffer_Remaining(wireFormat),
               "Wrong output buffer length, expected %zu got %zu", parcBuffer_Remaining(wireFormat), parcEventBuffer_GetLength(fwd_state->metisOutputQueue));

    parcBuffer_Release(&wireFormat);
    parcEventBuffer_Destroy(&fwd_state->metisOutputQueue);
    _fwdMetisState_Release(&fwd_state);
    parcEventScheduler_Destroy(&scheduler);
}

/*
 * Dequeue a small message to metis, should all be written out.
 */
LONGBOW_TEST_CASE(DownDirectionV1, _dequeueMessagesToMetis)
{
    TestData *data = longBowTestCase_GetClipBoardData(testCase);

    int api_fd;
    int client_fd;
    RtaConnection *conn = setupConnectionAndClientSocket(data, &api_fd, &client_fd);

    FwdMetisState *fwd_state = (FwdMetisState *) rtaConnection_GetPrivateData(conn, FWD_METIS);;

    // Put data in the output queue
    PARCBuffer *wireFormat = parcBuffer_Wrap(v1_interest_nameA, sizeof(v1_interest_nameA), 0, sizeof(v1_interest_nameA));
    _queueBufferMessageToMetis(wireFormat, fwd_state->metisOutputQueue);

    // write it out
    _dequeueMessagesToMetis(fwd_state);
    rtaFramework_NonThreadedStepCount(data->framework, 5);

    // we should now be able to read it
    bool readReady = _waitForSelect(client_fd);
    assertTrue(readReady, "client socket %d not ready for read", client_fd);

    uint8_t testArray[sizeof(v1_interest_nameA) + 1];
    ssize_t nrecv = recv(client_fd, testArray, sizeof(testArray), 0);

    assertTrue(nrecv == sizeof(v1_interest_nameA), "Wrong read length, expected %zu got %zd", sizeof(v1_interest_nameA), nrecv);
    assertTrue(memcmp(testArray, v1_interest_nameA, sizeof(v1_interest_nameA)) == 0, "Read memory does not compare");
    assertTrue(parcEventBuffer_GetLength(fwd_state->metisOutputQueue) == 0, "Metis output buffer not zero length, got %zu", parcEventBuffer_GetLength(fwd_state->metisOutputQueue));
    parcEventBuffer_Destroy(&(fwd_state->metisOutputQueue));
    parcBuffer_Release(&wireFormat);
}

/*
 * Set the forwarder's send buffer small so it will take two writes to send the packet.
 * This will test that when _dequeueMessagesToMetis cannot write the whole thing it will enable the
 * write event and that metis will then trigger a second write when there's buffer space.
 */
LONGBOW_TEST_CASE(DownDirectionV1, _dequeueMessagesToMetis_TwoWrites)
{
    TestData *data = longBowTestCase_GetClipBoardData(testCase);

    int api_fd;
    int client_fd;
    RtaConnection *conn = setupConnectionAndClientSocket(data, &api_fd, &client_fd);

    FwdMetisState *fwd_state = (FwdMetisState *) rtaConnection_GetPrivateData(conn, FWD_METIS);;

    // set the send buffer
    {
        // make it slightly bigger than 1/2
        const int sendBufferSize = sizeof(v1_interest_nameA) / 2 + 1;
        int res = setsockopt(fwd_state->fd, SOL_SOCKET, SO_SNDBUF, &sendBufferSize, sizeof(int));
        if (res < 0) {
            if (DEBUG_OUTPUT) {
                printf("%9c %s failed to set SO_SNDBUF to %d: (%d) %s\n",
                       ' ', __func__, sendBufferSize, errno, strerror(errno));
            }
            // This is a non-fatal error
        }
    }

    // Put data in the output queue
    PARCBuffer *wireFormat = parcBuffer_Wrap(v1_interest_nameA, sizeof(v1_interest_nameA), 0, sizeof(v1_interest_nameA));
    _queueBufferMessageToMetis(wireFormat, fwd_state->metisOutputQueue);

    // write it out
    _dequeueMessagesToMetis(fwd_state);
    rtaFramework_NonThreadedStepCount(data->framework, 5);

    // we should now be able to read it
    bool readReady = _waitForSelect(client_fd);
    assertTrue(readReady, "client socket %d not ready for read", client_fd);

    uint8_t testArray[sizeof(v1_interest_nameA) + 1];
    ssize_t nrecv = recv(client_fd, testArray, sizeof(testArray), 0);

    assertTrue(nrecv == sizeof(v1_interest_nameA), "Wrong read length, expected %zu got %zd", sizeof(v1_interest_nameA), nrecv);
    assertTrue(memcmp(testArray, v1_interest_nameA, sizeof(v1_interest_nameA)) == 0, "Read memory does not compare");
    assertTrue(parcEventBuffer_GetLength(fwd_state->metisOutputQueue) == 0, "Metis output buffer not zero length, got %zu", parcEventBuffer_GetLength(fwd_state->metisOutputQueue));
    parcEventBuffer_Destroy(&(fwd_state->metisOutputQueue));
    parcBuffer_Release(&wireFormat);
}

/*
 * Dequeue a message to a closed socket
 */
LONGBOW_TEST_CASE(DownDirectionV1, _dequeueMessagesToMetis_Closed)
{
    TestData *data = longBowTestCase_GetClipBoardData(testCase);

    int api_fd;
    int client_fd;
    RtaConnection *conn = setupConnectionAndClientSocket(data, &api_fd, &client_fd);

    FwdMetisState *fwd_state = (FwdMetisState *) rtaConnection_GetPrivateData(conn, FWD_METIS);;
    PARCBuffer *wireFormat = parcBuffer_Wrap(v1_interest_nameA, sizeof(v1_interest_nameA), 0, sizeof(v1_interest_nameA));
    _queueBufferMessageToMetis(wireFormat, fwd_state->metisOutputQueue);

    // close remote side then try to write to it
    close(client_fd);

    _dequeueMessagesToMetis(fwd_state);
    rtaFramework_NonThreadedStepCount(data->framework, 5);

    parcEventBuffer_Destroy(&(fwd_state->metisOutputQueue));
    parcBuffer_Release(&wireFormat);
}

/**
 * Sends an Interest down the stack.  We need to create an Interest and encode its TLV wire format,
 * then send it down the stack and make sure we receive it on a client socket.  We don't actually
 * run Metis in this test.
 */
LONGBOW_TEST_CASE(DownDirectionV1, connector_Fwd_Metis_Downcall_Read_Interst)
{
    TestData *data = longBowTestCase_GetClipBoardData(testCase);

    // create our connection.  This will become part of the RTA framework, so will be
    // cleaned up in the teardown
    int api_fd;
    int client_fd;
    RtaConnection *conn = setupConnectionAndClientSocket(data, &api_fd, &client_fd);
    FwdMetisState *fwd_state = (FwdMetisState *) rtaConnection_GetPrivateData(conn, FWD_METIS);

    // Create the interest with wire format and send it down the stack
    TransportMessage *tm = trafficTools_CreateTransportMessageWithDictionaryInterest(conn, CCNxTlvDictionary_SchemaVersion_V1);
    CCNxCodecNetworkBufferIoVec *vec = ccnxCodecSchemaV1PacketEncoder_DictionaryEncode(transportMessage_GetDictionary(tm), NULL);

    ccnxWireFormatMessage_PutIoVec(transportMessage_GetDictionary(tm), vec);
    ccnxCodecNetworkBufferIoVec_Release(&vec);

    // send it down the stack
    PARCEventQueue *in = rtaProtocolStack_GetPutQueue(rtaConnection_GetStack(conn), TESTING_UPPER, RTA_DOWN);
    rtaComponent_PutMessage(in, tm);
    rtaFramework_NonThreadedStepCount(data->framework, 5);

    bool readReady = _waitForSelect(client_fd);
    assertTrue(readReady, "select did not indicate read ready");

    // now read it from out listener.  It has a read timeout so if we dont get it in a reasonable amount
    // of time, read will return an error about the timeout

    const size_t maxPacketLength = 1024;
    uint8_t packet[maxPacketLength];

    ssize_t readBytes = read(client_fd, packet, maxPacketLength);
    assertFalse(readBytes < 0, "Got error on read: (%d) %s", errno, strerror(errno));

    parcEventBuffer_Destroy(&(fwd_state->metisOutputQueue));
    close(client_fd);
}

/**
 * Send an AddRoute command down the stack.  It does not need a wire format in the transport message, its
 * the job of the forwarder to create the Metis-specific message.
 */
LONGBOW_TEST_CASE(DownDirectionV1, connector_Fwd_Metis_Downcall_Read_CPIRequest)
{
    testUnimplemented("No way to create a v1 CPI message yet");

//    TestData *data = longBowTestCase_GetClipBoardData(testCase);
//
//    // create our connection.  This will become part of the RTA framework, so will be
//    // cleaned up in the teardown
//    int api_fd;
//    int client_fd;
//    RtaConnection *conn = setupConnectionAndClientSocket(data, &api_fd, &client_fd);
//    FwdMetisState *fwd_state = (FwdMetisState *) rtaConnection_GetPrivateData(conn, FWD_METIS);
//
//    // now make the control message
//    TransportMessage *tm = trafficTools_CreateTransportMessageWithDictionaryControl(conn, CCNxTlvDictionary_SchemaVersion_V1);
//    CCNxCodecNetworkBufferIoVec *vec = ccnxCodecSchemaV1PacketEncoder_DictionaryEncode(transportMessage_GetDictionary(tm), NULL);
//    ccnxWireFormatFacade_PutIoVec(transportMessage_GetDictionary(tm), vec);
//    ccnxCodecNetworkBufferIoVec_Release(&vec);
//
//    // send it down the stack
//    PARCEventQueue *in = rtaProtocolStack_GetPutQueue(rtaConnection_GetStack(conn), TESTING_UPPER, RTA_DOWN);
//    rtaComponent_PutMessage(in, tm);
//    rtaFramework_NonThreadedStepCount(data->framework, 5);
//
//    // now read it from out listener.  It has a read timeout so if we dont get it in a reasonable amount
//    // of time, read will return an error about the timeout
//
//    const size_t maxPacketLength = 1024;
//    uint8_t packet[maxPacketLength];
//
//    ssize_t readBytes = read(client_fd, packet, maxPacketLength);
//    assertFalse(readBytes < 0, "Got error on read: (%d) %s", errno, strerror(errno));
//    parcEventBuffer_Destroy(&(fwd_state->metisOutputQueue));
}

// ====================================================================

int
main(int argc, char *argv[])
{
    LongBowRunner *testRunner = LONGBOW_TEST_RUNNER_CREATE(connector_Forwarder_Metis);
    int exitStatus = longBowMain(argc, argv, testRunner, NULL);
    longBowTestRunner_Destroy(&testRunner);
    exit(exitStatus);
}