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