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