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