pcap_driver.c
Go to the documentation of this file.
1 /**
2  * @file pcap_driver.c
3  * @brief PCAP driver
4  *
5  * @section License
6  *
7  * SPDX-License-Identifier: GPL-2.0-or-later
8  *
9  * Copyright (C) 2010-2020 Oryx Embedded SARL. All rights reserved.
10  *
11  * This file is part of CycloneTCP Open.
12  *
13  * This program is free software; you can redistribute it and/or
14  * modify it under the terms of the GNU General Public License
15  * as published by the Free Software Foundation; either version 2
16  * of the License, or (at your option) any later version.
17  *
18  * This program is distributed in the hope that it will be useful,
19  * but WITHOUT ANY WARRANTY; without even the implied warranty of
20  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21  * GNU General Public License for more details.
22  *
23  * You should have received a copy of the GNU General Public License
24  * along with this program; if not, write to the Free Software Foundation,
25  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
26  *
27  * @author Oryx Embedded SARL (www.oryx-embedded.com)
28  * @version 1.9.8
29  **/
30 
31 //Switch to the appropriate trace level
32 #define TRACE_LEVEL NIC_TRACE_LEVEL
33 
34 //Dependencies
35 #include <stdlib.h>
36 #include "core/net.h"
38 #include "debug.h"
39 
40 //Undefine conflicting definitions
41 #undef Socket
42 #undef htons
43 #undef htonl
44 #undef ntohs
45 #undef ntohl
46 
47 //PCAP dependencies
48 #include <pcap.h>
49 
50 //Undefine conflicting definitions
51 #undef interface
52 
53 
54 /**
55  * @brief Packet descriptor
56  **/
57 
58 typedef struct
59 {
60  size_t length;
63 
64 
65 /**
66  * @brief PCAP driver context
67  **/
68 
69 typedef struct
70 {
71  pcap_t *handle;
76 
77 
78 /**
79  * @brief PCAP driver
80  **/
81 
83 {
85  ETH_MTU,
93  NULL,
94  NULL,
95  NULL,
96  TRUE,
97  TRUE,
98  TRUE,
99  TRUE
100 };
101 
102 
103 /**
104  * @brief PCAP driver initialization
105  * @param[in] interface Underlying network interface
106  * @return Error code
107  **/
108 
110 {
111  int_t ret;
112  uint_t i;
113  uint_t j;
114  pcap_if_t *device;
115  pcap_if_t *deviceList;
116  struct bpf_program filerCode;
117  char_t filterExpr[256];
118  char_t errorBuffer[PCAP_ERRBUF_SIZE];
119  PcapDriverContext *context;
120 #if (NET_RTOS_SUPPORT == ENABLED)
121  OsTask *task;
122 #endif
123 
124  //Debug message
125  TRACE_INFO("Initializing PCAP driver...\r\n");
126 
127  //Allocate PCAP driver context
128  context = (PcapDriverContext *) malloc(sizeof(PcapDriverContext));
129 
130  //Failed to allocate memory?
131  if(context == NULL)
132  {
133  //Debug message
134  printf("Failed to allocate context!\r\n");
135 
136  //Report an error
137  return ERROR_FAILURE;
138  }
139 
140  //Attach the PCAP driver context to the network interface
141  *((PcapDriverContext **) interface->nicContext) = context;
142  //Clear PCAP driver context
143  osMemset(context, 0, sizeof(PcapDriverContext));
144 
145  //Find all the devices
146  ret = pcap_findalldevs(&deviceList, errorBuffer);
147 
148  //Any error to report?
149  if(ret != 0)
150  {
151  //Debug message
152  printf("Failed to list devices!\r\n");
153 
154  //Clean up side effects
155  free(context);
156 
157  //Report an error
158  return ERROR_FAILURE;
159  }
160 
161  //No network adapter found?
162  if(deviceList == NULL)
163  {
164  //Debug message
165  printf("No network adapter found!\r\n");
166 
167  //Clean up side effects
168  free(context);
169 
170  //Exit immediately
171  return ERROR_FAILURE;
172  }
173 
174  //Network adapter selection
175  while(1)
176  {
177  //Debug message
178  printf("Network adapters:\r\n");
179 
180  //Point to the first device
181  device = deviceList;
182  i = 0;
183 
184  //Loop through the list of devices
185  while(device != NULL)
186  {
187  //Index of the current network adapter
188  printf(" %-2u", i + 1);
189 
190 #if !defined(_WIN32)
191  //Display the name of the device
192  if(device->name != NULL)
193  {
194  printf(" %-8s", device->name);
195  }
196 #endif
197  //Description of the device
198  if(device->description != NULL)
199  {
200  printf(" %s\r\n", device->description);
201  }
202  else
203  {
204  printf(" -\r\n");
205  }
206 
207  //Next device
208  device = device->next;
209  i++;
210  }
211 
212  //Display message
213  printf("Select network adapter for %s interface (1-%u):", interface->name, i);
214  //Get user choice
215  scanf("%d", &j);
216 
217  //Valid selection?
218  if(j >= 1 && j <= i)
219  {
220  break;
221  }
222  }
223 
224  //Point to the first device
225  device = deviceList;
226 
227  //Point to the desired network adapter
228  for(i = 1; i < j; i++)
229  {
230  device = device->next;
231  }
232 
233  //Open the device
234  context->handle = pcap_open_live(device->name, 65535,
235  TRUE, PCAP_DRIVER_TIMEOUT, errorBuffer);
236 
237  //Failed to open device?
238  if(context->handle == NULL)
239  {
240  //Debug message
241  printf("Failed to open device!\r\n");
242 
243  //Clean up side effects
244  pcap_freealldevs(deviceList);
245  free(context);
246 
247  //Report an error
248  return ERROR_FAILURE;
249  }
250 
251  //Free the device list
252  pcap_freealldevs(deviceList);
253 
254  //Filter expression
255  osSprintf(filterExpr, "!(ether src %02x:%02x:%02x:%02x:%02x:%02x) && "
256  "((ether dst %02x:%02x:%02x:%02x:%02x:%02x) || (ether broadcast) || (ether multicast))",
257  interface->macAddr.b[0], interface->macAddr.b[1], interface->macAddr.b[2],
258  interface->macAddr.b[3], interface->macAddr.b[4], interface->macAddr.b[5],
259  interface->macAddr.b[0], interface->macAddr.b[1], interface->macAddr.b[2],
260  interface->macAddr.b[3], interface->macAddr.b[4], interface->macAddr.b[5]);
261 
262  //Compile the filter
263  ret = pcap_compile(context->handle, &filerCode, filterExpr, 1, 0);
264 
265  //Failed to open device?
266  if(ret != 0)
267  {
268  //Debug message
269  printf("Failed to compile filter!\r\n");
270 
271  //Clean up side effects
272  pcap_close(context->handle);
273  free(context);
274 
275  //Report an error
276  return ERROR_FAILURE;
277  }
278 
279  //Set the filter
280  ret = pcap_setfilter(context->handle, &filerCode);
281 
282  //Failed to open device?
283  if(ret != 0)
284  {
285  //Debug message
286  printf("Failed to set filter!\r\n");
287 
288  //Clean up side effects
289  pcap_close(context->handle);
290  free(context);
291 
292  //Report an error
293  return ERROR_FAILURE;
294  }
295 
296 #if (NET_RTOS_SUPPORT == ENABLED)
297  //Create the receive task
298  task = osCreateTask("PCAP", (OsTaskCode) pcapDriverTask, interface, 0, 0);
299 
300  //Failed to create the task?
301  if(task == OS_INVALID_HANDLE)
302  {
303  //Debug message
304  printf("Failed to create task!\r\n");
305 
306  //Clean up side effects
307  pcap_close(context->handle);
308  free(context);
309 
310  //Report an error
311  return ERROR_FAILURE;
312  }
313 #endif
314 
315  //Accept any packets from the upper layer
316  osSetEvent(&interface->nicTxEvent);
317 
318  //Return status code
319  return NO_ERROR;
320 }
321 
322 
323 /**
324  * @brief PCAP timer handler
325  *
326  * This routine is periodically called by the TCP/IP stack to handle periodic
327  * operations such as polling the link state
328  *
329  * @param[in] interface Underlying network interface
330  **/
331 
332 void pcapDriverTick(NetInterface *interface)
333 {
334  //Not implemented
335 }
336 
337 
338 /**
339  * @brief Enable interrupts
340  * @param[in] interface Underlying network interface
341  **/
342 
344 {
345  //Not implemented
346 }
347 
348 
349 /**
350  * @brief Disable interrupts
351  * @param[in] interface Underlying network interface
352  **/
353 
355 {
356  //Not implemented
357 }
358 
359 
360 /**
361  * @brief PCAP event handler
362  * @param[in] interface Underlying network interface
363  **/
364 
366 {
367  uint_t n;
368  PcapDriverContext *context;
369  NetRxAncillary ancillary;
370 
371  //Point to the PCAP driver context
372  context = *((PcapDriverContext **) interface->nicContext);
373 
374  //Process all pending packets
375  while(context->queue[context->readIndex].length > 0)
376  {
377  //Additional options can be passed to the stack along with the packet
378  ancillary = NET_DEFAULT_RX_ANCILLARY;
379 
380  //Pass the packet to the upper layer
381  nicProcessPacket(interface, context->queue[context->readIndex].data,
382  context->queue[context->readIndex].length, &ancillary);
383 
384  //Compute the index of the next packet descriptor
385  n = (context->readIndex + 1) % PCAP_DRIVER_QUEUE_SIZE;
386 
387  //Release the current packet
388  context->queue[context->readIndex].length = 0;
389  //Point to the next packet descriptor
390  context->readIndex = n;
391  }
392 }
393 
394 
395 /**
396  * @brief Send a packet
397  * @param[in] interface Underlying network interface
398  * @param[in] buffer Multi-part buffer containing the data to send
399  * @param[in] offset Offset to the first data byte
400  * @param[in] ancillary Additional options passed to the stack along with
401  * the packet
402  * @return Error code
403  **/
404 
406  const NetBuffer *buffer, size_t offset, NetTxAncillary *ancillary)
407 {
408  int_t ret;
409  size_t length;
410  PcapDriverContext *context;
411  uint8_t temp[PCAP_DRIVER_MAX_PACKET_SIZE];
412 
413  //Point to the PCAP driver context
414  context = *((PcapDriverContext **) interface->nicContext);
415 
416  //Retrieve the length of the packet
417  length = netBufferGetLength(buffer) - offset;
418 
419  //Check the frame length
421  {
422  //The transmitter can accept another packet
423  osSetEvent(&interface->nicTxEvent);
424  //Report an error
425  return ERROR_INVALID_LENGTH;
426  }
427 
428  //Copy the packet to the transmit buffer
429  netBufferRead(temp, buffer, offset, length);
430 
431  //Send packet
432  ret = pcap_sendpacket(context->handle, temp, length);
433 
434  //The transmitter can accept another packet
435  osSetEvent(&interface->nicTxEvent);
436 
437  //Return status code
438  if(ret < 0)
439  {
440  return ERROR_FAILURE;
441  }
442  else
443  {
444  return NO_ERROR;
445  }
446 }
447 
448 
449 /**
450  * @brief Configure MAC address filtering
451  * @param[in] interface Underlying network interface
452  * @return Error code
453  **/
454 
456 {
457  //Not implemented
458  return NO_ERROR;
459 }
460 
461 
462 /**
463  * @brief PCAP receive task
464  * @param[in] interface Underlying network interface
465  **/
466 
467 void pcapDriverTask(NetInterface *interface)
468 {
469  int_t ret;
470  uint_t n;
471  uint_t length;
472  const uint8_t *data;
473  struct pcap_pkthdr *header;
474  PcapDriverContext *context;
475 
476  //Point to the PCAP driver context
477  context = *((PcapDriverContext **) interface->nicContext);
478 
479  //Process events
480  while(1)
481  {
482  //Wait for an incoming packet
483  ret = pcap_next_ex(context->handle, &header, &data);
484 
485  //Any packet received?
486  if(ret > 0)
487  {
488  //Retrieve the length of the packet
489  length = header->caplen;
490 
491  //Check the length of the received packet
493  {
494  //Check whether the link is up
495  if(interface->linkState)
496  {
497  //Compute the index of the next packet descriptor
498  n = (context->writeIndex + 1) % PCAP_DRIVER_QUEUE_SIZE;
499 
500  //Ensure the receive queue is not full
501  if(n != context->readIndex)
502  {
503  //Copy the incoming packet
504  osMemcpy(context->queue[context->writeIndex].data, data, length);
505  //Save the length of the packet
506  context->queue[context->writeIndex].length = length;
507 
508  //Point to the next packet descriptor
509  context->writeIndex = n;
510 
511  //Set event flag
512  interface->nicEvent = TRUE;
513  //Notify the TCP/IP stack of the event
515  }
516  }
517  }
518  }
519  else
520  {
521 #if (NET_RTOS_SUPPORT == DISABLED)
522  //No packet has been received
523  break;
524 #endif
525  }
526  }
527 }
uint8_t length
Definition: coap_common.h:190
void pcapDriverTick(NetInterface *interface)
PCAP timer handler.
Definition: pcap_driver.c:332
#define PCAP_DRIVER_MAX_PACKET_SIZE
Definition: pcap_driver.h:39
#define netEvent
Definition: net_legacy.h:267
uint8_t data[]
Definition: ethernet.h:209
signed int int_t
Definition: compiler_port.h:44
size_t netBufferRead(void *dest, const NetBuffer *src, size_t srcOffset, size_t length)
Read data from a multi-part buffer.
Definition: net_mem.c:672
Structure describing a buffer that spans multiple chunks.
Definition: net_mem.h:88
#define TRUE
Definition: os_port.h:50
void pcapDriverEventHandler(NetInterface *interface)
PCAP event handler.
Definition: pcap_driver.c:365
const NicDriver pcapDriver
PCAP driver.
Definition: pcap_driver.c:82
void nicProcessPacket(NetInterface *interface, uint8_t *packet, size_t length, NetRxAncillary *ancillary)
Handle a packet received by the network controller.
Definition: nic.c:388
PCAP driver context.
Definition: pcap_driver.c:69
error_t pcapDriverInit(NetInterface *interface)
PCAP driver initialization.
Definition: pcap_driver.c:109
OsTask * osCreateTask(const char_t *name, OsTaskCode taskCode, void *param, size_t stackSize, int_t priority)
Create a new task.
#define osMemcpy(dest, src, length)
Definition: os_port.h:134
error_t
Error codes.
Definition: error.h:42
#define osSprintf(dest,...)
Definition: os_port.h:206
const NetRxAncillary NET_DEFAULT_RX_ANCILLARY
Definition: net_misc.c:96
Generic error code.
Definition: error.h:45
#define NetRxAncillary
Definition: net_misc.h:40
#define NetInterface
Definition: net.h:36
Task object.
#define NetTxAncillary
Definition: net_misc.h:36
#define PCAP_DRIVER_TIMEOUT
Definition: pcap_driver.h:53
PcapDriverPacket queue[PCAP_DRIVER_QUEUE_SIZE]
Definition: pcap_driver.c:74
#define TRACE_INFO(...)
Definition: debug.h:95
size_t netBufferGetLength(const NetBuffer *buffer)
Get the actual length of a multi-part buffer.
Definition: net_mem.c:297
Packet descriptor.
Definition: pcap_driver.c:58
void pcapDriverEnableIrq(NetInterface *interface)
Enable interrupts.
Definition: pcap_driver.c:343
PCAP driver.
uint8_t data[PCAP_DRIVER_MAX_PACKET_SIZE]
Definition: pcap_driver.c:61
char char_t
Definition: compiler_port.h:43
#define OS_INVALID_HANDLE
Definition: os_port.h:79
#define ETH_MTU
Definition: ethernet.h:105
void(* OsTaskCode)(void *param)
Task routine.
uint8_t n
error_t pcapDriverUpdateMacAddrFilter(NetInterface *interface)
Configure MAC address filtering.
Definition: pcap_driver.c:455
void osSetEvent(OsEvent *event)
Set the specified event object to the signaled state.
#define PCAP_DRIVER_QUEUE_SIZE
Definition: pcap_driver.h:46
unsigned int uint_t
Definition: compiler_port.h:45
#define osMemset(p, value, length)
Definition: os_port.h:128
TCP/IP stack core.
NIC driver.
Definition: nic.h:257
void pcapDriverDisableIrq(NetInterface *interface)
Disable interrupts.
Definition: pcap_driver.c:354
error_t pcapDriverSendPacket(NetInterface *interface, const NetBuffer *buffer, size_t offset, NetTxAncillary *ancillary)
Send a packet.
Definition: pcap_driver.c:405
Success.
Definition: error.h:44
Debugging facilities.
void pcapDriverTask(NetInterface *interface)
PCAP receive task.
Definition: pcap_driver.c:467
Ethernet interface.
Definition: nic.h:82