added scheduler watchdog members to sys/scheduler console dir
[senf.git] / senf / Packets / 80211Bundle / RadiotapPacket.cc
1 // $Id$
2 //
3 // Copyright (C) 2008
4 // Fraunhofer Institute for Open Communication Systems (FOKUS)
5 // Competence Center NETwork research (NET), St. Augustin, GERMANY
6 //     Christian Niephaus <cni@berlios.de>
7 //     Stefan Bund <g0dil@berlios.de>
8 //
9 // This program is free software; you can redistribute it and/or modify
10 // it under the terms of the GNU General Public License as published by
11 // the Free Software Foundation; either version 2 of the License, or
12 // (at your option) any later version.
13 //
14 // This program is distributed in the hope that it will be useful,
15 // but WITHOUT ANY WARRANTY; without even the implied warranty of
16 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17 // GNU General Public License for more details.
18 //
19 // You should have received a copy of the GNU General Public License
20 // along with this program; if not, write to the
21 // Free Software Foundation, Inc.,
22 // 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
23
24 // Definition of RadiotapPacket non-inline non-template functions
25
26 #include "RadiotapPacket.hh"
27 //#include "RadiotapPacket.ih"
28
29 // Custom includes
30 #include "WLANPacket.hh"
31 #include <boost/io/ios_state.hpp>
32 #include <memory.h>
33
34 extern "C" {
35 #   include "radiotap/radiotap_iter.h"
36 }
37
38 #define prefix_
39 //-/////////////////////////////////////////////////////////////////////////////////////////////////
40
41 //-/////////////////////////////////////////////////////////////////////////////////////////////////
42 // Offset table management
43
44 prefix_ senf::RadiotapPacketParser::OffsetTable &
45 senf::RadiotapPacketParser::offsetTable(boost::uint32_t presentFlags)
46 {
47     typedef std::map<boost::uint32_t, OffsetTable> OffsetMap;
48     static OffsetMap offsetMap;
49
50     OffsetMap::iterator i (offsetMap.find(presentFlags));
51     if (i == offsetMap.end())
52         i = offsetMap.insert(std::make_pair(presentFlags, OffsetTable())).first;
53     return i->second;
54 }
55
56 prefix_ void senf::RadiotapPacketParser::parseOffsetTable(boost::uint8_t * data, int maxLength,
57                                                           OffsetTable & table)
58 {
59     struct ieee80211_radiotap_iterator iter;
60     ieee80211_radiotap_iterator_init(&iter,
61                                      (struct ieee80211_radiotap_header *)data,
62                                      maxLength,
63                                      0);
64     unsigned size (8u);
65     while (ieee80211_radiotap_iterator_next(&iter) == 0) {
66         if (iter.is_radiotap_ns &&
67             iter.this_arg_index <= int(senf::RadiotapPacketParser::MAX_INDEX))
68             table[iter.this_arg_index] = iter.this_arg - data;
69         // We need to set size here in the loop since the iter fields are only valid
70         // when at least one present bit is set ...
71         size = iter.this_arg - data + iter.this_arg_size;
72     }
73     table[MAX_INDEX+1] = size;
74 }
75
76 prefix_ void senf::RadiotapPacketParser::buildOffsetTable(boost::uint32_t presentFlags,
77                                                           OffsetTable & table)
78 {
79     SENF_ASSERT(!(presentFlags & ( (1<<IEEE80211_RADIOTAP_RADIOTAP_NAMESPACE) |
80                                    (1<<IEEE80211_RADIOTAP_VENDOR_NAMESPACE) |
81                                    (1<<IEEE80211_RADIOTAP_EXT) )),
82                 "Extended or vendor fields not supported");
83
84     struct ieee80211_radiotap_header header;
85     memset(&header, 0, sizeof(header));
86     // header.it_version = 0;
87
88     // Iterating this packet will generate invalid addresses but we don't care since neither
89     // radiotap.c nor we will ever dereference those pointers, we just calculate the offsets.
90     // This works, as long as we don't support extension headers ...
91     header.it_len = 0xFFFF;
92     header.it_present = presentFlags;
93
94     parseOffsetTable((boost::uint8_t*)&header, header.it_len, table);
95 }
96
97 //-/////////////////////////////////////////////////////////////////////////////////////////////////
98 // senf::RadiotapPacketParser
99
100 unsigned const senf::RadiotapPacketParser_Header::FIELD_SIZE[] = {
101     8, 1, 1, 4, 2, 1, 1, 2, 2, 2, 1, 1, 1, 1, 2, 2, 1, 1 };
102
103 prefix_ senf::UInt32Parser senf::RadiotapPacketParser::init_fcs()
104 {
105     if (!has_fcs()) {
106         protect(), data().insert(data().end(), 4u, 0u);
107         init_flags().fcsAtEnd_() = true;
108     }
109     return fcs();
110 }
111
112 prefix_ void senf::RadiotapPacketParser::disable_fcs()
113 {
114     if (has_fcs()) {
115         validate(RadiotapPacketParser_Header::fixed_bytes+4);
116         data().erase(data().end()-4, data().end());
117         flags().fcsAtEnd_() = false;
118     }
119 }
120
121 prefix_ senf::RadiotapPacketParser::OffsetTable const &
122 senf::RadiotapPacketParser::getTable(boost::uint32_t presentFlags)
123     const
124 {
125     OffsetTable & table(offsetTable(presentFlags));
126     if (! table[MAX_INDEX+1])
127         buildOffsetTable(presentFlags, table);
128     return table;
129 }
130
131 prefix_ void senf::RadiotapPacketParser::insertRemoveBytes(unsigned from , unsigned to, int bytes)
132 {
133     data_iterator b (i() + from);
134     data_iterator e (i() + to);
135     if (bytes >= 0) {
136         // Insert some bytes cleaning the old bytes to 0 first
137         std::fill(b, e,  0u);
138         if (bytes > 0)
139             // need to protect the parser since data().insert() invalidates iterators
140             protect(), data().insert(e, bytes, 0u);
141     }
142     else { // bytes < 0
143         // Remove some bytes ...
144         // remember: bytes is negative ...
145         if (b < e + bytes)
146             std::fill(b, e + bytes, 0u);
147         data().erase(e + bytes, e);
148     }
149 }
150
151 prefix_ void senf::RadiotapPacketParser::updatePresentFlags(boost::uint32_t flags)
152 {
153     if (flags == presentFlags())
154         return;
155     validate(bytes());
156
157     OffsetTable const & oldTable (currentTable());
158     OffsetTable const & newTable (getTable(flags));
159     unsigned b (RadiotapPacketParser_Header::fixed_bytes);
160     int cumulativeNewBytes (0);
161
162     for (unsigned index (0); index <= MAX_INDEX; ++index) {
163         // Skip any unchanged fields
164         for (; index <= MAX_INDEX+1
165                  && ((oldTable[index] == 0 && newTable[index] == 0)
166                      || (oldTable[index]+cumulativeNewBytes == newTable[index])); ++index)
167             if (newTable[index] != 0)
168                 b = newTable[index] + FIELD_SIZE[index];
169         if (index > MAX_INDEX+1)
170             break;
171         // Now skip over all changed fields
172         // (The condition index <= MAX_INDEX is not needed here since the last
173         // table entry MAX_INDEX+1 is always != 0 in both tables)
174         for (; ! (oldTable[index]!=0 && newTable[index]!=0); ++index) ;
175         // index now either points to
176         // a) an entry set in both tables
177         // b) at the end of the table which contains the total length
178         // (remember: the table has a size of MAX_INDEX+2 entries !!)
179         // in both cases, the difference between the new and old size
180         // is found from the difference between the old and the new table
181         // entry
182         int newBytes (newTable[index] - oldTable[index] - cumulativeNewBytes);
183         insertRemoveBytes(b, oldTable[index] + cumulativeNewBytes, newBytes);
184         cumulativeNewBytes += newBytes;
185         b = newTable[index] + FIELD_SIZE[index];
186     }
187     length() += cumulativeNewBytes;
188     presentFlags() = flags;
189     currentTable_ = &newTable;
190 }
191
192 //-/////////////////////////////////////////////////////////////////////////////////////////////////
193 // senf::RadiotapPacketType
194
195 prefix_ void senf::RadiotapPacketType::dump(packet p, std::ostream &os)
196 {
197     boost::io::ios_all_saver ias(os);
198     os << "Radiotap:\n"
199        << senf::fieldName("version") << unsigned(p->version()) << '\n'
200        << senf::fieldName("length")  << unsigned(p->length()) << '\n';
201
202 #   define FIELD(name, sign, desc)                                      \
203         if (p->name ## Present())                                       \
204             os << senf::fieldName(desc) << sign(p->name()) << '\n';
205
206 #   define ENTER(name)                                                  \
207         if (p->name ## Present()) {                                     \
208             packet::Parser::name ## _t subparser (p->name());
209
210 #   define SUBFIELD(name, sign, desc)                                   \
211         os << senf::fieldName(desc) << sign(subparser.name()) << '\n';
212
213 #   define LEAVE()                                                      \
214         }
215
216 #   define START_FLAGS(desc)                                            \
217         os << senf::fieldName(desc);
218
219 #   define FLAG(name, desc)                                             \
220         if (subparser.name()) os << desc " "
221
222 #   define END_FLAGS()                                                  \
223         os << '\n';
224
225     FIELD           ( tsft,              boost::uint64_t, "MAC timestamp"        );
226     ENTER           ( flags                                                      );
227       START_FLAGS   (                                     "flags"                );
228         FLAG        (     shortGI,                            "ShortGI"          );
229         FLAG        (     badFCS,                             "BadFCS"           );
230         FLAG        (     fcsAtEnd,                           "FCSatEnd"         );
231         FLAG        (     fragmentation,                      "Frag"             );
232         FLAG        (     wep,                                "WEP"              );
233         FLAG        (     shortPreamble,                      "ShortPreamble"    );
234         FLAG        (     cfp,                                "CFP"              );
235       END_FLAGS     (                                                            );
236     LEAVE           (                                                            );
237     FIELD           ( rate,              unsigned,        "rate"                 );
238     ENTER           ( channelOptions                                             );
239       SUBFIELD      (     freq,          unsigned,        "channel frequency"    );
240       START_FLAGS   (                                     "channel flags"        );
241         FLAG        (     flag2ghz,                           "2GHz"             );
242         FLAG        (     ofdm,                               "OFDM"             );
243         FLAG        (     cck,                                "CCK"              );
244         FLAG        (     turbo,                              "Turbo"            );
245         FLAG        (     quarterRateChannel,                 "Rate/4"           );
246         FLAG        (     halfRateChannel,                    "Rate/2"           );
247         FLAG        (     gsm,                                "GSM"              );
248         FLAG        (     staticTurbo,                        "StaticTurbo"      );
249         FLAG        (     gfsk,                               "GFSK"             );
250         FLAG        (     cckOfdm,                            "CCK+OFDM"         );
251         FLAG        (     passive,                            "Passive"          );
252         FLAG        (     flag5ghz,                           "5GHz"             );
253       END_FLAGS     (                                                            );
254     LEAVE           (                                                            );
255     FIELD           ( fhss,              unsigned,        "FHSS"                 );
256     FIELD           ( dbmAntennaSignal,  signed,          "antenna signal (dBm)" );
257     FIELD           ( dbmAntennaNoise,   signed,          "antenna noise (dBm)"  );
258     FIELD           ( lockQuality,       unsigned,        "lock quality"         );
259     FIELD           ( txAttenuation,     unsigned,        "tx attenuation"       );
260     FIELD           ( dbTxAttenuation,   unsigned,        "tx attenuation (dB)"  );
261     FIELD           ( dbmTxAttenuation,  signed,          "tx attenuation (dBm)" );
262     FIELD           ( antenna,           unsigned,        "antenna"              );
263     FIELD           ( dbAntennaSignal,   unsigned,        "antenna signal (dB)"  );
264     FIELD           ( dbAntennaNoise,    unsigned,        "antenna noise (dB)"   );
265     ENTER           ( rxFlags                                                    );
266       START_FLAGS   (                                     "rx flags"             );
267         FLAG        (     badPlcp,                            "BadPLCP"          );
268       END_FLAGS     (                                                            );
269     LEAVE           (                                                            );
270     ENTER           ( txFlags                                                    );
271       START_FLAGS   (                                     "tx flags"             );
272         FLAG        (     fail,                               "Fail"             );
273         FLAG        (     txRts,                              "RTS"              );
274         FLAG        (     txCts,                              "CTS"              );
275       END_FLAGS     (                                                            );
276     LEAVE           (                                                            );
277     FIELD           ( rtsRetries,        unsigned,        "rts retries"          );
278     FIELD           ( dataRetries,       unsigned,        "data retries"         );
279
280     if (p->flagsPresent() && p->flags().fcsAtEnd())
281         os << senf::fieldName("fcs") << unsigned(p->fcs()) << '\n';
282
283 #   undef END_FLAGS
284 #   undef FLAG
285 #   undef START_FLAGS
286 #   undef LEAVE
287 #   undef SUBFIELD
288 #   undef ENTER
289 #   undef FIELD
290 }
291
292 prefix_ void senf::RadiotapPacketType::init(packet p)
293 {
294     // ?? Why the heck do we need the +0? Otherwise we get an
295     // 'undefined reference to 'RadiotapPacketParser_Header::fixed_bytes'
296     p->length() << RadiotapPacketParser_Header::fixed_bytes+0;
297 }
298
299 prefix_ senf::PacketInterpreterBase::factory_t senf::RadiotapPacketType::nextPacketType(packet p)
300 {
301     static factory_t frameTypeFactory[] = { WLANPacket_MgtFrame::factory(),
302                                             WLANPacket_CtrlFrame::factory(),
303                                             WLANPacket_DataFrame::factory(),
304                                             no_factory() };
305     return frameTypeFactory[p->frameType()];
306 }
307
308 prefix_ senf::RadiotapPacketType::optional_range
309 senf::RadiotapPacketType::nextPacketRange(packet p)
310 {
311     parser rtParser (p.parser());
312     size_type h (senf::bytes(rtParser));
313     size_type t (rtParser.flagsPresent() && rtParser.flags().fcsAtEnd() ? 4 : 0);
314     return p.size() <= h+t
315         ? no_range()
316         : optional_range( range(p.data().begin() + h, p.data().end() - t) );
317 }
318
319 //-/////////////////////////////////////////////////////////////////////////////////////////////////
320 #undef prefix_
321
322 \f
323 // Local Variables:
324 // mode: c++
325 // fill-column: 100
326 // c-file-style: "senf"
327 // indent-tabs-mode: nil
328 // ispell-local-dictionary: "american"
329 // compile-command: "scons -u test"
330 // comment-column: 40
331 // End: