madwifi plugin: Plugin for detailed information from the MadWifi driver.
[collectd.git] / src / madwifi.c
1 /**
2  * collectd - src/madwifi.c
3  * Copyright (C) 2009  Ondrej 'SanTiago' Zajicek
4  *
5  * This program is free software; you can redistribute it and/or modify it
6  * under the terms of the GNU General Public License as published by the
7  * Free Software Foundation; only version 2 of the License is applicable.
8  *
9  * This program is distributed in the hope that it will be useful, but
10  * WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License along
15  * with this program; if not, write to the Free Software Foundation, Inc.,
16  * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
17  *
18  * Author:
19  *   Ondrej 'SanTiago' Zajicek <santiago@crfreenet.org>
20  *
21  *   based on some code from interfaces.c (collectd) and Madwifi driver
22  **/
23
24
25 /**
26  * There are several data streams provided by Madwifi plugin, some are 
27  * connected to network interface, some are connected to each node
28  * associated to that interface. Nodes represents other sides in
29  * wireless communication, for example on network interface in AP mode,
30  * there is one node for each associated station. Node data streams
31  * contain MAC address of the node as the last part  of the type_instance
32  * field.
33  *
34  * Inteface data streams:
35  *      ath_nodes       The number of associated nodes
36  *      ath_stat        Device statistic counters
37  *
38  * Node data streams:
39  *      node_octets     RX and TX data count (octets/bytes)
40  *      node_rssi       Received RSSI of the node
41  *      node_tx_rate    Reported TX rate to that node
42  *      node_stat       Node statistic counters
43  *
44  * Both statistic counters have type instances for each counter returned
45  * by Madwifi. See madwifi.h for content of ieee80211_nodestats, 
46  * ieee80211_stats and ath_stats structures. Type instances use the same
47  * name as fields in these structures (like ns_rx_dup). Some fields are
48  * not reported, because they are not counters (like ns_tx_deauth_code
49  * or ast_tx_rssi). Fields ns_rx_bytes and ns_tx_bytes are reported as
50  * node_octets data stream instead of type instance of node_stat.
51  * Statistics are not logged when they are zero.
52  * 
53  * There are two sets of these counters - the first 'WatchList' is a
54  * set of counters that are individually logged. The second 'MiscList'
55  * is a set of counters that are summed together and the sum is logged.
56  * By default, the most important statistics are in the WatchList and 
57  * many error statistics are in MiscList. There are also many statistics
58  * that are not in any of these sets, so they are not monitored by default.
59  * It is possible to alter these lists using configuration options:
60  *
61  *      WatchAdd X      Adds X to WachList
62  *      WatchRemove X   Removes X from WachList
63  *      WatchSet All    Adds all statistics to WatchList
64  *      WatchSet None   Removes all statistics from WachList
65  *
66  * There are also Misc* variants fo these options, they modifies MiscList
67  * instead of WatchList.
68  *
69  * Example:
70  *
71  *      WatchSet None
72  *      WatchAdd node_octets
73  *      WatchAdd node_rssi
74  *      WatchAdd is_rx_acl
75  *      WatchAdd is_scan_active
76  *
77  * That causes that just the four mentioned data streams are logged.
78  *
79  *
80  * By default, madwifi plugin enumerates network interfaces using /sys
81  * filesystem. Configuration option DisableSysfs can change this to use
82  * /proc filesystem (which is useful for example when running on Linux
83  * 2.4). But without /sys filesystem, Madwifi plugin cannot check whether
84  * given interface is madwifi interface and there are private ioctls used,
85  * which may do something completely different on non-madwifi devices.
86  * Therefore, option DisableSysfs should be used together with option
87  * Interface, to limit found interfaces to madwifi interfaces only.
88  **/
89
90
91 #include "collectd.h"
92 #include "common.h"
93 #include "plugin.h"
94 #include "configfile.h"
95 #include "utils_ignorelist.h"
96
97 #include <dirent.h>
98 #include <sys/ioctl.h>
99 #include <sys/socket.h>
100
101 #if !KERNEL_LINUX
102 # error "No applicable input method."
103 #endif
104
105 #include <linux/wireless.h>
106 #include "madwifi.h"
107
108
109
110 struct stat_spec {
111         uint16_t flags;
112         uint16_t offset;
113         const char *name;
114 };
115
116
117 #define OFFSETOF(s, i) ((size_t)&((s *)0)->i)
118
119 #define FLAG(i)  (((uint32_t) 1) << ((i) % 32))
120
121 #define SPC_STAT 0
122 #define NOD_STAT 1
123 #define IFA_STAT 2
124 #define ATH_STAT 3
125 #define SRC_MASK 3
126
127 /* By default, the item is disabled */
128 #define D 0
129
130 /* By default, the item is logged */
131 #define LOG 4
132
133 /* By default, the item is summed with other such items and logged together */
134 #define SU 8
135
136 #define SS_STAT(flags, name) { flags | SPC_STAT, 0, #name }
137 #define NS_STAT(flags, name) { flags | NOD_STAT, OFFSETOF(struct ieee80211_nodestats, name), #name }
138 #define IS_STAT(flags, name) { flags | IFA_STAT, OFFSETOF(struct ieee80211_stats, name), #name }
139 #define AS_STAT(flags, name) { flags | ATH_STAT, OFFSETOF(struct ath_stats, name), #name }
140
141
142 /*
143  * (Module-)Global variables
144  */
145
146 /* Indices of special stats in specs array */
147 #define STAT_NODE_OCTETS        0
148 #define STAT_NODE_RSSI          1
149 #define STAT_NODE_TX_RATE       2
150 #define STAT_ATH_NODES          3
151 #define STAT_NS_RX_BEACONS      4
152 #define STAT_AST_ANT_RX         5
153 #define STAT_AST_ANT_TX         6
154
155 static struct stat_spec specs[] = {
156
157 /* Special statistics */
158 SS_STAT(LOG, node_octets),              /* rx and tx data count (bytes) */
159 SS_STAT(LOG, node_rssi),                /* received RSSI of the node */
160 SS_STAT(LOG, node_tx_rate),             /* used tx rate to the node */
161 SS_STAT(LOG, ath_nodes),                /* the number of associated nodes */
162 SS_STAT(D,   ns_rx_beacons),            /* rx beacon frames */
163 SS_STAT(LOG, ast_ant_rx),               /* rx frames with antenna */
164 SS_STAT(LOG, ast_ant_tx),               /* tx frames with antenna */
165
166 /* Node statistics */
167 NS_STAT(LOG, ns_rx_data),               /* rx data frames */
168 NS_STAT(LOG, ns_rx_mgmt),               /* rx management frames */
169 NS_STAT(LOG, ns_rx_ctrl),               /* rx control frames */
170 NS_STAT(D,   ns_rx_ucast),              /* rx unicast frames */
171 NS_STAT(D,   ns_rx_mcast),              /* rx multi/broadcast frames */
172 NS_STAT(D,   ns_rx_proberesp),          /* rx probe response frames */
173 NS_STAT(LOG, ns_rx_dup),                /* rx discard because it's a dup */
174 NS_STAT(SU,  ns_rx_noprivacy),          /* rx w/ wep but privacy off */
175 NS_STAT(SU,  ns_rx_wepfail),            /* rx wep processing failed */
176 NS_STAT(SU,  ns_rx_demicfail),          /* rx demic failed */
177 NS_STAT(SU,  ns_rx_decap),              /* rx decapsulation failed */
178 NS_STAT(SU,  ns_rx_defrag),             /* rx defragmentation failed */
179 NS_STAT(D,   ns_rx_disassoc),           /* rx disassociation */
180 NS_STAT(D,   ns_rx_deauth),             /* rx deauthentication */
181 NS_STAT(SU,  ns_rx_decryptcrc),         /* rx decrypt failed on crc */
182 NS_STAT(SU,  ns_rx_unauth),             /* rx on unauthorized port */
183 NS_STAT(SU,  ns_rx_unencrypted),        /* rx unecrypted w/ privacy */
184 NS_STAT(LOG, ns_tx_data),               /* tx data frames */
185 NS_STAT(LOG, ns_tx_mgmt),               /* tx management frames */
186 NS_STAT(D,   ns_tx_ucast),              /* tx unicast frames */
187 NS_STAT(D,   ns_tx_mcast),              /* tx multi/broadcast frames */
188 NS_STAT(D,   ns_tx_probereq),           /* tx probe request frames */
189 NS_STAT(D,   ns_tx_uapsd),              /* tx on uapsd queue */
190 NS_STAT(SU,  ns_tx_novlantag),          /* tx discard due to no tag */
191 NS_STAT(SU,  ns_tx_vlanmismatch),       /* tx discard due to of bad tag */
192 NS_STAT(D,   ns_tx_eosplost),           /* uapsd EOSP retried out */
193 NS_STAT(D,   ns_ps_discard),            /* ps discard due to of age */
194 NS_STAT(D,   ns_uapsd_triggers),        /* uapsd triggers */
195 NS_STAT(LOG, ns_tx_assoc),              /* [re]associations */
196 NS_STAT(LOG, ns_tx_auth),               /* [re]authentications */
197 NS_STAT(D,   ns_tx_deauth),             /* deauthentications */
198 NS_STAT(D,   ns_tx_disassoc),           /* disassociations */
199 NS_STAT(D,   ns_psq_drops),             /* power save queue drops */
200
201 /* Iface statistics */
202 IS_STAT(SU,  is_rx_badversion),         /* rx frame with bad version */
203 IS_STAT(SU,  is_rx_tooshort),           /* rx frame too short */
204 IS_STAT(LOG, is_rx_wrongbss),           /* rx from wrong bssid */
205 IS_STAT(LOG, is_rx_dup),                /* rx discard due to it's a dup */
206 IS_STAT(SU,  is_rx_wrongdir),           /* rx w/ wrong direction */
207 IS_STAT(D,   is_rx_mcastecho),          /* rx discard due to of mcast echo */
208 IS_STAT(SU,  is_rx_notassoc),           /* rx discard due to sta !assoc */
209 IS_STAT(SU,  is_rx_noprivacy),          /* rx w/ wep but privacy off */
210 IS_STAT(SU,  is_rx_unencrypted),        /* rx w/o wep and privacy on */
211 IS_STAT(SU,  is_rx_wepfail),            /* rx wep processing failed */
212 IS_STAT(SU,  is_rx_decap),              /* rx decapsulation failed */
213 IS_STAT(D,   is_rx_mgtdiscard),         /* rx discard mgt frames */
214 IS_STAT(D,   is_rx_ctl),                /* rx discard ctrl frames */
215 IS_STAT(D,   is_rx_beacon),             /* rx beacon frames */
216 IS_STAT(D,   is_rx_rstoobig),           /* rx rate set truncated */
217 IS_STAT(SU,  is_rx_elem_missing),       /* rx required element missing*/
218 IS_STAT(SU,  is_rx_elem_toobig),        /* rx element too big */
219 IS_STAT(SU,  is_rx_elem_toosmall),      /* rx element too small */
220 IS_STAT(LOG, is_rx_elem_unknown),       /* rx element unknown */
221 IS_STAT(SU,  is_rx_badchan),            /* rx frame w/ invalid chan */
222 IS_STAT(SU,  is_rx_chanmismatch),       /* rx frame chan mismatch */
223 IS_STAT(SU,  is_rx_nodealloc),          /* rx frame dropped */
224 IS_STAT(LOG, is_rx_ssidmismatch),       /* rx frame ssid mismatch  */
225 IS_STAT(SU,  is_rx_auth_unsupported),   /* rx w/ unsupported auth alg */
226 IS_STAT(SU,  is_rx_auth_fail),          /* rx sta auth failure */
227 IS_STAT(SU,  is_rx_auth_countermeasures),/* rx auth discard due to CM */
228 IS_STAT(SU,  is_rx_assoc_bss),          /* rx assoc from wrong bssid */
229 IS_STAT(SU,  is_rx_assoc_notauth),      /* rx assoc w/o auth */
230 IS_STAT(SU,  is_rx_assoc_capmismatch),  /* rx assoc w/ cap mismatch */
231 IS_STAT(SU,  is_rx_assoc_norate),       /* rx assoc w/ no rate match */
232 IS_STAT(SU,  is_rx_assoc_badwpaie),     /* rx assoc w/ bad WPA IE */
233 IS_STAT(LOG, is_rx_deauth),             /* rx deauthentication */
234 IS_STAT(LOG, is_rx_disassoc),           /* rx disassociation */
235 IS_STAT(SU,  is_rx_badsubtype),         /* rx frame w/ unknown subtype*/
236 IS_STAT(SU,  is_rx_nobuf),              /* rx failed for lack of buf */
237 IS_STAT(SU,  is_rx_decryptcrc),         /* rx decrypt failed on crc */
238 IS_STAT(D,   is_rx_ahdemo_mgt),         /* rx discard ahdemo mgt frame*/
239 IS_STAT(SU,  is_rx_bad_auth),           /* rx bad auth request */
240 IS_STAT(SU,  is_rx_unauth),             /* rx on unauthorized port */
241 IS_STAT(SU,  is_rx_badkeyid),           /* rx w/ incorrect keyid */
242 IS_STAT(D,   is_rx_ccmpreplay),         /* rx seq# violation (CCMP), */
243 IS_STAT(D,   is_rx_ccmpformat),         /* rx format bad (CCMP), */
244 IS_STAT(D,   is_rx_ccmpmic),            /* rx MIC check failed (CCMP), */
245 IS_STAT(D,   is_rx_tkipreplay),         /* rx seq# violation (TKIP), */
246 IS_STAT(D,   is_rx_tkipformat),         /* rx format bad (TKIP), */
247 IS_STAT(D,   is_rx_tkipmic),            /* rx MIC check failed (TKIP), */
248 IS_STAT(D,   is_rx_tkipicv),            /* rx ICV check failed (TKIP), */
249 IS_STAT(D,   is_rx_badcipher),          /* rx failed due to of key type */
250 IS_STAT(D,   is_rx_nocipherctx),        /* rx failed due to key !setup */
251 IS_STAT(D,   is_rx_acl),                /* rx discard due to of acl policy */
252 IS_STAT(D,   is_rx_ffcnt),              /* rx fast frames */
253 IS_STAT(SU,  is_rx_badathtnl),          /* driver key alloc failed */
254 IS_STAT(SU,  is_tx_nobuf),              /* tx failed for lack of buf */
255 IS_STAT(SU,  is_tx_nonode),             /* tx failed for no node */
256 IS_STAT(SU,  is_tx_unknownmgt),         /* tx of unknown mgt frame */
257 IS_STAT(SU,  is_tx_badcipher),          /* tx failed due to of key type */
258 IS_STAT(SU,  is_tx_nodefkey),           /* tx failed due to no defkey */
259 IS_STAT(SU,  is_tx_noheadroom),         /* tx failed due to no space */
260 IS_STAT(D,   is_tx_ffokcnt),            /* tx fast frames sent success */
261 IS_STAT(D,   is_tx_fferrcnt),           /* tx fast frames sent success */
262 IS_STAT(D,   is_scan_active),           /* active scans started */
263 IS_STAT(D,   is_scan_passive),          /* passive scans started */
264 IS_STAT(D,   is_node_timeout),          /* nodes timed out inactivity */
265 IS_STAT(D,   is_crypto_nomem),          /* no memory for crypto ctx */
266 IS_STAT(D,   is_crypto_tkip),           /* tkip crypto done in s/w */
267 IS_STAT(D,   is_crypto_tkipenmic),      /* tkip en-MIC done in s/w */
268 IS_STAT(D,   is_crypto_tkipdemic),      /* tkip de-MIC done in s/w */
269 IS_STAT(D,   is_crypto_tkipcm),         /* tkip counter measures */
270 IS_STAT(D,   is_crypto_ccmp),           /* ccmp crypto done in s/w */
271 IS_STAT(D,   is_crypto_wep),            /* wep crypto done in s/w */
272 IS_STAT(D,   is_crypto_setkey_cipher),  /* cipher rejected key */
273 IS_STAT(D,   is_crypto_setkey_nokey),   /* no key index for setkey */
274 IS_STAT(D,   is_crypto_delkey),         /* driver key delete failed */
275 IS_STAT(D,   is_crypto_badcipher),      /* unknown cipher */
276 IS_STAT(D,   is_crypto_nocipher),       /* cipher not available */
277 IS_STAT(D,   is_crypto_attachfail),     /* cipher attach failed */
278 IS_STAT(D,   is_crypto_swfallback),     /* cipher fallback to s/w */
279 IS_STAT(D,   is_crypto_keyfail),        /* driver key alloc failed */
280 IS_STAT(D,   is_crypto_enmicfail),      /* en-MIC failed */
281 IS_STAT(SU,  is_ibss_capmismatch),      /* merge failed-cap mismatch */
282 IS_STAT(SU,  is_ibss_norate),           /* merge failed-rate mismatch */
283 IS_STAT(D,   is_ps_unassoc),            /* ps-poll for unassoc. sta */
284 IS_STAT(D,   is_ps_badaid),             /* ps-poll w/ incorrect aid */
285 IS_STAT(D,   is_ps_qempty),             /* ps-poll w/ nothing to send */
286
287 /* Atheros statistics */
288 AS_STAT(D,   ast_watchdog),             /* device reset by watchdog */
289 AS_STAT(D,   ast_hardware),             /* fatal hardware error interrupts */
290 AS_STAT(D,   ast_bmiss),                /* beacon miss interrupts */
291 AS_STAT(D,   ast_rxorn),                /* rx overrun interrupts */
292 AS_STAT(D,   ast_rxeol),                /* rx eol interrupts */
293 AS_STAT(D,   ast_txurn),                /* tx underrun interrupts */
294 AS_STAT(D,   ast_mib),                  /* mib interrupts */
295 AS_STAT(D,   ast_tx_packets),           /* packet sent on the interface */
296 AS_STAT(D,   ast_tx_mgmt),              /* management frames transmitted */
297 AS_STAT(LOG, ast_tx_discard),           /* frames discarded prior to assoc */
298 AS_STAT(SU,  ast_tx_invalid),           /* frames discarded due to is device gone */
299 AS_STAT(SU,  ast_tx_qstop),             /* tx queue stopped because it's full */
300 AS_STAT(SU,  ast_tx_encap),             /* tx encapsulation failed */
301 AS_STAT(SU,  ast_tx_nonode),            /* tx failed due to of no node */
302 AS_STAT(SU,  ast_tx_nobuf),             /* tx failed due to of no tx buffer (data), */
303 AS_STAT(SU,  ast_tx_nobufmgt),          /* tx failed due to of no tx buffer (mgmt),*/
304 AS_STAT(LOG, ast_tx_xretries),          /* tx failed due to of too many retries */
305 AS_STAT(SU,  ast_tx_fifoerr),           /* tx failed due to of FIFO underrun */
306 AS_STAT(SU,  ast_tx_filtered),          /* tx failed due to xmit filtered */
307 AS_STAT(LOG, ast_tx_shortretry),        /* tx on-chip retries (short), */
308 AS_STAT(LOG, ast_tx_longretry),         /* tx on-chip retries (long), */
309 AS_STAT(SU,  ast_tx_badrate),           /* tx failed due to of bogus xmit rate */
310 AS_STAT(D,   ast_tx_noack),             /* tx frames with no ack marked */
311 AS_STAT(D,   ast_tx_rts),               /* tx frames with rts enabled */
312 AS_STAT(D,   ast_tx_cts),               /* tx frames with cts enabled */
313 AS_STAT(D,   ast_tx_shortpre),          /* tx frames with short preamble */
314 AS_STAT(LOG, ast_tx_altrate),           /* tx frames with alternate rate */
315 AS_STAT(D,   ast_tx_protect),           /* tx frames with protection */
316 AS_STAT(SU,  ast_rx_orn),               /* rx failed due to of desc overrun */
317 AS_STAT(LOG, ast_rx_crcerr),            /* rx failed due to of bad CRC */
318 AS_STAT(SU,  ast_rx_fifoerr),           /* rx failed due to of FIFO overrun */
319 AS_STAT(SU,  ast_rx_badcrypt),          /* rx failed due to of decryption */
320 AS_STAT(SU,  ast_rx_badmic),            /* rx failed due to of MIC failure */
321 AS_STAT(LOG, ast_rx_phyerr),            /* rx PHY error summary count */
322 AS_STAT(SU,  ast_rx_tooshort),          /* rx discarded due to frame too short */
323 AS_STAT(SU,  ast_rx_toobig),            /* rx discarded due to frame too large */
324 AS_STAT(SU,  ast_rx_nobuf),             /* rx setup failed due to of no skbuff */
325 AS_STAT(D,   ast_rx_packets),           /* packet recv on the interface */
326 AS_STAT(D,   ast_rx_mgt),               /* management frames received */
327 AS_STAT(D,   ast_rx_ctl),               /* control frames received */
328 AS_STAT(D,   ast_be_xmit),              /* beacons transmitted */
329 AS_STAT(SU,  ast_be_nobuf),             /* no skbuff available for beacon */
330 AS_STAT(D,   ast_per_cal),              /* periodic calibration calls */
331 AS_STAT(D,   ast_per_calfail),          /* periodic calibration failed */
332 AS_STAT(D,   ast_per_rfgain),           /* periodic calibration rfgain reset */
333 AS_STAT(D,   ast_rate_calls),           /* rate control checks */
334 AS_STAT(D,   ast_rate_raise),           /* rate control raised xmit rate */
335 AS_STAT(D,   ast_rate_drop),            /* rate control dropped xmit rate */
336 AS_STAT(D,   ast_ant_defswitch),        /* rx/default antenna switches */
337 AS_STAT(D,   ast_ant_txswitch)          /* tx antenna switches */
338 };
339
340 /* Bounds between SS, NS, IS and AS stats in stats array */
341 static int bounds[4];
342
343 #define WL_LEN 6
344 /* Bitmasks for logged and error items */
345 static uint32_t watch_items[WL_LEN];
346 static uint32_t misc_items[WL_LEN];
347
348
349 static const char *config_keys[] =
350 {
351         "Interface",
352         "IgnoreSelected",
353         "DisableSysfs",
354         "WatchAdd",
355         "WatchRemove",
356         "WatchSet",
357         "MiscAdd",
358         "MiscRemove",
359         "MiscSet",
360         NULL
361 };
362 static int config_keys_num = 9;
363
364 static ignorelist_t *ignorelist;
365
366 static int use_sysfs = 1;
367 static int init_state = 0;
368
369 static inline int item_watched(int i)
370 {
371         return watch_items[i / 32] & FLAG (i);
372 }
373
374 static inline int item_summed(int i)
375 {
376         return misc_items[i / 32] & FLAG (i);
377 }
378
379 static inline void watchlist_add (uint32_t *wl, int item)
380 {
381         wl[item / 32] |= FLAG (item);
382 }
383
384 static inline void watchlist_remove (uint32_t *wl, int item)
385 {
386         wl[item / 32] &= ~FLAG (item);
387 }
388
389 static inline void watchlist_set (uint32_t *wl, uint32_t val)
390 {
391         int i;
392         for (i = 0; i < WL_LEN; i++)
393                 wl[i] = val;
394 }
395
396 /* This is horribly inefficient, but it is called only during configuration */
397 static int watchitem_find (const char *name)
398 {
399         int max = sizeof (specs) / sizeof (struct stat_spec);
400         int i;
401
402         for (i = 0; i < max; i++)
403                 if (strcasecmp (name, specs[i].name) == 0)
404                         return i;
405
406         return -1;
407 }
408
409
410 /* Collectd hooks */
411
412 /* We need init function called before madwifi_config */
413
414 static int madwifi_real_init (void)
415 {
416         int max = sizeof (specs) / sizeof (struct stat_spec);
417         int i;
418
419         for (i = 0; i < 4; i++)
420                 bounds[i] = 0;
421
422         watchlist_set(watch_items, 0);
423         watchlist_set(misc_items, 0);
424
425         for (i = 0; i < max; i++)
426         {
427                 bounds[specs[i].flags & SRC_MASK] = i;
428
429                 if (specs[i].flags & LOG)
430                         watch_items[i / 32] |= FLAG (i);
431
432                 if (specs[i].flags & SU)
433                         misc_items[i / 32] |= FLAG (i);
434         }
435
436         for (i = 0; i < 4; i++)
437                 bounds[i]++;
438
439         return (0);
440 }
441
442 static int bool_arg (const char *value)
443 {
444         return ((strcasecmp (value, "True") == 0)
445                 || (strcasecmp (value, "Yes") == 0)
446                 || (strcasecmp (value, "On") == 0));
447 }
448
449 static int madwifi_config (const char *key, const char *value)
450 {
451         if (init_state != 1)
452                 madwifi_real_init();
453         init_state = 1;
454
455         if (ignorelist == NULL)
456                 ignorelist = ignorelist_create (/* invert = */ 1);
457
458         if (strcasecmp (key, "Interface") == 0)
459                 ignorelist_add (ignorelist, value);
460
461         else if (strcasecmp (key, "IgnoreSelected") == 0)
462                 ignorelist_set_invert (ignorelist, ! bool_arg(value));
463
464         else if (strcasecmp (key, "DisableSysfs") == 0)
465                 use_sysfs = ! bool_arg(value);
466
467         else if (strcasecmp (key, "WatchSet") == 0)
468         {
469                 if (strcasecmp (value, "All") == 0)
470                         watchlist_set (watch_items, 0xFFFFFFFF);
471                 else if (strcasecmp (value, "None") == 0)
472                         watchlist_set (watch_items, 0);
473                 else return -1;
474         }
475
476         else if (strcasecmp (key, "WatchAdd") == 0)
477         {
478                 int id = watchitem_find (value);
479
480                 if (id < 0)
481                         return (-1);
482                 else
483                         watchlist_add (watch_items, id);
484         }
485
486         else if (strcasecmp (key, "WatchRemove") == 0)
487         {
488                 int id = watchitem_find (value);
489
490                 if (id < 0)
491                         return (-1);
492                 else
493                         watchlist_remove (watch_items, id);
494         }
495
496         else if (strcasecmp (key, "MiscSet") == 0)
497         {
498                 if (strcasecmp (value, "All") == 0)
499                         watchlist_set (misc_items, 0xFFFFFFFF);
500                 else if (strcasecmp (value, "None") == 0)
501                         watchlist_set (misc_items, 0);
502                 else return -1;
503         }
504
505         else if (strcasecmp (key, "MiscAdd") == 0)
506         {
507                 int id = watchitem_find (value);
508
509                 if (id < 0)
510                         return (-1);
511                 else
512                         watchlist_add (misc_items, id);
513         }
514
515         else if (strcasecmp (key, "MiscRemove") == 0)
516         {
517                 int id = watchitem_find (value);
518
519                 if (id < 0)
520                         return (-1);
521                 else
522                         watchlist_remove (misc_items, id);
523         }
524
525         else
526                 return (-1);
527
528         return (0);
529 }
530
531
532 static void submit (const char *dev, const char *type, const char *ti1,
533                         const char *ti2, value_t *val, int len)
534 {
535         value_list_t vl = VALUE_LIST_INIT;
536
537         vl.values = val;
538         vl.values_len = len;
539         sstrncpy (vl.host, hostname_g, sizeof (vl.host));
540         sstrncpy (vl.plugin, "madwifi", sizeof (vl.plugin));
541         sstrncpy (vl.plugin_instance, dev, sizeof (vl.plugin_instance));
542         sstrncpy (vl.type, type, sizeof (vl.type));
543
544         if (ti1 && !ti2)
545                 sstrncpy (vl.type_instance, ti1, sizeof (vl.type_instance));
546
547         if (ti1 && ti2)
548                 ssnprintf (vl.type_instance, sizeof (vl.type_instance), "%s-%s", ti1, ti2);
549
550         plugin_dispatch_values (&vl);
551 }
552
553 static void submit_counter (const char *dev, const char *type, const char *ti1,
554                                 const char *ti2, counter_t val)
555 {
556         value_t item;
557         item.counter = val;
558         submit (dev, type, ti1, ti2, &item, 1);
559 }
560
561 static void submit_counter2 (const char *dev, const char *type, const char *ti1,
562                                 const char *ti2, counter_t val1, counter_t val2)
563 {
564         value_t items[2];
565         items[0].counter = val1;
566         items[1].counter = val2;
567         submit (dev, type, ti1, ti2, items, 2);
568 }
569
570 static void submit_gauge (const char *dev, const char *type, const char *ti1,
571                                 const char *ti2, gauge_t val)
572 {
573         value_t item;
574         item.gauge = val;
575         submit (dev, type, ti1, ti2, &item, 1);
576 }
577
578 static void submit_antx (const char *dev, const char *name, u_int32_t *vals)
579 {
580         char no[2] = {0, 0};
581         int i;
582
583         for (i = 0; i < 8; i++)
584                 if (vals[i])
585                 {
586                         no[0] = '0' + i;
587                         submit_counter (dev, "ath_stat", name, no, vals[i]);
588                 }
589 }
590
591 static inline void
592 macaddr_to_str (char *buf, size_t bufsize, const uint8_t mac[IEEE80211_ADDR_LEN])
593 {
594         snprintf (buf, bufsize, "%02x:%02x:%02x:%02x:%02x:%02x",
595                 mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
596 }
597
598 static void
599 process_stat_struct (int which, const void *ptr, const char *dev, const char *mac,
600                          const char *type_name, const char *misc_name)
601 {
602         uint32_t misc = 0;
603         int i;
604
605         for (i = bounds[which - 1]; i < bounds[which]; i++)
606         {
607                 uint32_t val = *(uint32_t *)(((char *) ptr) + specs[i].offset) ;
608
609                 if (item_watched (i) && (val != 0))
610                         submit_counter (dev, type_name, specs[i].name, mac, val);
611
612                 if (item_summed (i))
613                         misc += val;
614         }
615         
616         if (misc != 0)
617                 submit_counter (dev, type_name, misc_name, mac, misc);
618
619 }
620
621 static void
622 process_athstats (int sk, const char *dev)
623 {
624         struct ifreq ifr;
625         struct ath_stats stats;
626
627         strncpy (ifr.ifr_name, dev, sizeof (ifr.ifr_name));
628         ifr.ifr_data = (void *) &stats;
629         if (ioctl (sk, SIOCGATHSTATS, &ifr) < 0)
630                 return;
631
632         /* These stats are handled as a special case, because they are
633            eight values each */
634
635         if (item_watched (STAT_AST_ANT_RX))
636                 submit_antx (dev, "ast_ant_rx", stats.ast_ant_rx);
637
638         if (item_watched (STAT_AST_ANT_TX))
639                 submit_antx (dev, "ast_ant_tx", stats.ast_ant_tx);
640
641         /* All other ath statistics */
642         process_stat_struct (ATH_STAT, &stats, dev, NULL, "ath_stat", "ast_misc");
643 }
644
645 static void
646 process_80211stats (int sk, const char *dev)
647 {
648         struct ifreq ifr;
649         struct ieee80211_stats stats;
650         strncpy (ifr.ifr_name, dev, sizeof (ifr.ifr_name));
651         ifr.ifr_data = (void *) &stats;
652         if (ioctl(sk, SIOCG80211STATS, &ifr) < 0)
653                 return;
654
655         process_stat_struct (IFA_STAT, &stats, dev, NULL, "ath_stat", "is_misc");
656 }
657
658
659 static void
660 process_station (int sk, const char *dev, struct ieee80211req_sta_info *si)
661 {
662         struct iwreq iwr;
663         static char mac[DATA_MAX_NAME_LEN];
664         struct ieee80211req_sta_stats stats;
665         const struct ieee80211_nodestats *ns = &stats.is_stats;
666
667         macaddr_to_str (mac, sizeof (mac), si->isi_macaddr);
668
669         if (item_watched (STAT_NODE_TX_RATE))
670                 submit_gauge (dev, "node_tx_rate", mac, NULL,
671                         (si->isi_rates[si->isi_txrate] & IEEE80211_RATE_VAL) / 2);
672
673         if (item_watched (STAT_NODE_RSSI))
674                 submit_gauge (dev, "node_rssi", mac, NULL, si->isi_rssi);
675
676         memset (&iwr, 0, sizeof (iwr));
677         strncpy(iwr.ifr_name, dev, sizeof (iwr.ifr_name));
678         iwr.u.data.pointer = (void *) &stats;
679         iwr.u.data.length = sizeof (stats);
680         memcpy(stats.is_u.macaddr, si->isi_macaddr, IEEE80211_ADDR_LEN);
681         if (ioctl(sk, IEEE80211_IOCTL_STA_STATS, &iwr) < 0)
682                 return;
683
684         /* These two stats are handled as a special case as they are
685            a pair of 64bit values */
686         if (item_watched (STAT_NODE_OCTETS))
687                 submit_counter2 (dev, "node_octets", mac, NULL,
688                         ns->ns_rx_bytes, ns->ns_tx_bytes);
689
690         /* This stat is handled as a special case, because it is stored
691            as uin64_t, but we will ignore upper half */
692         if (item_watched (STAT_NS_RX_BEACONS))
693                 submit_counter (dev, "node_stat", "ns_rx_beacons", mac,
694                         (ns->ns_rx_beacons & 0xFFFFFFFF));
695
696         /* All other node statistics */
697         process_stat_struct (NOD_STAT, ns, dev, mac, "node_stat", "ns_misc");
698 }
699
700 static void
701 process_stations (int sk, const char *dev)
702 {
703         uint8_t buf[24*1024];
704         struct iwreq iwr;
705         uint8_t *cp;
706         int len, nodes;
707
708         memset (&iwr, 0, sizeof (iwr));
709         strncpy (iwr.ifr_name, dev, sizeof (iwr.ifr_name));
710         iwr.u.data.pointer = (void *) buf;
711         iwr.u.data.length = sizeof (buf);
712         if (ioctl (sk, IEEE80211_IOCTL_STA_INFO, &iwr) < 0)
713                 return;
714
715         len = iwr.u.data.length;
716
717         cp = buf;
718         nodes = 0;
719         while (len >= sizeof (struct ieee80211req_sta_info))
720         {
721                 struct ieee80211req_sta_info *si = (void *) cp;
722                 process_station(sk, dev, si);
723                 cp += si->isi_len;
724                 len -= si->isi_len;
725                 nodes++;
726         }
727
728         if (item_watched (STAT_ATH_NODES))
729                 submit_gauge (dev, "ath_nodes", NULL, NULL, nodes);
730 }
731
732 static void
733 process_device (int sk, const char *dev)
734 {
735         process_athstats (sk, dev);
736         process_80211stats (sk, dev);
737         process_stations (sk, dev);
738 }
739
740 static int
741 check_devname (const char *dev)
742 {
743         char buf[256];
744         char buf2[256];
745         int i;
746
747         if (dev[0] == '.')
748                 return 0;
749         
750         ssnprintf (buf, sizeof (buf), "/sys/class/net/%s/device/driver", dev);
751         buf[sizeof (buf) - 1] = 0;
752
753         i = readlink (buf, buf2, sizeof (buf2) - 1);
754         if (i < 0)
755                 return 0;
756         buf2[i] = 0;
757
758         return (strstr (buf2, "/drivers/ath_") != NULL);
759 }
760
761 static int
762 sysfs_iterate(int sk)
763 {
764         struct dirent *de;
765
766         DIR *nets = opendir ("/sys/class/net/");
767         if (nets == NULL)
768         {
769                 WARNING ("madwifi plugin: opening /sys/class/net failed");
770                 return (-1);
771         }
772
773         while ((de = readdir (nets)))
774                 if (check_devname (de->d_name) &&
775                     (ignorelist_match (ignorelist, de->d_name) == 0))
776                         process_device (sk, de->d_name);
777
778         closedir(nets);
779
780         return 0;
781 }
782
783 static int
784 procfs_iterate(int sk)
785 {
786         char buffer[1024];
787         char *device, *dummy;
788         FILE *fh;
789         
790         if ((fh = fopen ("/proc/net/dev", "r")) == NULL)
791         {
792                 WARNING ("madwifi plugin: opening /proc/net/dev failed");
793                 return (-1);
794         }
795
796         while (fgets (buffer, 1024, fh) != NULL)
797         {
798                 if (!(dummy = strchr(buffer, ':')))
799                         continue;
800                 dummy[0] = '\0';
801
802                 device = buffer;
803                 while (device[0] == ' ')
804                         device++;
805
806                 if (device[0] == '\0')
807                         continue;
808
809                 if (ignorelist_match (ignorelist, device) == 0)
810                         process_device (sk, device);
811         }
812
813         fclose(fh);
814         return 0;
815 }
816
817 static int madwifi_read (void)
818 {
819         if (init_state == 0)
820                 madwifi_real_init();
821         init_state = 2;
822
823         int sk = socket(AF_INET, SOCK_DGRAM, 0);
824         if (sk < 0)
825                 return (-1);
826
827         int rv;
828
829 /* procfs iteration is not safe because it does not check whether given
830    interface is madwifi interface and there are private ioctls used, which
831    may do something completely different on non-madwifi devices.   
832    Therefore, it is not used unless explicitly enabled (and should be used
833    together with ignorelist). */
834
835         if (use_sysfs)
836                 rv = sysfs_iterate(sk);
837         else
838                 rv = procfs_iterate(sk);
839
840         close(sk);
841
842         return rv;
843 }
844
845 void module_register (void)
846 {
847         plugin_register_config ("madwifi", madwifi_config,
848                         config_keys, config_keys_num);
849
850         plugin_register_read ("madwifi", madwifi_read);
851 }