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