• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2009 Felix Obenhuber
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  *
9  * 1. Redistributions of source code must retain the above copyright
10  * notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  * notice, this list of conditions and the following disclaimer in the
13  * documentation and/or other materials provided with the distribution.
14  * 3. The name of the author may not be used to endorse or promote
15  * products derived from this software without specific prior written
16  * permission.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29  *
30  * Sockettrace sniffing API implementation for Linux platform
31  * By Felix Obenhuber <felix@obenhuber.de>
32  *
33  */
34 
35 #ifdef HAVE_CONFIG_H
36 #include "config.h"
37 #endif
38 
39 #include <libusb-1.0/libusb.h>
40 
41 #include <stdlib.h>
42 #include <unistd.h>
43 #include <fcntl.h>
44 #include <errno.h>
45 #include <string.h>
46 #include <pthread.h>
47 
48 #include "pcap-int.h"
49 #include "pcap-canusb-linux.h"
50 
51 #define CANUSB_IFACE "canusb"
52 
53 #define CANUSB_VID 0x0403
54 #define CANUSB_PID 0x8990
55 
56 #define USE_THREAD 1
57 
58 #if USE_THREAD == 0
59 #include <signal.h>
60 #endif
61 
62 
63 /* forward declaration */
64 static int canusb_activate(pcap_t *);
65 static int canusb_read_linux(pcap_t *, int , pcap_handler , u_char *);
66 static int canusb_inject_linux(pcap_t *, const void *, size_t);
67 static int canusb_setfilter_linux(pcap_t *, struct bpf_program *);
68 static int canusb_setdirection_linux(pcap_t *, pcap_direction_t);
69 static int canusb_stats_linux(pcap_t *, struct pcap_stat *);
70 
71 struct CAN_Msg
72 {
73     uint32_t timestamp;
74     uint32_t id;
75     uint32_t length;
76     uint8_t data[8];
77 };
78 
79 /*
80  * Private data for capturing on Linux CANbus USB devices.
81  */
82 struct pcap_canusb {
83     libusb_context *ctx;
84     libusb_device_handle *dev;
85     pthread_t worker;
86     int rdpipe, wrpipe;
87     volatile int loop;
88 };
89 
canusb_findalldevs(pcap_if_t ** alldevsp,char * err_str)90 int canusb_findalldevs(pcap_if_t **alldevsp, char *err_str)
91 {
92     libusb_context *fdctx;
93     libusb_device** devs;
94     unsigned char sernum[65];
95     int cnt, i;
96 
97     if (libusb_init(&fdctx) != 0) {
98         /*
99          * XXX - if this doesn't just mean "no USB file system mounted",
100          * perhaps we should report a real error rather than just
101          * saying "no CANUSB devices".
102          */
103         return 0;
104     }
105 
106     cnt = libusb_get_device_list(fdctx,&devs);
107 
108     for(i=0;i<cnt;i++)
109     {
110         int ret;
111         // Check if this device is interesting.
112         struct libusb_device_descriptor desc;
113         libusb_get_device_descriptor(devs[i],&desc);
114 
115         if ((desc.idVendor != CANUSB_VID) || (desc.idProduct != CANUSB_PID))
116             continue; //It is not, check next device
117 
118         //It is!
119         libusb_device_handle *dh = NULL;
120 
121         if ((ret = libusb_open(devs[i],&dh)) == 0)
122         {
123             char dev_name[30];
124             char dev_descr[50];
125             int n = libusb_get_string_descriptor_ascii(dh,desc.iSerialNumber,sernum,64);
126             sernum[n] = 0;
127 
128             snprintf(dev_name, 30, CANUSB_IFACE"%s", sernum);
129             snprintf(dev_descr, 50, "CanUSB [%s]", sernum);
130 
131             libusb_close(dh);
132 
133             if (pcap_add_if(alldevsp, dev_name, 0, dev_descr, err_str) < 0)
134             {
135                 libusb_free_device_list(devs,1);
136                 libusb_exit(fdctx);
137                 return -1;
138             }
139         }
140     }
141 
142     libusb_free_device_list(devs,1);
143     libusb_exit(fdctx);
144     return 0;
145 }
146 
canusb_opendevice(struct libusb_context * ctx,char * devserial)147 static libusb_device_handle* canusb_opendevice(struct libusb_context *ctx, char* devserial)
148 {
149     libusb_device** devs;
150     unsigned char serial[65];
151     int cnt,i,n;
152 
153     cnt = libusb_get_device_list(ctx,&devs);
154 
155     for(i=0;i<cnt;i++)
156     {
157         // Check if this device is interesting.
158         struct libusb_device_descriptor desc;
159         libusb_get_device_descriptor(devs[i],&desc);
160 
161         if ((desc.idVendor != CANUSB_VID) || (desc.idProduct != CANUSB_PID))
162           continue;
163 
164         //Found one!
165         libusb_device_handle *dh = NULL;
166 
167         if (libusb_open(devs[i],&dh) != 0) continue;
168 
169         n = libusb_get_string_descriptor_ascii(dh,desc.iSerialNumber,serial,64);
170         serial[n] = 0;
171 
172         if ((devserial) && (strcmp((char *)serial,devserial) != 0))
173         {
174             libusb_close(dh);
175             continue;
176         }
177 
178         if ((libusb_kernel_driver_active(dh,0)) && (libusb_detach_kernel_driver(dh,0) != 0))
179         {
180             libusb_close(dh);
181             continue;
182         }
183 
184         if (libusb_set_configuration(dh,1) != 0)
185         {
186             libusb_close(dh);
187             continue;
188         }
189 
190         if (libusb_claim_interface(dh,0) != 0)
191         {
192             libusb_close(dh);
193             continue;
194         }
195 
196         //Fount it!
197         libusb_free_device_list(devs,1);
198         return dh;
199     }
200 
201     libusb_free_device_list(devs,1);
202     return NULL;
203 }
204 
205 
206 pcap_t *
canusb_create(const char * device,char * ebuf,int * is_ours)207 canusb_create(const char *device, char *ebuf, int *is_ours)
208 {
209     const char *cp;
210     char *cpend;
211     long devnum;
212     pcap_t* p;
213     struct pcap_canusb *canusb;
214 
215     /* Does this look like a DAG device? */
216     cp = strrchr(device, '/');
217     if (cp == NULL)
218         cp = device;
219     /* Does it begin with "canusb"? */
220     if (strncmp(cp, "canusb", 6) != 0) {
221         /* Nope, doesn't begin with "canusb" */
222         *is_ours = 0;
223         return NULL;
224     }
225     /* Yes - is "canusb" followed by a number? */
226     cp += 6;
227     devnum = strtol(cp, &cpend, 10);
228     if (cpend == cp || *cpend != '\0') {
229         /* Not followed by a number. */
230         *is_ours = 0;
231         return NULL;
232     }
233     if (devnum < 0) {
234         /* Followed by a non-valid number. */
235         *is_ours = 0;
236         return NULL;
237     }
238 
239     /* OK, it's probably ours. */
240     *is_ours = 1;
241 
242     p = pcap_create_common(device, ebuf, sizeof (struct pcap_canusb));
243     if (p == NULL)
244         return (NULL);
245 
246     canusb = p->priv;
247     canusb->ctx = NULL;
248     canusb->dev = NULL;
249     canusb->rdpipe = -1;
250     canusb->wrpipe = -1;
251 
252     p->activate_op = canusb_activate;
253 
254     return (p);
255 }
256 
257 
canusb_capture_thread(void * arg)258 static void* canusb_capture_thread(void *arg)
259 {
260     struct pcap_canusb *canusb = arg;
261     int i;
262     struct
263     {
264       uint8_t rxsz, txsz;
265     } status;
266 
267     fcntl(canusb->wrpipe, F_SETFL, O_NONBLOCK);
268 
269     while(canusb->loop)
270     {
271         int sz;
272         struct CAN_Msg msg;
273 
274         libusb_interrupt_transfer(canusb->dev, 0x81, (unsigned char*)&status, sizeof(status), &sz, 100);
275         //HACK!!!!! -> drop buffered data, read new one by reading twice.
276         libusb_interrupt_transfer(canusb->dev, 0x81, (unsigned char*)&status, sizeof(status), &sz, 100);
277 
278         for(i = 0; i<status.rxsz; i++)
279         {
280             libusb_bulk_transfer(canusb->dev, 0x85, (unsigned char*)&msg, sizeof(msg), &sz, 100);
281             if(write(canusb->wrpipe, &msg, sizeof(msg)) < 0)
282                 fprintf(stderr,"write() error: %s\n", strerror(errno));
283         }
284 
285     }
286 
287     return NULL;
288 }
289 
canusb_startcapture(struct pcap_canusb * this)290 static int canusb_startcapture(struct pcap_canusb* this)
291 {
292     int pipefd[2];
293 
294     if (pipe(pipefd) == -1)
295         return -1;
296 
297     this->rdpipe = pipefd[0];
298     this->wrpipe = pipefd[1];
299 
300     this->loop = 1;
301     pthread_create(&this->worker, NULL, canusb_capture_thread, this);
302 
303     return this->rdpipe;
304 }
305 
canusb_clearbufs(struct pcap_canusb * this)306 static void canusb_clearbufs(struct pcap_canusb* this)
307 {
308     unsigned char cmd[16];
309     int al;
310 
311     cmd[0] = 1;  //Empty incoming buffer
312     cmd[1] = 1;  //Empty outgoing buffer
313     cmd[3] = 0;  //Not a write to serial number
314     memset(&cmd[4],0,16-4);
315 
316     libusb_interrupt_transfer(this->dev, 0x1,cmd,16,&al,100);
317 }
318 
319 
canusb_close(pcap_t * handle)320 static void canusb_close(pcap_t* handle)
321 {
322     struct pcap_canusb *canusb = handle->priv;
323 
324     canusb->loop = 0;
325     pthread_join(canusb->worker, NULL);
326 
327     if (canusb->dev)
328     {
329         libusb_close(canusb->dev);
330         canusb->dev = NULL;
331     }
332     if (canusb->ctx)
333     {
334         libusb_exit(canusb->ctx);
335         canusb->ctx = NULL;
336     }
337 }
338 
339 
340 
canusb_activate(pcap_t * handle)341 static int canusb_activate(pcap_t* handle)
342 {
343     struct pcap_canusb *canusb = handle->priv;
344     char *serial;
345 
346     if (libusb_init(&canusb->ctx) != 0) {
347         /*
348          * XXX - what causes this to fail?
349          */
350         snprintf(handle->errbuf, PCAP_ERRBUF_SIZE, "libusb_init() failed");
351         return PCAP_ERROR;
352     }
353 
354     handle->read_op = canusb_read_linux;
355 
356     handle->inject_op = canusb_inject_linux;
357     handle->setfilter_op = canusb_setfilter_linux;
358     handle->setdirection_op = canusb_setdirection_linux;
359     handle->getnonblock_op = pcap_getnonblock_fd;
360     handle->setnonblock_op = pcap_setnonblock_fd;
361     handle->stats_op = canusb_stats_linux;
362     handle->cleanup_op = canusb_close;
363 
364     /* Initialize some components of the pcap structure. */
365     handle->bufsize = 32;
366     handle->offset = 8;
367     handle->linktype = DLT_CAN_SOCKETCAN;
368     handle->set_datalink_op = NULL;
369 
370     serial = handle->opt.source + strlen(CANUSB_IFACE);
371 
372     canusb->dev = canusb_opendevice(canusb->ctx, serial);
373     if (!canusb->dev)
374     {
375         libusb_exit(canusb->ctx);
376         snprintf(handle->errbuf, PCAP_ERRBUF_SIZE, "Can't open USB Device");
377         return PCAP_ERROR;
378     }
379 
380     canusb_clearbufs(canusb);
381 
382     handle->fd = canusb_startcapture(canusb);
383     handle->selectable_fd = handle->fd;
384 
385     return 0;
386 }
387 
388 
389 
390 
391 static int
canusb_read_linux(pcap_t * handle,int max_packets,pcap_handler callback,u_char * user)392 canusb_read_linux(pcap_t *handle, int max_packets, pcap_handler callback, u_char *user)
393 {
394     static struct timeval firstpacket = { -1, -1};
395     int i = 0;
396     struct CAN_Msg msg;
397     struct pcap_pkthdr pkth;
398 
399     while(i < max_packets)
400     {
401         int n;
402         usleep(10 * 1000);
403         n = read(handle->fd, &msg, sizeof(msg));
404         if (n <= 0)
405             break;
406         pkth.caplen = pkth.len = n;
407         pkth.caplen -= 4;
408         pkth.caplen -= 8 - msg.length;
409 
410         if ((firstpacket.tv_sec == -1) && (firstpacket.tv_usec == -1))
411             gettimeofday(&firstpacket, NULL);
412 
413         pkth.ts.tv_usec = firstpacket.tv_usec + (msg.timestamp % 100) * 10000;
414         pkth.ts.tv_sec = firstpacket.tv_usec + (msg.timestamp / 100);
415         if (pkth.ts.tv_usec > 1000000)
416         {
417             pkth.ts.tv_usec -= 1000000;
418             pkth.ts.tv_sec++;
419         }
420 
421         callback(user, &pkth, (void*)&msg.id);
422         i++;
423     }
424 
425     return i;
426 }
427 
428 
429 static int
canusb_inject_linux(pcap_t * handle,const void * buf,size_t size)430 canusb_inject_linux(pcap_t *handle, const void *buf, size_t size)
431 {
432     /* not yet implemented */
433     snprintf(handle->errbuf, PCAP_ERRBUF_SIZE, "inject not supported on canusb devices");
434     return (-1);
435 }
436 
437 
438 static int
canusb_stats_linux(pcap_t * handle,struct pcap_stat * stats)439 canusb_stats_linux(pcap_t *handle, struct pcap_stat *stats)
440 {
441     /* not yet implemented */
442     stats->ps_recv = 0;     /* number of packets received */
443     stats->ps_drop = 0;     /* number of packets dropped */
444     stats->ps_ifdrop = 0;   /* drops by interface -- only supported on some platforms */
445     return 0;
446 }
447 
448 
449 static int
canusb_setfilter_linux(pcap_t * p,struct bpf_program * fp)450 canusb_setfilter_linux(pcap_t *p, struct bpf_program *fp)
451 {
452     /* not yet implemented */
453     return 0;
454 }
455 
456 
457 static int
canusb_setdirection_linux(pcap_t * p,pcap_direction_t d)458 canusb_setdirection_linux(pcap_t *p, pcap_direction_t d)
459 {
460     /* no support for PCAP_D_OUT */
461     if (d == PCAP_D_OUT)
462     {
463         snprintf(p->errbuf, sizeof(p->errbuf),
464             "Setting direction to PCAP_D_OUT is not supported on this interface");
465         return -1;
466     }
467 
468     p->direction = d;
469 
470     return 0;
471 }
472 
473 
474 /* eof */
475