fix wprobe-export
[librecmc/librecmc.git] / package / wprobe / src / user / wprobe-lib.c
1 /*
2  * wprobe.c: Wireless probe user space library
3  * Copyright (C) 2008-2009 Felix Fietkau <nbd@openwrt.org>
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License
7  * as published by the Free Software Foundation; either version 2
8  * of the License, or (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  */
15
16 #include <sys/types.h>
17 #include <sys/socket.h>
18 #include <stdio.h>
19 #include <string.h>
20 #include <stdlib.h>
21 #include <errno.h>
22 #include <getopt.h>
23 #include <unistd.h>
24 #include <stdbool.h>
25 #include <math.h>
26 #include <linux/wprobe.h>
27 #include <netlink/netlink.h>
28 #include <netlink/attr.h>
29 #include <netlink/genl/genl.h>
30 #ifndef NO_LOCAL_ACCESS 
31 #include <netlink/genl/ctrl.h>
32 #include <netlink/genl/family.h>
33 #include <endian.h>
34 #endif
35 #include "wprobe.h"
36
37 #define DEBUG 1
38 #ifdef DEBUG
39 #define DPRINTF(fmt, ...) fprintf(stderr, "%s(%d): " fmt, __func__, __LINE__, ##__VA_ARGS__)
40 #else
41 #define DPRINTF(fmt, ...) do {} while (0)
42 #endif
43
44 #if defined(BYTE_ORDER) && !defined(__BYTE_ORDER)
45 #define __LITTLE_ENDIAN LITTLE_ENDIAN
46 #define __BIG_ENDIAN BIG_ENDIAN
47 #define __BYTE_ORDER BYTE_ORDER
48 #endif
49
50 #ifndef __BYTE_ORDER
51 #error Unknown endian type
52 #endif
53
54 #define WPROBE_MAX_MSGLEN       65536
55
56 static inline __u16 __swab16(__u16 x)
57 {
58         return x<<8 | x>>8;
59 }
60
61 static inline __u32 __swab32(__u32 x)
62 {
63         return x<<24 | x>>24 |
64                 (x & (__u32)0x0000ff00UL)<<8 |
65                 (x & (__u32)0x00ff0000UL)>>8;
66 }
67
68 static inline __u64 __swab64(__u64 x)
69 {
70         return x<<56 | x>>56 |
71                 (x & (__u64)0x000000000000ff00ULL)<<40 |
72                 (x & (__u64)0x0000000000ff0000ULL)<<24 |
73                 (x & (__u64)0x00000000ff000000ULL)<< 8 |
74                 (x & (__u64)0x000000ff00000000ULL)>> 8 |
75                 (x & (__u64)0x0000ff0000000000ULL)>>24 |
76                 (x & (__u64)0x00ff000000000000ULL)>>40;
77 }
78
79
80 #if __BYTE_ORDER == __LITTLE_ENDIAN
81 #define SWAP16(var) var = __swab16(var)
82 #define SWAP32(var) var = __swab32(var)
83 #define SWAP64(var) var = __swab64(var)
84 #else
85 #define SWAP16(var) do {} while(0)
86 #define SWAP32(var) do {} while(0)
87 #define SWAP64(var) do {} while(0)
88 #endif
89
90 int wprobe_port = 17990;
91 static struct nlattr *tb[WPROBE_ATTR_LAST+1];
92 static struct nla_policy attribute_policy[WPROBE_ATTR_LAST+1] = {
93         [WPROBE_ATTR_ID] = { .type = NLA_U32 },
94         [WPROBE_ATTR_MAC] = { .type = NLA_UNSPEC, .minlen = 6, .maxlen = 6 },
95         [WPROBE_ATTR_NAME] = { .type = NLA_STRING },
96         [WPROBE_ATTR_FLAGS] = { .type = NLA_U32 },
97         [WPROBE_ATTR_TYPE] = { .type = NLA_U8 },
98         [WPROBE_ATTR_FLAGS] = { .type = NLA_U32 },
99         [WPROBE_VAL_S8] = { .type = NLA_U8 },
100         [WPROBE_VAL_S16] = { .type = NLA_U16 },
101         [WPROBE_VAL_S32] = { .type = NLA_U32 },
102         [WPROBE_VAL_S64] = { .type = NLA_U64 },
103         [WPROBE_VAL_U8] = { .type = NLA_U8 },
104         [WPROBE_VAL_U16] = { .type = NLA_U16 },
105         [WPROBE_VAL_U32] = { .type = NLA_U32 },
106         [WPROBE_VAL_U64] = { .type = NLA_U64 },
107         [WPROBE_VAL_SUM] = { .type = NLA_U64 },
108         [WPROBE_VAL_SUM_SQ] = { .type = NLA_U64 },
109         [WPROBE_VAL_SAMPLES] = { .type = NLA_U32 },
110         [WPROBE_VAL_SCALE_TIME] = { .type = NLA_U64 },
111         [WPROBE_ATTR_INTERVAL] = { .type = NLA_U64 },
112         [WPROBE_ATTR_SAMPLES_MIN] = { .type = NLA_U32 },
113         [WPROBE_ATTR_SAMPLES_MAX] = { .type = NLA_U32 },
114         [WPROBE_ATTR_SAMPLES_SCALE_M] = { .type = NLA_U32 },
115         [WPROBE_ATTR_SAMPLES_SCALE_D] = { .type = NLA_U32 },
116         [WPROBE_ATTR_FILTER_GROUP] = { .type = NLA_NESTED },
117         [WPROBE_ATTR_RXCOUNT] = { .type = NLA_U64 },
118         [WPROBE_ATTR_TXCOUNT] = { .type = NLA_U64 },
119 };
120
121 typedef int (*wprobe_cb_t)(struct nl_msg *, void *);
122
123 struct wprobe_iface_ops {
124         int (*send_msg)(struct wprobe_iface *dev, struct nl_msg *msg, wprobe_cb_t cb, void *arg);
125         void (*free)(struct wprobe_iface *dev);
126 };
127
128 struct wprobe_attr_cb {
129         struct list_head *list;
130         char *addr;
131 };
132
133 #define WPROBE_MAGIC_STR "WPROBE"
134 struct wprobe_init_hdr {
135         struct {
136                 char magic[sizeof(WPROBE_MAGIC_STR)];
137
138                 /* protocol version */
139                 uint8_t version;
140
141                 /* extra header length (unused for now) */
142                 uint16_t extra;
143         } pre __attribute__((packed));
144         union {
145                 struct {
146                         uint16_t genl_family;
147                 } v0 __attribute__((packed));
148         };
149 } __attribute__((packed));
150
151 struct wprobe_msg_hdr {
152         __u16 status;
153         __u16 error;
154         __u32 len;
155 };
156
157 enum wprobe_resp_status {
158         WPROBE_MSG_DONE = 0,
159         WPROBE_MSG_DATA = 1,
160 };
161
162 static inline void
163 wprobe_swap_msg_hdr(struct wprobe_msg_hdr *mhdr)
164 {
165         SWAP16(mhdr->status);
166         SWAP16(mhdr->error);
167         SWAP32(mhdr->len);
168 }
169
170 static int
171 save_attribute_handler(struct nl_msg *msg, void *arg)
172 {
173         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
174         const char *name = "N/A";
175         struct wprobe_attribute *attr;
176         int type = 0;
177         struct wprobe_attr_cb *cb = arg;
178
179         nla_parse(tb, WPROBE_ATTR_LAST, genlmsg_attrdata(gnlh, 0),
180                         genlmsg_attrlen(gnlh, 0), attribute_policy);
181
182         if (tb[WPROBE_ATTR_NAME])
183                 name = nla_data(tb[WPROBE_ATTR_NAME]);
184
185         attr = malloc(sizeof(struct wprobe_attribute) + strlen(name) + 1);
186         if (!attr)
187                 return -1;
188
189         memset(attr, 0, sizeof(struct wprobe_attribute));
190
191         if (tb[WPROBE_ATTR_ID])
192                 attr->id = nla_get_u32(tb[WPROBE_ATTR_ID]);
193
194         if (tb[WPROBE_ATTR_MAC] && cb->addr)
195                 memcpy(cb->addr, nla_data(tb[WPROBE_ATTR_MAC]), 6);
196
197         if (tb[WPROBE_ATTR_FLAGS])
198                 attr->flags = nla_get_u32(tb[WPROBE_ATTR_FLAGS]);
199
200         if (tb[WPROBE_ATTR_TYPE])
201                 type = nla_get_u8(tb[WPROBE_ATTR_TYPE]);
202
203         if ((type < WPROBE_VAL_STRING) ||
204                 (type > WPROBE_VAL_U64))
205                 type = 0;
206
207         attr->type = type;
208         strcpy(attr->name, name);
209         INIT_LIST_HEAD(&attr->list);
210         list_add(&attr->list, cb->list);
211         return 0;
212 }
213
214 static struct nl_msg *
215 wprobe_new_msg(struct wprobe_iface *dev, int cmd, bool dump)
216 {
217         struct nl_msg *msg;
218         uint32_t flags = 0;
219
220         msg = nlmsg_alloc_size(65536);
221         if (!msg)
222                 return NULL;
223
224         if (dump)
225                 flags |= NLM_F_DUMP;
226
227         genlmsg_put(msg, 0, 0, dev->genl_family,
228                         0, flags, cmd, 0);
229
230         NLA_PUT_STRING(msg, WPROBE_ATTR_INTERFACE, dev->ifname);
231 nla_put_failure:
232         return msg;
233 }
234
235
236 static int
237 dump_attributes(struct wprobe_iface *dev, bool link, struct list_head *list, char *addr)
238 {
239         struct nl_msg *msg;
240         struct wprobe_attr_cb cb;
241
242         cb.list = list;
243         cb.addr = addr;
244         msg = wprobe_new_msg(dev, WPROBE_CMD_GET_LIST, true);
245         if (!msg)
246                 return -ENOMEM;
247
248         if (link)
249                 NLA_PUT(msg, WPROBE_ATTR_MAC, 6, "\x00\x00\x00\x00\x00\x00");
250
251         return dev->ops->send_msg(dev, msg, save_attribute_handler, &cb);
252
253 nla_put_failure:
254         nlmsg_free(msg);
255         return -EINVAL;
256 }
257
258 static struct wprobe_iface *
259 wprobe_alloc_dev(void)
260 {
261         struct wprobe_iface *dev;
262
263         dev = malloc(sizeof(struct wprobe_iface));
264         if (!dev)
265                 return NULL;
266
267         memset(dev, 0, sizeof(struct wprobe_iface));
268
269         dev->interval = -1;
270         dev->scale_min = -1;
271         dev->scale_max = -1;
272         dev->scale_m = -1;
273         dev->scale_d = -1;
274         dev->sockfd = -1;
275
276         INIT_LIST_HEAD(&dev->global_attr);
277         INIT_LIST_HEAD(&dev->link_attr);
278         INIT_LIST_HEAD(&dev->links);
279         return dev;
280 }
281
282 static int
283 wprobe_init_dev(struct wprobe_iface *dev)
284 {
285         dump_attributes(dev, false, &dev->global_attr, NULL);
286         dump_attributes(dev, true, &dev->link_attr, NULL);
287         return 0;
288 }
289
290 #ifndef NO_LOCAL_ACCESS 
291 static int n_devs = 0;
292 static struct nl_sock *handle = NULL;
293 static struct nl_cache *cache = NULL;
294 static struct genl_family *family = NULL;
295
296 static int
297 error_handler(struct sockaddr_nl *nla, struct nlmsgerr *err, void *arg)
298 {
299         int *ret = arg;
300         *ret = err->error;
301         return NL_STOP;
302 }
303
304 static int
305 finish_handler(struct nl_msg *msg, void *arg)
306 {
307         int *ret = arg;
308         *ret = 0;
309         return NL_SKIP;
310 }
311
312 static int
313 ack_handler(struct nl_msg *msg, void *arg)
314 {
315         int *ret = arg;
316         *ret = 0;
317         return NL_STOP;
318 }
319
320 static void
321 wprobe_local_free(struct wprobe_iface *dev)
322 {
323         /* should not happen */
324         if (n_devs == 0)
325                 return;
326
327         if (--n_devs != 0)
328                 return;
329
330         if (cache)
331                 nl_cache_free(cache);
332         if (handle)
333                 nl_socket_free(handle);
334         handle = NULL;
335         cache = NULL;
336 }
337
338 static int
339 wprobe_local_init(void)
340 {
341         int ret;
342
343         if (n_devs++ > 0)
344                 return 0;
345
346         handle = nl_socket_alloc();
347         if (!handle) {
348                 DPRINTF("Failed to create handle\n");
349                 goto err;
350         }
351
352         if (genl_connect(handle)) {
353                 DPRINTF("Failed to connect to generic netlink\n");
354                 goto err;
355         }
356
357         ret = genl_ctrl_alloc_cache(handle, &cache);
358         if (ret < 0) {
359                 DPRINTF("Failed to allocate netlink cache\n");
360                 goto err;
361         }
362
363         family = genl_ctrl_search_by_name(cache, "wprobe");
364         if (!family) {
365                 DPRINTF("wprobe API not present\n");
366                 goto err;
367         }
368         return 0;
369
370 err:
371         wprobe_local_free(NULL);
372         return -EINVAL;
373 }
374
375
376 static int
377 wprobe_local_send_msg(struct wprobe_iface *dev, struct nl_msg *msg, wprobe_cb_t callback, void *arg)
378 {
379         struct nl_cb *cb;
380         int err = 0;
381
382         cb = nl_cb_alloc(NL_CB_DEFAULT);
383         if (!cb)
384                 goto out_no_cb;
385
386         if (callback)
387                 nl_cb_set(cb, NL_CB_VALID, NL_CB_CUSTOM, callback, arg);
388
389         err = nl_send_auto_complete(handle, msg);
390         if (err < 0)
391                 goto out;
392
393         err = 1;
394
395         nl_cb_err(cb, NL_CB_CUSTOM, error_handler, &err);
396         nl_cb_set(cb, NL_CB_FINISH, NL_CB_CUSTOM, finish_handler, &err);
397         nl_cb_set(cb, NL_CB_ACK, NL_CB_CUSTOM, ack_handler, &err);
398
399         while (err > 0)
400                 nl_recvmsgs(handle, cb);
401
402 out:
403         nl_cb_put(cb);
404 out_no_cb:
405         nlmsg_free(msg);
406         return err;
407 }
408
409 static const struct wprobe_iface_ops wprobe_local_ops = {
410         .send_msg = wprobe_local_send_msg,
411         .free = wprobe_local_free,
412 };
413
414 struct wprobe_iface *
415 wprobe_get_dev(const char *ifname)
416 {
417         struct wprobe_iface *dev;
418
419         if (wprobe_local_init() != 0)
420                 return NULL;
421
422         dev = wprobe_alloc_dev();
423         if (!dev)
424                 goto error_alloc;
425
426         dev->ifname = strdup(ifname);
427         dev->ops = &wprobe_local_ops;
428         dev->genl_family = genl_family_get_id(family);
429
430         if (wprobe_init_dev(dev) < 0)
431                 goto error;
432
433         return dev;
434
435 error:
436         free(dev);
437 error_alloc:
438         wprobe_local_free(NULL);
439         return NULL;
440 }
441
442 #endif
443
444 static void swap_nlmsghdr(struct nlmsghdr *nlh)
445 {
446         SWAP32(nlh->nlmsg_len);
447         SWAP16(nlh->nlmsg_type);
448         SWAP16(nlh->nlmsg_flags);
449         SWAP32(nlh->nlmsg_seq);
450         SWAP32(nlh->nlmsg_pid);
451 }
452
453 static void swap_genlmsghdr(struct genlmsghdr *gnlh)
454 {
455 #if 0 /* probably unnecessary */
456         SWAP16(gnlh->reserved);
457 #endif
458 }
459
460 static void
461 wprobe_swap_nested(void *data, int len, bool outgoing)
462 {
463         void *end = data + len;
464
465         while (data < end) {
466                 struct nlattr *nla = data;
467                 unsigned int type, len;
468
469                 if (!outgoing) {
470                         SWAP16(nla->nla_len);
471                         SWAP16(nla->nla_type);
472
473                         /* required for further sanity checks */
474                         if (data + nla->nla_len > end)
475                                 nla->nla_len = end - data;
476                 }
477
478                 len = NLA_ALIGN(nla->nla_len);
479                 type = nla->nla_type & NLA_TYPE_MASK;
480
481                 if (type <= WPROBE_ATTR_LAST) {
482 #if __BYTE_ORDER == __LITTLE_ENDIAN
483                         switch(attribute_policy[type].type) {
484                         case NLA_U16:
485                                 SWAP16(*(__u16 *)nla_data(nla));
486                                 break;
487                         case NLA_U32:
488                                 SWAP32(*(__u32 *)nla_data(nla));
489                                 break;
490                         case NLA_U64:
491                                 SWAP64(*(__u64 *)nla_data(nla));
492                                 break;
493                         case NLA_NESTED:
494                                 wprobe_swap_nested(nla_data(nla), nla_len(nla), outgoing);
495                                 break;
496                         }
497 #endif
498                 }
499                 data += len;
500
501                 if (outgoing) {
502                         SWAP16(nla->nla_len);
503                         SWAP16(nla->nla_type);
504                 }
505                 if (!nla->nla_len)
506                         break;
507         }
508 }
509
510 static struct nl_msg *
511 wprobe_msg_from_network(int socket, int len)
512 {
513         struct genlmsghdr *gnlh;
514         struct nlmsghdr *nlh;
515         struct nl_msg *msg;
516         void *data;
517
518         msg = nlmsg_alloc_size(len + 32);
519         if (!msg)
520                 return NULL;
521
522         nlh = nlmsg_hdr(msg);
523         if (read(socket, nlh, len) != len)
524                 goto free;
525
526         swap_nlmsghdr(nlh);
527         if (nlh->nlmsg_len > len)
528                 goto free;
529
530         gnlh = nlmsg_data(nlh);
531         swap_genlmsghdr(gnlh);
532
533         data = genlmsg_data(gnlh);
534         wprobe_swap_nested(data, genlmsg_len(gnlh), false);
535
536         return msg;
537 free:
538         nlmsg_free(msg);
539         return NULL;
540 }
541
542 static int
543 wprobe_msg_to_network(int socket, struct nl_msg *msg)
544 {
545         struct nlmsghdr *nlh = nlmsg_hdr(msg);
546         struct wprobe_msg_hdr mhdr;
547         struct genlmsghdr *gnlh;
548         void *buf, *data;
549         int buflen, datalen;
550         int ret;
551
552         buflen = nlh->nlmsg_len;
553         buf = malloc(buflen);
554         if (!buf)
555                 return -ENOMEM;
556
557         memset(&mhdr, 0, sizeof(mhdr));
558         mhdr.status = WPROBE_MSG_DATA;
559         mhdr.len = buflen;
560         wprobe_swap_msg_hdr(&mhdr);
561         write(socket, &mhdr, sizeof(mhdr));
562
563         memcpy(buf, nlh, buflen);
564         nlh = buf;
565         gnlh = nlmsg_data(nlh);
566         data = genlmsg_data(gnlh);
567         datalen = genlmsg_len(gnlh);
568
569         wprobe_swap_nested(data, datalen, true);
570         swap_genlmsghdr(gnlh);
571         swap_nlmsghdr(nlh);
572         ret = write(socket, buf, buflen);
573         free(buf);
574
575         return ret;
576 }
577
578 static int
579 wprobe_remote_send_msg(struct wprobe_iface *dev, struct nl_msg *msg, wprobe_cb_t callback, void *arg)
580 {
581         struct wprobe_msg_hdr mhdr;
582         int msgs = 0;
583
584         wprobe_msg_to_network(dev->sockfd, msg);
585         nlmsg_free(msg);
586         do {
587                 if (read(dev->sockfd, &mhdr, sizeof(mhdr)) != sizeof(mhdr)) {
588                         DPRINTF("Failed to read response header\n");
589                         return -1;
590                 }
591                 wprobe_swap_msg_hdr(&mhdr);
592
593                 switch(mhdr.status) {
594                 case WPROBE_MSG_DATA:
595                         if (mhdr.len > WPROBE_MAX_MSGLEN) {
596                                 fprintf(stderr, "Invalid length in received response message.\n");
597                                 exit(1);
598                         }
599
600                         msg = wprobe_msg_from_network(dev->sockfd, mhdr.len);
601                         if (!msg)
602                                 return -EINVAL;
603
604                         msgs++;
605                         callback(msg, arg);
606                         nlmsg_free(msg);
607                         break;
608                 }
609         } while (mhdr.status != WPROBE_MSG_DONE);
610
611         if (mhdr.error)
612                 return -mhdr.error;
613         else
614                 return msgs;
615 }
616
617
618 static void
619 wprobe_socket_dev_free(struct wprobe_iface *dev)
620 {
621         if (dev->sockfd >= 0)
622                 close(dev->sockfd);
623 }
624
625 static const struct wprobe_iface_ops wprobe_remote_ops = {
626         .send_msg = wprobe_remote_send_msg,
627         .free = wprobe_socket_dev_free,
628 };
629
630
631 #ifndef NO_LOCAL_ACCESS 
632 int
633 wprobe_server_init(int socket)
634 {
635         struct wprobe_init_hdr hdr;
636         int ret;
637
638         ret = wprobe_local_init();
639         if (ret != 0)
640                 return ret;
641
642         memset(&hdr, 0, sizeof(hdr));
643         memcpy(hdr.pre.magic, WPROBE_MAGIC_STR, sizeof(WPROBE_MAGIC_STR));
644         hdr.pre.version = 0;
645         hdr.v0.genl_family = genl_family_get_id(family);
646         SWAP16(hdr.v0.genl_family);
647         write(socket, (unsigned char *)&hdr, sizeof(hdr));
648
649         return 0;
650 }
651
652 static int
653 wprobe_server_cb(struct nl_msg *msg, void *arg)
654 {
655         int *socket = arg;
656         int ret;
657
658         ret = wprobe_msg_to_network(*socket, msg);
659         if (ret > 0)
660                 ret = 0;
661
662         return ret;
663 }
664
665
666 int
667 wprobe_server_handle(int socket)
668 {
669         struct wprobe_msg_hdr mhdr;
670         struct nl_msg *msg;
671         int ret;
672
673         ret = read(socket, &mhdr, sizeof(mhdr));
674         if (ret != sizeof(mhdr)) {
675                 if (ret <= 0)
676                         return -1;
677
678                 DPRINTF("Failed to read request header\n");
679                 return -EINVAL;
680         }
681         wprobe_swap_msg_hdr(&mhdr);
682
683         switch(mhdr.status) {
684         case WPROBE_MSG_DATA:
685                 if (mhdr.len > WPROBE_MAX_MSGLEN) {
686                         DPRINTF("Invalid length in received response message.\n");
687                         return -EINVAL;
688                 }
689                 msg = wprobe_msg_from_network(socket, mhdr.len);
690                 break;
691         default:
692                 DPRINTF("Invalid request header type\n");
693                 return -ENOENT;
694         }
695
696         if (!msg) {
697                 DPRINTF("Failed to get message\n");
698                 return -EINVAL;
699         }
700
701         ret = wprobe_local_send_msg(NULL, msg, wprobe_server_cb, &socket);
702
703         memset(&mhdr, 0, sizeof(mhdr));
704         mhdr.status = WPROBE_MSG_DONE;
705         if (ret < 0)
706                 mhdr.error = (uint16_t) -ret;
707
708         ret = write(socket, (unsigned char *)&mhdr, sizeof(mhdr));
709         if (ret > 0)
710                 ret = 0;
711
712         return ret;
713 }
714
715 void
716 wprobe_server_done(void)
717 {
718         wprobe_local_free(NULL);
719 }
720 #endif
721
722 struct wprobe_iface *
723 wprobe_get_from_socket(int socket, const char *name)
724 {
725         struct wprobe_iface *dev;
726         struct wprobe_init_hdr hdr;
727
728         dev = wprobe_alloc_dev();
729         if (!dev)
730                 goto out;
731
732         dev->ops = &wprobe_remote_ops;
733         dev->sockfd = socket;
734         dev->ifname = strdup(name);
735
736         /* read version and header length */
737         if (read(socket, &hdr.pre, sizeof(hdr.pre)) != sizeof(hdr.pre)) {
738                 DPRINTF("Could not read header\n");
739                 goto error;
740         }
741
742         /* magic not found */
743         if (memcmp(hdr.pre.magic, WPROBE_MAGIC_STR, sizeof(hdr.pre.magic)) != 0) {
744                 DPRINTF("Magic does not match\n");
745                 goto error;
746         }
747
748         /* unsupported version */
749         if (hdr.pre.version != 0) {
750                 DPRINTF("Protocol version does not match\n");
751                 goto error;
752         }
753
754         if (read(socket, &hdr.v0, sizeof(hdr.v0)) != sizeof(hdr.v0)) {
755                 DPRINTF("Could not read header data\n");
756                 goto error;
757         }
758
759         SWAP16(hdr.pre.extra);
760         SWAP16(hdr.v0.genl_family);
761         dev->genl_family = hdr.v0.genl_family;
762
763         if (wprobe_init_dev(dev) < 0) {
764                 DPRINTF("Could not initialize device\n");
765                 goto error;
766         }
767
768 out:
769         return dev;
770
771 error:
772         wprobe_free_dev(dev);
773         return NULL;
774 }
775
776 struct wprobe_iface *
777 wprobe_get_auto(const char *arg, char **err)
778 {
779         static struct sockaddr_in sa;
780         static char errbuf[512];
781
782         struct wprobe_iface *dev = NULL;
783         struct hostent *h;
784         char *devstr = strdup(arg);
785         char *sep = NULL;
786         int sock = -1;
787         int len;
788
789         if (err)
790                 *err = NULL;
791
792         sep = strchr(devstr, ':');
793         if (!sep) {
794 #ifndef NO_LOCAL_ACCESS 
795                 free(devstr);
796                 return wprobe_get_dev(arg);
797 #else
798                 if (err)
799                         *err = "Invalid argument";
800                 goto out;
801 #endif
802         }
803
804         *sep = 0;
805         sep++;
806
807         sock = socket(AF_INET, SOCK_STREAM, 0);
808         if (sock < 0)
809                 goto syserr;
810
811         h = gethostbyname(devstr);
812         if (!h) {
813                 sprintf(errbuf, "Host not found");
814                 goto out_err;
815         }
816
817         memcpy(&sa.sin_addr, h->h_addr, h->h_length);
818         sa.sin_family = AF_INET;
819         sa.sin_port = htons(wprobe_port);
820         if (connect(sock, (struct sockaddr *)&sa, sizeof(sa)) < 0)
821                 goto syserr;
822
823         dev = wprobe_get_from_socket(sock, sep);
824         if (!dev) {
825                 sprintf(errbuf, "wprobe connection initialization failed");
826                 goto out_err;
827         }
828         goto out;
829
830 syserr:
831         if (err) {
832                 strcpy(errbuf, "Connection failed: ");
833                 len = strlen(errbuf);
834                 strerror_r(errno, errbuf + len, sizeof(errbuf) - len - 1);
835         }
836 out_err:
837         if (err)
838                 *err = errbuf;
839         if (sock >= 0)
840                 close(sock);
841 out:
842         if (devstr)
843                 free(devstr);
844         return dev;
845 }
846
847 static void
848 free_attr_list(struct list_head *list)
849 {
850         struct wprobe_attribute *attr, *tmp;
851
852         list_for_each_entry_safe(attr, tmp, list, list) {
853                 list_del(&attr->list);
854                 free(attr);
855         }
856 }
857
858 void
859 wprobe_free_dev(struct wprobe_iface *dev)
860 {
861         if (dev->ops->free)
862                 dev->ops->free(dev);
863         free_attr_list(&dev->global_attr);
864         free_attr_list(&dev->link_attr);
865         free((void *)dev->ifname);
866         free(dev);
867 }
868
869 static struct wprobe_link *
870 get_link(struct list_head *list, const char *addr)
871 {
872         struct wprobe_link *l;
873
874         list_for_each_entry(l, list, list) {
875                 if (!memcmp(l->addr, addr, 6)) {
876                         list_del_init(&l->list);
877                         goto out;
878                 }
879         }
880
881         /* no previous link found, allocate a new one */
882         l = malloc(sizeof(struct wprobe_link));
883         if (!l)
884                 goto out;
885
886         memset(l, 0, sizeof(struct wprobe_link));
887         memcpy(l->addr, addr, sizeof(l->addr));
888         INIT_LIST_HEAD(&l->list);
889
890 out:
891         return l;
892 }
893
894 struct wprobe_save_cb {
895         struct list_head *list;
896         struct list_head old_list;
897 };
898
899 static int
900 save_link_handler(struct nl_msg *msg, void *arg)
901 {
902         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
903         struct wprobe_link *link;
904         struct wprobe_save_cb *cb = arg;
905         const char *addr;
906
907         nla_parse(tb, WPROBE_ATTR_LAST, genlmsg_attrdata(gnlh, 0),
908                         genlmsg_attrlen(gnlh, 0), attribute_policy);
909
910         if (!tb[WPROBE_ATTR_MAC] || (nla_len(tb[WPROBE_ATTR_MAC]) != 6))
911                 return -1;
912
913         addr = nla_data(tb[WPROBE_ATTR_MAC]);
914         link = get_link(&cb->old_list, addr);
915         if (!link)
916                 return -1;
917
918         if (tb[WPROBE_ATTR_FLAGS])
919                 link->flags = nla_get_u32(tb[WPROBE_ATTR_FLAGS]);
920
921         list_add_tail(&link->list, cb->list);
922         return 0;
923 }
924
925
926 int
927 wprobe_update_links(struct wprobe_iface *dev)
928 {
929         struct wprobe_link *l, *tmp;
930         struct nl_msg *msg;
931         struct wprobe_save_cb cb;
932         int err;
933
934         INIT_LIST_HEAD(&cb.old_list);
935         list_splice_init(&dev->links, &cb.old_list);
936         cb.list = &dev->links;
937
938         msg = wprobe_new_msg(dev, WPROBE_CMD_GET_LINKS, true);
939         if (!msg)
940                 return -ENOMEM;
941
942         err = dev->ops->send_msg(dev, msg, save_link_handler, &cb);
943         if (err < 0)
944                 return err;
945
946         list_for_each_entry_safe(l, tmp, &cb.old_list, list) {
947                 list_del(&l->list);
948                 free(l);
949         }
950
951         return 0;
952 }
953
954
955 struct wprobe_filter_data
956 {
957         wprobe_filter_cb cb;
958         void *arg;
959         struct wprobe_filter_item *buf;
960         int buflen;
961 };
962
963 static int
964 dump_filter_handler(struct nl_msg *msg, void *arg)
965 {
966         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
967         struct wprobe_filter_data *data = arg;
968         struct nlattr *p;
969         const char *name;
970         int count = 0;
971         int len;
972
973         nla_parse(tb, WPROBE_ATTR_LAST, genlmsg_attrdata(gnlh, 0),
974                         genlmsg_attrlen(gnlh, 0), attribute_policy);
975
976         if (!tb[WPROBE_ATTR_NAME] || !tb[WPROBE_ATTR_FILTER_GROUP])
977                 return -1;
978
979         name = nla_data(tb[WPROBE_ATTR_NAME]);
980         nla_for_each_nested(p, tb[WPROBE_ATTR_FILTER_GROUP], len) {
981                 count++;
982         }
983
984         if (data->buflen < count) {
985                 if (data->buf)
986                         free(data->buf);
987                 data->buflen = count;
988                 data->buf = malloc(sizeof(struct wprobe_filter_item) * count);
989                 memset(data->buf, 0, sizeof(struct wprobe_filter_item) * count);
990         }
991
992         count = 0;
993         nla_for_each_nested(p, tb[WPROBE_ATTR_FILTER_GROUP], len) {
994                 struct wprobe_filter_item *fi;
995
996                 nla_parse(tb, WPROBE_ATTR_LAST, nla_data(p),
997                                 nla_len(p), attribute_policy);
998
999                 if (!tb[WPROBE_ATTR_NAME] || !tb[WPROBE_ATTR_RXCOUNT]
1000                                 || !tb[WPROBE_ATTR_TXCOUNT])
1001                         continue;
1002
1003                 fi = &data->buf[count++];
1004                 strncpy(fi->name, nla_data(tb[WPROBE_ATTR_NAME]), sizeof(fi->name) - 1);
1005                 fi->name[sizeof(fi->name) - 1] = 0;
1006                 fi->rx = nla_get_u64(tb[WPROBE_ATTR_RXCOUNT]);
1007                 fi->tx = nla_get_u64(tb[WPROBE_ATTR_TXCOUNT]);
1008         }
1009         data->cb(data->arg, name, data->buf, count);
1010
1011         return 0;
1012 }
1013
1014 int
1015 wprobe_dump_filters(struct wprobe_iface *dev, wprobe_filter_cb cb, void *arg)
1016 {
1017         struct wprobe_filter_data data;
1018         struct nl_msg *msg;
1019         int err;
1020
1021         data.buf = 0;
1022         data.buflen = 0;
1023         data.cb = cb;
1024         data.arg = arg;
1025
1026         msg = wprobe_new_msg(dev, WPROBE_CMD_GET_FILTER, true);
1027         if (!msg)
1028                 return -ENOMEM;
1029
1030         err = dev->ops->send_msg(dev, msg, dump_filter_handler, &data);
1031         if (err < 0)
1032                 return err;
1033
1034         return 0;
1035 }
1036
1037 int
1038 wprobe_apply_config(struct wprobe_iface *dev)
1039 {
1040         struct nl_msg *msg;
1041
1042         msg = wprobe_new_msg(dev, WPROBE_CMD_CONFIG, false);
1043         if (!msg)
1044                 return -ENOMEM;
1045
1046         if (dev->interval >= 0)
1047                 NLA_PUT_MSECS(msg, WPROBE_ATTR_INTERVAL, dev->interval);
1048
1049         if (dev->filter_len < 0) {
1050                 NLA_PUT(msg, WPROBE_ATTR_FILTER, 0, NULL);
1051                 dev->filter_len = 0;
1052         } else if (dev->filter && dev->filter_len > 0) {
1053                 NLA_PUT(msg, WPROBE_ATTR_FILTER, dev->filter_len, dev->filter);
1054         }
1055         dev->filter = NULL;
1056
1057         dev->ops->send_msg(dev, msg, NULL, NULL);
1058         return 0;
1059
1060 nla_put_failure:
1061         nlmsg_free(msg);
1062         return -ENOMEM;
1063 }
1064
1065 int
1066 wprobe_measure(struct wprobe_iface *dev)
1067 {
1068         struct nl_msg *msg;
1069
1070         msg = wprobe_new_msg(dev, WPROBE_CMD_MEASURE, false);
1071         if (!msg)
1072                 return -ENOMEM;
1073
1074         dev->ops->send_msg(dev, msg, NULL, NULL);
1075         return 0;
1076 }
1077
1078 struct wprobe_request_cb {
1079         struct list_head *list;
1080         struct list_head old_list;
1081         char *addr;
1082 };
1083
1084 static int
1085 save_attrdata_handler(struct nl_msg *msg, void *arg)
1086 {
1087         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
1088         struct wprobe_request_cb *cb = arg;
1089         struct wprobe_attribute *attr;
1090         int type, id;
1091
1092         nla_parse(tb, WPROBE_ATTR_LAST, genlmsg_attrdata(gnlh, 0),
1093                         genlmsg_attrlen(gnlh, 0), attribute_policy);
1094
1095         if (!tb[WPROBE_ATTR_ID])
1096                 return -1;
1097
1098         if (!tb[WPROBE_ATTR_TYPE])
1099                 return -1;
1100
1101         id = nla_get_u32(tb[WPROBE_ATTR_ID]);
1102         list_for_each_entry(attr, &cb->old_list, list) {
1103                 if (attr->id == id)
1104                         goto found;
1105         }
1106         /* not found */
1107         return -1;
1108
1109 found:
1110         list_del_init(&attr->list);
1111
1112         type = nla_get_u8(tb[WPROBE_ATTR_TYPE]);
1113         if (type != attr->type) {
1114                 DPRINTF("WARNING: type mismatch for %s attribute '%s' (%d != %d)\n",
1115                         (cb->addr ? "link" : "global"),
1116                         attr->name,
1117                         type, attr->type);
1118                 goto out;
1119         }
1120
1121         if ((type < WPROBE_VAL_STRING) ||
1122                 (type > WPROBE_VAL_U64))
1123                 goto out;
1124
1125         memset(&attr->val, 0, sizeof(attr->val));
1126
1127 #define HANDLE_INT_TYPE(_idx, _type) \
1128         case WPROBE_VAL_S##_type: \
1129         case WPROBE_VAL_U##_type: \
1130                 attr->val.U##_type = nla_get_u##_type(tb[_idx]); \
1131                 break
1132
1133         switch(type) {
1134                 HANDLE_INT_TYPE(type, 8);
1135                 HANDLE_INT_TYPE(type, 16);
1136                 HANDLE_INT_TYPE(type, 32);
1137                 HANDLE_INT_TYPE(type, 64);
1138                 case WPROBE_VAL_STRING:
1139                         /* unimplemented */
1140                         break;
1141         }
1142 #undef HANDLE_TYPE
1143
1144         if (attr->flags & WPROBE_F_KEEPSTAT) {
1145                 if (tb[WPROBE_VAL_SUM])
1146                         attr->val.s = nla_get_u64(tb[WPROBE_VAL_SUM]);
1147
1148                 if (tb[WPROBE_VAL_SUM_SQ])
1149                         attr->val.ss = nla_get_u64(tb[WPROBE_VAL_SUM_SQ]);
1150
1151                 if (tb[WPROBE_VAL_SAMPLES])
1152                         attr->val.n = nla_get_u32(tb[WPROBE_VAL_SAMPLES]);
1153
1154                 if (attr->val.n > 0) {
1155                         float avg = ((float) attr->val.s) / attr->val.n;
1156                         float stdev = sqrt((((float) attr->val.ss) / attr->val.n) - (avg * avg));
1157                         if (isnan(stdev))
1158                                 stdev = 0.0f;
1159                         if (isnan(avg))
1160                                 avg = 0.0f;
1161                         attr->val.avg = avg;
1162                         attr->val.stdev = stdev;
1163                 }
1164         }
1165
1166 out:
1167         list_add_tail(&attr->list, cb->list);
1168         return 0;
1169 }
1170
1171
1172 int
1173 wprobe_request_data(struct wprobe_iface *dev, const unsigned char *addr)
1174 {
1175         struct wprobe_request_cb cb;
1176         struct list_head *attrs;
1177         struct nl_msg *msg;
1178         int err;
1179
1180         msg = wprobe_new_msg(dev, WPROBE_CMD_GET_INFO, true);
1181         if (!msg)
1182                 return -ENOMEM;
1183
1184         if (addr) {
1185                 attrs = &dev->link_attr;
1186                 NLA_PUT(msg, WPROBE_ATTR_MAC, 6, addr);
1187         } else {
1188                 attrs = &dev->global_attr;
1189         }
1190
1191         INIT_LIST_HEAD(&cb.old_list);
1192         list_splice_init(attrs, &cb.old_list);
1193         cb.list = attrs;
1194
1195         err = dev->ops->send_msg(dev, msg, save_attrdata_handler, &cb);
1196         list_splice(&cb.old_list, attrs->prev);
1197         return err;
1198
1199 nla_put_failure:
1200         nlmsg_free(msg);
1201         return -ENOMEM;
1202 }
1203
1204