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