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