-fix uninit
[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->fragcontext =
842     GNUNET_FRAGMENT_context_create (plugin->env->stats, WLAN_MTU,
843                                     &plugin->tracker,
844                                     GNUNET_TIME_UNIT_SECONDS,
845                                     msg,
846                                     &transmit_fragment, fm);
847   fm->timeout_task =
848     GNUNET_SCHEDULER_add_delayed (timeout, 
849                                   &fragmentmessage_timeout, fm);
850   GNUNET_CONTAINER_DLL_insert_tail (endpoint->sending_messages_head,
851                                     endpoint->sending_messages_tail,
852                                     fm);
853 }
854
855
856 /**
857  * Free a MAC endpoint.
858  * 
859  * @param endpoint pointer to the MacEndpoint to free
860  */
861 static void
862 free_macendpoint (struct MacEndpoint *endpoint)
863 {
864   struct Plugin *plugin = endpoint->plugin;
865   struct FragmentMessage *fm;
866   struct Session *session;
867
868   GNUNET_STATISTICS_update (plugin->env->stats,
869                             _("# WLAN MAC endpoints allocated"), -1, GNUNET_NO);
870   while (NULL != (session = endpoint->sessions_head))
871     free_session (session);
872   while (NULL != (fm = endpoint->sending_messages_head))
873     free_fragment_message (fm);
874   GNUNET_CONTAINER_DLL_remove (plugin->mac_head, 
875                                plugin->mac_tail, 
876                                endpoint);
877   plugin->mac_count--;
878   if (GNUNET_SCHEDULER_NO_TASK != endpoint->timeout_task)
879   {
880     GNUNET_SCHEDULER_cancel (endpoint->timeout_task);
881     endpoint->timeout_task = GNUNET_SCHEDULER_NO_TASK;
882   }
883   GNUNET_free (endpoint);
884 }
885
886
887 /**
888  * A MAC endpoint is timing out.  Clean up.
889  *
890  * @param cls pointer to the MacEndpoint
891  * @param tc pointer to the GNUNET_SCHEDULER_TaskContext
892  */
893 static void
894 macendpoint_timeout (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
895 {
896   struct MacEndpoint *endpoint = cls;
897   struct GNUNET_TIME_Relative timeout;
898
899   endpoint->timeout_task = GNUNET_SCHEDULER_NO_TASK;
900   timeout = GNUNET_TIME_absolute_get_remaining (endpoint->timeout);
901   if (0 == timeout.rel_value) 
902   {
903     free_macendpoint (endpoint);
904     return;
905   }
906   endpoint->timeout_task =
907     GNUNET_SCHEDULER_add_delayed (timeout, &macendpoint_timeout,
908                                   endpoint);
909 }
910
911
912 /**
913  * Find (or create) a MacEndpoint with a specific MAC address
914  *
915  * @param plugin pointer to the plugin struct
916  * @param addr the MAC address of the endpoint
917  * @return handle to our data structure for this MAC
918  */
919 static struct MacEndpoint *
920 create_macendpoint (struct Plugin *plugin,
921                     const struct GNUNET_TRANSPORT_WLAN_MacAddress *addr)
922 {
923   struct MacEndpoint *pos;
924
925   for (pos = plugin->mac_head; NULL != pos; pos = pos->next)
926     if (0 == memcmp (addr, &pos->addr, sizeof (struct GNUNET_TRANSPORT_WLAN_MacAddress)))
927       return pos; 
928   pos = GNUNET_malloc (sizeof (struct MacEndpoint));
929   pos->addr = *addr;
930   pos->plugin = plugin;
931   pos->defrag =
932     GNUNET_DEFRAGMENT_context_create (plugin->env->stats, WLAN_MTU,
933                                       MESSAGES_IN_DEFRAG_QUEUE_PER_MAC,
934                                       pos, 
935                                       &wlan_data_message_handler,
936                                       &send_ack);
937   pos->timeout = GNUNET_TIME_relative_to_absolute (MACENDPOINT_TIMEOUT);
938   pos->timeout_task =
939       GNUNET_SCHEDULER_add_delayed (MACENDPOINT_TIMEOUT, &macendpoint_timeout,
940                                     pos);
941   GNUNET_CONTAINER_DLL_insert (plugin->mac_head, plugin->mac_tail, pos);
942   plugin->mac_count++;
943   GNUNET_STATISTICS_update (plugin->env->stats, _("# WLAN MAC endpoints allocated"),
944                             1, GNUNET_NO);
945   LOG (GNUNET_ERROR_TYPE_DEBUG, 
946        "New MAC endpoint `%s'\n",
947        mac_to_string (addr));
948   return pos;
949 }
950
951
952 /**
953  * Creates a new outbound session the transport service will use to send data to the
954  * peer
955  *
956  * @param cls the plugin
957  * @param address the address
958  * @return the session or NULL of max connections exceeded
959  */
960 static struct Session *
961 wlan_plugin_get_session (void *cls,
962                          const struct GNUNET_HELLO_Address *address)
963 {
964   struct Plugin *plugin = cls;
965   struct MacEndpoint *endpoint;
966
967   if (NULL == address)
968     return NULL;
969   if (sizeof (struct GNUNET_TRANSPORT_WLAN_MacAddress) != address->address_length)
970   {
971     GNUNET_break (0);
972     return NULL;
973   }
974   LOG (GNUNET_ERROR_TYPE_DEBUG,
975        "Service asked to create session for peer `%s' with MAC `%s'\n",
976        GNUNET_i2s (&address->peer),
977        mac_to_string (address->address));
978   endpoint = create_macendpoint (plugin, address->address);
979   return create_session (endpoint, &address->peer);
980 }
981
982
983 /**
984  * Function that can be used to force the plugin to disconnect
985  * from the given peer and cancel all previous transmissions
986  * (and their continuation).
987  *
988  * @param cls closure
989  * @param target peer from which to disconnect
990  */
991 static void
992 wlan_plugin_disconnect (void *cls, const struct GNUNET_PeerIdentity *target)
993 {
994   struct Plugin *plugin = cls;
995   struct Session *session;
996   struct MacEndpoint *endpoint;
997
998   for (endpoint = plugin->mac_head; NULL != endpoint; endpoint = endpoint->next)
999     for (session = endpoint->sessions_head; NULL != session; session = session->next)
1000       if (0 == memcmp (target, &session->target,
1001                        sizeof (struct GNUNET_PeerIdentity)))
1002       {
1003         free_session (session);
1004         break; /* inner-loop only (in case peer has another MAC as well!) */
1005       }
1006 }
1007
1008
1009 /**
1010  * Function that can be used by the transport service to transmit
1011  * a message using the plugin.   Note that in the case of a
1012  * peer disconnecting, the continuation MUST be called
1013  * prior to the disconnect notification itself.  This function
1014  * will be called with this peer's HELLO message to initiate
1015  * a fresh connection to another peer.
1016  *
1017  * @param cls closure
1018  * @param session which session must be used
1019  * @param msgbuf the message to transmit
1020  * @param msgbuf_size number of bytes in 'msgbuf'
1021  * @param priority how important is the message (most plugins will
1022  *                 ignore message priority and just FIFO)
1023  * @param to how long to wait at most for the transmission (does not
1024  *                require plugins to discard the message after the timeout,
1025  *                just advisory for the desired delay; most plugins will ignore
1026  *                this as well)
1027  * @param cont continuation to call once the message has
1028  *        been transmitted (or if the transport is ready
1029  *        for the next transmission call; or if the
1030  *        peer disconnected...); can be NULL
1031  * @param cont_cls closure for cont
1032  * @return number of bytes used (on the physical network, with overheads);
1033  *         -1 on hard errors (i.e. address invalid); 0 is a legal value
1034  *         and does NOT mean that the message was not transmitted (DV)
1035  */
1036 static ssize_t
1037 wlan_plugin_send (void *cls,
1038                   struct Session *session,
1039                   const char *msgbuf, size_t msgbuf_size,
1040                   unsigned int priority,
1041                   struct GNUNET_TIME_Relative to,
1042                   GNUNET_TRANSPORT_TransmitContinuation cont, void *cont_cls)
1043 {
1044   struct Plugin *plugin = cls;
1045   struct WlanHeader *wlanheader;
1046   size_t size = msgbuf_size + sizeof (struct WlanHeader);
1047   char buf[size] GNUNET_ALIGN;
1048
1049   LOG (GNUNET_ERROR_TYPE_DEBUG, 
1050        "Transmitting %u bytes of payload to peer `%s' (starting with %u byte message of type %u)\n",
1051        msgbuf_size,
1052        GNUNET_i2s (&session->target),
1053        (unsigned int) ntohs (((struct GNUNET_MessageHeader*)msgbuf)->size),
1054        (unsigned int) ntohs (((struct GNUNET_MessageHeader*)msgbuf)->type));
1055   wlanheader = (struct WlanHeader *) buf;
1056   wlanheader->header.size = htons (msgbuf_size + sizeof (struct WlanHeader));
1057   wlanheader->header.type = htons (GNUNET_MESSAGE_TYPE_WLAN_DATA);
1058   wlanheader->sender = *plugin->env->my_identity;
1059   wlanheader->target = session->target;
1060   wlanheader->crc = htonl (GNUNET_CRYPTO_crc32_n (msgbuf, msgbuf_size));
1061   memcpy (&wlanheader[1], msgbuf, msgbuf_size);
1062   send_with_fragmentation (session->mac,
1063                            to,
1064                            &session->target,
1065                            &wlanheader->header,
1066                            cont, cont_cls);
1067   return size;
1068 }
1069
1070
1071 /**
1072  * We have received data from the WLAN via some session.  Process depending
1073  * on the message type (HELLO, DATA, FRAGMENTATION or FRAGMENTATION-ACK).
1074  *
1075  * @param cls pointer to the plugin
1076  * @param client pointer to the session this message belongs to
1077  * @param hdr start of the message
1078  */
1079 static void
1080 process_data (void *cls, void *client, const struct GNUNET_MessageHeader *hdr)
1081 {
1082   struct Plugin *plugin = cls;
1083   struct MacAndSession *mas = client;
1084   struct MacAndSession xmas;
1085 #define NUM_ATS 2
1086   struct GNUNET_ATS_Information ats[NUM_ATS]; /* FIXME: do better here */
1087   struct FragmentMessage *fm;
1088   struct GNUNET_PeerIdentity tmpsource;
1089   const struct WlanHeader *wlanheader;
1090   int ret;
1091   uint16_t msize;
1092
1093   ats[0].type = htonl (GNUNET_ATS_QUALITY_NET_DISTANCE);
1094   ats[0].value = htonl (1);
1095   ats[1].type = htonl (GNUNET_ATS_NETWORK_TYPE);
1096   ats[1].value = htonl (GNUNET_ATS_NET_WLAN);
1097   msize = ntohs (hdr->size);
1098   switch (ntohs (hdr->type))
1099   {
1100   case GNUNET_MESSAGE_TYPE_HELLO:
1101     if (GNUNET_OK != 
1102         GNUNET_HELLO_get_id ((const struct GNUNET_HELLO_Message *) hdr, &tmpsource))
1103     {
1104       GNUNET_break_op (0);
1105       break;
1106     }
1107     LOG (GNUNET_ERROR_TYPE_DEBUG, 
1108          "Processing %u bytes of HELLO from peer `%s' at MAC %s\n",
1109          (unsigned int) msize,
1110          GNUNET_i2s (&tmpsource),
1111          mac_to_string (&mas->endpoint->addr));
1112
1113     GNUNET_STATISTICS_update (plugin->env->stats,
1114                               _("# HELLO messages received via WLAN"), 1,
1115                               GNUNET_NO);
1116     plugin->env->receive (plugin->env->cls, 
1117                           &tmpsource,
1118                           hdr, 
1119                           ats, NUM_ATS,
1120                           mas->session,
1121                           (mas->endpoint == NULL) ? NULL : (const char *) &mas->endpoint->addr,
1122                           (mas->endpoint == NULL) ? 0 : sizeof (struct GNUNET_TRANSPORT_WLAN_MacAddress));
1123     break;
1124   case GNUNET_MESSAGE_TYPE_FRAGMENT:
1125     if (NULL == mas->endpoint)
1126     {
1127       GNUNET_break (0);
1128       break;
1129     }
1130     LOG (GNUNET_ERROR_TYPE_DEBUG, 
1131          "Processing %u bytes of FRAGMENT from MAC %s\n",
1132          (unsigned int) msize,
1133          mac_to_string (&mas->endpoint->addr));
1134     GNUNET_STATISTICS_update (plugin->env->stats,
1135                               _("# fragments received via WLAN"), 1, GNUNET_NO);
1136     (void) GNUNET_DEFRAGMENT_process_fragment (mas->endpoint->defrag,
1137                                               hdr);
1138     break;
1139   case GNUNET_MESSAGE_TYPE_FRAGMENT_ACK:
1140     if (NULL == mas->endpoint)
1141     {
1142       GNUNET_break (0);
1143       break;
1144     }
1145     GNUNET_STATISTICS_update (plugin->env->stats, _("# ACKs received via WLAN"),
1146                               1, GNUNET_NO);
1147     for (fm = mas->endpoint->sending_messages_head; NULL != fm; fm = fm->next)
1148     {
1149       ret = GNUNET_FRAGMENT_process_ack (fm->fragcontext, hdr);
1150       if (GNUNET_OK == ret)
1151       {
1152         LOG (GNUNET_ERROR_TYPE_DEBUG, 
1153              "Got last ACK, finished message transmission to `%s' (%p)\n",
1154              mac_to_string (&mas->endpoint->addr),
1155              fm);
1156         mas->endpoint->timeout = GNUNET_TIME_relative_to_absolute (MACENDPOINT_TIMEOUT);
1157         if (NULL != fm->cont)
1158         {
1159           fm->cont (fm->cont_cls, &fm->target, GNUNET_OK);
1160           fm->cont = NULL;
1161         }
1162         free_fragment_message (fm);
1163         break;
1164       }
1165       if (GNUNET_NO == ret)
1166       {
1167         LOG (GNUNET_ERROR_TYPE_DEBUG, 
1168              "Got an ACK, message transmission to `%s' not yet finished\n",
1169              mac_to_string (&mas->endpoint->addr));
1170         break;
1171       }
1172     }
1173     LOG (GNUNET_ERROR_TYPE_DEBUG, 
1174          "ACK not matched against any active fragmentation with MAC `%s'\n",
1175          mac_to_string (&mas->endpoint->addr));
1176     break;
1177   case GNUNET_MESSAGE_TYPE_WLAN_DATA:
1178     if (NULL == mas->endpoint)
1179     {
1180       GNUNET_break (0);
1181       break;
1182     }
1183     if (msize < sizeof (struct WlanHeader))
1184     {
1185       GNUNET_break (0);
1186       break;
1187     }    
1188     wlanheader = (const struct WlanHeader *) hdr;
1189     if (0 != memcmp (&wlanheader->target,
1190                      plugin->env->my_identity,
1191                      sizeof (struct GNUNET_PeerIdentity)))
1192     {
1193       LOG (GNUNET_ERROR_TYPE_DEBUG, 
1194            "WLAN data for `%s', not for me, ignoring\n",
1195            GNUNET_i2s (&wlanheader->target));
1196       break;
1197     }
1198     if (ntohl (wlanheader->crc) !=
1199         GNUNET_CRYPTO_crc32_n (&wlanheader[1], msize - sizeof (struct WlanHeader)))
1200     {
1201       GNUNET_STATISTICS_update (plugin->env->stats,
1202                                 _("# WLAN DATA messages discarded due to CRC32 error"), 1,
1203                                 GNUNET_NO);
1204       break;
1205     }
1206     xmas.endpoint = mas->endpoint;
1207     xmas.session = create_session (mas->endpoint, &wlanheader->sender);
1208     LOG (GNUNET_ERROR_TYPE_DEBUG, 
1209          "Processing %u bytes of WLAN DATA from peer `%s'\n",
1210          (unsigned int) msize,
1211          GNUNET_i2s (&wlanheader->sender));
1212     (void) GNUNET_SERVER_mst_receive (plugin->wlan_header_payload_tokenizer, 
1213                                       &xmas,
1214                                       (const char *) &wlanheader[1],
1215                                       msize - sizeof (struct WlanHeader),
1216                                       GNUNET_YES, GNUNET_NO); 
1217     break;
1218   default:
1219     if (NULL == mas->endpoint)
1220     {
1221       GNUNET_break (0);
1222       break;
1223     }
1224     if (NULL == mas->session)
1225     {
1226       GNUNET_break (0);
1227       break;
1228     }
1229     LOG (GNUNET_ERROR_TYPE_DEBUG,
1230          "Received packet with %u bytes of type %u from peer %s\n",
1231          (unsigned int) msize,
1232          (unsigned int) ntohs (hdr->type),
1233          GNUNET_i2s (&mas->session->target));
1234     plugin->env->receive (plugin->env->cls, 
1235                           &mas->session->target,
1236                           hdr, 
1237                           ats, NUM_ATS,
1238                           mas->session,
1239                           (mas->endpoint == NULL) ? NULL : (const char *) &mas->endpoint->addr,
1240                           (mas->endpoint == NULL) ? 0 : sizeof (struct GNUNET_TRANSPORT_WLAN_MacAddress));
1241     break;
1242   }
1243 }
1244 #undef NUM_ATS
1245
1246
1247 /**
1248  * Function used for to process the data from the suid process
1249  *
1250  * @param cls the plugin handle
1251  * @param client client that send the data (not used)
1252  * @param hdr header of the GNUNET_MessageHeader
1253  */
1254 static void
1255 handle_helper_message (void *cls, void *client,
1256                        const struct GNUNET_MessageHeader *hdr)
1257 {
1258   struct Plugin *plugin = cls;
1259   const struct GNUNET_TRANSPORT_WLAN_RadiotapReceiveMessage *rxinfo;
1260   const struct GNUNET_TRANSPORT_WLAN_HelperControlMessage *cm;
1261   struct MacAndSession mas;
1262   uint16_t msize;
1263
1264   msize = ntohs (hdr->size);
1265   switch (ntohs (hdr->type))
1266   {
1267   case GNUNET_MESSAGE_TYPE_WLAN_HELPER_CONTROL:
1268     if (msize != sizeof (struct GNUNET_TRANSPORT_WLAN_HelperControlMessage))
1269     {
1270       GNUNET_break (0);
1271       break;
1272     }
1273     cm = (const struct GNUNET_TRANSPORT_WLAN_HelperControlMessage *) hdr;
1274     if (GNUNET_YES == plugin->have_mac)
1275     {
1276       if (0 == memcmp (&plugin->mac_address,
1277                        &cm->mac,
1278                        sizeof (struct GNUNET_TRANSPORT_WLAN_MacAddress)))
1279         break; /* no change */
1280       /* remove old address */
1281       plugin->env->notify_address (plugin->env->cls, GNUNET_NO,
1282                                    &plugin->mac_address,
1283                                    sizeof (struct GNUNET_TRANSPORT_WLAN_MacAddress));      
1284     }
1285     plugin->mac_address = cm->mac;
1286     plugin->have_mac = GNUNET_YES;
1287     LOG (GNUNET_ERROR_TYPE_DEBUG,
1288          "Received WLAN_HELPER_CONTROL message with MAC address `%s' for peer `%s'\n",
1289          mac_to_string (&cm->mac),
1290          GNUNET_i2s (plugin->env->my_identity));
1291     plugin->env->notify_address (plugin->env->cls, GNUNET_YES,
1292                                  &plugin->mac_address,
1293                                  sizeof (struct GNUNET_TRANSPORT_WLAN_MacAddress));
1294     break;
1295   case GNUNET_MESSAGE_TYPE_WLAN_DATA_FROM_HELPER:
1296     LOG (GNUNET_ERROR_TYPE_DEBUG, 
1297          "Got data message from helper with %u bytes\n",
1298          msize);
1299     GNUNET_STATISTICS_update (plugin->env->stats,
1300                               _("# DATA messages received via WLAN"), 1,
1301                               GNUNET_NO);
1302     if (msize < sizeof (struct GNUNET_TRANSPORT_WLAN_RadiotapReceiveMessage))
1303     {
1304       GNUNET_break (0);
1305       LOG (GNUNET_ERROR_TYPE_DEBUG,
1306            "Size of packet is too small (%u bytes)\n",
1307            msize);
1308       break;
1309     }
1310     rxinfo = (const struct GNUNET_TRANSPORT_WLAN_RadiotapReceiveMessage *) hdr;
1311
1312     /* check if message is actually for us */
1313     if (0 != memcmp (&rxinfo->frame.addr3, &mac_bssid_gnunet,
1314                      sizeof (struct GNUNET_TRANSPORT_WLAN_MacAddress)))
1315     {
1316       /* Not the GNUnet BSSID */
1317       break;
1318     }
1319     if ( (0 != memcmp (&rxinfo->frame.addr1, &bc_all_mac,
1320                        sizeof (struct GNUNET_TRANSPORT_WLAN_MacAddress))) &&
1321          (0 != memcmp (&rxinfo->frame.addr1, &plugin->mac_address,
1322                        sizeof (struct GNUNET_TRANSPORT_WLAN_MacAddress))) )
1323     {
1324       /* Neither broadcast nor specifically for us */
1325       break;
1326     }
1327     if (0 == memcmp (&rxinfo->frame.addr2, &plugin->mac_address,
1328                      sizeof (struct GNUNET_TRANSPORT_WLAN_MacAddress)))
1329     {
1330       /* packet is FROM us, thus not FOR us */
1331       break;
1332     }
1333     
1334     GNUNET_STATISTICS_update (plugin->env->stats,
1335                               _("# WLAN DATA messages processed"),
1336                               1, GNUNET_NO);
1337     LOG (GNUNET_ERROR_TYPE_DEBUG,
1338          "Receiving %u bytes of data from MAC `%s'\n",
1339          (unsigned int) (msize - sizeof (struct GNUNET_TRANSPORT_WLAN_RadiotapReceiveMessage)),
1340          mac_to_string (&rxinfo->frame.addr2));
1341     mas.endpoint = create_macendpoint (plugin, &rxinfo->frame.addr2);
1342     mas.session = NULL;
1343     (void) GNUNET_SERVER_mst_receive (plugin->helper_payload_tokenizer, 
1344                                       &mas,
1345                                       (const char*) &rxinfo[1],
1346                                       msize - sizeof (struct GNUNET_TRANSPORT_WLAN_RadiotapReceiveMessage),
1347                                       GNUNET_YES, GNUNET_NO);
1348     break;
1349   default:
1350     GNUNET_break (0);
1351     LOG (GNUNET_ERROR_TYPE_DEBUG, 
1352          "Unexpected message of type %u (%u bytes)",
1353          ntohs (hdr->type), ntohs (hdr->size));
1354     break;
1355   }
1356 }
1357
1358
1359
1360 /**
1361  * Task to (periodically) send a HELLO beacon
1362  *
1363  * @param cls pointer to the plugin struct
1364  * @param tc scheduler context
1365  */
1366 static void
1367 send_hello_beacon (void *cls,
1368                    const struct GNUNET_SCHEDULER_TaskContext *tc)
1369 {
1370   struct Plugin *plugin = cls;
1371   uint16_t size;
1372   uint16_t hello_size;
1373   struct GNUNET_TRANSPORT_WLAN_RadiotapSendMessage *radioHeader;
1374   const struct GNUNET_MessageHeader *hello;
1375
1376   hello = plugin->env->get_our_hello ();
1377   hello_size = GNUNET_HELLO_size ((struct GNUNET_HELLO_Message *) hello);
1378   GNUNET_assert (sizeof (struct WlanHeader) + hello_size <= WLAN_MTU);
1379   size = sizeof (struct GNUNET_TRANSPORT_WLAN_RadiotapSendMessage) + hello_size;
1380   {
1381     char buf[size] GNUNET_ALIGN;
1382
1383     LOG (GNUNET_ERROR_TYPE_DEBUG, 
1384          "Sending %u byte HELLO beacon\n",
1385          (unsigned int) size);
1386     radioHeader = (struct GNUNET_TRANSPORT_WLAN_RadiotapSendMessage*) buf;
1387     get_radiotap_header (NULL, radioHeader, size);
1388     get_wlan_header (plugin, &radioHeader->frame, &bc_all_mac, size);
1389     memcpy (&radioHeader[1], hello, hello_size);
1390     if (NULL !=
1391         GNUNET_HELPER_send (plugin->suid_helper,
1392                             &radioHeader->header,
1393                             GNUNET_YES /* can drop */,
1394                             NULL, NULL))
1395       GNUNET_STATISTICS_update (plugin->env->stats, _("# HELLO beacons sent via WLAN"),
1396                                 1, GNUNET_NO);
1397   }
1398   plugin->beacon_task =
1399     GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply
1400                                   (HELLO_BEACON_SCALING_FACTOR,
1401                                    plugin->mac_count + 1),
1402                                   &send_hello_beacon,
1403                                   plugin);
1404
1405 }
1406
1407
1408 /**
1409  * Another peer has suggested an address for this
1410  * peer and transport plugin.  Check that this could be a valid
1411  * address.  If so, consider adding it to the list
1412  * of addresses.
1413  *
1414  * @param cls closure
1415  * @param addr pointer to the address
1416  * @param addrlen length of addr
1417  * @return GNUNET_OK if this is a plausible address for this peer
1418  *         and transport
1419  */
1420 static int
1421 wlan_plugin_address_suggested (void *cls, const void *addr, size_t addrlen)
1422 {
1423   struct Plugin *plugin = cls;
1424
1425   if (addrlen != sizeof (struct GNUNET_TRANSPORT_WLAN_MacAddress))
1426   {    
1427     GNUNET_break_op (0);
1428     return GNUNET_SYSERR;
1429   }
1430   if (GNUNET_YES != plugin->have_mac)
1431   {
1432     LOG (GNUNET_ERROR_TYPE_DEBUG, 
1433          "Rejecting MAC `%s': I don't know my MAC!\n",
1434          mac_to_string (addr));
1435     return GNUNET_NO; /* don't know my MAC */
1436   }
1437   if (0 != memcmp (addr,
1438                    &plugin->mac_address,
1439                    addrlen))
1440   {
1441     LOG (GNUNET_ERROR_TYPE_DEBUG, 
1442          "Rejecting MAC `%s': not my MAC!\n",
1443          mac_to_string (addr));
1444     return GNUNET_NO; /* not my MAC */
1445   }
1446   return GNUNET_OK;
1447 }
1448
1449
1450 /**
1451  * Function called for a quick conversion of the binary address to
1452  * a numeric address.  Note that the caller must not free the
1453  * address and that the next call to this function is allowed
1454  * to override the address again.
1455  *
1456  * @param cls closure
1457  * @param addr binary address
1458  * @param addrlen length of the address
1459  * @return string representing the same address
1460  */
1461 static const char *
1462 wlan_plugin_address_to_string (void *cls, const void *addr, size_t addrlen)
1463 {
1464   static char ret[40];
1465   const struct GNUNET_TRANSPORT_WLAN_MacAddress *mac;
1466
1467   if (sizeof (struct GNUNET_TRANSPORT_WLAN_MacAddress) != addrlen)
1468   {
1469     GNUNET_break (0);
1470     return NULL;
1471   }
1472   mac = addr;
1473   GNUNET_snprintf (ret, sizeof (ret), "%s MAC address %s",
1474                    PROTOCOL_PREFIX, 
1475                    mac_to_string (mac));
1476   return ret;
1477 }
1478
1479
1480 /**
1481  * Convert the transports address to a nice, human-readable format.
1482  *
1483  * @param cls closure
1484  * @param type name of the transport that generated the address
1485  * @param addr one of the addresses of the host, NULL for the last address
1486  *        the specific address format depends on the transport
1487  * @param addrlen length of the address
1488  * @param numeric should (IP) addresses be displayed in numeric form?
1489  * @param timeout after how long should we give up?
1490  * @param asc function to call on each string
1491  * @param asc_cls closure for asc
1492  */
1493 static void
1494 wlan_plugin_address_pretty_printer (void *cls, const char *type,
1495                                     const void *addr, size_t addrlen,
1496                                     int numeric,
1497                                     struct GNUNET_TIME_Relative timeout,
1498                                     GNUNET_TRANSPORT_AddressStringCallback asc,
1499                                     void *asc_cls)
1500 {
1501   const struct GNUNET_TRANSPORT_WLAN_MacAddress *mac;
1502   char *ret;
1503
1504   if (sizeof (struct GNUNET_TRANSPORT_WLAN_MacAddress) != addrlen)
1505   {
1506     /* invalid address  */
1507     LOG (GNUNET_ERROR_TYPE_WARNING,
1508          _("WLAN address with invalid size encountered\n"));
1509     asc (asc_cls, NULL);
1510     return;
1511   }
1512   mac = addr;
1513   GNUNET_asprintf (&ret,
1514                    "%s MAC address %s",
1515                    PROTOCOL_PREFIX, 
1516                    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  * Entry point for the plugin.
1581  *
1582  * @param cls closure, the 'struct GNUNET_TRANSPORT_PluginEnvironment*'
1583  * @return the 'struct GNUNET_TRANSPORT_PluginFunctions*' or NULL on error
1584  */
1585 void *
1586 libgnunet_plugin_transport_wlan_init (void *cls)
1587 {
1588   struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
1589   struct GNUNET_TRANSPORT_PluginFunctions *api;
1590   struct Plugin *plugin;
1591   char *interface;
1592   unsigned long long testmode;
1593
1594   /* check for 'special' mode */
1595   if (NULL == env->receive)
1596   {
1597     /* run in 'stub' mode (i.e. as part of gnunet-peerinfo), don't fully
1598        initialze the plugin or the API */
1599     api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
1600     api->cls = NULL;
1601     api->address_pretty_printer = &wlan_plugin_address_pretty_printer;
1602     api->address_to_string = &wlan_plugin_address_to_string;
1603     api->string_to_address = NULL; // FIXME!
1604     return api;
1605   }
1606
1607   testmode = 0;
1608   /* check configuration */
1609   if ( (GNUNET_YES == 
1610         GNUNET_CONFIGURATION_have_value (env->cfg, "transport-wlan", "TESTMODE")) &&
1611        ( (GNUNET_SYSERR ==
1612           GNUNET_CONFIGURATION_get_value_number (env->cfg, "transport-wlan",
1613                                                  "TESTMODE", &testmode)) ||
1614          (testmode > 2) ) )
1615     {
1616     LOG (GNUNET_ERROR_TYPE_ERROR,
1617          _("Invalid configuration option `%s' in section `%s'\n"),
1618          "TESTMODE",
1619          "transport-wlan");
1620     return NULL;
1621   }
1622   if ( (0 == testmode) &&
1623        (GNUNET_YES != GNUNET_OS_check_helper_binary ("gnunet-helper-transport-wlan")) )
1624   {
1625     LOG (GNUNET_ERROR_TYPE_ERROR,
1626          _("Helper binary `%s' not SUID, cannot run WLAN transport\n"),
1627          "gnunet-helper-transport-wlan");
1628     return NULL;
1629   }
1630   if (GNUNET_YES !=
1631       GNUNET_CONFIGURATION_get_value_string
1632       (env->cfg, "transport-wlan", "INTERFACE",
1633        &interface))
1634   {
1635     LOG (GNUNET_ERROR_TYPE_ERROR,
1636          _("Missing configuration option `%s' in section `%s'\n"),
1637          "INTERFACE",
1638          "transport-wlan");
1639     return NULL;    
1640   }
1641
1642   plugin = GNUNET_malloc (sizeof (struct Plugin));
1643   plugin->interface = interface;
1644   plugin->env = env;
1645   GNUNET_STATISTICS_set (plugin->env->stats, _("# WLAN sessions allocated"),
1646                          0, GNUNET_NO);
1647   GNUNET_STATISTICS_set (plugin->env->stats, _("# WLAN MAC endpoints allocated"),
1648                          0, 0);
1649   GNUNET_BANDWIDTH_tracker_init (&plugin->tracker,
1650                                  GNUNET_BANDWIDTH_value_init (100 * 1024 *
1651                                                               1024 / 8), 100);
1652   plugin->fragment_data_tokenizer = GNUNET_SERVER_mst_create (&process_data, plugin);
1653   plugin->wlan_header_payload_tokenizer = GNUNET_SERVER_mst_create (&process_data, plugin);
1654   plugin->helper_payload_tokenizer = GNUNET_SERVER_mst_create (&process_data, plugin);
1655   plugin->beacon_task = GNUNET_SCHEDULER_add_now (&send_hello_beacon, 
1656                                                   plugin);
1657   switch (testmode)
1658   {
1659   case 0: /* normal */ 
1660     plugin->helper_argv[0] = (char *) "gnunet-helper-transport-wlan";
1661     plugin->helper_argv[1] = interface;
1662     plugin->helper_argv[2] = NULL;
1663     plugin->suid_helper = GNUNET_HELPER_start ("gnunet-helper-transport-wlan",
1664                                                plugin->helper_argv,
1665                                                &handle_helper_message,
1666                                                plugin);
1667     break;
1668   case 1: /* testmode, peer 1 */
1669     plugin->helper_argv[0] = (char *) "gnunet-helper-transport-wlan-dummy";
1670     plugin->helper_argv[1] = (char *) "1";
1671     plugin->helper_argv[2] = NULL;
1672     plugin->suid_helper = GNUNET_HELPER_start ("gnunet-helper-transport-wlan-dummy",
1673                                                plugin->helper_argv,
1674                                                &handle_helper_message,
1675                                                plugin);
1676     break;
1677   case 2: /* testmode, peer 2 */
1678     plugin->helper_argv[0] = (char *) "gnunet-helper-transport-wlan-dummy";
1679     plugin->helper_argv[1] = (char *) "2";
1680     plugin->helper_argv[2] = NULL;
1681     plugin->suid_helper = GNUNET_HELPER_start ("gnunet-helper-transport-wlan-dummy",
1682                                                plugin->helper_argv,
1683                                                &handle_helper_message,
1684                                                plugin);
1685     break;
1686   default:
1687     GNUNET_assert (0);
1688   }
1689
1690   api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
1691   api->cls = plugin;
1692   api->send = &wlan_plugin_send;
1693   api->get_session = &wlan_plugin_get_session;
1694   api->disconnect = &wlan_plugin_disconnect;
1695   api->address_pretty_printer = &wlan_plugin_address_pretty_printer;
1696   api->check_address = &wlan_plugin_address_suggested;
1697   api->address_to_string = &wlan_plugin_address_to_string;
1698   return api;
1699 }
1700
1701
1702 /* end of plugin_transport_wlan.c */