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