plugin returns inbound session if outbound session is requiered
[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 session the session free
658  */
659 static void
660 free_session (struct Session *session)
661 {
662   struct MacEndpoint *endpoint = session->mac;
663   struct PendingMessage *pm;
664   
665   endpoint->plugin->env->session_end (endpoint->plugin->env->cls,
666                                       &session->target,
667                                       session);
668   while (NULL != (pm = session->pending_message_head))
669   {
670     GNUNET_CONTAINER_DLL_remove (session->pending_message_head,
671                                  session->pending_message_tail, pm);
672     if (GNUNET_SCHEDULER_NO_TASK != pm->timeout_task)
673     {
674       GNUNET_SCHEDULER_cancel (pm->timeout_task);
675       pm->timeout_task = GNUNET_SCHEDULER_NO_TASK;
676     }
677     GNUNET_free (pm->msg);
678     GNUNET_free (pm);
679   }
680   GNUNET_CONTAINER_DLL_remove (endpoint->sessions_head, 
681                                endpoint->sessions_tail,
682                                session);
683   if (session->timeout_task != GNUNET_SCHEDULER_NO_TASK)
684   {
685     GNUNET_SCHEDULER_cancel (session->timeout_task);
686     session->timeout_task = GNUNET_SCHEDULER_NO_TASK;
687   }
688   GNUNET_STATISTICS_update (endpoint->plugin->env->stats, _("# WLAN sessions allocated"), -1,
689                             GNUNET_NO);
690   GNUNET_free (session);
691 }
692
693
694 /**
695  * A session is timing out.  Clean up.
696  *
697  * @param cls pointer to the Session
698  * @param tc pointer to the GNUNET_SCHEDULER_TaskContext
699  */
700 static void
701 session_timeout (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
702 {
703   struct Session * session = cls;
704   struct GNUNET_TIME_Relative timeout;
705
706   session->timeout_task = GNUNET_SCHEDULER_NO_TASK;
707   timeout = GNUNET_TIME_absolute_get_remaining (session->timeout);
708   if (0 == timeout.rel_value_us) 
709   {
710     free_session (session);
711     return;
712   }
713   session->timeout_task =
714     GNUNET_SCHEDULER_add_delayed (timeout, &session_timeout, session);
715 }
716
717
718
719 /**
720  * Lookup a new session
721  *
722  * @param endpoint pointer to the mac endpoint of the peer
723  * @param peer peer identity to use for this session
724  * @return returns the session or NULL
725  */
726 static struct Session *
727 lookup_session (struct MacEndpoint *endpoint,
728                 const struct GNUNET_PeerIdentity *peer,
729                 int inbound)
730 {
731   struct Session *session;
732
733   for (session = endpoint->sessions_head; NULL != session; session = session->next)
734     if (0 == memcmp (peer, &session->target, sizeof (struct GNUNET_PeerIdentity)) &&
735                 (session->inbound == inbound))
736     {
737       session->timeout = GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
738       return session;
739     }
740   return NULL;
741 }
742
743 /**
744  * Create a new session
745  *
746  * @param endpoint pointer to the mac endpoint of the peer
747  * @param peer peer identity to use for this session
748  * @return returns the session or NULL
749  */
750 static struct Session *
751 create_session (struct MacEndpoint *endpoint,
752                 const struct GNUNET_PeerIdentity *peer, int inbound)
753 {
754   struct Session *session;
755
756   GNUNET_STATISTICS_update (endpoint->plugin->env->stats, _("# WLAN sessions allocated"), 1,
757                             GNUNET_NO);
758   session = GNUNET_malloc (sizeof (struct Session));
759   GNUNET_CONTAINER_DLL_insert_tail (endpoint->sessions_head,
760                                     endpoint->sessions_tail,
761                                     session);
762   session->inbound = inbound;
763   session->mac = endpoint;
764   session->target = *peer;
765   session->timeout = GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
766   session->timeout_task =
767       GNUNET_SCHEDULER_add_delayed (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, &session_timeout, session);
768   LOG (GNUNET_ERROR_TYPE_DEBUG,
769        "Created new %s session %p for peer `%s' with endpoint %s\n",
770        (GNUNET_YES == inbound) ? "inbound" : "outbound",
771        session,
772        GNUNET_i2s (peer),
773        mac_to_string (&endpoint->addr.mac));
774
775   return session;
776 }
777
778
779 /**
780  * Look up a session for a peer and create a new session if none is found
781  *
782  * @param endpoint pointer to the mac endpoint of the peer
783  * @param peer peer identity to use for this session
784  * @return returns the session
785  */
786 static struct Session *
787 get_session (struct MacEndpoint *endpoint,
788                 const struct GNUNET_PeerIdentity *peer,
789                 int inbound)
790 {
791   struct Session *session;
792   if (NULL != (session = lookup_session (endpoint, peer, inbound)))
793         return session;
794   return create_session (endpoint, peer, inbound);
795 }
796
797
798 /**
799  * Function called once we have successfully given the fragment
800  * message to the SUID helper process and we are thus ready for
801  * the next fragment.
802  *
803  * @param cls the 'struct FragmentMessage' 
804  * @param result result of the operation (GNUNET_OK on success, GNUNET_NO if the helper died, GNUNET_SYSERR
805  *        if the helper was stopped)
806  */
807 static void
808 fragment_transmission_done (void *cls,
809                             int result)
810 {
811   struct FragmentMessage *fm = cls;
812
813
814   fm->sh = NULL;
815   GNUNET_FRAGMENT_context_transmission_done (fm->fragcontext);
816 }
817
818
819 /**
820  * Transmit a fragment of a message.
821  *
822  * @param cls 'struct FragmentMessage' this fragment message belongs to
823  * @param hdr pointer to the start of the fragment message 
824  */
825 static void
826 transmit_fragment (void *cls,
827                    const struct GNUNET_MessageHeader *hdr)
828 {
829   struct FragmentMessage *fm = cls;
830   struct MacEndpoint *endpoint = fm->macendpoint;
831   size_t size;
832   uint16_t msize;
833
834   if (NULL == endpoint)
835   {
836         GNUNET_break (0);
837         return;
838   }
839
840   msize = ntohs (hdr->size);
841   size = sizeof (struct GNUNET_TRANSPORT_WLAN_RadiotapSendMessage) + msize;
842   {
843     char buf[size];
844     struct GNUNET_TRANSPORT_WLAN_RadiotapSendMessage *radio_header;
845
846     radio_header = (struct GNUNET_TRANSPORT_WLAN_RadiotapSendMessage *) buf;
847     get_radiotap_header (endpoint, radio_header, size);
848     get_wlan_header (endpoint->plugin,
849                      &radio_header->frame, 
850                      &endpoint->addr.mac,
851                      size);
852     memcpy (&radio_header[1], hdr, msize);
853     GNUNET_assert (NULL == fm->sh);
854     fm->sh = GNUNET_HELPER_send (endpoint->plugin->suid_helper,
855                                  &radio_header->header,
856                                  GNUNET_NO,
857                                  &fragment_transmission_done, fm);
858     fm->size_on_wire += size;
859     if (NULL != fm->sh)
860       GNUNET_STATISTICS_update (endpoint->plugin->env->stats, _("# WLAN message fragments sent"),
861                                 1, GNUNET_NO);
862     else
863       GNUNET_FRAGMENT_context_transmission_done (fm->fragcontext);
864     GNUNET_STATISTICS_update (endpoint->plugin->env->stats,
865                               "# bytes currently in WLAN buffers",
866                               -msize, GNUNET_NO);
867     GNUNET_STATISTICS_update (endpoint->plugin->env->stats,
868                               "# bytes transmitted via WLAN",
869                               msize, GNUNET_NO);
870   }
871 }
872
873
874 /**
875  * Frees the space of a message in the fragment queue (send queue)
876  *
877  * @param fm message to free
878  */
879 static void
880 free_fragment_message (struct FragmentMessage *fm)
881 {
882   struct MacEndpoint *endpoint = fm->macendpoint;
883
884   GNUNET_STATISTICS_update (endpoint->plugin->env->stats, _("# WLAN messages pending (with fragmentation)"), 
885                             -1, GNUNET_NO);
886   GNUNET_CONTAINER_DLL_remove (endpoint->sending_messages_head,
887                                endpoint->sending_messages_tail, fm);
888   if (NULL != fm->sh)
889   {
890     GNUNET_HELPER_send_cancel (fm->sh);
891     fm->sh = NULL;
892   }
893   GNUNET_FRAGMENT_context_destroy (fm->fragcontext,
894                                                                    &endpoint->msg_delay,
895                                                                    &endpoint->ack_delay);
896   if (fm->timeout_task != GNUNET_SCHEDULER_NO_TASK)
897   {
898     GNUNET_SCHEDULER_cancel (fm->timeout_task);
899     fm->timeout_task = GNUNET_SCHEDULER_NO_TASK;
900   }
901   GNUNET_free (fm);
902 }
903
904
905 /**
906  * A FragmentMessage has timed out.  Remove it.
907  *
908  * @param cls pointer to the 'struct FragmentMessage'
909  * @param tc pointer to the GNUNET_SCHEDULER_TaskContext
910  */
911 static void
912 fragmentmessage_timeout (void *cls,
913                          const struct GNUNET_SCHEDULER_TaskContext *tc)
914 {
915   struct FragmentMessage *fm = cls;
916
917   fm->timeout_task = GNUNET_SCHEDULER_NO_TASK;
918   if (NULL != fm->cont)
919   {
920     fm->cont (fm->cont_cls, &fm->target, GNUNET_SYSERR, fm->size_payload, fm->size_on_wire);
921     fm->cont = NULL;
922   }
923   free_fragment_message (fm);
924 }
925
926
927 /**
928  * Transmit a message to the given destination with fragmentation.
929  *
930  * @param endpoint desired destination
931  * @param timeout how long can the message wait?
932  * @param target peer that should receive the message
933  * @param msg message to transmit
934  * @param payload_size bytes of payload
935  * @param cont continuation to call once the message has
936  *        been transmitted (or if the transport is ready
937  *        for the next transmission call; or if the
938  *        peer disconnected...); can be NULL
939  * @param cont_cls closure for cont
940  */
941 static void
942 send_with_fragmentation (struct MacEndpoint *endpoint,
943                          struct GNUNET_TIME_Relative timeout,
944                          const struct GNUNET_PeerIdentity *target,                       
945                          const struct GNUNET_MessageHeader *msg,
946                          size_t payload_size,
947                          GNUNET_TRANSPORT_TransmitContinuation cont, void *cont_cls)
948
949 {
950   struct FragmentMessage *fm;
951   struct Plugin *plugin;
952
953   plugin = endpoint->plugin;
954   fm = GNUNET_malloc (sizeof (struct FragmentMessage));
955   fm->macendpoint = endpoint;
956   fm->target = *target;
957   fm->size_payload = payload_size;
958   fm->size_on_wire = 0;
959   fm->timeout = GNUNET_TIME_relative_to_absolute (timeout);
960   fm->cont = cont;
961   fm->cont_cls = cont_cls;
962   /* 1 MBit/s typical data rate, 1430 byte fragments => ~100 ms per message */
963   fm->fragcontext =
964     GNUNET_FRAGMENT_context_create (plugin->env->stats, WLAN_MTU,
965                                     &plugin->tracker,
966                                     endpoint->msg_delay,
967                                     endpoint->ack_delay,
968                                     msg,
969                                     &transmit_fragment, fm);
970   fm->timeout_task =
971     GNUNET_SCHEDULER_add_delayed (timeout, 
972                                   &fragmentmessage_timeout, fm);
973   GNUNET_CONTAINER_DLL_insert_tail (endpoint->sending_messages_head,
974                                     endpoint->sending_messages_tail,
975                                     fm);
976 }
977
978
979 /**
980  * Free a MAC endpoint.
981  * 
982  * @param endpoint pointer to the MacEndpoint to free
983  */
984 static void
985 free_macendpoint (struct MacEndpoint *endpoint)
986 {
987   struct Plugin *plugin = endpoint->plugin;
988   struct FragmentMessage *fm;
989   struct Session *session;
990
991   GNUNET_STATISTICS_update (plugin->env->stats,
992                             _("# WLAN MAC endpoints allocated"), -1, GNUNET_NO);
993   while (NULL != (session = endpoint->sessions_head))
994     free_session (session);
995   while (NULL != (fm = endpoint->sending_messages_head))
996     free_fragment_message (fm);
997   GNUNET_CONTAINER_DLL_remove (plugin->mac_head, 
998                                plugin->mac_tail, 
999                                endpoint);
1000
1001   if (NULL != endpoint->defrag)
1002   {
1003     GNUNET_DEFRAGMENT_context_destroy(endpoint->defrag);
1004     endpoint->defrag = NULL;
1005   }
1006
1007   plugin->mac_count--;
1008   if (GNUNET_SCHEDULER_NO_TASK != endpoint->timeout_task)
1009   {
1010     GNUNET_SCHEDULER_cancel (endpoint->timeout_task);
1011     endpoint->timeout_task = GNUNET_SCHEDULER_NO_TASK;
1012   }
1013   GNUNET_free (endpoint);
1014 }
1015
1016
1017 /**
1018  * A MAC endpoint is timing out.  Clean up.
1019  *
1020  * @param cls pointer to the MacEndpoint
1021  * @param tc pointer to the GNUNET_SCHEDULER_TaskContext
1022  */
1023 static void
1024 macendpoint_timeout (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1025 {
1026   struct MacEndpoint *endpoint = cls;
1027   struct GNUNET_TIME_Relative timeout;
1028
1029   endpoint->timeout_task = GNUNET_SCHEDULER_NO_TASK;
1030   timeout = GNUNET_TIME_absolute_get_remaining (endpoint->timeout);
1031   if (0 == timeout.rel_value_us) 
1032   {
1033     free_macendpoint (endpoint);
1034     return;
1035   }
1036   endpoint->timeout_task =
1037     GNUNET_SCHEDULER_add_delayed (timeout, &macendpoint_timeout,
1038                                   endpoint);
1039 }
1040
1041
1042 /**
1043  * Find (or create) a MacEndpoint with a specific MAC address
1044  *
1045  * @param plugin pointer to the plugin struct
1046  * @param addr the MAC address of the endpoint
1047  * @return handle to our data structure for this MAC
1048  */
1049 static struct MacEndpoint *
1050 create_macendpoint (struct Plugin *plugin,
1051                     const struct WlanAddress *addr)
1052 {
1053   struct MacEndpoint *pos;
1054
1055   for (pos = plugin->mac_head; NULL != pos; pos = pos->next)
1056     if (0 == memcmp (addr, &pos->addr, sizeof (struct WlanAddress)))
1057       return pos; 
1058   pos = GNUNET_malloc (sizeof (struct MacEndpoint));
1059   pos->addr = *addr;
1060   pos->plugin = plugin;
1061   pos->defrag =
1062     GNUNET_DEFRAGMENT_context_create (plugin->env->stats, WLAN_MTU,
1063                                       MESSAGES_IN_DEFRAG_QUEUE_PER_MAC,
1064                                       pos, 
1065                                       &wlan_data_message_handler,
1066                                       &send_ack);
1067
1068   pos->msg_delay = GNUNET_TIME_UNIT_MILLISECONDS;
1069   pos->ack_delay = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS,
1070                                                                                                   100);
1071   pos->timeout = GNUNET_TIME_relative_to_absolute (MACENDPOINT_TIMEOUT);
1072   pos->timeout_task =
1073       GNUNET_SCHEDULER_add_delayed (MACENDPOINT_TIMEOUT, &macendpoint_timeout,
1074                                     pos);
1075   GNUNET_CONTAINER_DLL_insert (plugin->mac_head, plugin->mac_tail, pos);
1076   plugin->mac_count++;
1077   GNUNET_STATISTICS_update (plugin->env->stats, _("# WLAN MAC endpoints allocated"),
1078                             1, GNUNET_NO);
1079   LOG (GNUNET_ERROR_TYPE_DEBUG, 
1080        "New MAC endpoint `%s'\n",
1081        wlan_plugin_address_to_string(NULL, addr, sizeof (struct WlanAddress)));
1082   return pos;
1083 }
1084
1085
1086 /**
1087  * Function obtain the network type for a session
1088  *
1089  * @param cls closure ('struct Plugin*')
1090  * @param session the session
1091  * @return the network type in HBO or GNUNET_SYSERR
1092  */
1093 static enum GNUNET_ATS_Network_Type
1094 wlan_get_network (void *cls, 
1095                   struct Session *session)
1096 {
1097   GNUNET_assert (NULL != session);
1098   return GNUNET_ATS_NET_WLAN;
1099 }
1100
1101
1102 /**
1103  * Creates a new outbound session the transport service will use to send data to the
1104  * peer
1105  *
1106  * @param cls the plugin
1107  * @param address the address
1108  * @return the session or NULL of max connections exceeded
1109  */
1110 static struct Session *
1111 wlan_plugin_get_session (void *cls,
1112                          const struct GNUNET_HELLO_Address *address)
1113 {
1114   struct Plugin *plugin = cls;
1115   struct MacEndpoint *endpoint;
1116
1117   if (NULL == address)
1118     return NULL;
1119   if (sizeof (struct WlanAddress) != address->address_length)
1120   {
1121     GNUNET_break (0);
1122     return NULL;
1123   }
1124   LOG (GNUNET_ERROR_TYPE_DEBUG,
1125        "Service asked to create session for peer `%s' with MAC `%s'\n",
1126        GNUNET_i2s (&address->peer),
1127        wlan_plugin_address_to_string(NULL, address->address, address->address_length));
1128   endpoint = create_macendpoint (plugin, address->address);
1129   return get_session (endpoint, &address->peer, GNUNET_NO);
1130 }
1131
1132
1133 /**
1134  * Function that can be used to force the plugin to disconnect
1135  * from the given peer and cancel all previous transmissions
1136  * (and their continuation).
1137  *
1138  * @param cls closure
1139  * @param target peer from which to disconnect
1140  */
1141 static void
1142 wlan_plugin_disconnect (void *cls, const struct GNUNET_PeerIdentity *target)
1143 {
1144   struct Plugin *plugin = cls;
1145   struct Session *session;
1146   struct MacEndpoint *endpoint;
1147
1148   for (endpoint = plugin->mac_head; NULL != endpoint; endpoint = endpoint->next)
1149     for (session = endpoint->sessions_head; NULL != session; session = session->next)
1150       if (0 == memcmp (target, &session->target,
1151                        sizeof (struct GNUNET_PeerIdentity)))
1152       {
1153         free_session (session);
1154         break; /* inner-loop only (in case peer has another MAC as well!) */
1155       }
1156 }
1157
1158
1159 /**
1160  * Function that can be used by the transport service to transmit
1161  * a message using the plugin.   Note that in the case of a
1162  * peer disconnecting, the continuation MUST be called
1163  * prior to the disconnect notification itself.  This function
1164  * will be called with this peer's HELLO message to initiate
1165  * a fresh connection to another peer.
1166  *
1167  * @param cls closure
1168  * @param session which session must be used
1169  * @param msgbuf the message to transmit
1170  * @param msgbuf_size number of bytes in 'msgbuf'
1171  * @param priority how important is the message (most plugins will
1172  *                 ignore message priority and just FIFO)
1173  * @param to how long to wait at most for the transmission (does not
1174  *                require plugins to discard the message after the timeout,
1175  *                just advisory for the desired delay; most plugins will ignore
1176  *                this as well)
1177  * @param cont continuation to call once the message has
1178  *        been transmitted (or if the transport is ready
1179  *        for the next transmission call; or if the
1180  *        peer disconnected...); can be NULL
1181  * @param cont_cls closure for cont
1182  * @return number of bytes used (on the physical network, with overheads);
1183  *         -1 on hard errors (i.e. address invalid); 0 is a legal value
1184  *         and does NOT mean that the message was not transmitted (DV)
1185  */
1186 static ssize_t
1187 wlan_plugin_send (void *cls,
1188                   struct Session *session,
1189                   const char *msgbuf, size_t msgbuf_size,
1190                   unsigned int priority,
1191                   struct GNUNET_TIME_Relative to,
1192                   GNUNET_TRANSPORT_TransmitContinuation cont, void *cont_cls)
1193 {
1194   struct Plugin *plugin = cls;
1195   struct WlanHeader *wlanheader;
1196   size_t size = msgbuf_size + sizeof (struct WlanHeader);
1197   char buf[size] GNUNET_ALIGN;
1198
1199   LOG (GNUNET_ERROR_TYPE_DEBUG, 
1200        "Transmitting %u bytes of payload to peer `%s' (starting with %u byte message of type %u)\n",
1201        msgbuf_size,
1202        GNUNET_i2s (&session->target),
1203        (unsigned int) ntohs (((struct GNUNET_MessageHeader*)msgbuf)->size),
1204        (unsigned int) ntohs (((struct GNUNET_MessageHeader*)msgbuf)->type));
1205   wlanheader = (struct WlanHeader *) buf;
1206   wlanheader->header.size = htons (msgbuf_size + sizeof (struct WlanHeader));
1207   wlanheader->header.type = htons (GNUNET_MESSAGE_TYPE_WLAN_DATA);
1208   wlanheader->sender = *plugin->env->my_identity;
1209   wlanheader->target = session->target;
1210   wlanheader->crc = htonl (GNUNET_CRYPTO_crc32_n (msgbuf, msgbuf_size));
1211   memcpy (&wlanheader[1], msgbuf, msgbuf_size);
1212
1213   GNUNET_STATISTICS_update (plugin->env->stats,
1214                             "# bytes currently in WLAN buffers",
1215                             msgbuf_size, GNUNET_NO);
1216
1217   send_with_fragmentation (session->mac,
1218                            to,
1219                            &session->target,
1220                            &wlanheader->header,
1221                            msgbuf_size,
1222                            cont, cont_cls);
1223   return size;
1224 }
1225
1226
1227 /**
1228  * We have received data from the WLAN via some session.  Process depending
1229  * on the message type (HELLO, DATA, FRAGMENTATION or FRAGMENTATION-ACK).
1230  *
1231  * @param cls pointer to the plugin
1232  * @param client pointer to the session this message belongs to
1233  * @param hdr start of the message
1234  */
1235 static int
1236 process_data (void *cls, void *client, const struct GNUNET_MessageHeader *hdr)
1237 {
1238   struct Plugin *plugin = cls;
1239   struct MacAndSession *mas = client;
1240   struct MacAndSession xmas;
1241   struct GNUNET_ATS_Information ats;
1242   struct FragmentMessage *fm;
1243   struct GNUNET_PeerIdentity tmpsource;
1244   const struct WlanHeader *wlanheader;
1245   int ret;
1246   uint16_t msize;
1247
1248   ats.type = htonl (GNUNET_ATS_NETWORK_TYPE);
1249   ats.value = htonl (GNUNET_ATS_NET_WLAN);
1250   msize = ntohs (hdr->size);
1251
1252   GNUNET_STATISTICS_update (plugin->env->stats,
1253                             "# bytes received via WLAN",
1254                             msize, GNUNET_NO);
1255
1256   switch (ntohs (hdr->type))
1257   {
1258   case GNUNET_MESSAGE_TYPE_HELLO:
1259     if (GNUNET_OK != 
1260         GNUNET_HELLO_get_id ((const struct GNUNET_HELLO_Message *) hdr, &tmpsource))
1261     {
1262       GNUNET_break_op (0);
1263       break;
1264     }
1265     LOG (GNUNET_ERROR_TYPE_DEBUG,
1266          "Processing %u bytes of HELLO from peer `%s' at MAC %s\n",
1267          (unsigned int) msize,
1268          GNUNET_i2s (&tmpsource),
1269          wlan_plugin_address_to_string (NULL, &mas->endpoint->addr, sizeof (struct WlanAddress)));
1270
1271     GNUNET_STATISTICS_update (plugin->env->stats,
1272                               _("# HELLO messages received via WLAN"), 1,
1273                               GNUNET_NO);
1274     plugin->env->receive (plugin->env->cls, 
1275                           &tmpsource,
1276                           hdr, 
1277                           mas->session,
1278                           (mas->endpoint == NULL) ? NULL : (const char *) &mas->endpoint->addr,
1279                           (mas->endpoint == NULL) ? 0 : sizeof (struct WlanAddress));
1280     plugin->env->update_address_metrics (plugin->env->cls,
1281                                          &tmpsource,
1282                                          (mas->endpoint == NULL) ? NULL : (const char *) &mas->endpoint->addr,
1283                                          (mas->endpoint == NULL) ? 0 : sizeof (struct WlanAddress),
1284                                          mas->session,
1285                                          &ats, 1);
1286     break;
1287   case GNUNET_MESSAGE_TYPE_FRAGMENT:
1288     if (NULL == mas->endpoint)
1289     {
1290       GNUNET_break (0);
1291       break;
1292     }
1293     LOG (GNUNET_ERROR_TYPE_DEBUG, 
1294          "Processing %u bytes of FRAGMENT from MAC %s\n",
1295          (unsigned int) msize,
1296          wlan_plugin_address_to_string (NULL, &mas->endpoint->addr, sizeof (struct WlanAddress)));
1297     GNUNET_STATISTICS_update (plugin->env->stats,
1298                               _("# fragments received via WLAN"), 1, GNUNET_NO);
1299     (void) GNUNET_DEFRAGMENT_process_fragment (mas->endpoint->defrag,
1300                                               hdr);
1301     break;
1302   case GNUNET_MESSAGE_TYPE_FRAGMENT_ACK:
1303     if (NULL == mas->endpoint)
1304     {
1305       GNUNET_break (0);
1306       break;
1307     }
1308     GNUNET_STATISTICS_update (plugin->env->stats, _("# ACKs received via WLAN"),
1309                               1, GNUNET_NO);
1310     for (fm = mas->endpoint->sending_messages_head; NULL != fm; fm = fm->next)
1311     {
1312       ret = GNUNET_FRAGMENT_process_ack (fm->fragcontext, hdr);
1313       if (GNUNET_OK == ret)
1314       {
1315         LOG (GNUNET_ERROR_TYPE_DEBUG, 
1316              "Got last ACK, finished message transmission to `%s' (%p)\n",
1317                  wlan_plugin_address_to_string (NULL, &mas->endpoint->addr, sizeof (struct WlanAddress)),
1318              fm);
1319         mas->endpoint->timeout = GNUNET_TIME_relative_to_absolute (MACENDPOINT_TIMEOUT);
1320         if (NULL != fm->cont)
1321         {
1322           fm->cont (fm->cont_cls, &fm->target, GNUNET_OK, fm->size_payload, fm->size_on_wire);
1323           fm->cont = NULL;
1324         }
1325         free_fragment_message (fm);
1326         break;
1327       }
1328       if (GNUNET_NO == ret)
1329       {
1330         LOG (GNUNET_ERROR_TYPE_DEBUG, 
1331              "Got an ACK, message transmission to `%s' not yet finished\n",
1332                   wlan_plugin_address_to_string (NULL, &mas->endpoint->addr, sizeof (struct WlanAddress)));
1333         break;
1334       }
1335     }
1336     LOG (GNUNET_ERROR_TYPE_DEBUG, 
1337          "ACK not matched against any active fragmentation with MAC `%s'\n",
1338          wlan_plugin_address_to_string (NULL, &mas->endpoint->addr, sizeof (struct WlanAddress)));
1339     break;
1340   case GNUNET_MESSAGE_TYPE_WLAN_DATA:
1341     if (NULL == mas->endpoint)
1342     {
1343       GNUNET_break (0);
1344       break;
1345     }
1346     if (msize < sizeof (struct WlanHeader))
1347     {
1348       GNUNET_break (0);
1349       break;
1350     }    
1351     wlanheader = (const struct WlanHeader *) hdr;
1352     if (0 != memcmp (&wlanheader->target,
1353                      plugin->env->my_identity,
1354                      sizeof (struct GNUNET_PeerIdentity)))
1355     {
1356       LOG (GNUNET_ERROR_TYPE_DEBUG, 
1357            "WLAN data for `%s', not for me, ignoring\n",
1358            GNUNET_i2s (&wlanheader->target));
1359       break;
1360     }
1361     if (ntohl (wlanheader->crc) !=
1362         GNUNET_CRYPTO_crc32_n (&wlanheader[1], msize - sizeof (struct WlanHeader)))
1363     {
1364       GNUNET_STATISTICS_update (plugin->env->stats,
1365                                 _("# WLAN DATA messages discarded due to CRC32 error"), 1,
1366                                 GNUNET_NO);
1367       break;
1368     }
1369     xmas.endpoint = mas->endpoint;
1370     if (NULL == (xmas.session =  lookup_session (mas->endpoint, &wlanheader->sender, GNUNET_YES)))
1371     {
1372         xmas.session = create_session (mas->endpoint, &wlanheader->sender, GNUNET_YES);
1373         plugin->env->session_start (NULL, &wlanheader->sender,
1374                         PLUGIN_NAME, NULL, 0, xmas.session, NULL, 0);
1375       LOG (GNUNET_ERROR_TYPE_DEBUG,
1376                 "Notifying transport about peer `%s''s new inbound session %p \n",
1377                 GNUNET_i2s (&wlanheader->sender), xmas.session);
1378     }
1379     LOG (GNUNET_ERROR_TYPE_DEBUG,
1380                 "Processing %u bytes of WLAN DATA from peer `%s'\n",
1381          (unsigned int) msize,
1382          GNUNET_i2s (&wlanheader->sender));
1383     (void) GNUNET_SERVER_mst_receive (plugin->wlan_header_payload_tokenizer, 
1384                                       &xmas,
1385                                       (const char *) &wlanheader[1],
1386                                       msize - sizeof (struct WlanHeader),
1387                                       GNUNET_YES, GNUNET_NO); 
1388     break;
1389   default:
1390     if (NULL == mas->endpoint)
1391     {
1392       GNUNET_break (0);
1393       break;
1394     }
1395     if (NULL == mas->session)
1396     {
1397       GNUNET_break (0);
1398       break;
1399     }
1400     LOG (GNUNET_ERROR_TYPE_DEBUG,
1401          "Received packet with %u bytes of type %u from peer %s\n",
1402          (unsigned int) msize,
1403          (unsigned int) ntohs (hdr->type),
1404          GNUNET_i2s (&mas->session->target));
1405     plugin->env->receive (plugin->env->cls, 
1406                           &mas->session->target,
1407                           hdr, 
1408                           mas->session,
1409                           (mas->endpoint == NULL) ? NULL : (const char *) &mas->endpoint->addr,
1410                           (mas->endpoint == NULL) ? 0 : sizeof (struct WlanAddress));
1411     plugin->env->update_address_metrics (plugin->env->cls,
1412                                          &mas->session->target,
1413                                          (mas->endpoint == NULL) ? NULL : (const char *) &mas->endpoint->addr,
1414                                          (mas->endpoint == NULL) ? 0 : sizeof (struct WlanAddress),
1415                                          mas->session,
1416                                          &ats, 1);
1417     break;
1418   }
1419   return GNUNET_OK;
1420 }
1421
1422
1423 /**
1424  * Function used for to process the data from the suid process
1425  *
1426  * @param cls the plugin handle
1427  * @param client client that send the data (not used)
1428  * @param hdr header of the GNUNET_MessageHeader
1429  */
1430 static int
1431 handle_helper_message (void *cls, void *client,
1432                        const struct GNUNET_MessageHeader *hdr)
1433 {
1434   struct Plugin *plugin = cls;
1435   const struct GNUNET_TRANSPORT_WLAN_RadiotapReceiveMessage *rxinfo;
1436   const struct GNUNET_TRANSPORT_WLAN_HelperControlMessage *cm;
1437   struct WlanAddress wa;
1438   struct MacAndSession mas;
1439   uint16_t msize;
1440
1441   msize = ntohs (hdr->size);
1442   switch (ntohs (hdr->type))
1443   {
1444   case GNUNET_MESSAGE_TYPE_WLAN_HELPER_CONTROL:
1445     if (msize != sizeof (struct GNUNET_TRANSPORT_WLAN_HelperControlMessage))
1446     {
1447       GNUNET_break (0);
1448       break;
1449     }
1450     cm = (const struct GNUNET_TRANSPORT_WLAN_HelperControlMessage *) hdr;
1451     if (GNUNET_YES == plugin->have_mac)
1452     {
1453       if (0 == memcmp (&plugin->mac_address,
1454                        &cm->mac,
1455                        sizeof (struct GNUNET_TRANSPORT_WLAN_MacAddress)))
1456         break; /* no change */
1457       /* remove old address */
1458       memset (&wa, 0, sizeof (struct WlanAddress));
1459       wa.mac = plugin->mac_address;
1460       wa.options = htonl(plugin->options);
1461       plugin->env->notify_address (plugin->env->cls, GNUNET_NO,
1462                                    &wa,
1463                                    sizeof (wa),
1464                                    "wlan");
1465     }
1466     plugin->mac_address = cm->mac;
1467     plugin->have_mac = GNUNET_YES;
1468     memset (&wa, 0, sizeof (struct WlanAddress));
1469     wa.mac = plugin->mac_address;
1470     wa.options = htonl(plugin->options);
1471     LOG (GNUNET_ERROR_TYPE_DEBUG,
1472          "Received WLAN_HELPER_CONTROL message with MAC address `%s' for peer `%s'\n",
1473          mac_to_string (&cm->mac),
1474          GNUNET_i2s (plugin->env->my_identity));
1475     plugin->env->notify_address (plugin->env->cls, GNUNET_YES,
1476                                  &wa,
1477                                  sizeof (struct WlanAddress),
1478                                  "wlan");
1479     break;
1480   case GNUNET_MESSAGE_TYPE_WLAN_DATA_FROM_HELPER:
1481     LOG (GNUNET_ERROR_TYPE_DEBUG, 
1482          "Got data message from helper with %u bytes\n",
1483          msize);
1484     GNUNET_STATISTICS_update (plugin->env->stats,
1485                               _("# DATA messages received via WLAN"), 1,
1486                               GNUNET_NO);
1487     if (msize < sizeof (struct GNUNET_TRANSPORT_WLAN_RadiotapReceiveMessage))
1488     {
1489       GNUNET_break (0);
1490       LOG (GNUNET_ERROR_TYPE_DEBUG,
1491            "Size of packet is too small (%u bytes)\n",
1492            msize);
1493       break;
1494     }
1495     rxinfo = (const struct GNUNET_TRANSPORT_WLAN_RadiotapReceiveMessage *) hdr;
1496
1497     /* check if message is actually for us */
1498     if (0 != memcmp (&rxinfo->frame.addr3, &mac_bssid_gnunet,
1499                      sizeof (struct GNUNET_TRANSPORT_WLAN_MacAddress)))
1500     {
1501       /* Not the GNUnet BSSID */
1502       break;
1503     }
1504     if ( (0 != memcmp (&rxinfo->frame.addr1, &bc_all_mac,
1505                        sizeof (struct GNUNET_TRANSPORT_WLAN_MacAddress))) &&
1506          (0 != memcmp (&rxinfo->frame.addr1, &plugin->mac_address,
1507                        sizeof (struct GNUNET_TRANSPORT_WLAN_MacAddress))) )
1508     {
1509       /* Neither broadcast nor specifically for us */
1510       break;
1511     }
1512     if (0 == memcmp (&rxinfo->frame.addr2, &plugin->mac_address,
1513                      sizeof (struct GNUNET_TRANSPORT_WLAN_MacAddress)))
1514     {
1515       /* packet is FROM us, thus not FOR us */
1516       break;
1517     }
1518     
1519     GNUNET_STATISTICS_update (plugin->env->stats,
1520                               _("# WLAN DATA messages processed"),
1521                               1, GNUNET_NO);
1522     LOG (GNUNET_ERROR_TYPE_DEBUG,
1523          "Receiving %u bytes of data from MAC `%s'\n",
1524          (unsigned int) (msize - sizeof (struct GNUNET_TRANSPORT_WLAN_RadiotapReceiveMessage)),
1525          mac_to_string (&rxinfo->frame.addr2));
1526     wa.mac = rxinfo->frame.addr2;
1527     wa.options = htonl (0);
1528     mas.endpoint = create_macendpoint (plugin, &wa);
1529     mas.session = NULL;
1530     (void) GNUNET_SERVER_mst_receive (plugin->helper_payload_tokenizer, 
1531                                       &mas,
1532                                       (const char*) &rxinfo[1],
1533                                       msize - sizeof (struct GNUNET_TRANSPORT_WLAN_RadiotapReceiveMessage),
1534                                       GNUNET_YES, GNUNET_NO);
1535     break;
1536   default:
1537     GNUNET_break (0);
1538     LOG (GNUNET_ERROR_TYPE_DEBUG, 
1539          "Unexpected message of type %u (%u bytes)",
1540          ntohs (hdr->type), ntohs (hdr->size));
1541     break;
1542   }
1543   return GNUNET_OK;
1544 }
1545
1546
1547
1548 /**
1549  * Task to (periodically) send a HELLO beacon
1550  *
1551  * @param cls pointer to the plugin struct
1552  * @param tc scheduler context
1553  */
1554 static void
1555 send_hello_beacon (void *cls,
1556                    const struct GNUNET_SCHEDULER_TaskContext *tc)
1557 {
1558   struct Plugin *plugin = cls;
1559   uint16_t size;
1560   uint16_t hello_size;
1561   struct GNUNET_TRANSPORT_WLAN_RadiotapSendMessage *radioHeader;
1562   const struct GNUNET_MessageHeader *hello;
1563
1564   hello = plugin->env->get_our_hello ();
1565   hello_size = GNUNET_HELLO_size ((struct GNUNET_HELLO_Message *) hello);
1566   GNUNET_assert (sizeof (struct WlanHeader) + hello_size <= WLAN_MTU);
1567   size = sizeof (struct GNUNET_TRANSPORT_WLAN_RadiotapSendMessage) + hello_size;
1568   {
1569     char buf[size] GNUNET_ALIGN;
1570
1571     LOG (GNUNET_ERROR_TYPE_DEBUG, 
1572          "Sending %u byte HELLO beacon\n",
1573          (unsigned int) size);
1574     radioHeader = (struct GNUNET_TRANSPORT_WLAN_RadiotapSendMessage*) buf;
1575     get_radiotap_header (NULL, radioHeader, size);
1576     get_wlan_header (plugin, &radioHeader->frame, &bc_all_mac, size);
1577     memcpy (&radioHeader[1], hello, hello_size);
1578     if (NULL !=
1579         GNUNET_HELPER_send (plugin->suid_helper,
1580                             &radioHeader->header,
1581                             GNUNET_YES /* can drop */,
1582                             NULL, NULL))
1583       GNUNET_STATISTICS_update (plugin->env->stats, _("# HELLO beacons sent via WLAN"),
1584                                 1, GNUNET_NO);
1585   }
1586   plugin->beacon_task =
1587     GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply
1588                                   (HELLO_BEACON_SCALING_FACTOR,
1589                                    plugin->mac_count + 1),
1590                                   &send_hello_beacon,
1591                                   plugin);
1592
1593 }
1594
1595
1596 /**
1597  * Another peer has suggested an address for this
1598  * peer and transport plugin.  Check that this could be a valid
1599  * address.  If so, consider adding it to the list
1600  * of addresses.
1601  *
1602  * @param cls closure
1603  * @param addr pointer to the address
1604  * @param addrlen length of addr
1605  * @return GNUNET_OK if this is a plausible address for this peer
1606  *         and transport
1607  */
1608 static int
1609 wlan_plugin_address_suggested (void *cls, const void *addr, size_t addrlen)
1610 {
1611   struct Plugin *plugin = cls;
1612   struct WlanAddress *wa = (struct WlanAddress *) addr;
1613
1614   if (addrlen != sizeof (struct WlanAddress))
1615   {    
1616     GNUNET_break_op (0);
1617     return GNUNET_SYSERR;
1618   }
1619   if (GNUNET_YES != plugin->have_mac)
1620   {
1621     LOG (GNUNET_ERROR_TYPE_DEBUG, 
1622          "Rejecting MAC `%s': I don't know my MAC!\n",
1623          mac_to_string (addr));
1624     return GNUNET_NO; /* don't know my MAC */
1625   }
1626   if (0 != memcmp (&wa->mac,
1627                    &plugin->mac_address,
1628                    sizeof (wa->mac)))
1629   {
1630     LOG (GNUNET_ERROR_TYPE_DEBUG, 
1631          "Rejecting MAC `%s': not my MAC!\n",
1632          mac_to_string (addr));
1633     return GNUNET_NO; /* not my MAC */
1634   }
1635   return GNUNET_OK;
1636 }
1637
1638
1639 /**
1640  * Function called for a quick conversion of the binary address to
1641  * a numeric address.  Note that the caller must not free the
1642  * address and that the next call to this function is allowed
1643  * to override the address again.
1644  *
1645  * @param cls closure
1646  * @param addr binary address
1647  * @param addrlen length of the address
1648  * @return string representing the same address
1649  */
1650 static const char *
1651 wlan_plugin_address_to_string (void *cls, const void *addr, size_t addrlen)
1652 {
1653   const struct GNUNET_TRANSPORT_WLAN_MacAddress *mac;
1654   static char macstr[36];
1655
1656   if (sizeof (struct WlanAddress) != addrlen)
1657   {
1658     GNUNET_break (0);
1659     return NULL;
1660   }
1661   mac = &((struct WlanAddress *) addr)->mac;
1662   GNUNET_snprintf (macstr, sizeof (macstr), "%s.%u.%s",
1663                 PLUGIN_NAME, ntohl (((struct WlanAddress *) addr)->options),
1664                 mac_to_string (mac));
1665   return macstr;
1666 }
1667
1668
1669 /**
1670  * Convert the transports address to a nice, human-readable format.
1671  *
1672  * @param cls closure
1673  * @param type name of the transport that generated the address
1674  * @param addr one of the addresses of the host, NULL for the last address
1675  *        the specific address format depends on the transport
1676  * @param addrlen length of the address
1677  * @param numeric should (IP) addresses be displayed in numeric form?
1678  * @param timeout after how long should we give up?
1679  * @param asc function to call on each string
1680  * @param asc_cls closure for asc
1681  */
1682 static void
1683 wlan_plugin_address_pretty_printer (void *cls, const char *type,
1684                                     const void *addr, size_t addrlen,
1685                                     int numeric,
1686                                     struct GNUNET_TIME_Relative timeout,
1687                                     GNUNET_TRANSPORT_AddressStringCallback asc,
1688                                     void *asc_cls)
1689 {
1690   char *ret;
1691
1692   if (sizeof (struct WlanAddress) != addrlen)
1693   {
1694     /* invalid address  */
1695     LOG (GNUNET_ERROR_TYPE_WARNING,
1696          _("WLAN address with invalid size encountered\n"));
1697     asc (asc_cls, NULL);
1698     return;
1699   }
1700   ret = GNUNET_strdup (wlan_plugin_address_to_string(NULL, addr, addrlen));
1701   asc (asc_cls, ret);
1702   GNUNET_free (ret);
1703   asc (asc_cls, NULL);
1704 }
1705
1706
1707 /**
1708  * Exit point from the plugin. 
1709  *
1710  * @param cls pointer to the api struct
1711  */
1712 void *
1713 libgnunet_plugin_transport_wlan_done (void *cls)
1714 {
1715         struct WlanAddress wa;
1716   struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
1717   struct Plugin *plugin = api->cls;
1718   struct MacEndpoint *endpoint;
1719   struct MacEndpoint *endpoint_next;
1720
1721   if (NULL == plugin)
1722   {
1723     GNUNET_free (api);
1724     return NULL;
1725   }
1726
1727   if (GNUNET_YES == plugin->have_mac)
1728   {
1729                 memset (&wa, 0, sizeof (wa));
1730                 wa.options = htonl (plugin->options);
1731                 wa.mac = plugin->mac_address;
1732       plugin->env->notify_address (plugin->env->cls, GNUNET_NO,
1733                                &wa,
1734                                sizeof (struct WlanAddress),
1735                                "wlan");
1736       plugin->have_mac = GNUNET_NO;
1737   }
1738
1739   if (GNUNET_SCHEDULER_NO_TASK != plugin->beacon_task)
1740   {
1741     GNUNET_SCHEDULER_cancel (plugin->beacon_task);
1742     plugin->beacon_task = GNUNET_SCHEDULER_NO_TASK;
1743   }
1744   if (NULL != plugin->suid_helper)
1745   {
1746     GNUNET_HELPER_stop (plugin->suid_helper, GNUNET_NO);
1747     plugin->suid_helper = NULL;
1748   }
1749   endpoint_next = plugin->mac_head;
1750   while (NULL != (endpoint = endpoint_next))
1751   {
1752     endpoint_next = endpoint->next;
1753     free_macendpoint (endpoint);
1754   }
1755   if (NULL != plugin->fragment_data_tokenizer)
1756   {
1757     GNUNET_SERVER_mst_destroy (plugin->fragment_data_tokenizer);
1758     plugin->fragment_data_tokenizer = NULL;
1759   }
1760   if (NULL != plugin->wlan_header_payload_tokenizer)
1761   {
1762     GNUNET_SERVER_mst_destroy (plugin->wlan_header_payload_tokenizer);
1763     plugin->wlan_header_payload_tokenizer = NULL;
1764   }
1765   if (NULL != plugin->helper_payload_tokenizer)
1766   {
1767     GNUNET_SERVER_mst_destroy (plugin->helper_payload_tokenizer);
1768     plugin->helper_payload_tokenizer = NULL;
1769   }
1770   GNUNET_free_non_null (plugin->interface);
1771   GNUNET_free (plugin);
1772   GNUNET_free (api);
1773   return NULL;
1774 }
1775
1776
1777 /**
1778  * Function called to convert a string address to
1779  * a binary address.
1780  *
1781  * @param cls closure ('struct Plugin*')
1782  * @param addr string address
1783  * @param addrlen length of the address
1784  * @param buf location to store the buffer
1785  * @param added location to store the number of bytes in the buffer.
1786  *        If the function returns GNUNET_SYSERR, its contents are undefined.
1787  * @return GNUNET_OK on success, GNUNET_SYSERR on failure
1788  */
1789 static int
1790 wlan_string_to_address (void *cls, const char *addr, uint16_t addrlen,
1791                         void **buf, size_t *added)
1792 {
1793   struct WlanAddress *wa;
1794   unsigned int a[6];
1795   unsigned int i;
1796   char plugin[5];
1797   uint32_t options;
1798
1799   if ((NULL == addr) || (addrlen == 0))
1800   {
1801     GNUNET_break (0);
1802     return GNUNET_SYSERR;
1803   }
1804   if ('\0' != addr[addrlen - 1])
1805   {
1806     GNUNET_break (0);
1807     return GNUNET_SYSERR;
1808   }
1809   if (strlen (addr) != addrlen - 1)
1810   {
1811     GNUNET_break (0);
1812     return GNUNET_SYSERR;
1813   }
1814
1815   if (8 != SSCANF (addr,
1816                    "%4s.%u.%X:%X:%X:%X:%X:%X",
1817                    plugin, &options,
1818                    &a[0], &a[1], &a[2], &a[3], &a[4], &a[5]))
1819   {
1820     GNUNET_break (0);
1821     return GNUNET_SYSERR;
1822   }
1823   wa = GNUNET_malloc (sizeof (struct WlanAddress));
1824   for (i=0;i<6;i++)
1825     wa->mac.mac[i] = a[i];
1826   wa->options = htonl (0);
1827   *buf = wa;
1828   *added = sizeof (struct WlanAddress);
1829   return GNUNET_OK;
1830 }
1831
1832
1833 /**
1834  * Entry point for the plugin.
1835  *
1836  * @param cls closure, the 'struct GNUNET_TRANSPORT_PluginEnvironment*'
1837  * @return the 'struct GNUNET_TRANSPORT_PluginFunctions*' or NULL on error
1838  */
1839 void *
1840 libgnunet_plugin_transport_wlan_init (void *cls)
1841 {
1842   struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
1843   struct GNUNET_TRANSPORT_PluginFunctions *api;
1844   struct Plugin *plugin;
1845   char *interface;
1846   unsigned long long testmode;
1847   char *binary;
1848
1849   /* check for 'special' mode */
1850   if (NULL == env->receive)
1851   {
1852     /* run in 'stub' mode (i.e. as part of gnunet-peerinfo), don't fully
1853        initialze the plugin or the API */
1854     api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
1855     api->cls = NULL;
1856     api->address_pretty_printer = &wlan_plugin_address_pretty_printer;
1857     api->address_to_string = &wlan_plugin_address_to_string;
1858     api->string_to_address = &wlan_string_to_address;
1859     return api;
1860   }
1861
1862   testmode = 0;
1863   /* check configuration */
1864   if ( (GNUNET_YES == 
1865         GNUNET_CONFIGURATION_have_value (env->cfg, "transport-wlan", "TESTMODE")) &&
1866        ( (GNUNET_SYSERR ==
1867           GNUNET_CONFIGURATION_get_value_number (env->cfg, "transport-wlan",
1868                                                  "TESTMODE", &testmode)) ||
1869          (testmode > 2) ) )
1870   {
1871     GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
1872                                "transport-wlan", "TESTMODE");
1873     return NULL;
1874   }
1875   binary = GNUNET_OS_get_libexec_binary_path ("gnunet-helper-transport-wlan");
1876   if ( (0 == testmode) &&
1877        (GNUNET_YES != GNUNET_OS_check_helper_binary (binary, GNUNET_YES, NULL)) )
1878   {
1879     LOG (GNUNET_ERROR_TYPE_ERROR,
1880          _("Helper binary `%s' not SUID, cannot run WLAN transport\n"),
1881          "gnunet-helper-transport-wlan");
1882     GNUNET_free (binary);
1883     return NULL;
1884   }
1885     GNUNET_free (binary);
1886   if (GNUNET_YES !=
1887       GNUNET_CONFIGURATION_get_value_string
1888       (env->cfg, "transport-wlan", "INTERFACE",
1889        &interface))
1890   {
1891     GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
1892                                "transport-wlan", "INTERFACE");
1893     return NULL;    
1894   }
1895
1896   plugin = GNUNET_malloc (sizeof (struct Plugin));
1897   plugin->interface = interface;
1898   plugin->env = env;
1899   GNUNET_STATISTICS_set (plugin->env->stats, _("# WLAN sessions allocated"),
1900                          0, GNUNET_NO);
1901   GNUNET_STATISTICS_set (plugin->env->stats, _("# WLAN MAC endpoints allocated"),
1902                          0, 0);
1903   GNUNET_BANDWIDTH_tracker_init (&plugin->tracker,
1904                                  GNUNET_BANDWIDTH_value_init (100 * 1024 *
1905                                                               1024 / 8), 100);
1906   plugin->fragment_data_tokenizer = GNUNET_SERVER_mst_create (&process_data, plugin);
1907   plugin->wlan_header_payload_tokenizer = GNUNET_SERVER_mst_create (&process_data, plugin);
1908   plugin->helper_payload_tokenizer = GNUNET_SERVER_mst_create (&process_data, plugin);
1909   plugin->beacon_task = GNUNET_SCHEDULER_add_now (&send_hello_beacon, 
1910                                                   plugin);
1911
1912   plugin->options = 0;
1913
1914   /* some compilers do not like switch on 'long long'... */
1915   switch ((unsigned int) testmode)
1916   {
1917   case 0: /* normal */ 
1918     plugin->helper_argv[0] = (char *) "gnunet-helper-transport-wlan";
1919     plugin->helper_argv[1] = interface;
1920     plugin->helper_argv[2] = NULL;
1921     plugin->suid_helper = GNUNET_HELPER_start (GNUNET_NO,
1922                                                "gnunet-helper-transport-wlan",
1923                                                plugin->helper_argv,
1924                                                &handle_helper_message,
1925                                                NULL,
1926                                                plugin);
1927     break;
1928   case 1: /* testmode, peer 1 */
1929     plugin->helper_argv[0] = (char *) "gnunet-helper-transport-wlan-dummy";
1930     plugin->helper_argv[1] = (char *) "1";
1931     plugin->helper_argv[2] = NULL;
1932     plugin->suid_helper = GNUNET_HELPER_start (GNUNET_NO,
1933                                                "gnunet-helper-transport-wlan-dummy",
1934                                                plugin->helper_argv,
1935                                                &handle_helper_message,
1936                                                NULL,
1937                                                plugin);
1938     break;
1939   case 2: /* testmode, peer 2 */
1940     plugin->helper_argv[0] = (char *) "gnunet-helper-transport-wlan-dummy";
1941     plugin->helper_argv[1] = (char *) "2";
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   default:
1951     GNUNET_assert (0);
1952   }
1953
1954   api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
1955   api->cls = plugin;
1956   api->send = &wlan_plugin_send;
1957   api->get_session = &wlan_plugin_get_session;
1958   api->disconnect = &wlan_plugin_disconnect;
1959   api->address_pretty_printer = &wlan_plugin_address_pretty_printer;
1960   api->check_address = &wlan_plugin_address_suggested;
1961   api->address_to_string = &wlan_plugin_address_to_string;
1962   api->string_to_address = &wlan_string_to_address;
1963   api->get_network = &wlan_get_network;
1964   return api;
1965 }
1966
1967
1968 /* end of plugin_transport_wlan.c */