OSDN Git Service

6a1de9097f426aaf6dc5c93a7138dd610bd1443e
[android-x86/external-wireless-tools.git] / wireless_tools / iwevent.c
1 /*
2  *      Wireless Tools
3  *
4  *              Jean II - HPL 99->01
5  *
6  * Main code for "iwevent". This listent for wireless events on rtnetlink.
7  * You need to link this code against "iwcommon.c" and "-lm".
8  *
9  * Part of this code is from Alexey Kuznetsov, part is from Casey Carter,
10  * I've just put the pieces together...
11  * By the way, if you know a way to remove the root restrictions, tell me
12  * about it...
13  *
14  * This file is released under the GPL license.
15  *     Copyright (c) 1997-2002 Jean Tourrilhes <jt@hpl.hp.com>
16  */
17
18 /***************************** INCLUDES *****************************/
19
20 #include "iwlib.h"              /* Header */
21
22 #include <linux/netlink.h>
23 #include <linux/rtnetlink.h>
24
25 #include <getopt.h>
26 #include <time.h>
27 #include <sys/time.h>
28
29 /************************ RTNETLINK HELPERS ************************/
30 /*
31  * The following code is extracted from :
32  * ----------------------------------------------
33  * libnetlink.c RTnetlink service routines.
34  *
35  *              This program is free software; you can redistribute it and/or
36  *              modify it under the terms of the GNU General Public License
37  *              as published by the Free Software Foundation; either version
38  *              2 of the License, or (at your option) any later version.
39  *
40  * Authors:     Alexey Kuznetsov, <kuznet@ms2.inr.ac.ru>
41  * -----------------------------------------------
42  */
43
44 struct rtnl_handle
45 {
46         int                     fd;
47         struct sockaddr_nl      local;
48         struct sockaddr_nl      peer;
49         __u32                   seq;
50         __u32                   dump;
51 };
52
53 static inline void rtnl_close(struct rtnl_handle *rth)
54 {
55         close(rth->fd);
56 }
57
58 static inline int rtnl_open(struct rtnl_handle *rth, unsigned subscriptions)
59 {
60         int addr_len;
61
62         memset(rth, 0, sizeof(rth));
63
64         rth->fd = socket(PF_NETLINK, SOCK_RAW, NETLINK_ROUTE);
65         if (rth->fd < 0) {
66                 perror("Cannot open netlink socket");
67                 return -1;
68         }
69
70         memset(&rth->local, 0, sizeof(rth->local));
71         rth->local.nl_family = AF_NETLINK;
72         rth->local.nl_groups = subscriptions;
73
74         if (bind(rth->fd, (struct sockaddr*)&rth->local, sizeof(rth->local)) < 0) {
75                 perror("Cannot bind netlink socket");
76                 return -1;
77         }
78         addr_len = sizeof(rth->local);
79         if (getsockname(rth->fd, (struct sockaddr*)&rth->local, &addr_len) < 0) {
80                 perror("Cannot getsockname");
81                 return -1;
82         }
83         if (addr_len != sizeof(rth->local)) {
84                 fprintf(stderr, "Wrong address length %d\n", addr_len);
85                 return -1;
86         }
87         if (rth->local.nl_family != AF_NETLINK) {
88                 fprintf(stderr, "Wrong address family %d\n", rth->local.nl_family);
89                 return -1;
90         }
91         rth->seq = time(NULL);
92         return 0;
93 }
94
95 /********************* WIRELESS EVENT DECODING *********************/
96 /*
97  * This is the bit I wrote...
98  */
99
100 #if WIRELESS_EXT > 13
101 /*------------------------------------------------------------------*/
102 /*
103  * Print one element from the scanning results
104  */
105 static inline int
106 print_event_token(struct iw_event *     event,  /* Extracted token */
107                   struct iw_range *     iwrange,        /* Range info */
108                   int                   has_range)
109 {
110   char          buffer[128];    /* Temporary buffer */
111
112   /* Now, let's decode the event */
113   switch(event->cmd)
114     {
115       /* ----- set events ----- */
116       /* Events that result from a "SET XXX" operation by the user */
117     case SIOCSIWNWID:
118       if(event->u.nwid.disabled)
119         printf("NWID:off/any\n");
120       else
121         printf("NWID:%X\n", event->u.nwid.value);
122       break;
123     case SIOCSIWFREQ:
124       {
125         float           freq;                   /* Frequency/channel */
126         freq = iw_freq2float(&(event->u.freq));
127         iw_print_freq(buffer, freq);
128         printf("%s\n", buffer);
129       }
130       break;
131     case SIOCSIWMODE:
132       printf("Mode:%s\n",
133              iw_operation_mode[event->u.mode]);
134       break;
135     case SIOCSIWESSID:
136       {
137         char essid[IW_ESSID_MAX_SIZE+1];
138         if((event->u.essid.pointer) && (event->u.essid.length))
139           memcpy(essid, event->u.essid.pointer, event->u.essid.length);
140         essid[event->u.essid.length] = '\0';
141         if(event->u.essid.flags)
142           {
143             /* Does it have an ESSID index ? */
144             if((event->u.essid.flags & IW_ENCODE_INDEX) > 1)
145               printf("ESSID:\"%s\" [%d]\n", essid,
146                      (event->u.essid.flags & IW_ENCODE_INDEX));
147             else
148               printf("ESSID:\"%s\"\n", essid);
149           }
150         else
151           printf("ESSID:off/any\n");
152       }
153       break;
154     case SIOCSIWENCODE:
155       {
156         unsigned char   key[IW_ENCODING_TOKEN_MAX];
157         if(event->u.data.pointer)
158           memcpy(key, event->u.essid.pointer, event->u.data.length);
159         else
160           event->u.data.flags |= IW_ENCODE_NOKEY;
161         printf("Encryption key:");
162         if(event->u.data.flags & IW_ENCODE_DISABLED)
163           printf("off\n");
164         else
165           {
166             /* Display the key */
167             iw_print_key(buffer, key, event->u.data.length,
168                          event->u.data.flags);
169             printf("%s", buffer);
170
171             /* Other info... */
172             if((event->u.data.flags & IW_ENCODE_INDEX) > 1)
173               printf(" [%d]", event->u.data.flags & IW_ENCODE_INDEX);
174             if(event->u.data.flags & IW_ENCODE_RESTRICTED)
175               printf("   Encryption mode:restricted");
176             if(event->u.data.flags & IW_ENCODE_OPEN)
177               printf("   Encryption mode:open");
178             printf("\n");
179           }
180       }
181       break;
182       /* ----- driver events ----- */
183       /* Events generated by the driver when something important happens */
184     case SIOCGIWAP:
185       printf("New Access Point/Cell address:%s\n",
186              iw_pr_ether(buffer, event->u.ap_addr.sa_data));
187       break;
188     case SIOCGIWSCAN:
189       printf("Scan request completed\n");
190       break;
191     case IWEVTXDROP:
192       printf("Tx packet dropped:%s\n",
193              iw_pr_ether(buffer, event->u.ap_addr.sa_data));
194       break;
195       /* ----- junk ----- */
196       /* other junk not currently in use */
197     case SIOCGIWRATE:
198       iw_print_bitrate(buffer, event->u.bitrate.value);
199       printf("Bit Rate:%s\n", buffer);
200       break;
201     case IWEVQUAL:
202       {
203         event->u.qual.updated = 0x0;    /* Not that reliable, disable */
204         iw_print_stats(buffer, &event->u.qual, iwrange, has_range);
205         printf("Link %s\n", buffer);
206         break;
207       }
208     default:
209       printf("(Unknown Wireless event 0x%04X)\n", event->cmd);
210     }   /* switch(event->cmd) */
211
212   return(0);
213 }
214
215 /*------------------------------------------------------------------*/
216 /*
217  * Print out all Wireless Events part of the RTNetlink message
218  * Most often, there will be only one event per message, but
219  * just make sure we read everything...
220  */
221 static inline int
222 print_event_stream(char *       ifname,
223                    char *       data,
224                    int          len)
225 {
226   struct iw_event       iwe;
227   struct stream_descr   stream;
228   int                   i = 0;
229   int                   ret;
230   char                  buffer[64];
231   struct timeval        recv_time;
232 #if 0
233   struct iw_range       range;
234   int                   has_range;
235 #endif
236
237 #if 0
238   has_range = (iw_get_range_info(skfd, ifname, &range) < 0);
239 #endif
240
241   /* In readable form */
242   gettimeofday(&recv_time, NULL);
243   iw_print_timeval(buffer, &recv_time);
244
245   iw_init_event_stream(&stream, data, len);
246   do
247     {
248       /* Extract an event and print it */
249       ret = iw_extract_event_stream(&stream, &iwe);
250       if(ret != 0)
251         {
252           if(i++ == 0)
253             printf("%s   %-8.8s ", buffer, ifname);
254           else
255             printf("                           ");
256           if(ret > 0)
257             print_event_token(&iwe, NULL, 0);
258           else
259             printf("(Invalid event)\n");
260         }
261     }
262   while(ret > 0);
263
264   return(0);
265 }
266 #endif  /* WIRELESS_EXT > 13 */
267
268 /*********************** RTNETLINK EVENT DUMP***********************/
269 /*
270  * Dump the events we receive from rtnetlink
271  * This code is mostly from Casey
272  */
273
274 /*------------------------------------------------------------------*/
275 /*
276  * Respond to a single RTM_NEWLINK event from the rtnetlink socket.
277  */
278 static inline int
279 index2name(int  index, char *name)
280 {
281   int           skfd = -1;      /* generic raw socket desc.     */
282   struct ifreq  irq;
283   int           ret = 0;
284
285   memset(name, 0, IFNAMSIZ + 1);
286
287   /* Create a channel to the NET kernel. */
288   if((skfd = iw_sockets_open()) < 0)
289     {
290       perror("socket");
291       exit(-1);
292     }
293
294   /* Get interface name */
295   irq.ifr_ifindex = index;
296   if(ioctl(skfd, SIOCGIFNAME, &irq) < 0)
297     ret = -1;
298   else
299     strncpy(name, irq.ifr_name, IFNAMSIZ);
300
301   close(skfd);
302   return(ret);
303 }
304
305
306 /*------------------------------------------------------------------*/
307 /*
308  * Respond to a single RTM_NEWLINK event from the rtnetlink socket.
309  */
310 static int
311 LinkCatcher(struct nlmsghdr *nlh)
312 {
313   struct ifinfomsg* ifi;
314   char ifname[IFNAMSIZ + 1];
315
316 #if 0
317   fprintf(stderr, "nlmsg_type = %d.\n", nlh->nlmsg_type);
318 #endif
319
320   if(nlh->nlmsg_type != RTM_NEWLINK)
321     return 0;
322
323   ifi = NLMSG_DATA(nlh);
324
325   /* Get a name... */
326   index2name(ifi->ifi_index, ifname);
327
328 #if WIRELESS_EXT > 13
329   /* Code is ugly, but sort of works - Jean II */
330
331   /* Check for attributes */
332   if (nlh->nlmsg_len > NLMSG_ALIGN(sizeof(struct ifinfomsg))) {
333       int attrlen = nlh->nlmsg_len - NLMSG_ALIGN(sizeof(struct ifinfomsg));
334       struct rtattr *attr = (void*)ifi + NLMSG_ALIGN(sizeof(struct ifinfomsg));
335
336       while (RTA_OK(attr, attrlen)) {
337         /* Check if the Wireless kind */
338         if(attr->rta_type == IFLA_WIRELESS) {
339           /* Go to display it */
340           print_event_stream(ifname,
341                              (void *)attr + RTA_ALIGN(sizeof(struct rtattr)),
342                              attr->rta_len - RTA_ALIGN(sizeof(struct rtattr)));
343         }
344         attr = RTA_NEXT(attr, attrlen);
345       }
346   }
347 #endif  /* WIRELESS_EXT > 13 */
348
349   return 0;
350 }
351
352 /* ---------------------------------------------------------------- */
353 /*
354  * We must watch the rtnelink socket for events.
355  * This routine handles those events (i.e., call this when rth.fd
356  * is ready to read).
357  */
358 static inline void
359 handle_netlink_events(struct rtnl_handle *      rth)
360 {
361   while(1)
362     {
363       struct sockaddr_nl sanl;
364       socklen_t sanllen;
365
366       struct nlmsghdr *h;
367       int amt;
368       char buf[8192];
369
370       amt = recvfrom(rth->fd, buf, sizeof(buf), MSG_DONTWAIT, (struct sockaddr*)&sanl, &sanllen);
371       if(amt < 0)
372         {
373           if(errno != EINTR && errno != EAGAIN)
374             {
375               fprintf(stderr, "%s: error reading netlink: %s.\n",
376                       __PRETTY_FUNCTION__, strerror(errno));
377             }
378           return;
379         }
380
381       if(amt == 0)
382         {
383           fprintf(stderr, "%s: EOF on netlink??\n", __PRETTY_FUNCTION__);
384           return;
385         }
386
387       h = (struct nlmsghdr*)buf;
388       while(amt >= (int)sizeof(*h))
389         {
390           int len = h->nlmsg_len;
391           int l = len - sizeof(*h);
392
393           if(l < 0 || len > amt)
394             {
395               fprintf(stderr, "%s: malformed netlink message: len=%d\n", __PRETTY_FUNCTION__, len);
396               break;
397             }
398
399           switch(h->nlmsg_type)
400             {
401             case RTM_NEWLINK:
402               LinkCatcher(h);
403               break;
404             default:
405 #if 0
406               fprintf(stderr, "%s: got nlmsg of type %#x.\n", __PRETTY_FUNCTION__, h->nlmsg_type);
407 #endif
408               break;
409             }
410
411           len = NLMSG_ALIGN(len);
412           amt -= len;
413           h = (struct nlmsghdr*)((char*)h + len);
414         }
415
416       if(amt > 0)
417         fprintf(stderr, "%s: remnant of size %d on netlink\n", __PRETTY_FUNCTION__, amt);
418     }
419 }
420
421 /**************************** MAIN LOOP ****************************/
422
423 /* ---------------------------------------------------------------- */
424 /*
425  * Wait until we get an event
426  */
427 static inline int
428 wait_for_event(struct rtnl_handle *     rth)
429 {
430 #if 0
431   struct timeval        tv;     /* Select timeout */
432 #endif
433
434   /* Forever */
435   while(1)
436     {
437       fd_set            rfds;           /* File descriptors for select */
438       int               last_fd;        /* Last fd */
439       int               ret;
440
441       /* Guess what ? We must re-generate rfds each time */
442       FD_ZERO(&rfds);
443       FD_SET(rth->fd, &rfds);
444       last_fd = rth->fd;
445
446       /* Wait until something happens */
447       ret = select(last_fd + 1, &rfds, NULL, NULL, NULL);
448
449       /* Check if there was an error */
450       if(ret < 0)
451         {
452           if(errno == EAGAIN || errno == EINTR)
453             continue;
454           fprintf(stderr, "Unhandled signal - exiting...\n");
455           break;
456         }
457
458       /* Check if there was a timeout */
459       if(ret == 0)
460         {
461           continue;
462         }
463
464       /* Check for interface discovery events. */
465       if(FD_ISSET(rth->fd, &rfds))
466         handle_netlink_events(rth);
467     }
468
469   return(0);
470 }
471
472 /******************************* MAIN *******************************/
473
474 /* ---------------------------------------------------------------- */
475 /*
476  * helper ;-)
477  */
478 static void
479 iw_usage(int status)
480 {
481   fputs("Usage: iwevent [OPTIONS]\n"
482         "   Monitors and displays Wireless Events.\n"
483         "   Options are:\n"
484         "     -h,--help  Print this message.\n",
485         status ? stderr : stdout);
486   exit(status);
487 }
488 /* Command line options */
489 static const struct option long_opts[] = {
490   { "help", no_argument, NULL, 'h' },
491   { NULL, 0, NULL, 0 }
492 };
493
494 /* ---------------------------------------------------------------- */
495 /*
496  * main body of the program
497  */
498 int
499 main(int        argc,
500      char *     argv[])
501 {
502   struct rtnl_handle    rth;
503   int opt;
504
505   /* Check command line options */
506   while((opt = getopt_long(argc, argv, "h", long_opts, NULL)) > 0)
507     {
508       switch(opt)
509         {
510         case 'h':
511           iw_usage(0);
512           break;
513
514         default:
515           iw_usage(1);
516           break;
517         }
518     }
519   if(optind < argc)
520     {
521       fputs("Too many arguments.\n", stderr);
522       iw_usage(1);
523     }
524
525   /* Open netlink channel */
526   if(rtnl_open(&rth, RTMGRP_LINK) < 0)
527     {
528       perror("Can't initialize rtnetlink socket");
529       return(1);
530     }
531
532   /* Do what we have to do */
533   wait_for_event(&rth);
534
535   /* Cleanup - only if you are pedantic */
536   rtnl_close(&rth);
537
538   return(0);
539 }