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