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