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