fcfecbb6f2724814fb5b30e28f40fa95a39f2837
[project/luci.git] / libs / iwinfo / src / iwinfo_wext_scan.c
1 /*
2  * iwinfo - Wireless Information Library - Linux Wireless Extension Backend
3  *
4  *   Copyright (C) 2009 Jo-Philipp Wich <xm@subsignal.org>
5  *
6  * The iwinfo library is free software: you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License version 2
8  * as published by the Free Software Foundation.
9  *
10  * The iwinfo library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
13  * See the GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License along
16  * with the iwinfo library. If not, see http://www.gnu.org/licenses/.
17  *
18  * Parts of this code are derived from the Linux wireless tools, iwlib.c,
19  * iwlist.c and iwconfig.c in particular.
20  */
21
22 #include "iwinfo.h"
23 #include "iwinfo_wext_scan.h"
24
25
26 static int ioctl_socket = -1;
27
28 static int wext_ioctl(const char *ifname, int cmd, struct iwreq *wrq)
29 {
30         /* prepare socket */
31         if( ioctl_socket == -1 )
32                 ioctl_socket = socket(AF_INET, SOCK_DGRAM, 0);
33
34         strncpy(wrq->ifr_name, ifname, IFNAMSIZ);
35         return ioctl(ioctl_socket, cmd, wrq);
36 }
37
38 static double wext_freq2float(const struct iw_freq *in)
39 {
40         int             i;
41         double  res = (double) in->m;
42         for(i = 0; i < in->e; i++) res *= 10;
43         return res;
44 }
45
46 static int wext_extract_event(struct stream_descr *stream, struct iw_event *iwe)
47 {
48         const struct iw_ioctl_description *descr = NULL;
49         int event_type = 0;
50         unsigned int event_len = 1;
51         char *pointer;
52         unsigned cmd_index;             /* *MUST* be unsigned */
53
54         /* Check for end of stream */
55         if((stream->current + IW_EV_LCP_PK_LEN) > stream->end)
56                 return 0;
57
58         /* Extract the event header (to get the event id).
59          * Note : the event may be unaligned, therefore copy... */
60         memcpy((char *) iwe, stream->current, IW_EV_LCP_PK_LEN);
61
62         /* Check invalid events */
63         if(iwe->len <= IW_EV_LCP_PK_LEN)
64                 return -1;
65
66         /* Get the type and length of that event */
67         if(iwe->cmd <= SIOCIWLAST)
68         {
69                 cmd_index = iwe->cmd - SIOCIWFIRST;
70                 if(cmd_index < standard_ioctl_num)
71                         descr = &(standard_ioctl_descr[cmd_index]);
72         }
73         else
74         {
75                 cmd_index = iwe->cmd - IWEVFIRST;
76                 if(cmd_index < standard_event_num)
77                         descr = &(standard_event_descr[cmd_index]);
78         }
79
80         if(descr != NULL)
81                 event_type = descr->header_type;
82
83         /* Unknown events -> event_type=0 => IW_EV_LCP_PK_LEN */
84         event_len = event_type_size[event_type];
85
86         /* Check if we know about this event */
87         if(event_len <= IW_EV_LCP_PK_LEN)
88         {
89                 /* Skip to next event */
90                 stream->current += iwe->len;
91                 return 2;
92         }
93
94         event_len -= IW_EV_LCP_PK_LEN;
95
96         /* Set pointer on data */
97         if(stream->value != NULL)
98                 pointer = stream->value;                        /* Next value in event */
99         else
100                 pointer = stream->current + IW_EV_LCP_PK_LEN;   /* First value in event */
101
102         /* Copy the rest of the event (at least, fixed part) */
103         if((pointer + event_len) > stream->end)
104         {
105                 /* Go to next event */
106                 stream->current += iwe->len;
107                 return -2;
108         }
109
110         /* Fixup for WE-19 and later : pointer no longer in the stream */
111         /* Beware of alignement. Dest has local alignement, not packed */
112         if( event_type == IW_HEADER_TYPE_POINT )
113                 memcpy((char *) iwe + IW_EV_LCP_LEN + IW_EV_POINT_OFF, pointer, event_len);
114         else
115                 memcpy((char *) iwe + IW_EV_LCP_LEN, pointer, event_len);
116
117         /* Skip event in the stream */
118         pointer += event_len;
119
120         /* Special processing for iw_point events */
121         if(event_type == IW_HEADER_TYPE_POINT)
122         {
123                 /* Check the length of the payload */
124                 unsigned int extra_len = iwe->len - (event_len + IW_EV_LCP_PK_LEN);
125                 if(extra_len > 0)
126                 {
127                         /* Set pointer on variable part (warning : non aligned) */
128                         iwe->u.data.pointer = pointer;
129
130                         /* Check that we have a descriptor for the command */
131                         if(descr == NULL)
132                                 /* Can't check payload -> unsafe... */
133                                 iwe->u.data.pointer = NULL;     /* Discard paylod */
134                         else
135                         {
136                                 /* Those checks are actually pretty hard to trigger,
137                                 * because of the checks done in the kernel... */
138
139                                 unsigned int    token_len = iwe->u.data.length * descr->token_size;
140
141                                 /* Ugly fixup for alignement issues.
142                                 * If the kernel is 64 bits and userspace 32 bits,
143                                 * we have an extra 4+4 bytes.
144                                 * Fixing that in the kernel would break 64 bits userspace. */
145                                 if((token_len != extra_len) && (extra_len >= 4))
146                                 {
147                                         uint16_t alt_dlen = *((uint16_t *) pointer);
148                                         unsigned int alt_token_len = alt_dlen * descr->token_size;
149                                         if((alt_token_len + 8) == extra_len)
150                                         {
151                                                 /* Ok, let's redo everything */
152                                                 pointer -= event_len;
153                                                 pointer += 4;
154                                                 /* Dest has local alignement, not packed */
155                                                 memcpy((char *) iwe + IW_EV_LCP_LEN + IW_EV_POINT_OFF, pointer, event_len);
156                                                 pointer += event_len + 4;
157                                                 iwe->u.data.pointer = pointer;
158                                                 token_len = alt_token_len;
159                                         }
160                                 }
161
162                                 /* Discard bogus events which advertise more tokens than
163                                 * what they carry... */
164                                 if(token_len > extra_len)
165                                         iwe->u.data.pointer = NULL;     /* Discard paylod */
166
167                                 /* Check that the advertised token size is not going to
168                                 * produce buffer overflow to our caller... */
169                                 if((iwe->u.data.length > descr->max_tokens)
170                                 && !(descr->flags & IW_DESCR_FLAG_NOMAX))
171                                         iwe->u.data.pointer = NULL;     /* Discard paylod */
172
173                                 /* Same for underflows... */
174                                 if(iwe->u.data.length < descr->min_tokens)
175                                         iwe->u.data.pointer = NULL;     /* Discard paylod */
176                         }
177                 }
178                 else
179                         /* No data */
180                         iwe->u.data.pointer = NULL;
181
182                 /* Go to next event */
183                 stream->current += iwe->len;
184         }
185         else
186         {
187                 /* Ugly fixup for alignement issues.
188                 * If the kernel is 64 bits and userspace 32 bits,
189                 * we have an extra 4 bytes.
190                 * Fixing that in the kernel would break 64 bits userspace. */
191                 if((stream->value == NULL)
192                 && ((((iwe->len - IW_EV_LCP_PK_LEN) % event_len) == 4)
193                 || ((iwe->len == 12) && ((event_type == IW_HEADER_TYPE_UINT) ||
194                 (event_type == IW_HEADER_TYPE_QUAL))) ))
195                 {
196                         pointer -= event_len;
197                         pointer += 4;
198                         /* Beware of alignement. Dest has local alignement, not packed */
199                         memcpy((char *) iwe + IW_EV_LCP_LEN, pointer, event_len);
200                         pointer += event_len;
201                 }
202
203                 /* Is there more value in the event ? */
204                 if((pointer + event_len) <= (stream->current + iwe->len))
205                         /* Go to next value */
206                         stream->value = pointer;
207                 else
208                 {
209                         /* Go to next event */
210                         stream->value = NULL;
211                         stream->current += iwe->len;
212                 }
213         }
214
215         return 1;
216 }
217
218 static inline void wext_fill_wpa(unsigned char *iebuf, int buflen, struct iwinfo_scanlist_entry *e)
219 {
220         int ielen = iebuf[1] + 2;
221         int offset = 2; /* Skip the IE id, and the length. */
222         unsigned char wpa1_oui[3] = {0x00, 0x50, 0xf2};
223         unsigned char wpa2_oui[3] = {0x00, 0x0f, 0xac};
224         unsigned char *wpa_oui;
225         int i;
226         uint16_t ver = 0;
227         uint16_t cnt = 0;
228         int wpa1 = 0, wpa2 = 0;
229         char buf[256];
230
231         struct iwinfo_crypto_entry *ce = &e->crypto;
232
233         if( !ce->enabled )
234                 return;
235
236         //memset(&e->crypto, 0, sizeof(struct iwinfo_crypto_entry));
237
238         if(ielen > buflen)
239                 ielen = buflen;
240
241         switch(iebuf[0])
242         {
243                 case 0x30:      /* WPA2 */
244                         /* Check if we have enough data */
245                         if(ielen < 4)
246                                 return;
247
248                         wpa_oui = wpa2_oui;
249                         break;
250
251                 case 0xdd:      /* WPA or else */
252                         wpa_oui = wpa1_oui;
253                         /* Not all IEs that start with 0xdd are WPA. 
254                         *        * So check that the OUI is valid. */
255                         if((ielen < 8) || ((memcmp(&iebuf[offset], wpa_oui, 3) != 0)
256                                 && (iebuf[offset+3] == 0x01)))
257                                         return;
258
259                         offset += 4;
260                         break;
261
262                 default:
263                         return;
264         }
265
266         /* Pick version number (little endian) */
267         ver = iebuf[offset] | (iebuf[offset + 1] << 8);
268         offset += 2;
269
270         if(iebuf[0] == 0xdd)
271                 wpa1 = 1;
272
273         if(iebuf[0] == 0x30)
274                 wpa2 = 1;
275
276         if( wpa1 && (ce->wpa_version == 2) )
277                 ce->wpa_version = 3;
278         else if( wpa2 && (ce->wpa_version == 1) )
279                 ce->wpa_version = 3;
280         else if( wpa1 && !ce->wpa_version )
281                 ce->wpa_version = 1;
282         else if( wpa2 && !ce->wpa_version )
283                 ce->wpa_version = 2;
284
285         if(ielen < (offset + 4))
286         {
287                 ce->group_ciphers |= (1<<2); /* TKIP */
288                 ce->pair_ciphers  |= (1<<2); /* TKIP */
289                 ce->auth_suites   |= (1<<2); /* PSK */
290                 return;
291         }
292
293         if(memcmp(&iebuf[offset], wpa_oui, 3) != 0)
294                 ce->group_ciphers |= (1<<7); /* Proprietary */
295         else
296                 ce->group_ciphers |= (1<<iebuf[offset+3]);
297
298         offset += 4;
299
300         if(ielen < (offset + 2))
301         {
302                 ce->pair_ciphers |= (1<<2); /* TKIP */
303                 ce->auth_suites  |= (1<<2); /* PSK */
304                 return;
305         }
306
307         /* Otherwise, we have some number of pairwise ciphers. */
308         cnt = iebuf[offset] | (iebuf[offset + 1] << 8);
309         offset += 2;
310
311         if(ielen < (offset + 4*cnt))
312                 return;
313
314         *buf = '\0';
315         for(i = 0; i < cnt; i++)
316         {
317                 if(memcmp(&iebuf[offset], wpa_oui, 3) != 0)
318                         ce->pair_ciphers |= (1<<7); /* Proprietary */
319                 else if(iebuf[offset+3] <= IW_IE_CYPHER_NUM)
320                         ce->pair_ciphers |= (1<<iebuf[offset+3]);
321                 //else
322                 //      ce->pair_ciphers[ce->pair_cipher_num++] = 255; /* Unknown */
323
324                 offset += 4;
325         }
326
327         /* Check if we are done */
328         if(ielen < (offset + 2))
329                 return;
330
331         /* Now, we have authentication suites. */
332         cnt = iebuf[offset] | (iebuf[offset + 1] << 8);
333         offset += 2;
334         *buf = '\0';
335
336         if(ielen < (offset + 4*cnt))
337                 return;
338
339         for(i = 0; i < cnt; i++)
340         {
341                 if(memcmp(&iebuf[offset], wpa_oui, 3) != 0)
342                         ce->auth_suites |= (1<<7); /* Proprietary */
343                 else if(iebuf[offset+3] <= IW_IE_KEY_MGMT_NUM)
344                         ce->auth_suites |= (1<<iebuf[offset+3]);
345                 //else
346                 //      ce->auth_suites[ce->auth_suite_num++] = 255; /* Unknown */
347
348                 offset += 4;
349         }
350 }
351
352
353 static inline int wext_fill_entry(struct stream_descr *stream, struct iw_event *event,
354         struct iw_range *iw_range, int has_range, struct iwinfo_scanlist_entry *e)
355 {
356         int i;
357         double freq;
358
359         /* Now, let's decode the event */
360         switch(event->cmd)
361         {
362                 case SIOCGIWAP:
363                         memcpy(e->mac, &event->u.ap_addr.sa_data, 6);
364                         break;
365
366                 case SIOCGIWFREQ:
367                         if( event->u.freq.m >= 1000 )
368                         {
369                                 freq = wext_freq2float(&(event->u.freq));
370
371                                 for(i = 0; i < iw_range->num_frequency; i++)
372                                 {
373                                         if( wext_freq2float(&iw_range->freq[i]) == freq )
374                                         {
375                                                 e->channel = iw_range->freq[i].i;
376                                                 break;
377                                         }
378                                 }
379                         }
380                         else
381                         {
382                                 e->channel = event->u.freq.m;
383                         }
384
385                         break;
386
387                 case SIOCGIWMODE:
388                         switch(event->u.mode)
389                         {
390                                 case 1:
391                                         sprintf((char *) e->mode, "Ad-Hoc");
392                                         break;
393
394                                 case 3:
395                                         sprintf((char *) e->mode, "Master");
396                                         break;
397
398                                 default:
399                                         sprintf((char *) e->mode, "Unknown");
400                         }
401
402                         break;
403
404                 case SIOCGIWESSID:
405                         if( event->u.essid.pointer && event->u.essid.length && event->u.essid.flags )
406                                 memcpy(e->ssid, event->u.essid.pointer, event->u.essid.length);
407
408                         break;
409
410                 case SIOCGIWENCODE:
411                         e->crypto.enabled = !(event->u.data.flags & IW_ENCODE_DISABLED);
412                         break;
413
414                 case IWEVQUAL:
415                         e->signal = event->u.qual.level;
416                         e->quality = event->u.qual.qual;
417                         e->quality_max = iw_range->max_qual.qual;
418                         break;
419 #if 0
420                 case SIOCGIWRATE:
421                         if(state->val_index == 0)
422                         {
423                                 lua_pushstring(L, "bitrates");
424                                 lua_newtable(L);
425                         }
426                         //iw_print_bitrate(buffer, sizeof(buffer), event->u.bitrate.value);
427                         snprintf(buffer, sizeof(buffer), "%d", event->u.bitrate.value);
428                         lua_pushinteger(L, state->val_index + 1);
429                         lua_pushstring(L, buffer);
430                         lua_settable(L, -3);
431
432                         /* Check for termination */
433                         if(stream->value == NULL)
434                         {
435                                 lua_settable(L, -3);
436                                 state->val_index = 0;
437                         } else
438                                 state->val_index++;
439                         break;
440 #endif
441                  case IWEVGENIE:
442                         i = 0;
443
444                         while(i <= (event->u.data.length - 2))
445                         {
446                                 switch(((unsigned char *)event->u.data.pointer)[i])
447                                 {
448                                         case 0xdd:  /* WPA1 (and other) */
449                                         case 0x30:  /* WPA2 */
450                                                 wext_fill_wpa((unsigned char *)event->u.data.pointer + i,
451                                                         event->u.data.length, e);
452
453                                                 break;
454                                 }
455
456                                 i += ((unsigned char *)event->u.data.pointer)[i+1] + 2;
457                         }
458
459                         break;
460         }
461
462         return 0;
463 }
464
465
466 int wext_get_scanlist(const char *ifname, char *buf, int *len)
467 {
468         struct iwreq wrq;
469         struct iw_scan_req scanopt;        /* Options for 'set' */
470         //int scanflags = 0;      /* Flags for scan */
471         unsigned char *buffer = NULL;      /* Results */
472         int buflen = IW_SCAN_MAX_DATA; /* Min for compat WE<17 */
473         struct iw_range range;
474         int has_range = 1;
475         struct timeval tv;             /* Select timeout */
476         int timeout = 15000000;     /* 15s */
477
478         int entrylen = 0;
479         struct iwinfo_scanlist_entry e;
480
481         //IWINFO_BUFSIZE
482         wrq.u.data.pointer = (caddr_t) &range;
483         wrq.u.data.length  = sizeof(struct iw_range);
484         wrq.u.data.flags   = 0; 
485
486         if( wext_ioctl(ifname, SIOCGIWRANGE, &wrq) >= 0 )
487         {
488                 /* Init timeout value -> 250ms between set and first get */
489                 tv.tv_sec  = 0;
490                 tv.tv_usec = 250000;
491
492                 /* Clean up set args */
493                 memset(&scanopt, 0, sizeof(scanopt));
494
495                 wrq.u.data.pointer = NULL;
496                 wrq.u.data.flags   = 0;
497                 wrq.u.data.length  = 0;
498
499                 /* Initiate Scanning */
500                 if( wext_ioctl(ifname, SIOCSIWSCAN, &wrq) >= 0 )
501                 {
502                         timeout -= tv.tv_usec;
503
504                         /* Forever */
505                         while(1)
506                         {
507                                 fd_set rfds;       /* File descriptors for select */
508                                 int last_fd;    /* Last fd */
509                                 int ret;
510
511                                 /* Guess what ? We must re-generate rfds each time */
512                                 FD_ZERO(&rfds);
513                                 last_fd = -1;
514                                 /* In here, add the rtnetlink fd in the list */
515
516                                 /* Wait until something happens */
517                                 ret = select(last_fd + 1, &rfds, NULL, NULL, &tv);
518
519                                 /* Check if there was an error */
520                                 if(ret < 0)
521                                 {
522                                         if(errno == EAGAIN || errno == EINTR)
523                                                 continue;
524
525                                         return -1;
526                                 }
527
528                                 /* Check if there was a timeout */
529                                 if(ret == 0)
530                                 {
531                                         unsigned char *newbuf;
532
533                 realloc:
534                                         /* (Re)allocate the buffer - realloc(NULL, len) == malloc(len) */
535                                         newbuf = realloc(buffer, buflen);
536                                         if(newbuf == NULL)
537                                         {
538                                                 if(buffer)
539                                                         free(buffer);
540
541                                                 return -1;
542                                         }
543
544                                         buffer = newbuf;
545
546                                         /* Try to read the results */
547                                         wrq.u.data.pointer = buffer;
548                                         wrq.u.data.flags   = 0;
549                                         wrq.u.data.length  = buflen;
550
551                                         if( wext_ioctl(ifname, SIOCGIWSCAN, &wrq) )
552                                         {
553                                                 /* Check if buffer was too small (WE-17 only) */
554                                                 if((errno == E2BIG) && (range.we_version_compiled > 16))
555                                                 {
556                                                         /* Some driver may return very large scan results, either
557                                                          * because there are many cells, or because they have many
558                                                          * large elements in cells (like IWEVCUSTOM). Most will
559                                                          * only need the regular sized buffer. We now use a dynamic
560                                                          * allocation of the buffer to satisfy everybody. Of course,
561                                                          * as we don't know in advance the size of the array, we try
562                                                          * various increasing sizes. Jean II */
563
564                                                         /* Check if the driver gave us any hints. */
565                                                         if(wrq.u.data.length > buflen)
566                                                                 buflen = wrq.u.data.length;
567                                                         else
568                                                                 buflen *= 2;
569
570                                                         /* Try again */
571                                                         goto realloc;
572                                                 }
573
574                                                 /* Check if results not available yet */
575                                                 if(errno == EAGAIN)
576                                                 {
577                                                         /* Restart timer for only 100ms*/
578                                                         tv.tv_sec = 0;
579                                                         tv.tv_usec = 100000;
580                                                         timeout -= tv.tv_usec;
581
582                                                         if(timeout > 0)
583                                                                 continue;   /* Try again later */
584                                                 }
585
586                                                 /* Bad error */
587                                                 free(buffer);
588                                                 return -1;
589
590                                         } else {
591                                                 /* We have the results, go to process them */
592                                                 break;
593                                         }
594                                 }
595                         }
596
597                         if( wrq.u.data.length )
598                         {
599                                 struct iw_event       iwe;
600                                 struct stream_descr   stream;
601                                 int ret;
602                                 int first = 1;
603
604                                 memset(&stream, 0, sizeof(stream));
605                                 stream.current = (char *)buffer;
606                                 stream.end     = (char *)buffer + wrq.u.data.length;
607
608                                 do
609                                 {
610                                         /* Extract an event and print it */
611                                         ret = wext_extract_event(&stream, &iwe);
612
613                                         if(ret >= 0)
614                                         {
615                                                 if( (iwe.cmd == SIOCGIWAP) || (ret == 0) )
616                                                 {
617                                                         if( first )
618                                                         {
619                                                                 first = 0;
620                                                         }
621                                                         else if( (entrylen + sizeof(struct iwinfo_scanlist_entry)) <= IWINFO_BUFSIZE )
622                                                         {
623                                                                 memcpy(&buf[entrylen], &e, sizeof(struct iwinfo_scanlist_entry));
624                                                                 entrylen += sizeof(struct iwinfo_scanlist_entry);
625                                                         }
626                                                         else
627                                                         {
628                                                                 /* we exceed the callers buffer size, abort here ... */
629                                                                 break;
630                                                         }
631
632                                                         memset(&e, 0, sizeof(struct iwinfo_scanlist_entry));
633                                                 }
634
635                                                 wext_fill_entry(&stream, &iwe, &range, has_range, &e);
636                                         }
637
638                                 } while(ret > 0);
639
640                                 free(buffer);
641                                 *len = entrylen;
642                                 return 0;
643                         }
644
645                         free(buffer);
646                         return 0;
647                 }
648         }
649
650         return -1;
651 }
652