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