First test of wlan driver, sends beacon every 2 seconds
[oweals/gnunet.git] / src / transport / gnunet-transport-wlan-helper.c
1 /*
2  This file is part of GNUnet.
3  (C) 2010 Christian Grothoff (and other contributing authors)
4
5  GNUnet is free software; you can redistribute it and/or modify
6  it under the terms of the GNU General Public License as published
7  by the Free Software Foundation; either version 3, or (at your
8  option) any later version.
9
10  GNUnet is distributed in the hope that it will be useful, but
11  WITHOUT ANY WARRANTY; without even the implied warranty of
12  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  General Public License for more details.
14
15  You should have received a copy of the GNU General Public License
16  along with GNUnet; see the file COPYING.  If not, write to the
17  Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18  Boston, MA 02111-1307, USA.
19  */
20
21 /**
22  * @file src/transport/gnunet-transport-wlan-helper.c
23  * @brief wlan layer two server; must run as root (SUID will do)
24  *        This code will work under GNU/Linux only.
25  * @author David Brodski
26  *
27  * This program serves as the mediator between the wlan interface and
28  * gnunet
29  */
30
31 #include <sys/socket.h>
32 #include <sys/ioctl.h>
33 #include <sys/types.h>
34 #include <sys/wait.h>
35 #include <sys/time.h>
36 #include <sys/stat.h>
37 #include <netpacket/packet.h>
38 #include <linux/if_ether.h>
39 #include <linux/if.h>
40 #include <linux/wireless.h>
41 #include <netinet/in.h>
42 #include <linux/if_tun.h>
43 #include <stdio.h>
44 #include <stdlib.h>
45 #include <string.h>
46 #include <unistd.h>
47 #include <fcntl.h>
48 #include <errno.h>
49 #include <dirent.h>
50 //#include <sys/utsname.h>
51 #include <sys/param.h>
52
53 /*
54  //#include <resolv.h>
55  #include <string.h>
56  #include <utime.h>
57  //#include <unistd.h>
58  #include <getopt.h>
59  */
60 //#include "platform.h"
61 #include "gnunet_constants.h"
62 #include "gnunet_os_lib.h"
63 #include "gnunet_transport_plugin.h"
64 #include "transport.h"
65 #include "gnunet_util_lib.h"
66 #include "plugin_transport_wlan.h"
67 #include "gnunet_common.h"
68 #include "gnunet-transport-wlan-helper.h"
69 #include "gnunet_crypto_lib.h"
70
71 #include <pcap.h>
72 #include <stdio.h>
73 #include <stdlib.h>
74 #include <sys/stat.h>
75
76 #include "wlan/radiotap-parser.h"
77 /* radiotap-parser defines types like u8 that
78  * ieee80211_radiotap.h needs
79  *
80  * we use our local copy of ieee80211_radiotap.h
81  *
82  * - since we can't support extensions we don't understand
83  * - since linux does not include it in userspace headers
84  */
85 #include "wlan/ieee80211_radiotap.h"
86 #include "wlan/crctable_osdep.h"
87 #include "wlan/loopback_helper.h"
88
89 #define ARPHRD_IEEE80211        801
90 #define ARPHRD_IEEE80211_PRISM  802
91 #define ARPHRD_IEEE80211_FULL   803
92
93 int first;
94 int closeprog;
95
96 #include "wlan/helper_common.h"
97 #include "wlan/loopback_helper.h"
98
99 #define DEBUG 1
100
101 typedef enum
102 {
103   DT_NULL = 0,
104   DT_WLANNG,
105   DT_HOSTAP,
106   DT_MADWIFI,
107   DT_MADWIFING,
108   DT_BCM43XX,
109   DT_ORINOCO,
110   DT_ZD1211RW,
111   DT_ACX,
112   DT_MAC80211_RT,
113   DT_AT76USB,
114   DT_IPW2200
115
116 } DRIVER_TYPE;
117
118 static const char * szaDriverTypes[] =
119   { [DT_NULL] = "Unknown", [DT_WLANNG] = "Wlan-NG", [DT_HOSTAP] = "HostAP",
120       [DT_MADWIFI] = "Madwifi", [DT_MADWIFING] = "Madwifi-NG",
121       [DT_BCM43XX] = "BCM43xx", [DT_ORINOCO] = "Orinoco",
122       [DT_ZD1211RW] = "ZD1211RW", [DT_ACX] = "ACX",
123       [DT_MAC80211_RT] = "Mac80211-Radiotap", [DT_AT76USB] = "Atmel 76_usb",
124       [DT_IPW2200] = "ipw2200" };
125
126 struct Hardware_Infos
127 {
128
129   struct sendbuf *write_pout;
130   int fd_in, arptype_in;
131   int fd_out, arptype_out;
132   int fd_main;
133   int fd_rtc;
134
135   DRIVER_TYPE drivertype; /* inited to DT_UNKNOWN on allocation by wi_alloc */
136
137   FILE *f_cap_in;
138
139   struct pcap_file_header pfh_in;
140
141   int sysfs_inject;
142   int channel;
143   int freq;
144   int rate;
145   int tx_power;
146   char *wlanctlng; /* XXX never set */
147   char *iwpriv;
148   char *iwconfig;
149   char *ifconfig;
150   char *iface;
151   char *main_if;
152   unsigned char pl_mac[6];
153   int inject_wlanng;
154 };
155
156 //#include "radiotap.h"
157
158 // mac of this node
159 char mac[] =
160   { 0x13, 0x22, 0x33, 0x44, 0x55, 0x66 };
161
162 /* wifi bitrate to use in 500kHz units */
163
164 static const u8 u8aRatesToUse[] =
165   {
166
167   54 * 2, 48 * 2, 36 * 2, 24 * 2, 18 * 2, 12 * 2, 9 * 2, 11 * 2, 11, // 5.5
168       2 * 2, 1 * 2 };
169
170 #define OFFSET_FLAGS 0x10
171 #define OFFSET_RATE 0x11
172
173 // this is where we store a summary of the
174 // information from the radiotap header
175
176 typedef struct
177 {
178   int m_nChannel;
179   int m_nChannelFlags;
180   int m_nRate;
181   int m_nAntenna;
182   int m_nRadiotapFlags;
183 }__attribute__((packed)) PENUMBRA_RADIOTAP_DATA;
184
185 static void
186 sigfunc_hw(int sig)
187 {
188   closeprog = 1;
189 }
190
191 void
192 Dump(u8 * pu8, int nLength)
193 {
194   char sz[256], szBuf[512], szChar[17], *buf, fFirst = 1;
195   unsigned char baaLast[2][16];
196   uint n, nPos = 0, nStart = 0, nLine = 0, nSameCount = 0;
197
198   buf = szBuf;
199   szChar[0] = '\0';
200
201   for (n = 0; n < nLength; n++)
202     {
203       baaLast[(nLine & 1) ^ 1][n & 0xf] = pu8[n];
204       if ((pu8[n] < 32) || (pu8[n] >= 0x7f))
205         szChar[n & 0xf] = '.';
206       else
207         szChar[n & 0xf] = pu8[n];
208       szChar[(n & 0xf) + 1] = '\0';
209       nPos += sprintf(&sz[nPos], "%02X ", baaLast[(nLine & 1) ^ 1][n & 0xf]);
210       if ((n & 15) != 15)
211         continue;
212       if ((memcmp(baaLast[0], baaLast[1], 16) == 0) && (!fFirst))
213         {
214           nSameCount++;
215         }
216       else
217         {
218           if (nSameCount)
219             buf += sprintf(buf, "(repeated %d times)\n", nSameCount);
220           buf += sprintf(buf, "%04x: %s %s\n", nStart, sz, szChar);
221           nSameCount = 0;
222           printf("%s", szBuf);
223           buf = szBuf;
224         }
225       nPos = 0;
226       nStart = n + 1;
227       nLine++;
228       fFirst = 0;
229       sz[0] = '\0';
230       szChar[0] = '\0';
231     }
232   if (nSameCount)
233     buf += sprintf(buf, "(repeated %d times)\n", nSameCount);
234
235   buf += sprintf(buf, "%04x: %s", nStart, sz);
236   if (n & 0xf)
237     {
238       *buf++ = ' ';
239       while (n & 0xf)
240         {
241           buf += sprintf(buf, "   ");
242           n++;
243         }
244     }
245   buf += sprintf(buf, "%s\n", szChar);
246   printf("%s", szBuf);
247 }
248
249 void
250 usage()
251 {
252   printf("Usage: wlan-hwd [options] <interface>\n\nOptions\n"
253     "-f/--fcs           Mark as having FCS (CRC) already\n"
254     "                   (pkt ends with 4 x sacrificial - chars)\n"
255     "Example:\n"
256     "  echo -n mon0 > /sys/class/ieee80211/phy0/add_iface\n"
257     "  iwconfig mon0 mode monitor\n"
258     "  ifconfig mon0 up\n"
259     "  wlan-hwd mon0        Spam down mon0 with\n"
260     "                       radiotap header first\n"
261     "\n");
262   exit(1);
263 }
264
265 void
266 packet_callback(unsigned char *Args, const struct pcap_pkthdr* Pkthdr,
267     unsigned char *Packet)
268 {
269   fprintf(stderr, "+");
270   fflush(stderr);
271 }
272
273 unsigned long
274 calc_crc_osdep(unsigned char * buf, int len)
275 {
276   unsigned long crc = 0xFFFFFFFF;
277
278   for (; len > 0; len--, buf++)
279     crc = crc_tbl_osdep[(crc ^ *buf) & 0xFF] ^ (crc >> 8);
280
281   return (~crc);
282 }
283
284 /* CRC checksum verification routine */
285
286 int
287 check_crc_buf_osdep(unsigned char *buf, int len)
288 {
289   unsigned long crc;
290
291   if (len < 0)
292     return 0;
293
294   crc = calc_crc_osdep(buf, len);
295   buf += len;
296   return (((crc) & 0xFF) == buf[0] && ((crc >> 8) & 0xFF) == buf[1] && ((crc
297       >> 16) & 0xFF) == buf[2] && ((crc >> 24) & 0xFF) == buf[3]);
298 }
299
300 /* Search a file recursively */
301 static char *
302 searchInside(const char * dir, const char * filename)
303 {
304   char * ret;
305   char * curfile;
306   struct stat sb;
307   int len, lentot;
308   DIR *dp;
309   struct dirent *ep;
310
311   dp = opendir(dir);
312   if (dp == NULL)
313     {
314       return NULL;
315     }
316
317   len = strlen(filename);
318   lentot = strlen(dir) + 256 + 2;
319   curfile = (char *) calloc(1, lentot);
320
321   while ((ep = readdir(dp)) != NULL)
322     {
323
324       memset(curfile, 0, lentot);
325       sprintf(curfile, "%s/%s", dir, ep->d_name);
326
327       //Checking if it's the good file
328       if ((int) strlen(ep->d_name) == len && !strcmp(ep->d_name, filename))
329         {
330           (void) closedir(dp);
331           return curfile;
332         }
333       lstat(curfile, &sb);
334
335       //If it's a directory and not a link, try to go inside to search
336       if (S_ISDIR(sb.st_mode) && !S_ISLNK(sb.st_mode))
337         {
338           //Check if the directory isn't "." or ".."
339           if (strcmp(".", ep->d_name) && strcmp("..", ep->d_name))
340             {
341               //Recursive call
342               ret = searchInside(curfile, filename);
343               if (ret != NULL)
344                 {
345                   (void) closedir(dp);
346                   free(curfile);
347                   return ret;
348                 }
349             }
350         }
351     }
352   (void) closedir(dp);
353   free(curfile);
354   return NULL;
355 }
356
357 /* Search a wireless tool and return its path */
358 static char *
359 wiToolsPath(const char * tool)
360 {
361   char * path;
362   int i, nbelems;
363   static const char * paths[] =
364     { "/sbin", "/usr/sbin", "/usr/local/sbin", "/bin", "/usr/bin",
365         "/usr/local/bin", "/tmp" };
366
367   nbelems = sizeof(paths) / sizeof(char *);
368
369   for (i = 0; i < nbelems; i++)
370     {
371       path = searchInside(paths[i], tool);
372       if (path != NULL)
373         return path;
374     }
375
376   return NULL;
377 }
378
379 static int
380 linux_get_channel(struct Hardware_Infos *dev)
381 {
382   struct iwreq wrq;
383   int fd, frequency;
384   int chan = 0;
385
386   memset(&wrq, 0, sizeof(struct iwreq));
387
388   if (dev->main_if)
389     strncpy(wrq.ifr_name, dev->main_if, IFNAMSIZ );
390   else
391     strncpy(wrq.ifr_name, dev->iface, IFNAMSIZ );
392
393   fd = dev->fd_in;
394   if (dev->drivertype == DT_IPW2200)
395     fd = dev->fd_main;
396
397   if (ioctl(fd, SIOCGIWFREQ, &wrq) < 0)
398     return (-1);
399
400   frequency = wrq.u.freq.m;
401   if (frequency > 100000000)
402     frequency /= 100000;
403   else if (frequency > 1000000)
404     frequency /= 1000;
405
406   if (frequency > 1000)
407     chan = getChannelFromFrequency(frequency);
408   else
409     chan = frequency;
410
411   return chan;
412 }
413
414 static int
415 linux_read(struct Hardware_Infos * dev, unsigned char *buf, int count,
416     struct rx_info * ri)
417 {
418   unsigned char tmpbuf[4096];
419
420   int caplen, n, got_signal, got_noise, got_channel, fcs_removed;
421
422   caplen = n = got_signal = got_noise = got_channel = fcs_removed = 0;
423
424   if ((unsigned) count > sizeof(tmpbuf))
425     return (-1);
426   caplen = read(dev->fd_in, tmpbuf, count);
427   if (0 > caplen)
428     {
429       if (errno == EAGAIN)
430         return (0);
431
432       perror("read failed");
433       return (-1);
434     }
435
436   memset(buf, 0, sizeof(buf));
437
438   /* XXX */
439   if (ri)
440     memset(ri, 0, sizeof(*ri));
441
442   if (dev->arptype_in == ARPHRD_IEEE80211_PRISM)
443     {
444       /* skip the prism header */
445       if (tmpbuf[7] == 0x40)
446         {
447           /* prism54 uses a different format */
448           if (ri)
449             {
450               ri->ri_power = tmpbuf[0x33];
451               ri->ri_noise = *(unsigned int *) (tmpbuf + 0x33 + 12);
452               ri->ri_rate = (*(unsigned int *) (tmpbuf + 0x33 + 24)) * 500000;
453
454               got_signal = 1;
455               got_noise = 1;
456             }
457
458           n = 0x40;
459         }
460       else
461         {
462           if (ri)
463             {
464               ri->ri_mactime = *(u_int64_t*) (tmpbuf + 0x5C - 48);
465               ri->ri_channel = *(unsigned int *) (tmpbuf + 0x5C - 36);
466               ri->ri_power = *(unsigned int *) (tmpbuf + 0x5C);
467               ri->ri_noise = *(unsigned int *) (tmpbuf + 0x5C + 12);
468               ri->ri_rate = (*(unsigned int *) (tmpbuf + 0x5C + 24)) * 500000;
469
470               got_channel = 1;
471               got_signal = 1;
472               got_noise = 1;
473             }
474
475           n = *(int *) (tmpbuf + 4);
476         }
477
478       if (n < 8 || n >= caplen)
479         return (0);
480     }
481
482   if (dev->arptype_in == ARPHRD_IEEE80211_FULL)
483     {
484       struct ieee80211_radiotap_iterator iterator;
485       struct ieee80211_radiotap_header *rthdr;
486
487       rthdr = (struct ieee80211_radiotap_header *) tmpbuf;
488
489       if (ieee80211_radiotap_iterator_init(&iterator, rthdr, caplen) < 0)
490         return (0);
491
492       /* go through the radiotap arguments we have been given
493        * by the driver
494        */
495
496       while (ri && (ieee80211_radiotap_iterator_next(&iterator) >= 0))
497         {
498
499           switch (iterator.this_arg_index)
500             {
501
502           case IEEE80211_RADIOTAP_TSFT:
503             ri->ri_mactime = le64_to_cpu(*((uint64_t*) iterator.this_arg));
504             break;
505
506           case IEEE80211_RADIOTAP_DBM_ANTSIGNAL:
507             if (!got_signal)
508               {
509                 if (*iterator.this_arg < 127)
510                   ri->ri_power = *iterator.this_arg;
511                 else
512                   ri->ri_power = *iterator.this_arg - 255;
513
514                 got_signal = 1;
515               }
516             break;
517
518           case IEEE80211_RADIOTAP_DB_ANTSIGNAL:
519             if (!got_signal)
520               {
521                 if (*iterator.this_arg < 127)
522                   ri->ri_power = *iterator.this_arg;
523                 else
524                   ri->ri_power = *iterator.this_arg - 255;
525
526                 got_signal = 1;
527               }
528             break;
529
530           case IEEE80211_RADIOTAP_DBM_ANTNOISE:
531             if (!got_noise)
532               {
533                 if (*iterator.this_arg < 127)
534                   ri->ri_noise = *iterator.this_arg;
535                 else
536                   ri->ri_noise = *iterator.this_arg - 255;
537
538                 got_noise = 1;
539               }
540             break;
541
542           case IEEE80211_RADIOTAP_DB_ANTNOISE:
543             if (!got_noise)
544               {
545                 if (*iterator.this_arg < 127)
546                   ri->ri_noise = *iterator.this_arg;
547                 else
548                   ri->ri_noise = *iterator.this_arg - 255;
549
550                 got_noise = 1;
551               }
552             break;
553
554           case IEEE80211_RADIOTAP_ANTENNA:
555             ri->ri_antenna = *iterator.this_arg;
556             break;
557
558           case IEEE80211_RADIOTAP_CHANNEL:
559             ri->ri_channel = *iterator.this_arg;
560             got_channel = 1;
561             break;
562
563           case IEEE80211_RADIOTAP_RATE:
564             ri->ri_rate = (*iterator.this_arg) * 500000;
565             break;
566
567           case IEEE80211_RADIOTAP_FLAGS:
568             /* is the CRC visible at the end?
569              * remove
570              */
571             if (*iterator.this_arg & IEEE80211_RADIOTAP_F_FCS)
572               {
573                 fcs_removed = 1;
574                 caplen -= 4;
575               }
576
577             if (*iterator.this_arg & IEEE80211_RADIOTAP_F_RX_BADFCS)
578               return (0);
579
580             break;
581
582             }
583         }
584
585       n = le16_to_cpu(rthdr->it_len);
586
587       if (n <= 0 || n >= caplen)
588         return (0);
589     }
590
591   caplen -= n;
592
593   //detect fcs at the end, even if the flag wasn't set and remove it
594   if (fcs_removed == 0 && check_crc_buf_osdep(tmpbuf + n, caplen - 4) == 1)
595     {
596       caplen -= 4;
597     }
598
599   memcpy(buf, tmpbuf + n, caplen);
600
601   if (ri && !got_channel)
602     ri->ri_channel = linux_get_channel(dev);
603
604   return (caplen);
605 }
606
607 static int
608 linux_write(struct Hardware_Infos * dev, unsigned char *buf, unsigned int count)
609 {
610   int ret, usedrtap = 0;
611   unsigned short int *p_rtlen;
612
613   unsigned char * u8aRadiotap = buf;
614
615   /* Pointer to the radiotap header length field for later use. */
616   p_rtlen = (unsigned short int*) (u8aRadiotap + 2);
617   usedrtap = 0;
618   ret = write(dev->fd_out, buf, count);
619
620   if (ret < 0)
621     {
622       if (errno == EAGAIN || errno == EWOULDBLOCK || errno == ENOBUFS || errno
623           == ENOMEM)
624         {
625           usleep(10000);
626           return (0);
627         }
628
629       perror("write failed");
630       return (-1);
631     }
632
633   /* radiotap header length is stored little endian on all systems */
634   if (usedrtap)
635     ret -= letoh16(*p_rtlen);
636
637   if (ret < 0)
638     {
639       if (errno == EAGAIN || errno == EWOULDBLOCK || errno == ENOBUFS || errno
640           == ENOMEM)
641         {
642           usleep(10000);
643           return (0);
644         }
645
646       perror("write failed");
647       return (-1);
648     }
649
650   return (ret);
651 }
652
653 static int
654 openraw(struct Hardware_Infos * dev, char * iface, int fd, int * arptype,
655     uint8_t *mac)
656 {
657   struct ifreq ifr;
658   struct iwreq wrq;
659   struct packet_mreq mr;
660   struct sockaddr_ll sll;
661
662   /* find the interface index */
663
664   memset(&ifr, 0, sizeof(ifr));
665   strncpy(ifr.ifr_name, iface, sizeof(ifr.ifr_name) - 1);
666
667   if (ioctl(fd, SIOCGIFINDEX, &ifr) < 0)
668     {
669       printf("Interface %s: \n", iface);
670       perror("ioctl(SIOCGIFINDEX) failed");
671       return (1);
672     }
673
674   memset(&sll, 0, sizeof(sll));
675   sll.sll_family = AF_PACKET;
676   sll.sll_ifindex = ifr.ifr_ifindex;
677
678   switch (dev->drivertype)
679     {
680   default:
681     sll.sll_protocol = htons(ETH_P_ALL);
682     break;
683     }
684
685   /* lookup the hardware type */
686
687   if (ioctl(fd, SIOCGIFHWADDR, &ifr) < 0)
688     {
689       printf("Interface %s: \n", iface);
690       perror("ioctl(SIOCGIFHWADDR) failed");
691       return (1);
692     }
693
694   /* lookup iw mode */
695   memset(&wrq, 0, sizeof(struct iwreq));
696   strncpy(wrq.ifr_name, iface, IFNAMSIZ);
697
698   if (ioctl(fd, SIOCGIWMODE, &wrq) < 0)
699     {
700       /* most probably not supported (ie for rtap ipw interface) *
701        * so just assume its correctly set...                     */
702       wrq.u.mode = IW_MODE_MONITOR;
703     }
704
705   if ((ifr.ifr_hwaddr.sa_family != ARPHRD_IEEE80211 && ifr.ifr_hwaddr.sa_family
706       != ARPHRD_IEEE80211_PRISM && ifr.ifr_hwaddr.sa_family
707       != ARPHRD_IEEE80211_FULL) || (wrq.u.mode != IW_MODE_MONITOR))
708     {
709       printf("Error: %s not in monitor mode\n", iface);
710       return (1);
711     }
712
713   /* Is interface st to up, broadcast & running ? */
714   if ((ifr.ifr_flags | IFF_UP | IFF_BROADCAST | IFF_RUNNING) != ifr.ifr_flags)
715     {
716       /* Bring interface up*/
717       ifr.ifr_flags |= IFF_UP | IFF_BROADCAST | IFF_RUNNING;
718
719       if (ioctl(fd, SIOCSIFFLAGS, &ifr) < 0)
720         {
721           perror("ioctl(SIOCSIFFLAGS) failed");
722           return (1);
723         }
724     }
725   /* bind the raw socket to the interface */
726
727   if (bind(fd, (struct sockaddr *) &sll, sizeof(sll)) < 0)
728     {
729       printf("Interface %s: \n", iface);
730       perror("bind(ETH_P_ALL) failed");
731       return (1);
732     }
733
734   /* lookup the hardware type */
735
736   if (ioctl(fd, SIOCGIFHWADDR, &ifr) < 0)
737     {
738       printf("Interface %s: \n", iface);
739       perror("ioctl(SIOCGIFHWADDR) failed");
740       return (1);
741     }
742
743   memcpy(mac, (unsigned char*) ifr.ifr_hwaddr.sa_data, 6);
744
745   *arptype = ifr.ifr_hwaddr.sa_family;
746
747   if (ifr.ifr_hwaddr.sa_family != ARPHRD_IEEE80211 && ifr.ifr_hwaddr.sa_family
748       != ARPHRD_IEEE80211_PRISM && ifr.ifr_hwaddr.sa_family
749       != ARPHRD_IEEE80211_FULL)
750     {
751       if (ifr.ifr_hwaddr.sa_family == 1)
752         fprintf(stderr, "\nARP linktype is set to 1 (Ethernet) ");
753       else
754         fprintf(stderr, "\nUnsupported hardware link type %4d ",
755             ifr.ifr_hwaddr.sa_family);
756
757       fprintf(stderr, "- expected ARPHRD_IEEE80211,\nARPHRD_IEEE80211_"
758         "FULL or ARPHRD_IEEE80211_PRISM instead.  Make\n"
759         "sure RFMON is enabled: run 'airmon-ng start %s"
760         " <#>'\nSysfs injection support was not found "
761         "either.\n\n", iface);
762       return (1);
763     }
764
765   /* enable promiscuous mode */
766
767   memset(&mr, 0, sizeof(mr));
768   mr.mr_ifindex = sll.sll_ifindex;
769   mr.mr_type = PACKET_MR_PROMISC;
770
771   if (setsockopt(fd, SOL_PACKET, PACKET_ADD_MEMBERSHIP, &mr, sizeof(mr)) < 0)
772     {
773       perror("setsockopt(PACKET_MR_PROMISC) failed");
774       return (1);
775     }
776
777   return (0);
778 }
779
780 int
781 wlaninit(struct Hardware_Infos * dev, char *iface)
782 {
783
784   char *iwpriv;
785   char strbuf[512];
786   dev->inject_wlanng = 1;
787   dev->rate = 2; /* default to 1Mbps if nothing is set */
788
789   /* open raw socks */
790   dev->fd_in = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
791   if (0 > dev->fd_in)
792     {
793       perror("socket(PF_PACKET) failed at fd_in");
794       if (getuid() != 0)
795         fprintf(stderr, "This program requires root privileges.\n");
796       return (1);
797     }
798
799   dev->fd_main = socket(PF_PACKET, SOCK_RAW, htons( ETH_P_ALL ) );
800   if (0 > dev->fd_main)
801     {
802       perror("socket(PF_PACKET) failed at fd_main");
803       if (getuid() != 0)
804         fprintf(stderr, "This program requires root privileges.\n");
805       return (1);
806     }
807
808   /* Check iwpriv existence */
809
810   iwpriv = wiToolsPath("iwpriv");
811   dev->iwpriv = iwpriv;
812   dev->iwconfig = wiToolsPath("iwconfig");
813   dev->ifconfig = wiToolsPath("ifconfig");
814
815   if (!iwpriv)
816     {
817       fprintf(stderr, "Can't find wireless tools, exiting.\n");
818       goto close_in;
819     }
820
821   dev->fd_out = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
822   if (0 > dev->fd_out)
823     {
824       perror("socket(PF_PACKET) failed at fd_out");
825       goto close_in;
826     }
827
828   /* figure out device type */
829
830   /* mac80211 radiotap injection
831    * detected based on interface called mon...
832    * since mac80211 allows multiple virtual interfaces
833    *
834    * note though that the virtual interfaces are ultimately using a
835    * single physical radio: that means for example they must all
836    * operate on the same channel
837    */
838
839   /* mac80211 stack detection */
840   memset(strbuf, 0, sizeof(strbuf));
841   snprintf(strbuf, sizeof(strbuf) - 1,
842       "ls /sys/class/net/%s/phy80211/subsystem >/dev/null 2>/dev/null", iface);
843
844   if (system(strbuf) == 0)
845     dev->drivertype = DT_MAC80211_RT;
846
847   else
848     {
849       // At the moment only mac80211 tested
850       return 1;
851     }
852
853 #ifdef DEBUG
854   fprintf(stderr, "Interface %s -> driver: %s\n", iface,
855       szaDriverTypes[dev->drivertype]);
856 #endif
857
858   if (openraw(dev, iface, dev->fd_out, &dev->arptype_out, dev->pl_mac) != 0)
859     {
860       goto close_out;
861     }
862
863   dev->fd_in = dev->fd_out;
864
865   dev->arptype_in = dev->arptype_out;
866
867   return 0;
868   close_out: close(dev->fd_out);
869   close_in: close(dev->fd_in);
870   return 1;
871 }
872
873 static void
874 stdin_send_hw(void *cls, void *client, const struct GNUNET_MessageHeader *hdr)
875 {
876   struct Hardware_Infos * dev = cls;
877   struct sendbuf *write_pout = dev->write_pout;
878   struct Radiotap_Send * header = (struct Radiotap_Send *) &hdr[1];
879   int sendsize;
880
881   unsigned char u8aRadiotap[] =
882     { 0x00, 0x00, // <-- radiotap version
883         0x0c, 0x00, // <- radiotap header length
884         0x04, 0x80, 0x00, 0x00, // <-- bitmap
885         0x00, // <-- rate
886         0x00, // <-- padding for natural alignment
887         0x18, 0x00, // <-- TX flags
888       };
889
890   sendsize = ntohs(hdr->size) - sizeof(struct Radiotap_Send)
891       - sizeof(struct GNUNET_MessageHeader);
892
893   if ((sendsize) > MAXLINE * 2)
894     {
895       fprintf(stderr, "Function stdin_send: Packet too big for buffer\n");
896       exit(1);
897     }
898
899   if (GNUNET_MESSAGE_TYPE_WLAN_HELPER_DATA != ntohs(hdr->type))
900     {
901       fprintf(stderr, "Function stdin_send: wrong packet type\n");
902       exit(1);
903     }
904
905   u8aRadiotap[8] = header->rate;
906
907   switch (dev->drivertype)
908     {
909
910   case DT_MAC80211_RT:
911     memcpy(write_pout->buf, u8aRadiotap, sizeof(u8aRadiotap));
912     memcpy(write_pout->buf + sizeof(u8aRadiotap), write_pout->buf
913         + sizeof(struct Radiotap_Send) + sizeof(struct GNUNET_MessageHeader),
914         sendsize);
915     sendsize += sizeof(u8aRadiotap);
916
917     //usedrtap = 1;
918     break;
919   default:
920     break;
921     }
922
923   write_pout->size = sendsize;
924 }
925
926 int
927 maketest(unsigned char * buf)
928 {
929   unsigned char u8aRadiotap[] =
930     { 0x00, 0x00, // <-- radiotap version
931         0x0c, 0x00, // <- radiotap header length
932         0x04, 0x80, 0x00, 0x00, // <-- bitmap
933         0x00, // <-- rate
934         0x00, // <-- padding for natural alignment
935         0x18, 0x00, // <-- TX flags
936       };
937
938   static const uint8_t u8aIeeeHeader[] =
939     { 0x08, 0x01, // Frame Control 0x08= 00001000 -> | b1,2 = 0 -> Version 0;
940         //      b3,4 = 10 -> Data; b5-8 = 0 -> Normal Data
941         //      0x01 = 00000001 -> | b1 = 1 to DS; b2 = 0 not from DS;
942         0x00, 0x00, // Duration/ID
943         0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // mac1 - in this case receiver
944         0x13, 0x22, 0x33, 0x44, 0x55, 0x66, // mac2 - in this case sender
945         0x13, 0x22, 0x33, 0x44, 0x55, 0x66, // mac3 - in this case bssid
946         0x10, 0x86, //Sequence Control
947       };
948
949   static const char txt[] = "Hallo1Hallo2 Hallo3 Hallo4...998877665544332211";
950
951   u8aRadiotap[8] = 8;
952   memcpy(buf, u8aRadiotap, sizeof(u8aRadiotap));
953   struct ieee80211_frame * ieee = (struct ieee80211_frame *) u8aIeeeHeader;
954   memcpy(buf + sizeof(u8aRadiotap), ieee, sizeof(u8aIeeeHeader));
955   memcpy(buf + sizeof(u8aRadiotap) + sizeof(u8aIeeeHeader), txt, sizeof(txt));
956   return sizeof(u8aRadiotap) + sizeof(u8aIeeeHeader) + sizeof(txt);
957
958 }
959
960 int
961 hardwaremode(int argc, char *argv[])
962 {
963
964   struct Hardware_Infos dev;
965   struct ifreq ifreq;
966   struct rx_info * rxinfo;
967   uint8_t * mac = dev.pl_mac;
968   int fdpin, fdpout;
969
970   signal(SIGINT, &sigfunc_hw);
971   signal(SIGTERM, &sigfunc_hw);
972
973   if (wlaninit(&dev, argv[1]))
974     {
975       return 1;
976     }
977
978   printf("Device %s -> Ethernet %02x:%02x:%02x:%02x:%02x:%02x\n",
979       ifreq.ifr_name, (int) mac[0], (int) mac[1], (int) mac[2], (int) mac[3],
980       (int) mac[4], (int) mac[5]);
981
982   //return 0;
983
984   char readbuf[MAXLINE];
985   int readsize = 0;
986   struct sendbuf write_std;
987   write_std.size = 0;
988   write_std.pos = 0;
989
990   struct sendbuf write_pout;
991   write_pout.size = 0;
992   write_pout.pos = 0;
993
994   dev.write_pout = &write_pout;
995
996   int ret = 0;
997   int maxfd = 0;
998
999   fd_set rfds;
1000   fd_set wfds;
1001   struct timeval tv;
1002   int retval;
1003
1004   struct GNUNET_SERVER_MessageStreamTokenizer * stdin_mst;
1005
1006   fdpin = dev.fd_in;
1007   fdpout = dev.fd_out;
1008
1009   stdin_mst = GNUNET_SERVER_mst_create(&stdin_send_hw, &dev);
1010
1011   //send mac first
1012
1013   write_std.size = send_mac_to_plugin((char *) &write_std.buf, mac);
1014
1015   //wait
1016   tv.tv_sec = 2;
1017   tv.tv_usec = 0;
1018   retval = select(0, NULL, NULL, NULL, &tv);
1019
1020   while (0 == closeprog)
1021     {
1022
1023       write_pout.size = maketest(write_pout.buf);
1024       tv.tv_sec = 2;
1025       tv.tv_usec = 0;
1026       retval = select(0, NULL, NULL, NULL, &tv);
1027
1028       maxfd = 0;
1029
1030       //set timeout
1031       tv.tv_sec = 5;
1032       tv.tv_usec = 0;
1033
1034       FD_ZERO(&rfds);
1035       // if output queue is empty
1036       if (0 == write_pout.size)
1037         {
1038           FD_SET(STDIN_FILENO, &rfds);
1039
1040         }
1041       if (0 == write_std.size)
1042         {
1043           //FD_SET(fdpin, &rfds);
1044           //maxfd = fdpin;
1045         }
1046       FD_ZERO(&wfds);
1047       // if there is something to write
1048       if (0 < write_std.size)
1049         {
1050           FD_SET(STDOUT_FILENO, &wfds);
1051           maxfd = MAX(maxfd, STDOUT_FILENO);
1052         }
1053
1054       if (0 < write_pout.size)
1055         {
1056           FD_SET(fdpout, &wfds);
1057           maxfd = MAX(maxfd, fdpout);
1058         }
1059
1060       retval = select(maxfd + 1, &rfds, &wfds, NULL, &tv);
1061
1062       if (-1 == retval && EINTR == errno)
1063         {
1064           continue;
1065         }
1066       if (0 > retval)
1067         {
1068           fprintf(stderr, "select failed: %s\n", strerror(errno));
1069           exit(1);
1070         }
1071
1072       if (FD_ISSET(STDOUT_FILENO, &wfds))
1073         {
1074           ret = write(STDOUT_FILENO, write_std.buf + write_std.pos,
1075               write_std.size - write_std.pos);
1076
1077           if (0 > ret)
1078             {
1079               closeprog = 1;
1080               fprintf(stderr, "Write ERROR to STDOUT\n");
1081               exit(1);
1082             }
1083           else
1084             {
1085               write_std.pos += ret;
1086               // check if finished
1087               if (write_std.pos == write_std.size)
1088                 {
1089                   write_std.pos = 0;
1090                   write_std.size = 0;
1091                 }
1092             }
1093         }
1094
1095       if (FD_ISSET(fdpout, &wfds))
1096         {
1097
1098           ret = linux_write(&dev, write_pout.buf, write_pout.size);
1099           //ret = write(fdpout, write_pout.buf + write_pout.pos, write_pout.size
1100           //    - write_pout.pos);
1101
1102           if (0 > ret)
1103             {
1104               closeprog = 1;
1105               fprintf(stderr, "Write ERROR to fdpout\n");
1106             }
1107           else
1108             {
1109               write_pout.pos += ret;
1110               // check if finished
1111               if (write_pout.pos != write_pout.size && ret != 0)
1112                 {
1113                   closeprog = 1;
1114                   fprintf(stderr, "Write ERROR packet not in one piece send: %u, %u\n", write_pout.pos, write_pout.size);
1115                 }
1116               else if (write_pout.pos == write_pout.size)
1117                 {
1118                   write_pout.pos = 0;
1119                   write_pout.size = 0;
1120                 }
1121
1122             }
1123         }
1124
1125       if (FD_ISSET(STDIN_FILENO, &rfds))
1126         {
1127           readsize = read(STDIN_FILENO, readbuf, sizeof(readbuf));
1128
1129           if (0 > readsize)
1130             {
1131               closeprog = 1;
1132               fprintf(stderr, "Read ERROR to STDIN_FILENO\n");
1133             }
1134           else if (0 < readsize)
1135             {
1136               GNUNET_SERVER_mst_receive(stdin_mst, NULL, readbuf, readsize,
1137                   GNUNET_NO, GNUNET_NO);
1138
1139             }
1140           else
1141             {
1142               //eof
1143               closeprog = 1;
1144             }
1145         }
1146
1147       if (FD_ISSET(fdpin, &rfds))
1148         {
1149           rxinfo = (struct rx_info *) (write_pout.buf
1150               + sizeof(struct GNUNET_MessageHeader));
1151           readsize = linux_read(&dev, (unsigned char *) readbuf
1152               + sizeof(struct rx_info) + sizeof(struct GNUNET_MessageHeader),
1153               sizeof(readbuf) - sizeof(struct rx_info)
1154                   - sizeof(struct GNUNET_MessageHeader), rxinfo);
1155           //readsize = read(fdpin, readbuf, sizeof(readbuf));
1156
1157           if (0 > readsize)
1158             {
1159               closeprog = 1;
1160               fprintf(stderr, "Read ERROR to fdpin: %s\n", strerror(errno));
1161               closeprog = 1;
1162             }
1163           else if (0 < readsize)
1164             {
1165
1166             }
1167           else
1168             {
1169               //eof
1170               //closeprog = 1;
1171             }
1172         }
1173
1174     }
1175
1176   return 0;
1177
1178 }
1179
1180 int
1181 main(int argc, char *argv[])
1182 {
1183   if (3 != argc)
1184     {
1185       fprintf(
1186           stderr,
1187           "This program must be started with the interface and the operating mode as argument.\n");
1188       return 1;
1189     }
1190
1191   if (strstr(argv[2], "1") || strstr(argv[2], "2"))
1192     {
1193
1194       return testmode(argc, argv);
1195     }
1196   else
1197     {
1198       hardwaremode(argc, argv);
1199     }
1200
1201 #if 0
1202   u8 u8aSendBuffer[500];
1203   char szErrbuf[PCAP_ERRBUF_SIZE];
1204   int nCaptureHeaderLength = 0, n80211HeaderLength = 0, nLinkEncap = 0;
1205   int nOrdinal = 0, r, nDelay = 100000;
1206   int nRateIndex = 0, retval, bytes;
1207   pcap_t *ppcap = NULL;
1208   struct bpf_program bpfprogram;
1209   char * szProgram = "", fBrokenSocket = 0;
1210   u16 u16HeaderLen;
1211   char szHostname[PATH_MAX];
1212
1213   if (gethostname(szHostname, sizeof (szHostname) - 1))
1214     {
1215       perror("unable to get hostname");
1216     }
1217   szHostname[sizeof (szHostname) - 1] = '\0';
1218
1219   printf("Packetspammer (c)2007 Andy Green <andy@warmcat.com>  GPL2\n");
1220
1221   while (1)
1222     {
1223       int nOptionIndex;
1224       static const struct option optiona[] =
1225         {
1226             { "delay", required_argument, NULL, 'd'},
1227             { "fcs", no_argument, &flagMarkWithFCS, 1},
1228             { "help", no_argument, &flagHelp, 1},
1229             { "verbose", no_argument, &flagVerbose, 1},
1230             { 0, 0, 0, 0}
1231         };
1232       int c = getopt_long(argc, argv, "d:hf",
1233           optiona, &nOptionIndex);
1234
1235       if (c == -1)
1236       break;
1237       switch (c)
1238         {
1239           case 0: // long option
1240           break;
1241
1242           case 'h': // help
1243           usage();
1244
1245           case 'd': // delay
1246           nDelay = atoi(optarg);
1247           break;
1248
1249           case 'f': // mark as FCS attached
1250           flagMarkWithFCS = 1;
1251           break;
1252
1253           case 'v': //Verbose / readable output to cout
1254           flagVerbose = 1;
1255           break;
1256
1257           default:
1258           printf("unknown switch %c\n", c);
1259           usage();
1260           break;
1261         }
1262     }
1263
1264   if (optind >= argc)
1265   usage();
1266
1267   // open the interface in pcap
1268
1269   szErrbuf[0] = '\0';
1270   ppcap = pcap_open_live(argv[optind], 800, 1, 20, szErrbuf);
1271   if (ppcap == NULL)
1272     {
1273       printf("Unable to open interface %s in pcap: %s\n",
1274           argv[optind], szErrbuf);
1275       return (1);
1276     }
1277
1278   //get mac from interface
1279
1280   /*int sock, j, k;
1281    char mac[32];
1282
1283    sock=socket(PF_INET, SOCK_STREAM, 0);
1284    if (-1==sock) {
1285    perror("can not open socket\n");
1286    return 1;
1287    }
1288
1289    if (-1==ioctl(sock, SIOCGIFHWADDR, &ifr)) {
1290    perror("ioctl(SIOCGIFHWADDR) ");
1291    return 1;
1292    }
1293    for (j=0, k=0; j<6; j++) {
1294    k+=snprintf(mac+k, sizeof(mac)-k-1, j ? ":%02X" : "%02X",
1295    (int)(unsigned int)(unsigned char)ifr.ifr_hwaddr.sa_data[j]);
1296    }
1297    mac[sizeof(mac)-1]='\0';
1298    */
1299
1300   //get header type
1301   nLinkEncap = pcap_datalink(ppcap);
1302   nCaptureHeaderLength = 0;
1303
1304   switch (nLinkEncap)
1305     {
1306
1307       case DLT_PRISM_HEADER:
1308       printf("DLT_PRISM_HEADER Encap\n");
1309       nCaptureHeaderLength = 0x40;
1310       n80211HeaderLength = 0x20; // ieee80211 comes after this
1311       szProgram = "radio[0x4a:4]==0x13223344";
1312       break;
1313
1314       case DLT_IEEE802_11_RADIO:
1315       printf("DLT_IEEE802_11_RADIO Encap\n");
1316       nCaptureHeaderLength = 0x40;
1317       n80211HeaderLength = 0x18; // ieee80211 comes after this
1318       szProgram = "ether[0x0a:4]==0x13223344";
1319       break;
1320
1321       default:
1322       printf("!!! unknown encapsulation on %s !\n", argv[1]);
1323       return (1);
1324
1325     }
1326
1327   if (pcap_compile(ppcap, &bpfprogram, szProgram, 1, 0) == -1)
1328     {
1329       puts(szProgram);
1330       puts(pcap_geterr(ppcap));
1331       return (1);
1332     }
1333   else
1334     {
1335       if (pcap_setfilter(ppcap, &bpfprogram) == -1)
1336         {
1337           puts(szProgram);
1338           puts(pcap_geterr(ppcap));
1339         }
1340       else
1341         {
1342           printf("RX Filter applied\n");
1343         }
1344       pcap_freecode(&bpfprogram);
1345     }
1346
1347   pcap_setnonblock(ppcap, 1, szErrbuf);
1348
1349   printf("   (delay between packets %dus)\n", nDelay);
1350
1351   memset(u8aSendBuffer, 0, sizeof(u8aSendBuffer));
1352
1353   while (!fBrokenSocket)
1354     {
1355       u8 * pu8 = u8aSendBuffer;
1356       struct pcap_pkthdr * ppcapPacketHeader = NULL;
1357       struct ieee80211_radiotap_iterator rti;
1358       PENUMBRA_RADIOTAP_DATA prd;
1359       //init of the values
1360       prd.m_nRate = 255;
1361       prd.m_nChannel = 255;
1362       prd.m_nAntenna = 255;
1363       prd.m_nRadiotapFlags = 255;
1364       u8 * pu8Payload = u8aSendBuffer;
1365       int n, nRate;
1366
1367       // receive
1368
1369       retval = pcap_next_ex(ppcap, &ppcapPacketHeader,
1370           (const u_char**) &pu8Payload);
1371
1372       if (retval < 0)
1373         {
1374           fBrokenSocket = 1;
1375           continue;
1376         }
1377
1378       if (retval != 1)
1379       goto do_tx;
1380
1381       u16HeaderLen = (pu8Payload[2] + (pu8Payload[3] << 8));
1382
1383       printf("rtap: ");
1384       Dump(pu8Payload, u16HeaderLen);
1385
1386       if (ppcapPacketHeader->len < (u16HeaderLen + n80211HeaderLength))
1387       continue;
1388
1389       bytes = ppcapPacketHeader->len - (u16HeaderLen + n80211HeaderLength);
1390       if (bytes < 0)
1391       continue;
1392
1393       if (ieee80211_radiotap_iterator_init(&rti,
1394               (struct ieee80211_radiotap_header *) pu8Payload, bytes) < 0)
1395       continue;
1396
1397       while ((n = ieee80211_radiotap_iterator_next(&rti)) == 0)
1398         {
1399
1400           switch (rti.this_arg_index)
1401             {
1402               case IEEE80211_RADIOTAP_RATE:
1403               prd.m_nRate = (*rti.this_arg);
1404               break;
1405
1406               case IEEE80211_RADIOTAP_CHANNEL:
1407               prd.m_nChannel = le16_to_cpu(*((u16 *)rti.this_arg));
1408               prd.m_nChannelFlags = le16_to_cpu(*((u16 *)(rti.this_arg + 2)));
1409               break;
1410
1411               case IEEE80211_RADIOTAP_ANTENNA:
1412               prd.m_nAntenna = (*rti.this_arg) + 1;
1413               break;
1414
1415               case IEEE80211_RADIOTAP_FLAGS:
1416               prd.m_nRadiotapFlags = *rti.this_arg;
1417               break;
1418
1419             }
1420         }
1421
1422       pu8Payload += u16HeaderLen + n80211HeaderLength;
1423
1424       if (prd.m_nRadiotapFlags & IEEE80211_RADIOTAP_F_FCS)
1425       bytes -= 4;
1426
1427       printf("RX: Rate: %2d.%dMbps, Freq: %d.%dGHz, "
1428           "Ant: %d, Flags: 0x%X\n", prd.m_nRate / 2, 5 * (prd.m_nRate & 1),
1429           prd.m_nChannel / 1000, prd.m_nChannel - ((prd.m_nChannel / 1000)
1430               * 1000), prd.m_nAntenna, prd.m_nRadiotapFlags);
1431
1432       Dump(pu8Payload, bytes);
1433
1434       do_tx:
1435
1436       // transmit
1437
1438       memcpy(u8aSendBuffer, u8aRadiotapHeader, sizeof(u8aRadiotapHeader));
1439       if (flagMarkWithFCS)
1440       pu8[OFFSET_FLAGS] |= IEEE80211_RADIOTAP_F_FCS;
1441       nRate = pu8[OFFSET_RATE] = u8aRatesToUse[nRateIndex++];
1442       if (nRateIndex >= sizeof(u8aRatesToUse))
1443       nRateIndex = 0;
1444       pu8 += sizeof(u8aRadiotapHeader);
1445
1446       memcpy(pu8, u8aIeeeHeader, sizeof(u8aIeeeHeader));
1447       pu8 += sizeof(u8aIeeeHeader);
1448
1449       pu8 += sprintf((char *) u8aSendBuffer, "Packetspammer %02d"
1450           "broadcast packet"
1451           "#%05d -- :-D --%s ----", nRate / 2, nOrdinal++, szHostname);
1452       r = pcap_inject(ppcap, u8aSendBuffer, pu8 - u8aSendBuffer);
1453       if (r != (pu8 - u8aSendBuffer))
1454         {
1455           perror("Trouble injecting packet");
1456           return (1);
1457         }
1458       if (nDelay)
1459       usleep(nDelay);
1460     }
1461
1462 #endif
1463   return (0);
1464 }
1465