-ensure stats queues do not grow too big
[oweals/gnunet.git] / src / transport / plugin_transport_wlan.c
1 /*
2   This file is part of GNUnet
3   Copyright (C) 2010-2014 GNUnet e.V.
4
5   GNUnet is free software; you can redistribute it and/or modify
6   it under the terms of the GNU General Public License as published
7   by the Free Software Foundation; either version 3, or (at your
8   option) any later version.
9
10   GNUnet is distributed in the hope that it will be useful, but
11   WITHOUT ANY WARRANTY; without even the implied warranty of
12   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13   General Public License for more details.
14
15   You should have received a copy of the GNU General Public License
16   along with GNUnet; see the file COPYING.  If not, write to the
17   Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
18   Boston, MA 02110-1301, USA.
19 */
20
21 /**
22  * @file transport/plugin_transport_wlan.c
23  * @brief transport plugin for wlan and/or bluetooth
24  * @author David Brodski
25  * @author Christian Grothoff
26  *
27  * BUILD_WLAN or BUILD_BLUETOOTH must be defined such that the respective
28  * variant of this code is compiled.
29  */
30 #include "platform.h"
31 #include "gnunet_util_lib.h"
32 #include "gnunet_hello_lib.h"
33 #include "gnunet_protocols.h"
34 #include "gnunet_statistics_service.h"
35 #include "gnunet_transport_service.h"
36 #include "gnunet_transport_plugin.h"
37 #include "plugin_transport_wlan.h"
38 #include "gnunet_fragmentation_lib.h"
39 #include "gnunet_constants.h"
40
41 #if BUILD_WLAN
42 /* begin case wlan */
43 #define PLUGIN_NAME "wlan"
44 #define CONFIG_NAME "transport-wlan"
45 #define HELPER_NAME "gnunet-helper-transport-wlan"
46 #define DUMMY_HELPER_NAME "gnunet-helper-transport-wlan-dummy"
47 #define LIBGNUNET_PLUGIN_TRANSPORT_INIT libgnunet_plugin_transport_wlan_init
48 #define LIBGNUNET_PLUGIN_TRANSPORT_DONE libgnunet_plugin_transport_wlan_done
49 #define LOG(kind,...) GNUNET_log_from (kind, "transport-wlan",__VA_ARGS__)
50
51 /**
52  * time out of a mac endpoint
53  */
54 #define MACENDPOINT_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, 2)
55
56 /**
57  * We reduce the frequence of HELLO beacons in relation to
58  * the number of MAC addresses currently visible to us.
59  * This is the multiplication factor.
60  */
61 #define HELLO_BEACON_SCALING_FACTOR GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 2)
62
63
64 /* end case wlan */
65 #elif BUILD_BLUETOOTH
66 /* begin case bluetooth */
67
68 #define PLUGIN_NAME "bluetooth"
69 #define CONFIG_NAME "transport-bluetooth"
70 #define HELPER_NAME "gnunet-helper-transport-bluetooth"
71 /* yes, this is correct, we use the same dummy driver as 'wlan' */
72 #define DUMMY_HELPER_NAME "gnunet-helper-transport-wlan-dummy"
73 #define LIBGNUNET_PLUGIN_TRANSPORT_INIT libgnunet_plugin_transport_bluetooth_init
74 #define LIBGNUNET_PLUGIN_TRANSPORT_DONE libgnunet_plugin_transport_bluetooth_done
75 #define LOG(kind,...) GNUNET_log_from (kind, "transport-bluetooth",__VA_ARGS__)
76
77 /**
78  * time out of a mac endpoint
79  */
80 #define MACENDPOINT_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, 60)
81
82
83 /**
84  * We reduce the frequence of HELLO beacons in relation to
85  * the number of MAC addresses currently visible to us.
86  * This is the multiplication factor.
87  */
88 #define HELLO_BEACON_SCALING_FACTOR GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 60)
89
90 /* end case bluetooth */
91 #else
92 #error need to build wlan or bluetooth
93 #endif
94
95 /**
96  * Max size of packet (that we give to the WLAN driver for transmission)
97  */
98 #define WLAN_MTU 1430
99
100
101 /**
102  * Which network scope do we belong to?
103  */
104 #if BUILD_WLAN
105 static const enum GNUNET_ATS_Network_Type scope = GNUNET_ATS_NET_WLAN;
106 #else
107 static const enum GNUNET_ATS_Network_Type scope = GNUNET_ATS_NET_BT;
108 #endif
109
110
111 /**
112  * Maximum number of messages in defragmentation queue per MAC
113  */
114 #define MESSAGES_IN_DEFRAG_QUEUE_PER_MAC 2
115
116 /**
117  * Link layer control fields for better compatibility
118  * (i.e. GNUnet over WLAN is not IP-over-WLAN).
119  */
120 #define WLAN_LLC_DSAP_FIELD 0x1f
121 #define WLAN_LLC_SSAP_FIELD 0x1f
122
123
124 GNUNET_NETWORK_STRUCT_BEGIN
125 /**
126  * Header for messages which need fragmentation.  This is the format of
127  * a message we obtain AFTER defragmentation.  We then need to check
128  * the CRC and then tokenize the payload and pass it to the
129  * 'receive' callback.
130  */
131 struct WlanHeader
132 {
133
134   /**
135    * Message type is #GNUNET_MESSAGE_TYPE_WLAN_DATA.
136    */
137   struct GNUNET_MessageHeader header;
138
139   /**
140    * CRC32 checksum (only over the payload), in NBO.
141    */
142   uint32_t crc GNUNET_PACKED;
143
144   /**
145    * Sender of the message.
146    */
147   struct GNUNET_PeerIdentity sender;
148
149   /**
150    * Target of the message.
151    */
152   struct GNUNET_PeerIdentity target;
153
154   /* followed by payload, possibly including
155      multiple messages! */
156
157 };
158
159
160 /**
161  * Address format for WLAN.
162  */
163 struct WlanAddress
164 {
165   /**
166    * Options set for the WLAN, in NBO.
167    */
168   uint32_t options GNUNET_PACKED;
169
170   /**
171    * WLAN addresses using MACs.
172    */
173   struct GNUNET_TRANSPORT_WLAN_MacAddress mac;
174 };
175
176
177 GNUNET_NETWORK_STRUCT_END
178
179
180 /**
181  * Information kept for each message that is yet to be fragmented and
182  * transmitted.
183  */
184 struct PendingMessage
185 {
186   /**
187    * next entry in the DLL
188    */
189   struct PendingMessage *next;
190
191   /**
192    * previous entry in the DLL
193    */
194   struct PendingMessage *prev;
195
196   /**
197    * The pending message
198    */
199   struct WlanHeader *msg;
200
201   /**
202    * Continuation function to call once the message
203    * has been sent.  Can be NULL if there is no
204    * continuation to call.
205    */
206   GNUNET_TRANSPORT_TransmitContinuation transmit_cont;
207
208   /**
209    * Cls for @e transmit_cont
210    */
211   void *transmit_cont_cls;
212
213   /**
214    * Timeout task (for this message).
215    */
216   struct GNUNET_SCHEDULER_Task * timeout_task;
217
218 };
219
220
221 /**
222  * Session handle for connections with other peers.
223  */
224 struct GNUNET_ATS_Session
225 {
226   /**
227    * To whom are we talking to (set to our identity
228    * if we are still waiting for the welcome message)
229    */
230   struct GNUNET_PeerIdentity target;
231
232   /**
233    * We keep all sessions in a DLL at their respective
234    * `struct MACEndpoint *`.
235    */
236   struct GNUNET_ATS_Session *next;
237
238   /**
239    * We keep all sessions in a DLL at their respective
240    * `struct MACEndpoint *`.
241    */
242   struct GNUNET_ATS_Session *prev;
243
244   /**
245    * MAC endpoint with the address of this peer.
246    */
247   struct MacEndpoint *mac;
248
249   /**
250    * Address associated with this session and MAC endpoint
251    */
252   struct GNUNET_HELLO_Address *address;
253
254   /**
255    * When should this session time out?
256    */
257   struct GNUNET_TIME_Absolute timeout;
258
259   /**
260    * Timeout task (for the session).
261    */
262   struct GNUNET_SCHEDULER_Task * timeout_task;
263
264 };
265
266
267 /**
268  * Struct for messages that are being fragmented in a MAC's transmission queue.
269  */
270 struct FragmentMessage
271 {
272
273   /**
274    * This is a doubly-linked list.
275    */
276   struct FragmentMessage *next;
277
278   /**
279    * This is a doubly-linked list.
280    */
281   struct FragmentMessage *prev;
282
283   /**
284    * MAC endpoint this message belongs to
285    */
286   struct MacEndpoint *macendpoint;
287
288   /**
289    * Fragmentation context
290    */
291   struct GNUNET_FRAGMENT_Context *fragcontext;
292
293   /**
294    * Transmission handle to helper (to cancel if the frag context
295    * is destroyed early for some reason).
296    */
297   struct GNUNET_HELPER_SendHandle *sh;
298
299   /**
300    * Intended recipient.
301    */
302   struct GNUNET_PeerIdentity target;
303
304   /**
305    * Timeout value for the message.
306    */
307   struct GNUNET_TIME_Absolute timeout;
308
309   /**
310    * Timeout task.
311    */
312   struct GNUNET_SCHEDULER_Task * timeout_task;
313
314   /**
315    * Continuation to call when we're done with this message.
316    */
317   GNUNET_TRANSPORT_TransmitContinuation cont;
318
319   /**
320    * Message we need to fragment and transmit, NULL after the
321    * @e fragmentcontext has been created.
322    */
323   struct GNUNET_MessageHeader *msg;
324
325   /**
326    * Closure for @e cont
327    */
328   void *cont_cls;
329
330   /**
331    * Size of original message
332    */
333   size_t size_payload;
334
335   /**
336    * Number of bytes used to transmit message
337    */
338   size_t size_on_wire;
339
340 };
341
342
343 /**
344  * Struct to represent one network card connection
345  */
346 struct MacEndpoint
347 {
348
349   /**
350    * We keep all MACs in a DLL in the plugin.
351    */
352   struct MacEndpoint *next;
353
354   /**
355    * We keep all MACs in a DLL in the plugin.
356    */
357   struct MacEndpoint *prev;
358
359   /**
360    * Pointer to the global plugin struct.
361    */
362   struct Plugin *plugin;
363
364   /**
365    * Head of sessions that use this MAC.
366    */
367   struct GNUNET_ATS_Session *sessions_head;
368
369   /**
370    * Tail of sessions that use this MAC.
371    */
372   struct GNUNET_ATS_Session *sessions_tail;
373
374   /**
375    * Head of messages we are currently sending to this MAC.
376    */
377   struct FragmentMessage *sending_messages_head;
378
379   /**
380    * Tail of messages we are currently sending to this MAC.
381    */
382   struct FragmentMessage *sending_messages_tail;
383
384   /**
385    * Defrag context for this MAC
386    */
387   struct GNUNET_DEFRAGMENT_Context *defrag;
388
389   /**
390    * When should this endpoint time out?
391    */
392   struct GNUNET_TIME_Absolute timeout;
393
394   /**
395    * Timeout task.
396    */
397   struct GNUNET_SCHEDULER_Task * timeout_task;
398
399   /**
400    * count of messages in the fragment out queue for this mac endpoint
401    */
402   unsigned int fragment_messages_out_count;
403
404   /**
405    * peer MAC address
406    */
407   struct WlanAddress wlan_addr;
408
409   /**
410    * Message delay for fragmentation context
411    */
412   struct GNUNET_TIME_Relative msg_delay;
413
414   /**
415    * ACK delay for fragmentation context
416    */
417   struct GNUNET_TIME_Relative ack_delay;
418
419   /**
420    * Desired transmission power for this MAC
421    */
422   uint16_t tx_power;
423
424   /**
425    * Desired transmission rate for this MAC
426    */
427   uint8_t rate;
428
429   /**
430    * Antenna we should use for this MAC
431    */
432   uint8_t antenna;
433
434 };
435
436
437 /**
438  * Encapsulation of all of the state of the plugin.
439  */
440 struct Plugin
441 {
442   /**
443    * Our environment.
444    */
445   struct GNUNET_TRANSPORT_PluginEnvironment *env;
446
447   /**
448    * Handle to helper process for priviledged operations.
449    */
450   struct GNUNET_HELPER_Handle *suid_helper;
451
452   /**
453    * Function to call about session status changes.
454    */
455   GNUNET_TRANSPORT_SessionInfoCallback sic;
456
457   /**
458    * Closure for @e sic.
459    */
460   void *sic_cls;
461
462   /**
463    * ARGV-vector for the helper (all helpers take only the binary
464    * name, one actual argument, plus the NULL terminator for 'argv').
465    */
466   char *helper_argv[3];
467
468   /**
469    * The interface of the wlan card given to us by the user.
470    */
471   char *wlan_interface;
472
473   /**
474    * Tokenizer for demultiplexing of data packets resulting from
475    * defragmentation.
476    */
477   struct GNUNET_SERVER_MessageStreamTokenizer *fragment_data_tokenizer;
478
479   /**
480    * Tokenizer for demultiplexing of data packets received from the suid helper
481    */
482   struct GNUNET_SERVER_MessageStreamTokenizer *helper_payload_tokenizer;
483
484   /**
485    * Tokenizer for demultiplexing of data packets that follow the WLAN Header
486    */
487   struct GNUNET_SERVER_MessageStreamTokenizer *wlan_header_payload_tokenizer;
488
489   /**
490    * Head of list of open connections.
491    */
492   struct MacEndpoint *mac_head;
493
494   /**
495    * Tail of list of open connections.
496    */
497   struct MacEndpoint *mac_tail;
498
499   /**
500    * Task that periodically sends a HELLO beacon via the helper.
501    */
502   struct GNUNET_SCHEDULER_Task *beacon_task;
503
504   /**
505    * Tracker for bandwidth limit
506    */
507   struct GNUNET_BANDWIDTH_Tracker tracker;
508
509   /**
510    * The mac_address of the wlan card given to us by the helper.
511    */
512   struct GNUNET_TRANSPORT_WLAN_MacAddress mac_address;
513
514   /**
515    * Have we received a control message with our MAC address yet?
516    */
517   int have_mac;
518
519   /**
520    * Number of connections
521    */
522   unsigned int mac_count;
523
524   /**
525    * Options for addresses
526    */
527   uint32_t options;
528
529 };
530
531
532 /**
533  * Information associated with a message.  Can contain
534  * the session or the MAC endpoint associated with the
535  * message (or both).
536  */
537 struct MacAndSession
538 {
539   /**
540    * NULL if the identity of the other peer is not known.
541    */
542   struct GNUNET_ATS_Session *session;
543
544   /**
545    * MAC address of the other peer, NULL if not known.
546    */
547   struct MacEndpoint *endpoint;
548 };
549
550
551 /**
552  * Print MAC addresses nicely.
553  *
554  * @param mac the mac address
555  * @return string to a static buffer with
556  * the human-readable mac, will be overwritten during the next call to
557  * this function
558  */
559 static const char *
560 mac_to_string (const struct GNUNET_TRANSPORT_WLAN_MacAddress * mac)
561 {
562   static char macstr[20];
563
564   GNUNET_snprintf (macstr,
565                    sizeof (macstr),
566                    "%.2X:%.2X:%.2X:%.2X:%.2X:%.2X",
567                    mac->mac[0], mac->mac[1],
568                    mac->mac[2], mac->mac[3],
569                    mac->mac[4], mac->mac[5]);
570   return macstr;
571 }
572
573
574 /**
575  * Function called for a quick conversion of the binary address to
576  * a numeric address.  Note that the caller must not free the
577  * address and that the next call to this function is allowed
578  * to override the address again.
579  *
580  * @param cls closure
581  * @param addr binary address
582  * @param addrlen length of the address
583  * @return string representing the same address
584  */
585 static const char *
586 wlan_plugin_address_to_string (void *cls,
587                                const void *addr,
588                                size_t addrlen)
589 {
590   const struct GNUNET_TRANSPORT_WLAN_MacAddress *mac;
591   static char macstr[36];
592
593   if (sizeof (struct WlanAddress) != addrlen)
594   {
595     GNUNET_break (0);
596     return NULL;
597   }
598   mac = &((struct WlanAddress *) addr)->mac;
599   GNUNET_snprintf (macstr,
600                    sizeof (macstr),
601                    "%s.%u.%s",
602                    PLUGIN_NAME,
603                    ntohl (((struct WlanAddress *) addr)->options),
604                    mac_to_string (mac));
605   return macstr;
606 }
607
608
609 /**
610  * If a session monitor is attached, notify it about the new
611  * session state.
612  *
613  * @param plugin our plugin
614  * @param session session that changed state
615  * @param state new state of the session
616  */
617 static void
618 notify_session_monitor (struct Plugin *plugin,
619                         struct GNUNET_ATS_Session *session,
620                         enum GNUNET_TRANSPORT_SessionState state)
621 {
622   struct GNUNET_TRANSPORT_SessionInfo info;
623
624   if (NULL == plugin->sic)
625     return;
626   memset (&info, 0, sizeof (info));
627   info.state = state;
628   info.is_inbound = GNUNET_SYSERR; /* hard to say */
629   info.num_msg_pending = 0; /* we queue per MAC, not per peer */
630   info.num_bytes_pending = 0; /* we queue per MAC, not per peer */
631   info.receive_delay = GNUNET_TIME_UNIT_ZERO_ABS; /* not supported by WLAN */
632   info.session_timeout = session->timeout;
633   info.address = session->address;
634   plugin->sic (plugin->sic_cls,
635                session,
636                &info);
637 }
638
639
640 /**
641  * Fill the radiotap header
642  *
643  * @param endpoint pointer to the endpoint, can be NULL
644  * @param header pointer to the radiotap header
645  * @param size total message size
646  */
647 static void
648 get_radiotap_header (struct MacEndpoint *endpoint,
649                      struct GNUNET_TRANSPORT_WLAN_RadiotapSendMessage *header,
650                      uint16_t size)
651 {
652   header->header.type = ntohs (GNUNET_MESSAGE_TYPE_WLAN_DATA_TO_HELPER);
653   header->header.size = ntohs (size);
654   if (NULL != endpoint)
655   {
656     header->rate = endpoint->rate;
657     header->tx_power = endpoint->tx_power;
658     header->antenna = endpoint->antenna;
659   }
660   else
661   {
662     header->rate = 255;
663     header->tx_power = 0;
664     header->antenna = 0;
665   }
666 }
667
668
669 /**
670  * Generate the WLAN hardware header for one packet
671  *
672  * @param plugin the plugin handle
673  * @param header address to write the header to
674  * @param to_mac_addr address of the recipient
675  * @param size size of the whole packet, needed to calculate the time to send the packet
676  */
677 static void
678 get_wlan_header (struct Plugin *plugin,
679                  struct GNUNET_TRANSPORT_WLAN_Ieee80211Frame *header,
680                  const struct GNUNET_TRANSPORT_WLAN_MacAddress *to_mac_addr,
681                  unsigned int size)
682 {
683   const int rate = 11000000;
684
685   header->frame_control = htons (IEEE80211_FC0_TYPE_DATA);
686   header->addr1 = *to_mac_addr;
687   header->addr2 = plugin->mac_address;
688   header->addr3 = mac_bssid_gnunet;
689   header->duration = GNUNET_htole16 ((size * 1000000) / rate + 290);
690   header->sequence_control = 0; // FIXME?
691   header->llc[0] = WLAN_LLC_DSAP_FIELD;
692   header->llc[1] = WLAN_LLC_SSAP_FIELD;
693   header->llc[2] = 0;  // FIXME?
694   header->llc[3] = 0;  // FIXME?
695 }
696
697
698 /**
699  * Send an ACK for a fragment we received.
700  *
701  * @param cls the `struct MacEndpoint *` the ACK must be sent to
702  * @param msg_id id of the message
703  * @param hdr pointer to the hdr where the ack is stored
704  */
705 static void
706 send_ack (void *cls,
707           uint32_t msg_id,
708           const struct GNUNET_MessageHeader *hdr)
709 {
710   struct MacEndpoint *endpoint = cls;
711   struct GNUNET_TRANSPORT_WLAN_RadiotapSendMessage* radio_header;
712   uint16_t msize = ntohs (hdr->size);
713   size_t size = sizeof (struct GNUNET_TRANSPORT_WLAN_RadiotapSendMessage) + msize;
714   char buf[size];
715
716   if (NULL == endpoint)
717   {
718     GNUNET_break (0);
719     return;
720   }
721   if (size >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
722   {
723     GNUNET_break (0);
724     return;
725   }
726   LOG (GNUNET_ERROR_TYPE_DEBUG,
727        "Sending ACK to %s\n",
728        mac_to_string (&endpoint->wlan_addr.mac));
729   radio_header = (struct GNUNET_TRANSPORT_WLAN_RadiotapSendMessage *) buf;
730   get_radiotap_header (endpoint, radio_header, size);
731   get_wlan_header (endpoint->plugin,
732                    &radio_header->frame,
733                    &endpoint->wlan_addr.mac,
734                    sizeof (endpoint->wlan_addr.mac));
735   memcpy (&radio_header[1], hdr, msize);
736   if (NULL !=
737       GNUNET_HELPER_send (endpoint->plugin->suid_helper,
738                           &radio_header->header,
739                           GNUNET_NO /* dropping ACKs is bad */,
740                           NULL, NULL))
741     GNUNET_STATISTICS_update (endpoint->plugin->env->stats,
742                               _("# ACKs sent"),
743                               1, GNUNET_NO);
744 }
745
746
747 /**
748  * Handles the data after all fragments are put together
749  *
750  * @param cls macendpoint this messages belongs to
751  * @param hdr pointer to the data
752  */
753 static void
754 wlan_data_message_handler (void *cls,
755                            const struct GNUNET_MessageHeader *hdr)
756 {
757   struct MacEndpoint *endpoint = cls;
758   struct Plugin *plugin = endpoint->plugin;
759   struct MacAndSession mas;
760
761   GNUNET_STATISTICS_update (plugin->env->stats,
762                             _("# Messages defragmented"),
763                             1,
764                             GNUNET_NO);
765   mas.session = NULL;
766   mas.endpoint = endpoint;
767   (void) GNUNET_SERVER_mst_receive (plugin->fragment_data_tokenizer,
768                                     &mas,
769                                     (const char *) hdr,
770                                     ntohs (hdr->size),
771                                     GNUNET_YES, GNUNET_NO);
772 }
773
774
775 /**
776  * Free a session
777  *
778  * @param cls our `struct Plugin`.
779  * @param session the session free
780  */
781 static int
782 wlan_plugin_disconnect_session (void *cls,
783                                 struct GNUNET_ATS_Session *session)
784 {
785   struct MacEndpoint *endpoint = session->mac;
786   struct Plugin *plugin = endpoint->plugin;
787
788   plugin->env->session_end (plugin->env->cls,
789                             session->address,
790                             session);
791   notify_session_monitor (plugin,
792                           session,
793                           GNUNET_TRANSPORT_SS_DONE);
794   GNUNET_CONTAINER_DLL_remove (endpoint->sessions_head,
795                                endpoint->sessions_tail,
796                                session);
797   if (session->timeout_task != NULL)
798   {
799     GNUNET_SCHEDULER_cancel (session->timeout_task);
800     session->timeout_task = NULL;
801   }
802   GNUNET_STATISTICS_update (plugin->env->stats,
803                             _("# Sessions allocated"),
804                             -1,
805                             GNUNET_NO);
806   GNUNET_HELLO_address_free (session->address);
807   GNUNET_free (session);
808   return GNUNET_OK;
809 }
810
811
812 /**
813  * Function that is called to get the keepalive factor.
814  * #GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT is divided by this number to
815  * calculate the interval between keepalive packets.
816  *
817  * @param cls closure with the `struct Plugin`
818  * @return keepalive factor
819  */
820 static unsigned int
821 wlan_plugin_query_keepalive_factor (void *cls)
822 {
823   return 3;
824 }
825
826
827 /**
828  * A session is timing out.  Clean up.
829  *
830  * @param cls pointer to the Session
831  */
832 static void
833 session_timeout (void *cls)
834 {
835   struct GNUNET_ATS_Session *session = cls;
836   struct GNUNET_TIME_Relative left;
837
838   session->timeout_task = NULL;
839   left = GNUNET_TIME_absolute_get_remaining (session->timeout);
840   if (0 != left.rel_value_us)
841   {
842     session->timeout_task =
843       GNUNET_SCHEDULER_add_delayed (left,
844                                     &session_timeout,
845                                     session);
846     return;
847   }
848   wlan_plugin_disconnect_session (session->mac->plugin,
849                                   session);
850 }
851
852
853
854 /**
855  * Lookup a new session
856  *
857  * @param endpoint pointer to the mac endpoint of the peer
858  * @param peer peer identity to use for this session
859  * @return returns the session or NULL
860  */
861 static struct GNUNET_ATS_Session *
862 lookup_session (struct MacEndpoint *endpoint,
863                 const struct GNUNET_PeerIdentity *peer)
864 {
865   struct GNUNET_ATS_Session *session;
866
867   for (session = endpoint->sessions_head; NULL != session; session = session->next)
868     if (0 == memcmp (peer, &session->target, sizeof (struct GNUNET_PeerIdentity)))
869       return session;
870   return NULL;
871 }
872
873
874 /**
875  * Create a new session
876  *
877  * @param endpoint pointer to the mac endpoint of the peer
878  * @param peer peer identity to use for this session
879  * @return returns the session or NULL
880  */
881 static struct GNUNET_ATS_Session *
882 create_session (struct MacEndpoint *endpoint,
883                 const struct GNUNET_PeerIdentity *peer)
884 {
885   struct GNUNET_ATS_Session *session;
886
887   GNUNET_STATISTICS_update (endpoint->plugin->env->stats,
888                             _("# Sessions allocated"),
889                             1,
890                             GNUNET_NO);
891   session = GNUNET_new (struct GNUNET_ATS_Session);
892   GNUNET_CONTAINER_DLL_insert_tail (endpoint->sessions_head,
893                                     endpoint->sessions_tail,
894                                     session);
895   session->address = GNUNET_HELLO_address_allocate (peer,
896                                                     PLUGIN_NAME,
897                                                     &endpoint->wlan_addr,
898                                                     sizeof (endpoint->wlan_addr),
899                                                     GNUNET_HELLO_ADDRESS_INFO_NONE);
900   session->mac = endpoint;
901   session->target = *peer;
902   session->timeout = GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
903   session->timeout_task =
904       GNUNET_SCHEDULER_add_delayed (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, &session_timeout,
905                                     session);
906   notify_session_monitor (endpoint->plugin,
907                           session,
908                           GNUNET_TRANSPORT_SS_INIT);
909   notify_session_monitor (endpoint->plugin,
910                           session,
911                           GNUNET_TRANSPORT_SS_UP);
912   LOG (GNUNET_ERROR_TYPE_DEBUG,
913        "Created new session %p for peer `%s' with endpoint %s\n",
914        session,
915        GNUNET_i2s (peer),
916        mac_to_string (&endpoint->wlan_addr.mac));
917
918   return session;
919 }
920
921
922 /**
923  * Look up a session for a peer and create a new session if none is found
924  *
925  * @param endpoint pointer to the mac endpoint of the peer
926  * @param peer peer identity to use for this session
927  * @return returns the session
928  */
929 static struct GNUNET_ATS_Session *
930 get_session (struct MacEndpoint *endpoint,
931              const struct GNUNET_PeerIdentity *peer)
932 {
933   struct GNUNET_ATS_Session *session;
934
935   if (NULL != (session = lookup_session (endpoint, peer)))
936     return session;
937   return create_session (endpoint, peer);
938 }
939
940
941 /**
942  * Function called once we have successfully given the fragment
943  * message to the SUID helper process and we are thus ready for
944  * the next fragment.
945  *
946  * @param cls the `struct FragmentMessage *`
947  * @param result result of the operation (#GNUNET_OK on success,
948  *        #GNUNET_NO if the helper died, #GNUNET_SYSERR
949  *        if the helper was stopped)
950  */
951 static void
952 fragment_transmission_done (void *cls,
953                             int result)
954 {
955   struct FragmentMessage *fm = cls;
956
957   fm->sh = NULL;
958   GNUNET_FRAGMENT_context_transmission_done (fm->fragcontext);
959 }
960
961
962 /**
963  * Transmit a fragment of a message.
964  *
965  * @param cls `struct FragmentMessage *` this fragment message belongs to
966  * @param hdr pointer to the start of the fragment message
967  */
968 static void
969 transmit_fragment (void *cls,
970                    const struct GNUNET_MessageHeader *hdr)
971 {
972   struct FragmentMessage *fm = cls;
973   struct MacEndpoint *endpoint = fm->macendpoint;
974   size_t size;
975   uint16_t msize;
976
977   if (NULL == endpoint)
978   {
979     GNUNET_break (0);
980     return;
981   }
982   msize = ntohs (hdr->size);
983   size = sizeof (struct GNUNET_TRANSPORT_WLAN_RadiotapSendMessage) + msize;
984   {
985     char buf[size];
986     struct GNUNET_TRANSPORT_WLAN_RadiotapSendMessage *radio_header;
987
988     radio_header = (struct GNUNET_TRANSPORT_WLAN_RadiotapSendMessage *) buf;
989     get_radiotap_header (endpoint, radio_header, size);
990     LOG (GNUNET_ERROR_TYPE_DEBUG,
991          "Sending %u bytes of data to MAC `%s'\n",
992          (unsigned int) msize,
993          mac_to_string (&endpoint->wlan_addr.mac));
994
995     get_wlan_header (endpoint->plugin,
996                      &radio_header->frame,
997                      &endpoint->wlan_addr.mac,
998                      sizeof (endpoint->wlan_addr.mac));
999     memcpy (&radio_header[1], hdr, msize);
1000     GNUNET_assert (NULL == fm->sh);
1001     fm->sh = GNUNET_HELPER_send (endpoint->plugin->suid_helper,
1002                                  &radio_header->header,
1003                                  GNUNET_NO,
1004                                  &fragment_transmission_done, fm);
1005     fm->size_on_wire += size;
1006     if (NULL != fm->sh)
1007     {
1008       GNUNET_STATISTICS_update (endpoint->plugin->env->stats,
1009                                 _("# message fragments sent"),
1010                                 1,
1011                                 GNUNET_NO);
1012     }
1013     else
1014     {
1015       GNUNET_FRAGMENT_context_transmission_done (fm->fragcontext);
1016     }
1017     GNUNET_STATISTICS_update (endpoint->plugin->env->stats,
1018                               "# bytes currently in buffers",
1019                               -msize, GNUNET_NO);
1020     GNUNET_STATISTICS_update (endpoint->plugin->env->stats,
1021                               "# bytes transmitted",
1022                               msize, GNUNET_NO);
1023   }
1024 }
1025
1026
1027 /**
1028  * Frees the space of a message in the fragment queue (send queue)
1029  *
1030  * @param fm message to free
1031  */
1032 static void
1033 free_fragment_message (struct FragmentMessage *fm)
1034 {
1035   struct MacEndpoint *endpoint = fm->macendpoint;
1036
1037   GNUNET_STATISTICS_update (endpoint->plugin->env->stats,
1038                             _("# messages pending (with fragmentation)"),
1039                             -1, GNUNET_NO);
1040   GNUNET_CONTAINER_DLL_remove (endpoint->sending_messages_head,
1041                                endpoint->sending_messages_tail,
1042                                fm);
1043   if (NULL != fm->sh)
1044   {
1045     GNUNET_HELPER_send_cancel (fm->sh);
1046     fm->sh = NULL;
1047   }
1048   if (NULL != fm->msg)
1049   {
1050     GNUNET_free (fm->msg);
1051     fm->msg = NULL;
1052   }
1053   if (NULL != fm->fragcontext)
1054   {
1055     GNUNET_FRAGMENT_context_destroy (fm->fragcontext,
1056                                      &endpoint->msg_delay,
1057                                      &endpoint->ack_delay);
1058     fm->fragcontext = NULL;
1059   }
1060   if (NULL != fm->timeout_task)
1061   {
1062     GNUNET_SCHEDULER_cancel (fm->timeout_task);
1063     fm->timeout_task = NULL;
1064   }
1065   GNUNET_free (fm);
1066 }
1067
1068
1069 /**
1070  * A FragmentMessage has timed out.  Remove it.
1071  *
1072  * @param cls pointer to the 'struct FragmentMessage'
1073  */
1074 static void
1075 fragmentmessage_timeout (void *cls)
1076 {
1077   struct FragmentMessage *fm = cls;
1078
1079   fm->timeout_task = NULL;
1080   if (NULL != fm->cont)
1081   {
1082     fm->cont (fm->cont_cls,
1083               &fm->target,
1084               GNUNET_SYSERR,
1085               fm->size_payload,
1086               fm->size_on_wire);
1087     fm->cont = NULL;
1088   }
1089   free_fragment_message (fm);
1090 }
1091
1092
1093 /**
1094  * Transmit a message to the given destination with fragmentation.
1095  *
1096  * @param endpoint desired destination
1097  * @param timeout how long can the message wait?
1098  * @param target peer that should receive the message
1099  * @param msg message to transmit
1100  * @param payload_size bytes of payload
1101  * @param cont continuation to call once the message has
1102  *        been transmitted (or if the transport is ready
1103  *        for the next transmission call; or if the
1104  *        peer disconnected...); can be NULL
1105  * @param cont_cls closure for @a cont
1106  */
1107 static void
1108 send_with_fragmentation (struct MacEndpoint *endpoint,
1109                          struct GNUNET_TIME_Relative timeout,
1110                          const struct GNUNET_PeerIdentity *target,
1111                          const struct GNUNET_MessageHeader *msg,
1112                          size_t payload_size,
1113                          GNUNET_TRANSPORT_TransmitContinuation cont,
1114                          void *cont_cls)
1115
1116 {
1117   struct FragmentMessage *fm;
1118   struct Plugin *plugin;
1119
1120   plugin = endpoint->plugin;
1121   fm = GNUNET_new (struct FragmentMessage);
1122   fm->macendpoint = endpoint;
1123   fm->target = *target;
1124   fm->size_payload = payload_size;
1125   fm->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1126   fm->cont = cont;
1127   fm->cont_cls = cont_cls;
1128   /* 1 MBit/s typical data rate, 1430 byte fragments => ~100 ms per message */
1129   fm->timeout_task =
1130     GNUNET_SCHEDULER_add_delayed (timeout,
1131                                   &fragmentmessage_timeout,
1132                                   fm);
1133   if (GNUNET_YES == plugin->have_mac)
1134   {
1135     fm->fragcontext =
1136       GNUNET_FRAGMENT_context_create (plugin->env->stats,
1137                                       WLAN_MTU,
1138                                       &plugin->tracker,
1139                                       fm->macendpoint->msg_delay,
1140                                       fm->macendpoint->ack_delay,
1141                                       msg,
1142                                       &transmit_fragment, fm);
1143   }
1144   else
1145   {
1146     fm->msg = GNUNET_copy_message (msg);
1147   }
1148   GNUNET_CONTAINER_DLL_insert_tail (endpoint->sending_messages_head,
1149                                     endpoint->sending_messages_tail,
1150                                     fm);
1151 }
1152
1153
1154 /**
1155  * Free a MAC endpoint.
1156  *
1157  * @param endpoint pointer to the MacEndpoint to free
1158  */
1159 static void
1160 free_macendpoint (struct MacEndpoint *endpoint)
1161 {
1162   struct Plugin *plugin = endpoint->plugin;
1163   struct FragmentMessage *fm;
1164   struct GNUNET_ATS_Session *session;
1165
1166   GNUNET_STATISTICS_update (plugin->env->stats,
1167                             _("# MAC endpoints allocated"),
1168                             -1,
1169                             GNUNET_NO);
1170   while (NULL != (session = endpoint->sessions_head))
1171     wlan_plugin_disconnect_session (plugin,
1172                                     session);
1173   while (NULL != (fm = endpoint->sending_messages_head))
1174     free_fragment_message (fm);
1175   GNUNET_CONTAINER_DLL_remove (plugin->mac_head,
1176                                plugin->mac_tail,
1177                                endpoint);
1178
1179   if (NULL != endpoint->defrag)
1180   {
1181     GNUNET_DEFRAGMENT_context_destroy(endpoint->defrag);
1182     endpoint->defrag = NULL;
1183   }
1184
1185   plugin->mac_count--;
1186   if (NULL != endpoint->timeout_task)
1187   {
1188     GNUNET_SCHEDULER_cancel (endpoint->timeout_task);
1189     endpoint->timeout_task = NULL;
1190   }
1191   GNUNET_free (endpoint);
1192 }
1193
1194
1195 /**
1196  * A MAC endpoint is timing out.  Clean up.
1197  *
1198  * @param cls pointer to the `struct MacEndpoint *`
1199  */
1200 static void
1201 macendpoint_timeout (void *cls)
1202 {
1203   struct MacEndpoint *endpoint = cls;
1204   struct GNUNET_TIME_Relative timeout;
1205
1206   endpoint->timeout_task = NULL;
1207   timeout = GNUNET_TIME_absolute_get_remaining (endpoint->timeout);
1208   if (0 == timeout.rel_value_us)
1209   {
1210     free_macendpoint (endpoint);
1211     return;
1212   }
1213   endpoint->timeout_task =
1214     GNUNET_SCHEDULER_add_delayed (timeout,
1215                                   &macendpoint_timeout,
1216                                   endpoint);
1217 }
1218
1219
1220 /**
1221  * Find (or create) a MacEndpoint with a specific MAC address
1222  *
1223  * @param plugin pointer to the plugin struct
1224  * @param mac the MAC address of the endpoint
1225  * @return handle to our data structure for this MAC
1226  */
1227 static struct MacEndpoint *
1228 create_macendpoint (struct Plugin *plugin,
1229                     struct WlanAddress *mac)
1230 {
1231   struct MacEndpoint *pos;
1232
1233   for (pos = plugin->mac_head; NULL != pos; pos = pos->next)
1234     if (0 == memcmp (mac, &pos->wlan_addr, sizeof (pos->wlan_addr)))
1235       return pos;
1236   pos = GNUNET_new (struct MacEndpoint);
1237   pos->wlan_addr = (*mac);
1238   pos->plugin = plugin;
1239   pos->defrag =
1240     GNUNET_DEFRAGMENT_context_create (plugin->env->stats,
1241                                       WLAN_MTU,
1242                                       MESSAGES_IN_DEFRAG_QUEUE_PER_MAC,
1243                                       pos,
1244                                       &wlan_data_message_handler,
1245                                       &send_ack);
1246
1247   pos->msg_delay = GNUNET_TIME_UNIT_MILLISECONDS;
1248   pos->ack_delay = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, 100);
1249   pos->timeout = GNUNET_TIME_relative_to_absolute (MACENDPOINT_TIMEOUT);
1250   pos->timeout_task =
1251       GNUNET_SCHEDULER_add_delayed (MACENDPOINT_TIMEOUT, &macendpoint_timeout,
1252                                     pos);
1253   GNUNET_CONTAINER_DLL_insert (plugin->mac_head,
1254                                plugin->mac_tail,
1255                                pos);
1256   plugin->mac_count++;
1257   GNUNET_STATISTICS_update (plugin->env->stats,
1258                             _("# MAC endpoints allocated"),
1259                             1, GNUNET_NO);
1260   LOG (GNUNET_ERROR_TYPE_DEBUG,
1261        "New MAC endpoint `%s'\n",
1262        wlan_plugin_address_to_string (NULL,
1263                                       &pos->wlan_addr,
1264                                       sizeof (struct WlanAddress)));
1265   return pos;
1266 }
1267
1268
1269 /**
1270  * Function obtain the network type for a session
1271  *
1272  * @param cls closure (`struct Plugin*`)
1273  * @param session the session
1274  * @return the network type in HBO or #GNUNET_SYSERR
1275  */
1276 static enum GNUNET_ATS_Network_Type
1277 wlan_plugin_get_network (void *cls,
1278                          struct GNUNET_ATS_Session *session)
1279 {
1280 #if BUILD_WLAN
1281   return GNUNET_ATS_NET_WLAN;
1282 #else
1283   return GNUNET_ATS_NET_BT;
1284 #endif
1285 }
1286
1287
1288 /**
1289  * Function obtain the network type for an address.
1290  *
1291  * @param cls closure (`struct Plugin *`)
1292  * @param address the address
1293  * @return the network type
1294  */
1295 static enum GNUNET_ATS_Network_Type
1296 wlan_plugin_get_network_for_address (void *cls,
1297                                     const struct GNUNET_HELLO_Address *address)
1298 {
1299 #if BUILD_WLAN
1300   return GNUNET_ATS_NET_WLAN;
1301 #else
1302   return GNUNET_ATS_NET_BT;
1303 #endif
1304 }
1305
1306
1307 /**
1308  * Creates a new outbound session the transport service will use to
1309  * send data to the peer
1310  *
1311  * @param cls the `struct Plugin *`
1312  * @param address the address
1313  * @return the session or NULL of max connections exceeded
1314  */
1315 static struct GNUNET_ATS_Session *
1316 wlan_plugin_get_session (void *cls,
1317                          const struct GNUNET_HELLO_Address *address)
1318 {
1319   struct Plugin *plugin = cls;
1320   struct MacEndpoint *endpoint;
1321
1322   if (NULL == address)
1323     return NULL;
1324   if (sizeof (struct WlanAddress) != address->address_length)
1325   {
1326     GNUNET_break (0);
1327     return NULL;
1328   }
1329   LOG (GNUNET_ERROR_TYPE_DEBUG,
1330        "Service asked to create session for peer `%s' with MAC `%s'\n",
1331        GNUNET_i2s (&address->peer),
1332        wlan_plugin_address_to_string (NULL,
1333                                       address->address,
1334                                       address->address_length));
1335   endpoint = create_macendpoint (plugin,
1336                                  (struct WlanAddress *) address->address);
1337   return get_session (endpoint, &address->peer);
1338 }
1339
1340
1341 /**
1342  * Function that can be used to force the plugin to disconnect
1343  * from the given peer and cancel all previous transmissions
1344  * (and their continuation).
1345  *
1346  * @param cls closure
1347  * @param target peer from which to disconnect
1348  */
1349 static void
1350 wlan_plugin_disconnect_peer (void *cls,
1351                              const struct GNUNET_PeerIdentity *target)
1352 {
1353   struct Plugin *plugin = cls;
1354   struct GNUNET_ATS_Session *session;
1355   struct MacEndpoint *endpoint;
1356
1357   for (endpoint = plugin->mac_head; NULL != endpoint; endpoint = endpoint->next)
1358     for (session = endpoint->sessions_head; NULL != session; session = session->next)
1359       if (0 == memcmp (target, &session->target,
1360                        sizeof (struct GNUNET_PeerIdentity)))
1361       {
1362         wlan_plugin_disconnect_session (plugin, session);
1363         break; /* inner-loop only (in case peer has another MAC as well!) */
1364       }
1365 }
1366
1367
1368 /**
1369  * Function that can be used by the transport service to transmit
1370  * a message using the plugin.   Note that in the case of a
1371  * peer disconnecting, the continuation MUST be called
1372  * prior to the disconnect notification itself.  This function
1373  * will be called with this peer's HELLO message to initiate
1374  * a fresh connection to another peer.
1375  *
1376  * @param cls closure
1377  * @param session which session must be used
1378  * @param msgbuf the message to transmit
1379  * @param msgbuf_size number of bytes in @a msgbuf
1380  * @param priority how important is the message (most plugins will
1381  *                 ignore message priority and just FIFO)
1382  * @param to how long to wait at most for the transmission (does not
1383  *                require plugins to discard the message after the timeout,
1384  *                just advisory for the desired delay; most plugins will ignore
1385  *                this as well)
1386  * @param cont continuation to call once the message has
1387  *        been transmitted (or if the transport is ready
1388  *        for the next transmission call; or if the
1389  *        peer disconnected...); can be NULL
1390  * @param cont_cls closure for @a cont
1391  * @return number of bytes used (on the physical network, with overheads);
1392  *         -1 on hard errors (i.e. address invalid); 0 is a legal value
1393  *         and does NOT mean that the message was not transmitted (DV)
1394  */
1395 static ssize_t
1396 wlan_plugin_send (void *cls,
1397                   struct GNUNET_ATS_Session *session,
1398                   const char *msgbuf, size_t msgbuf_size,
1399                   unsigned int priority,
1400                   struct GNUNET_TIME_Relative to,
1401                   GNUNET_TRANSPORT_TransmitContinuation cont, void *cont_cls)
1402 {
1403   struct Plugin *plugin = cls;
1404   struct WlanHeader *wlanheader;
1405   size_t size = msgbuf_size + sizeof (struct WlanHeader);
1406   char buf[size] GNUNET_ALIGN;
1407
1408   LOG (GNUNET_ERROR_TYPE_DEBUG,
1409        "Transmitting %u bytes of payload to peer `%s' (starting with %u byte message of type %u)\n",
1410        msgbuf_size,
1411        GNUNET_i2s (&session->target),
1412        (unsigned int) ntohs (((struct GNUNET_MessageHeader*)msgbuf)->size),
1413        (unsigned int) ntohs (((struct GNUNET_MessageHeader*)msgbuf)->type));
1414   wlanheader = (struct WlanHeader *) buf;
1415   wlanheader->header.size = htons (msgbuf_size + sizeof (struct WlanHeader));
1416   wlanheader->header.type = htons (GNUNET_MESSAGE_TYPE_WLAN_DATA);
1417   wlanheader->sender = *plugin->env->my_identity;
1418   wlanheader->target = session->target;
1419   wlanheader->crc = htonl (GNUNET_CRYPTO_crc32_n (msgbuf, msgbuf_size));
1420   memcpy (&wlanheader[1],
1421           msgbuf,
1422           msgbuf_size);
1423   GNUNET_STATISTICS_update (plugin->env->stats,
1424                             "# bytes currently in buffers",
1425                             msgbuf_size,
1426                             GNUNET_NO);
1427   send_with_fragmentation (session->mac,
1428                            to,
1429                            &session->target,
1430                            &wlanheader->header,
1431                            msgbuf_size,
1432                            cont, cont_cls);
1433   return size;
1434 }
1435
1436
1437 /**
1438  * We have received data from the WLAN via some session.  Process depending
1439  * on the message type (HELLO, DATA, FRAGMENTATION or FRAGMENTATION-ACK).
1440  *
1441  * @param cls pointer to the plugin
1442  * @param client pointer to the session this message belongs to
1443  * @param hdr start of the message
1444  */
1445 static int
1446 process_data (void *cls,
1447               void *client,
1448               const struct GNUNET_MessageHeader *hdr)
1449 {
1450   struct Plugin *plugin = cls;
1451   struct GNUNET_HELLO_Address *address;
1452   struct MacAndSession *mas = client;
1453   struct FragmentMessage *fm;
1454   struct GNUNET_PeerIdentity tmpsource;
1455   const struct WlanHeader *wlanheader;
1456   int ret;
1457   uint16_t msize;
1458
1459   msize = ntohs (hdr->size);
1460
1461   GNUNET_STATISTICS_update (plugin->env->stats,
1462                             "# bytes received",
1463                             msize, GNUNET_NO);
1464
1465   switch (ntohs (hdr->type))
1466   {
1467   case GNUNET_MESSAGE_TYPE_HELLO:
1468
1469     if (GNUNET_OK !=
1470         GNUNET_HELLO_get_id ((const struct GNUNET_HELLO_Message *) hdr,
1471                              &tmpsource))
1472     {
1473       GNUNET_break_op (0);
1474       break;
1475     }
1476     if (NULL == mas->endpoint)
1477     {
1478       GNUNET_break (0);
1479       break;
1480     }
1481
1482     LOG (GNUNET_ERROR_TYPE_DEBUG,
1483          "Processing %u bytes of HELLO from peer `%s' at MAC %s\n",
1484          (unsigned int) msize,
1485          GNUNET_i2s (&tmpsource),
1486          wlan_plugin_address_to_string (NULL,
1487                                         &mas->endpoint->wlan_addr,
1488                                         sizeof (mas->endpoint->wlan_addr)));
1489
1490     GNUNET_STATISTICS_update (plugin->env->stats,
1491                               _("# HELLO messages received"), 1,
1492                               GNUNET_NO);
1493     address = GNUNET_HELLO_address_allocate (&tmpsource,
1494                                              PLUGIN_NAME,
1495                                              &mas->endpoint->wlan_addr,
1496                                              sizeof (mas->endpoint->wlan_addr),
1497                                              GNUNET_HELLO_ADDRESS_INFO_NONE);
1498     mas->session = lookup_session (mas->endpoint,
1499                                    &tmpsource);
1500     if (NULL == mas->session)
1501     {
1502       mas->session = create_session (mas->endpoint,
1503                                      &tmpsource);
1504       plugin->env->session_start (plugin->env->cls,
1505                                   address,
1506                                   mas->session,
1507                                   scope);
1508     }
1509     plugin->env->receive (plugin->env->cls,
1510                           address,
1511                           mas->session,
1512                           hdr);
1513     GNUNET_HELLO_address_free (address);
1514     break;
1515   case GNUNET_MESSAGE_TYPE_FRAGMENT:
1516     if (NULL == mas->endpoint)
1517     {
1518       GNUNET_break (0);
1519       break;
1520     }
1521     LOG (GNUNET_ERROR_TYPE_DEBUG,
1522          "Processing %u bytes of FRAGMENT from MAC %s\n",
1523          (unsigned int) msize,
1524          wlan_plugin_address_to_string (NULL,
1525                                         &mas->endpoint->wlan_addr,
1526                                         sizeof (mas->endpoint->wlan_addr)));
1527     GNUNET_STATISTICS_update (plugin->env->stats,
1528                               _("# fragments received"),
1529                               1,
1530                               GNUNET_NO);
1531     (void) GNUNET_DEFRAGMENT_process_fragment (mas->endpoint->defrag,
1532                                               hdr);
1533     break;
1534   case GNUNET_MESSAGE_TYPE_FRAGMENT_ACK:
1535     if (NULL == mas->endpoint)
1536     {
1537       GNUNET_break (0);
1538       break;
1539     }
1540     GNUNET_STATISTICS_update (plugin->env->stats,
1541                               _("# ACKs received"),
1542                               1, GNUNET_NO);
1543     for (fm = mas->endpoint->sending_messages_head; NULL != fm; fm = fm->next)
1544     {
1545       ret = GNUNET_FRAGMENT_process_ack (fm->fragcontext, hdr);
1546       if (GNUNET_OK == ret)
1547       {
1548         LOG (GNUNET_ERROR_TYPE_DEBUG,
1549              "Got last ACK, finished message transmission to `%s' (%p)\n",
1550              wlan_plugin_address_to_string (NULL,
1551                                             &mas->endpoint->wlan_addr,
1552                                             sizeof (mas->endpoint->wlan_addr)),
1553              fm);
1554         mas->endpoint->timeout = GNUNET_TIME_relative_to_absolute (MACENDPOINT_TIMEOUT);
1555         if (NULL != fm->cont)
1556         {
1557           fm->cont (fm->cont_cls,
1558                     &fm->target,
1559                     GNUNET_OK,
1560                     fm->size_payload,
1561                     fm->size_on_wire);
1562           fm->cont = NULL;
1563         }
1564         free_fragment_message (fm);
1565         break;
1566       }
1567       if (GNUNET_NO == ret)
1568       {
1569         LOG (GNUNET_ERROR_TYPE_DEBUG,
1570              "Got an ACK, message transmission to `%s' not yet finished\n",
1571              wlan_plugin_address_to_string (NULL,
1572                                             &mas->endpoint->wlan_addr,
1573                                             sizeof (mas->endpoint->wlan_addr)));
1574         break;
1575       }
1576     }
1577     if (NULL == fm)
1578       LOG (GNUNET_ERROR_TYPE_DEBUG,
1579            "ACK not matched against any active fragmentation with MAC `%s'\n",
1580            wlan_plugin_address_to_string (NULL,
1581                                           &mas->endpoint->wlan_addr,
1582                                           sizeof (mas->endpoint->wlan_addr)));
1583     break;
1584   case GNUNET_MESSAGE_TYPE_WLAN_DATA:
1585     if (NULL == mas->endpoint)
1586     {
1587       GNUNET_break (0);
1588       break;
1589     }
1590     if (msize < sizeof (struct WlanHeader))
1591     {
1592       GNUNET_break (0);
1593       break;
1594     }
1595     wlanheader = (const struct WlanHeader *) hdr;
1596     if (0 != memcmp (&wlanheader->target,
1597                      plugin->env->my_identity,
1598                      sizeof (struct GNUNET_PeerIdentity)))
1599     {
1600       LOG (GNUNET_ERROR_TYPE_DEBUG,
1601            "Data for `%s', not for me, ignoring\n",
1602            GNUNET_i2s (&wlanheader->target));
1603       break;
1604     }
1605     if (ntohl (wlanheader->crc) !=
1606         GNUNET_CRYPTO_crc32_n (&wlanheader[1],
1607                                msize - sizeof (struct WlanHeader)))
1608     {
1609       GNUNET_STATISTICS_update (plugin->env->stats,
1610                                 _("# DATA messages discarded due to CRC32 error"),
1611                                 1,
1612                                 GNUNET_NO);
1613       break;
1614     }
1615     mas->session = lookup_session (mas->endpoint,
1616                                    &wlanheader->sender);
1617     if (NULL == mas->session)
1618     {
1619       mas->session = create_session (mas->endpoint,
1620                                      &wlanheader->sender);
1621       address = GNUNET_HELLO_address_allocate (&wlanheader->sender,
1622                                                PLUGIN_NAME,
1623                                                &mas->endpoint->wlan_addr,
1624                                                sizeof (struct WlanAddress),
1625                                                GNUNET_HELLO_ADDRESS_INFO_NONE);
1626       plugin->env->session_start (plugin->env->cls,
1627                                   address,
1628                                   mas->session,
1629                                   scope);
1630       LOG (GNUNET_ERROR_TYPE_DEBUG,
1631            "Notifying transport about peer `%s''s new session %p \n",
1632            GNUNET_i2s (&wlanheader->sender),
1633            mas->session);
1634       GNUNET_HELLO_address_free (address);
1635     }
1636     LOG (GNUNET_ERROR_TYPE_DEBUG,
1637          "Processing %u bytes of DATA from peer `%s'\n",
1638          (unsigned int) msize,
1639          GNUNET_i2s (&wlanheader->sender));
1640     mas->session->timeout = GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
1641     (void) GNUNET_SERVER_mst_receive (plugin->wlan_header_payload_tokenizer,
1642                                       mas,
1643                                       (const char *) &wlanheader[1],
1644                                       msize - sizeof (struct WlanHeader),
1645                                       GNUNET_YES,
1646                                       GNUNET_NO);
1647     break;
1648   default:
1649     if (NULL == mas->endpoint)
1650     {
1651       GNUNET_break (0);
1652       break;
1653     }
1654     if (NULL == mas->session)
1655     {
1656       GNUNET_break (0);
1657       break;
1658     }
1659     LOG (GNUNET_ERROR_TYPE_DEBUG,
1660          "Received packet with %u bytes of type %u from peer %s\n",
1661          (unsigned int) msize,
1662          (unsigned int) ntohs (hdr->type),
1663          GNUNET_i2s (&mas->session->target));
1664     plugin->env->receive (plugin->env->cls,
1665                           mas->session->address,
1666                           mas->session,
1667                           hdr);
1668     break;
1669   }
1670   return GNUNET_OK;
1671 }
1672
1673
1674 /**
1675  * Task to (periodically) send a HELLO beacon
1676  *
1677  * @param cls pointer to the plugin struct
1678  */
1679 static void
1680 send_hello_beacon (void *cls)
1681 {
1682   struct Plugin *plugin = cls;
1683   uint16_t size;
1684   uint16_t hello_size;
1685   struct GNUNET_TRANSPORT_WLAN_RadiotapSendMessage *radioHeader;
1686   const struct GNUNET_MessageHeader *hello;
1687
1688   hello = plugin->env->get_our_hello ();
1689   if (NULL != hello)
1690   {
1691     hello_size = GNUNET_HELLO_size ((struct GNUNET_HELLO_Message *) hello);
1692     GNUNET_assert (sizeof (struct WlanHeader) + hello_size <= WLAN_MTU);
1693     size = sizeof (struct GNUNET_TRANSPORT_WLAN_RadiotapSendMessage) + hello_size;
1694   {
1695     char buf[size] GNUNET_ALIGN;
1696
1697     LOG (GNUNET_ERROR_TYPE_DEBUG,
1698          "Sending %u byte HELLO beacon\n",
1699          (unsigned int) size);
1700     radioHeader = (struct GNUNET_TRANSPORT_WLAN_RadiotapSendMessage*) buf;
1701     get_radiotap_header (NULL, radioHeader, size);
1702     LOG (GNUNET_ERROR_TYPE_DEBUG,
1703          "Broadcasting %u bytes of data to MAC `%s'\n",
1704          (unsigned int) size,
1705          mac_to_string (&bc_all_mac));
1706     get_wlan_header (plugin, &radioHeader->frame, &bc_all_mac, size);
1707     memcpy (&radioHeader[1], hello, hello_size);
1708     if (NULL !=
1709         GNUNET_HELPER_send (plugin->suid_helper,
1710                             &radioHeader->header,
1711                             GNUNET_YES /* can drop */,
1712                             NULL, NULL))
1713       GNUNET_STATISTICS_update (plugin->env->stats,
1714                                 _("# HELLO beacons sent"),
1715                                 1, GNUNET_NO);
1716   } }
1717   plugin->beacon_task =
1718     GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply
1719                                   (HELLO_BEACON_SCALING_FACTOR,
1720                                    plugin->mac_count + 1),
1721                                   &send_hello_beacon,
1722                                   plugin);
1723
1724 }
1725
1726
1727 /**
1728  * Function used for to process the data from the suid process
1729  *
1730  * @param cls the plugin handle
1731  * @param client client that send the data (not used)
1732  * @param hdr header of the GNUNET_MessageHeader
1733  */
1734 static int
1735 handle_helper_message (void *cls, void *client,
1736                        const struct GNUNET_MessageHeader *hdr)
1737 {
1738   struct Plugin *plugin = cls;
1739   struct GNUNET_HELLO_Address *my_address;
1740   const struct GNUNET_TRANSPORT_WLAN_RadiotapReceiveMessage *rxinfo;
1741   const struct GNUNET_TRANSPORT_WLAN_HelperControlMessage *cm;
1742   struct WlanAddress wa;
1743   struct MacAndSession mas;
1744   uint16_t msize;
1745   struct FragmentMessage *fm;
1746   struct MacEndpoint *endpoint;
1747
1748   msize = ntohs (hdr->size);
1749   switch (ntohs (hdr->type))
1750   {
1751   case GNUNET_MESSAGE_TYPE_WLAN_HELPER_CONTROL:
1752     if (msize != sizeof (struct GNUNET_TRANSPORT_WLAN_HelperControlMessage))
1753     {
1754       GNUNET_break (0);
1755       break;
1756     }
1757     cm = (const struct GNUNET_TRANSPORT_WLAN_HelperControlMessage *) hdr;
1758     if (GNUNET_YES == plugin->have_mac)
1759     {
1760       if (0 == memcmp (&plugin->mac_address,
1761                        &cm->mac,
1762                        sizeof (struct GNUNET_TRANSPORT_WLAN_MacAddress)))
1763         break; /* no change */
1764       /* remove old address */
1765       memset (&wa, 0, sizeof (struct WlanAddress));
1766       wa.mac = plugin->mac_address;
1767       wa.options = htonl(plugin->options);
1768       my_address = GNUNET_HELLO_address_allocate (plugin->env->my_identity,
1769                                                   PLUGIN_NAME,
1770                                                   &wa, sizeof (wa),
1771                                                   GNUNET_HELLO_ADDRESS_INFO_NONE);
1772       plugin->env->notify_address (plugin->env->cls,
1773                                    GNUNET_NO,
1774                                    my_address);
1775       GNUNET_HELLO_address_free (my_address);
1776       plugin->mac_address = cm->mac;
1777     }
1778     else
1779     {
1780       plugin->mac_address = cm->mac;
1781       plugin->have_mac = GNUNET_YES;
1782       for (endpoint = plugin->mac_head; NULL != endpoint; endpoint = endpoint->next)
1783       {
1784         for (fm = endpoint->sending_messages_head; NULL != fm; fm = fm->next)
1785         {
1786           if (NULL != fm->fragcontext)
1787           {
1788             GNUNET_break (0); /* should not happen */
1789             continue;
1790           }
1791           fm->fragcontext =
1792             GNUNET_FRAGMENT_context_create (plugin->env->stats,
1793                                             WLAN_MTU,
1794                                             &plugin->tracker,
1795                                             fm->macendpoint->msg_delay,
1796                                             fm->macendpoint->ack_delay,
1797                                             fm->msg,
1798                                             &transmit_fragment, fm);
1799           GNUNET_free (fm->msg);
1800           fm->msg = NULL;
1801         }
1802       }
1803       GNUNET_break (NULL == plugin->beacon_task);
1804       plugin->beacon_task = GNUNET_SCHEDULER_add_now (&send_hello_beacon,
1805                                                       plugin);
1806
1807     }
1808
1809     memset (&wa, 0, sizeof (struct WlanAddress));
1810     wa.mac = plugin->mac_address;
1811     wa.options = htonl(plugin->options);
1812     my_address = GNUNET_HELLO_address_allocate (plugin->env->my_identity,
1813                                                 PLUGIN_NAME,
1814                                                 &wa, sizeof (wa),
1815                                                 GNUNET_HELLO_ADDRESS_INFO_NONE);
1816
1817     LOG (GNUNET_ERROR_TYPE_DEBUG,
1818          "Received WLAN_HELPER_CONTROL message with MAC address `%s' for peer `%s'\n",
1819          mac_to_string (&cm->mac),
1820          GNUNET_i2s (plugin->env->my_identity));
1821     plugin->env->notify_address (plugin->env->cls,
1822                                  GNUNET_YES,
1823                                  my_address);
1824     GNUNET_HELLO_address_free (my_address);
1825     break;
1826   case GNUNET_MESSAGE_TYPE_WLAN_DATA_FROM_HELPER:
1827     LOG (GNUNET_ERROR_TYPE_DEBUG,
1828          "Got data message from helper with %u bytes\n",
1829          msize);
1830     GNUNET_STATISTICS_update (plugin->env->stats,
1831                               _("# DATA messages received"), 1,
1832                               GNUNET_NO);
1833     if (msize < sizeof (struct GNUNET_TRANSPORT_WLAN_RadiotapReceiveMessage))
1834     {
1835       LOG (GNUNET_ERROR_TYPE_DEBUG,
1836            "Size of packet is too small (%u bytes < %u)\n",
1837            msize,  sizeof (struct GNUNET_TRANSPORT_WLAN_RadiotapReceiveMessage));
1838       break;
1839     }
1840     rxinfo = (const struct GNUNET_TRANSPORT_WLAN_RadiotapReceiveMessage *) hdr;
1841
1842     /* check if message is actually for us */
1843     if (0 != memcmp (&rxinfo->frame.addr3, &mac_bssid_gnunet,
1844                      sizeof (struct GNUNET_TRANSPORT_WLAN_MacAddress)))
1845     {
1846       /* Not the GNUnet BSSID */
1847       break;
1848     }
1849     if ( (0 != memcmp (&rxinfo->frame.addr1, &bc_all_mac,
1850                        sizeof (struct GNUNET_TRANSPORT_WLAN_MacAddress))) &&
1851          (0 != memcmp (&rxinfo->frame.addr1, &plugin->mac_address,
1852                        sizeof (struct GNUNET_TRANSPORT_WLAN_MacAddress))) )
1853     {
1854       /* Neither broadcast nor specifically for us */
1855       break;
1856     }
1857     if (0 == memcmp (&rxinfo->frame.addr2, &plugin->mac_address,
1858                      sizeof (struct GNUNET_TRANSPORT_WLAN_MacAddress)))
1859     {
1860       /* packet is FROM us, thus not FOR us */
1861       break;
1862     }
1863
1864     GNUNET_STATISTICS_update (plugin->env->stats,
1865                               _("# DATA messages processed"),
1866                               1, GNUNET_NO);
1867     LOG (GNUNET_ERROR_TYPE_DEBUG,
1868          "Receiving %u bytes of data from MAC `%s'\n",
1869          (unsigned int) (msize - sizeof (struct GNUNET_TRANSPORT_WLAN_RadiotapReceiveMessage)),
1870          mac_to_string (&rxinfo->frame.addr2));
1871     LOG (GNUNET_ERROR_TYPE_DEBUG,
1872          "Receiving %u bytes of data to MAC `%s'\n",
1873          (unsigned int) (msize - sizeof (struct GNUNET_TRANSPORT_WLAN_RadiotapReceiveMessage)),
1874          mac_to_string (&rxinfo->frame.addr1));
1875     LOG (GNUNET_ERROR_TYPE_DEBUG,
1876          "Receiving %u bytes of data with BSSID MAC `%s'\n",
1877          (unsigned int) (msize - sizeof (struct GNUNET_TRANSPORT_WLAN_RadiotapReceiveMessage)),
1878          mac_to_string (&rxinfo->frame.addr3));
1879     wa.mac = rxinfo->frame.addr2;
1880     wa.options = htonl (0);
1881     mas.endpoint = create_macendpoint (plugin, &wa);
1882     mas.session = NULL;
1883     (void) GNUNET_SERVER_mst_receive (plugin->helper_payload_tokenizer,
1884                                       &mas,
1885                                       (const char*) &rxinfo[1],
1886                                       msize - sizeof (struct GNUNET_TRANSPORT_WLAN_RadiotapReceiveMessage),
1887                                       GNUNET_YES, GNUNET_NO);
1888     break;
1889   default:
1890     GNUNET_break (0);
1891     LOG (GNUNET_ERROR_TYPE_DEBUG,
1892          "Unexpected message of type %u (%u bytes)",
1893          ntohs (hdr->type), ntohs (hdr->size));
1894     break;
1895   }
1896   return GNUNET_OK;
1897 }
1898
1899
1900 /**
1901  * Another peer has suggested an address for this
1902  * peer and transport plugin.  Check that this could be a valid
1903  * address.  If so, consider adding it to the list
1904  * of addresses.
1905  *
1906  * @param cls closure
1907  * @param addr pointer to the address
1908  * @param addrlen length of @a addr
1909  * @return #GNUNET_OK if this is a plausible address for this peer
1910  *         and transport
1911  */
1912 static int
1913 wlan_plugin_address_suggested (void *cls,
1914                                const void *addr,
1915                                size_t addrlen)
1916 {
1917   struct Plugin *plugin = cls;
1918   struct WlanAddress *wa = (struct WlanAddress *) addr;
1919
1920   if (addrlen != sizeof (struct WlanAddress))
1921   {
1922     GNUNET_break_op (0);
1923     return GNUNET_SYSERR;
1924   }
1925   if (GNUNET_YES != plugin->have_mac)
1926   {
1927     LOG (GNUNET_ERROR_TYPE_DEBUG,
1928          "Rejecting MAC `%s': I don't know my MAC!\n",
1929          mac_to_string (addr));
1930     return GNUNET_NO; /* don't know my MAC */
1931   }
1932   if (0 != memcmp (&wa->mac,
1933                    &plugin->mac_address,
1934                    sizeof (wa->mac)))
1935   {
1936     LOG (GNUNET_ERROR_TYPE_DEBUG,
1937          "Rejecting MAC `%s': not my MAC!\n",
1938          mac_to_string (addr));
1939     return GNUNET_NO; /* not my MAC */
1940   }
1941   return GNUNET_OK;
1942 }
1943
1944
1945 /**
1946  * Convert the transports address to a nice, human-readable format.
1947  *
1948  * @param cls closure
1949  * @param type name of the transport that generated the address
1950  * @param addr one of the addresses of the host, NULL for the last address
1951  *        the specific address format depends on the transport
1952  * @param addrlen length of the address
1953  * @param numeric should (IP) addresses be displayed in numeric form?
1954  * @param timeout after how long should we give up?
1955  * @param asc function to call on each string
1956  * @param asc_cls closure for @a asc
1957  */
1958 static void
1959 wlan_plugin_address_pretty_printer (void *cls,
1960                                     const char *type,
1961                                     const void *addr,
1962                                     size_t addrlen,
1963                                     int numeric,
1964                                     struct GNUNET_TIME_Relative timeout,
1965                                     GNUNET_TRANSPORT_AddressStringCallback asc,
1966                                     void *asc_cls)
1967 {
1968   const char *ret;
1969
1970   if (sizeof (struct WlanAddress) == addrlen)
1971     ret = wlan_plugin_address_to_string (NULL,
1972                                          addr,
1973                                          addrlen);
1974   else
1975     ret = NULL;
1976   asc (asc_cls,
1977        ret,
1978        (NULL == ret) ? GNUNET_SYSERR : GNUNET_OK);
1979   asc (asc_cls, NULL, GNUNET_OK);
1980 }
1981
1982
1983 /**
1984  * Exit point from the plugin.
1985  *
1986  * @param cls pointer to the api struct
1987  */
1988 void *
1989 LIBGNUNET_PLUGIN_TRANSPORT_DONE (void *cls)
1990 {
1991   struct WlanAddress wa;
1992   struct GNUNET_HELLO_Address *address;
1993   struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
1994   struct Plugin *plugin = api->cls;
1995   struct MacEndpoint *endpoint;
1996   struct MacEndpoint *endpoint_next;
1997
1998   if (NULL == plugin)
1999   {
2000     GNUNET_free (api);
2001     return NULL;
2002   }
2003   if (GNUNET_YES == plugin->have_mac)
2004   {
2005     memset (&wa, 0, sizeof(wa));
2006     wa.options = htonl (plugin->options);
2007     wa.mac = plugin->mac_address;
2008     address = GNUNET_HELLO_address_allocate (plugin->env->my_identity,
2009                                              PLUGIN_NAME,
2010                                              &wa, sizeof (struct WlanAddress),
2011                                              GNUNET_HELLO_ADDRESS_INFO_NONE);
2012
2013     plugin->env->notify_address (plugin->env->cls,
2014                                  GNUNET_NO,
2015                                  address);
2016     plugin->have_mac = GNUNET_NO;
2017     GNUNET_HELLO_address_free (address);
2018   }
2019
2020   if (NULL != plugin->beacon_task)
2021   {
2022     GNUNET_SCHEDULER_cancel (plugin->beacon_task);
2023     plugin->beacon_task = NULL;
2024   }
2025   if (NULL != plugin->suid_helper)
2026   {
2027     GNUNET_HELPER_stop (plugin->suid_helper,
2028                         GNUNET_NO);
2029     plugin->suid_helper = NULL;
2030   }
2031   endpoint_next = plugin->mac_head;
2032   while (NULL != (endpoint = endpoint_next))
2033   {
2034     endpoint_next = endpoint->next;
2035     free_macendpoint (endpoint);
2036   }
2037   if (NULL != plugin->fragment_data_tokenizer)
2038   {
2039     GNUNET_SERVER_mst_destroy (plugin->fragment_data_tokenizer);
2040     plugin->fragment_data_tokenizer = NULL;
2041   }
2042   if (NULL != plugin->wlan_header_payload_tokenizer)
2043   {
2044     GNUNET_SERVER_mst_destroy (plugin->wlan_header_payload_tokenizer);
2045     plugin->wlan_header_payload_tokenizer = NULL;
2046   }
2047   if (NULL != plugin->helper_payload_tokenizer)
2048   {
2049     GNUNET_SERVER_mst_destroy (plugin->helper_payload_tokenizer);
2050     plugin->helper_payload_tokenizer = NULL;
2051   }
2052   GNUNET_free_non_null (plugin->wlan_interface);
2053   GNUNET_free (plugin);
2054   GNUNET_free (api);
2055   return NULL;
2056 }
2057
2058
2059 /**
2060  * Function called to convert a string address to
2061  * a binary address.
2062  *
2063  * @param cls closure (`struct Plugin *`)
2064  * @param addr string address
2065  * @param addrlen length of the address
2066  * @param buf location to store the buffer
2067  * @param added location to store the number of bytes in the buffer.
2068  *        If the function returns #GNUNET_SYSERR, its contents are undefined.
2069  * @return #GNUNET_OK on success, #GNUNET_SYSERR on failure
2070  */
2071 static int
2072 wlan_plugin_string_to_address (void *cls,
2073                                const char *addr,
2074                                uint16_t addrlen,
2075                                void **buf,
2076                                size_t *added)
2077 {
2078   struct WlanAddress *wa;
2079   unsigned int a[6];
2080   unsigned int i;
2081   char plugin[5];
2082   uint32_t options;
2083
2084   if ((NULL == addr) || (0 == addrlen))
2085   {
2086     GNUNET_break (0);
2087     return GNUNET_SYSERR;
2088   }
2089   if ('\0' != addr[addrlen - 1])
2090   {
2091     GNUNET_break (0);
2092     return GNUNET_SYSERR;
2093   }
2094   if (strlen (addr) != addrlen - 1)
2095   {
2096     GNUNET_break (0);
2097     return GNUNET_SYSERR;
2098   }
2099
2100   if (8 != SSCANF (addr,
2101                    "%4s.%u.%X:%X:%X:%X:%X:%X",
2102                    plugin, &options,
2103                    &a[0], &a[1], &a[2],
2104                    &a[3], &a[4], &a[5]))
2105   {
2106     GNUNET_break (0);
2107     return GNUNET_SYSERR;
2108   }
2109   wa = GNUNET_new (struct WlanAddress);
2110   for (i=0;i<6;i++)
2111     wa->mac.mac[i] = a[i];
2112   wa->options = htonl (0);
2113   *buf = wa;
2114   *added = sizeof (struct WlanAddress);
2115   return GNUNET_OK;
2116 }
2117
2118
2119 /**
2120  * Begin monitoring sessions of a plugin.  There can only
2121  * be one active monitor per plugin (i.e. if there are
2122  * multiple monitors, the transport service needs to
2123  * multiplex the generated events over all of them).
2124  *
2125  * @param cls closure of the plugin
2126  * @param sic callback to invoke, NULL to disable monitor;
2127  *            plugin will being by iterating over all active
2128  *            sessions immediately and then enter monitor mode
2129  * @param sic_cls closure for @a sic
2130  */
2131 static void
2132 wlan_plugin_setup_monitor (void *cls,
2133                            GNUNET_TRANSPORT_SessionInfoCallback sic,
2134                            void *sic_cls)
2135 {
2136   struct Plugin *plugin = cls;
2137   struct MacEndpoint *mac;
2138   struct GNUNET_ATS_Session *session;
2139
2140   plugin->sic = sic;
2141   plugin->sic_cls = sic_cls;
2142   if (NULL != sic)
2143   {
2144     for (mac = plugin->mac_head; NULL != mac; mac = mac->next)
2145       for (session = mac->sessions_head; NULL != session; session = session->next)
2146       {
2147         notify_session_monitor (plugin,
2148                                 session,
2149                                 GNUNET_TRANSPORT_SS_INIT);
2150         notify_session_monitor (plugin,
2151                                 session,
2152                                 GNUNET_TRANSPORT_SS_UP);
2153       }
2154     sic (sic_cls, NULL, NULL);
2155   }
2156 }
2157
2158
2159
2160 /**
2161  * Function that will be called whenever the transport service wants to
2162  * notify the plugin that a session is still active and in use and
2163  * therefore the session timeout for this session has to be updated
2164  *
2165  * @param cls closure
2166  * @param peer which peer was the session for
2167  * @param session which session is being updated
2168  */
2169 static void
2170 wlan_plugin_update_session_timeout (void *cls,
2171                                     const struct GNUNET_PeerIdentity *peer,
2172                                     struct GNUNET_ATS_Session *session)
2173 {
2174   GNUNET_assert (NULL != session->timeout_task);
2175   session->timeout = GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
2176 }
2177
2178
2179 /**
2180  * Function that will be called whenever the transport service wants to
2181  * notify the plugin that the inbound quota changed and that the plugin
2182  * should update it's delay for the next receive value
2183  *
2184  * @param cls closure
2185  * @param peer which peer was the session for
2186  * @param session which session is being updated
2187  * @param delay new delay to use for receiving
2188  */
2189 static void
2190 wlan_plugin_update_inbound_delay (void *cls,
2191                                   const struct GNUNET_PeerIdentity *peer,
2192                                   struct GNUNET_ATS_Session *session,
2193                                   struct GNUNET_TIME_Relative delay)
2194 {
2195   /* does nothing, as inbound delay is not supported by WLAN */
2196 }
2197
2198
2199 /**
2200  * Entry point for the plugin.
2201  *
2202  * @param cls closure, the `struct GNUNET_TRANSPORT_PluginEnvironment *`
2203  * @return the `struct GNUNET_TRANSPORT_PluginFunctions *` or NULL on error
2204  */
2205 void *
2206 LIBGNUNET_PLUGIN_TRANSPORT_INIT (void *cls)
2207 {
2208   struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
2209   struct GNUNET_TRANSPORT_PluginFunctions *api;
2210   struct Plugin *plugin;
2211   char *wlan_interface;
2212   unsigned long long testmode;
2213   char *binary;
2214
2215   /* check for 'special' mode */
2216   if (NULL == env->receive)
2217   {
2218     /* run in 'stub' mode (i.e. as part of gnunet-peerinfo), don't fully
2219        initialze the plugin or the API */
2220     api = GNUNET_new (struct GNUNET_TRANSPORT_PluginFunctions);
2221     api->cls = NULL;
2222     api->address_pretty_printer = &wlan_plugin_address_pretty_printer;
2223     api->address_to_string = &wlan_plugin_address_to_string;
2224     api->string_to_address = &wlan_plugin_string_to_address;
2225     return api;
2226   }
2227
2228   testmode = 0;
2229   /* check configuration */
2230   if ( (GNUNET_YES ==
2231         GNUNET_CONFIGURATION_have_value (env->cfg,
2232                                          CONFIG_NAME,
2233                                          "TESTMODE")) &&
2234        ( (GNUNET_SYSERR ==
2235           GNUNET_CONFIGURATION_get_value_number (env->cfg,
2236                                                  CONFIG_NAME,
2237                                                  "TESTMODE",
2238                                                  &testmode)) ||
2239          (testmode > 2) ) )
2240   {
2241     GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
2242                                CONFIG_NAME,
2243                                "TESTMODE");
2244     return NULL;
2245   }
2246   binary = GNUNET_OS_get_libexec_binary_path (HELPER_NAME);
2247   if ( (0 == testmode) &&
2248        (GNUNET_YES !=
2249         GNUNET_OS_check_helper_binary (binary,
2250                                        GNUNET_YES,
2251                                        NULL)) )
2252   {
2253     LOG (GNUNET_ERROR_TYPE_ERROR,
2254          _("Helper binary `%s' not SUID, cannot run WLAN transport\n"),
2255          HELPER_NAME);
2256     GNUNET_free (binary);
2257     return NULL;
2258   }
2259     GNUNET_free (binary);
2260   if (GNUNET_YES !=
2261       GNUNET_CONFIGURATION_get_value_string (env->cfg,
2262                                              CONFIG_NAME,
2263                                              "INTERFACE",
2264                                              &wlan_interface))
2265   {
2266     GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
2267                                CONFIG_NAME,
2268                                "INTERFACE");
2269     return NULL;
2270   }
2271
2272   plugin = GNUNET_new (struct Plugin);
2273   plugin->wlan_interface = wlan_interface;
2274   plugin->env = env;
2275   GNUNET_STATISTICS_set (plugin->env->stats,
2276                          _("# sessions allocated"),
2277                          0, GNUNET_NO);
2278   GNUNET_STATISTICS_set (plugin->env->stats,
2279                          _("# MAC endpoints allocated"),
2280                          0, 0);
2281   GNUNET_BANDWIDTH_tracker_init (&plugin->tracker, NULL, NULL,
2282                                  GNUNET_BANDWIDTH_value_init (100 * 1024 *
2283                                                               1024 / 8),
2284                                  100);
2285   plugin->fragment_data_tokenizer = GNUNET_SERVER_mst_create (&process_data,
2286                                                               plugin);
2287   plugin->wlan_header_payload_tokenizer = GNUNET_SERVER_mst_create (&process_data,
2288                                                                     plugin);
2289   plugin->helper_payload_tokenizer = GNUNET_SERVER_mst_create (&process_data,
2290                                                                plugin);
2291
2292   plugin->options = 0;
2293
2294   /* some compilers do not like switch on 'long long'... */
2295   switch ((unsigned int) testmode)
2296   {
2297   case 0: /* normal */
2298     plugin->helper_argv[0] = (char *) HELPER_NAME;
2299     plugin->helper_argv[1] = wlan_interface;
2300     plugin->helper_argv[2] = NULL;
2301     plugin->suid_helper = GNUNET_HELPER_start (GNUNET_NO,
2302                                                HELPER_NAME,
2303                                                plugin->helper_argv,
2304                                                &handle_helper_message,
2305                                                NULL,
2306                                                plugin);
2307     break;
2308   case 1: /* testmode, peer 1 */
2309     plugin->helper_argv[0] = (char *) DUMMY_HELPER_NAME;
2310     plugin->helper_argv[1] = (char *) "1";
2311     plugin->helper_argv[2] = NULL;
2312     plugin->suid_helper = GNUNET_HELPER_start (GNUNET_NO,
2313                                                DUMMY_HELPER_NAME,
2314                                                plugin->helper_argv,
2315                                                &handle_helper_message,
2316                                                NULL,
2317                                                plugin);
2318     break;
2319   case 2: /* testmode, peer 2 */
2320     plugin->helper_argv[0] = (char *) DUMMY_HELPER_NAME;
2321     plugin->helper_argv[1] = (char *) "2";
2322     plugin->helper_argv[2] = NULL;
2323     plugin->suid_helper = GNUNET_HELPER_start (GNUNET_NO,
2324                                                DUMMY_HELPER_NAME,
2325                                                plugin->helper_argv,
2326                                                &handle_helper_message,
2327                                                NULL,
2328                                                plugin);
2329     break;
2330   default:
2331     GNUNET_assert (0);
2332   }
2333
2334   api = GNUNET_new (struct GNUNET_TRANSPORT_PluginFunctions);
2335   api->cls = plugin;
2336   api->send = &wlan_plugin_send;
2337   api->get_session = &wlan_plugin_get_session;
2338   api->disconnect_peer = &wlan_plugin_disconnect_peer;
2339   api->disconnect_session = &wlan_plugin_disconnect_session;
2340   api->query_keepalive_factor = &wlan_plugin_query_keepalive_factor;
2341   api->address_pretty_printer = &wlan_plugin_address_pretty_printer;
2342   api->check_address = &wlan_plugin_address_suggested;
2343   api->address_to_string = &wlan_plugin_address_to_string;
2344   api->string_to_address = &wlan_plugin_string_to_address;
2345   api->get_network = &wlan_plugin_get_network;
2346   api->get_network_for_address = &wlan_plugin_get_network_for_address;
2347   api->update_session_timeout = &wlan_plugin_update_session_timeout;
2348   api->update_inbound_delay = &wlan_plugin_update_inbound_delay;
2349   api->setup_monitor = &wlan_plugin_setup_monitor;
2350   return api;
2351 }
2352
2353
2354 /* end of plugin_transport_wlan.c */