-some minor code cleanup
[oweals/gnunet.git] / src / transport / gnunet-helper-transport-wlan.c
1 /*
2    This file is part of GNUnet.
3    (C) 2010, 2011, 2012 Christian Grothoff (and other contributing authors)
4    Copyright (c) 2007, 2008, Andy Green <andy@warmcat.com>
5    Copyright (C) 2009 Thomas d'Otreppe
6
7    GNUnet is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published
9    by the Free Software Foundation; either version 3, or (at your
10    option) any later version.
11
12    GNUnet is distributed in the hope that it will be useful, but
13    WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15    General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with GNUnet; see the file COPYING.  If not, write to the
19    Free Software Foundation, Inc., 59 Temple Place - Suite 330,
20    Boston, MA 02111-1307, USA.
21 */
22 /**
23  * @file src/transport/gnunet-helper-transport-wlan.c
24  * @brief mediator between the wlan interface and gnunet; must run as root (SUID will do)
25  *        This code will work under GNU/Linux only.
26  * @author David Brodski
27  * @author Christian Grothoff
28  *
29  * This program will allow receiving and sending traffic from the WLAN
30  * interface.  It will force traffic to be in 'ad-hoc' mode, use the
31  * proper MAC address of the WLAN interface and use a GNUnet-specific
32  * SSID (and a GNUnet-specific SNAP header).  It only takes a single
33  * argument, which is the name of the WLAN interface to use.  The
34  * program detects if the interface is not a WLAN interface and exits
35  * with an error in that case.
36  *
37  * Once initialized, the program will first send a 'struct
38  * GNUNET_TRANSPORT_WLAN_HelperControlMessage' to 'stdout'.  That
39  * message contains the MAC address of the WLAN interface.  It will
40  * then read messages from the WLAN interface and send them together
41  * with performance information as 'struct
42  * GNUNET_TRANSPORT_WLAN_RadiotapReceiveMessage' messages to 'stdout'.
43  * Furthermore, it will read a stream of messages from 'stdin' that
44  * have the format from 'struct
45  * GNUNET_TRANSPORT_WLAN_RadiotapSendMessage'.  Those messages will
46  * then be sent via the WLAN interface; however, the sender MAC
47  * address will be forced to be the correct address from our WLAN
48  * card.  If 'stdin' closes, receiving from the WLAN interface will
49  * continue.  If 'stdout' causes a SIGPIPE, the process dies from the
50  * signal.  Errors cause an error message to be reported to 'stderr',
51  * in most cases the process also exits (with status code '1').  The
52  * program never terminates normally; it is safe to kill the
53  * process with SIGTERM or SIGKILL at any time.
54  *
55  * Since it uses RAW sockets, the binary must be installed SUID or run
56  * as 'root'.  In order to keep the security risk of the resulting
57  * SUID binary minimal, the program ONLY opens the RAW socket with
58  * root privileges, then drops them and only then starts to process
59  * command line arguments.  The code also does not link against any
60  * shared libraries (except libc) and is strictly minimal (except for
61  * checking for errors).  The following list of people have reviewed
62  * this code and considered it safe since the last modification (if
63  * you reviewed it, please have your name added to the list):
64  *
65  * - Christian Grothoff (Apr 3rd 2012)
66  */
67
68 /*-
69  * we use our local copy of ieee80211_radiotap.h
70  *
71  * - since we can't support extensions we don't understand
72  * - since linux does not include it in userspace headers
73  *
74  * Portions of this code were taken from the ieee80211_radiotap.h header,
75  * which is
76  *
77  * Copyright (c) 2003, 2004 David Young.  All rights reserved.
78  *
79  * Redistribution and use in source and binary forms, with or without
80  * modification, are permitted provided that the following conditions
81  * are met:
82  * 1. Redistributions of source code must retain the above copyright
83  *    notice, this list of conditions and the following disclaimer.
84  * 2. Redistributions in binary form must reproduce the above copyright
85  *    notice, this list of conditions and the following disclaimer in the
86  *    documentation and/or other materials provided with the distribution.
87  * 3. The name of David Young may not be used to endorse or promote
88  *    products derived from this software without specific prior
89  *    written permission.
90  *
91  * THIS SOFTWARE IS PROVIDED BY DAVID YOUNG ``AS IS'' AND ANY
92  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
93  * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
94  * PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL DAVID
95  * YOUNG BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
96  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
97  * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
98  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
99  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
100  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
101  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
102  * OF SUCH DAMAGE.
103  */
104
105 /*
106  * Modifications to fit into the linux IEEE 802.11 stack,
107  * Mike Kershaw (dragorn@kismetwireless.net)
108  */
109 /*
110  * parts taken from aircrack-ng, parts changend.
111  */
112 #include "gnunet_config.h"
113 #include <sys/socket.h>
114 #include <sys/ioctl.h>
115 #include <sys/types.h>
116 #include <unistd.h>
117 #include <sys/wait.h>
118 #include <sys/time.h>
119 #include <sys/stat.h>
120 #include <netpacket/packet.h>
121 #include <linux/if_ether.h>
122 #include <linux/if.h>
123 #include <linux/wireless.h>
124 #include <netinet/in.h>
125 #include <linux/if_tun.h>
126 #include <stdio.h>
127 #include <stdlib.h>
128 #include <string.h>
129 #include <stdarg.h>
130 #include <fcntl.h>
131 #include <errno.h>
132 #include <dirent.h>
133 #include <sys/param.h>
134 #include <unistd.h>
135 #include <stdint.h>
136
137 #include "gnunet_protocols.h"
138 #include "plugin_transport_wlan.h"
139
140 /**
141  * Packet format type for the messages we receive from 
142  * the kernel.  This is for Ethernet 10Mbps format (no
143  * performance information included).
144  */
145 #define ARPHRD_ETHER        1 
146
147
148 /**
149  * Packet format type for the messages we receive from 
150  * the kernel.  This is for plain messages (with no
151  * performance information included).
152  */
153 #define ARPHRD_IEEE80211        801
154
155
156 /**
157  * Packet format type for the messages we receive from 
158  * the kernel.  This is for the PRISM format.
159  */
160 #define ARPHRD_IEEE80211_PRISM  802
161
162 /**
163  * Packet format type for the messages we receive from 
164  * the kernel.  This is for messages with a
165  * 'struct Ieee80211RadiotapHeader' (see below).
166  */
167 #define ARPHRD_IEEE80211_FULL   803
168
169
170 /**
171  * Maximum size of a message allowed in either direction
172  * (used for our receive and sent buffers).
173  */
174 #define MAXLINE 4096
175
176
177
178 /* ********* structure of messages of type ARPHRD_IEEE80211_PRISM *********** */
179
180 /**
181  * Device name length in PRISM frames.
182  * (In the kernel, this is "WLAN_DEVNAMELEN_MAX")
183  */
184 #define PRISM_DEVICE_NAME_LENGTH 16
185
186 /**
187  * Monitor Frame (indicator that we have a 'struct PrismHeader').
188  */
189 #define PRISM_MSGCODE_MONITOR 0x0041
190
191 /**
192  * Mac time element.  In micro-seconds.
193  * Drivers appear to use a 64bit counter to hold mactime internal
194  * the then fill the prism header with the lower 32 bits
195  */
196 #define PRISM_DID_MACTIME 0x2041 
197
198 /**
199  * Channel element
200  */
201 #define PRISM_DID_CHANNEL 0x3041 
202
203 /**
204  * Signal element.  Should be the signal strength in dbm, some people
205  * suggest that instead "100 - (strength in dbm)" is used (to make this
206  * a positive integer).
207  */
208 #define PRISM_DID_SIGNAL 0x6041 
209
210 /**
211  * Noise element
212  */
213 #define PRISM_DID_NOISE 0x7041 
214
215 /**
216  * Rate element, in units/multiples of 500Khz
217  */
218 #define PRISM_DID_RATE 0x8041 
219
220
221 /**
222  * Value is set (supplied)
223  */
224 #define PRISM_STATUS_OK 0 
225
226 /**
227  * Value not supplied.
228  */
229 #define PRISM_STATUS_NO_VALUE 1
230
231
232 /**
233  * Values in the 'struct PrismHeader'.  All in host byte order (!).
234  */
235 struct PrismValue
236 {
237   /**
238    * This has a different ID for each parameter, see
239    * PRISM_DID_* constants.
240    */
241   uint32_t did; 
242   
243   /**
244    * See PRISM_STATUS_*-constants.  Note that they are unusual: 0 = set;  1 = not set
245    */
246   uint16_t status; 
247   
248   /**
249    * length of data (which is always a uint32_t, but presumably this can be used
250    * to specify that fewer bytes are used (with values in 'len' from 0-4).  We
251    * ignore this field.
252    */
253   uint16_t len; 
254
255   /**
256    * The data value
257    */
258   uint32_t data; 
259
260 } __attribute__ ((packed));
261
262
263 /**
264  * Prism header format ('struct p80211msg' in Linux).  All in host byte order (!).
265  */
266 struct PrismHeader
267 {
268   /**
269    * We expect this to be a PRISM_MSGCODE_*.
270    */
271   uint32_t msgcode;
272   
273   /**
274    * The length of the entire header.
275    */
276   uint32_t msglen;     
277
278   /**
279    * Name of the device that captured the packet.
280    */
281   char devname[PRISM_DEVICE_NAME_LENGTH];
282
283   /* followed by 'struct PrismValue's.  Documentation suggests that these
284      are typically the hosttime, mactime, channel, rssi, sq, signal, noise,
285      rate, istx and frmlen values, but documentation is sparse.  So we
286      will use the 'did' fields to find out what we actually got. */
287
288 } __attribute__ ((packed));
289
290
291 /* ******  end of structure of messages of type ARPHRD_IEEE80211_PRISM ******* */
292
293 /* ********** structure of messages of type ARPHRD_IEEE80211_FULL *********** */
294
295 /**
296  * Bits in the 'it_present' bitmask from the 'struct
297  * Ieee80211RadiotapHeader'.  For each value, we give the name, data
298  * type, unit and then a description below.  Note that the actual size
299  * of the extension can be bigger as arguments must be padded so that
300  * args of a given length must begin at a boundary of that length.
301  * However, note that compound args are allowed (eg, 2 x uint16_t for
302  * IEEE80211_RADIOTAP_CHANNEL) so total argument length is not a
303  * reliable indicator of alignment requirement.  See also
304  * 'man 9 ieee80211_radiotap'.
305  */
306 enum RadiotapType
307 {
308
309   /**
310    * IEEE80211_RADIOTAP_TSFT              __le64       microseconds
311    *
312    *      Value in microseconds of the MAC's 64-bit 802.11 Time
313    *      Synchronization Function timer when the first bit of the
314    *      MPDU arrived at the MAC. For received frames, only.
315    */
316   IEEE80211_RADIOTAP_TSFT = 0,
317
318   /**
319    * IEEE80211_RADIOTAP_FLAGS             uint8_t           bitmap
320    *
321    *      Properties of transmitted and received frames. See flags
322    *      defined below.
323    */
324   IEEE80211_RADIOTAP_FLAGS = 1,
325
326   /**
327    * IEEE80211_RADIOTAP_RATE              uint8_t           500kb/s
328    *
329    *      Tx/Rx data rate
330    */
331   IEEE80211_RADIOTAP_RATE = 2,
332
333   /**
334    * IEEE80211_RADIOTAP_CHANNEL           2 x __le16   MHz, bitmap
335    *
336    *      Tx/Rx frequency in MHz, followed by flags (see below).
337    */
338   IEEE80211_RADIOTAP_CHANNEL = 3,
339   /**
340    * IEEE80211_RADIOTAP_FHSS              __le16       see below
341    *
342    *      For frequency-hopping radios, the hop set (first byte)
343    *      and pattern (second byte).
344    */
345   IEEE80211_RADIOTAP_FHSS = 4,
346
347   /**
348    * IEEE80211_RADIOTAP_DBM_ANTSIGNAL     s8           decibels from
349    *                                                   one milliwatt (dBm)
350    *
351    *      RF signal power at the antenna, decibel difference from
352    *      one milliwatt.
353    */
354   IEEE80211_RADIOTAP_DBM_ANTSIGNAL = 5,
355
356   /**
357    * IEEE80211_RADIOTAP_DBM_ANTNOISE      s8           decibels from
358    *                                                   one milliwatt (dBm)
359    *
360    *      RF noise power at the antenna, decibel difference from one
361    *      milliwatt.
362    */
363   IEEE80211_RADIOTAP_DBM_ANTNOISE = 6,
364
365   /**
366    * IEEE80211_RADIOTAP_LOCK_QUALITY      __le16       unitless
367    *
368    *      Quality of Barker code lock. Unitless. Monotonically
369    *      nondecreasing with "better" lock strength. Called "Signal
370    *      Quality" in datasheets.  (Is there a standard way to measure
371    *      this?)
372    */
373   IEEE80211_RADIOTAP_LOCK_QUALITY = 7,
374
375   /**
376    * IEEE80211_RADIOTAP_TX_ATTENUATION    __le16       unitless
377    *
378    *      Transmit power expressed as unitless distance from max
379    *      power set at factory calibration.  0 is max power.
380    *      Monotonically nondecreasing with lower power levels.
381    */
382   IEEE80211_RADIOTAP_TX_ATTENUATION = 8,
383
384   /**
385    * IEEE80211_RADIOTAP_DB_TX_ATTENUATION __le16       decibels (dB)
386    *
387    *      Transmit power expressed as decibel distance from max power
388    *      set at factory calibration.  0 is max power.  Monotonically
389    *      nondecreasing with lower power levels.
390    */
391   IEEE80211_RADIOTAP_DB_TX_ATTENUATION = 9,
392
393   /**
394    * IEEE80211_RADIOTAP_DBM_TX_POWER      s8           decibels from
395    *                                                   one milliwatt (dBm)
396    *
397    *      Transmit power expressed as dBm (decibels from a 1 milliwatt
398    *      reference). This is the absolute power level measured at
399    *      the antenna port.
400    */
401   IEEE80211_RADIOTAP_DBM_TX_POWER = 10,
402
403   /** 
404    * IEEE80211_RADIOTAP_ANTENNA           uint8_t           antenna index
405    *
406    *      Unitless indication of the Rx/Tx antenna for this packet.
407    *      The first antenna is antenna 0.
408    */
409   IEEE80211_RADIOTAP_ANTENNA = 11,
410
411   /**
412    * IEEE80211_RADIOTAP_DB_ANTSIGNAL      uint8_t           decibel (dB)
413    *
414    *      RF signal power at the antenna, decibel difference from an
415    *      arbitrary, fixed reference.
416    */
417   IEEE80211_RADIOTAP_DB_ANTSIGNAL = 12,
418
419   /**
420    * IEEE80211_RADIOTAP_DB_ANTNOISE       uint8_t           decibel (dB)
421    *
422    *      RF noise power at the antenna, decibel difference from an
423    *      arbitrary, fixed reference point.
424    */
425   IEEE80211_RADIOTAP_DB_ANTNOISE = 13,
426
427   /**
428    * IEEE80211_RADIOTAP_RX_FLAGS          __le16       bitmap
429    *
430    *     Properties of received frames. See flags defined below.
431    */
432   IEEE80211_RADIOTAP_RX_FLAGS = 14,
433
434   /** 
435    * IEEE80211_RADIOTAP_TX_FLAGS          __le16       bitmap
436    *
437    *     Properties of transmitted frames. See flags defined below.  
438    */
439   IEEE80211_RADIOTAP_TX_FLAGS = 15,
440
441   /**
442    * IEEE80211_RADIOTAP_RTS_RETRIES       uint8_t           data
443    *
444    *     Number of rts retries a transmitted frame used.
445    */
446   IEEE80211_RADIOTAP_RTS_RETRIES = 16,
447
448   /**
449    * IEEE80211_RADIOTAP_DATA_RETRIES      uint8_t           data
450    *
451    *     Number of unicast retries a transmitted frame used.
452    */
453   IEEE80211_RADIOTAP_DATA_RETRIES = 17,
454
455   /**
456    * Extension bit, used to indicate that more bits are needed for
457    * the bitmask.
458    */
459   IEEE80211_RADIOTAP_EXT = 31
460 };
461
462 /**
463  * Bitmask indicating an extension of the bitmask is used. 
464  * (Mask corresponding to IEEE80211_RADIOTAP_EXT).
465  */
466 #define IEEE80211_RADIOTAP_PRESENT_EXTEND_MASK (1 << IEEE80211_RADIOTAP_EXT)
467
468
469
470 /**
471  * Bit in IEEE80211_RADIOTAP_FLAGS (which we might get
472  * as part of a 'struct Ieee80211RadiotapHeader' extension
473  * if the IEEE80211_RADIOTAP_FLAGS bit is set in
474  * 'it_present').  The radiotap flags are an 8-bit field.
475  *
476  * Frame was sent/received during CFP (Contention Free Period)
477  */
478 #define IEEE80211_RADIOTAP_F_CFP        0x01
479
480 /**
481  * Bit in IEEE80211_RADIOTAP_FLAGS (which we might get
482  * as part of a 'struct Ieee80211RadiotapHeader' extension
483  * if the IEEE80211_RADIOTAP_FLAGS bit is set in
484  * 'it_present').  The radiotap flags are an 8-bit field.
485  *
486  * Frame was sent/received with short preamble
487  */
488 #define IEEE80211_RADIOTAP_F_SHORTPRE   0x02  
489
490 /**
491  * Bit in IEEE80211_RADIOTAP_FLAGS (which we might get
492  * as part of a 'struct Ieee80211RadiotapHeader' extension
493  * if the IEEE80211_RADIOTAP_FLAGS bit is set in
494  * 'it_present').  The radiotap flags are an 8-bit field.
495  *
496  * Frame was sent/received with WEP encryption
497  */
498 #define IEEE80211_RADIOTAP_F_WEP        0x04 
499
500 /**
501  * Bit in IEEE80211_RADIOTAP_FLAGS (which we might get
502  * as part of a 'struct Ieee80211RadiotapHeader' extension
503  * if the IEEE80211_RADIOTAP_FLAGS bit is set in
504  * 'it_present').  The radiotap flags are an 8-bit field.
505  *
506  * Frame was sent/received with fragmentation
507  */
508 #define IEEE80211_RADIOTAP_F_FRAG       0x08 
509
510 /**
511  * Bit in IEEE80211_RADIOTAP_FLAGS (which we might get
512  * as part of a 'struct Ieee80211RadiotapHeader' extension
513  * if the IEEE80211_RADIOTAP_FLAGS bit is set in
514  * 'it_present').  The radiotap flags are an 8-bit field.
515  *
516  * Frame includes FCS (CRC at the end that needs to be removeD).
517  */
518 #define IEEE80211_RADIOTAP_F_FCS        0x10    
519
520 /**
521  * Bit in IEEE80211_RADIOTAP_FLAGS (which we might get
522  * as part of a 'struct Ieee80211RadiotapHeader' extension
523  * if the IEEE80211_RADIOTAP_FLAGS bit is set in
524  * 'it_present').  The radiotap flags are an 8-bit field.
525  *
526  * Frame has padding between 802.11 header and payload
527  * (to 32-bit boundary)
528  */
529 #define IEEE80211_RADIOTAP_F_DATAPAD    0x20    
530
531
532 /**
533  * For IEEE80211_RADIOTAP_RX_FLAGS:
534  * frame failed crc check
535  */
536 #define IEEE80211_RADIOTAP_F_RX_BADFCS  0x0001  
537
538 /**
539  * For IEEE80211_RADIOTAP_TX_FLAGS ('txflags' in 'struct RadiotapTransmissionHeader'):
540  * failed due to excessive retries
541  */
542 #define IEEE80211_RADIOTAP_F_TX_FAIL    0x0001  
543
544 /**
545  * For IEEE80211_RADIOTAP_TX_FLAGS ('txflags' in 'struct RadiotapTransmissionHeader'):
546  * used cts 'protection'
547  */
548 #define IEEE80211_RADIOTAP_F_TX_CTS     0x0002  
549
550 /**
551  * For IEEE80211_RADIOTAP_TX_FLAGS ('txflags' in 'struct RadiotapTransmissionHeader'):
552  * used rts/cts handshake 
553  */
554 #define IEEE80211_RADIOTAP_F_TX_RTS     0x0004  
555
556 /**
557  * For IEEE80211_RADIOTAP_TX_FLAGS ('txflags' in 'struct RadiotapTransmissionHeader'):
558  * frame should not be ACKed
559  */
560 #define IEEE80211_RADIOTAP_F_TX_NOACK   0x0008
561
562 /**
563  * For IEEE80211_RADIOTAP_TX_FLAGS ('txflags' in 'struct RadiotapTransmissionHeader'):
564  * sequence number handled by userspace 
565  */
566 #define IEEE80211_RADIOTAP_F_TX_NOSEQ   0x0010
567
568
569 /**
570  * Generic header for radiotap messages (receiving and sending).  A
571  * bit mask (it_present) determines which specific records follow.
572  *
573  * I am trying to describe precisely what the application programmer
574  * should expect in the following, and for that reason I tell the
575  * units and origin of each measurement (where it applies), or else I
576  * use sufficiently weaselly language ("is a monotonically nondecreasing
577  * function of...") that I cannot set false expectations for lawyerly
578  * readers.
579  *
580  * The radio capture header precedes the 802.11 header.
581  * All data in the header is little endian on all platforms.
582  */
583 struct Ieee80211RadiotapHeader
584 {
585   /**
586    * Version 0. Only increases for drastic changes, introduction of
587    * compatible new fields does not count.
588    */
589   uint8_t it_version;
590
591   /**
592    * Padding.  Set to 0.  
593    */
594   uint8_t it_pad;
595
596   /**
597    * length of the whole header in bytes, including it_version,
598    * it_pad, it_len, and data fields.
599    */
600   uint16_t it_len;
601
602   /**
603    * A bitmap telling which fields are present. Set bit 31
604    * (0x80000000) to extend the bitmap by another 32 bits.  Additional
605    * extensions are made by setting bit 31.
606    */
607   uint32_t it_present;
608 };
609
610
611 /**
612  * Format of the header we need to prepend to messages to be sent to the 
613  * Kernel.
614  */
615 struct RadiotapTransmissionHeader
616 {
617
618   /**
619    * First we begin with the 'generic' header we also get when receiving
620    * messages.
621    */
622   struct Ieee80211RadiotapHeader header;
623
624   /**
625    * Transmission rate (we use 0, kernel makes up its mind anyway).
626    */
627   uint8_t rate;
628
629   /**
630    * Padding (we use 0).  There is a requirement to pad args, so that
631    * args of a given length must begin at a boundary of that length.
632    * As our next argument is the 'it_len' with 2 bytes, we need 1 byte
633    * of padding.
634    */
635   uint8_t pad1;
636
637   /**
638    * Transmission flags from on the IEEE80211_RADIOTAP_F_TX_* constant family.
639    */
640   uint16_t txflags;
641
642 };
643
644 /**
645  * The above 'struct RadiotapTransmissionHeader' should have the
646  * following value for 'header.it_present' based on the presence of
647  * the 'rate' and 'txflags' in the overall struct.
648  */
649 #define IEEE80211_RADIOTAP_OUR_TRANSMISSION_HEADER_MASK ((1 << IEEE80211_RADIOTAP_RATE) | (1 << IEEE80211_RADIOTAP_TX_FLAGS))
650
651
652
653 /**
654  * struct Ieee80211RadiotapHeaderIterator - tracks walk through present radiotap arguments
655  * in the radiotap header.  Used when we parse radiotap packets received from the kernel.
656  */
657 struct Ieee80211RadiotapHeaderIterator
658 {
659   /**
660    * pointer to the radiotap header we are walking through
661    */
662   const struct Ieee80211RadiotapHeader *rtheader;
663
664   /**
665    * pointer to current radiotap arg
666    */
667   const uint8_t *this_arg;
668
669   /**
670    * internal next argument pointer
671    */
672   const uint8_t *arg;
673
674   /**
675    * internal pointer to next present uint32_t (if IEEE80211_RADIOTAP_EXT is used).
676    */
677   const uint32_t *next_bitmap;
678
679   /**
680    * length of radiotap header in host byte ordering
681    */
682   size_t max_length;
683
684   /**
685    * internal shifter for current uint32_t bitmap, (it_present in host byte order),
686    * If bit 0 is set, the 'arg_index' argument is present.
687    */
688   uint32_t bitmap_shifter;
689
690   /**
691    * IEEE80211_RADIOTAP_... index of current arg
692    */
693   unsigned int this_arg_index;
694
695   /**
696    * internal next argument index
697    */
698   unsigned int arg_index;
699
700 };
701
702
703 /* ************** end of structure of ARPHRD_IEEE80211_FULL ************** */
704
705 /* ************************** our globals ******************************* */
706
707 /**
708  * struct for storing the information of the hardware.  There is only
709  * one of these.
710  */
711 struct HardwareInfos
712 {
713
714   /**
715    * file descriptor for the raw socket
716    */
717   int fd_raw;
718
719   /**
720    * Which format has the header that we're getting when receiving packets?
721    * Some  ARPHRD_IEEE80211_XXX-value.
722    */
723   int arptype_in;
724
725   /**
726    * Name of the interface, not necessarily 0-terminated (!).
727    */
728   char iface[IFNAMSIZ];
729
730   /**
731    * MAC address of our own WLAN interface.
732    */
733   struct GNUNET_TRANSPORT_WLAN_MacAddress pl_mac;
734 };
735
736
737 /**
738  * IO buffer used for buffering data in transit (to wireless or to stdout).
739  */
740 struct SendBuffer
741 {
742   /**
743    * How many bytes of data are stored in 'buf' for transmission right now?
744    * Data always starts at offset 0 and extends to 'size'.
745    */
746   size_t size;
747
748   /**
749    * How many bytes that were stored in 'buf' did we already write to the
750    * destination?  Always smaller than 'size'.
751    */
752   size_t pos;
753   
754   /**
755    * Buffered data; twice the maximum allowed message size as we add some
756    * headers.
757    */
758   char buf[MAXLINE * 2];
759 };
760
761
762 /**
763  * Buffer for data read from stdin to be transmitted to the wirless card.
764  */
765 static struct SendBuffer write_pout;
766
767 /**
768  * Buffer for data read from the wireless card to be transmitted to stdout.
769  */
770 static struct SendBuffer write_std;
771
772
773
774 /* *********** specialized version of server_mst.c begins here ********** */
775
776 /**
777  * To what multiple do we align messages?  8 byte should suffice for everyone
778  * for now.
779  */
780 #define ALIGN_FACTOR 8
781
782 /**
783  * Smallest supported message.
784  */
785 #define MIN_BUFFER_SIZE sizeof (struct GNUNET_MessageHeader)
786
787
788 /**
789  * Functions with this signature are called whenever a
790  * complete message is received by the tokenizer.
791  *
792  * @param cls closure
793  * @param message the actual message
794  */
795 typedef void (*MessageTokenizerCallback) (void *cls, 
796                                           const struct
797                                           GNUNET_MessageHeader *
798                                           message);
799
800 /**
801  * Handle to a message stream tokenizer.
802  */
803 struct MessageStreamTokenizer
804 {
805
806   /**
807    * Function to call on completed messages.
808    */
809   MessageTokenizerCallback cb;
810
811   /**
812    * Closure for cb.
813    */
814   void *cb_cls;
815
816   /**
817    * Size of the buffer (starting at 'hdr').
818    */
819   size_t curr_buf;
820
821   /**
822    * How many bytes in buffer have we already processed?
823    */
824   size_t off;
825
826   /**
827    * How many bytes in buffer are valid right now?
828    */
829   size_t pos;
830
831   /**
832    * Beginning of the buffer.  Typed like this to force alignment.
833    */
834   struct GNUNET_MessageHeader *hdr;
835
836 };
837
838
839 /**
840  * Create a message stream tokenizer.
841  *
842  * @param cb function to call on completed messages
843  * @param cb_cls closure for cb
844  * @return handle to tokenizer
845  */
846 static struct MessageStreamTokenizer *
847 mst_create (MessageTokenizerCallback cb,
848             void *cb_cls)
849 {
850   struct MessageStreamTokenizer *ret;
851
852   ret = malloc (sizeof (struct MessageStreamTokenizer));
853   if (NULL == ret)
854   {
855     fprintf (stderr, "Failed to allocate buffer for tokenizer\n");
856     exit (1);
857   }
858   ret->hdr = malloc (MIN_BUFFER_SIZE);
859   if (NULL == ret->hdr)
860   {
861     fprintf (stderr, "Failed to allocate buffer for alignment\n");
862     exit (1);
863   }
864   ret->curr_buf = MIN_BUFFER_SIZE;
865   ret->cb = cb;
866   ret->cb_cls = cb_cls;
867   return ret;
868 }
869
870
871 /**
872  * Add incoming data to the receive buffer and call the
873  * callback for all complete messages.
874  *
875  * @param mst tokenizer to use
876  * @param buf input data to add
877  * @param size number of bytes in buf
878  * @return GNUNET_OK if we are done processing (need more data)
879  *         GNUNET_SYSERR if the data stream is corrupt
880  */
881 static int
882 mst_receive (struct MessageStreamTokenizer *mst,
883              const char *buf, size_t size)
884 {
885   const struct GNUNET_MessageHeader *hdr;
886   size_t delta;
887   uint16_t want;
888   char *ibuf;
889   int need_align;
890   unsigned long offset;
891   int ret;
892
893   ret = GNUNET_OK;
894   ibuf = (char *) mst->hdr;
895   while (mst->pos > 0)
896   {
897 do_align:
898     if ((mst->curr_buf - mst->off < sizeof (struct GNUNET_MessageHeader)) ||
899         (0 != (mst->off % ALIGN_FACTOR)))
900     {
901       /* need to align or need more space */
902       mst->pos -= mst->off;
903       memmove (ibuf, &ibuf[mst->off], mst->pos);
904       mst->off = 0;
905     }
906     if (mst->pos - mst->off < sizeof (struct GNUNET_MessageHeader))
907     {
908       delta =
909           GNUNET_MIN (sizeof (struct GNUNET_MessageHeader) -
910                       (mst->pos - mst->off), size);
911       memcpy (&ibuf[mst->pos], buf, delta);
912       mst->pos += delta;
913       buf += delta;
914       size -= delta;
915     }
916     if (mst->pos - mst->off < sizeof (struct GNUNET_MessageHeader))
917     {
918       return GNUNET_OK;
919     }
920     hdr = (const struct GNUNET_MessageHeader *) &ibuf[mst->off];
921     want = ntohs (hdr->size);
922     if (want < sizeof (struct GNUNET_MessageHeader))
923     {
924       fprintf (stderr,
925                "Received invalid message from stdin\n");
926       exit (1);
927     }
928     if (mst->curr_buf - mst->off < want)
929     {
930       /* need more space */
931       mst->pos -= mst->off;
932       memmove (ibuf, &ibuf[mst->off], mst->pos);
933       mst->off = 0;
934     }
935     if (want > mst->curr_buf)
936     {
937       mst->hdr = realloc (mst->hdr, want);
938       if (NULL == mst->hdr)
939       {
940         fprintf (stderr, "Failed to allocate buffer for alignment\n");
941         exit (1);
942       }
943       ibuf = (char *) mst->hdr;
944       mst->curr_buf = want;
945     }
946     hdr = (const struct GNUNET_MessageHeader *) &ibuf[mst->off];
947     if (mst->pos - mst->off < want)
948     {
949       delta = GNUNET_MIN (want - (mst->pos - mst->off), size);
950       memcpy (&ibuf[mst->pos], buf, delta);
951       mst->pos += delta;
952       buf += delta;
953       size -= delta;
954     }
955     if (mst->pos - mst->off < want)
956     {
957       return GNUNET_OK;
958     }
959     mst->cb (mst->cb_cls, hdr);
960     mst->off += want;
961     if (mst->off == mst->pos)
962     {
963       /* reset to beginning of buffer, it's free right now! */
964       mst->off = 0;
965       mst->pos = 0;
966     }
967   }
968   while (size > 0)
969   {
970     if (size < sizeof (struct GNUNET_MessageHeader))
971       break;
972     offset = (unsigned long) buf;
973     need_align = (0 != offset % ALIGN_FACTOR) ? GNUNET_YES : GNUNET_NO;
974     if (GNUNET_NO == need_align)
975     {
976       /* can try to do zero-copy and process directly from original buffer */
977       hdr = (const struct GNUNET_MessageHeader *) buf;
978       want = ntohs (hdr->size);
979       if (want < sizeof (struct GNUNET_MessageHeader))
980       {
981         fprintf (stderr,
982                  "Received invalid message from stdin\n");
983         exit (1);
984       }
985       if (size < want)
986         break;                  /* or not, buffer incomplete, so copy to private buffer... */
987       mst->cb (mst->cb_cls, hdr);
988       buf += want;
989       size -= want;
990     }
991     else
992     {
993       /* need to copy to private buffer to align;
994        * yes, we go a bit more spagetti than usual here */
995       goto do_align;
996     }
997   }
998   if (size > 0)
999   {
1000     if (size + mst->pos > mst->curr_buf)
1001     {
1002       mst->hdr = realloc (mst->hdr, size + mst->pos);
1003       if (NULL == mst->hdr)
1004       {
1005         fprintf (stderr, "Failed to allocate buffer for alignment\n");
1006         exit (1);
1007       }
1008       ibuf = (char *) mst->hdr;
1009       mst->curr_buf = size + mst->pos;
1010     }
1011     if (mst->pos + size > mst->curr_buf)
1012     {
1013       fprintf (stderr,
1014                "Assertion failed\n");
1015       exit (1);
1016     }
1017     memcpy (&ibuf[mst->pos], buf, size);
1018     mst->pos += size;
1019   }
1020   return ret;
1021 }
1022
1023
1024 /**
1025  * Destroys a tokenizer.
1026  *
1027  * @param mst tokenizer to destroy
1028  */
1029 static void
1030 mst_destroy (struct MessageStreamTokenizer *mst)
1031 {
1032   free (mst->hdr);
1033   free (mst);
1034 }
1035
1036 /* *****************  end of server_mst.c clone ***************** **/
1037
1038
1039 /* ************** code for handling of ARPHRD_IEEE80211_FULL ************** */
1040
1041 /**
1042  * Radiotap header iteration
1043  *
1044  * call __ieee80211_radiotap_iterator_init() to init a semi-opaque iterator
1045  * struct Ieee80211RadiotapHeaderIterator (no need to init the struct beforehand)
1046  * then loop calling __ieee80211_radiotap_iterator_next()... it returns -1
1047  * if there are no more args in the header, or the next argument type index
1048  * that is present.  The iterator's this_arg member points to the start of the
1049  * argument associated with the current argument index that is present,
1050  * which can be found in the iterator's this_arg_index member.  This arg
1051  * index corresponds to the IEEE80211_RADIOTAP_... defines.
1052  *
1053  * @param iterator iterator to initialize
1054  * @param radiotap_header message to parse
1055  * @param max_length number of valid bytes in radiotap_header
1056  * @return 0 on success, -1 on error
1057  */
1058 static int
1059 ieee80211_radiotap_iterator_init (struct Ieee80211RadiotapHeaderIterator *iterator,
1060                                   const struct Ieee80211RadiotapHeader *radiotap_header, 
1061                                   size_t max_length)
1062 {
1063   if ( (iterator == NULL) ||
1064        (radiotap_header == NULL) )
1065     return -1;
1066
1067   /* Linux only supports version 0 radiotap format */
1068   if (0 != radiotap_header->it_version)
1069     return -1;
1070
1071   /* sanity check for allowed length and radiotap length field */
1072   if ( (max_length < sizeof (struct Ieee80211RadiotapHeader)) ||
1073        (max_length < (GNUNET_le16toh (radiotap_header->it_len))) )
1074     return -1;
1075
1076   memset (iterator, 0, sizeof (struct Ieee80211RadiotapHeaderIterator));
1077   iterator->rtheader = radiotap_header;
1078   iterator->max_length = GNUNET_le16toh (radiotap_header->it_len);
1079   iterator->bitmap_shifter = GNUNET_le32toh (radiotap_header->it_present);
1080   iterator->arg = ((uint8_t *) radiotap_header) + sizeof (struct Ieee80211RadiotapHeader);
1081
1082   /* find payload start allowing for extended bitmap(s) */
1083   if (0 != (iterator->bitmap_shifter & IEEE80211_RADIOTAP_PRESENT_EXTEND_MASK))
1084   {
1085     while (GNUNET_le32toh (*((uint32_t *) iterator->arg)) & IEEE80211_RADIOTAP_PRESENT_EXTEND_MASK)
1086     {
1087       iterator->arg += sizeof (uint32_t);
1088       /*
1089        * check for insanity where the present bitmaps
1090        * keep claiming to extend up to or even beyond the
1091        * stated radiotap header length
1092        */
1093       if (iterator->arg - ((uint8_t*) iterator->rtheader) > iterator->max_length)
1094         return -1;
1095     }
1096     iterator->arg += sizeof (uint32_t);
1097     /*
1098      * no need to check again for blowing past stated radiotap
1099      * header length, becuase ieee80211_radiotap_iterator_next
1100      * checks it before it is dereferenced
1101      */
1102   }
1103   /* we are all initialized happily */
1104   return 0;
1105 }
1106
1107
1108 /**
1109  * Returns the next radiotap parser iterator arg.
1110  *
1111  * This function returns the next radiotap arg index (IEEE80211_RADIOTAP_...)
1112  * and sets iterator->this_arg to point to the payload for the arg.  It takes
1113  * care of alignment handling and extended present fields.  interator->this_arg
1114  * can be changed by the caller.  The args pointed to are in little-endian
1115  * format.
1116  *
1117  * @param iterator: radiotap_iterator to move to next arg (if any)
1118  * @return next present arg index on success or -1 if no more or error
1119  */
1120 static int
1121 ieee80211_radiotap_iterator_next (struct Ieee80211RadiotapHeaderIterator *iterator)
1122 {
1123   /*
1124    * small length lookup table for all radiotap types we heard of
1125    * starting from b0 in the bitmap, so we can walk the payload
1126    * area of the radiotap header
1127    *
1128    * There is a requirement to pad args, so that args
1129    * of a given length must begin at a boundary of that length
1130    * -- but note that compound args are allowed (eg, 2 x uint16_t
1131    * for IEEE80211_RADIOTAP_CHANNEL) so total arg length is not
1132    * a reliable indicator of alignment requirement.
1133    *
1134    * upper nybble: content alignment for arg
1135    * lower nybble: content length for arg
1136    */
1137
1138   static const uint8_t rt_sizes[] = {
1139     [IEEE80211_RADIOTAP_TSFT] = 0x88,
1140     [IEEE80211_RADIOTAP_FLAGS] = 0x11,
1141     [IEEE80211_RADIOTAP_RATE] = 0x11,
1142     [IEEE80211_RADIOTAP_CHANNEL] = 0x24,
1143     [IEEE80211_RADIOTAP_FHSS] = 0x22,
1144     [IEEE80211_RADIOTAP_DBM_ANTSIGNAL] = 0x11,
1145     [IEEE80211_RADIOTAP_DBM_ANTNOISE] = 0x11,
1146     [IEEE80211_RADIOTAP_LOCK_QUALITY] = 0x22,
1147     [IEEE80211_RADIOTAP_TX_ATTENUATION] = 0x22,
1148     [IEEE80211_RADIOTAP_DB_TX_ATTENUATION] = 0x22,
1149     [IEEE80211_RADIOTAP_DBM_TX_POWER] = 0x11,
1150     [IEEE80211_RADIOTAP_ANTENNA] = 0x11,
1151     [IEEE80211_RADIOTAP_DB_ANTSIGNAL] = 0x11,
1152     [IEEE80211_RADIOTAP_DB_ANTNOISE] = 0x11,
1153     [IEEE80211_RADIOTAP_TX_FLAGS] = 0x22,
1154     [IEEE80211_RADIOTAP_RX_FLAGS] = 0x22,
1155     [IEEE80211_RADIOTAP_RTS_RETRIES] = 0x11,
1156     [IEEE80211_RADIOTAP_DATA_RETRIES] = 0x11
1157         /*
1158          * add more here as they are defined in
1159          * include/net/ieee80211_radiotap.h
1160          */
1161   };
1162
1163   /*
1164    * for every radiotap entry we can at
1165    * least skip (by knowing the length)...
1166    */
1167   while (iterator->arg_index < sizeof (rt_sizes))
1168   {
1169     int hit = (0 != (iterator->bitmap_shifter & 1));
1170
1171     if (hit)
1172     {
1173       unsigned int wanted_alignment;
1174       unsigned int unalignment;
1175       /*
1176        * arg is present, account for alignment padding
1177        *  8-bit args can be at any alignment
1178        * 16-bit args must start on 16-bit boundary
1179        * 32-bit args must start on 32-bit boundary
1180        * 64-bit args must start on 64-bit boundary
1181        *
1182        * note that total arg size can differ from alignment of
1183        * elements inside arg, so we use upper nybble of length table
1184        * to base alignment on.  First, 'wanted_alignment' is set to be
1185        * 1 for 8-bit, 2 for 16-bit, 4 for 32-bit and 8 for 64-bit
1186        * arguments.  Then, we calculate the 'unalignment' (how many
1187        * bytes we are over by taking the difference of 'arg' and the
1188        * overall starting point modulo the desired alignment.  As
1189        * desired alignments are powers of two, we can do modulo with
1190        * binary "&" (and also avoid the possibility of a division by
1191        * zero if the 'rt_sizes' table contains bogus entries).
1192        *
1193        * also note: these alignments are relative to the start of the
1194        * radiotap header.  There is no guarantee that the radiotap
1195        * header itself is aligned on any kind of boundary, thus we
1196        * need to really look at the delta here.
1197        */
1198       wanted_alignment = rt_sizes[iterator->arg_index] >> 4;
1199       unalignment = (((void *) iterator->arg) - ((void *) iterator->rtheader)) & (wanted_alignment - 1);
1200       if (0 != unalignment)
1201       {
1202         /* need padding (by 'wanted_alignment - unalignment') */
1203         iterator->arg_index += wanted_alignment - unalignment;
1204       }
1205       
1206       /*
1207        * this is what we will return to user, but we need to
1208        * move on first so next call has something fresh to test
1209        */     
1210       iterator->this_arg_index = iterator->arg_index;
1211       iterator->this_arg = iterator->arg;
1212
1213       /* internally move on the size of this arg (using lower nybble from
1214          the table) */ 
1215       iterator->arg += rt_sizes[iterator->arg_index] & 0x0f;
1216       
1217       /*
1218        * check for insanity where we are given a bitmap that
1219        * claims to have more arg content than the length of the
1220        * radiotap section.  We will normally end up equalling this
1221        * max_length on the last arg, never exceeding it.
1222        */      
1223       if ((((void *) iterator->arg) - ((void *) iterator->rtheader)) > iterator->max_length)
1224         return -1;      
1225     }
1226
1227     /* Now, move on to next bit / next entry */
1228     iterator->arg_index++;
1229
1230     if (0 == (iterator->arg_index % 32))
1231     {
1232       /* completed current uint32_t bitmap */
1233       if (0 != (iterator->bitmap_shifter & 1))
1234       {
1235         /* bit 31 was set, there is more; move to next uint32_t bitmap */
1236         iterator->bitmap_shifter = GNUNET_le32toh (*iterator->next_bitmap);
1237         iterator->next_bitmap++;
1238       }
1239       else
1240       {
1241         /* no more bitmaps: end (by setting arg_index to high, unsupported value) */
1242         iterator->arg_index = sizeof (rt_sizes);
1243       }
1244     }
1245     else
1246     {                           
1247       /* just try the next bit (while loop will move on) */
1248       iterator->bitmap_shifter >>= 1;
1249     }
1250
1251     /* if we found a valid arg earlier, return it now */
1252     if (hit)
1253       return iterator->this_arg_index;
1254   }
1255
1256   /* we don't know how to handle any more args (or there are no more),
1257      so we're done (this is not an error) */
1258   return -1;
1259 }
1260
1261
1262 /**
1263  * Calculate crc32, the start of the calculation
1264  *
1265  * @param buf buffer to calc the crc
1266  * @param len len of the buffer
1267  * @return crc sum
1268  */
1269 static unsigned long
1270 calc_crc_osdep (const unsigned char *buf, size_t len)
1271 {
1272   static const unsigned long int crc_tbl_osdep[256] = {
1273     0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419, 0x706AF48F,
1274     0xE963A535, 0x9E6495A3,
1275     0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988, 0x09B64C2B, 0x7EB17CBD,
1276     0xE7B82D07, 0x90BF1D91,
1277     0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE, 0x1ADAD47D, 0x6DDDE4EB,
1278     0xF4D4B551, 0x83D385C7,
1279     0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, 0x14015C4F, 0x63066CD9,
1280     0xFA0F3D63, 0x8D080DF5,
1281     0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172, 0x3C03E4D1, 0x4B04D447,
1282     0xD20D85FD, 0xA50AB56B,
1283     0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940, 0x32D86CE3, 0x45DF5C75,
1284     0xDCD60DCF, 0xABD13D59,
1285     0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116, 0x21B4F4B5, 0x56B3C423,
1286     0xCFBA9599, 0xB8BDA50F,
1287     0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924, 0x2F6F7C87, 0x58684C11,
1288     0xC1611DAB, 0xB6662D3D,
1289     0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A, 0x71B18589, 0x06B6B51F,
1290     0x9FBFE4A5, 0xE8B8D433,
1291     0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818, 0x7F6A0DBB, 0x086D3D2D,
1292     0x91646C97, 0xE6635C01,
1293     0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E, 0x6C0695ED, 0x1B01A57B,
1294     0x8208F4C1, 0xF50FC457,
1295     0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C, 0x62DD1DDF, 0x15DA2D49,
1296     0x8CD37CF3, 0xFBD44C65,
1297     0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2, 0x4ADFA541, 0x3DD895D7,
1298     0xA4D1C46D, 0xD3D6F4FB,
1299     0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0, 0x44042D73, 0x33031DE5,
1300     0xAA0A4C5F, 0xDD0D7CC9,
1301     0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086, 0x5768B525, 0x206F85B3,
1302     0xB966D409, 0xCE61E49F,
1303     0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 0x59B33D17, 0x2EB40D81,
1304     0xB7BD5C3B, 0xC0BA6CAD,
1305     0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A, 0xEAD54739, 0x9DD277AF,
1306     0x04DB2615, 0x73DC1683,
1307     0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8, 0xE40ECF0B, 0x9309FF9D,
1308     0x0A00AE27, 0x7D079EB1,
1309     0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE, 0xF762575D, 0x806567CB,
1310     0x196C3671, 0x6E6B06E7,
1311     0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC, 0xF9B9DF6F, 0x8EBEEFF9,
1312     0x17B7BE43, 0x60B08ED5,
1313     0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252, 0xD1BB67F1, 0xA6BC5767,
1314     0x3FB506DD, 0x48B2364B,
1315     0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60, 0xDF60EFC3, 0xA867DF55,
1316     0x316E8EEF, 0x4669BE79,
1317     0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236, 0xCC0C7795, 0xBB0B4703,
1318     0x220216B9, 0x5505262F,
1319     0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, 0xC2D7FFA7, 0xB5D0CF31,
1320     0x2CD99E8B, 0x5BDEAE1D,
1321     0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A, 0x9C0906A9, 0xEB0E363F,
1322     0x72076785, 0x05005713,
1323     0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38, 0x92D28E9B, 0xE5D5BE0D,
1324     0x7CDCEFB7, 0x0BDBDF21,
1325     0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E, 0x81BE16CD, 0xF6B9265B,
1326     0x6FB077E1, 0x18B74777,
1327     0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C, 0x8F659EFF, 0xF862AE69,
1328     0x616BFFD3, 0x166CCF45,
1329     0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2, 0xA7672661, 0xD06016F7,
1330     0x4969474D, 0x3E6E77DB,
1331     0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0, 0xA9BCAE53, 0xDEBB9EC5,
1332     0x47B2CF7F, 0x30B5FFE9,
1333     0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, 0xBAD03605, 0xCDD70693,
1334     0x54DE5729, 0x23D967BF,
1335     0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94, 0xB40BBE37, 0xC30C8EA1,
1336     0x5A05DF1B, 0x2D02EF8D
1337   };
1338
1339   unsigned long crc = 0xFFFFFFFF;
1340
1341   for (; len > 0; len--, buf++)
1342     crc = crc_tbl_osdep[(crc ^ *buf) & 0xFF] ^ (crc >> 8);
1343   return (~crc);
1344 }
1345
1346
1347 /**
1348  * Calculate and check crc of the wlan packet
1349  *
1350  * @param buf buffer of the packet, with len + 4 bytes of data,
1351  *            the last 4 bytes being the checksum
1352  * @param len length of the payload in data
1353  * @return 0 on success (checksum matches), 1 on error
1354  */
1355 static int
1356 check_crc_buf_osdep (const unsigned char *buf, size_t len)
1357 {
1358   unsigned long crc;
1359
1360   crc = calc_crc_osdep (buf, len);
1361   buf += len;
1362   if (((crc) & 0xFF) == buf[0] && ((crc >> 8) & 0xFF) == buf[1] &&
1363       ((crc >> 16) & 0xFF) == buf[2] && ((crc >> 24) & 0xFF) == buf[3])
1364     return 0;
1365   return 1;     
1366 }
1367
1368
1369 /* ************end of code for handling of ARPHRD_IEEE80211_FULL ************** */
1370
1371
1372 /* ************beginning of code for reading packets from kernel ************** */
1373
1374 /**
1375  * Return the channel from the frequency (in Mhz)
1376  *
1377  * @param frequency of the channel
1378  * @return number of the channel
1379  */
1380 static int
1381 get_channel_from_frequency (int32_t frequency)
1382 {
1383   if (frequency >= 2412 && frequency <= 2472)
1384     return (frequency - 2407) / 5;
1385   if (frequency == 2484)
1386     return 14;
1387   if (frequency >= 5000 && frequency <= 6100)
1388     return (frequency - 5000) / 5;
1389   return -1;
1390 }
1391
1392
1393 /**
1394  * Get the channel used by our WLAN interface.
1395  *
1396  * @param dev pointer to the dev struct of the card
1397  * @return channel number, -1 on error
1398  */
1399 static int
1400 linux_get_channel (const struct HardwareInfos *dev)
1401 {
1402   struct iwreq wrq;
1403   int32_t frequency;
1404
1405   memset (&wrq, 0, sizeof (struct iwreq));
1406   strncpy (wrq.ifr_name, dev->iface, IFNAMSIZ);
1407   if (0 > ioctl (dev->fd_raw, SIOCGIWFREQ, &wrq))
1408     return -1;
1409   frequency = wrq.u.freq.m; /* 'iw_freq' defines 'm' as '__s32', so we keep it signed */
1410   if (100000000 < frequency)
1411     frequency /= 100000;
1412   else if (1000000 < frequency)
1413     frequency /= 1000;
1414   if (1000 < frequency)
1415     return get_channel_from_frequency (frequency);
1416   return frequency;
1417 }
1418
1419
1420 /**
1421  * Read from the raw socket (the wlan card), parse the packet and
1422  * put the result into the buffer for transmission to 'stdout'.
1423  *
1424  * @param dev pointer to the struct of the wlan card
1425  * @param buf buffer to read to; first bytes will be the 'struct GNUNET_TRANSPORT_WLAN_Ieee80211Frame',
1426  *            followed by the actual payload
1427  * @param buf_size size of the buffer
1428  * @param ri where to write radiotap_rx info
1429  * @return number of bytes written to 'buf'
1430  */
1431 static ssize_t
1432 linux_read (struct HardwareInfos *dev, 
1433             unsigned char *buf, size_t buf_size,
1434             struct GNUNET_TRANSPORT_WLAN_RadiotapReceiveMessage *ri)
1435 {
1436   unsigned char tmpbuf[buf_size];
1437   ssize_t caplen;
1438   size_t n;
1439   int got_signal = 0;
1440   int got_noise = 0;
1441   int got_channel = 0;
1442   int fcs_removed = 0;
1443
1444   caplen = read (dev->fd_raw, tmpbuf, buf_size);
1445   if (0 > caplen)
1446   {
1447     if (EAGAIN == errno)
1448       return 0;
1449     fprintf (stderr, "Failed to read from RAW socket: %s\n", strerror (errno));
1450     return -1;
1451   }
1452
1453   memset (ri, 0, sizeof (*ri)); 
1454   switch (dev->arptype_in)
1455   {
1456   case ARPHRD_IEEE80211_PRISM:
1457     {
1458       const struct PrismHeader *ph;
1459
1460       ph = (const struct PrismHeader*) tmpbuf;
1461       n = ph->msglen;
1462       if ( (n < 8) || (n >= caplen) )
1463         return 0; /* invalid format */
1464       if ( (PRISM_MSGCODE_MONITOR == ph->msgcode) &&
1465            (n >= sizeof (struct PrismHeader)) )
1466       {
1467         const char *pos;
1468         size_t left;
1469         struct PrismValue pv;
1470         
1471         left = n - sizeof (struct PrismHeader);
1472         pos = (const char *) &ph[1];
1473         while (left > sizeof (struct PrismValue))
1474         {
1475           left -= sizeof (struct PrismValue);
1476           memcpy (&pv, pos, sizeof (struct PrismValue));
1477           pos += sizeof (struct PrismValue);
1478
1479           switch (pv.did)
1480           {
1481           case PRISM_DID_NOISE:
1482             if (PRISM_STATUS_OK == pv.status)
1483             {
1484               ri->ri_noise = pv.data;
1485               got_noise = 1;
1486             }
1487             break;
1488           case PRISM_DID_RATE:
1489             if (PRISM_STATUS_OK == pv.status)
1490               ri->ri_rate = pv.data * 500000;
1491             break;
1492           case PRISM_DID_CHANNEL:
1493             if (PRISM_STATUS_OK == pv.status)
1494             {
1495               ri->ri_channel = pv.data;
1496               got_channel = 1;
1497             }
1498             break;
1499           case PRISM_DID_MACTIME:
1500             if (PRISM_STATUS_OK == pv.status)
1501               ri->ri_mactime = pv.data;
1502             break;
1503           case PRISM_DID_SIGNAL:
1504             if (PRISM_STATUS_OK == pv.status)
1505             {
1506               ri->ri_power = pv.data;
1507               got_signal = 1;
1508             }
1509             break;
1510           }
1511         }
1512       } 
1513       if ( (n < 8) || (n >= caplen) )
1514         return 0; /* invalid format */
1515     }
1516     break;
1517   case ARPHRD_IEEE80211_FULL:
1518     {
1519       struct Ieee80211RadiotapHeaderIterator iterator;
1520       struct Ieee80211RadiotapHeader *rthdr;
1521
1522       memset (&iterator, 0, sizeof (iterator));
1523       rthdr = (struct Ieee80211RadiotapHeader *) tmpbuf;
1524       n = GNUNET_le16toh (rthdr->it_len);
1525       if ( (n < sizeof (struct Ieee80211RadiotapHeader)) || (n >= caplen))
1526         return 0; /* invalid 'it_len' */
1527       if (0 != ieee80211_radiotap_iterator_init (&iterator, rthdr, caplen))
1528         return 0;
1529       /* go through the radiotap arguments we have been given by the driver */
1530       while (0 <= ieee80211_radiotap_iterator_next (&iterator))
1531       {
1532         switch (iterator.this_arg_index)
1533         {
1534         case IEEE80211_RADIOTAP_TSFT:
1535           ri->ri_mactime = GNUNET_le64toh (*((uint64_t *) iterator.this_arg));
1536           break;
1537         case IEEE80211_RADIOTAP_DBM_ANTSIGNAL:
1538           if (!got_signal)
1539           {
1540             ri->ri_power = * ((int8_t*) iterator.this_arg);
1541             got_signal = 1;       
1542           }
1543           break;
1544         case IEEE80211_RADIOTAP_DB_ANTSIGNAL:
1545           if (!got_signal)
1546           {
1547             ri->ri_power = * ((int8_t*) iterator.this_arg);
1548             got_signal = 1;
1549           }
1550           break;
1551         case IEEE80211_RADIOTAP_DBM_ANTNOISE:
1552           if (!got_noise)
1553           {
1554             ri->ri_noise = * ((int8_t*) iterator.this_arg);
1555             got_noise = 1;
1556           }
1557           break;
1558         case IEEE80211_RADIOTAP_DB_ANTNOISE:
1559           if (!got_noise)
1560           {
1561             ri->ri_noise = * ((int8_t*) iterator.this_arg);
1562             got_noise = 1;
1563           }
1564           break;
1565         case IEEE80211_RADIOTAP_ANTENNA:
1566           ri->ri_antenna = *iterator.this_arg;
1567           break;
1568         case IEEE80211_RADIOTAP_CHANNEL:
1569           ri->ri_channel = *iterator.this_arg;
1570           got_channel = 1;
1571           break;
1572         case IEEE80211_RADIOTAP_RATE:
1573           ri->ri_rate = (*iterator.this_arg) * 500000;
1574           break;
1575         case IEEE80211_RADIOTAP_FLAGS:
1576           {
1577             uint8_t flags = *iterator.this_arg;
1578             /* is the CRC visible at the end? if so, remove */
1579             if (0 != (flags & IEEE80211_RADIOTAP_F_FCS))
1580             {
1581               fcs_removed = 1;
1582               caplen -= sizeof (uint32_t);
1583             }
1584             break;
1585           }
1586         case IEEE80211_RADIOTAP_RX_FLAGS:
1587           {
1588             uint16_t flags = ntohs (* ((uint16_t *) iterator.this_arg));
1589             if (0 != (flags & IEEE80211_RADIOTAP_F_RX_BADFCS))
1590               return 0;
1591           }
1592           break;
1593         } /* end of 'switch' */
1594       } /* end of the 'while' loop */
1595     }       
1596     break;
1597   case ARPHRD_IEEE80211:
1598     n = 0; /* no header */
1599     break;
1600   case ARPHRD_ETHER:
1601     {
1602       if (sizeof (struct GNUNET_TRANSPORT_WLAN_Ieee8023Frame) > caplen)
1603         return 0; /* invalid */
1604       memcpy (&buf[sizeof (struct GNUNET_TRANSPORT_WLAN_Ieee80211Frame)],
1605               tmpbuf + sizeof (struct GNUNET_TRANSPORT_WLAN_Ieee8023Frame),
1606               caplen - sizeof (struct GNUNET_TRANSPORT_WLAN_Ieee8023Frame) - 4 /* 4 byte FCS */);
1607       return caplen - sizeof (struct GNUNET_TRANSPORT_WLAN_Ieee8023Frame) - 4;
1608     }       
1609   default:
1610     errno = ENOTSUP; /* unsupported format */
1611     return -1;
1612   }
1613   caplen -= n;
1614   if (! got_channel)
1615     ri->ri_channel = linux_get_channel (dev);
1616
1617   /* detect CRC32 at the end, even if the flag wasn't set and remove it */
1618   if ( (0 == fcs_removed) && 
1619        (0 == check_crc_buf_osdep (tmpbuf + n, caplen - sizeof (uint32_t))) )  
1620   {
1621     /* NOTE: this heuristic can of course fail if there happens to
1622        be a matching checksum at the end. Would be good to have
1623        some data to see how often this heuristic actually works. */
1624     caplen -= sizeof (uint32_t);
1625   }
1626   /* copy payload to target buffer */
1627   memcpy (buf, tmpbuf + n, caplen);
1628   return caplen;
1629 }
1630
1631
1632 /* ************end of code for reading packets from kernel ************** */
1633
1634 /* ************other helper functions for main start here ************** */
1635
1636
1637 /**
1638  * Open the wireless network interface for reading/writing.
1639  *
1640  * @param dev pointer to the device struct
1641  * @return 0 on success
1642  */
1643 static int
1644 open_device_raw (struct HardwareInfos *dev)
1645 {
1646   struct ifreq ifr;
1647   struct iwreq wrq;
1648   struct packet_mreq mr;
1649   struct sockaddr_ll sll;
1650
1651   /* find the interface index */
1652   memset (&ifr, 0, sizeof (ifr));
1653   strncpy (ifr.ifr_name, dev->iface, IFNAMSIZ);
1654   if (-1 == ioctl (dev->fd_raw, SIOCGIFINDEX, &ifr))
1655   {
1656     fprintf (stderr, "ioctl(SIOCGIFINDEX) on interface `%.*s' failed: %s\n",
1657              IFNAMSIZ, dev->iface, strerror (errno));
1658     return 1;
1659   }
1660
1661   /* lookup the hardware type */
1662   memset (&sll, 0, sizeof (sll));
1663   sll.sll_family = AF_PACKET;
1664   sll.sll_ifindex = ifr.ifr_ifindex;
1665   sll.sll_protocol = htons (ETH_P_ALL);
1666   if (-1 == ioctl (dev->fd_raw, SIOCGIFHWADDR, &ifr))
1667   {
1668     fprintf (stderr, "ioctl(SIOCGIFHWADDR) on interface `%.*s' failed: %s\n",
1669              IFNAMSIZ, dev->iface, strerror (errno));
1670     return 1;
1671   }
1672   if (((ifr.ifr_hwaddr.sa_family != ARPHRD_IEEE80211) &&
1673        (ifr.ifr_hwaddr.sa_family != ARPHRD_ETHER) &&
1674        (ifr.ifr_hwaddr.sa_family != ARPHRD_IEEE80211_PRISM) &&
1675        (ifr.ifr_hwaddr.sa_family != ARPHRD_IEEE80211_FULL)) )
1676   {
1677     fprintf (stderr, "Error: interface `%.*s' is not using a supported hardware address family (got %d)\n",
1678              IFNAMSIZ, dev->iface,
1679              ifr.ifr_hwaddr.sa_family);
1680     return 1;
1681   }
1682
1683   /* lookup iw mode */
1684   memset (&wrq, 0, sizeof (struct iwreq));
1685   strncpy (wrq.ifr_name, dev->iface, IFNAMSIZ);
1686   if (-1 == ioctl (dev->fd_raw, SIOCGIWMODE, &wrq))
1687   {
1688     /* most probably not supported (ie for rtap ipw interface) *
1689      * so just assume its correctly set...                     */
1690     wrq.u.mode = IW_MODE_MONITOR;
1691   }
1692
1693   if ( (wrq.u.mode != IW_MODE_MONITOR) &&
1694        (wrq.u.mode != IW_MODE_ADHOC) )  
1695   {
1696     fprintf (stderr, "Error: interface `%.*s' is not in monitor or ad-hoc mode (got %d)\n",
1697              IFNAMSIZ, dev->iface,
1698              wrq.u.mode);
1699     return 1;
1700   }
1701
1702   /* Is interface st to up, broadcast & running ? */
1703   if ((ifr.ifr_flags | IFF_UP | IFF_BROADCAST | IFF_RUNNING) != ifr.ifr_flags)
1704   {
1705     /* Bring interface up */
1706     ifr.ifr_flags |= IFF_UP | IFF_BROADCAST | IFF_RUNNING;
1707
1708     if (-1 == ioctl (dev->fd_raw, SIOCSIFFLAGS, &ifr))
1709     {
1710       fprintf (stderr, "ioctl(SIOCSIFFLAGS) on interface `%.*s' failed: %s\n",
1711                IFNAMSIZ, dev->iface, strerror (errno));
1712       return 1;
1713     }
1714   }
1715
1716   /* bind the raw socket to the interface */
1717   if (-1 == bind (dev->fd_raw, (struct sockaddr *) &sll, sizeof (sll)))
1718   {
1719     fprintf (stderr, "Failed to bind interface `%.*s': %s\n", IFNAMSIZ,
1720              dev->iface, strerror (errno));
1721     return 1;
1722   }
1723
1724   /* lookup the hardware type */
1725   if (-1 == ioctl (dev->fd_raw, SIOCGIFHWADDR, &ifr))
1726   {
1727     fprintf (stderr, "ioctl(SIOCGIFHWADDR) on interface `%.*s' failed: %s\n",
1728              IFNAMSIZ, dev->iface, strerror (errno));
1729     return 1;
1730   }
1731
1732   memcpy (&dev->pl_mac, ifr.ifr_hwaddr.sa_data, MAC_ADDR_SIZE);
1733   dev->arptype_in = ifr.ifr_hwaddr.sa_family;
1734   if ((ifr.ifr_hwaddr.sa_family != ARPHRD_ETHER) &&
1735       (ifr.ifr_hwaddr.sa_family != ARPHRD_IEEE80211) &&
1736       (ifr.ifr_hwaddr.sa_family != ARPHRD_IEEE80211_PRISM) &&
1737       (ifr.ifr_hwaddr.sa_family != ARPHRD_IEEE80211_FULL))
1738   {
1739     fprintf (stderr, "Unsupported hardware link type %d on interface `%.*s'\n",
1740              ifr.ifr_hwaddr.sa_family, IFNAMSIZ, dev->iface);
1741     return 1;
1742   }
1743
1744   /* enable promiscuous mode */
1745   memset (&mr, 0, sizeof (mr));
1746   mr.mr_ifindex = sll.sll_ifindex;
1747   mr.mr_type = PACKET_MR_PROMISC;
1748   if (0 !=
1749       setsockopt (dev->fd_raw, SOL_PACKET, PACKET_ADD_MEMBERSHIP, &mr,
1750                   sizeof (mr)))
1751   {
1752     fprintf (stderr, 
1753              "Failed to enable promiscuous mode on interface `%.*s'\n",
1754              IFNAMSIZ, 
1755              dev->iface);
1756     return 1;
1757   }
1758   return 0;
1759 }
1760
1761
1762 /**
1763  * Test if the given interface name really corresponds to a wireless
1764  * device.
1765  *
1766  * @param iface name of the interface
1767  * @return 0 on success, 1 on error
1768  */
1769 static int
1770 test_wlan_interface (const char *iface)
1771 {
1772   char strbuf[512];
1773   struct stat sbuf;
1774   int ret;
1775
1776   ret = snprintf (strbuf, sizeof (strbuf), 
1777                   "/sys/class/net/%s/phy80211/subsystem",
1778                   iface);
1779   if ((ret < 0) || (ret >= sizeof (strbuf)) || (0 != stat (strbuf, &sbuf)))
1780   {
1781     fprintf (stderr, 
1782              "Did not find 802.11 interface `%s'. Exiting.\n", 
1783              iface);
1784     exit (1);
1785   }
1786   return 0;
1787 }
1788
1789
1790 /**
1791  * Test incoming packets mac for being our own.
1792  *
1793  * @param taIeeeHeader buffer of the packet
1794  * @param dev the Hardware_Infos struct
1795  * @return 0 if mac belongs to us, 1 if mac is for another target
1796  */
1797 static int
1798 mac_test (const struct GNUNET_TRANSPORT_WLAN_Ieee80211Frame *taIeeeHeader,
1799           const struct HardwareInfos *dev)
1800 {
1801   static struct GNUNET_TRANSPORT_WLAN_MacAddress all_zeros;
1802
1803   if ( (0 == memcmp (&taIeeeHeader->addr3, &all_zeros, MAC_ADDR_SIZE)) ||
1804        (0 == memcmp (&taIeeeHeader->addr1, &all_zeros, MAC_ADDR_SIZE)) )
1805     return 0; /* some drivers set no Macs, then assume it is all for us! */
1806
1807   if (0 != memcmp (&taIeeeHeader->addr3, &mac_bssid_gnunet, MAC_ADDR_SIZE))
1808     return 1; /* not a GNUnet ad-hoc package */
1809   if ( (0 == memcmp (&taIeeeHeader->addr1, &dev->pl_mac, MAC_ADDR_SIZE)) ||
1810        (0 == memcmp (&taIeeeHeader->addr1, &bc_all_mac, MAC_ADDR_SIZE)) )
1811     return 0; /* for us, or broadcast */
1812   return 1; /* not for us */
1813 }
1814
1815
1816 /**
1817  * Set the wlan header to sane values to make attacks more difficult
1818  *
1819  * @param taIeeeHeader pointer to the header of the packet
1820  * @param dev pointer to the Hardware_Infos struct
1821  */
1822 static void
1823 mac_set (struct GNUNET_TRANSPORT_WLAN_Ieee80211Frame *taIeeeHeader,
1824          const struct HardwareInfos *dev)
1825 {
1826   taIeeeHeader->frame_control = htons (IEEE80211_FC0_TYPE_DATA);
1827   taIeeeHeader->addr2 = dev->pl_mac;
1828   taIeeeHeader->addr3 = mac_bssid_gnunet;
1829 }
1830
1831
1832 /**
1833  * Process data from the stdin.  Takes the message, prepends the
1834  * radiotap transmission header, forces the sender MAC to be correct
1835  * and puts it into our buffer for transmission to the kernel.
1836  *
1837  * @param cls pointer to the device struct ('struct HardwareInfos*')
1838  * @param hdr pointer to the start of the packet
1839  */
1840 static void
1841 stdin_send_hw (void *cls, const struct GNUNET_MessageHeader *hdr)
1842 {
1843   struct HardwareInfos *dev = cls;
1844   const struct GNUNET_TRANSPORT_WLAN_RadiotapSendMessage *header;
1845   struct GNUNET_TRANSPORT_WLAN_Ieee80211Frame *wlanheader;
1846   size_t sendsize;
1847   struct RadiotapTransmissionHeader rtheader;
1848   struct GNUNET_TRANSPORT_WLAN_Ieee8023Frame etheader;
1849
1850   sendsize = ntohs (hdr->size);
1851   if ( (sendsize <
1852         sizeof (struct GNUNET_TRANSPORT_WLAN_RadiotapSendMessage)) ||
1853        (GNUNET_MESSAGE_TYPE_WLAN_DATA_TO_HELPER != ntohs (hdr->type)) ) 
1854   {
1855     fprintf (stderr, "Received malformed message\n");
1856     exit (1);
1857   }
1858   sendsize -= (sizeof (struct GNUNET_TRANSPORT_WLAN_RadiotapSendMessage) - sizeof (struct GNUNET_TRANSPORT_WLAN_Ieee80211Frame));
1859   if (MAXLINE < sendsize)
1860   {
1861     fprintf (stderr, "Packet too big for buffer\n");
1862     exit (1);
1863   }
1864   header = (const struct GNUNET_TRANSPORT_WLAN_RadiotapSendMessage *) hdr;
1865   switch (dev->arptype_in)
1866   {
1867   case ARPHRD_IEEE80211_PRISM:
1868   case ARPHRD_IEEE80211_FULL:
1869   case ARPHRD_IEEE80211:
1870     rtheader.header.it_version = 0;
1871     rtheader.header.it_pad = 0; 
1872     rtheader.header.it_len = GNUNET_htole16 (sizeof (rtheader));
1873     rtheader.header.it_present = GNUNET_htole16 (IEEE80211_RADIOTAP_OUR_TRANSMISSION_HEADER_MASK);
1874     rtheader.rate = header->rate; 
1875     rtheader.pad1 = 0;
1876     rtheader.txflags = GNUNET_htole16 (IEEE80211_RADIOTAP_F_TX_NOACK | IEEE80211_RADIOTAP_F_TX_NOSEQ);
1877     memcpy (write_pout.buf, &rtheader, sizeof (rtheader));
1878     memcpy (&write_pout.buf[sizeof (rtheader)], &header->frame, sendsize);
1879     wlanheader = (struct GNUNET_TRANSPORT_WLAN_Ieee80211Frame *) &write_pout.buf[sizeof (rtheader)];
1880
1881     /* payload contains MAC address, but we don't trust it, so we'll
1882      * overwrite it with OUR MAC address to prevent mischief */
1883     mac_set (wlanheader, dev);
1884     write_pout.size = sendsize + sizeof (rtheader);
1885     break;
1886   case ARPHRD_ETHER:
1887     etheader.dst = header->frame.addr1;
1888     /* etheader.src = header->frame.addr2; --- untrusted input */
1889     etheader.src = dev->pl_mac;
1890     etheader.type = htons (ETH_P_IP);
1891     memcpy (write_pout.buf, &etheader, sizeof (etheader));
1892     memcpy (&write_pout.buf[sizeof (etheader)], &header[1], sendsize - sizeof (struct GNUNET_TRANSPORT_WLAN_Ieee80211Frame));
1893     write_pout.size = sendsize - sizeof (struct GNUNET_TRANSPORT_WLAN_Ieee80211Frame) + sizeof (etheader);
1894     break;
1895   default:
1896     fprintf (stderr,
1897              "Unsupported ARPTYPE!\n");
1898     break;
1899   }
1900 }
1901
1902
1903 /**
1904  * Main function of the helper.  This code accesses a WLAN interface
1905  * in monitoring mode (layer 2) and then forwards traffic in both
1906  * directions between the WLAN interface and stdin/stdout of this
1907  * process.  Error messages are written to stdout.
1908  *
1909  * @param argc number of arguments, must be 2
1910  * @param argv arguments only argument is the name of the interface (i.e. 'mon0')
1911  * @return 0 on success (never happens, as we don't return unless aborted), 1 on error
1912  */
1913 int
1914 main (int argc, char *argv[])
1915 {
1916   struct HardwareInfos dev;
1917   char readbuf[MAXLINE];
1918   int maxfd;
1919   fd_set rfds;
1920   fd_set wfds;
1921   int stdin_open;
1922   struct MessageStreamTokenizer *stdin_mst;
1923   int raw_eno;
1924   uid_t uid;
1925
1926   /* assert privs so we can modify the firewall rules! */
1927   uid = getuid ();
1928 #ifdef HAVE_SETRESUID
1929   if (0 != setresuid (uid, 0, 0))
1930   {
1931     fprintf (stderr, "Failed to setresuid to root: %s\n", strerror (errno));
1932     return 254;
1933   }
1934 #else
1935   if (0 != seteuid (0)) 
1936   {
1937     fprintf (stderr, "Failed to seteuid back to root: %s\n", strerror (errno));
1938     return 254;
1939   }
1940 #endif
1941
1942   /* make use of SGID capabilities on POSIX */
1943   memset (&dev, 0, sizeof (dev));
1944   dev.fd_raw = socket (PF_PACKET, SOCK_RAW, htons (ETH_P_ALL));
1945   raw_eno = errno; /* remember for later */
1946
1947   /* now that we've dropped root rights, we can do error checking */
1948   if (2 != argc)
1949   {
1950     fprintf (stderr,
1951              "You must specify the name of the interface as the first and only argument to this program.\n");
1952     if (-1 != dev.fd_raw)
1953       (void) close (dev.fd_raw);
1954     return 1;
1955   }
1956
1957   if (-1 == dev.fd_raw)
1958   {
1959     fprintf (stderr, "Failed to create raw socket: %s\n", strerror (raw_eno));
1960     return 1;
1961   }
1962   if (dev.fd_raw >= FD_SETSIZE)
1963   {
1964     fprintf (stderr, "File descriptor too large for select (%d > %d)\n",
1965              dev.fd_raw, FD_SETSIZE);
1966     (void) close (dev.fd_raw);
1967     return 1;
1968   }
1969   if (0 != test_wlan_interface (argv[1]))
1970   {
1971     (void) close (dev.fd_raw);
1972     return 1;
1973   }
1974   strncpy (dev.iface, argv[1], IFNAMSIZ);
1975   if (0 != open_device_raw (&dev))
1976   {
1977     (void) close (dev.fd_raw);
1978     return 1;
1979   }
1980
1981   /* drop privs */
1982   {
1983     uid_t uid = getuid ();
1984 #ifdef HAVE_SETRESUID
1985     if (0 != setresuid (uid, uid, uid))
1986     {
1987       fprintf (stderr, "Failed to setresuid: %s\n", strerror (errno));
1988       if (-1 != dev.fd_raw)
1989         (void) close (dev.fd_raw);
1990       return 1;
1991     }
1992 #else
1993     if (0 != (setuid (uid) | seteuid (uid)))
1994     {
1995       fprintf (stderr, "Failed to setuid: %s\n", strerror (errno));
1996       if (-1 != dev.fd_raw)
1997         (void) close (dev.fd_raw);
1998       return 1;
1999     }
2000 #endif
2001   }
2002
2003
2004   /* send MAC address of the WLAN interface to STDOUT first */
2005   {
2006     struct GNUNET_TRANSPORT_WLAN_HelperControlMessage macmsg;
2007
2008     macmsg.hdr.size = htons (sizeof (macmsg));
2009     macmsg.hdr.type = htons (GNUNET_MESSAGE_TYPE_WLAN_HELPER_CONTROL);
2010     memcpy (&macmsg.mac, &dev.pl_mac, sizeof (struct GNUNET_TRANSPORT_WLAN_MacAddress));
2011     memcpy (write_std.buf, &macmsg, sizeof (macmsg));
2012     write_std.size = sizeof (macmsg);
2013   }  
2014
2015   stdin_mst = mst_create (&stdin_send_hw, &dev);  
2016   stdin_open = 1;
2017   while (1)
2018   {
2019     maxfd = -1;
2020     FD_ZERO (&rfds);
2021     if ((0 == write_pout.size) && (1 == stdin_open))
2022     {
2023       FD_SET (STDIN_FILENO, &rfds);
2024       maxfd = MAX (maxfd, STDIN_FILENO);
2025     }
2026     if (0 == write_std.size)
2027     {
2028       FD_SET (dev.fd_raw, &rfds);
2029       maxfd = MAX (maxfd, dev.fd_raw);
2030     }
2031     FD_ZERO (&wfds);
2032     if (0 < write_std.size)
2033     {
2034       FD_SET (STDOUT_FILENO, &wfds);
2035       maxfd = MAX (maxfd, STDOUT_FILENO);
2036     }
2037     if (0 < write_pout.size)
2038     {
2039       FD_SET (dev.fd_raw, &wfds);
2040       maxfd = MAX (maxfd, dev.fd_raw);
2041     }
2042     {
2043       int retval = select (maxfd + 1, &rfds, &wfds, NULL, NULL);
2044       if ((-1 == retval) && (EINTR == errno))
2045         continue;
2046       if (0 > retval)
2047       {
2048         fprintf (stderr, "select failed: %s\n", strerror (errno));
2049         break;
2050       }
2051     }
2052     if (FD_ISSET (STDOUT_FILENO, &wfds))
2053     {
2054       ssize_t ret =
2055           write (STDOUT_FILENO, write_std.buf + write_std.pos,
2056                  write_std.size - write_std.pos);
2057       if (0 > ret)
2058       {
2059         fprintf (stderr, "Failed to write to STDOUT: %s\n", strerror (errno));
2060         break;
2061       }
2062       write_std.pos += ret;
2063       if (write_std.pos == write_std.size)
2064       {
2065         write_std.pos = 0;
2066         write_std.size = 0;
2067       }
2068     }
2069     if (FD_ISSET (dev.fd_raw, &wfds))
2070     {
2071       ssize_t ret =
2072         write (dev.fd_raw, write_pout.buf + write_std.pos, 
2073                write_pout.size - write_pout.pos);
2074       if (0 > ret)
2075       {
2076         fprintf (stderr, "Failed to write to WLAN device: %s\n",
2077                  strerror (errno));
2078         break;
2079       }
2080       write_pout.pos += ret;
2081       if ((write_pout.pos != write_pout.size) && (0 != ret))
2082       {
2083         /* we should not get partial sends with packet-oriented devices... */
2084         fprintf (stderr, "Write error, partial send: %u/%u\n",
2085                  (unsigned int) write_pout.pos,
2086                  (unsigned int) write_pout.size);
2087         break;
2088       }
2089       if (write_pout.pos == write_pout.size)
2090       {
2091         write_pout.pos = 0;
2092         write_pout.size = 0;
2093       }
2094     }
2095
2096     if (FD_ISSET (STDIN_FILENO, &rfds))
2097     {
2098       ssize_t ret = 
2099         read (STDIN_FILENO, readbuf, sizeof (readbuf));
2100       if (0 > ret)
2101       {
2102         fprintf (stderr, "Read error from STDIN: %s\n", strerror (errno));
2103         break;
2104       }
2105       if (0 == ret)
2106       {
2107         /* stop reading... */
2108         stdin_open = 0;
2109       }
2110       mst_receive (stdin_mst, readbuf, ret);
2111     }
2112
2113     if (FD_ISSET (dev.fd_raw, &rfds))
2114     {
2115       struct GNUNET_TRANSPORT_WLAN_RadiotapReceiveMessage *rrm;
2116       ssize_t ret;
2117
2118       rrm = (struct GNUNET_TRANSPORT_WLAN_RadiotapReceiveMessage *) write_std.buf;
2119       ret =
2120           linux_read (&dev, (unsigned char *) &rrm->frame,
2121                       sizeof (write_std.buf) 
2122                       - sizeof (struct GNUNET_TRANSPORT_WLAN_RadiotapReceiveMessage) 
2123                       + sizeof (struct GNUNET_TRANSPORT_WLAN_Ieee80211Frame), 
2124                       rrm);
2125       if (0 > ret)
2126       {
2127         fprintf (stderr, "Read error from raw socket: %s\n", strerror (errno));
2128         break;
2129       }
2130       if ((0 < ret) && (0 == mac_test (&rrm->frame, &dev)))
2131       {
2132         write_std.size = ret 
2133           + sizeof (struct GNUNET_TRANSPORT_WLAN_RadiotapReceiveMessage) 
2134           - sizeof (struct GNUNET_TRANSPORT_WLAN_Ieee80211Frame);
2135         rrm->header.size = htons (write_std.size);
2136         rrm->header.type = htons (GNUNET_MESSAGE_TYPE_WLAN_DATA_FROM_HELPER);
2137       }
2138     }
2139   }
2140   /* Error handling, try to clean up a bit at least */
2141   mst_destroy (stdin_mst);
2142   (void) close (dev.fd_raw);
2143   return 1;                     /* we never exit 'normally' */
2144 }
2145
2146 /* end of gnunet-helper-transport-wlan.c */