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