capture_example.c Source File

Reference Documentation

Platform
Napatech SmartNIC
Content Type
Reference Information
Capture Software Version
Link™ Capture Software 12.15
Napatech Software Suite: examples/net/capture/capture_example.c Source File
capture_example.c
Go to the documentation of this file.
1 /*
2  *
3  * Copyright 2025 Napatech A/S. All Rights Reserved.
4  *
5  * 1. Copying, modification, and distribution of this file, or executable
6  * versions of this file, is governed by the terms of the Napatech Software
7  * license agreement under which this file was made available. If you do not
8  * agree to the terms of the license do not install, copy, access or
9  * otherwise use this file.
10  *
11  * 2. Under the Napatech Software license agreement you are granted a
12  * limited, non-exclusive, non-assignable, copyright license to copy, modify
13  * and distribute this file in conjunction with Napatech SmartNIC's and
14  * similar hardware manufactured or supplied by Napatech A/S.
15  *
16  * 3. The full Napatech Software License Agreement is included in this
17  * distribution, please see "NA-0009 Software License Agreement.pdf"
18  *
19  * 4. Redistributions of source code must retain this copyright notice,
20  * list of conditions and the following disclaimer.
21  *
22  * THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT ANY WARRANTIES, EXPRESS OR
23  * IMPLIED, AND NAPATECH DISCLAIMS ALL IMPLIED WARRANTIES INCLUDING ANY
24  * IMPLIED WARRANTY OF TITLE, MERCHANTABILITY, NONINFRINGEMENT, OR OF
25  * FITNESS FOR A PARTICULAR PURPOSE. TO THE EXTENT NOT PROHIBITED BY
26  * APPLICABLE LAW, IN NO EVENT SHALL NAPATECH BE LIABLE FOR PERSONAL INJURY,
27  * OR ANY INCIDENTAL, SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES WHATSOEVER,
28  * INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS OF PROFITS, CORRUPTION OR
29  * LOSS OF DATA, FAILURE TO TRANSMIT OR RECEIVE ANY DATA OR INFORMATION,
30  * BUSINESS INTERRUPTION OR ANY OTHER COMMERCIAL DAMAGES OR LOSSES, ARISING
31  * OUT OF OR RELATED TO YOUR USE OR INABILITY TO USE NAPATECH SOFTWARE OR
32  * SERVICES OR ANY THIRD PARTY SOFTWARE OR APPLICATIONS IN CONJUNCTION WITH
33  * THE NAPATECH SOFTWARE OR SERVICES, HOWEVER CAUSED, REGARDLESS OF THE THEORY
34  * OF LIABILITY (CONTRACT, TORT OR OTHERWISE) AND EVEN IF NAPATECH HAS BEEN
35  * ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. SOME JURISDICTIONS DO NOT ALLOW
36  * THE EXCLUSION OR LIMITATION OF LIABILITY FOR PERSONAL INJURY, OR OF
37  * INCIDENTAL OR CONSEQUENTIAL DAMAGES, SO THIS LIMITATION MAY NOT APPLY TO YOU.
38  *
39  *
40 
41  */
42 
43 /**
44  * @example net/capture/capture_example.c
45  * @section capture_example_description Description
46  *
47  * This source file is an example of how to do capture to disk via the
48  * segment interface using NTAPI.
49  *
50  * The following NTAPI functions are used:
51  * - @ref NT_Init()
52  * - @ref NT_NetRxOpen()
53  * - @ref NT_NTPL()
54  * - @ref NT_NetRxRead()
55  * - @ref NT_NetRxGet()
56  * - @ref NT_NET_GET_SEGMENT_PTR()
57  * - @ref NT_NET_GET_SEGMENT_LENGTH()
58  * - @ref NT_NET_GET_SEGMENT_TIMESTAMP()
59  * - @ref NT_NetRxRelease()
60  * - @ref NT_NetRxClose()
61  * - @ref NT_Done()
62  * - @ref NT_ExplainError()
63  *
64  * @section capture_example_prerequisites Prerequisites
65  * A Napatech capture accelerator is need to run this example. The ntservice.ini
66  * must have at least one HostBuffersRx defined. Below is an example
67  * of a minimum ini-file. It will create a 32MB RX hostbuffer from
68  * NUMA node 0.
69  * @code
70  * [System]
71  * TimestampFormat = NATIVE
72  *
73  * [Adapter0]
74  * AdapterType = NT20E
75  * BusId = 00:0a:00.00
76  * HostBuffersRx = [1,32,0]
77  * @endcode
78  *
79  * @section capture_example_flow Program flow
80  * @{
81  * The following is required to perform capture of segments to disk:
82  * - \#include/nt.h - Applications/Tools only need to include @ref
83  * nt.h to obtain prototypes, macros etc. from NTAPI.
84  * - @ref NT_Init(@ref NTAPI_VERSION) - Initialize the NTAPI
85  * library. @ref NTAPI_VERSION is a define that describes the version
86  * of the API described in the header files included by @ref
87  * nt.h. NT_Init() will ask the NTAPI library to convert return data
88  * to the @ref NTAPI_VERSION if possible. This will ensure that
89  * applications can run on NTAPI libraries of newer versions.
90  * - @ref NT_NetRxOpen() - Open the stream using a stream ID.
91  * The stream ID must match the one used when creating the
92  * filter.
93  * - @ref NT_NTPL() - Assign traffic to the stream. A stream does not
94  * return data until traffic is assigned to it by a filter. Stream
95  * IDs can be shared between other streams.
96  * - NT_NetRxRead() - Get the file header. A NT file header must be
97  * written to the beginning of the file after the last NT_NTPL()
98  * call has been made. Set @ref NtNetRx_s::cmd "NtNetRx_s.cmd"=@ref
99  * NT_NETRX_READ_CMD_GET_FILE_HEADER and issue the NT_NetRxRead()
100  * call. The fileheader is returned in @ref
101  * NtNetRxFileHeader_s::data
102  * "NtNetRx_s.u.fileheader.data".
103  * - Create the capture file and write NT header. Use the OS specific
104  * functions to create a new capture file.
105  * - Optional step. Wait until we start seeing segments that are hit
106  * by the NTPL assign command. This is done to avoid getting
107  * segments that are not fully classified by the stream.
108  * NT_NetRxGet() is called with a timeout of 1000ms and will return
109  * NT_STATUS_TIMEOUT in case nothing is received within 1000ms and
110  * will return NT_SUCCESS when a segment is returned. Segments with NT_NET_GET_SEGMENTLENGTH()==0
111  * can be returned so it is needed to check for the segment length before using data within
112  * the segment. The NT_NET_GET_SEGMENT_TIMESTAMP() macro can still be used on the empty segments.
113  * Return values different from that is an indication of an error. Segments that
114  * are prior to the expected time are released via NT_NetRxRelease().
115  * - NT_NetRxGet(), write to file and NT_NetRxRelease() - Receive
116  * segments, write to disk and release segments. The @ref
117  * SegmentMacros are used to find the segment and length and
118  * timestamp of the segment:
119  * - @ref NT_NET_GET_SEGMENT_PTR() - Get a pointer to the segment.
120  * - @ref NT_NET_GET_SEGMENT_LENGTH() - Get length of the segment to store.
121  * - @ref NT_NET_GET_SEGMENT_TIMESTAMP() - The time the segment was delivered.
122  * - @ref _nt_net_build_pkt_netbuf() and @ref _nt_net_get_next_packet() are used to traverse
123  * packets inside a segment. This is usefull if inspection is needed before saving the
124  * segment.
125  * - NT_NetRxClose() - Close the stream when terminating.
126  * This will close the stream and release the NTPL assignment made on the hostbuffer.
127  * - Close captured file
128  * - @ref NT_Done() - Close down the NTAPI library.
129  *
130  *<hr>
131  * @section capture_example_code Code
132  * @}
133  */
134 
135 // Include this in order to access the Napatech API
136 #include <nt.h>
137 
138 #if defined(__linux__) || defined(__FreeBSD__)
139  #include <signal.h>
140  #include <stdatomic.h>
141 #endif
142 
143 #if defined(WIN32) || defined (WIN64)
144  #define snprintf(dst, ...) _snprintf_s((dst), _countof(dst), __VA_ARGS__)
145 #endif
146 
147 
148 #if defined(WIN32) || defined (WIN64)
149  volatile int appRunning = 0; // The application will run as long as appRunning == 1
150 #else
151  atomic_int appRunning = 0; // The application will run as long as appRunning == 1
152 #endif
153 
154 struct ntpcap_ts_s {
155  uint32_t sec;
156  uint32_t usec;
157 };
158 
159 struct ntpcap_hdr_s {
160  struct ntpcap_ts_s ts;
161  uint32_t caplen;
162  uint32_t wirelen;
163 };
164 
165 /*****************************************************************************
166  Ctrl-C signal handler routine.
167 ******************************************************************************/
168 #if defined(WIN32) || defined (WIN64)
169 static BOOL WINAPI StopApplication(int sig)
170 {
171  (void) sig;
172  appRunning = 0;
173  return TRUE;
174 }
175 #else
176 static void StopApplication(int sig)
177 {
178  if (sig == SIGINT)
179  appRunning = 0;
180 }
181 #endif
182 
183 /*****************************************************************************
184  Main routine. It initializes, configures FPGA, starts needed threads.
185  On Ctrl-C it stops looping and begins the cleanup process.
186 ******************************************************************************/
187 int main(void)
188 {
189  FILE* hf = NULL; // File handle
190  int numSegments = 0; // The number of segments received
191  int numPackets = 0; // The number of packets received
192  uint64_t numBytes = 0; // The number of bytes received
193  uint64_t numBytesWire = 0; // The number of bytes received on the wire
194  char tmpBuffer[20]; // Buffer to build filter string
195  char errorBuffer[NT_ERRBUF_SIZE]; // Error buffer
196  int status; // Status variable
197  NtNetStreamRx_t hNetRx = NULL; // Handle to the RX stream
198  NtConfigStream_t hCfgStream; // Handle to a config stream
199  NtNtplInfo_t ntplInfo; // Return data structure from the NT_NTPL() call.
200  NtNetBuf_t hNetBuf = NULL; // Net buffer container. Segment data is returned in this when calling NT_NetRxGet().
201  NtNetRx_t readCmd; // NetRx read command structure.
202  struct NtNetBuf_s pktNetBuf; // Packet netbuf structure.
203  struct ntpcap_ts_s* pTs = NULL;
204 
205  // Set up ctrl+c handler
206 #if defined(WIN32) || defined (WIN64)
207  SetConsoleCtrlHandler((PHANDLER_ROUTINE)StopApplication, TRUE);
208 #else
209  struct sigaction newaction; // Ctrl+c handle
210  memset(&newaction, 0, sizeof(newaction));
211  newaction.sa_handler = StopApplication;
212  if (sigaction(SIGINT, &newaction, NULL) < 0) {
213  fprintf(stderr, "Failed to register SIGINT sigaction.\n");
214  exit(EXIT_FAILURE);
215  }
216 #endif
217 
218  // Initialize the NTAPI library and thereby check if NTAPI_VERSION can be used together with this library
219  if ((status = NT_Init(NTAPI_VERSION)) != NT_SUCCESS) {
220  // Get the status code as text
221  NT_ExplainError(status, errorBuffer, sizeof(errorBuffer));
222  fprintf(stderr, "NT_Init() failed: %s\n", errorBuffer);
223  return -1;
224  }
225 
226  // Open a config stream to assign a filter to a stream ID.
227  if ((status = NT_ConfigOpen(&hCfgStream, "TestStream")) != NT_SUCCESS) {
228  // Get the status code as text
229  NT_ExplainError(status, errorBuffer, sizeof(errorBuffer));
230  fprintf(stderr, "NT_ConfigOpen() failed: %s\n", errorBuffer);
231  return -1;
232  }
233 
234  // Assign traffic to stream ID 1 and mask all traffic matching the assign statement color=7.
235  if ((status = NT_NTPL(hCfgStream, "Assign[streamid=1;color=7] = port == 0", &ntplInfo, NT_NTPL_PARSER_VALIDATE_NORMAL)) != NT_SUCCESS) {
236  // Get the status code as text
237  NT_ExplainError(status, errorBuffer, sizeof(errorBuffer));
238  fprintf(stderr, "NT_NTPL() failed: %s\n", errorBuffer);
239  fprintf(stderr, ">>> NTPL errorcode: %X\n", ntplInfo.u.errorData.errCode);
240  fprintf(stderr, ">>> %s\n", ntplInfo.u.errorData.errBuffer[0]);
241  fprintf(stderr, ">>> %s\n", ntplInfo.u.errorData.errBuffer[1]);
242  fprintf(stderr, ">>> %s\n", ntplInfo.u.errorData.errBuffer[2]);
243  return -1;
244  }
245 
246  // Used if PCAP header used
247  pTs = (struct ntpcap_ts_s *)(void *)&(ntplInfo.ts);
248 
249  // Close the config stream
250  if ((status = NT_ConfigClose(hCfgStream)) != NT_SUCCESS) {
251  // Get the status code as text
252  NT_ExplainError(status, errorBuffer, sizeof(errorBuffer));
253  fprintf(stderr, "NT_ConfigClose() failed: %s\n", errorBuffer);
254  return -1;
255  }
256 
257  // Open stat stream
258  NtStatStream_t hStat = NULL;
259  if ((status = NT_StatOpen(&hStat, "hStat")) != NT_SUCCESS) {
260  fprintf(stderr, "Failed to create statistics stream: 0x%08X\n", status);
261  return -1;
262  }
263 
264  // Reset stats
265  static NtStatistics_t statSet;
267  statSet.u.query_v4.poll = 1;
268  statSet.u.query_v4.clear = 1;
269  if ((status = NT_StatRead(hStat, &statSet))) {
270  fprintf(stderr, "Failed resetting statistics: 0x%08X\n", status);
271  return -1;
272  }
273 
274  // Get a stream handle with stream ID 1. NT_NET_INTERFACE_SEGMENT specify that we will receive data in a segment based matter.
275  if ((status = NT_NetRxOpen(&hNetRx, "TestStream", NT_NET_INTERFACE_SEGMENT, 1, -1)) != NT_SUCCESS) {
276  // Get the status code as text
277  NT_ExplainError(status, errorBuffer, sizeof(errorBuffer));
278  fprintf(stderr, "NT_NetRxOpen() failed: %s\n", errorBuffer);
279  return -1;
280  }
281 
282  // Read the file header.
284  if ((status = NT_NetRxRead(hNetRx, &readCmd)) != NT_SUCCESS) {
285  NT_ExplainError(status, errorBuffer, sizeof(errorBuffer));
286  fprintf(stderr, "NT_NetRxRead() failed: %s\n", errorBuffer);
287  return -1;
288  }
289 
290  // Create the capture file
291  if ((hf = fopen("capfile.ntcap", "w+b")) == NULL) {
292  perror("Failed to open capfile.ntcap");
293  return -1;
294  }
295 
296  // Write the file header
297  fwrite(readCmd.u.fileheader.data, (size_t)readCmd.u.fileheader.size, 1, hf);
298 
299  // Setting that the application can start processing data
300  appRunning = 1;
301 
302  // Optional step. Wait for the first packet that hit the NTPL assign command
303  printf("Waiting for the first segment\n");
304  while (appRunning == 1) {
305 
306  if ((status = NT_NetRxGet(hNetRx, &hNetBuf, 1000)) != NT_SUCCESS) {
307  if ((status == NT_STATUS_TIMEOUT) || (status == NT_STATUS_TRYAGAIN)) {
308  // Timeouts are ok, we just need to wait a little longer for a segment
309  continue;
310  }
311  // Get the status code as text
312  NT_ExplainError(status, errorBuffer, sizeof(errorBuffer));
313  fprintf(stderr, "NT_NetRxGet() failed: %s\n", errorBuffer);
314  fclose(hf);
315  return -1;
316  }
317  // We got a segment. Check if the timestamp is newer than when the NTPL assign command was applied
318  // If PCAP header configured, we need to convert the timestamps received
320  if ((((struct ntpcap_ts_s *)NT_NET_GET_SEGMENT_PTR(hNetBuf))->sec * 1000000 + ((struct ntpcap_ts_s *)NT_NET_GET_SEGMENT_PTR(hNetBuf))->usec) >
321  (pTs->sec * 1000000 + pTs->usec)) {
322  break; // Break out, we have received a segment that is received after the NTPL assign command was applied
323  }
324  } else
326  if ((((struct ntpcap_ts_s *)NT_NET_GET_SEGMENT_PTR(hNetBuf))->sec * 1000000000 + ((struct ntpcap_ts_s *)NT_NET_GET_SEGMENT_PTR(hNetBuf))->usec) >
327  (pTs->sec * 1000000000 + pTs->usec)) {
328  break; // Break out, we have received a segment that is received after the NTPL assign command was applied
329  }
330  } else {
331  if (NT_NET_GET_SEGMENT_TIMESTAMP(hNetBuf) > ntplInfo.ts) {
332  break; // Break out, we have received a segment that is received after the NTPL assign command was applied
333  }
334  }
335 
336  // Release the segment as it is too "old".
337  if ((status = NT_NetRxRelease(hNetRx, hNetBuf)) != NT_SUCCESS) {
338  // Get the status code as text
339  NT_ExplainError(status, errorBuffer, sizeof(errorBuffer));
340  fprintf(stderr, "NT_NetRxRelease() failed: %s\n", errorBuffer);
341  fclose(hf);
342  return -1;
343  }
344  }
345 
346  // Write 10 segments to disk
347  while (appRunning == 1 && hNetBuf != NULL) {
348  if (NT_NET_GET_SEGMENT_LENGTH(hNetBuf)) {
349  // Optional step. Here all packets are inspected before storing
350  // Start by building a packet netbuf structure
353  {
354  struct ntpcap_hdr_s* pHdr = (struct ntpcap_hdr_s *)NT_NET_GET_SEGMENT_PTR(hNetBuf);
355  uint64_t segLength = NT_NET_GET_SEGMENT_LENGTH(hNetBuf);
356  uint64_t totSegmentBytes = 0;
357  while (totSegmentBytes < segLength) {
358  if (pHdr->wirelen) {
359  numPackets++;
360  numBytesWire += pHdr->wirelen;
361  }
362  totSegmentBytes += pHdr->caplen + (uint32_t)sizeof(struct ntpcap_hdr_s);
363  pHdr = (struct ntpcap_hdr_s *)((uint8_t *)pHdr + pHdr->caplen + sizeof(struct ntpcap_hdr_s));
364  }
365  } else {
366  _nt_net_build_pkt_netbuf(hNetBuf, &pktNetBuf);
367  do {
368  // Just count the amount of packets and wire length
369  numPackets++;
370  numBytesWire += NT_NET_GET_PKT_WIRE_LENGTH((&pktNetBuf));
371  } while (_nt_net_get_next_packet(hNetBuf, NT_NET_GET_SEGMENT_LENGTH(hNetBuf), &pktNetBuf)>0);
372  }
373 
374  if (fwrite(NT_NET_GET_SEGMENT_PTR(hNetBuf), NT_NET_GET_SEGMENT_LENGTH(hNetBuf), 1, hf) <= 0) {
375  perror("Failed writing segment");
376  fclose(hf);
377  return -1;
378  }
379  // Increment the number of segments processed.
380  numSegments++;
381  // Increment the bytes received
382  numBytes += NT_NET_GET_SEGMENT_LENGTH(hNetBuf);
383  printf("%016llx - Received segment of %lu bytes.\n",
384  (unsigned long long)NT_NET_GET_SEGMENT_TIMESTAMP(hNetBuf), NT_NET_GET_SEGMENT_LENGTH(hNetBuf));
385  }
386 
387  // Release the current segment
388  if ((status = NT_NetRxRelease(hNetRx, hNetBuf)) != NT_SUCCESS) {
389  // Get the status code as text
390  NT_ExplainError(status, errorBuffer, sizeof(errorBuffer));
391  fprintf(stderr, "NT_NetRxRelease() failed: %s\n", errorBuffer);
392  fclose(hf);
393  return -1;
394  }
395 
396  if (numSegments == 10) {
397  break;
398  }
399 
400  // Get the next segment
401  while (appRunning == 1) {
402  if ((status = NT_NetRxGet(hNetRx, &hNetBuf, 1000)) != NT_SUCCESS) {
403  if ((status == NT_STATUS_TIMEOUT) || (status == NT_STATUS_TRYAGAIN)) {
404  // Timeouts are ok, we just need to wait a little longer for a segment
405  continue;
406  }
407  // Get the status code as text
408  NT_ExplainError(status, errorBuffer, sizeof(errorBuffer));
409  fprintf(stderr, "NT_NetRxGet() failed: %s\n", errorBuffer);
410  fclose(hf);
411  return -1;
412  }
413  break; // We got a segment
414  }
415  }
416 
417  // Close the stream and release the hostbuffer. This will also remove the NTPL assignments performed.
418  NT_NetRxClose(hNetRx);
419 
420  // Close the file
421  fclose(hf);
422 
423  // Request stats
425  statSet.u.query_v4.poll = 1;
426  statSet.u.query_v4.clear = 0;
427  if ((status = NT_StatRead(hStat, &statSet)) != NT_SUCCESS) {
428  fprintf(stderr, "Failed reading statistics: 0x%08X\n", status);
429  return -1;
430  }
431 
432  // Read drop counters for streamid 1
433  uint64_t totDropsPkts = statSet.u.query_v4.data.stream.streamid[1].drop.pkts;
434  uint64_t totDropsBytes = statSet.u.query_v4.data.stream.streamid[1].drop.octets;
435 
436  // Close stat stream
437  NT_StatClose(hStat);
438 
439 
440  // Open a config stream to delete a filter.
441  if ((status = NT_ConfigOpen(&hCfgStream, "TestStream")) != NT_SUCCESS) {
442  // Get the status code as text
443  NT_ExplainError(status, errorBuffer, sizeof(errorBuffer));
444  fprintf(stderr, "NT_ConfigOpen() failed: %s\n", errorBuffer);
445  return -1;
446  }
447 
448  // Delete the filter
449  snprintf(tmpBuffer, sizeof(tmpBuffer), "delete=%d", ntplInfo.ntplId);
450  if ((status = NT_NTPL(hCfgStream, tmpBuffer, &ntplInfo, NT_NTPL_PARSER_VALIDATE_NORMAL)) != NT_SUCCESS) {
451  // Get the status code as text
452  NT_ExplainError(status, errorBuffer, sizeof(errorBuffer));
453  fprintf(stderr, "NT_NTPL() failed: %s\n", errorBuffer);
454  fprintf(stderr, ">>> NTPL errorcode: %X\n", ntplInfo.u.errorData.errCode);
455  fprintf(stderr, ">>> %s\n", ntplInfo.u.errorData.errBuffer[0]);
456  fprintf(stderr, ">>> %s\n", ntplInfo.u.errorData.errBuffer[1]);
457  fprintf(stderr, ">>> %s\n", ntplInfo.u.errorData.errBuffer[2]);
458  return -1;
459  }
460 
461  // Close the config stream
462  if ((status = NT_ConfigClose(hCfgStream)) != NT_SUCCESS) {
463  // Get the status code as text
464  NT_ExplainError(status, errorBuffer, sizeof(errorBuffer));
465  fprintf(stderr, "NT_ConfigClose() failed: %s\n", errorBuffer);
466  return -1;
467  }
468 
469  printf("Drop: %16lu packets, %16lu bytes\n", totDropsPkts, totDropsBytes);
470  printf("Done: %16d segments, %16d packets, %16lu bytes, %16lu bytes on wire\n", numSegments, numPackets, numBytes, numBytesWire);
471 
472  // Close down the NTAPI library
473  NT_Done();
474 
475  return 0;
476 }
477 
478 //
479 // EOF
480 //