de735b97111a2af6c8b784fd81b434a553b5e43b
[oweals/gnunet.git] / src / transport / plugin_transport_wlan.c
1 /*
2  This file is part of GNUnet
3  (C) 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009 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  */
26
27 //TODO split rx and tx structures for better handling
28
29 #include "platform.h"
30 #include "gnunet_hello_lib.h"
31 #include "gnunet_protocols.h"
32 #include "gnunet_util_lib.h"
33 #include "gnunet_statistics_service.h"
34 #include "gnunet_transport_service.h"
35 #include "gnunet_transport_plugin.h"
36 #include "plugin_transport_wlan.h"
37 #include "gnunet_common.h"
38 #include "gnunet_crypto_lib.h"
39 #include "gnunet_fragmentation_lib.h"
40 #include "gnunet_constants.h"
41 //#include "wlan/ieee80211.h"
42 //#include  <netinet/ip.h>
43
44 #include <string.h>
45
46 #define PROTOCOL_PREFIX "wlan"
47
48 #define PLUGIN_LOG_NAME "wlan-plugin"
49
50 /**
51  * Max size of packet
52  */
53 #define WLAN_MTU 1430
54
55 /**
56  * time out of a session
57  */
58 #define SESSION_TIMEOUT GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT
59
60 /**
61  * time out of a mac endpoint
62  */
63 #define MACENDPOINT_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, 2)
64
65 /**
66  * scaling factor for hello beacon
67  */
68 #define HELLO_BEACON_SCALING_FACTOR 30
69
70 /**
71  * scaling factor for restarting the helper
72  */
73 #define HELPER_RESTART_SCALING_FACTOR 2
74
75 /**
76  * max size of fragment queue
77  */
78 #define FRAGMENT_QUEUE_SIZE 10
79 /**
80  * max messages in fragment queue per session/client
81  */
82 #define FRAGMENT_QUEUE_MESSAGES_OUT_PER_SESSION 1
83
84 /**
85  * max messages in fragment queue per MAC
86  */
87 #define FRAGMENT_QUEUE_MESSAGES_OUT_PER_MACENDPOINT 1
88
89 /**
90  * max messages in in queue
91  */
92 #define MESSAGES_IN_QUEUE_SIZE 10
93 /**
94  * max messages in in queue per session/client
95  */
96 #define MESSAGES_IN_DEFRAG_QUEUE_PER_MAC 1
97
98 /**
99  * LLC fields for better compatibility
100  */
101 #define WLAN_LLC_DSAP_FIELD 0x1f
102 #define WLAN_LLC_SSAP_FIELD 0x1f
103
104
105 /**
106  * DEBUG switch
107  */
108 #define DEBUG_wlan GNUNET_EXTRA_LOGGING
109 #define DEBUG_wlan_retransmission GNUNET_EXTRA_LOGGING
110 #define DEBUG_wlan_ip_udp_packets_on_air GNUNET_NO
111 #define DEBUG_wlan_msg_dump GNUNET_EXTRA_LOGGING
112
113
114 #define IEEE80211_ADDR_LEN      6       /* size of 802.11 address */
115
116 #define IEEE80211_FC0_VERSION_MASK              0x03
117 #define IEEE80211_FC0_VERSION_SHIFT             0
118 #define IEEE80211_FC0_VERSION_0                 0x00
119 #define IEEE80211_FC0_TYPE_MASK                 0x0c
120 #define IEEE80211_FC0_TYPE_SHIFT                2
121 #define IEEE80211_FC0_TYPE_MGT                  0x00
122 #define IEEE80211_FC0_TYPE_CTL                  0x04
123 #define IEEE80211_FC0_TYPE_DATA                 0x08
124
125 /*
126  * Structure of an internet header, naked of options.
127  */
128 struct iph
129 {
130 #if __BYTE_ORDER == __LITTLE_ENDIAN
131   unsigned int ip_hl:4;         /* header length */
132   unsigned int ip_v:4;          /* version */
133 #endif
134 #if __BYTE_ORDER == __BIG_ENDIAN
135   unsigned int ip_v:4;          /* version */
136   unsigned int ip_hl:4;         /* header length */
137 #endif
138   u_int8_t ip_tos;              /* type of service */
139   u_short ip_len;               /* total length */
140   u_short ip_id;                /* identification */
141   u_short ip_off;               /* fragment offset field */
142 #define IP_RF 0x8000            /* reserved fragment flag */
143 #define IP_DF 0x4000            /* dont fragment flag */
144 #define IP_MF 0x2000            /* more fragments flag */
145 #define IP_OFFMASK 0x1fff       /* mask for fragmenting bits */
146   u_int8_t ip_ttl;              /* time to live */
147   u_int8_t ip_p;                /* protocol */
148   u_short ip_sum;               /* checksum */
149   struct in_addr ip_src, ip_dst;        /* source and dest address */
150 };
151
152 struct udphdr
153 {
154   u_int16_t source;
155   u_int16_t dest;
156   u_int16_t len;
157   u_int16_t check;
158 };
159
160 /*
161  * generic definitions for IEEE 802.11 frames
162  */
163 struct ieee80211_frame
164 {
165   u_int8_t i_fc[2];
166   u_int8_t i_dur[2];
167   u_int8_t i_addr1[IEEE80211_ADDR_LEN];
168   u_int8_t i_addr2[IEEE80211_ADDR_LEN];
169   u_int8_t i_addr3[IEEE80211_ADDR_LEN];
170   u_int8_t i_seq[2];
171   u_int8_t llc[4];
172 #if DEBUG_wlan_ip_udp_packets_on_air > 1
173   struct iph ip;
174   struct udphdr udp;
175 #endif
176 } GNUNET_PACKED;
177
178 /**
179  * Encapsulation of all of the state of the plugin.
180  */
181 struct Plugin
182 {
183   /**
184    * Our environment.
185    */
186   struct GNUNET_TRANSPORT_PluginEnvironment *env;
187
188   /**
189    * List of open connections. head
190    */
191   struct MacEndpoint *mac_head;
192
193   /**
194    * List of open connections. tail
195    */
196   struct MacEndpoint *mac_tail;
197
198   /**
199    * Number of connections
200    */
201   unsigned int mac_count;
202
203   /**
204    * encapsulation of data from the local wlan helper program
205    */
206   struct GNUNET_SERVER_MessageStreamTokenizer *suid_tokenizer;
207
208   /**
209    * encapsulation of packets received from the wlan helper
210    */
211   struct GNUNET_SERVER_MessageStreamTokenizer *data_tokenizer;
212
213   /**
214    * stdout pipe handle for the gnunet-wlan-helper process
215    */
216   struct GNUNET_DISK_PipeHandle *server_stdout;
217
218   /**
219    * stdout file handle for the gnunet-wlan-helper process
220    */
221   const struct GNUNET_DISK_FileHandle *server_stdout_handle;
222
223   /**
224    * stdin pipe handle for the gnunet-wlan-helper process
225    */
226   struct GNUNET_DISK_PipeHandle *server_stdin;
227
228   /**
229    * stdin file handle for the gnunet-wlan-helper process
230    */
231   const struct GNUNET_DISK_FileHandle *server_stdin_handle;
232
233   /**
234    * ID of the gnunet-wlan-server std read task
235    */
236   GNUNET_SCHEDULER_TaskIdentifier server_read_task;
237
238   /**
239    * ID of the gnunet-wlan-server std read task
240    */
241   GNUNET_SCHEDULER_TaskIdentifier server_write_task;
242
243   /**
244    * ID of the delay task for writing
245    */
246   GNUNET_SCHEDULER_TaskIdentifier server_write_delay_task;
247
248   /**
249    * The process id of the wlan process
250    */
251   struct GNUNET_OS_Process *server_proc;
252
253   /**
254    * The interface of the wlan card given to us by the user.
255    */
256   char *interface;
257
258   /**
259    * Mode of operation for the helper, 0 = normal, 1 = first loopback, 2 = second loopback
260    */
261   long long unsigned int testmode;
262
263   /**
264    * The mac_address of the wlan card given to us by the helper.
265    */
266   struct MacAddress mac_address;
267
268   /**
269    * Sessions currently pending for transmission
270    * to a peer, if any.
271    */
272   struct Sessionqueue *pending_Sessions_head;
273
274   /**
275    * Sessions currently pending for transmission
276    * to a peer (tail), if any.
277    */
278   struct Sessionqueue *pending_Sessions_tail;
279
280   /**
281    * number of pending sessions
282    */
283   unsigned int pendingsessions;
284
285   /**
286    * Messages in the sending queues
287    */
288   int pending_Fragment_Messages;
289
290   /**
291    * messages ready for send, head
292    */
293   struct FragmentMessage_queue *sending_messages_head;
294   /**
295    * messages ready for send, tail
296    */
297   struct FragmentMessage_queue *sending_messages_tail;
298   /**
299    * time of the next "hello-beacon"
300    */
301   struct GNUNET_TIME_Absolute beacon_time;
302
303   /**
304    * queue to send acks for received fragments (head)
305    */
306   struct AckSendQueue *ack_send_queue_head;
307
308   /**
309    * queue to send acks for received fragments (tail)
310    */
311   struct AckSendQueue *ack_send_queue_tail;
312
313   /**
314    * Tracker for bandwidth limit
315    */
316   struct GNUNET_BANDWIDTH_Tracker tracker;
317 };
318
319 /**
320  * Struct to store data if file write did not accept the whole packet
321  */
322 struct Finish_send
323 {
324   /**
325    * pointer to the global plugin struct
326    */
327   struct Plugin *plugin;
328
329   /**
330    * head of the next part to send to the helper
331    */
332   char *head_of_next_write;
333
334   /**
335    * Start of the message to send, needed for free
336    */
337   struct GNUNET_MessageHeader *msgstart;
338
339   /**
340    * rest size to send
341    */
342   ssize_t size;
343 };
344
345 /**
346  * Queue of sessions, for the general session queue and the pending session queue
347  */
348 //TODO DOXIGEN
349 struct Sessionqueue
350 {
351   struct Sessionqueue *next;
352   struct Sessionqueue *prev;
353   struct Session *content;
354 };
355
356 /**
357  * Queue of fragmented messages, for the sending queue of the plugin
358  */
359 //TODO DOXIGEN
360 struct FragmentMessage_queue
361 {
362   struct FragmentMessage_queue *next;
363   struct FragmentMessage_queue *prev;
364   struct FragmentMessage *content;
365 };
366
367 /**
368  * Queue for the fragments received
369  */
370 //TODO DOXIGEN
371 struct Receive_Fragment_Queue
372 {
373   struct Receive_Fragment_Queue *next;
374   struct Receive_Fragment_Queue *prev;
375   uint16_t num;
376   const char *msg;
377   uint16_t size;
378   struct Radiotap_rx rxinfo;
379 };
380
381 //TODO DOXIGEN
382 struct MacEndpoint_id_fragment_triple
383 {
384   struct MacEndpoint *endpoint;
385   uint32_t message_id;
386   struct FragmentMessage *fm;
387 };
388
389 //TODO DOXIGEN
390 struct Plugin_Session_pair
391 {
392   struct Plugin *plugin;
393   struct Session *session;
394 };
395
396 /**
397  * Information kept for each message that is yet to
398  * be transmitted.
399  */
400 struct PendingMessage
401 {
402   /**
403    * dll next
404    */
405   struct PendingMessage *next;
406   /**
407    * dll prev
408    */
409   struct PendingMessage *prev;
410
411   /**
412    * The pending message
413    */
414   struct WlanHeader *msg;
415
416   /**
417    * Size of the message
418    */
419   size_t message_size;
420
421   /**
422    * Continuation function to call once the message
423    * has been sent.  Can be NULL if there is no
424    * continuation to call.
425    */
426   GNUNET_TRANSPORT_TransmitContinuation transmit_cont;
427
428   /**
429    * Cls for transmit_cont
430    */
431   void *transmit_cont_cls;
432
433   /**
434    * Timeout value for the pending message.
435    */
436   struct GNUNET_TIME_Absolute timeout;
437
438 };
439
440 /**
441  * Queue for acks to send for fragments recived
442  */
443 struct AckSendQueue
444 {
445
446   /**
447    * next ack in the ack send queue
448    */
449   struct AckSendQueue *next;
450   /**
451    * previous ack in the ack send queue
452    */
453   struct AckSendQueue *prev;
454   /**
455    * pointer to the session this ack belongs to
456    */
457   struct MacEndpoint *endpoint;
458   /**
459    * ID of message, to distinguish between the messages, picked randomly.
460    */
461   uint32_t message_id;
462
463   /**
464    * msg to send
465    */
466   struct GNUNET_MessageHeader *hdr;
467   /**
468    * pointer to the ieee wlan header
469    */
470   struct ieee80211_frame *ieeewlanheader;
471   /**
472    * pointer to the radiotap header
473    */
474   struct Radiotap_Send *radioHeader;
475 };
476
477 /**
478  * Session infos gathered from a messages
479  */
480
481 struct Session_light
482 {
483   /**
484    * the session this message belongs to
485    */
486   struct Session *session;
487   /**
488    * peer mac address
489    */
490   struct MacAddress addr;
491
492   /**
493    * mac endpoint
494    */
495   struct MacEndpoint *macendpoint;
496 };
497
498 /**
499  * Session handle for connections.
500  */
501 struct Session
502 {
503
504   /**
505    * API requirement.
506    */
507   struct SessionHeader header;
508
509   /**
510    * Message currently pending for transmission
511    * to this peer, if any. head
512    */
513   struct PendingMessage *pending_message_head;
514
515   /**
516    * Message currently pending for transmission
517    * to this peer, if any. tail
518    */
519   struct PendingMessage *pending_message_tail;
520
521   /**
522    * To whom are we talking to (set to our identity
523    * if we are still waiting for the welcome message)
524    */
525   struct GNUNET_PeerIdentity target;
526
527   /**
528    * Address of the other peer (either based on our 'connect'
529    * call or on our 'accept' call).
530    */
531   void *connect_addr;
532
533   /**
534    * Last activity on this connection.  Used to select preferred
535    * connection and timeout
536    */
537   struct GNUNET_TIME_Absolute last_activity;
538
539   /**
540    * Timeout task.
541    */
542   GNUNET_SCHEDULER_TaskIdentifier timeout_task;
543
544   /**
545    * peer connection
546    */
547   struct MacEndpoint *mac;
548
549   /**
550    * count of messages in the fragment out queue for this session
551    */
552
553   int fragment_messages_out_count;
554
555 };
556
557 /**
558  * Struct to represent one network card connection
559  */
560 struct MacEndpoint
561 {
562   /**
563    * Pointer to the global plugin struct.
564    */
565   struct Plugin *plugin;
566   /**
567    * Struct to hold the session reachable over this mac; head
568    */
569   struct Sessionqueue *sessions_head;
570   /**
571    * Struct to hold the session reachable over this mac; tail
572    */
573   struct Sessionqueue *sessions_tail;
574   /**
575    * Messages currently sending
576    * to a peer, if any.
577    */
578   struct FragmentMessage *sending_messages_head;
579
580   /**
581    * Messages currently sending
582    * to a peer (tail), if any.
583    */
584   struct FragmentMessage *sending_messages_tail;
585   /**
586    * dll next
587    */
588   struct MacEndpoint *next;
589   /**
590    * dll prev
591    */
592   struct MacEndpoint *prev;
593
594   /**
595    * peer mac address
596    */
597   struct MacAddress addr;
598
599   /**
600    * Defrag context for this mac endpoint
601    */
602   struct GNUNET_DEFRAGMENT_Context *defrag;
603
604   /**
605    * count of messages in the fragment out queue for this mac endpoint
606    */
607
608   int fragment_messages_out_count;
609
610   //TODO DOXIGEN
611   uint8_t rate;
612   uint16_t tx_power;
613   uint8_t antenna;
614
615   /**
616    * Duplicates received
617    */
618   int dups;
619
620   /**
621    * Fragments received
622    */
623   int fragc;
624
625   /**
626    * Acks received
627    */
628   int acks;
629
630   /**
631    * Last activity on this endpoint.  Used to select preferred
632    * connection.
633    */
634   struct GNUNET_TIME_Absolute last_activity;
635
636   /**
637    * Timeout task.
638    */
639   GNUNET_SCHEDULER_TaskIdentifier timeout_task;
640 };
641
642 /**
643  * Struct for Messages in the fragment queue
644  */
645
646 struct FragmentMessage
647 {
648
649   /**
650    * Session this message belongs to
651    */
652
653   struct Session *session;
654
655   /**
656    * This is a doubly-linked list.
657    */
658   struct FragmentMessage *next;
659
660   /**
661    * This is a doubly-linked list.
662    */
663   struct FragmentMessage *prev;
664
665   /**
666    * Fragmentation context
667    */
668   struct GNUNET_FRAGMENT_Context *fragcontext;
669
670   /**
671    * Timeout value for the message.
672    */
673   struct GNUNET_TIME_Absolute timeout;
674
675   /**
676    * Timeout task.
677    */
678   GNUNET_SCHEDULER_TaskIdentifier timeout_task;
679
680   /**
681    * Fragment to send
682    */
683   char *frag;
684
685   /**
686    * size of message
687    */
688   size_t size;
689
690   /**
691    * pointer to the ieee wlan header
692    */
693   struct ieee80211_frame *ieeewlanheader;
694   /**
695    * pointer to the radiotap header
696    */
697   struct Radiotap_Send *radioHeader;
698 };
699
700 static void
701 do_transmit (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
702 static void
703 free_session (struct Plugin *plugin, struct Sessionqueue *queue,
704               int do_free_macendpoint);
705 static struct MacEndpoint *
706 create_macendpoint (struct Plugin *plugin, const struct MacAddress *addr);
707
708 static void
709 finish_sending (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
710
711 /**
712  * Generates a nice hexdump of a memory area.
713  *
714  * \param  mem     pointer to memory to dump
715  * \param  length  how many bytes to dump
716  */
717 static void
718 hexdump (const void *mem, unsigned length)
719 {
720   char line[80];
721   char *src = (char *) mem;
722
723   printf ("dumping %u bytes from %p\r\n"
724           "       0  1  2  3  4  5  6  7  8  9  A  B  C  D  E  F    0123456789ABCDEF\r\n",
725           length, src);
726   unsigned i;
727   int j;
728
729   for (i = 0; i < length; i += 16, src += 16)
730   {
731     char *t = line;
732
733     t += sprintf (t, "%04x:  ", i);
734     for (j = 0; j < 16; j++)
735     {
736       if (i + j < length)
737         t += sprintf (t, "%02X", src[j] & 0xff);
738       else
739         t += sprintf (t, "  ");
740       t += sprintf (t, j % 2 ? " " : "-");
741     }
742
743     t += sprintf (t, "  ");
744     for (j = 0; j < 16; j++)
745     {
746       if (i + j < length)
747       {
748         if (isprint ((unsigned char) src[j]))
749           t += sprintf (t, "%c", src[j]);
750         else
751           t += sprintf (t, ".");
752       }
753       else
754       {
755         t += sprintf (t, " ");
756       }
757     }
758
759     t += sprintf (t, "\r\n");
760     printf ("%s", line);
761   }
762 }
763
764 /**
765  * Function to find a MacEndpoint with a specific mac addr
766  * @param plugin pointer to the plugin struct
767  * @param addr pointer to the mac address
768  * @param create_new GNUNET_YES if a new end point should be created
769  * @return
770  */
771 static struct MacEndpoint *
772 get_macendpoint (struct Plugin *plugin, const struct MacAddress *addr,
773                  int create_new)
774 {
775   struct MacEndpoint *queue = plugin->mac_head;
776
777   while (queue != NULL)
778   {
779     //GNUNET_assert (queue->sessions_head != NULL);
780     if (memcmp (addr, &queue->addr, sizeof (struct MacAddress)) == 0)
781       return queue;             /* session found */
782     queue = queue->next;
783   }
784
785   if (create_new == GNUNET_YES)
786   {
787     return create_macendpoint (plugin, addr);
788   }
789   else
790   {
791     return NULL;
792   }
793
794 }
795
796 /**
797  * search for a session with the macendpoint and peer id
798  *
799  * @param plugin pointer to the plugin struct
800  * @param endpoint pointer to the mac endpoint of the peer
801  * @param peer pointer to the peerid
802  * @return returns the session
803  */
804 static struct Session *
805 search_session (struct Plugin *plugin, const struct MacEndpoint *endpoint,
806                 const struct GNUNET_PeerIdentity *peer)
807 {
808   GNUNET_assert (endpoint != NULL);
809   struct Sessionqueue *queue = endpoint->sessions_head;
810
811   while (queue != NULL)
812   {
813     GNUNET_assert (queue->content != NULL);
814     if (memcmp
815         (peer, &queue->content->target,
816          sizeof (struct GNUNET_PeerIdentity)) == 0)
817       return queue->content;    /* session found */
818     queue = queue->next;
819   }
820   return NULL;
821 }
822
823 /**
824  * Function called for a quick conversion of the binary address to
825  * a numeric address.  Note that the caller must not free the
826  * address and that the next call to this function is allowed
827  * to override the address again.
828  *
829  * @param cls closure
830  * @param addr binary address
831  * @param addrlen length of the address
832  * @return string representing the same address
833  */
834 static const char *
835 wlan_plugin_address_to_string (void *cls, const void *addr, size_t addrlen)
836 {
837   static char ret[40];
838   const struct MacAddress *mac;
839
840   if (addrlen != sizeof (struct MacAddress))
841   {
842     GNUNET_break (0);
843     return NULL;
844   }
845   mac = addr;
846   GNUNET_snprintf (ret, sizeof (ret), "%s Mac-Address %X:%X:%X:%X:%X:%X",
847                    PROTOCOL_PREFIX, mac->mac[0], mac->mac[1], mac->mac[2],
848                    mac->mac[3], mac->mac[4], mac->mac[5]);
849
850   return ret;
851 }
852
853 /**
854  * Function for the scheduler if a session times out
855  * @param cls pointer to the Sessionqueue
856  * @param tc pointer to the GNUNET_SCHEDULER_TaskContext
857  */
858 static void
859 session_timeout (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
860 {
861   struct Sessionqueue *queue = cls;
862
863   GNUNET_assert (queue != NULL);
864   GNUNET_assert(queue->content != NULL);
865   queue->content->timeout_task = GNUNET_SCHEDULER_NO_TASK;
866   if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
867   {
868     return;
869   }
870   if (GNUNET_TIME_absolute_get_remaining
871       (GNUNET_TIME_absolute_add
872        (queue->content->last_activity, SESSION_TIMEOUT)).rel_value == 0)
873   {
874
875     GNUNET_assert(queue->content->mac != NULL);
876     GNUNET_assert(queue->content->mac->plugin != NULL);
877     GNUNET_STATISTICS_update (queue->content->mac->plugin->env->stats, _("# wlan session timeouts"), 1, GNUNET_NO);
878     free_session (queue->content->mac->plugin, queue, GNUNET_YES);
879   }
880   else
881   {
882     queue->content->timeout_task =
883         GNUNET_SCHEDULER_add_delayed (SESSION_TIMEOUT, &session_timeout, queue);
884   }
885 }
886
887 /**
888  * create a new session
889  *
890  * @param plugin pointer to the plugin struct
891  * @param endpoint pointer to the mac endpoint of the peer
892  * @param peer peer identity to use for this session
893  * @return returns the session
894  */
895
896 static struct Session *
897 create_session (struct Plugin *plugin, struct MacEndpoint *endpoint,
898                 const struct GNUNET_PeerIdentity *peer)
899 {
900   GNUNET_assert (endpoint != NULL);
901   GNUNET_assert (plugin != NULL);
902   GNUNET_STATISTICS_update (plugin->env->stats, _("# wlan session created"), 1, GNUNET_NO);
903   struct Sessionqueue *queue =
904       GNUNET_malloc (sizeof (struct Sessionqueue) + sizeof (struct Session));
905
906   GNUNET_CONTAINER_DLL_insert_tail (endpoint->sessions_head,
907                                     endpoint->sessions_tail, queue);
908
909   queue->content = (struct Session *) &queue[1];
910   queue->content->mac = endpoint;
911   memcpy (&(queue->content->target), peer, sizeof (struct GNUNET_PeerIdentity));
912   queue->content->last_activity = GNUNET_TIME_absolute_get ();
913   queue->content->timeout_task =
914       GNUNET_SCHEDULER_add_delayed (SESSION_TIMEOUT, &session_timeout, queue);
915
916 #if DEBUG_wlan
917   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
918                    "New session %p with endpoint %p: %s\n", queue->content,
919                    endpoint, wlan_plugin_address_to_string (NULL,
920                                                             endpoint->addr.mac,
921                                                             6));
922 #endif
923
924   return queue->content;
925 }
926
927 /**
928  * Get session from address, create if no session exists
929  *
930  * @param plugin pointer to the plugin struct
931  * @param addr pointer to the mac address of the peer
932  * @param peer pointer to the peerid
933  * @return returns the session
934  */
935 static struct Session *
936 get_session (struct Plugin *plugin, const struct MacAddress *addr,
937              const struct GNUNET_PeerIdentity *peer)
938 {
939   struct MacEndpoint *mac;
940
941   mac = get_macendpoint (plugin, addr, GNUNET_YES);
942   struct Session *session = search_session (plugin, mac, peer);
943
944   if (session != NULL)
945     return session;
946   return create_session (plugin, mac, peer);
947 }
948
949 /**
950  * Queue the session to send data
951  * checks if there is a message pending
952  * checks if this session is not allready in the queue
953  * @param plugin pointer to the plugin
954  * @param session pointer to the session to add
955  */
956 static void
957 queue_session (struct Plugin *plugin, struct Session *session)
958 {
959   struct Sessionqueue *queue = plugin->pending_Sessions_head;
960
961   if (session->pending_message_head != NULL)
962   {
963     while (queue != NULL)
964     {
965       // content is never NULL
966       GNUNET_assert (queue->content != NULL);
967       // is session already in queue?
968       if (session == queue->content)
969       {
970         return;
971       }
972       // try next
973       queue = queue->next;
974     }
975
976     // Session is not in the queue
977
978     queue = GNUNET_malloc (sizeof (struct Sessionqueue));
979     queue->content = session;
980
981     //insert at the tail
982     GNUNET_CONTAINER_DLL_insert_tail (plugin->pending_Sessions_head,
983                                       plugin->pending_Sessions_tail, queue);
984     plugin->pendingsessions++;
985     GNUNET_STATISTICS_set(plugin->env->stats, _("# wlan pending sessions"), plugin->pendingsessions, GNUNET_NO);
986   }
987
988 }
989
990 /**
991  * Function to schedule the write task, executed after a delay
992  * @param cls pointer to the plugin struct
993  * @param tc GNUNET_SCHEDULER_TaskContext pointer
994  */
995 static void
996 delay_fragment_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
997 {
998   struct Plugin *plugin = cls;
999
1000   plugin->server_write_delay_task = GNUNET_SCHEDULER_NO_TASK;
1001
1002   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1003     return;
1004
1005   // GNUNET_TIME_UNIT_FOREVER_REL is needed to clean up old msg
1006   if (plugin->server_write_task == GNUNET_SCHEDULER_NO_TASK)
1007   {
1008     plugin->server_write_task =
1009         GNUNET_SCHEDULER_add_write_file (GNUNET_TIME_UNIT_FOREVER_REL,
1010                                          plugin->server_stdin_handle,
1011                                          &do_transmit, plugin);
1012   }
1013 }
1014
1015 /**
1016  * Function to calculate the time of the next periodic "hello-beacon"
1017  * @param plugin pointer to the plugin struct
1018  */
1019
1020 static void
1021 set_next_beacon_time (struct Plugin *const plugin)
1022 {
1023   //under 10 known peers: once a second
1024   if (plugin->mac_count < 10)
1025   {
1026     plugin->beacon_time =
1027         GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get (),
1028                                   GNUNET_TIME_relative_multiply
1029                                   (GNUNET_TIME_UNIT_SECONDS,
1030                                    HELLO_BEACON_SCALING_FACTOR));
1031   }
1032   //under 30 known peers: every 10 seconds
1033   else if (plugin->mac_count < 30)
1034   {
1035     plugin->beacon_time =
1036         GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get (),
1037                                   GNUNET_TIME_relative_multiply
1038                                   (GNUNET_TIME_UNIT_SECONDS,
1039                                    10 * HELLO_BEACON_SCALING_FACTOR));
1040   }
1041   //over 30 known peers: once a minute
1042   else
1043   {
1044     plugin->beacon_time =
1045         GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get (),
1046                                   GNUNET_TIME_relative_multiply
1047                                   (GNUNET_TIME_UNIT_MINUTES,
1048                                    HELLO_BEACON_SCALING_FACTOR));
1049   }
1050 }
1051
1052 /**
1053  * Function to set the timer for the next timeout of the fragment queue
1054  * @param plugin the handle to the plugin struct
1055  */
1056
1057 static void
1058 set_next_send (struct Plugin *const plugin)
1059 {
1060   struct GNUNET_TIME_Relative next_send;
1061
1062   //cancel old task
1063   if (plugin->server_write_delay_task != GNUNET_SCHEDULER_NO_TASK)
1064   {
1065     GNUNET_SCHEDULER_cancel (plugin->server_write_delay_task);
1066     plugin->server_write_delay_task = GNUNET_SCHEDULER_NO_TASK;
1067   }
1068
1069   //check if some acks are in the queue
1070   if (plugin->ack_send_queue_head != NULL)
1071   {
1072     next_send = GNUNET_TIME_UNIT_ZERO;
1073   }
1074
1075   //check if there are some fragments in the queue
1076   else if (plugin->sending_messages_head != NULL)
1077   {
1078     next_send = GNUNET_TIME_UNIT_ZERO;
1079   }
1080   else
1081   {
1082     next_send = GNUNET_TIME_absolute_get_remaining (plugin->beacon_time);
1083   }
1084
1085 #if DEBUG_wlan
1086   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
1087                    "Next packet is send in: %u\n", next_send.rel_value);
1088 #endif
1089
1090   if (next_send.rel_value == GNUNET_TIME_UNIT_ZERO.rel_value)
1091   {
1092     if (plugin->server_write_task == GNUNET_SCHEDULER_NO_TASK)
1093     {
1094       plugin->server_write_task =
1095           GNUNET_SCHEDULER_add_write_file (GNUNET_TIME_UNIT_FOREVER_REL,
1096                                            plugin->server_stdin_handle,
1097                                            &do_transmit, plugin);
1098     }
1099   }
1100   else
1101   {
1102     if (plugin->server_write_delay_task == GNUNET_SCHEDULER_NO_TASK)
1103     {
1104       plugin->server_write_delay_task =
1105           GNUNET_SCHEDULER_add_delayed (next_send, &delay_fragment_task,
1106                                         plugin);
1107     }
1108   }
1109 }
1110
1111 /**
1112  * Function to get the next queued Session, removes the session from the queue
1113  * @param plugin pointer to the plugin struct
1114  * @return pointer to the session found, returns NULL if there is now session in the queue
1115  */
1116 static struct Session *
1117 get_next_queue_session (struct Plugin *plugin)
1118 {
1119   struct Session *session;
1120   struct Sessionqueue *sessionqueue;
1121   struct Sessionqueue *sessionqueue_alt;
1122   struct PendingMessage *pm;
1123
1124   sessionqueue = plugin->pending_Sessions_head;
1125
1126   while (sessionqueue != NULL)
1127   {
1128     session = sessionqueue->content;
1129
1130     GNUNET_assert (session != NULL);
1131     pm = session->pending_message_head;
1132
1133     if (pm == NULL)
1134         {
1135 #if DEBUG_wlan
1136           GNUNET_log_from(GNUNET_ERROR_TYPE_ERROR, PLUGIN_LOG_NAME,
1137               "pending message is empty, should not happen. session %p\n",
1138               session);
1139 #endif
1140           sessionqueue_alt = sessionqueue;
1141           sessionqueue = sessionqueue->next;
1142           plugin->pendingsessions--;
1143           GNUNET_STATISTICS_set(plugin->env->stats, _("# wlan pending sessions"), plugin->pendingsessions, GNUNET_NO);
1144           GNUNET_CONTAINER_DLL_remove (plugin->pending_Sessions_head,
1145               plugin->pending_Sessions_tail,
1146               sessionqueue_alt);
1147
1148           GNUNET_free (sessionqueue_alt);
1149           continue;
1150
1151         }
1152
1153     //check for message timeout
1154     if (GNUNET_TIME_absolute_get_remaining (pm->timeout).rel_value > 0)
1155     {
1156       //check if session has no message in the fragment queue
1157       if ((session->mac->fragment_messages_out_count <
1158            FRAGMENT_QUEUE_MESSAGES_OUT_PER_MACENDPOINT) &&
1159           (session->fragment_messages_out_count <
1160            FRAGMENT_QUEUE_MESSAGES_OUT_PER_SESSION))
1161       {
1162         plugin->pendingsessions--;
1163         GNUNET_STATISTICS_set(plugin->env->stats, _("# wlan pending sessions"), plugin->pendingsessions, GNUNET_NO);
1164         GNUNET_CONTAINER_DLL_remove (plugin->pending_Sessions_head,
1165                                      plugin->pending_Sessions_tail,
1166                                      sessionqueue);
1167         GNUNET_free (sessionqueue);
1168
1169         return session;
1170       }
1171       else
1172       {
1173         sessionqueue = sessionqueue->next;
1174       }
1175     }
1176     else
1177     {
1178       GNUNET_CONTAINER_DLL_remove (session->pending_message_head,
1179                                    session->pending_message_tail, pm);
1180
1181       //call the cont func that it did not work
1182       if (pm->transmit_cont != NULL)
1183         pm->transmit_cont (pm->transmit_cont_cls, &(session->target),
1184                            GNUNET_SYSERR);
1185       GNUNET_free (pm->msg);
1186       GNUNET_free (pm);
1187
1188       if (session->pending_message_head == NULL)
1189       {
1190         sessionqueue_alt = sessionqueue;
1191         sessionqueue = sessionqueue->next;
1192         plugin->pendingsessions--;
1193         GNUNET_STATISTICS_set(plugin->env->stats, _("# wlan pending sessions"), plugin->pendingsessions, GNUNET_NO);
1194         GNUNET_CONTAINER_DLL_remove (plugin->pending_Sessions_head,
1195                                      plugin->pending_Sessions_tail,
1196                                      sessionqueue_alt);
1197
1198         GNUNET_free (sessionqueue_alt);
1199       }
1200     }
1201
1202   }
1203   return NULL;
1204 }
1205
1206 /**
1207  * frees the space of a message in the fragment queue (send queue)
1208  * @param plugin the plugin struct
1209  * @param fm message to free
1210  */
1211 static void
1212 free_fragment_message (struct Plugin *plugin, struct FragmentMessage *fm)
1213 {
1214   struct Session *session = fm->session;
1215   struct MacEndpoint *endpoint = session->mac;
1216   struct FragmentMessage_queue *fmq;
1217   struct FragmentMessage_queue *fmq_next;
1218
1219   if (fm != NULL)
1220   {
1221     fmq = plugin->sending_messages_head;
1222     while (fmq != NULL)
1223     {
1224       fmq_next = fmq->next;
1225       if (fmq->content == fm)
1226       {
1227         GNUNET_CONTAINER_DLL_remove (plugin->sending_messages_head,
1228                                      plugin->sending_messages_tail, fmq);
1229         GNUNET_free (fmq);
1230       }
1231       fmq = fmq_next;
1232     }
1233
1234     (session->mac->fragment_messages_out_count)--;
1235     session->fragment_messages_out_count--;
1236     plugin->pending_Fragment_Messages--;
1237     GNUNET_CONTAINER_DLL_remove (endpoint->sending_messages_head,
1238                                  endpoint->sending_messages_tail, fm);
1239     GNUNET_FRAGMENT_context_destroy (fm->fragcontext);
1240     if (fm->timeout_task != GNUNET_SCHEDULER_NO_TASK){
1241         GNUNET_SCHEDULER_cancel (fm->timeout_task);
1242         fm->timeout_task = GNUNET_SCHEDULER_NO_TASK;
1243     }
1244
1245     GNUNET_free (fm);
1246
1247     queue_session (plugin, session);
1248 #if DEBUG_wlan
1249     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
1250                      "Free pending fragment messages %p, session %p\n", fm,
1251                      session);
1252 #endif
1253   }
1254 }
1255
1256 /**
1257  * function to fill the radiotap header
1258  * @param plugin pointer to the plugin struct
1259  * @param endpoint pointer to the endpoint
1260  * @param header pointer to the radiotap header
1261  * @return GNUNET_YES at success
1262  */
1263 static int
1264 getRadiotapHeader (struct Plugin *plugin, struct MacEndpoint *endpoint,
1265                    struct Radiotap_Send *header)
1266 {
1267
1268   if (endpoint != NULL)
1269   {
1270     header->rate = endpoint->rate;
1271     header->tx_power = endpoint->tx_power;
1272     header->antenna = endpoint->antenna;
1273   }
1274   else
1275   {
1276     header->rate = 255;
1277     header->tx_power = 0;
1278     header->antenna = 0;
1279   }
1280
1281   return GNUNET_YES;
1282 }
1283
1284 /**
1285  * function to generate the wlan hardware header for one packet
1286  * @param Header address to write the header to
1287  * @param to_mac_addr address of the recipient
1288  * @param plugin pointer to the plugin struct
1289  * @param size size of the whole packet, needed to calculate the time to send the packet
1290  * @return GNUNET_YES if there was no error
1291  */
1292 static int
1293 getWlanHeader (struct ieee80211_frame *Header,
1294                const struct MacAddress *to_mac_addr, struct Plugin *plugin,
1295                unsigned int size)
1296 {
1297   uint16_t *tmp16;
1298   const int rate = 11000000;
1299
1300   Header->i_fc[0] = IEEE80211_FC0_TYPE_DATA;
1301   Header->i_fc[1] = 0x00;
1302   memcpy (&Header->i_addr3, &mac_bssid, sizeof (mac_bssid));
1303   memcpy (&Header->i_addr2, plugin->mac_address.mac,
1304           sizeof (plugin->mac_address));
1305   memcpy (&Header->i_addr1, to_mac_addr, sizeof (struct MacAddress));
1306
1307   tmp16 = (uint16_t *) Header->i_dur;
1308   *tmp16 = (uint16_t) htole16 ((size * 1000000) / rate + 290);
1309   Header->llc[0] = WLAN_LLC_DSAP_FIELD;
1310   Header->llc[1] = WLAN_LLC_SSAP_FIELD;
1311
1312 #if DEBUG_wlan_ip_udp_packets_on_air > 1
1313   uint crc = 0;
1314   uint16_t *x;
1315   int count;
1316
1317   Header->ip.ip_dst.s_addr = *((uint32_t *) & to_mac_addr->mac[2]);
1318   Header->ip.ip_src.s_addr = *((uint32_t *) & plugin->mac_address.mac[2]);
1319   Header->ip.ip_v = 4;
1320   Header->ip.ip_hl = 5;
1321   Header->ip.ip_p = 17;
1322   Header->ip.ip_ttl = 1;
1323   Header->ip.ip_len = htons (size + 8);
1324   Header->ip.ip_sum = 0;
1325   x = (uint16_t *) & Header->ip;
1326   count = sizeof (struct iph);
1327   while (count > 1)
1328   {
1329     /* This is the inner loop */
1330     crc += (unsigned short) *x++;
1331     count -= 2;
1332   }
1333   /* Add left-over byte, if any */
1334   if (count > 0)
1335     crc += *(unsigned char *) x;
1336   crc = (crc & 0xffff) + (crc >> 16);
1337   Header->ip.ip_sum = htons (~(unsigned short) crc);
1338   Header->udp.len = htons (size - sizeof (struct ieee80211_frame));
1339
1340 #endif
1341
1342   return GNUNET_YES;
1343 }
1344
1345 /**
1346  * 32bit CRC
1347  *
1348  * @param msgbuf pointer tor the data
1349  * @param msgbuf_size size of the data
1350  *
1351  * @return 32bit crc value
1352  */
1353
1354 uint32_t
1355 getcrc32 (const char *msgbuf, size_t msgbuf_size)
1356 {
1357
1358   return GNUNET_CRYPTO_crc32_n (msgbuf, msgbuf_size);;
1359 }
1360
1361 /**
1362  * 16bit CRC
1363  *
1364  * @param msgbuf pointer tor the data
1365  * @param msgbuf_size size of the data
1366  *
1367  * @return 16bit crc value
1368  */
1369
1370 uint16_t
1371 getcrc16 (const char *msgbuf, size_t msgbuf_size)
1372 {
1373   //TODO calc some crc
1374   return 0;
1375 }
1376
1377 /**
1378  * function to add a fragment of a message to send
1379  * @param cls FragmentMessage this message belongs to
1380  * @param hdr pointer to the start of the message
1381  */
1382
1383 void
1384 add_message_for_send (void *cls, const struct GNUNET_MessageHeader *hdr)
1385 {
1386
1387   struct FragmentMessage *fm = cls;
1388   struct FragmentMessage_queue *fmqueue;
1389
1390   GNUNET_assert (cls != NULL);
1391   GNUNET_assert (fm->frag == NULL);
1392   struct MacEndpoint *endpoint = fm->session->mac;
1393   struct Plugin *plugin = endpoint->plugin;
1394   struct GNUNET_MessageHeader *msgheader;
1395   struct GNUNET_MessageHeader *msgheader2;
1396   uint16_t size;
1397
1398 #if DEBUG_wlan_retransmission > 1
1399   GNUNET_loHELLO_BEACON_SCALING_FACTORg_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
1400                    "Adding fragment of message %p to send, session %p, endpoint %p, type %u\n",
1401                    fm, fm->session, endpoint, hdr->type);
1402 #endif
1403
1404   size =
1405       sizeof (struct GNUNET_MessageHeader) + sizeof (struct Radiotap_Send) +
1406       sizeof (struct ieee80211_frame) + ntohs (hdr->size);
1407   fm->frag = GNUNET_malloc (size);
1408   fm->size = size;
1409
1410   msgheader = (struct GNUNET_MessageHeader *) fm->frag;
1411   msgheader->size = htons (size);
1412   msgheader->type = htons (GNUNET_MESSAGE_TYPE_WLAN_HELPER_DATA);
1413
1414   fm->radioHeader = (struct Radiotap_Send *) &msgheader[1];
1415   fm->ieeewlanheader = (struct ieee80211_frame *) &fm->radioHeader[1];
1416   msgheader2 = (struct GNUNET_MessageHeader *) &fm->ieeewlanheader[1];
1417   memcpy (msgheader2, hdr, ntohs (hdr->size));
1418
1419   fmqueue = GNUNET_malloc (sizeof (struct FragmentMessage_queue));
1420   fmqueue->content = fm;
1421
1422   GNUNET_CONTAINER_DLL_insert_tail (plugin->sending_messages_head,
1423                                     plugin->sending_messages_tail, fmqueue);
1424   set_next_send (plugin);
1425 }
1426
1427
1428 /**
1429  * We have been notified that wlan-helper has written something to stdout.
1430  * Handle the output, then reschedule this function to be called again once
1431  * more is available.
1432  *
1433  * @param cls the plugin handle
1434  * @param tc the scheduling context
1435  */
1436 static void
1437 wlan_plugin_helper_read (void *cls,
1438                          const struct GNUNET_SCHEDULER_TaskContext *tc)
1439 {
1440   struct Plugin *plugin = cls;
1441
1442   plugin->server_read_task = GNUNET_SCHEDULER_NO_TASK;
1443
1444   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1445     return;
1446
1447   char mybuf[WLAN_MTU + sizeof (struct GNUNET_MessageHeader)];
1448   ssize_t bytes;
1449
1450   bytes =
1451       GNUNET_DISK_file_read (plugin->server_stdout_handle, mybuf,
1452                              sizeof (mybuf));
1453   if (bytes <= 0)
1454   {
1455 #if DEBUG_wlan
1456     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
1457                      _
1458                      ("Finished reading from wlan-helper stdout with code: %d\n"),
1459                      bytes);
1460 #endif
1461     return;
1462   }
1463   GNUNET_SERVER_mst_receive (plugin->suid_tokenizer, NULL, mybuf, bytes,
1464                              GNUNET_NO, GNUNET_NO);
1465
1466   GNUNET_assert (plugin->server_read_task == GNUNET_SCHEDULER_NO_TASK);
1467   plugin->server_read_task =
1468       GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL,
1469                                       plugin->server_stdout_handle,
1470                                       &wlan_plugin_helper_read, plugin);
1471 }
1472
1473 /**
1474  * Start the gnunet-wlan-helper process.
1475  *
1476  * @param plugin the transport plugin
1477  * @return GNUNET_YES if process was started, GNUNET_SYSERR on error
1478  */
1479 static int
1480 wlan_transport_start_wlan_helper (struct Plugin *plugin)
1481 {
1482   const char *filenamehw = "gnunet-transport-wlan-helper";
1483   const char *filenameloopback = "gnunet-transport-wlan-helper-dummy";
1484
1485   plugin->server_stdout = GNUNET_DISK_pipe (GNUNET_YES, GNUNET_NO, GNUNET_YES);
1486   if (plugin->server_stdout == NULL)
1487     return GNUNET_SYSERR;
1488
1489   plugin->server_stdin = GNUNET_DISK_pipe (GNUNET_YES, GNUNET_YES, GNUNET_NO);
1490   if (plugin->server_stdin == NULL)
1491     return GNUNET_SYSERR;
1492
1493   /* Start the server process */
1494
1495   if (plugin->testmode == 0)
1496   {
1497
1498 #if DEBUG_wlan
1499     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
1500                      "Starting gnunet-wlan-helper process cmd: %s %s %i\n",
1501                      filenamehw, plugin->interface, plugin->testmode);
1502 #endif
1503
1504     if (GNUNET_OS_check_helper_binary (filenamehw) == GNUNET_YES)
1505     {
1506       plugin->server_proc =
1507           GNUNET_OS_start_process (plugin->server_stdin, plugin->server_stdout,
1508                                    filenamehw, filenamehw, plugin->interface,
1509                                    NULL);
1510     }
1511     else if (GNUNET_OS_check_helper_binary (filenamehw) == GNUNET_NO)
1512     {
1513       GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, PLUGIN_LOG_NAME,
1514                        "gnunet-transport-wlan-helper is not suid, please change it or look at the doku\n");
1515       GNUNET_break (0);
1516     }
1517     else
1518     {
1519       GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, PLUGIN_LOG_NAME,
1520                        "gnunet-transport-wlan-helper not found, please look if it exists and is the $PATH variable!\n");
1521       GNUNET_break (0);
1522     }
1523
1524   }
1525   else if (plugin->testmode == 1)
1526   {
1527
1528 #if DEBUG_wlan
1529     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
1530                      "Starting gnunet-wlan-helper loopback 1 process cmd: %s %s %i\n",
1531                      filenameloopback, plugin->interface, plugin->testmode);
1532 #endif
1533
1534     if (GNUNET_OS_check_helper_binary (filenameloopback) != GNUNET_SYSERR)
1535     {
1536       plugin->server_proc =
1537           GNUNET_OS_start_process (plugin->server_stdin, plugin->server_stdout,
1538                                    filenameloopback, filenameloopback, "1",
1539                                    NULL);
1540     }
1541     else
1542     {
1543       GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, PLUGIN_LOG_NAME,
1544                        "gnunet-transport-wlan-helper-dummy not found, please look if it exists and is the $PATH variable!\n");
1545       GNUNET_break (0);
1546     }
1547   }
1548   else if (plugin->testmode == 2)
1549   {
1550 #if DEBUG_wlan
1551     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
1552                      "Starting gnunet-wlan-helper loopback 2 process cmd: %s %s %i\n",
1553                      filenameloopback, plugin->interface, plugin->testmode);
1554 #endif
1555     if (GNUNET_OS_check_helper_binary (filenameloopback) != GNUNET_SYSERR)
1556     {
1557       plugin->server_proc =
1558           GNUNET_OS_start_process (plugin->server_stdin, plugin->server_stdout,
1559                                    filenameloopback, filenameloopback, "2",
1560                                    NULL);
1561     }
1562     else
1563     {
1564       GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, PLUGIN_LOG_NAME,
1565                        "gnunet-transport-wlan-helper-dummy not found, please look if it exists and is in the $PATH variable!\n");
1566       GNUNET_break (0);
1567     }
1568   }
1569   if (plugin->server_proc == NULL)
1570   {
1571 #if DEBUG_wlan
1572     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
1573                      "Failed to start gnunet-wlan-helper process\n");
1574 #endif
1575     return GNUNET_SYSERR;
1576   }
1577
1578   /* Close the write end of the read pipe */
1579   GNUNET_DISK_pipe_close_end (plugin->server_stdout,
1580                               GNUNET_DISK_PIPE_END_WRITE);
1581
1582   /* Close the read end of the write pipe */
1583   GNUNET_DISK_pipe_close_end (plugin->server_stdin, GNUNET_DISK_PIPE_END_READ);
1584
1585   plugin->server_stdout_handle =
1586       GNUNET_DISK_pipe_handle (plugin->server_stdout,
1587                                GNUNET_DISK_PIPE_END_READ);
1588   plugin->server_stdin_handle =
1589       GNUNET_DISK_pipe_handle (plugin->server_stdin,
1590                                GNUNET_DISK_PIPE_END_WRITE);
1591
1592   GNUNET_assert (plugin->server_read_task == GNUNET_SCHEDULER_NO_TASK);
1593
1594 #if DEBUG_wlan
1595   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
1596                    "Adding server_read_task for the wlan-helper\n");
1597 #endif
1598
1599   plugin->server_read_task =
1600       GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL,
1601                                       plugin->server_stdout_handle,
1602                                       &wlan_plugin_helper_read, plugin);
1603
1604   return GNUNET_YES;
1605 }
1606
1607 /**
1608  * Stops the gnunet-wlan-helper process.
1609  *
1610  * @param plugin the transport plugin
1611  * @return GNUNET_YES if process was started, GNUNET_SYSERR on error
1612  */
1613 static int
1614 wlan_transport_stop_wlan_helper (struct Plugin *plugin)
1615 {
1616 #if DEBUG_wlan
1617     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
1618                      "Stoping WLAN helper process\n");
1619 #endif
1620
1621   if (plugin->server_write_delay_task != GNUNET_SCHEDULER_NO_TASK)
1622   {
1623     GNUNET_SCHEDULER_cancel (plugin->server_write_delay_task);
1624     plugin->server_write_delay_task = GNUNET_SCHEDULER_NO_TASK;
1625   }
1626
1627   if (plugin->server_write_task != GNUNET_SCHEDULER_NO_TASK)
1628   {
1629     GNUNET_SCHEDULER_cancel (plugin->server_write_task);
1630     plugin->server_write_task = GNUNET_SCHEDULER_NO_TASK;
1631   }
1632
1633   if (plugin->server_read_task != GNUNET_SCHEDULER_NO_TASK)
1634   {
1635     GNUNET_SCHEDULER_cancel (plugin->server_read_task);
1636     plugin->server_read_task = GNUNET_SCHEDULER_NO_TASK;
1637   }
1638
1639   GNUNET_DISK_pipe_close (plugin->server_stdout);
1640   GNUNET_DISK_pipe_close (plugin->server_stdin);
1641   GNUNET_OS_process_kill (plugin->server_proc, SIGKILL);
1642   GNUNET_OS_process_wait(plugin->server_proc);
1643   GNUNET_OS_process_close (plugin->server_proc);
1644
1645   return GNUNET_YES;
1646 }
1647
1648 /**
1649  * function for delayed restart of the helper process
1650  * @param cls Finish_send struct if message should be finished
1651  * @param tc TaskContext
1652  */
1653 static void
1654 delay_restart_helper (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1655 {
1656   struct Finish_send *finish = cls;
1657   struct Plugin *plugin;
1658   plugin = finish->plugin;
1659
1660   plugin->server_write_task = GNUNET_SCHEDULER_NO_TASK;
1661   if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
1662   {
1663     GNUNET_free_non_null(finish->msgstart);
1664     GNUNET_free (finish);
1665     return;
1666   }
1667
1668   wlan_transport_start_wlan_helper(plugin);
1669
1670   if (finish->size != 0)
1671     {
1672       plugin->server_write_task =
1673                       GNUNET_SCHEDULER_add_write_file (GNUNET_TIME_UNIT_FOREVER_REL,
1674                                                        plugin->server_stdin_handle,
1675                                                        &finish_sending, finish);
1676     }
1677   else
1678     {
1679       set_next_send (plugin);
1680       GNUNET_free_non_null(finish->msgstart);
1681       GNUNET_free (finish);
1682     }
1683
1684 }
1685
1686 /**
1687  * Function to restart the helper
1688  * @param plugin pointer to the global plugin struct
1689  * @param finish pointer to the Finish_send struct to finish
1690  */
1691 static void
1692 restart_helper(struct Plugin *plugin, struct Finish_send *finish)
1693 {
1694   static struct GNUNET_TIME_Relative next_try = {1000};
1695   GNUNET_assert(finish != NULL);
1696
1697   wlan_transport_stop_wlan_helper(plugin);
1698   plugin->server_write_task = GNUNET_SCHEDULER_add_delayed (next_try, &delay_restart_helper, finish);
1699   GNUNET_TIME_relative_multiply(next_try, HELPER_RESTART_SCALING_FACTOR);
1700
1701 }
1702
1703 /**
1704  * function to finish a sending if not all could have been writen befor
1705  * @param cls pointer to the Finish_send struct
1706  * @param tc TaskContext
1707  */
1708 static void
1709 finish_sending (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1710 {
1711   struct Finish_send *finish = cls;
1712   struct Plugin *plugin;
1713   ssize_t bytes;
1714
1715   plugin = finish->plugin;
1716   plugin->server_write_task = GNUNET_SCHEDULER_NO_TASK;
1717
1718   if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
1719   {
1720     GNUNET_free (finish->msgstart);
1721     GNUNET_free (finish);
1722     return;
1723   }
1724   bytes =
1725       GNUNET_DISK_file_write (plugin->server_stdin_handle, finish->head_of_next_write,
1726                               finish->size);
1727
1728   if (bytes != finish->size)
1729   {
1730     if (bytes != GNUNET_SYSERR)
1731       {
1732       finish->head_of_next_write += bytes;
1733       finish->size -= bytes;
1734       plugin->server_write_task =
1735           GNUNET_SCHEDULER_add_write_file (GNUNET_TIME_UNIT_FOREVER_REL,
1736                                            plugin->server_stdin_handle,
1737                                            &finish_sending, finish);
1738       }
1739     else
1740       {
1741        restart_helper(plugin, finish);
1742       }
1743   }
1744   else
1745   {
1746     GNUNET_free (finish->msgstart);
1747     GNUNET_free (finish);
1748     set_next_send (plugin);
1749   }
1750 }
1751
1752 /**
1753  * function to send a hello beacon
1754  * @param plugin pointer to the plugin struct
1755  */
1756 static void
1757 send_hello_beacon (struct Plugin *plugin)
1758 {
1759
1760 #if DEBUG_wlan
1761   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
1762                    "Sending hello beacon\n");
1763 #endif
1764
1765   uint16_t size;
1766   ssize_t bytes;
1767   uint16_t hello_size;
1768   struct GNUNET_MessageHeader *msgheader;
1769   struct ieee80211_frame *ieeewlanheader;
1770   struct Radiotap_Send *radioHeader;
1771   struct GNUNET_MessageHeader *msgheader2;
1772   const struct GNUNET_MessageHeader *hello;
1773   struct Finish_send * finish;
1774
1775   GNUNET_assert (plugin != NULL);
1776
1777   GNUNET_STATISTICS_update (plugin->env->stats, _("# wlan hello beacons send"), 1, GNUNET_NO);
1778
1779   hello = plugin->env->get_our_hello ();
1780   hello_size = GNUNET_HELLO_size ((struct GNUNET_HELLO_Message *) hello);
1781   GNUNET_assert (sizeof (struct WlanHeader) + hello_size <= WLAN_MTU);
1782   size =
1783       sizeof (struct GNUNET_MessageHeader) + sizeof (struct Radiotap_Send) +
1784       sizeof (struct ieee80211_frame) + hello_size;
1785
1786   msgheader = GNUNET_malloc (size);
1787   msgheader->size = htons (size);
1788   msgheader->type = htons (GNUNET_MESSAGE_TYPE_WLAN_HELPER_DATA);
1789
1790   radioHeader = (struct Radiotap_Send *) &msgheader[1];
1791   getRadiotapHeader (plugin, NULL, radioHeader);
1792   ieeewlanheader = (struct ieee80211_frame *) &radioHeader[1];
1793   getWlanHeader (ieeewlanheader, &bc_all_mac, plugin, size);
1794
1795   msgheader2 = (struct GNUNET_MessageHeader *) &ieeewlanheader[1];
1796   /*msgheader2->size =
1797       htons (GNUNET_HELLO_size ((struct GNUNET_HELLO_Message *) hello) +
1798              sizeof (struct GNUNET_MessageHeader));
1799
1800   msgheader2->type = htons (GNUNET_MESSAGE_TYPE_WLAN_ADVERTISEMENT);*/
1801   memcpy (msgheader2, hello, hello_size);
1802
1803   bytes = GNUNET_DISK_file_write (plugin->server_stdin_handle, msgheader, size);
1804
1805   if (bytes == GNUNET_SYSERR)
1806   {
1807     GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, PLUGIN_LOG_NAME,
1808                      _
1809                      ("Error writing to wlan healper. errno == %d, ERROR: %s\n"),
1810                      errno, strerror (errno));
1811     finish = GNUNET_malloc (sizeof (struct Finish_send));
1812     finish->plugin = plugin;
1813     finish->head_of_next_write = NULL;
1814     finish->size = 0;
1815     finish->msgstart = NULL;
1816     restart_helper(plugin, finish);
1817
1818     set_next_beacon_time (plugin);
1819
1820   }
1821   else
1822     {
1823     GNUNET_assert (bytes == size);
1824     set_next_beacon_time (plugin);
1825     set_next_send (plugin);
1826     }
1827   GNUNET_free (msgheader);
1828
1829
1830 }
1831
1832 /**
1833  * function to add an ack to send it for a received fragment
1834  * @param cls MacEndpoint this ack belongs to
1835  * @param msg_id id of the message
1836  * @param hdr pointer to the hdr where the ack is stored
1837  *
1838  */
1839
1840 static void
1841 add_ack_for_send (void *cls, uint32_t msg_id,
1842                   const struct GNUNET_MessageHeader *hdr)
1843 {
1844
1845   struct AckSendQueue *ack;
1846
1847   GNUNET_assert (cls != NULL);
1848   struct MacEndpoint *endpoint = cls;
1849   struct Plugin *plugin = endpoint->plugin;
1850   struct GNUNET_MessageHeader *msgheader;
1851   struct GNUNET_MessageHeader *msgheader2;
1852   uint16_t size;
1853
1854   size =
1855       sizeof (struct GNUNET_MessageHeader) + sizeof (struct Radiotap_Send) +
1856       sizeof (struct ieee80211_frame) + ntohs (hdr->size) +
1857       sizeof (struct AckSendQueue);
1858
1859   ack = GNUNET_malloc (size);
1860   ack->message_id = msg_id;
1861   ack->endpoint = endpoint;
1862
1863   size =
1864       sizeof (struct GNUNET_MessageHeader) + sizeof (struct Radiotap_Send) +
1865       sizeof (struct ieee80211_frame) + ntohs (hdr->size);
1866
1867   msgheader = (struct GNUNET_MessageHeader *) &ack[1];
1868   ack->hdr = (struct GNUNET_MessageHeader *) &ack[1];
1869   msgheader->size = htons (size);
1870   msgheader->type = htons (GNUNET_MESSAGE_TYPE_WLAN_HELPER_DATA);
1871
1872   ack->radioHeader = (struct Radiotap_Send *) &msgheader[1];
1873   ack->ieeewlanheader = (struct ieee80211_frame *) &(ack->radioHeader)[1];
1874   msgheader2 = (struct GNUNET_MessageHeader *) &(ack->ieeewlanheader)[1];
1875   memcpy (msgheader2, hdr, ntohs (hdr->size));
1876
1877   GNUNET_CONTAINER_DLL_insert_tail (plugin->ack_send_queue_head,
1878                                     plugin->ack_send_queue_tail, ack);
1879
1880 #if DEBUG_wlan_retransmission > 1
1881   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
1882                    "Adding ack with message id %u to send, AckSendQueue %p, endpoint %p\n",
1883                    msg_id, ack, endpoint);
1884 #endif
1885
1886   set_next_send (plugin);
1887 }
1888
1889 /**
1890  * Function for the scheduler if a FragmentMessage times out
1891  * @param cls pointer to the FragmentMessage
1892  * @param tc pointer to the GNUNET_SCHEDULER_TaskContext
1893  */
1894 static void
1895 fragmentmessage_timeout (void *cls,
1896                          const struct GNUNET_SCHEDULER_TaskContext *tc)
1897 {
1898   struct FragmentMessage *fm = cls;
1899
1900   GNUNET_assert (fm != NULL);
1901   fm->timeout_task = GNUNET_SCHEDULER_NO_TASK;
1902   if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
1903   {
1904     return;
1905   }
1906   free_fragment_message (fm->session->mac->plugin, fm);
1907 }
1908
1909 /**
1910  * Function to check if there is some space in the fragment queue
1911  * inserts a message if space is available
1912  * @param plugin the plugin struct
1913  */
1914
1915 static void
1916 check_fragment_queue (struct Plugin *plugin)
1917 {
1918   struct Session *session;
1919   struct FragmentMessage *fm;
1920   struct GNUNET_PeerIdentity pid;
1921
1922   struct PendingMessage *pm;
1923
1924   if (plugin->pending_Fragment_Messages < FRAGMENT_QUEUE_SIZE)
1925   {
1926     session = get_next_queue_session (plugin);
1927     if (session != NULL)
1928     {
1929       pm = session->pending_message_head;
1930       GNUNET_assert (pm != NULL);
1931       GNUNET_CONTAINER_DLL_remove (session->pending_message_head,
1932                                    session->pending_message_tail, pm);
1933       session->mac->fragment_messages_out_count++;
1934       session->fragment_messages_out_count++;
1935       plugin->pending_Fragment_Messages++;
1936
1937       fm = GNUNET_malloc (sizeof (struct FragmentMessage));
1938       fm->session = session;
1939       fm->timeout.abs_value = pm->timeout.abs_value;
1940       fm->frag = NULL;
1941       fm->fragcontext =
1942           GNUNET_FRAGMENT_context_create (plugin->env->stats, WLAN_MTU,
1943                                           &plugin->tracker,
1944                                           GNUNET_TIME_UNIT_SECONDS,
1945                                           &(pm->msg->header),
1946                                           &add_message_for_send, fm);
1947       fm->timeout_task =
1948           GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_absolute_get_remaining
1949                                         (fm->timeout), fragmentmessage_timeout,
1950                                         fm);
1951       GNUNET_CONTAINER_DLL_insert_tail (session->mac->sending_messages_head,
1952                                         session->mac->sending_messages_tail,
1953                                         fm);
1954
1955       if (pm->transmit_cont != NULL)
1956       {
1957         pid = session->target;
1958         pm->transmit_cont (pm->transmit_cont_cls, &pid, GNUNET_OK);
1959 #if DEBUG_wlan
1960         GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
1961                          "called pm->transmit_cont for %p\n", session);
1962 #endif
1963       }
1964       else
1965       {
1966 #if DEBUG_wlan
1967         GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
1968                          "no pm->transmit_cont for %p\n", session);
1969 #endif
1970       }
1971       GNUNET_free (pm);
1972
1973       if (session->pending_message_head != NULL)
1974       {
1975         //requeue session
1976         queue_session (plugin, session);
1977       }
1978
1979     }
1980   }
1981
1982   //check if timeout changed
1983   set_next_send (plugin);
1984 }
1985
1986 /**
1987  * Function to send an ack, does not free the ack
1988  * @param plugin pointer to the plugin
1989  */
1990 static void
1991 send_ack (struct Plugin *plugin)
1992 {
1993
1994   ssize_t bytes;
1995   struct AckSendQueue *ack;
1996   struct Finish_send * finish;
1997
1998   ack = plugin->ack_send_queue_head;
1999
2000
2001 #if DEBUG_wlan
2002   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
2003                    "Sending ack for message_id %u for mac endpoint %p, size %u\n",
2004                    ack->message_id, ack->endpoint,
2005                    ntohs (ack->hdr->size) - sizeof (struct Radiotap_Send));
2006 #endif
2007
2008   GNUNET_assert (plugin != NULL);
2009   GNUNET_STATISTICS_update (plugin->env->stats, _("# wlan acks send"), 1, GNUNET_NO);
2010
2011   getRadiotapHeader (plugin, ack->endpoint, ack->radioHeader);
2012   getWlanHeader (ack->ieeewlanheader, &ack->endpoint->addr, plugin,
2013                  ntohs (ack->hdr->size));
2014
2015   bytes =
2016       GNUNET_DISK_file_write (plugin->server_stdin_handle, ack->hdr,
2017                               ntohs (ack->hdr->size));
2018   if (bytes == GNUNET_SYSERR)
2019   {
2020     GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, PLUGIN_LOG_NAME,
2021                      _
2022                      ("Error writing to wlan healper. errno == %d, ERROR: %s\n"),
2023                      errno, strerror (errno));
2024     finish = GNUNET_malloc (sizeof (struct Finish_send));
2025     finish->plugin = plugin;
2026     finish->head_of_next_write = NULL;
2027     finish->size = 0;
2028     finish->msgstart = NULL;
2029     restart_helper(plugin, finish);
2030   }
2031   else
2032   {
2033     GNUNET_assert (bytes == ntohs (ack->hdr->size));
2034     GNUNET_CONTAINER_DLL_remove (plugin->ack_send_queue_head,
2035                                  plugin->ack_send_queue_tail, ack);
2036     GNUNET_free (ack);
2037     set_next_send (plugin);
2038   }
2039 }
2040
2041 /**
2042  * Function called when wlan helper is ready to get some data
2043  *
2044  * @param cls closure
2045  * @param tc GNUNET_SCHEDULER_TaskContext
2046  */
2047 static void
2048 do_transmit (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2049 {
2050   struct Plugin *plugin = cls;
2051   GNUNET_assert (plugin != NULL);
2052
2053   plugin->server_write_task = GNUNET_SCHEDULER_NO_TASK;
2054   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
2055     return;
2056
2057   struct Session *session;
2058   struct FragmentMessage *fm;
2059   struct Finish_send *finish;
2060   struct FragmentMessage_queue *fmq;
2061   ssize_t bytes;
2062
2063   if (plugin->ack_send_queue_head != NULL)
2064   {
2065     send_ack (plugin);
2066     return;
2067   }
2068
2069   //test if a "hello-beacon" has to be send
2070   if (GNUNET_TIME_absolute_get_remaining (plugin->beacon_time).rel_value == 0)
2071   {
2072     send_hello_beacon (plugin);
2073     return;
2074   }
2075
2076   if (plugin->sending_messages_head != NULL)
2077   {
2078     GNUNET_STATISTICS_update (plugin->env->stats, _("# wlan fragments send"), 1, GNUNET_NO);
2079
2080     fmq = plugin->sending_messages_head;
2081     fm = fmq->content;
2082     GNUNET_CONTAINER_DLL_remove (plugin->sending_messages_head,
2083                                  plugin->sending_messages_tail, fmq);
2084     GNUNET_free (fmq);
2085
2086     session = fm->session;
2087     GNUNET_assert (session != NULL);
2088
2089 #if DEBUG_wlan
2090     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
2091                      "Sending GNUNET_MESSAGE_TYPE_WLAN_FRAGMENT for fragment message %p, size: %u\n",
2092                      fm, fm->size);
2093 #endif
2094
2095     getRadiotapHeader (plugin, session->mac, fm->radioHeader);
2096     getWlanHeader (fm->ieeewlanheader, &(fm->session->mac->addr), plugin,
2097                    fm->size);
2098
2099     bytes =
2100         GNUNET_DISK_file_write (plugin->server_stdin_handle, fm->frag,
2101                                 fm->size);
2102
2103
2104     if (bytes != fm->size)
2105     {
2106       finish = GNUNET_malloc (sizeof (struct Finish_send));
2107       finish->plugin = plugin;
2108       finish->msgstart = (struct GNUNET_MessageHeader *) fm->frag;
2109       GNUNET_assert (plugin->server_write_task == GNUNET_SCHEDULER_NO_TASK);
2110
2111       if (bytes == GNUNET_SYSERR)
2112       {
2113         GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, PLUGIN_LOG_NAME,
2114                          _
2115                          ("Error writing to wlan healper. errno == %d, ERROR: %s\n"),
2116                          errno, strerror (errno));
2117
2118         finish->head_of_next_write = fm->frag;
2119         finish->size = fm->size;
2120         restart_helper(plugin, finish);
2121       }
2122       else
2123       {
2124         finish->head_of_next_write = fm->frag + bytes;
2125         finish->size = fm->size - bytes;
2126         plugin->server_write_task =
2127                   GNUNET_SCHEDULER_add_write_file (GNUNET_TIME_UNIT_FOREVER_REL,
2128                                                    plugin->server_stdin_handle,
2129                                                    &finish_sending, finish);
2130       }
2131
2132       fm->frag = NULL;
2133     }
2134     else
2135     {
2136       GNUNET_free (fm->frag);
2137       fm->frag = NULL;
2138       set_next_send (plugin);
2139     }
2140     GNUNET_FRAGMENT_context_transmission_done (fm->fragcontext);
2141     return;
2142   }
2143
2144   GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, PLUGIN_LOG_NAME,
2145                    "do_transmit did nothing, should not happen!\n");
2146 }
2147
2148 /**
2149  * Another peer has suggested an address for this
2150  * peer and transport plugin.  Check that this could be a valid
2151  * address.  If so, consider adding it to the list
2152  * of addresses.
2153  *
2154  * @param cls closure
2155  * @param addr pointer to the address
2156  * @param addrlen length of addr
2157  * @return GNUNET_OK if this is a plausible address for this peer
2158  *         and transport
2159  */
2160 static int
2161 wlan_plugin_address_suggested (void *cls, const void *addr, size_t addrlen)
2162 {
2163   //struct Plugin *plugin = cls;
2164
2165   /* check if the address is plausible; if so,
2166    * add it to our list! */
2167
2168   GNUNET_assert (cls != NULL);
2169   //FIXME mitm is not checked
2170   //Mac Address has 6 bytes
2171   if (addrlen == 6)
2172   {
2173     /* TODO check for bad addresses like multicast, broadcast, etc */
2174 #if DEBUG_wlan
2175     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
2176                          "wlan_plugin_address_suggested got good address, size %u!\n", addrlen);
2177 #endif
2178     return GNUNET_OK;
2179   }
2180 #if DEBUG_wlan
2181     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
2182                          "wlan_plugin_address_suggested got bad address, size %u!\n", addrlen);
2183 #endif
2184   return GNUNET_SYSERR;
2185 }
2186
2187 /**
2188  * Function that can be used by the transport service to transmit
2189  * a message using the plugin.
2190  *
2191  * @param cls closure
2192  * @param target who should receive this message
2193  * @param priority how important is the message
2194  * @param msgbuf the message to transmit
2195  * @param msgbuf_size number of bytes in 'msgbuf'
2196  * @param timeout when should we time out
2197  * @param session which session must be used (or NULL for "any")
2198  * @param addr the address to use (can be NULL if the plugin
2199  *                is "on its own" (i.e. re-use existing TCP connection))
2200  * @param addrlen length of the address in bytes
2201  * @param force_address GNUNET_YES if the plugin MUST use the given address,
2202  *                otherwise the plugin may use other addresses or
2203  *                existing connections (if available)
2204  * @param cont continuation to call once the message has
2205  *        been transmitted (or if the transport is ready
2206  *        for the next transmission call; or if the
2207  *        peer disconnected...)
2208  * @param cont_cls closure for cont
2209  * @return number of bytes used (on the physical network, with overheads);
2210  *         -1 on hard errors (i.e. address invalid); 0 is a legal value
2211  *         and does NOT mean that the message was not transmitted (DV)
2212  */
2213 static ssize_t
2214 wlan_plugin_send (void *cls, const struct GNUNET_PeerIdentity *target,
2215                   const char *msgbuf, size_t msgbuf_size, unsigned int priority,
2216                   struct GNUNET_TIME_Relative timeout, struct Session *session,
2217                   const void *addr, size_t addrlen, int force_address,
2218                   GNUNET_TRANSPORT_TransmitContinuation cont, void *cont_cls)
2219 {
2220   struct Plugin *plugin = cls;
2221   struct PendingMessage *newmsg;
2222   struct WlanHeader *wlanheader;
2223   GNUNET_assert (plugin != NULL);
2224   //check if msglen > 0
2225   GNUNET_assert (msgbuf_size > 0);
2226
2227   //get session if needed
2228   if (session == NULL)
2229   {
2230     if (wlan_plugin_address_suggested (plugin, addr, addrlen) == GNUNET_OK)
2231     {
2232       session = get_session (plugin, addr, target);
2233     }
2234     else
2235     {
2236       GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, PLUGIN_LOG_NAME,
2237                        _("Wlan Address len %d is wrong\n"), addrlen);
2238       return -1;
2239     }
2240   }
2241
2242   GNUNET_STATISTICS_update (plugin->env->stats, _("# wlan messages queued"), 1, GNUNET_NO);
2243
2244   //queue message:
2245
2246   //queue message in session
2247   //test if there is no other message in the "queue"
2248   //FIXME: to many send requests
2249   if (session->pending_message_head != NULL)
2250   {
2251     newmsg = session->pending_message_head;
2252     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
2253                      "wlan_plugin_send: a pending message is already in the queue for this client\n remaining time to send this message is %u, queued fragment messages for this mac connection %u\n",
2254                      GNUNET_TIME_absolute_get_remaining (newmsg->
2255                                                          timeout).rel_value,
2256                      session->mac->fragment_messages_out_count);
2257   }
2258
2259   newmsg = GNUNET_malloc (sizeof (struct PendingMessage));
2260   newmsg->msg = GNUNET_malloc (msgbuf_size + sizeof (struct WlanHeader));
2261   wlanheader = newmsg->msg;
2262   //copy msg to buffer, not fragmented / segmented yet, but with message header
2263   wlanheader->header.size = htons (msgbuf_size + sizeof (struct WlanHeader));
2264   wlanheader->header.type = htons (GNUNET_MESSAGE_TYPE_WLAN_DATA);
2265   memcpy (&(wlanheader->target), target, sizeof (struct GNUNET_PeerIdentity));
2266   memcpy (&(wlanheader->source), plugin->env->my_identity,
2267           sizeof (struct GNUNET_PeerIdentity));
2268   wlanheader->crc = 0;
2269   memcpy (&wlanheader[1], msgbuf, msgbuf_size);
2270   wlanheader->crc =
2271       htonl (getcrc32
2272              ((char *) wlanheader, msgbuf_size + sizeof (struct WlanHeader)));
2273   //GNUNET_log_from(GNUNET_ERROR_TYPE_INFO, PLUGIN_LOG_NAME,  "Wlan message Header crc: %u, %u\n",getcrc32((char*) wlanheader, msgbuf_size + sizeof(struct WlanHeader)), wlanheader->crc);
2274   //hexdump(newmsg->msg, msgbuf_size + sizeof(struct WlanHeader));
2275
2276   newmsg->transmit_cont = cont;
2277   newmsg->transmit_cont_cls = cont_cls;
2278   newmsg->timeout = GNUNET_TIME_relative_to_absolute (timeout);
2279
2280   newmsg->timeout.abs_value = newmsg->timeout.abs_value - 500;
2281
2282   newmsg->message_size = msgbuf_size + sizeof (struct WlanHeader);
2283
2284   GNUNET_CONTAINER_DLL_insert_tail (session->pending_message_head,
2285                                     session->pending_message_tail, newmsg);
2286
2287 #if DEBUG_wlan
2288   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
2289                    "New message for %p with size (incl wlan header) %u added\n",
2290                    session, newmsg->message_size);
2291 #endif
2292 #if DEBUG_wlan_msg_dump > 1
2293   hexdump (msgbuf, GNUNET_MIN (msgbuf_size, 256));
2294 #endif
2295   //queue session
2296   queue_session (plugin, session);
2297
2298   check_fragment_queue (plugin);
2299   //FIXME not the correct size
2300   return msgbuf_size;
2301
2302 }
2303
2304 /**
2305  * function to free a mac endpoint
2306  * @param plugin pointer to the plugin struct
2307  * @param endpoint pointer to the MacEndpoint to free
2308  */
2309 static void
2310 free_macendpoint (struct Plugin *plugin, struct MacEndpoint *endpoint)
2311 {
2312   struct Sessionqueue *sessions;
2313   struct Sessionqueue *sessions_next;
2314
2315   GNUNET_assert (endpoint != NULL);
2316
2317   sessions = endpoint->sessions_head;
2318   while (sessions != NULL)
2319   {
2320     sessions_next = sessions->next;
2321     free_session (plugin, sessions, GNUNET_NO);
2322     sessions = sessions_next;
2323   }
2324
2325   GNUNET_CONTAINER_DLL_remove (plugin->mac_head, plugin->mac_tail, endpoint);
2326   if (endpoint->timeout_task != GNUNET_SCHEDULER_NO_TASK)
2327   {
2328     GNUNET_SCHEDULER_cancel (endpoint->timeout_task);
2329     endpoint->timeout_task = GNUNET_SCHEDULER_NO_TASK;
2330   }
2331   plugin->mac_count--;
2332   GNUNET_STATISTICS_set(plugin->env->stats, _("# wlan mac endpoints"), plugin->mac_count, GNUNET_NO);
2333   GNUNET_free (endpoint);
2334
2335 }
2336
2337 /**
2338  * function to free a session
2339  * @param plugin pointer to the plugin
2340  * @param queue pointer to the sessionqueue element to free
2341  * @param free_macendpoint if GNUNET_YES and mac endpoint would be empty, free mac endpoint
2342  */
2343 static void
2344 free_session (struct Plugin *plugin, struct Sessionqueue *queue,
2345               int do_free_macendpoint)
2346 {
2347   struct Sessionqueue *pendingsession;
2348   struct Sessionqueue *pendingsession_tmp;
2349   struct PendingMessage *pm;
2350   struct MacEndpoint *endpoint;
2351   struct FragmentMessage *fm;
2352   struct FragmentMessage *fmnext;
2353   int check = 0;
2354
2355   GNUNET_assert (plugin != NULL);
2356   GNUNET_assert (queue != NULL);
2357   GNUNET_assert (queue->content != NULL);
2358
2359   //session found
2360   //is this session pending for send
2361   pendingsession = plugin->pending_Sessions_head;
2362   while (pendingsession != NULL)
2363   {
2364     pendingsession_tmp = pendingsession;
2365     pendingsession = pendingsession->next;
2366     GNUNET_assert (pendingsession_tmp->content != NULL);
2367     if (pendingsession_tmp->content == queue->content)
2368     {
2369       plugin->pendingsessions--;
2370       GNUNET_STATISTICS_set(plugin->env->stats, _("# wlan pending sessions"), plugin->pendingsessions, GNUNET_NO);
2371       GNUNET_CONTAINER_DLL_remove (plugin->pending_Sessions_head,
2372                                    plugin->pending_Sessions_tail,
2373                                    pendingsession_tmp);
2374       GNUNET_free (pendingsession_tmp);
2375
2376       GNUNET_assert (check == 0);
2377       check = 1;
2378     }
2379   }
2380
2381   endpoint = queue->content->mac;
2382   fm = endpoint->sending_messages_head;
2383   while (fm != NULL)
2384   {
2385     fmnext = fm->next;
2386     if (fm->session == queue->content)
2387     {
2388       free_fragment_message (plugin, fm);
2389     }
2390     fm = fmnext;
2391   }
2392
2393   // remove PendingMessage
2394   pm = queue->content->pending_message_head;
2395   while (pm != NULL)
2396   {
2397     GNUNET_CONTAINER_DLL_remove (queue->content->pending_message_head,
2398                                  queue->content->pending_message_tail, pm);
2399     GNUNET_free (pm->msg);
2400     GNUNET_free (pm);
2401     pm = queue->content->pending_message_head;
2402   }
2403
2404   GNUNET_CONTAINER_DLL_remove (endpoint->sessions_head, endpoint->sessions_tail,
2405                                queue);
2406   //Check that no ohter session on this endpoint for this session exits
2407   GNUNET_assert(search_session(plugin, endpoint, &queue->content->target) == NULL);
2408   if (endpoint->sessions_head == NULL && do_free_macendpoint == GNUNET_YES)
2409   {
2410     free_macendpoint (plugin, endpoint);
2411     //check if no endpoint with the same address exists
2412     GNUNET_assert(get_macendpoint(plugin, &endpoint->addr, GNUNET_NO) == NULL);
2413   }
2414
2415   if (queue->content->timeout_task != GNUNET_SCHEDULER_NO_TASK)
2416   {
2417     GNUNET_SCHEDULER_cancel (queue->content->timeout_task);
2418     queue->content->timeout_task = GNUNET_SCHEDULER_NO_TASK;
2419   }
2420   GNUNET_free (queue);
2421
2422   check_fragment_queue (plugin);
2423 }
2424
2425 /**
2426  * Function that can be used to force the plugin to disconnect
2427  * from the given peer and cancel all previous transmissions
2428  * (and their continuation).
2429  *
2430  * @param cls closure
2431  * @param target peer from which to disconnect
2432  */
2433 static void
2434 wlan_plugin_disconnect (void *cls, const struct GNUNET_PeerIdentity *target)
2435 {
2436   struct Plugin *plugin = cls;
2437   struct Sessionqueue *queue;
2438   struct Sessionqueue *queue_next;
2439   struct MacEndpoint *endpoint = plugin->mac_head;
2440   struct MacEndpoint *endpoint_next;
2441
2442   // just look at all the session for the needed one
2443   while (endpoint != NULL)
2444   {
2445     queue = endpoint->sessions_head;
2446     endpoint_next = endpoint->next;
2447     while (queue != NULL)
2448     {
2449       // content is never NULL
2450       GNUNET_assert (queue->content != NULL);
2451       queue_next = queue->next;
2452       if (memcmp
2453           (target, &(queue->content->target),
2454            sizeof (struct GNUNET_PeerIdentity)) == 0)
2455       {
2456         free_session (plugin, queue, GNUNET_YES);
2457       }
2458       // try next
2459       queue = queue_next;
2460     }
2461     endpoint = endpoint_next;
2462   }
2463 }
2464
2465 /**
2466  * Convert the transports address to a nice, human-readable
2467  * format.
2468  *
2469  * @param cls closure
2470  * @param type name of the transport that generated the address
2471  * @param addr one of the addresses of the host, NULL for the last address
2472  *        the specific address format depends on the transport
2473  * @param addrlen length of the address
2474  * @param numeric should (IP) addresses be displayed in numeric form?
2475  * @param timeout after how long should we give up?
2476  * @param asc function to call on each string
2477  * @param asc_cls closure for asc
2478  */
2479 static void
2480 wlan_plugin_address_pretty_printer (void *cls, const char *type,
2481                                     const void *addr, size_t addrlen,
2482                                     int numeric,
2483                                     struct GNUNET_TIME_Relative timeout,
2484                                     GNUNET_TRANSPORT_AddressStringCallback asc,
2485                                     void *asc_cls)
2486 {
2487   char *ret;
2488   const unsigned char *input;
2489
2490   //GNUNET_assert(cls !=NULL);
2491   if (addrlen != sizeof(struct MacAddress))
2492   {
2493     /* invalid address (MAC addresses have 6 bytes) */
2494     //GNUNET_break (0);
2495 #if DEBUG_wlan
2496       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
2497                    "Func wlan_plugin_address_pretty_printer got size: %u, worng size!\n",
2498                    addrlen);
2499 #endif
2500     asc(asc_cls, NULL);
2501     return;
2502   }
2503   input = (const unsigned char *) addr;
2504   GNUNET_asprintf (&ret,
2505                    "Transport %s: %s Mac-Address %.2X:%.2X:%.2X:%.2X:%.2X:%.2X",type,
2506                    PROTOCOL_PREFIX, input[0], input[1], input[2], input[3],
2507                    input[4], input[5]);
2508 #if DEBUG_wlan
2509   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
2510                    "Func wlan_plugin_address_pretty_printer got size: %u, nummeric %u, type %s; made string: %s\n",
2511                    addrlen, numeric, type, ret);
2512 #endif
2513   asc ( asc_cls, ret);
2514   //only one mac address per plugin
2515   asc ( asc_cls, NULL);
2516 }
2517
2518
2519
2520 /**
2521  * handels the data after all fragments are put together
2522  * @param cls macendpoint this messages belongs to
2523  * @param hdr pointer to the data
2524  */
2525 static void
2526 wlan_data_message_handler (void *cls, const struct GNUNET_MessageHeader *hdr)
2527 {
2528   struct MacEndpoint *endpoint = (struct MacEndpoint *) cls;
2529   struct Plugin *plugin = endpoint->plugin;
2530   struct WlanHeader *wlanheader;
2531   struct Session *session;
2532
2533   const struct GNUNET_MessageHeader *temp_hdr;
2534   struct GNUNET_PeerIdentity tmpsource;
2535   int crc;
2536
2537   GNUNET_assert (plugin != NULL);
2538
2539   if (ntohs (hdr->type) == GNUNET_MESSAGE_TYPE_WLAN_DATA)
2540   {
2541
2542 #if DEBUG_wlan
2543     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
2544                      "Func wlan_data_message_handler got GNUNET_MESSAGE_TYPE_WLAN_DATA size: %u\n",
2545                      ntohs (hdr->size));
2546 #endif
2547
2548     if (ntohs (hdr->size) <
2549         sizeof (struct WlanHeader) + sizeof (struct GNUNET_MessageHeader))
2550     {
2551       //packet not big enought
2552       return;
2553     }
2554
2555     GNUNET_STATISTICS_update (plugin->env->stats, _("# wlan whole messages received"), 1, GNUNET_NO);
2556     wlanheader = (struct WlanHeader *) hdr;
2557
2558     session = search_session (plugin, endpoint, &wlanheader->source);
2559
2560     temp_hdr = (const struct GNUNET_MessageHeader *) &wlanheader[1];
2561     crc = ntohl (wlanheader->crc);
2562     wlanheader->crc = 0;
2563     if (getcrc32 ((char *) wlanheader, ntohs (wlanheader->header.size)) != crc)
2564     {
2565       //wrong crc, dispose message
2566       GNUNET_log_from (GNUNET_ERROR_TYPE_INFO, PLUGIN_LOG_NAME,
2567                        "Wlan message header crc was wrong: %u != %u\n",
2568                        getcrc32 ((char *) wlanheader,
2569                                  ntohs (wlanheader->header.size)), crc);
2570       hexdump ((void *) hdr, ntohs (hdr->size));
2571       return;
2572     }
2573
2574     //if not in session list
2575     if (session == NULL)
2576     {
2577 #if DEBUG_wlan
2578       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
2579                        "WLAN client not in session list: packet size = %u, inner size = %u, header size = %u\n",
2580                        ntohs (wlanheader->header.size), ntohs (temp_hdr->size),
2581                        sizeof (struct WlanHeader));
2582 #endif
2583       //try if it is a hello message
2584       if (ntohs (wlanheader->header.size) >=
2585           ntohs (temp_hdr->size) + sizeof (struct WlanHeader))
2586       {
2587         if (ntohs (temp_hdr->type) == GNUNET_MESSAGE_TYPE_HELLO)
2588         {
2589           if (GNUNET_HELLO_get_id
2590               ((const struct GNUNET_HELLO_Message *) temp_hdr,
2591                &tmpsource) == GNUNET_OK)
2592           {
2593             session = create_session (plugin, endpoint, &tmpsource);
2594           }
2595           else
2596           {
2597             GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, PLUGIN_LOG_NAME,
2598                              "WLAN client not in session list and hello message is not okay\n");
2599             return;
2600           }
2601
2602         }
2603         else
2604         {
2605           GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, PLUGIN_LOG_NAME,
2606                            "WLAN client not in session list and not a hello message\n");
2607           return;
2608         }
2609       }
2610       else
2611       {
2612         GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, PLUGIN_LOG_NAME,
2613                          "WLAN client not in session list and message size in does not fit\npacket size = %u, inner size = %u, header size = %u\n",
2614                          ntohs (wlanheader->header.size),
2615                          ntohs (temp_hdr->size), sizeof (struct WlanHeader));
2616         return;
2617       }
2618     }
2619
2620     //"receive" the message
2621
2622     if (memcmp
2623         (&wlanheader->source, &session->target,
2624          sizeof (struct GNUNET_PeerIdentity)) != 0)
2625     {
2626       //wrong peer id
2627 #if DEBUG_wlan
2628       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
2629                        "WLAN peer source id doesn't match packet peer source id: session %p\n",
2630                        session);
2631 #endif
2632       return;
2633     }
2634
2635     if (memcmp
2636         (&wlanheader->target, plugin->env->my_identity,
2637          sizeof (struct GNUNET_PeerIdentity)) != 0)
2638     {
2639       //wrong peer id
2640 #if DEBUG_wlan
2641       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
2642                        "WLAN peer target id doesn't match our peer id: session %p\n",
2643                        session);
2644 #endif
2645       return;
2646     }
2647
2648     GNUNET_SERVER_mst_receive (plugin->data_tokenizer, session,
2649                                (const char *) temp_hdr,
2650                                ntohs (hdr->size) - sizeof (struct WlanHeader),
2651                                GNUNET_YES, GNUNET_NO);
2652
2653     return;
2654   }
2655   else
2656   {
2657     GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, PLUGIN_LOG_NAME,
2658                      "wlan_data_message_handler got wrong message type: %u\n",
2659                      ntohs (hdr->size));
2660     return;
2661   }
2662 }
2663
2664 /**
2665  * function to process the a message, give it to the higher layer
2666  * @param cls pointer to the plugin
2667  * @param client pointer to the session this message belongs to
2668  * @param hdr start of the message
2669  */
2670 //TODO ATS informations
2671 static void
2672 process_data (void *cls, void *client, const struct GNUNET_MessageHeader *hdr)
2673 {
2674
2675   GNUNET_assert (client != NULL);
2676   GNUNET_assert (cls != NULL);
2677   struct Session *session = (struct Session *) client;
2678   struct Plugin *plugin = (struct Plugin *) cls;
2679
2680   struct GNUNET_ATS_Information distance;
2681
2682   distance.type = htonl (GNUNET_ATS_QUALITY_NET_DISTANCE);
2683   distance.value = htonl (1);
2684
2685 #if DEBUG_wlan
2686   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
2687                    "Calling plugin->env->receive for session %p; %s; size: %u\n",
2688                    session, wlan_plugin_address_to_string (NULL,
2689                                                            session->mac->
2690                                                            addr.mac, 6),
2691                    htons (hdr->size));
2692 #endif
2693
2694   plugin->env->receive (plugin->env->cls, &(session->target), hdr,
2695                         (const struct GNUNET_ATS_Information *)
2696                         &distance, 1, session,
2697                         (const char *) &session->mac->addr,
2698                         sizeof (session->mac->addr));
2699 }
2700
2701 /**
2702  * Function used for to process the data received from the wlan interface
2703  *
2704  * @param cls the plugin handle
2705  * @param session_light pointer to the struct holding known informations
2706  * @param hdr hdr of the GNUNET_MessageHeader
2707  * @param rxinfo pointer to the radiotap informations got with this packet
2708  */
2709 static void
2710 wlan_data_helper (void *cls, struct Session_light *session_light,
2711                   const struct GNUNET_MessageHeader *hdr,
2712                   const struct Radiotap_rx *rxinfo)
2713 {
2714   struct Plugin *plugin = cls;
2715   struct FragmentMessage *fm;
2716   struct FragmentMessage *fm2;
2717   struct GNUNET_PeerIdentity tmpsource;
2718
2719   GNUNET_assert(plugin != NULL);
2720
2721   //ADVERTISEMENT
2722   if (ntohs (hdr->type) == GNUNET_MESSAGE_TYPE_HELLO)
2723   {
2724
2725     //TODO better DOS protection, error handling
2726     //TODO test first than create session
2727     GNUNET_assert (session_light != NULL);
2728
2729 #if DEBUG_wlan
2730     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
2731                      "Func wlan_data_helper got GNUNET_MESSAGE_TYPE_HELLO size: %u; %s\n",
2732                      ntohs (hdr->size), wlan_plugin_address_to_string (NULL,
2733                                                                        session_light->addr.
2734                                                                        mac, 6));
2735 #endif
2736
2737     if (session_light->macendpoint == NULL)
2738     {
2739       session_light->macendpoint =
2740           get_macendpoint (plugin, &session_light->addr, GNUNET_YES);
2741     }
2742
2743
2744     if (GNUNET_HELLO_get_id
2745         ((const struct GNUNET_HELLO_Message *) hdr,
2746          &tmpsource) == GNUNET_OK)
2747     {
2748         session_light->session = search_session (plugin, session_light->macendpoint, &tmpsource);
2749       if (session_light->session == NULL)
2750         {
2751           session_light->session = create_session (plugin, session_light->macendpoint, &tmpsource);
2752         }
2753       GNUNET_STATISTICS_update (plugin->env->stats, _("# wlan hello messages received"), 1, GNUNET_NO);
2754       plugin->env->receive(plugin->env->cls,&session_light->session->target,hdr, NULL, 0, session_light->session,
2755           (const char *) &session_light->session->mac->addr,
2756           sizeof (session_light->session->mac->addr));
2757     }
2758     else
2759     {
2760       GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, PLUGIN_LOG_NAME,
2761                        "WLAN client not in session list and hello message is not okay\n");
2762       return;
2763     }
2764   }
2765
2766   //FRAGMENT
2767
2768   else if (ntohs (hdr->type) == GNUNET_MESSAGE_TYPE_FRAGMENT)
2769   {
2770
2771     GNUNET_assert (session_light != NULL);
2772     if (session_light->macendpoint == NULL)
2773     {
2774       session_light->macendpoint =
2775           get_macendpoint (plugin, &session_light->addr, GNUNET_YES);
2776     }
2777
2778 #if DEBUG_wlan
2779     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
2780                      "Func wlan_data_helper got GNUNET_MESSAGE_TYPE_FRAGMENT with size: %u; mac endpoint %p: %s\n",
2781                      ntohs (hdr->size), session_light->macendpoint,
2782                      wlan_plugin_address_to_string (NULL,
2783                                                     session_light->addr.mac,
2784                                                     6));
2785 #endif
2786
2787     GNUNET_STATISTICS_update (plugin->env->stats, _("# wlan fragments received"), 1, GNUNET_NO);
2788     int ret =
2789         GNUNET_DEFRAGMENT_process_fragment (session_light->macendpoint->defrag,
2790                                             hdr);
2791
2792     if (ret == GNUNET_NO)
2793     {
2794       session_light->macendpoint->dups++;
2795     }
2796     else if (ret == GNUNET_OK)
2797     {
2798       session_light->macendpoint->fragc++;
2799     }
2800     set_next_send (plugin);
2801
2802   }
2803
2804   //ACK
2805
2806   else if (ntohs (hdr->type) == GNUNET_MESSAGE_TYPE_FRAGMENT_ACK)
2807   {
2808     GNUNET_assert (session_light != NULL);
2809     if (session_light->macendpoint == NULL)
2810     {
2811       session_light->macendpoint =
2812           get_macendpoint (plugin, &session_light->addr, GNUNET_NO);
2813     }
2814
2815     if (session_light->macendpoint == NULL)
2816     {
2817 #if DEBUG_wlan
2818       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
2819                        "Macendpoint does not exist for this GNUNET_MESSAGE_TYPE_FRAGMENT_ACK size: %u; %s\n",
2820                        ntohs (hdr->size), wlan_plugin_address_to_string (NULL,
2821                                                                          session_light->addr.mac,
2822                                                                          6));
2823 #endif
2824       return;
2825     }
2826
2827 #if DEBUG_wlan
2828     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
2829                      "Func wlan_data_helper got GNUNET_MESSAGE_TYPE_FRAGMENT_ACK size: %u; mac endpoint: %p; %s\n",
2830                      ntohs (hdr->size), session_light->macendpoint,
2831                      wlan_plugin_address_to_string (NULL,
2832                                                     session_light->addr.mac,
2833                                                     6));
2834 #endif
2835     fm = session_light->macendpoint->sending_messages_head;
2836     while (fm != NULL)
2837     {
2838       fm2 = fm->next;
2839       GNUNET_STATISTICS_update (plugin->env->stats, _("# wlan acks received"), 1, GNUNET_NO);
2840       int ret = GNUNET_FRAGMENT_process_ack (fm->fragcontext, hdr);
2841
2842       if (ret == GNUNET_OK)
2843       {
2844 #if DEBUG_wlan_retransmission > 1
2845         GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
2846                          "Got last ack, finished fragment message %p\n", fm);
2847 #endif
2848         session_light->macendpoint->acks++;
2849         fm->session->last_activity = GNUNET_TIME_absolute_get ();
2850         session_light->macendpoint->last_activity = fm->session->last_activity;
2851         free_fragment_message (plugin, fm);
2852         check_fragment_queue (plugin);
2853         return;
2854       }
2855       if (ret == GNUNET_NO)
2856       {
2857 #if DEBUG_wlan_retransmission > 1
2858         GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
2859                          "Got ack for: %p\n", fm);
2860 #endif
2861         session_light->macendpoint->acks++;
2862         return;
2863       }
2864       if (ret == GNUNET_SYSERR)
2865       {
2866
2867       }
2868
2869       fm = fm2;
2870     }
2871
2872 #if DEBUG_wlan_retransmission > 1
2873     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
2874                      "WLAN fragment not in fragment list\n");
2875 #endif
2876     return;
2877
2878   }
2879   else
2880   {
2881     // TODO Wrong data?
2882     GNUNET_log_from (GNUNET_ERROR_TYPE_INFO, PLUGIN_LOG_NAME,
2883                      "WLAN packet inside the WLAN helper packet has not the right type: %u size: %u\n",
2884                      ntohs (hdr->type), ntohs (hdr->size));
2885     GNUNET_break (0);
2886     return;
2887   }
2888
2889 #if 0
2890   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
2891                    "Helper finished\n");
2892 #endif
2893
2894 }
2895
2896 /**
2897  * Function to print mac addresses nice *
2898  * @param pointer to 6 byte with the mac address
2899  * @return pointer to the chars which hold the print out
2900  */
2901 const char *
2902 macprinter (const u_int8_t * mac)
2903 {
2904   static char macstr[20];
2905
2906   GNUNET_snprintf (macstr, sizeof (macstr), "%X:%X:%X:%X:%X:%X", mac[0], mac[1],
2907                    mac[2], mac[3], mac[4], mac[5]);
2908   return macstr;
2909 }
2910
2911 /**
2912  * Function for the scheduler if a mac endpoint times out
2913  * @param cls pointer to the MacEndpoint
2914  * @param tc pointer to the GNUNET_SCHEDULER_TaskContext
2915  */
2916 static void
2917 macendpoint_timeout (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2918 {
2919   struct MacEndpoint *endpoint = cls;
2920
2921   GNUNET_assert (endpoint != NULL);
2922   endpoint->timeout_task = GNUNET_SCHEDULER_NO_TASK;
2923   if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
2924   {
2925     return;
2926   }
2927   if (GNUNET_TIME_absolute_get_remaining
2928       (GNUNET_TIME_absolute_add
2929        (endpoint->last_activity, MACENDPOINT_TIMEOUT)).rel_value == 0)
2930   {
2931     GNUNET_assert(endpoint->plugin != NULL);
2932     GNUNET_STATISTICS_update (endpoint->plugin->env->stats, _("# wlan mac endpoints timeouts"), 1, GNUNET_NO);
2933     free_macendpoint (endpoint->plugin, endpoint);
2934   }
2935   else
2936   {
2937     endpoint->timeout_task =
2938         GNUNET_SCHEDULER_add_delayed (MACENDPOINT_TIMEOUT, &macendpoint_timeout,
2939                                       endpoint);
2940   }
2941 }
2942
2943 /**
2944  * function to create an macendpoint
2945  * @param plugin pointer to the plugin struct
2946  * @param addr pointer to the macaddress
2947  * @return returns a macendpoint
2948  */
2949 static struct MacEndpoint *
2950 create_macendpoint (struct Plugin *plugin, const struct MacAddress *addr)
2951 {
2952   struct MacEndpoint *newend = GNUNET_malloc (sizeof (struct MacEndpoint));
2953
2954   GNUNET_assert(plugin != NULL);
2955   GNUNET_STATISTICS_update (plugin->env->stats, _("# wlan mac endpoints created"), 1, GNUNET_NO);
2956   newend->addr = *addr;
2957   newend->plugin = plugin;
2958   newend->addr = *addr;
2959   newend->fragment_messages_out_count = 0;
2960   newend->defrag =
2961       GNUNET_DEFRAGMENT_context_create (plugin->env->stats, WLAN_MTU,
2962                                         MESSAGES_IN_DEFRAG_QUEUE_PER_MAC,
2963                                         newend, &wlan_data_message_handler,
2964                                         &add_ack_for_send);
2965   newend->last_activity = GNUNET_TIME_absolute_get ();
2966   newend->timeout_task =
2967       GNUNET_SCHEDULER_add_delayed (MACENDPOINT_TIMEOUT, &macendpoint_timeout,
2968                                     newend);
2969
2970   plugin->mac_count++;
2971   GNUNET_STATISTICS_set(plugin->env->stats, _("# wlan mac endpoints"), plugin->mac_count, GNUNET_NO);
2972   GNUNET_CONTAINER_DLL_insert_tail (plugin->mac_head, plugin->mac_tail, newend);
2973 #if DEBUG_wlan
2974   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
2975                    "New Mac Endpoint %p: %s\n", newend,
2976                    wlan_plugin_address_to_string (NULL, newend->addr.mac, 6));
2977 #endif
2978   return newend;
2979 }
2980
2981 /**
2982  * Function used for to process the data from the suid process
2983  *
2984  * @param cls the plugin handle
2985  * @param client client that send the data (not used)
2986  * @param hdr header of the GNUNET_MessageHeader
2987  */
2988 static void
2989 wlan_process_helper (void *cls, void *client,
2990                      const struct GNUNET_MessageHeader *hdr)
2991 {
2992   struct Plugin *plugin = cls;
2993   struct ieee80211_frame *wlanIeeeHeader = NULL;
2994   struct Session_light *session_light = NULL;
2995   struct Radiotap_rx *rxinfo;
2996   const struct GNUNET_MessageHeader *temp_hdr = NULL;
2997
2998   int datasize = 0;
2999   int pos;
3000
3001   GNUNET_assert(plugin != NULL);
3002   switch (ntohs (hdr->type))
3003   {
3004   case GNUNET_MESSAGE_TYPE_WLAN_HELPER_DATA:
3005 #if DEBUG_wlan
3006     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
3007                      "Func wlan_process_helper got GNUNET_MESSAGE_TYPE_WLAN_HELPER_DATA size: %u\n",
3008                      ntohs (hdr->size));
3009 #endif
3010
3011     GNUNET_STATISTICS_update (plugin->env->stats, _("# wlan WLAN_HELPER_DATA received"), 1, GNUNET_NO);
3012     //call wlan_process_helper with the message inside, later with wlan: analyze signal
3013     if (ntohs (hdr->size) <
3014         sizeof (struct ieee80211_frame) + 2*sizeof (struct GNUNET_MessageHeader) +
3015         sizeof (struct Radiotap_rx))
3016     {
3017 #if DEBUG_wlan
3018       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
3019                        "Size of packet is too small; size: %u min size: %u\n",
3020                        ntohs (hdr->size),
3021                        sizeof (struct ieee80211_frame) +
3022                        sizeof (struct GNUNET_MessageHeader));
3023 #endif
3024       //GNUNET_break (0);
3025       /* FIXME: restart SUID process */
3026       return;
3027     }
3028
3029     rxinfo = (struct Radiotap_rx *) &hdr[1];
3030     wlanIeeeHeader = (struct ieee80211_frame *) &rxinfo[1];
3031
3032     //process only if it is an broadcast or for this computer both with the gnunet bssid
3033
3034     //check for bssid
3035     if (memcmp
3036         (&(wlanIeeeHeader->i_addr3), &mac_bssid,
3037          sizeof (struct MacAddress)) == 0)
3038     {
3039       //check for broadcast or mac
3040       if ((memcmp
3041           (&(wlanIeeeHeader->i_addr1), &bc_all_mac,
3042            sizeof (struct MacAddress)) == 0) ||
3043           (memcmp (&(wlanIeeeHeader->i_addr1), &(plugin->mac_address),
3044                   sizeof (struct MacAddress)) == 0))
3045       {
3046           //if packet is from us return
3047           if ((memcmp (&(wlanIeeeHeader->i_addr2), &(plugin->mac_address),
3048                   sizeof (struct MacAddress)) == 0)){
3049               return;
3050           }
3051         // process the inner data
3052
3053
3054         datasize =
3055             ntohs (hdr->size) - sizeof (struct ieee80211_frame) -
3056             sizeof (struct GNUNET_MessageHeader) - sizeof (struct Radiotap_rx);
3057
3058         session_light = GNUNET_malloc (sizeof (struct Session_light));
3059         memcpy (&session_light->addr, &(wlanIeeeHeader->i_addr2),
3060                 sizeof (struct MacAddress));
3061         //session_light->session = search_session(plugin,session_light->addr);
3062         GNUNET_STATISTICS_update (plugin->env->stats, _("# wlan messaged for this client received"), 1, GNUNET_NO);
3063
3064         pos = 0;
3065         while (pos < datasize)
3066         {
3067           temp_hdr = (struct GNUNET_MessageHeader *) &wlanIeeeHeader[1] + pos;
3068           if (ntohs(temp_hdr->size) <= datasize + pos)
3069             {
3070               GNUNET_STATISTICS_update (plugin->env->stats, _("# wlan messaged inside WLAN_HELPER_DATA received"), 1, GNUNET_NO);
3071               wlan_data_helper (plugin, session_light, temp_hdr, rxinfo);
3072             }
3073           else
3074             {
3075 #if DEBUG_wlan
3076             GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
3077                        "Size of packet is too small; size: %u > size of packet: %u\n",
3078                        ntohs(temp_hdr->size),datasize + pos);
3079 #endif
3080             }
3081           pos += ntohs (temp_hdr->size);
3082
3083         }
3084
3085         //clean up
3086         GNUNET_free (session_light);
3087       }
3088       else
3089       {
3090 #if DEBUG_wlan
3091         GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
3092                          "Func wlan_process_helper got wrong MAC: %s\n",
3093                          macprinter (wlanIeeeHeader->i_addr1));
3094 #endif
3095       }
3096     }
3097     else
3098     {
3099 #if DEBUG_wlan
3100       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
3101                        "Func wlan_process_helper got wrong BSSID: %s\n",
3102                        macprinter (wlanIeeeHeader->i_addr2));
3103 #endif
3104     }
3105     break;
3106   case GNUNET_MESSAGE_TYPE_WLAN_HELPER_CONTROL:
3107     //TODO more control messages
3108     if (ntohs (hdr->size) != sizeof (struct Wlan_Helper_Control_Message))
3109     {
3110       GNUNET_break (0);
3111       /* FIXME: restart SUID process */
3112       return;
3113     }
3114     memcpy (&plugin->mac_address, &hdr[1], sizeof (struct MacAddress));
3115 #if DEBUG_wlan
3116     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
3117                      "Received WLAN_HELPER_CONTROL message with transport of address %s\n",
3118                      wlan_plugin_address_to_string (cls, &plugin->mac_address,
3119                                                     sizeof (struct
3120                                                             MacAddress)));
3121 #endif
3122     plugin->env->notify_address (plugin->env->cls, GNUNET_YES,
3123                                  &plugin->mac_address,
3124                                  sizeof (struct MacAddress));
3125     break;
3126   default:
3127 #if DEBUG_wlan
3128     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
3129                      "Func wlan_process_helper got unknown message with number %u, size %u\n",
3130                      ntohs (hdr->type), ntohs (hdr->size));
3131
3132 #endif
3133 #if DEBUG_wlan_msg_dump > 1
3134     hexdump (hdr, GNUNET_MIN (ntohs (hdr->size), 256));
3135 #endif
3136     GNUNET_break (0);
3137     return;
3138   }
3139 }
3140
3141 /**
3142  * Exit point from the plugin.
3143  * @param cls pointer to the api struct
3144  */
3145
3146 //FIXME cleanup
3147 void *
3148 libgnunet_plugin_transport_wlan_done (void *cls)
3149 {
3150   struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
3151   struct Plugin *plugin = api->cls;
3152   struct MacEndpoint *endpoint = plugin->mac_head;
3153   struct MacEndpoint *endpoint_next;
3154
3155 #if DEBUG_wlan
3156   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
3157                    "libgnunet_plugin_transport_wlan_done started\n");
3158 #endif
3159
3160   wlan_transport_stop_wlan_helper(plugin);
3161
3162   GNUNET_assert (cls != NULL);
3163   //free sessions
3164   while (endpoint != NULL)
3165   {
3166     endpoint_next = endpoint->next;
3167     free_macendpoint (plugin, endpoint);
3168     endpoint = endpoint_next;
3169
3170   }
3171
3172
3173   if (plugin->suid_tokenizer != NULL)
3174     GNUNET_SERVER_mst_destroy (plugin->suid_tokenizer);
3175
3176   if (plugin->data_tokenizer != NULL)
3177     GNUNET_SERVER_mst_destroy (plugin->data_tokenizer);
3178
3179   GNUNET_free_non_null (plugin->interface);
3180   GNUNET_free (plugin);
3181   GNUNET_free (api);
3182   return NULL;
3183 }
3184
3185 /**
3186  * Entry point for the plugin.
3187  *
3188  * @param cls closure, the 'struct GNUNET_TRANSPORT_PluginEnvironment*'
3189  * @return the 'struct GNUNET_TRANSPORT_PluginFunctions*' or NULL on error
3190  */
3191 void *
3192 libgnunet_plugin_transport_wlan_init (void *cls)
3193 {
3194   //struct GNUNET_SERVICE_Context *service;
3195   struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
3196   struct GNUNET_TRANSPORT_PluginFunctions *api;
3197   struct Plugin *plugin;
3198
3199   GNUNET_assert (cls != NULL);
3200
3201   plugin = GNUNET_malloc (sizeof (struct Plugin));
3202   plugin->env = env;
3203   plugin->pendingsessions = 0;
3204   GNUNET_STATISTICS_set(plugin->env->stats, _("# wlan pending sessions"), plugin->pendingsessions, GNUNET_NO);
3205   plugin->mac_count = 0;
3206   GNUNET_STATISTICS_set(plugin->env->stats, _("# wlan mac endpoints"), plugin->mac_count, GNUNET_NO);
3207   plugin->server_write_task = GNUNET_SCHEDULER_NO_TASK;
3208   plugin->server_read_task = GNUNET_SCHEDULER_NO_TASK;
3209   plugin->server_write_delay_task = GNUNET_SCHEDULER_NO_TASK;
3210   GNUNET_BANDWIDTH_tracker_init (&plugin->tracker,
3211                                  GNUNET_BANDWIDTH_value_init (100 * 1024 *
3212                                                               1024 / 8), 100);
3213
3214   plugin->suid_tokenizer =
3215       GNUNET_SERVER_mst_create (&wlan_process_helper, plugin);
3216
3217   plugin->data_tokenizer = GNUNET_SERVER_mst_create (&process_data, plugin);
3218
3219   //plugin->sessions = GNUNET_malloc (sizeof (struct Sessionqueue));
3220   //plugin->pending_Sessions_head = GNUNET_malloc (sizeof (struct Sessionqueue));
3221
3222   api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
3223   api->cls = plugin;
3224   api->send = &wlan_plugin_send;
3225   api->disconnect = &wlan_plugin_disconnect;
3226   api->address_pretty_printer = &wlan_plugin_address_pretty_printer;
3227   api->check_address = &wlan_plugin_address_suggested;
3228   api->address_to_string = &wlan_plugin_address_to_string;
3229
3230   //read config
3231
3232   if (GNUNET_CONFIGURATION_have_value (env->cfg, "transport-wlan", "TESTMODE"))
3233   {
3234     if (GNUNET_SYSERR ==
3235         GNUNET_CONFIGURATION_get_value_number (env->cfg, "transport-wlan",
3236                                                "TESTMODE", &(plugin->testmode)))
3237       plugin->testmode = 0;             //default value
3238   }
3239
3240   if (GNUNET_CONFIGURATION_have_value (env->cfg, "transport-wlan", "INTERFACE"))
3241   {
3242     if (GNUNET_CONFIGURATION_get_value_string
3243         (env->cfg, "transport-wlan", "INTERFACE",
3244          &(plugin->interface)) != GNUNET_YES)
3245     {
3246       libgnunet_plugin_transport_wlan_done (api);
3247       return NULL;
3248     }
3249   }
3250
3251   //start the plugin
3252   wlan_transport_start_wlan_helper (plugin);
3253   set_next_beacon_time (plugin);
3254   set_next_send(plugin);
3255 #if DEBUG_wlan
3256   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
3257                    "wlan init finished\n");
3258 #endif
3259
3260   return api;
3261 }
3262
3263 /* end of plugin_transport_wlan.c */