candump.c 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864
  1. /*
  2. * candump.c
  3. *
  4. * Copyright (c) 2002-2009 Volkswagen Group Electronic Research
  5. * All rights reserved.
  6. *
  7. * Redistribution and use in source and binary forms, with or without
  8. * modification, are permitted provided that the following conditions
  9. * are met:
  10. * 1. Redistributions of source code must retain the above copyright
  11. * notice, this list of conditions and the following disclaimer.
  12. * 2. Redistributions in binary form must reproduce the above copyright
  13. * notice, this list of conditions and the following disclaimer in the
  14. * documentation and/or other materials provided with the distribution.
  15. * 3. Neither the name of Volkswagen nor the names of its contributors
  16. * may be used to endorse or promote products derived from this software
  17. * without specific prior written permission.
  18. *
  19. * Alternatively, provided that this notice is retained in full, this
  20. * software may be distributed under the terms of the GNU General
  21. * Public License ("GPL") version 2, in which case the provisions of the
  22. * GPL apply INSTEAD OF those given above.
  23. *
  24. * The provided data structures and external interfaces from this code
  25. * are not restricted to be used by modules with a GPL compatible license.
  26. *
  27. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  28. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  29. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  30. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  31. * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  32. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  33. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  34. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  35. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  36. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  37. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
  38. * DAMAGE.
  39. *
  40. * Send feedback to <linux-can@vger.kernel.org>
  41. *
  42. */
  43. #include <stdio.h>
  44. #include <stdlib.h>
  45. #include <stdint.h>
  46. #include <unistd.h>
  47. #include <string.h>
  48. #include <signal.h>
  49. #include <ctype.h>
  50. #include <libgen.h>
  51. #include <time.h>
  52. #include <errno.h>
  53. #include <sys/time.h>
  54. #include <sys/types.h>
  55. #include <sys/socket.h>
  56. #include <sys/ioctl.h>
  57. #include <sys/uio.h>
  58. #include <net/if.h>
  59. #include <linux/can.h>
  60. #include <linux/can/raw.h>
  61. #include "terminal.h"
  62. #include "lib.h"
  63. /* for hardware timestamps - since Linux 2.6.30 */
  64. #ifndef SO_TIMESTAMPING
  65. #define SO_TIMESTAMPING 37
  66. #endif
  67. /* from #include <linux/net_tstamp.h> - since Linux 2.6.30 */
  68. #define SOF_TIMESTAMPING_SOFTWARE (1<<4)
  69. #define SOF_TIMESTAMPING_RX_SOFTWARE (1<<3)
  70. #define SOF_TIMESTAMPING_RAW_HARDWARE (1<<6)
  71. #define MAXSOCK 16 /* max. number of CAN interfaces given on the cmdline */
  72. #define MAXIFNAMES 30 /* size of receive name index to omit ioctls */
  73. #define MAXCOL 6 /* number of different colors for colorized output */
  74. #define ANYDEV "any" /* name of interface to receive from any CAN interface */
  75. #define ANL "\r\n" /* newline in ASC mode */
  76. #define SILENT_INI 42 /* detect user setting on commandline */
  77. #define SILENT_OFF 0 /* no silent mode */
  78. #define SILENT_ANI 1 /* silent mode with animation */
  79. #define SILENT_ON 2 /* silent mode (completely silent) */
  80. #define BOLD ATTBOLD
  81. #define RED ATTBOLD FGRED
  82. #define GREEN ATTBOLD FGGREEN
  83. #define YELLOW ATTBOLD FGYELLOW
  84. #define BLUE ATTBOLD FGBLUE
  85. #define MAGENTA ATTBOLD FGMAGENTA
  86. #define CYAN ATTBOLD FGCYAN
  87. const char col_on [MAXCOL][19] = {BLUE, RED, GREEN, BOLD, MAGENTA, CYAN};
  88. const char col_off [] = ATTRESET;
  89. static char *cmdlinename[MAXSOCK];
  90. static __u32 dropcnt[MAXSOCK];
  91. static __u32 last_dropcnt[MAXSOCK];
  92. static char devname[MAXIFNAMES][IFNAMSIZ+1];
  93. static int dindex[MAXIFNAMES];
  94. static int max_devname_len; /* to prevent frazzled device name output */
  95. const int canfd_on = 1;
  96. #define MAXANI 4
  97. const char anichar[MAXANI] = {'|', '/', '-', '\\'};
  98. const char extra_m_info[4][4] = {"- -", "B -", "- E", "B E"};
  99. extern int optind, opterr, optopt;
  100. static volatile int running = 1;
  101. void print_usage(char *prg)
  102. {
  103. fprintf(stderr, "\nUsage: %s [options] <CAN interface>+\n", prg);
  104. fprintf(stderr, " (use CTRL-C to terminate %s)\n\n", prg);
  105. fprintf(stderr, "Options: -t <type> (timestamp: (a)bsolute/(d)elta/(z)ero/(A)bsolute w date)\n");
  106. fprintf(stderr, " -H (read hardware timestamps instead of system timestamps)\n");
  107. fprintf(stderr, " -c (increment color mode level)\n");
  108. fprintf(stderr, " -i (binary output - may exceed 80 chars/line)\n");
  109. fprintf(stderr, " -a (enable additional ASCII output)\n");
  110. fprintf(stderr, " -S (swap byte order in printed CAN data[] - marked with '%c' )\n", SWAP_DELIMITER);
  111. fprintf(stderr, " -s <level> (silent mode - %d: off (default) %d: animation %d: silent)\n", SILENT_OFF, SILENT_ANI, SILENT_ON);
  112. fprintf(stderr, " -b <can> (bridge mode - send received frames to <can>)\n");
  113. fprintf(stderr, " -B <can> (bridge mode - like '-b' with disabled loopback)\n");
  114. fprintf(stderr, " -u <usecs> (delay bridge forwarding by <usecs> microseconds)\n");
  115. fprintf(stderr, " -l (log CAN-frames into file. Sets '-s %d' by default)\n", SILENT_ON);
  116. fprintf(stderr, " -L (use log file format on stdout)\n");
  117. fprintf(stderr, " -n <count> (terminate after receiption of <count> CAN frames)\n");
  118. fprintf(stderr, " -r <size> (set socket receive buffer to <size>)\n");
  119. fprintf(stderr, " -D (Don't exit if a \"detected\" can device goes down.\n");
  120. fprintf(stderr, " -d (monitor dropped CAN frames)\n");
  121. fprintf(stderr, " -e (dump CAN error frames in human-readable format)\n");
  122. fprintf(stderr, " -x (print extra message infos, rx/tx brs esi)\n");
  123. fprintf(stderr, " -T <msecs> (terminate after <msecs> without any reception)\n");
  124. fprintf(stderr, "\n");
  125. fprintf(stderr, "Up to %d CAN interfaces with optional filter sets can be specified\n", MAXSOCK);
  126. fprintf(stderr, "on the commandline in the form: <ifname>[,filter]*\n");
  127. fprintf(stderr, "\nComma separated filters can be specified for each given CAN interface:\n");
  128. fprintf(stderr, " <can_id>:<can_mask> (matches when <received_can_id> & mask == can_id & mask)\n");
  129. fprintf(stderr, " <can_id>~<can_mask> (matches when <received_can_id> & mask != can_id & mask)\n");
  130. fprintf(stderr, " #<error_mask> (set error frame filter, see include/linux/can/error.h)\n");
  131. fprintf(stderr, " [j|J] (join the given CAN filters - logical AND semantic)\n");
  132. fprintf(stderr, "\nCAN IDs, masks and data content are given and expected in hexadecimal values.\n");
  133. fprintf(stderr, "When can_id and can_mask are both 8 digits, they are assumed to be 29 bit EFF.\n");
  134. fprintf(stderr, "Without any given filter all data frames are received ('0:0' default filter).\n");
  135. fprintf(stderr, "\nUse interface name '%s' to receive from all CAN interfaces.\n", ANYDEV);
  136. fprintf(stderr, "\nExamples:\n");
  137. fprintf(stderr, "%s -c -c -ta can0,123:7FF,400:700,#000000FF can2,400~7F0 can3 can8\n", prg);
  138. fprintf(stderr, "%s -l any,0~0,#FFFFFFFF (log only error frames but no(!) data frames)\n", prg);
  139. fprintf(stderr, "%s -l any,0:0,#FFFFFFFF (log error frames and also all data frames)\n", prg);
  140. fprintf(stderr, "%s vcan2,92345678:DFFFFFFF (match only for extended CAN ID 12345678)\n", prg);
  141. fprintf(stderr, "%s vcan2,123:7FF (matches CAN ID 123 - including EFF and RTR frames)\n", prg);
  142. fprintf(stderr, "%s vcan2,123:C00007FF (matches CAN ID 123 - only SFF and non-RTR frames)\n", prg);
  143. fprintf(stderr, "\n");
  144. }
  145. void sigterm(int signo)
  146. {
  147. running = 0;
  148. }
  149. int idx2dindex(int ifidx, int socket) {
  150. int i;
  151. struct ifreq ifr;
  152. for (i=0; i < MAXIFNAMES; i++) {
  153. if (dindex[i] == ifidx)
  154. return i;
  155. }
  156. /* create new interface index cache entry */
  157. /* remove index cache zombies first */
  158. for (i=0; i < MAXIFNAMES; i++) {
  159. if (dindex[i]) {
  160. ifr.ifr_ifindex = dindex[i];
  161. if (ioctl(socket, SIOCGIFNAME, &ifr) < 0)
  162. dindex[i] = 0;
  163. }
  164. }
  165. for (i=0; i < MAXIFNAMES; i++)
  166. if (!dindex[i]) /* free entry */
  167. break;
  168. if (i == MAXIFNAMES) {
  169. fprintf(stderr, "Interface index cache only supports %d interfaces.\n",
  170. MAXIFNAMES);
  171. exit(1);
  172. }
  173. dindex[i] = ifidx;
  174. ifr.ifr_ifindex = ifidx;
  175. if (ioctl(socket, SIOCGIFNAME, &ifr) < 0)
  176. perror("SIOCGIFNAME");
  177. if (max_devname_len < strlen(ifr.ifr_name))
  178. max_devname_len = strlen(ifr.ifr_name);
  179. strcpy(devname[i], ifr.ifr_name);
  180. #ifdef DEBUG
  181. printf("new index %d (%s)\n", i, devname[i]);
  182. #endif
  183. return i;
  184. }
  185. int main(int argc, char **argv)
  186. {
  187. fd_set rdfs;
  188. int s[MAXSOCK];
  189. int bridge = 0;
  190. useconds_t bridge_delay = 0;
  191. unsigned char timestamp = 0;
  192. unsigned char hwtimestamp = 0;
  193. unsigned char down_causes_exit = 1;
  194. unsigned char dropmonitor = 0;
  195. unsigned char extra_msg_info = 0;
  196. unsigned char silent = SILENT_INI;
  197. unsigned char silentani = 0;
  198. unsigned char color = 0;
  199. unsigned char view = 0;
  200. unsigned char log = 0;
  201. unsigned char logfrmt = 0;
  202. int count = 0;
  203. int rcvbuf_size = 0;
  204. int opt, ret;
  205. int currmax, numfilter;
  206. int join_filter;
  207. char *ptr, *nptr;
  208. struct sockaddr_can addr;
  209. char ctrlmsg[CMSG_SPACE(sizeof(struct timeval) + 3*sizeof(struct timespec) + sizeof(__u32))];
  210. struct iovec iov;
  211. struct msghdr msg;
  212. struct cmsghdr *cmsg;
  213. struct can_filter *rfilter;
  214. can_err_mask_t err_mask;
  215. struct canfd_frame frame;
  216. int nbytes, i, maxdlen;
  217. struct ifreq ifr;
  218. struct timeval tv, last_tv;
  219. struct timeval timeout, timeout_config = { 0, 0 }, *timeout_current = NULL;
  220. FILE *logfile = NULL;
  221. signal(SIGTERM, sigterm);
  222. signal(SIGHUP, sigterm);
  223. signal(SIGINT, sigterm);
  224. last_tv.tv_sec = 0;
  225. last_tv.tv_usec = 0;
  226. while ((opt = getopt(argc, argv, "t:HciaSs:b:B:u:lDdxLn:r:heT:?")) != -1) {
  227. switch (opt) {
  228. case 't':
  229. timestamp = optarg[0];
  230. if ((timestamp != 'a') && (timestamp != 'A') &&
  231. (timestamp != 'd') && (timestamp != 'z')) {
  232. fprintf(stderr, "%s: unknown timestamp mode '%c' - ignored\n",
  233. basename(argv[0]), optarg[0]);
  234. timestamp = 0;
  235. }
  236. break;
  237. case 'H':
  238. hwtimestamp = 1;
  239. break;
  240. case 'c':
  241. color++;
  242. break;
  243. case 'i':
  244. view |= CANLIB_VIEW_BINARY;
  245. break;
  246. case 'a':
  247. view |= CANLIB_VIEW_ASCII;
  248. break;
  249. case 'S':
  250. view |= CANLIB_VIEW_SWAP;
  251. break;
  252. case 'e':
  253. view |= CANLIB_VIEW_ERROR;
  254. break;
  255. case 's':
  256. silent = atoi(optarg);
  257. if (silent > SILENT_ON) {
  258. print_usage(basename(argv[0]));
  259. exit(1);
  260. }
  261. break;
  262. case 'b':
  263. case 'B':
  264. if (strlen(optarg) >= IFNAMSIZ) {
  265. fprintf(stderr, "Name of CAN device '%s' is too long!\n\n", optarg);
  266. return 1;
  267. } else {
  268. bridge = socket(PF_CAN, SOCK_RAW, CAN_RAW);
  269. if (bridge < 0) {
  270. perror("bridge socket");
  271. return 1;
  272. }
  273. addr.can_family = AF_CAN;
  274. strcpy(ifr.ifr_name, optarg);
  275. if (ioctl(bridge, SIOCGIFINDEX, &ifr) < 0)
  276. perror("SIOCGIFINDEX");
  277. addr.can_ifindex = ifr.ifr_ifindex;
  278. if (!addr.can_ifindex) {
  279. perror("invalid bridge interface");
  280. return 1;
  281. }
  282. /* disable default receive filter on this write-only RAW socket */
  283. setsockopt(bridge, SOL_CAN_RAW, CAN_RAW_FILTER, NULL, 0);
  284. if (opt == 'B') {
  285. const int loopback = 0;
  286. setsockopt(bridge, SOL_CAN_RAW, CAN_RAW_LOOPBACK,
  287. &loopback, sizeof(loopback));
  288. }
  289. if (bind(bridge, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
  290. perror("bridge bind");
  291. return 1;
  292. }
  293. }
  294. break;
  295. case 'u':
  296. bridge_delay = (useconds_t)strtoul(optarg, (char **)NULL, 10);
  297. break;
  298. case 'l':
  299. log = 1;
  300. break;
  301. case 'D':
  302. down_causes_exit = 0;
  303. break;
  304. case 'd':
  305. dropmonitor = 1;
  306. break;
  307. case 'x':
  308. extra_msg_info = 1;
  309. break;
  310. case 'L':
  311. logfrmt = 1;
  312. break;
  313. case 'n':
  314. count = atoi(optarg);
  315. if (count < 1) {
  316. print_usage(basename(argv[0]));
  317. exit(1);
  318. }
  319. break;
  320. case 'r':
  321. rcvbuf_size = atoi(optarg);
  322. if (rcvbuf_size < 1) {
  323. print_usage(basename(argv[0]));
  324. exit(1);
  325. }
  326. break;
  327. case 'T':
  328. errno = 0;
  329. timeout_config.tv_usec = strtol(optarg, NULL, 0);
  330. if (errno != 0) {
  331. print_usage(basename(argv[0]));
  332. exit(1);
  333. }
  334. timeout_config.tv_sec = timeout_config.tv_usec / 1000;
  335. timeout_config.tv_usec = (timeout_config.tv_usec % 1000) * 1000;
  336. timeout_current = &timeout;
  337. break;
  338. default:
  339. print_usage(basename(argv[0]));
  340. exit(1);
  341. break;
  342. }
  343. }
  344. if (optind == argc) {
  345. print_usage(basename(argv[0]));
  346. exit(0);
  347. }
  348. if (logfrmt && view) {
  349. fprintf(stderr, "Log file format selected: Please disable ASCII/BINARY/SWAP options!\n");
  350. exit(0);
  351. }
  352. if (silent == SILENT_INI) {
  353. if (log) {
  354. fprintf(stderr, "Disabled standard output while logging.\n");
  355. silent = SILENT_ON; /* disable output on stdout */
  356. } else
  357. silent = SILENT_OFF; /* default output */
  358. }
  359. currmax = argc - optind; /* find real number of CAN devices */
  360. if (currmax > MAXSOCK) {
  361. fprintf(stderr, "More than %d CAN devices given on commandline!\n", MAXSOCK);
  362. return 1;
  363. }
  364. for (i=0; i < currmax; i++) {
  365. ptr = argv[optind+i];
  366. nptr = strchr(ptr, ',');
  367. #ifdef DEBUG
  368. printf("open %d '%s'.\n", i, ptr);
  369. #endif
  370. s[i] = socket(PF_CAN, SOCK_RAW, CAN_RAW);
  371. if (s[i] < 0) {
  372. perror("socket");
  373. return 1;
  374. }
  375. cmdlinename[i] = ptr; /* save pointer to cmdline name of this socket */
  376. if (nptr)
  377. nbytes = nptr - ptr; /* interface name is up the first ',' */
  378. else
  379. nbytes = strlen(ptr); /* no ',' found => no filter definitions */
  380. if (nbytes >= IFNAMSIZ) {
  381. fprintf(stderr, "name of CAN device '%s' is too long!\n", ptr);
  382. return 1;
  383. }
  384. if (nbytes > max_devname_len)
  385. max_devname_len = nbytes; /* for nice printing */
  386. addr.can_family = AF_CAN;
  387. memset(&ifr.ifr_name, 0, sizeof(ifr.ifr_name));
  388. strncpy(ifr.ifr_name, ptr, nbytes);
  389. #ifdef DEBUG
  390. printf("using interface name '%s'.\n", ifr.ifr_name);
  391. #endif
  392. if (strcmp(ANYDEV, ifr.ifr_name)) {
  393. if (ioctl(s[i], SIOCGIFINDEX, &ifr) < 0) {
  394. perror("SIOCGIFINDEX");
  395. exit(1);
  396. }
  397. addr.can_ifindex = ifr.ifr_ifindex;
  398. } else
  399. addr.can_ifindex = 0; /* any can interface */
  400. if (nptr) {
  401. /* found a ',' after the interface name => check for filters */
  402. /* determine number of filters to alloc the filter space */
  403. numfilter = 0;
  404. ptr = nptr;
  405. while (ptr) {
  406. numfilter++;
  407. ptr++; /* hop behind the ',' */
  408. ptr = strchr(ptr, ','); /* exit condition */
  409. }
  410. rfilter = malloc(sizeof(struct can_filter) * numfilter);
  411. if (!rfilter) {
  412. fprintf(stderr, "Failed to create filter space!\n");
  413. return 1;
  414. }
  415. numfilter = 0;
  416. err_mask = 0;
  417. join_filter = 0;
  418. while (nptr) {
  419. ptr = nptr+1; /* hop behind the ',' */
  420. nptr = strchr(ptr, ','); /* update exit condition */
  421. if (sscanf(ptr, "%x:%x",
  422. &rfilter[numfilter].can_id,
  423. &rfilter[numfilter].can_mask) == 2) {
  424. rfilter[numfilter].can_mask &= ~CAN_ERR_FLAG;
  425. numfilter++;
  426. } else if (sscanf(ptr, "%x~%x",
  427. &rfilter[numfilter].can_id,
  428. &rfilter[numfilter].can_mask) == 2) {
  429. rfilter[numfilter].can_id |= CAN_INV_FILTER;
  430. rfilter[numfilter].can_mask &= ~CAN_ERR_FLAG;
  431. numfilter++;
  432. } else if (*ptr == 'j' || *ptr == 'J') {
  433. join_filter = 1;
  434. } else if (sscanf(ptr, "#%x", &err_mask) != 1) {
  435. fprintf(stderr, "Error in filter option parsing: '%s'\n", ptr);
  436. return 1;
  437. }
  438. }
  439. if (err_mask)
  440. setsockopt(s[i], SOL_CAN_RAW, CAN_RAW_ERR_FILTER,
  441. &err_mask, sizeof(err_mask));
  442. if (join_filter && setsockopt(s[i], SOL_CAN_RAW, CAN_RAW_JOIN_FILTERS,
  443. &join_filter, sizeof(join_filter)) < 0) {
  444. perror("setsockopt CAN_RAW_JOIN_FILTERS not supported by your Linux Kernel");
  445. return 1;
  446. }
  447. if (numfilter)
  448. setsockopt(s[i], SOL_CAN_RAW, CAN_RAW_FILTER,
  449. rfilter, numfilter * sizeof(struct can_filter));
  450. free(rfilter);
  451. } /* if (nptr) */
  452. /* try to switch the socket into CAN FD mode */
  453. setsockopt(s[i], SOL_CAN_RAW, CAN_RAW_FD_FRAMES, &canfd_on, sizeof(canfd_on));
  454. if (rcvbuf_size) {
  455. int curr_rcvbuf_size;
  456. socklen_t curr_rcvbuf_size_len = sizeof(curr_rcvbuf_size);
  457. /* try SO_RCVBUFFORCE first, if we run with CAP_NET_ADMIN */
  458. if (setsockopt(s[i], SOL_SOCKET, SO_RCVBUFFORCE,
  459. &rcvbuf_size, sizeof(rcvbuf_size)) < 0) {
  460. #ifdef DEBUG
  461. printf("SO_RCVBUFFORCE failed so try SO_RCVBUF ...\n");
  462. #endif
  463. if (setsockopt(s[i], SOL_SOCKET, SO_RCVBUF,
  464. &rcvbuf_size, sizeof(rcvbuf_size)) < 0) {
  465. perror("setsockopt SO_RCVBUF");
  466. return 1;
  467. }
  468. if (getsockopt(s[i], SOL_SOCKET, SO_RCVBUF,
  469. &curr_rcvbuf_size, &curr_rcvbuf_size_len) < 0) {
  470. perror("getsockopt SO_RCVBUF");
  471. return 1;
  472. }
  473. /* Only print a warning the first time we detect the adjustment */
  474. /* n.b.: The wanted size is doubled in Linux in net/sore/sock.c */
  475. if (!i && curr_rcvbuf_size < rcvbuf_size*2)
  476. fprintf(stderr, "The socket receive buffer size was "
  477. "adjusted due to /proc/sys/net/core/rmem_max.\n");
  478. }
  479. }
  480. if (timestamp || log || logfrmt) {
  481. if (hwtimestamp) {
  482. const int timestamping_flags = (SOF_TIMESTAMPING_SOFTWARE | \
  483. SOF_TIMESTAMPING_RX_SOFTWARE | \
  484. SOF_TIMESTAMPING_RAW_HARDWARE);
  485. if (setsockopt(s[i], SOL_SOCKET, SO_TIMESTAMPING,
  486. &timestamping_flags, sizeof(timestamping_flags)) < 0) {
  487. perror("setsockopt SO_TIMESTAMPING is not supported by your Linux kernel");
  488. return 1;
  489. }
  490. } else {
  491. const int timestamp_on = 1;
  492. if (setsockopt(s[i], SOL_SOCKET, SO_TIMESTAMP,
  493. &timestamp_on, sizeof(timestamp_on)) < 0) {
  494. perror("setsockopt SO_TIMESTAMP");
  495. return 1;
  496. }
  497. }
  498. }
  499. if (dropmonitor) {
  500. const int dropmonitor_on = 1;
  501. if (setsockopt(s[i], SOL_SOCKET, SO_RXQ_OVFL,
  502. &dropmonitor_on, sizeof(dropmonitor_on)) < 0) {
  503. perror("setsockopt SO_RXQ_OVFL not supported by your Linux Kernel");
  504. return 1;
  505. }
  506. }
  507. if (bind(s[i], (struct sockaddr *)&addr, sizeof(addr)) < 0) {
  508. perror("bind");
  509. return 1;
  510. }
  511. }
  512. if (log) {
  513. time_t currtime;
  514. struct tm now;
  515. char fname[sizeof("candump-2006-11-20_202026.log")+1];
  516. if (time(&currtime) == (time_t)-1) {
  517. perror("time");
  518. return 1;
  519. }
  520. localtime_r(&currtime, &now);
  521. sprintf(fname, "candump-%04d-%02d-%02d_%02d%02d%02d.log",
  522. now.tm_year + 1900,
  523. now.tm_mon + 1,
  524. now.tm_mday,
  525. now.tm_hour,
  526. now.tm_min,
  527. now.tm_sec);
  528. if (silent != SILENT_ON)
  529. printf("\nWarning: console output active while logging!");
  530. fprintf(stderr, "\nEnabling Logfile '%s'\n\n", fname);
  531. logfile = fopen(fname, "w");
  532. if (!logfile) {
  533. perror("logfile");
  534. return 1;
  535. }
  536. }
  537. /* these settings are static and can be held out of the hot path */
  538. iov.iov_base = &frame;
  539. msg.msg_name = &addr;
  540. msg.msg_iov = &iov;
  541. msg.msg_iovlen = 1;
  542. msg.msg_control = &ctrlmsg;
  543. while (running) {
  544. FD_ZERO(&rdfs);
  545. for (i=0; i<currmax; i++)
  546. FD_SET(s[i], &rdfs);
  547. if (timeout_current)
  548. *timeout_current = timeout_config;
  549. if ((ret = select(s[currmax-1]+1, &rdfs, NULL, NULL, timeout_current)) <= 0) {
  550. //perror("select");
  551. running = 0;
  552. continue;
  553. }
  554. for (i=0; i<currmax; i++) { /* check all CAN RAW sockets */
  555. if (FD_ISSET(s[i], &rdfs)) {
  556. int idx;
  557. /* these settings may be modified by recvmsg() */
  558. iov.iov_len = sizeof(frame);
  559. msg.msg_namelen = sizeof(addr);
  560. msg.msg_controllen = sizeof(ctrlmsg);
  561. msg.msg_flags = 0;
  562. nbytes = recvmsg(s[i], &msg, 0);
  563. idx = idx2dindex(addr.can_ifindex, s[i]);
  564. if (nbytes < 0) {
  565. if ((errno == ENETDOWN) && !down_causes_exit) {
  566. fprintf(stderr, "%s: interface down\n", devname[idx]);
  567. continue;
  568. }
  569. perror("read");
  570. return 1;
  571. }
  572. if ((size_t)nbytes == CAN_MTU)
  573. maxdlen = CAN_MAX_DLEN;
  574. else if ((size_t)nbytes == CANFD_MTU)
  575. maxdlen = CANFD_MAX_DLEN;
  576. else {
  577. fprintf(stderr, "read: incomplete CAN frame\n");
  578. return 1;
  579. }
  580. if (count && (--count == 0))
  581. running = 0;
  582. if (bridge) {
  583. if (bridge_delay)
  584. usleep(bridge_delay);
  585. nbytes = write(bridge, &frame, nbytes);
  586. if (nbytes < 0) {
  587. perror("bridge write");
  588. return 1;
  589. } else if ((size_t)nbytes != CAN_MTU && (size_t)nbytes != CANFD_MTU) {
  590. fprintf(stderr,"bridge write: incomplete CAN frame\n");
  591. return 1;
  592. }
  593. }
  594. for (cmsg = CMSG_FIRSTHDR(&msg);
  595. cmsg && (cmsg->cmsg_level == SOL_SOCKET);
  596. cmsg = CMSG_NXTHDR(&msg,cmsg)) {
  597. if (cmsg->cmsg_type == SO_TIMESTAMP) {
  598. memcpy(&tv, CMSG_DATA(cmsg), sizeof(tv));
  599. } else if (cmsg->cmsg_type == SO_TIMESTAMPING) {
  600. struct timespec *stamp = (struct timespec *)CMSG_DATA(cmsg);
  601. /*
  602. * stamp[0] is the software timestamp
  603. * stamp[1] is deprecated
  604. * stamp[2] is the raw hardware timestamp
  605. * See chapter 2.1.2 Receive timestamps in
  606. * linux/Documentation/networking/timestamping.txt
  607. */
  608. tv.tv_sec = stamp[2].tv_sec;
  609. tv.tv_usec = stamp[2].tv_nsec/1000;
  610. } else if (cmsg->cmsg_type == SO_RXQ_OVFL)
  611. memcpy(&dropcnt[i], CMSG_DATA(cmsg), sizeof(__u32));
  612. }
  613. /* check for (unlikely) dropped frames on this specific socket */
  614. if (dropcnt[i] != last_dropcnt[i]) {
  615. __u32 frames = dropcnt[i] - last_dropcnt[i];
  616. if (silent != SILENT_ON)
  617. printf("DROPCOUNT: dropped %d CAN frame%s on '%s' socket (total drops %d)\n",
  618. frames, (frames > 1)?"s":"", devname[idx], dropcnt[i]);
  619. if (log)
  620. fprintf(logfile, "DROPCOUNT: dropped %d CAN frame%s on '%s' socket (total drops %d)\n",
  621. frames, (frames > 1)?"s":"", devname[idx], dropcnt[i]);
  622. last_dropcnt[i] = dropcnt[i];
  623. }
  624. /* once we detected a EFF frame indent SFF frames accordingly */
  625. if (frame.can_id & CAN_EFF_FLAG)
  626. view |= CANLIB_VIEW_INDENT_SFF;
  627. if (log) {
  628. char buf[CL_CFSZ]; /* max length */
  629. /* log CAN frame with absolute timestamp & device */
  630. sprint_canframe(buf, &frame, 0, maxdlen);
  631. fprintf(logfile, "(%010ld.%06ld) %*s %s\n",
  632. tv.tv_sec, tv.tv_usec,
  633. max_devname_len, devname[idx], buf);
  634. }
  635. if (logfrmt) {
  636. char buf[CL_CFSZ]; /* max length */
  637. /* print CAN frame in log file style to stdout */
  638. sprint_canframe(buf, &frame, 0, maxdlen);
  639. printf("(%010ld.%06ld) %*s %s\n",
  640. tv.tv_sec, tv.tv_usec,
  641. max_devname_len, devname[idx], buf);
  642. goto out_fflush; /* no other output to stdout */
  643. }
  644. if (silent != SILENT_OFF){
  645. if (silent == SILENT_ANI) {
  646. printf("%c\b", anichar[silentani%=MAXANI]);
  647. silentani++;
  648. }
  649. goto out_fflush; /* no other output to stdout */
  650. }
  651. printf(" %s", (color>2)?col_on[idx%MAXCOL]:"");
  652. switch (timestamp) {
  653. case 'a': /* absolute with timestamp */
  654. printf("(%010ld.%06ld) ", tv.tv_sec, tv.tv_usec);
  655. break;
  656. case 'A': /* absolute with date */
  657. {
  658. struct tm tm;
  659. char timestring[25];
  660. tm = *localtime(&tv.tv_sec);
  661. strftime(timestring, 24, "%Y-%m-%d %H:%M:%S", &tm);
  662. printf("(%s.%06ld) ", timestring, tv.tv_usec);
  663. }
  664. break;
  665. case 'd': /* delta */
  666. case 'z': /* starting with zero */
  667. {
  668. struct timeval diff;
  669. if (last_tv.tv_sec == 0) /* first init */
  670. last_tv = tv;
  671. diff.tv_sec = tv.tv_sec - last_tv.tv_sec;
  672. diff.tv_usec = tv.tv_usec - last_tv.tv_usec;
  673. if (diff.tv_usec < 0)
  674. diff.tv_sec--, diff.tv_usec += 1000000;
  675. if (diff.tv_sec < 0)
  676. diff.tv_sec = diff.tv_usec = 0;
  677. printf("(%03ld.%06ld) ", diff.tv_sec, diff.tv_usec);
  678. if (timestamp == 'd')
  679. last_tv = tv; /* update for delta calculation */
  680. }
  681. break;
  682. default: /* no timestamp output */
  683. break;
  684. }
  685. printf(" %s", (color && (color<3))?col_on[idx%MAXCOL]:"");
  686. printf("%*s", max_devname_len, devname[idx]);
  687. if (extra_msg_info) {
  688. if (msg.msg_flags & MSG_DONTROUTE)
  689. printf (" TX %s", extra_m_info[frame.flags & 3]);
  690. else
  691. printf (" RX %s", extra_m_info[frame.flags & 3]);
  692. }
  693. printf("%s ", (color==1)?col_off:"");
  694. fprint_long_canframe(stdout, &frame, NULL, view, maxdlen);
  695. printf("%s", (color>1)?col_off:"");
  696. printf("\n");
  697. }
  698. out_fflush:
  699. fflush(stdout);
  700. }
  701. }
  702. for (i=0; i<currmax; i++)
  703. close(s[i]);
  704. if (bridge)
  705. close(bridge);
  706. if (log)
  707. fclose(logfile);
  708. return 0;
  709. }