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
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.
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.
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.
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
29 * This program will allow receiving and sending traffic from the WLAN
30 * interface. It will force traffic to be in 'ad-hoc' mode, use the
31 * proper MAC address of the WLAN interface and use a GNUnet-specific
32 * SSID (and a GNUnet-specific SNAP header). It only takes a single
33 * argument, which is the name of the interface to use. Since it uses
34 * RAW sockets, it must be installed SUID or run as 'root'. In order
35 * to keep the security risk of the resulting SUID binary minimal, the
36 * program ONLY opens the RAW socket with root privileges, then drops
37 * them and only then starts to process command line arguments. The
38 * code also does not link against any shared libraries (except libc)
39 * and is strictly minimal (except for checking for errors). The
40 * following list of people have reviewed this code and considered it
41 * safe since the last modification (if you reviewed it, please have
42 * your name added to the list):
44 * - Christian Grothoff (Mar 16th 2012)
48 * we use our local copy of ieee80211_radiotap.h
50 * - since we can't support extensions we don't understand
51 * - since linux does not include it in userspace headers
53 * Portions of this code were taken from the ieee80211_radiotap.h header,
56 * Copyright (c) 2003, 2004 David Young. All rights reserved.
58 * Redistribution and use in source and binary forms, with or without
59 * modification, are permitted provided that the following conditions
61 * 1. Redistributions of source code must retain the above copyright
62 * notice, this list of conditions and the following disclaimer.
63 * 2. Redistributions in binary form must reproduce the above copyright
64 * notice, this list of conditions and the following disclaimer in the
65 * documentation and/or other materials provided with the distribution.
66 * 3. The name of David Young may not be used to endorse or promote
67 * products derived from this software without specific prior
70 * THIS SOFTWARE IS PROVIDED BY DAVID YOUNG ``AS IS'' AND ANY
71 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
72 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
73 * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL DAVID
74 * YOUNG BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
75 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
76 * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
77 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
78 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
79 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
80 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
85 * Modifications to fit into the linux IEEE 802.11 stack,
86 * Mike Kershaw (dragorn@kismetwireless.net)
89 * parts taken from aircrack-ng, parts changend.
93 #include <sys/socket.h>
94 #include <sys/ioctl.h>
95 #include <sys/types.h>
100 #include <netpacket/packet.h>
101 #include <linux/if_ether.h>
102 #include <linux/if.h>
103 #include <linux/wireless.h>
104 #include <netinet/in.h>
105 #include <linux/if_tun.h>
113 #include <sys/param.h>
117 #include "gnunet_protocols.h"
118 #include "plugin_transport_wlan.h"
121 * Packet format type for the messages we receive from
122 * the kernel. This is for plain messages (with no
123 * performance information included).
125 #define ARPHRD_IEEE80211 801
128 * Packet format type for the messages we receive from
129 * the kernel. This is for the PRISM format.
131 #define ARPHRD_IEEE80211_PRISM 802
134 * Packet format type for the messages we receive from
135 * the kernel. This is for messages with a
136 * 'struct Ieee80211RadiotapHeader' (see below).
138 #define ARPHRD_IEEE80211_FULL 803
142 * Maximum size of a message allowed in either direction
143 * (used for our receive and sent buffers).
149 /* ********* structure of messages of type ARPHRD_IEEE80211_PRISM *********** */
152 * Device name length in PRISM frames.
153 * (In the kernel, this is "WLAN_DEVNAMELEN_MAX")
155 #define PRISM_DEVICE_NAME_LENGTH 16
158 * Monitor Frame (indicator that we have a 'struct PrismHeader').
160 #define PRISM_MSGCODE_MONITOR 0x0041
163 * Mac time element. In micro-seconds.
164 * Drivers appear to use a 64bit counter to hold mactime internal
165 * the then fill the prism header with the lower 32 bits
167 #define PRISM_DID_MACTIME 0x2041
172 #define PRISM_DID_CHANNEL 0x3041
175 * Signal element. Should be the signal strength in dbm, some people
176 * suggest that instead "100 - (strength in dbm)" is used (to make this
177 * a positive integer).
179 #define PRISM_DID_SIGNAL 0x6041
184 #define PRISM_DID_NOISE 0x7041
187 * Rate element, in units/multiples of 500Khz
189 #define PRISM_DID_RATE 0x8041
193 * Value is set (supplied)
195 #define PRISM_STATUS_OK 0
198 * Value not supplied.
200 #define PRISM_STATUS_NO_VALUE 1
204 * Values in the 'struct PrismHeader'. All in host byte order (!).
209 * This has a different ID for each parameter, see
210 * PRISM_DID_* constants.
215 * See PRISM_STATUS_*-constants. Note that they are unusual: 0 = set; 1 = not set
220 * length of data (which is always a uint32_t, but presumably this can be used
221 * to specify that fewer bytes are used (with values in 'len' from 0-4). We
231 } __attribute__ ((packed));
235 * Prism header format ('struct p80211msg' in Linux). All in host byte order (!).
240 * We expect this to be a PRISM_MSGCODE_*.
245 * The length of the entire header.
250 * Name of the device that captured the packet.
252 char devname[PRISM_DEVICE_NAME_LENGTH];
254 /* followed by 'struct PrismValue's. Documentation suggests that these
255 are typically the hosttime, mactime, channel, rssi, sq, signal, noise,
256 rate, istx and frmlen values, but documentation is sparse. So we
257 will use the 'did' fields to find out what we actually got. */
259 } __attribute__ ((packed));
262 /* ****** end of structure of messages of type ARPHRD_IEEE80211_PRISM ******* */
264 /* ********** structure of messages of type ARPHRD_IEEE80211_FULL *********** */
267 * Bits in the 'it_present' bitmask from the 'struct
268 * Ieee80211RadiotapHeader'. For each value, we give the name, data
269 * type, unit and then a description below. Note that the actual size
270 * of the extension can be bigger as arguments must be padded so that
271 * args of a given length must begin at a boundary of that length.
272 * However, note that compound args are allowed (eg, 2 x uint16_t for
273 * IEEE80211_RADIOTAP_CHANNEL) so total argument length is not a
274 * reliable indicator of alignment requirement. See also
275 * 'man 9 ieee80211_radiotap'.
281 * IEEE80211_RADIOTAP_TSFT __le64 microseconds
283 * Value in microseconds of the MAC's 64-bit 802.11 Time
284 * Synchronization Function timer when the first bit of the
285 * MPDU arrived at the MAC. For received frames, only.
287 IEEE80211_RADIOTAP_TSFT = 0,
290 * IEEE80211_RADIOTAP_FLAGS uint8_t bitmap
292 * Properties of transmitted and received frames. See flags
295 IEEE80211_RADIOTAP_FLAGS = 1,
298 * IEEE80211_RADIOTAP_RATE uint8_t 500kb/s
302 IEEE80211_RADIOTAP_RATE = 2,
305 * IEEE80211_RADIOTAP_CHANNEL 2 x __le16 MHz, bitmap
307 * Tx/Rx frequency in MHz, followed by flags (see below).
309 IEEE80211_RADIOTAP_CHANNEL = 3,
311 * IEEE80211_RADIOTAP_FHSS __le16 see below
313 * For frequency-hopping radios, the hop set (first byte)
314 * and pattern (second byte).
316 IEEE80211_RADIOTAP_FHSS = 4,
319 * IEEE80211_RADIOTAP_DBM_ANTSIGNAL s8 decibels from
320 * one milliwatt (dBm)
322 * RF signal power at the antenna, decibel difference from
325 IEEE80211_RADIOTAP_DBM_ANTSIGNAL = 5,
328 * IEEE80211_RADIOTAP_DBM_ANTNOISE s8 decibels from
329 * one milliwatt (dBm)
331 * RF noise power at the antenna, decibel difference from one
334 IEEE80211_RADIOTAP_DBM_ANTNOISE = 6,
337 * IEEE80211_RADIOTAP_LOCK_QUALITY __le16 unitless
339 * Quality of Barker code lock. Unitless. Monotonically
340 * nondecreasing with "better" lock strength. Called "Signal
341 * Quality" in datasheets. (Is there a standard way to measure
344 IEEE80211_RADIOTAP_LOCK_QUALITY = 7,
347 * IEEE80211_RADIOTAP_TX_ATTENUATION __le16 unitless
349 * Transmit power expressed as unitless distance from max
350 * power set at factory calibration. 0 is max power.
351 * Monotonically nondecreasing with lower power levels.
353 IEEE80211_RADIOTAP_TX_ATTENUATION = 8,
356 * IEEE80211_RADIOTAP_DB_TX_ATTENUATION __le16 decibels (dB)
358 * Transmit power expressed as decibel distance from max power
359 * set at factory calibration. 0 is max power. Monotonically
360 * nondecreasing with lower power levels.
362 IEEE80211_RADIOTAP_DB_TX_ATTENUATION = 9,
365 * IEEE80211_RADIOTAP_DBM_TX_POWER s8 decibels from
366 * one milliwatt (dBm)
368 * Transmit power expressed as dBm (decibels from a 1 milliwatt
369 * reference). This is the absolute power level measured at
372 IEEE80211_RADIOTAP_DBM_TX_POWER = 10,
375 * IEEE80211_RADIOTAP_ANTENNA uint8_t antenna index
377 * Unitless indication of the Rx/Tx antenna for this packet.
378 * The first antenna is antenna 0.
380 IEEE80211_RADIOTAP_ANTENNA = 11,
383 * IEEE80211_RADIOTAP_DB_ANTSIGNAL uint8_t decibel (dB)
385 * RF signal power at the antenna, decibel difference from an
386 * arbitrary, fixed reference.
388 IEEE80211_RADIOTAP_DB_ANTSIGNAL = 12,
391 * IEEE80211_RADIOTAP_DB_ANTNOISE uint8_t decibel (dB)
393 * RF noise power at the antenna, decibel difference from an
394 * arbitrary, fixed reference point.
396 IEEE80211_RADIOTAP_DB_ANTNOISE = 13,
399 * IEEE80211_RADIOTAP_RX_FLAGS __le16 bitmap
401 * Properties of received frames. See flags defined below.
403 IEEE80211_RADIOTAP_RX_FLAGS = 14,
406 * IEEE80211_RADIOTAP_TX_FLAGS __le16 bitmap
408 * Properties of transmitted frames. See flags defined below.
410 IEEE80211_RADIOTAP_TX_FLAGS = 15,
413 * IEEE80211_RADIOTAP_RTS_RETRIES uint8_t data
415 * Number of rts retries a transmitted frame used.
417 IEEE80211_RADIOTAP_RTS_RETRIES = 16,
420 * IEEE80211_RADIOTAP_DATA_RETRIES uint8_t data
422 * Number of unicast retries a transmitted frame used.
424 IEEE80211_RADIOTAP_DATA_RETRIES = 17,
427 * Extension bit, used to indicate that more bits are needed for
430 IEEE80211_RADIOTAP_EXT = 31
434 * Bitmask indicating an extension of the bitmask is used.
435 * (Mask corresponding to IEEE80211_RADIOTAP_EXT).
437 #define IEEE80211_RADIOTAP_PRESENT_EXTEND_MASK (1 << IEEE80211_RADIOTAP_EXT)
442 * Bit in IEEE80211_RADIOTAP_FLAGS (which we might get
443 * as part of a 'struct Ieee80211RadiotapHeader' extension
444 * if the IEEE80211_RADIOTAP_FLAGS bit is set in
445 * 'it_present'). The radiotap flags are an 8-bit field.
447 * Frame was sent/received during CFP (Contention Free Period)
449 #define IEEE80211_RADIOTAP_F_CFP 0x01
452 * Bit in IEEE80211_RADIOTAP_FLAGS (which we might get
453 * as part of a 'struct Ieee80211RadiotapHeader' extension
454 * if the IEEE80211_RADIOTAP_FLAGS bit is set in
455 * 'it_present'). The radiotap flags are an 8-bit field.
457 * Frame was sent/received with short preamble
459 #define IEEE80211_RADIOTAP_F_SHORTPRE 0x02
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.
467 * Frame was sent/received with WEP encryption
469 #define IEEE80211_RADIOTAP_F_WEP 0x04
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.
477 * Frame was sent/received with fragmentation
479 #define IEEE80211_RADIOTAP_F_FRAG 0x08
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.
487 * Frame includes FCS (CRC at the end that needs to be removeD).
489 #define IEEE80211_RADIOTAP_F_FCS 0x10
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.
497 * Frame has padding between 802.11 header and payload
498 * (to 32-bit boundary)
500 #define IEEE80211_RADIOTAP_F_DATAPAD 0x20
504 * For IEEE80211_RADIOTAP_RX_FLAGS:
505 * frame failed crc check
507 #define IEEE80211_RADIOTAP_F_RX_BADFCS 0x0001
510 * For IEEE80211_RADIOTAP_TX_FLAGS ('txflags' in 'struct RadiotapTransmissionHeader'):
511 * failed due to excessive retries
513 #define IEEE80211_RADIOTAP_F_TX_FAIL 0x0001
516 * For IEEE80211_RADIOTAP_TX_FLAGS ('txflags' in 'struct RadiotapTransmissionHeader'):
517 * used cts 'protection'
519 #define IEEE80211_RADIOTAP_F_TX_CTS 0x0002
522 * For IEEE80211_RADIOTAP_TX_FLAGS ('txflags' in 'struct RadiotapTransmissionHeader'):
523 * used rts/cts handshake
525 #define IEEE80211_RADIOTAP_F_TX_RTS 0x0004
528 * For IEEE80211_RADIOTAP_TX_FLAGS ('txflags' in 'struct RadiotapTransmissionHeader'):
529 * frame should not be ACKed
531 #define IEEE80211_RADIOTAP_F_TX_NOACK 0x0008
534 * For IEEE80211_RADIOTAP_TX_FLAGS ('txflags' in 'struct RadiotapTransmissionHeader'):
535 * sequence number handled by userspace
537 #define IEEE80211_RADIOTAP_F_TX_NOSEQ 0x0010
541 * Generic header for radiotap messages (receiving and sending). A
542 * bit mask (it_present) determines which specific records follow.
544 * I am trying to describe precisely what the application programmer
545 * should expect in the following, and for that reason I tell the
546 * units and origin of each measurement (where it applies), or else I
547 * use sufficiently weaselly language ("is a monotonically nondecreasing
548 * function of...") that I cannot set false expectations for lawyerly
551 * The radio capture header precedes the 802.11 header.
552 * All data in the header is little endian on all platforms.
554 struct Ieee80211RadiotapHeader
557 * Version 0. Only increases for drastic changes, introduction of
558 * compatible new fields does not count.
568 * length of the whole header in bytes, including it_version,
569 * it_pad, it_len, and data fields.
574 * A bitmap telling which fields are present. Set bit 31
575 * (0x80000000) to extend the bitmap by another 32 bits. Additional
576 * extensions are made by setting bit 31.
583 * Format of the header we need to prepend to messages to be sent to the
586 struct RadiotapTransmissionHeader
590 * First we begin with the 'generic' header we also get when receiving
593 struct Ieee80211RadiotapHeader header;
596 * Transmission rate (we use 0, kernel makes up its mind anyway).
601 * Padding (we use 0). There is a requirement to pad args, so that
602 * args of a given length must begin at a boundary of that length.
603 * As our next argument is the 'it_len' with 2 bytes, we need 1 byte
609 * Transmission flags from on the IEEE80211_RADIOTAP_F_TX_* constant family.
616 * The above 'struct RadiotapTransmissionHeader' should have the
617 * following value for 'header.it_present' based on the presence of
618 * the 'rate' and 'txflags' in the overall struct.
620 #define IEEE80211_RADIOTAP_OUR_TRANSMISSION_HEADER_MASK ((1 << IEEE80211_RADIOTAP_RATE) | (1 << IEEE80211_RADIOTAP_TX_FLAGS))
625 * struct Ieee80211RadiotapHeaderIterator - tracks walk through present radiotap arguments
626 * in the radiotap header. Used when we parse radiotap packets received from the kernel.
628 struct Ieee80211RadiotapHeaderIterator
631 * pointer to the radiotap header we are walking through
633 const struct Ieee80211RadiotapHeader *rtheader;
636 * pointer to current radiotap arg
638 const uint8_t *this_arg;
641 * internal next argument pointer
646 * internal pointer to next present uint32_t (if IEEE80211_RADIOTAP_EXT is used).
648 const uint32_t *next_bitmap;
651 * length of radiotap header in host byte ordering
656 * internal shifter for current uint32_t bitmap, (it_present in host byte order),
657 * If bit 0 is set, the 'arg_index' argument is present.
659 uint32_t bitmap_shifter;
662 * IEEE80211_RADIOTAP_... index of current arg
664 unsigned int this_arg_index;
667 * internal next argument index
669 unsigned int arg_index;
674 /* ************** end of structure of ARPHRD_IEEE80211_FULL ************** */
676 /* ************************** our globals ******************************* */
679 * struct for storing the information of the hardware. There is only
686 * file descriptor for the raw socket
691 * Which format has the header that we're getting when receiving packets?
692 * Some ARPHRD_IEEE80211_XXX-value.
697 * Name of the interface, not necessarily 0-terminated (!).
699 char iface[IFNAMSIZ];
702 * MAC address of our own WLAN interface.
704 struct GNUNET_TRANSPORT_WLAN_MacAddress pl_mac;
709 * IO buffer used for buffering data in transit (to wireless or to stdout).
714 * How many bytes of data are stored in 'buf' for transmission right now?
715 * Data always starts at offset 0 and extends to 'size'.
720 * How many bytes that were stored in 'buf' did we already write to the
721 * destination? Always smaller than 'size'.
726 * Buffered data; twice the maximum allowed message size as we add some
729 char buf[MAXLINE * 2];
734 * Buffer for data read from stdin to be transmitted to the wirless card.
736 static struct SendBuffer write_pout;
739 * Buffer for data read from the wireless card to be transmitted to stdout.
741 static struct SendBuffer write_std;
745 /* *********** specialized version of server_mst.c begins here ********** */
748 * To what multiple do we align messages? 8 byte should suffice for everyone
751 #define ALIGN_FACTOR 8
754 * Smallest supported message.
756 #define MIN_BUFFER_SIZE sizeof (struct GNUNET_MessageHeader)
760 * Functions with this signature are called whenever a
761 * complete message is received by the tokenizer.
764 * @param message the actual message
766 typedef void (*MessageTokenizerCallback) (void *cls,
768 GNUNET_MessageHeader *
772 * Handle to a message stream tokenizer.
774 struct MessageStreamTokenizer
778 * Function to call on completed messages.
780 MessageTokenizerCallback cb;
788 * Size of the buffer (starting at 'hdr').
793 * How many bytes in buffer have we already processed?
798 * How many bytes in buffer are valid right now?
803 * Beginning of the buffer. Typed like this to force alignment.
805 struct GNUNET_MessageHeader *hdr;
811 * Create a message stream tokenizer.
813 * @param cb function to call on completed messages
814 * @param cb_cls closure for cb
815 * @return handle to tokenizer
817 static struct MessageStreamTokenizer *
818 mst_create (MessageTokenizerCallback cb,
821 struct MessageStreamTokenizer *ret;
823 ret = malloc (sizeof (struct MessageStreamTokenizer));
826 fprintf (stderr, "Failed to allocate buffer for tokenizer\n");
829 ret->hdr = malloc (MIN_BUFFER_SIZE);
830 if (NULL == ret->hdr)
832 fprintf (stderr, "Failed to allocate buffer for alignment\n");
835 ret->curr_buf = MIN_BUFFER_SIZE;
837 ret->cb_cls = cb_cls;
843 * Add incoming data to the receive buffer and call the
844 * callback for all complete messages.
846 * @param mst tokenizer to use
847 * @param buf input data to add
848 * @param size number of bytes in buf
849 * @return GNUNET_OK if we are done processing (need more data)
850 * GNUNET_SYSERR if the data stream is corrupt
853 mst_receive (struct MessageStreamTokenizer *mst,
854 const char *buf, size_t size)
856 const struct GNUNET_MessageHeader *hdr;
861 unsigned long offset;
865 ibuf = (char *) mst->hdr;
869 if ((mst->curr_buf - mst->off < sizeof (struct GNUNET_MessageHeader)) ||
870 (0 != (mst->off % ALIGN_FACTOR)))
872 /* need to align or need more space */
873 mst->pos -= mst->off;
874 memmove (ibuf, &ibuf[mst->off], mst->pos);
877 if (mst->pos - mst->off < sizeof (struct GNUNET_MessageHeader))
880 GNUNET_MIN (sizeof (struct GNUNET_MessageHeader) -
881 (mst->pos - mst->off), size);
882 memcpy (&ibuf[mst->pos], buf, delta);
887 if (mst->pos - mst->off < sizeof (struct GNUNET_MessageHeader))
891 hdr = (const struct GNUNET_MessageHeader *) &ibuf[mst->off];
892 want = ntohs (hdr->size);
893 if (want < sizeof (struct GNUNET_MessageHeader))
896 "Received invalid message from stdin\n");
899 if (mst->curr_buf - mst->off < want)
901 /* need more space */
902 mst->pos -= mst->off;
903 memmove (ibuf, &ibuf[mst->off], mst->pos);
906 if (want > mst->curr_buf)
908 mst->hdr = realloc (mst->hdr, want);
909 if (NULL == mst->hdr)
911 fprintf (stderr, "Failed to allocate buffer for alignment\n");
914 ibuf = (char *) mst->hdr;
915 mst->curr_buf = want;
917 hdr = (const struct GNUNET_MessageHeader *) &ibuf[mst->off];
918 if (mst->pos - mst->off < want)
920 delta = GNUNET_MIN (want - (mst->pos - mst->off), size);
921 memcpy (&ibuf[mst->pos], buf, delta);
926 if (mst->pos - mst->off < want)
930 mst->cb (mst->cb_cls, hdr);
932 if (mst->off == mst->pos)
934 /* reset to beginning of buffer, it's free right now! */
941 if (size < sizeof (struct GNUNET_MessageHeader))
943 offset = (unsigned long) buf;
944 need_align = (0 != offset % ALIGN_FACTOR) ? GNUNET_YES : GNUNET_NO;
945 if (GNUNET_NO == need_align)
947 /* can try to do zero-copy and process directly from original buffer */
948 hdr = (const struct GNUNET_MessageHeader *) buf;
949 want = ntohs (hdr->size);
950 if (want < sizeof (struct GNUNET_MessageHeader))
953 "Received invalid message from stdin\n");
957 break; /* or not, buffer incomplete, so copy to private buffer... */
958 mst->cb (mst->cb_cls, hdr);
964 /* need to copy to private buffer to align;
965 * yes, we go a bit more spagetti than usual here */
971 if (size + mst->pos > mst->curr_buf)
973 mst->hdr = realloc (mst->hdr, size + mst->pos);
974 if (NULL == mst->hdr)
976 fprintf (stderr, "Failed to allocate buffer for alignment\n");
979 ibuf = (char *) mst->hdr;
980 mst->curr_buf = size + mst->pos;
982 if (mst->pos + size > mst->curr_buf)
985 "Assertion failed\n");
988 memcpy (&ibuf[mst->pos], buf, size);
996 * Destroys a tokenizer.
998 * @param mst tokenizer to destroy
1001 mst_destroy (struct MessageStreamTokenizer *mst)
1007 /* ***************** end of server_mst.c clone ***************** **/
1010 /* ************** code for handling of ARPHRD_IEEE80211_FULL ************** */
1013 * Radiotap header iteration
1015 * call __ieee80211_radiotap_iterator_init() to init a semi-opaque iterator
1016 * struct Ieee80211RadiotapHeaderIterator (no need to init the struct beforehand)
1017 * then loop calling __ieee80211_radiotap_iterator_next()... it returns -1
1018 * if there are no more args in the header, or the next argument type index
1019 * that is present. The iterator's this_arg member points to the start of the
1020 * argument associated with the current argument index that is present,
1021 * which can be found in the iterator's this_arg_index member. This arg
1022 * index corresponds to the IEEE80211_RADIOTAP_... defines.
1024 * @param iterator iterator to initialize
1025 * @param radiotap_header message to parse
1026 * @param max_length number of valid bytes in radiotap_header
1027 * @return 0 on success, -1 on error
1030 ieee80211_radiotap_iterator_init (struct Ieee80211RadiotapHeaderIterator *iterator,
1031 const struct Ieee80211RadiotapHeader *radiotap_header,
1034 if ( (iterator == NULL) ||
1035 (radiotap_header == NULL) )
1038 /* Linux only supports version 0 radiotap format */
1039 if (0 != radiotap_header->it_version)
1042 /* sanity check for allowed length and radiotap length field */
1043 if ( (max_length < sizeof (struct Ieee80211RadiotapHeader)) ||
1044 (max_length < (GNUNET_le16toh (radiotap_header->it_len))) )
1047 memset (iterator, 0, sizeof (struct Ieee80211RadiotapHeaderIterator));
1048 iterator->rtheader = radiotap_header;
1049 iterator->max_length = GNUNET_le16toh (radiotap_header->it_len);
1050 iterator->bitmap_shifter = GNUNET_le32toh (radiotap_header->it_present);
1051 iterator->arg = ((uint8_t *) radiotap_header) + sizeof (struct Ieee80211RadiotapHeader);
1053 /* find payload start allowing for extended bitmap(s) */
1054 if (0 != (iterator->bitmap_shifter & IEEE80211_RADIOTAP_PRESENT_EXTEND_MASK))
1056 while (GNUNET_le32toh (*((uint32_t *) iterator->arg)) & IEEE80211_RADIOTAP_PRESENT_EXTEND_MASK)
1058 iterator->arg += sizeof (uint32_t);
1060 * check for insanity where the present bitmaps
1061 * keep claiming to extend up to or even beyond the
1062 * stated radiotap header length
1064 if (iterator->arg - ((uint8_t*) iterator->rtheader) > iterator->max_length)
1067 iterator->arg += sizeof (uint32_t);
1069 * no need to check again for blowing past stated radiotap
1070 * header length, becuase ieee80211_radiotap_iterator_next
1071 * checks it before it is dereferenced
1074 /* we are all initialized happily */
1080 * Returns the next radiotap parser iterator arg.
1082 * This function returns the next radiotap arg index (IEEE80211_RADIOTAP_...)
1083 * and sets iterator->this_arg to point to the payload for the arg. It takes
1084 * care of alignment handling and extended present fields. interator->this_arg
1085 * can be changed by the caller. The args pointed to are in little-endian
1088 * @param iterator: radiotap_iterator to move to next arg (if any)
1089 * @return next present arg index on success or -1 if no more or error
1092 ieee80211_radiotap_iterator_next (struct Ieee80211RadiotapHeaderIterator *iterator)
1095 * small length lookup table for all radiotap types we heard of
1096 * starting from b0 in the bitmap, so we can walk the payload
1097 * area of the radiotap header
1099 * There is a requirement to pad args, so that args
1100 * of a given length must begin at a boundary of that length
1101 * -- but note that compound args are allowed (eg, 2 x uint16_t
1102 * for IEEE80211_RADIOTAP_CHANNEL) so total arg length is not
1103 * a reliable indicator of alignment requirement.
1105 * upper nybble: content alignment for arg
1106 * lower nybble: content length for arg
1109 static const uint8_t rt_sizes[] = {
1110 [IEEE80211_RADIOTAP_TSFT] = 0x88,
1111 [IEEE80211_RADIOTAP_FLAGS] = 0x11,
1112 [IEEE80211_RADIOTAP_RATE] = 0x11,
1113 [IEEE80211_RADIOTAP_CHANNEL] = 0x24,
1114 [IEEE80211_RADIOTAP_FHSS] = 0x22,
1115 [IEEE80211_RADIOTAP_DBM_ANTSIGNAL] = 0x11,
1116 [IEEE80211_RADIOTAP_DBM_ANTNOISE] = 0x11,
1117 [IEEE80211_RADIOTAP_LOCK_QUALITY] = 0x22,
1118 [IEEE80211_RADIOTAP_TX_ATTENUATION] = 0x22,
1119 [IEEE80211_RADIOTAP_DB_TX_ATTENUATION] = 0x22,
1120 [IEEE80211_RADIOTAP_DBM_TX_POWER] = 0x11,
1121 [IEEE80211_RADIOTAP_ANTENNA] = 0x11,
1122 [IEEE80211_RADIOTAP_DB_ANTSIGNAL] = 0x11,
1123 [IEEE80211_RADIOTAP_DB_ANTNOISE] = 0x11,
1124 [IEEE80211_RADIOTAP_TX_FLAGS] = 0x22,
1125 [IEEE80211_RADIOTAP_RX_FLAGS] = 0x22,
1126 [IEEE80211_RADIOTAP_RTS_RETRIES] = 0x11,
1127 [IEEE80211_RADIOTAP_DATA_RETRIES] = 0x11
1129 * add more here as they are defined in
1130 * include/net/ieee80211_radiotap.h
1135 * for every radiotap entry we can at
1136 * least skip (by knowing the length)...
1138 while (iterator->arg_index < sizeof (rt_sizes))
1140 int hit = (0 != (iterator->bitmap_shifter & 1));
1144 unsigned int wanted_alignment;
1145 unsigned int unalignment;
1147 * arg is present, account for alignment padding
1148 * 8-bit args can be at any alignment
1149 * 16-bit args must start on 16-bit boundary
1150 * 32-bit args must start on 32-bit boundary
1151 * 64-bit args must start on 64-bit boundary
1153 * note that total arg size can differ from alignment of
1154 * elements inside arg, so we use upper nybble of length table
1155 * to base alignment on. First, 'wanted_alignment' is set to be
1156 * 1 for 8-bit, 2 for 16-bit, 4 for 32-bit and 8 for 64-bit
1157 * arguments. Then, we calculate the 'unalignment' (how many
1158 * bytes we are over by taking the difference of 'arg' and the
1159 * overall starting point modulo the desired alignment. As
1160 * desired alignments are powers of two, we can do modulo with
1161 * binary "&" (and also avoid the possibility of a division by
1162 * zero if the 'rt_sizes' table contains bogus entries).
1164 * also note: these alignments are relative to the start of the
1165 * radiotap header. There is no guarantee that the radiotap
1166 * header itself is aligned on any kind of boundary, thus we
1167 * need to really look at the delta here.
1169 wanted_alignment = rt_sizes[iterator->arg_index] >> 4;
1170 unalignment = (((void *) iterator->arg) - ((void *) iterator->rtheader)) & (wanted_alignment - 1);
1171 if (0 != unalignment)
1173 /* need padding (by 'wanted_alignment - unalignment') */
1174 iterator->arg_index += wanted_alignment - unalignment;
1178 * this is what we will return to user, but we need to
1179 * move on first so next call has something fresh to test
1181 iterator->this_arg_index = iterator->arg_index;
1182 iterator->this_arg = iterator->arg;
1184 /* internally move on the size of this arg (using lower nybble from
1186 iterator->arg += rt_sizes[iterator->arg_index] & 0x0f;
1189 * check for insanity where we are given a bitmap that
1190 * claims to have more arg content than the length of the
1191 * radiotap section. We will normally end up equalling this
1192 * max_length on the last arg, never exceeding it.
1194 if ((((void *) iterator->arg) - ((void *) iterator->rtheader)) > iterator->max_length)
1198 /* Now, move on to next bit / next entry */
1199 iterator->arg_index++;
1201 if (0 == (iterator->arg_index % 32))
1203 /* completed current uint32_t bitmap */
1204 if (0 != (iterator->bitmap_shifter & 1))
1206 /* bit 31 was set, there is more; move to next uint32_t bitmap */
1207 iterator->bitmap_shifter = GNUNET_le32toh (*iterator->next_bitmap);
1208 iterator->next_bitmap++;
1212 /* no more bitmaps: end (by setting arg_index to high, unsupported value) */
1213 iterator->arg_index = sizeof (rt_sizes);
1218 /* just try the next bit (while loop will move on) */
1219 iterator->bitmap_shifter >>= 1;
1222 /* if we found a valid arg earlier, return it now */
1224 return iterator->this_arg_index;
1227 /* we don't know how to handle any more args (or there are no more),
1228 so we're done (this is not an error) */
1234 * Calculate crc32, the start of the calculation
1236 * @param buf buffer to calc the crc
1237 * @param len len of the buffer
1240 static unsigned long
1241 calc_crc_osdep (const unsigned char *buf, size_t len)
1243 static const unsigned long int crc_tbl_osdep[256] = {
1244 0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419, 0x706AF48F,
1245 0xE963A535, 0x9E6495A3,
1246 0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988, 0x09B64C2B, 0x7EB17CBD,
1247 0xE7B82D07, 0x90BF1D91,
1248 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE, 0x1ADAD47D, 0x6DDDE4EB,
1249 0xF4D4B551, 0x83D385C7,
1250 0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, 0x14015C4F, 0x63066CD9,
1251 0xFA0F3D63, 0x8D080DF5,
1252 0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172, 0x3C03E4D1, 0x4B04D447,
1253 0xD20D85FD, 0xA50AB56B,
1254 0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940, 0x32D86CE3, 0x45DF5C75,
1255 0xDCD60DCF, 0xABD13D59,
1256 0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116, 0x21B4F4B5, 0x56B3C423,
1257 0xCFBA9599, 0xB8BDA50F,
1258 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924, 0x2F6F7C87, 0x58684C11,
1259 0xC1611DAB, 0xB6662D3D,
1260 0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A, 0x71B18589, 0x06B6B51F,
1261 0x9FBFE4A5, 0xE8B8D433,
1262 0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818, 0x7F6A0DBB, 0x086D3D2D,
1263 0x91646C97, 0xE6635C01,
1264 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E, 0x6C0695ED, 0x1B01A57B,
1265 0x8208F4C1, 0xF50FC457,
1266 0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C, 0x62DD1DDF, 0x15DA2D49,
1267 0x8CD37CF3, 0xFBD44C65,
1268 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2, 0x4ADFA541, 0x3DD895D7,
1269 0xA4D1C46D, 0xD3D6F4FB,
1270 0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0, 0x44042D73, 0x33031DE5,
1271 0xAA0A4C5F, 0xDD0D7CC9,
1272 0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086, 0x5768B525, 0x206F85B3,
1273 0xB966D409, 0xCE61E49F,
1274 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 0x59B33D17, 0x2EB40D81,
1275 0xB7BD5C3B, 0xC0BA6CAD,
1276 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A, 0xEAD54739, 0x9DD277AF,
1277 0x04DB2615, 0x73DC1683,
1278 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8, 0xE40ECF0B, 0x9309FF9D,
1279 0x0A00AE27, 0x7D079EB1,
1280 0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE, 0xF762575D, 0x806567CB,
1281 0x196C3671, 0x6E6B06E7,
1282 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC, 0xF9B9DF6F, 0x8EBEEFF9,
1283 0x17B7BE43, 0x60B08ED5,
1284 0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252, 0xD1BB67F1, 0xA6BC5767,
1285 0x3FB506DD, 0x48B2364B,
1286 0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60, 0xDF60EFC3, 0xA867DF55,
1287 0x316E8EEF, 0x4669BE79,
1288 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236, 0xCC0C7795, 0xBB0B4703,
1289 0x220216B9, 0x5505262F,
1290 0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, 0xC2D7FFA7, 0xB5D0CF31,
1291 0x2CD99E8B, 0x5BDEAE1D,
1292 0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A, 0x9C0906A9, 0xEB0E363F,
1293 0x72076785, 0x05005713,
1294 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38, 0x92D28E9B, 0xE5D5BE0D,
1295 0x7CDCEFB7, 0x0BDBDF21,
1296 0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E, 0x81BE16CD, 0xF6B9265B,
1297 0x6FB077E1, 0x18B74777,
1298 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C, 0x8F659EFF, 0xF862AE69,
1299 0x616BFFD3, 0x166CCF45,
1300 0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2, 0xA7672661, 0xD06016F7,
1301 0x4969474D, 0x3E6E77DB,
1302 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0, 0xA9BCAE53, 0xDEBB9EC5,
1303 0x47B2CF7F, 0x30B5FFE9,
1304 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, 0xBAD03605, 0xCDD70693,
1305 0x54DE5729, 0x23D967BF,
1306 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94, 0xB40BBE37, 0xC30C8EA1,
1307 0x5A05DF1B, 0x2D02EF8D
1310 unsigned long crc = 0xFFFFFFFF;
1312 for (; len > 0; len--, buf++)
1313 crc = crc_tbl_osdep[(crc ^ *buf) & 0xFF] ^ (crc >> 8);
1319 * Calculate and check crc of the wlan packet
1321 * @param buf buffer of the packet, with len + 4 bytes of data,
1322 * the last 4 bytes being the checksum
1323 * @param len length of the payload in data
1324 * @return 0 on success (checksum matches), 1 on error
1327 check_crc_buf_osdep (const unsigned char *buf, size_t len)
1331 crc = calc_crc_osdep (buf, len);
1333 if (((crc) & 0xFF) == buf[0] && ((crc >> 8) & 0xFF) == buf[1] &&
1334 ((crc >> 16) & 0xFF) == buf[2] && ((crc >> 24) & 0xFF) == buf[3])
1340 /* ************end of code for handling of ARPHRD_IEEE80211_FULL ************** */
1343 /* ************beginning of code for reading packets from kernel ************** */
1346 * Return the channel from the frequency (in Mhz)
1348 * @param frequency of the channel
1349 * @return number of the channel
1352 get_channel_from_frequency (int32_t frequency)
1354 if (frequency >= 2412 && frequency <= 2472)
1355 return (frequency - 2407) / 5;
1356 if (frequency == 2484)
1358 if (frequency >= 5000 && frequency <= 6100)
1359 return (frequency - 5000) / 5;
1365 * Get the channel used by our WLAN interface.
1367 * @param dev pointer to the dev struct of the card
1368 * @return channel number, -1 on error
1371 linux_get_channel (const struct HardwareInfos *dev)
1376 memset (&wrq, 0, sizeof (struct iwreq));
1377 strncpy (wrq.ifr_name, dev->iface, IFNAMSIZ);
1378 if (0 > ioctl (dev->fd_raw, SIOCGIWFREQ, &wrq))
1380 frequency = wrq.u.freq.m; /* 'iw_freq' defines 'm' as '__s32', so we keep it signed */
1381 if (100000000 < frequency)
1382 frequency /= 100000;
1383 else if (1000000 < frequency)
1385 if (1000 < frequency)
1386 return get_channel_from_frequency (frequency);
1392 * Read from the raw socket (the wlan card), parse the packet and
1393 * put the result into the buffer for transmission to 'stdout'.
1395 * @param dev pointer to the struct of the wlan card
1396 * @param buf buffer to read to; first bytes will be the 'struct GNUNET_TRANSPORT_WLAN_Ieee80211Frame',
1397 * followed by the actual payload
1398 * @param buf_size size of the buffer
1399 * @param ri where to write radiotap_rx info
1400 * @return number of bytes written to 'buf'
1403 linux_read (struct HardwareInfos *dev,
1404 unsigned char *buf, size_t buf_size,
1405 struct GNUNET_TRANSPORT_WLAN_RadiotapReceiveMessage *ri)
1407 unsigned char tmpbuf[buf_size];
1412 int got_channel = 0;
1413 int fcs_removed = 0;
1415 caplen = read (dev->fd_raw, tmpbuf, buf_size);
1418 if (EAGAIN == errno)
1420 fprintf (stderr, "Failed to read from RAW socket: %s\n", strerror (errno));
1424 memset (ri, 0, sizeof (*ri));
1425 switch (dev->arptype_in)
1427 case ARPHRD_IEEE80211_PRISM:
1429 const struct PrismHeader *ph;
1431 ph = (const struct PrismHeader*) tmpbuf;
1433 if ( (n < 8) || (n >= caplen) )
1434 return 0; /* invalid format */
1435 if ( (PRISM_MSGCODE_MONITOR == ph->msgcode) &&
1436 (n >= sizeof (struct PrismHeader)) )
1440 struct PrismValue pv;
1442 left = n - sizeof (struct PrismHeader);
1443 pos = (const char *) &ph[1];
1444 while (left > sizeof (struct PrismValue))
1446 left -= sizeof (struct PrismValue);
1447 memcpy (&pv, pos, sizeof (struct PrismValue));
1448 pos += sizeof (struct PrismValue);
1452 case PRISM_DID_NOISE:
1453 if (PRISM_STATUS_OK == pv.status)
1455 ri->ri_noise = pv.data;
1459 case PRISM_DID_RATE:
1460 if (PRISM_STATUS_OK == pv.status)
1461 ri->ri_rate = pv.data * 500000;
1463 case PRISM_DID_CHANNEL:
1464 if (PRISM_STATUS_OK == pv.status)
1466 ri->ri_channel = pv.data;
1470 case PRISM_DID_MACTIME:
1471 if (PRISM_STATUS_OK == pv.status)
1472 ri->ri_mactime = pv.data;
1474 case PRISM_DID_SIGNAL:
1475 if (PRISM_STATUS_OK == pv.status)
1477 ri->ri_power = pv.data;
1484 if ( (n < 8) || (n >= caplen) )
1485 return 0; /* invalid format */
1488 case ARPHRD_IEEE80211_FULL:
1490 struct Ieee80211RadiotapHeaderIterator iterator;
1491 struct Ieee80211RadiotapHeader *rthdr;
1493 memset (&iterator, 0, sizeof (iterator));
1494 rthdr = (struct Ieee80211RadiotapHeader *) tmpbuf;
1495 n = GNUNET_le16toh (rthdr->it_len);
1496 if ( (n < sizeof (struct Ieee80211RadiotapHeader)) || (n >= caplen))
1497 return 0; /* invalid 'it_len' */
1498 if (0 != ieee80211_radiotap_iterator_init (&iterator, rthdr, caplen))
1500 /* go through the radiotap arguments we have been given by the driver */
1501 while (0 <= ieee80211_radiotap_iterator_next (&iterator))
1503 switch (iterator.this_arg_index)
1505 case IEEE80211_RADIOTAP_TSFT:
1506 ri->ri_mactime = GNUNET_le64toh (*((uint64_t *) iterator.this_arg));
1508 case IEEE80211_RADIOTAP_DBM_ANTSIGNAL:
1511 ri->ri_power = * ((int8_t*) iterator.this_arg);
1515 case IEEE80211_RADIOTAP_DB_ANTSIGNAL:
1518 ri->ri_power = * ((int8_t*) iterator.this_arg);
1522 case IEEE80211_RADIOTAP_DBM_ANTNOISE:
1525 ri->ri_noise = * ((int8_t*) iterator.this_arg);
1529 case IEEE80211_RADIOTAP_DB_ANTNOISE:
1532 ri->ri_noise = * ((int8_t*) iterator.this_arg);
1536 case IEEE80211_RADIOTAP_ANTENNA:
1537 ri->ri_antenna = *iterator.this_arg;
1539 case IEEE80211_RADIOTAP_CHANNEL:
1540 ri->ri_channel = *iterator.this_arg;
1543 case IEEE80211_RADIOTAP_RATE:
1544 ri->ri_rate = (*iterator.this_arg) * 500000;
1546 case IEEE80211_RADIOTAP_FLAGS:
1548 uint8_t flags = *iterator.this_arg;
1549 /* is the CRC visible at the end? if so, remove */
1550 if (0 != (flags & IEEE80211_RADIOTAP_F_FCS))
1553 caplen -= sizeof (uint32_t);
1557 case IEEE80211_RADIOTAP_RX_FLAGS:
1559 uint16_t flags = ntohs (* ((uint16_t *) iterator.this_arg));
1560 if (0 != (flags & IEEE80211_RADIOTAP_F_RX_BADFCS))
1564 } /* end of 'switch' */
1565 } /* end of the 'while' loop */
1568 case ARPHRD_IEEE80211:
1569 n = 0; /* no header */
1572 errno = ENOTSUP; /* unsupported format */
1577 ri->ri_channel = linux_get_channel (dev);
1579 /* detect CRC32 at the end, even if the flag wasn't set and remove it */
1580 if ( (0 == fcs_removed) &&
1581 (0 == check_crc_buf_osdep (tmpbuf + n, caplen - sizeof (uint32_t))) )
1583 /* NOTE: this heuristic can of course fail if there happens to
1584 be a matching checksum at the end. Would be good to have
1585 some data to see how often this heuristic actually works. */
1586 caplen -= sizeof (uint32_t);
1588 /* copy payload to target buffer */
1589 memcpy (buf, tmpbuf + n, caplen);
1594 /* ************end of code for reading packets from kernel ************** */
1596 /* ************other helper functions for main start here ************** */
1600 * Open the wireless network interface for reading/writing.
1602 * @param dev pointer to the device struct
1603 * @return 0 on success
1606 open_device_raw (struct HardwareInfos *dev)
1610 struct packet_mreq mr;
1611 struct sockaddr_ll sll;
1613 /* find the interface index */
1614 memset (&ifr, 0, sizeof (ifr));
1615 strncpy (ifr.ifr_name, dev->iface, IFNAMSIZ);
1616 if (-1 == ioctl (dev->fd_raw, SIOCGIFINDEX, &ifr))
1618 fprintf (stderr, "ioctl(SIOCGIFINDEX) on interface `%.*s' failed: %s\n",
1619 IFNAMSIZ, dev->iface, strerror (errno));
1623 /* lookup the hardware type */
1624 memset (&sll, 0, sizeof (sll));
1625 sll.sll_family = AF_PACKET;
1626 sll.sll_ifindex = ifr.ifr_ifindex;
1627 sll.sll_protocol = htons (ETH_P_ALL);
1628 if (-1 == ioctl (dev->fd_raw, SIOCGIFHWADDR, &ifr))
1630 fprintf (stderr, "ioctl(SIOCGIFHWADDR) on interface `%.*s' failed: %s\n",
1631 IFNAMSIZ, dev->iface, strerror (errno));
1635 /* lookup iw mode */
1636 memset (&wrq, 0, sizeof (struct iwreq));
1637 strncpy (wrq.ifr_name, dev->iface, IFNAMSIZ);
1638 if (-1 == ioctl (dev->fd_raw, SIOCGIWMODE, &wrq))
1640 /* most probably not supported (ie for rtap ipw interface) *
1641 * so just assume its correctly set... */
1642 wrq.u.mode = IW_MODE_MONITOR;
1645 if (((ifr.ifr_hwaddr.sa_family != ARPHRD_IEEE80211) &&
1646 (ifr.ifr_hwaddr.sa_family != ARPHRD_IEEE80211_PRISM) &&
1647 (ifr.ifr_hwaddr.sa_family != ARPHRD_IEEE80211_FULL)) ||
1648 (wrq.u.mode != IW_MODE_MONITOR))
1650 fprintf (stderr, "Error: interface `%.*s' is not in monitor mode\n",
1651 IFNAMSIZ, dev->iface);
1655 /* Is interface st to up, broadcast & running ? */
1656 if ((ifr.ifr_flags | IFF_UP | IFF_BROADCAST | IFF_RUNNING) != ifr.ifr_flags)
1658 /* Bring interface up */
1659 ifr.ifr_flags |= IFF_UP | IFF_BROADCAST | IFF_RUNNING;
1661 if (-1 == ioctl (dev->fd_raw, SIOCSIFFLAGS, &ifr))
1663 fprintf (stderr, "ioctl(SIOCSIFFLAGS) on interface `%.*s' failed: %s\n",
1664 IFNAMSIZ, dev->iface, strerror (errno));
1669 /* bind the raw socket to the interface */
1670 if (-1 == bind (dev->fd_raw, (struct sockaddr *) &sll, sizeof (sll)))
1672 fprintf (stderr, "Failed to bind interface `%.*s': %s\n", IFNAMSIZ,
1673 dev->iface, strerror (errno));
1677 /* lookup the hardware type */
1678 if (-1 == ioctl (dev->fd_raw, SIOCGIFHWADDR, &ifr))
1680 fprintf (stderr, "ioctl(SIOCGIFHWADDR) on interface `%.*s' failed: %s\n",
1681 IFNAMSIZ, dev->iface, strerror (errno));
1685 memcpy (&dev->pl_mac, ifr.ifr_hwaddr.sa_data, MAC_ADDR_SIZE);
1686 dev->arptype_in = ifr.ifr_hwaddr.sa_family;
1687 if ((ifr.ifr_hwaddr.sa_family != ARPHRD_IEEE80211) &&
1688 (ifr.ifr_hwaddr.sa_family != ARPHRD_IEEE80211_PRISM) &&
1689 (ifr.ifr_hwaddr.sa_family != ARPHRD_IEEE80211_FULL))
1691 fprintf (stderr, "Unsupported hardware link type %d on interface `%.*s'\n",
1692 ifr.ifr_hwaddr.sa_family, IFNAMSIZ, dev->iface);
1696 /* enable promiscuous mode */
1697 memset (&mr, 0, sizeof (mr));
1698 mr.mr_ifindex = sll.sll_ifindex;
1699 mr.mr_type = PACKET_MR_PROMISC;
1701 setsockopt (dev->fd_raw, SOL_PACKET, PACKET_ADD_MEMBERSHIP, &mr,
1705 "Failed to enable promiscuous mode on interface `%.*s'\n",
1715 * Test if the given interface name really corresponds to a wireless
1718 * @param iface name of the interface
1719 * @return 0 on success, 1 on error
1722 test_wlan_interface (const char *iface)
1728 ret = snprintf (strbuf, sizeof (strbuf),
1729 "/sys/class/net/%s/phy80211/subsystem",
1731 if ((ret < 0) || (ret >= sizeof (strbuf)) || (0 != stat (strbuf, &sbuf)))
1734 "Did not find 802.11 interface `%s'. Exiting.\n",
1743 * Test incoming packets mac for being our own.
1745 * @param taIeeeHeader buffer of the packet
1746 * @param dev the Hardware_Infos struct
1747 * @return 0 if mac belongs to us, 1 if mac is for another target
1750 mac_test (const struct GNUNET_TRANSPORT_WLAN_Ieee80211Frame *taIeeeHeader,
1751 const struct HardwareInfos *dev)
1753 if (0 != memcmp (&taIeeeHeader->addr3, &mac_bssid_gnunet, MAC_ADDR_SIZE))
1754 return 1; /* not a GNUnet ad-hoc package */
1755 if ( (0 == memcmp (&taIeeeHeader->addr1, &dev->pl_mac, MAC_ADDR_SIZE)) ||
1756 (0 == memcmp (&taIeeeHeader->addr1, &bc_all_mac, MAC_ADDR_SIZE)) )
1757 return 0; /* for us, or broadcast */
1758 return 1; /* not for us */
1763 * Set the wlan header to sane values to make attacks more difficult
1765 * @param taIeeeHeader pointer to the header of the packet
1766 * @param dev pointer to the Hardware_Infos struct
1769 mac_set (struct GNUNET_TRANSPORT_WLAN_Ieee80211Frame *taIeeeHeader,
1770 const struct HardwareInfos *dev)
1772 taIeeeHeader->frame_control = htons (IEEE80211_FC0_TYPE_DATA);
1773 taIeeeHeader->addr2 = dev->pl_mac;
1774 taIeeeHeader->addr3 = mac_bssid_gnunet;
1779 * Process data from the stdin. Takes the message, prepends the
1780 * radiotap transmission header, forces the sender MAC to be correct
1781 * and puts it into our buffer for transmission to the kernel.
1783 * @param cls pointer to the device struct ('struct HardwareInfos*')
1784 * @param hdr pointer to the start of the packet
1787 stdin_send_hw (void *cls, const struct GNUNET_MessageHeader *hdr)
1789 struct HardwareInfos *dev = cls;
1790 const struct GNUNET_TRANSPORT_WLAN_RadiotapSendMessage *header;
1791 struct GNUNET_TRANSPORT_WLAN_Ieee80211Frame *wlanheader;
1793 struct RadiotapTransmissionHeader rtheader;
1795 sendsize = ntohs (hdr->size);
1797 sizeof (struct GNUNET_TRANSPORT_WLAN_RadiotapSendMessage)) ||
1798 (GNUNET_MESSAGE_TYPE_WLAN_HELPER_DATA != ntohs (hdr->type)) )
1800 fprintf (stderr, "Received malformed message\n");
1803 sendsize -= (sizeof (struct GNUNET_TRANSPORT_WLAN_RadiotapSendMessage) - sizeof (struct GNUNET_TRANSPORT_WLAN_Ieee80211Frame));
1804 if (MAXLINE < sendsize)
1806 fprintf (stderr, "Function stdin_send_hw: Packet too big for buffer\n");
1809 header = (const struct GNUNET_TRANSPORT_WLAN_RadiotapSendMessage *) hdr;
1810 rtheader.header.it_version = 0;
1811 rtheader.header.it_pad = 0;
1812 rtheader.header.it_len = GNUNET_htole16 (sizeof (rtheader));
1813 rtheader.header.it_present = GNUNET_htole16 (IEEE80211_RADIOTAP_OUR_TRANSMISSION_HEADER_MASK);
1814 rtheader.rate = header->rate;
1816 rtheader.txflags = GNUNET_htole16 (IEEE80211_RADIOTAP_F_TX_NOACK | IEEE80211_RADIOTAP_F_TX_NOSEQ);
1817 memcpy (write_pout.buf, &rtheader, sizeof (rtheader));
1818 memcpy (&write_pout.buf[sizeof (rtheader)], &header->frame, sendsize);
1819 wlanheader = (struct GNUNET_TRANSPORT_WLAN_Ieee80211Frame *) &write_pout.buf[sizeof (rtheader)];
1821 /* payload contains MAC address, but we don't trust it, so we'll
1822 * overwrite it with OUR MAC address to prevent mischief */
1823 mac_set (wlanheader, dev);
1824 write_pout.size = sendsize + sizeof (rtheader);
1829 * Main function of the helper. This code accesses a WLAN interface
1830 * in monitoring mode (layer 2) and then forwards traffic in both
1831 * directions between the WLAN interface and stdin/stdout of this
1832 * process. Error messages are written to stdout.
1834 * @param argc number of arguments, must be 2
1835 * @param argv arguments only argument is the name of the interface (i.e. 'mon0')
1836 * @return 0 on success (never happens, as we don't return unless aborted), 1 on error
1839 main (int argc, char *argv[])
1841 struct HardwareInfos dev;
1842 char readbuf[MAXLINE];
1847 struct MessageStreamTokenizer *stdin_mst;
1850 memset (&dev, 0, sizeof (dev));
1851 dev.fd_raw = socket (PF_PACKET, SOCK_RAW, htons (ETH_P_ALL));
1852 raw_eno = errno; /* remember for later */
1856 uid_t uid = getuid ();
1857 #ifdef HAVE_SETRESUID
1858 if (0 != setresuid (uid, uid, uid))
1860 fprintf (stderr, "Failed to setresuid: %s\n", strerror (errno));
1861 if (-1 != dev.fd_raw)
1862 (void) close (dev.fd_raw);
1866 if (0 != (setuid (uid) | seteuid (uid)))
1868 fprintf (stderr, "Failed to setuid: %s\n", strerror (errno));
1869 if (-1 != dev.fd_raw)
1870 (void) close (dev.fd_raw);
1876 /* now that we've dropped root rights, we can do error checking */
1880 "You must specify the name of the interface as the first and only argument to this program.\n");
1881 if (-1 != dev.fd_raw)
1882 (void) close (dev.fd_raw);
1886 if (-1 == dev.fd_raw)
1888 fprintf (stderr, "Failed to create raw socket: %s\n", strerror (raw_eno));
1891 if (dev.fd_raw >= FD_SETSIZE)
1893 fprintf (stderr, "File descriptor too large for select (%d > %d)\n",
1894 dev.fd_raw, FD_SETSIZE);
1895 (void) close (dev.fd_raw);
1898 if (0 != test_wlan_interface (argv[1]))
1900 (void) close (dev.fd_raw);
1903 strncpy (dev.iface, argv[1], IFNAMSIZ);
1904 if (0 != open_device_raw (&dev))
1906 (void) close (dev.fd_raw);
1910 /* send MAC address of the WLAN interface to STDOUT first */
1912 struct GNUNET_TRANSPORT_WLAN_HelperControlMessage macmsg;
1914 macmsg.hdr.size = htons (sizeof (macmsg));
1915 macmsg.hdr.type = htons (GNUNET_MESSAGE_TYPE_WLAN_HELPER_CONTROL);
1916 memcpy (&macmsg.mac, &dev.pl_mac, sizeof (struct GNUNET_TRANSPORT_WLAN_MacAddress));
1917 memcpy (write_std.buf, &macmsg, sizeof (macmsg));
1918 write_std.size = sizeof (macmsg);
1921 stdin_mst = mst_create (&stdin_send_hw, &dev);
1927 if ((0 == write_pout.size) && (1 == stdin_open))
1929 FD_SET (STDIN_FILENO, &rfds);
1930 maxfd = MAX (maxfd, STDIN_FILENO);
1932 if (0 == write_std.size)
1934 FD_SET (dev.fd_raw, &rfds);
1935 maxfd = MAX (maxfd, dev.fd_raw);
1938 if (0 < write_std.size)
1940 FD_SET (STDOUT_FILENO, &wfds);
1941 maxfd = MAX (maxfd, STDOUT_FILENO);
1943 if (0 < write_pout.size)
1945 FD_SET (dev.fd_raw, &wfds);
1946 maxfd = MAX (maxfd, dev.fd_raw);
1949 int retval = select (maxfd + 1, &rfds, &wfds, NULL, NULL);
1950 if ((-1 == retval) && (EINTR == errno))
1954 fprintf (stderr, "select failed: %s\n", strerror (errno));
1958 if (FD_ISSET (STDOUT_FILENO, &wfds))
1961 write (STDOUT_FILENO, write_std.buf + write_std.pos,
1962 write_std.size - write_std.pos);
1965 fprintf (stderr, "Failed to write to STDOUT: %s\n", strerror (errno));
1968 write_std.pos += ret;
1969 if (write_std.pos == write_std.size)
1975 if (FD_ISSET (dev.fd_raw, &wfds))
1978 write (dev.fd_raw, write_pout.buf + write_std.pos,
1979 write_pout.size - write_pout.pos);
1982 fprintf (stderr, "Failed to write to WLAN device: %s\n",
1986 write_pout.pos += ret;
1987 if ((write_pout.pos != write_pout.size) && (0 != ret))
1989 /* we should not get partial sends with packet-oriented devices... */
1990 fprintf (stderr, "Write error, partial send: %u/%u\n",
1991 (unsigned int) write_pout.pos,
1992 (unsigned int) write_pout.size);
1995 if (write_pout.pos == write_pout.size)
1998 write_pout.size = 0;
2002 if (FD_ISSET (STDIN_FILENO, &rfds))
2005 read (STDIN_FILENO, readbuf, sizeof (readbuf));
2008 fprintf (stderr, "Read error from STDIN: %s\n", strerror (errno));
2013 /* stop reading... */
2016 mst_receive (stdin_mst, readbuf, ret);
2019 if (FD_ISSET (dev.fd_raw, &rfds))
2021 struct GNUNET_TRANSPORT_WLAN_RadiotapReceiveMessage *rrm;
2024 rrm = (struct GNUNET_TRANSPORT_WLAN_RadiotapReceiveMessage *) write_std.buf;
2026 linux_read (&dev, (unsigned char *) &rrm->frame,
2027 sizeof (write_std.buf)
2028 - sizeof (struct GNUNET_TRANSPORT_WLAN_RadiotapReceiveMessage)
2029 + sizeof (struct GNUNET_TRANSPORT_WLAN_Ieee80211Frame),
2033 fprintf (stderr, "Read error from raw socket: %s\n", strerror (errno));
2036 if ((0 < ret) && (0 == mac_test (&rrm->frame, &dev)))
2038 write_std.size = ret
2039 + sizeof (struct GNUNET_TRANSPORT_WLAN_RadiotapReceiveMessage)
2040 - sizeof (struct GNUNET_TRANSPORT_WLAN_Ieee80211Frame);
2041 rrm->header.size = htons (write_std.size);
2042 rrm->header.type = htons (GNUNET_MESSAGE_TYPE_WLAN_HELPER_DATA);
2046 /* Error handling, try to clean up a bit at least */
2047 mst_destroy (stdin_mst);
2048 (void) close (dev.fd_raw);
2049 return 1; /* we never exit 'normally' */
2052 /* end of gnunet-helper-transport-wlan.c */