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