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