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