aboutsummaryrefslogtreecommitdiffstats
path: root/metis/ccnx/forwarder/metis/platforms/linux/metis_GenericEther.c
blob: 825429839db1515c735481b9bd978272d185ef33 (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
/*
 * 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.
 */

/**
 * Implements the platform-specific code for working with an Ethernet interface.
 *
 * The Linux Ethernet device uses an AF_PACKET socket SOCK_RAW.
 *
 */

#include <config.h>
#include <stdio.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>

#include <arpa/inet.h>
#include <linux/if_packet.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <net/if.h>
#include <netinet/ether.h>
#include <net/ethernet.h>

#include <LongBow/runtime.h>

#include <parc/algol/parc_Memory.h>
#include <ccnx/forwarder/metis/io/metis_GenericEther.h>
#include <ccnx/forwarder/metis/core/metis_System.h>
#include <parc/algol/parc_Object.h>
#include <ccnx/forwarder/metis/tlv/metis_Tlv.h>
#include <ccnx/forwarder/metis/io/metis_Ethernet.h>

struct metis_generic_ether {
    uint16_t ethertype;
    int etherSocket;

    int linuxInterfaceIndex;

    PARCBuffer *macAddress;
    MetisLogger *logger;

    // MTU set on interface when we are created
    unsigned mtu;
};

static bool _linuxEthernet_SetupSocket(MetisGenericEther *ether, const char *devstr);

static void
_metisGenericEther_Destroy(MetisGenericEther **etherPtr)
{
    MetisGenericEther *ether = *etherPtr;

    if (ether->etherSocket > 0) {
        close(ether->etherSocket);
    }

    if (ether->macAddress) {
        parcBuffer_Release(&ether->macAddress);
    }

    metisLogger_Release(&ether->logger);
}

parcObject_ExtendPARCObject(MetisGenericEther, _metisGenericEther_Destroy, NULL, NULL, NULL, NULL, NULL, NULL);

parcObject_ImplementAcquire(metisGenericEther, MetisGenericEther);

parcObject_ImplementRelease(metisGenericEther, MetisGenericEther);

// =========================
// PUBLIC API
// =========================

MetisGenericEther *
metisGenericEther_Create(MetisForwarder *metis, const char *deviceName, uint16_t etherType)
{
    assertNotNull(metis, "Parameter metis must be non-null");
    assertNotNull(deviceName, "Parameter deviceName must be non-null");

    MetisGenericEther *ether = NULL;

    if (metisEthernet_IsValidEthertype(etherType)) {
        ether = parcObject_CreateInstance(MetisGenericEther);
        ether->ethertype = etherType;
        ether->logger = metisLogger_Acquire(metisForwarder_GetLogger(metis));
        ether->mtu = metisSystem_InterfaceMtu(metis, deviceName);

        ether->etherSocket = -1; // invalid valid
        ether->macAddress = NULL;

        bool success = _linuxEthernet_SetupSocket(ether, deviceName);

        if (success) {
            if (metisLogger_IsLoggable(metisForwarder_GetLogger(metis), MetisLoggerFacility_IO, PARCLogLevel_Debug)) {
                char *str = parcBuffer_ToHexString(ether->macAddress);
                metisLogger_Log(metisForwarder_GetLogger(metis), MetisLoggerFacility_IO, PARCLogLevel_Debug, __func__,
                                "GenericEther %p created on device %s (%s) for ethertype 0x%04x fd %d ifindex %u mtu %u",
                                (void *) ether, deviceName, str, etherType, ether->etherSocket, ether->linuxInterfaceIndex,
                                ether->mtu);
                parcMemory_Deallocate((void **) &str);
            }
        } else {
            if (metisLogger_IsLoggable(metisForwarder_GetLogger(metis), MetisLoggerFacility_IO, PARCLogLevel_Error)) {
                metisLogger_Log(metisForwarder_GetLogger(metis), MetisLoggerFacility_IO, PARCLogLevel_Error, __func__,
                                "GenericEther failed to created on device %s for ethertype 0x%04x",
                                deviceName, etherType);
            }

            // this will also null ether
            metisGenericEther_Release(&ether);
        }
    } else {
        if (metisLogger_IsLoggable(metisForwarder_GetLogger(metis), MetisLoggerFacility_IO, PARCLogLevel_Error)) {
            metisLogger_Log(metisForwarder_GetLogger(metis), MetisLoggerFacility_IO, PARCLogLevel_Error, __func__,
                            "GenericEther failed to created on device %s for ethertype 0x%04x, invalid ethertype",
                            deviceName, etherType);
        }
    }

    return ether;
}

int
metisGenericEther_GetDescriptor(const MetisGenericEther *ether)
{
    assertNotNull(ether, "Parameter ether must be non-null");
    return ether->etherSocket;
}

/**
 * Based on the fixed header, trim the buffer
 *
 * Some platforms do not strip the ethernet CRC from the raw packet.  Trim the buffer to
 * the right sized based on the fixed header.
 *
 * @param [in] ether An allocated ethernet interface
 * @param [in] readBuffer The buffer to trim
 *
 * Example:
 * @code
 * <#example#>
 * @endcode
 */
static void
_linuxEthernet_TrimBuffer(MetisGenericEther *ether, PARCEventBuffer *readBuffer)
{
    // read the fixed header
    uint8_t *etherHeader = parcEventBuffer_Pullup(readBuffer, ETHER_HDR_LEN + metisTlv_FixedHeaderLength());

    if (etherHeader) {
        uint8_t *fixedHeader = etherHeader + ETHER_HDR_LEN;
        size_t totalLength = metisTlv_TotalPacketLength(fixedHeader) + ETHER_HDR_LEN;

        if (parcEventBuffer_GetLength(readBuffer) > totalLength) {
            if (metisLogger_IsLoggable(ether->logger, MetisLoggerFacility_IO, PARCLogLevel_Debug)) {
                metisLogger_Log(ether->logger, MetisLoggerFacility_IO, PARCLogLevel_Debug, __func__,
                                "%s buffer length %zu, actual length %zu (ether header + ccnx packet), trimming %zu bytes",
                                __func__, parcEventBuffer_GetLength(readBuffer), totalLength,
                                parcEventBuffer_GetLength(readBuffer) - totalLength);
            }

            PARCEventBuffer *temp = parcEventBuffer_Create();

            // there's no way to drain from the end, so we move to a tempororary buffer,
            // drain the unwanted part, then move back.

            int movedBytes = parcEventBuffer_ReadIntoBuffer(readBuffer, temp, totalLength);
            assertTrue(movedBytes == totalLength, "Failed to move all the bytes, got %d expected %zu", movedBytes, totalLength);

            // flush all the bytes out of the read buffer
            parcEventBuffer_Read(readBuffer, NULL, -1);

            // now put back what we want
            int failure = parcEventBuffer_AppendBuffer(temp, readBuffer);
            assertFalse(failure, "parcEventBuffer_AppendBuffer failed");

            parcEventBuffer_Destroy(&temp);
        }
    }
}

/*
 * Reading a raw socket, on some systems, may include the FCS trailer
 */
bool
metisGenericEther_ReadNextFrame(MetisGenericEther *ether, PARCEventBuffer *readBuffer)
{
    assertNotNull(ether, "Parameter ether must be non-null");
    assertNotNull(readBuffer, "Parameter readBuffer must be non-null");

    bool success = false;

    int evread_length = parcEventBuffer_ReadFromFileDescriptor(readBuffer, ether->etherSocket, (int) -1);

    if (metisLogger_IsLoggable(ether->logger, MetisLoggerFacility_IO, PARCLogLevel_Debug)) {
        metisLogger_Log(ether->logger, MetisLoggerFacility_IO, PARCLogLevel_Debug, __func__,
                        "%s read length %d", __func__, evread_length);
    }

    if (evread_length > 0) {
        _linuxEthernet_TrimBuffer(ether, readBuffer);
        success = true;
    }

    return success;
}

bool
metisGenericEther_SendFrame(MetisGenericEther *ether, PARCEventBuffer *buffer)
{
    assertNotNull(ether, "Parameter ether must be non-null");

    // cannot use parcEventBuffer_WriteToFileDescriptor because we need to write the length in one go, not use the
    // iovec approach in parcEventBuffer_WriteToFileDescriptor.  It can cause problems on some platforms.

    uint8_t *linear = parcEventBuffer_Pullup(buffer, -1);
    size_t length = parcEventBuffer_GetLength(buffer);

    ssize_t written = write(ether->etherSocket, linear, length);
    if (written == length) {
        return true;
    }
    return false;
}

PARCBuffer *
metisGenericEther_GetMacAddress(const MetisGenericEther *ether)
{
    assertNotNull(ether, "Parameter ether must be non-null");
    return ether->macAddress;
}

uint16_t
metisGenericEther_GetEtherType(const MetisGenericEther *ether)
{
    assertNotNull(ether, "Parameter ether must be non-null");
    return ether->ethertype;
}

unsigned
metisGenericEther_GetMTU(const MetisGenericEther *ether)
{
    return ether->mtu;
}

// ==================
// PRIVATE API

static bool
_linuxEthernet_SetInterfaceIndex(MetisGenericEther *ether, const char *devstr)
{
    // get the interface index of the desired device
    bool success = false;

    struct ifreq if_idx;
    memset(&if_idx, 0, sizeof(if_idx));
    strncpy(if_idx.ifr_name, devstr, IFNAMSIZ - 1);
    if (!ioctl(ether->etherSocket, SIOCGIFINDEX, &if_idx)) {
        ether->linuxInterfaceIndex = if_idx.ifr_ifindex;
        success = true;
    } else {
        if (metisLogger_IsLoggable(ether->logger, MetisLoggerFacility_IO, PARCLogLevel_Error)) {
            metisLogger_Log(ether->logger, MetisLoggerFacility_IO, PARCLogLevel_Error, __func__,
                            "ioctl SIOCGIFINDEX error: (%d) %s", errno, strerror(errno));
        }
    }

    return success;
}

static bool
_linuxEthernet_SetInterfaceAddress(MetisGenericEther *ether, const char *devstr)
{
    bool success = false;

    assertNull(ether->macAddress, "Should only be called once with null macAddress");

    // get the MAC address of the device
    struct ifreq if_mac;
    memset(&if_mac, 0, sizeof(if_mac));
    strncpy(if_mac.ifr_name, devstr, IFNAMSIZ - 1);
    if (!ioctl(ether->etherSocket, SIOCGIFHWADDR, &if_mac)) {
        if (if_mac.ifr_hwaddr.sa_family == ARPHRD_ETHER) {
            ether->macAddress = parcBuffer_Allocate(ETHER_ADDR_LEN);
            parcBuffer_PutArray(ether->macAddress, ETHER_ADDR_LEN, (uint8_t *) if_mac.ifr_hwaddr.sa_data);
            parcBuffer_Flip(ether->macAddress);
            success = true;
        } else {
            if (metisLogger_IsLoggable(ether->logger, MetisLoggerFacility_IO, PARCLogLevel_Error)) {
                metisLogger_Log(ether->logger, MetisLoggerFacility_IO, PARCLogLevel_Error, __func__,
                                "Device %s does not have an Ethernet hardware address", devstr);
            }
        }
    }
    return success;
}

static bool
_linuxEthernet_Bind(MetisGenericEther *ether)
{
    bool success = false;

    // we need to bind to the ethertype to receive packets
    struct sockaddr_ll my_addr;
    my_addr.sll_family = PF_PACKET;
    my_addr.sll_protocol = htons(ether->ethertype);
    my_addr.sll_ifindex = ether->linuxInterfaceIndex;

    if (!bind(ether->etherSocket, (struct sockaddr *) &my_addr, sizeof(struct sockaddr_ll))) {
        success = true;
    } else {
        if (metisLogger_IsLoggable(ether->logger, MetisLoggerFacility_IO, PARCLogLevel_Error)) {
            metisLogger_Log(ether->logger, MetisLoggerFacility_IO, PARCLogLevel_Error, __func__,
                            "bind error: (%d) %s", errno, strerror(errno));
        }
    }
    return success;
}

static bool
_linuxEthernet_SetNonBlocking(MetisGenericEther *ether)
{
    bool success = false;
    uint32_t on = 1;
    if (!ioctl(ether->etherSocket, FIONBIO, &on)) {
        success = true;
    }
    return success;
}

static bool
_linuxEthernet_SetupSocket(MetisGenericEther *ether, const char *devstr)
{
    bool success = false;
    ether->etherSocket = socket(AF_PACKET, SOCK_RAW, htons(ether->ethertype));
    if (ether->etherSocket > 0) {
        if (_linuxEthernet_SetInterfaceIndex(ether, devstr)) {
            if (_linuxEthernet_SetInterfaceAddress(ether, devstr)) {
                if (_linuxEthernet_Bind(ether)) {
                    // set non-blocking
                    if (_linuxEthernet_SetNonBlocking(ether)) {
                        success = true;
                    }
                }
            }
        }
    }

    if (!success) {
        if (metisLogger_IsLoggable(ether->logger, MetisLoggerFacility_IO, PARCLogLevel_Error)) {
            metisLogger_Log(ether->logger, MetisLoggerFacility_IO, PARCLogLevel_Error, __func__,
                            "setup socket error: (%d) %s", errno, strerror(errno));
        }
    }

    return success;
}