9976ae65b6b50f0734365523997d8126d7291f58
[oweals/gnunet.git] / src / transport / plugin_transport_wlan.c
1 /*
2  This file is part of GNUnet
3  (C) 2010 2011 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
741       t += sprintf (t, j % 2 ? " " : "-");
742     }
743
744     t += sprintf (t, "  ");
745     for (j = 0; j < 16; j++)
746     {
747       if (i + j < length)
748       {
749         if (isprint ((unsigned char) src[j]))
750           t += sprintf (t, "%c", src[j]);
751         else
752           t += sprintf (t, ".");
753       }
754       else
755       {
756         t += sprintf (t, " ");
757       }
758     }
759
760     t += sprintf (t, "\r\n");
761     printf ("%s", line);
762   }
763 }
764
765 /**
766  * Function to find a MacEndpoint with a specific mac addr
767  * @param plugin pointer to the plugin struct
768  * @param addr pointer to the mac address
769  * @param create_new GNUNET_YES if a new end point should be created
770  * @return
771  */
772 static struct MacEndpoint *
773 get_macendpoint (struct Plugin *plugin, const struct MacAddress *addr,
774                  int create_new)
775 {
776   struct MacEndpoint *queue = plugin->mac_head;
777
778   while (queue != NULL)
779   {
780     //GNUNET_assert (queue->sessions_head != NULL);
781     if (memcmp (addr, &queue->addr, sizeof (struct MacAddress)) == 0)
782       return queue;             /* session found */
783     queue = queue->next;
784   }
785
786   if (create_new == GNUNET_YES)
787   {
788     return create_macendpoint (plugin, addr);
789   }
790   else
791   {
792     return NULL;
793   }
794
795 }
796
797 /**
798  * search for a session with the macendpoint and peer id
799  *
800  * @param plugin pointer to the plugin struct
801  * @param endpoint pointer to the mac endpoint of the peer
802  * @param peer pointer to the peerid
803  * @return returns the session
804  */
805 static struct Session *
806 search_session (struct Plugin *plugin, const struct MacEndpoint *endpoint,
807                 const struct GNUNET_PeerIdentity *peer)
808 {
809   GNUNET_assert (endpoint != NULL);
810   struct Sessionqueue *queue = endpoint->sessions_head;
811
812   while (queue != NULL)
813   {
814     GNUNET_assert (queue->content != NULL);
815     if (memcmp
816         (peer, &queue->content->target,
817          sizeof (struct GNUNET_PeerIdentity)) == 0)
818       return queue->content;    /* session found */
819     queue = queue->next;
820   }
821   return NULL;
822 }
823
824 /**
825  * Function called for a quick conversion of the binary address to
826  * a numeric address.  Note that the caller must not free the
827  * address and that the next call to this function is allowed
828  * to override the address again.
829  *
830  * @param cls closure
831  * @param addr binary address
832  * @param addrlen length of the address
833  * @return string representing the same address
834  */
835 static const char *
836 wlan_plugin_address_to_string (void *cls, const void *addr, size_t addrlen)
837 {
838   static char ret[40];
839   const struct MacAddress *mac;
840
841   if (addrlen != sizeof (struct MacAddress))
842   {
843     GNUNET_break (0);
844     return NULL;
845   }
846   mac = addr;
847   GNUNET_snprintf (ret, sizeof (ret), "%s Mac-Address %X:%X:%X:%X:%X:%X",
848                    PROTOCOL_PREFIX, mac->mac[0], mac->mac[1], mac->mac[2],
849                    mac->mac[3], mac->mac[4], mac->mac[5]);
850
851   return ret;
852 }
853
854 /**
855  * Function for the scheduler if a session times out
856  * @param cls pointer to the Sessionqueue
857  * @param tc pointer to the GNUNET_SCHEDULER_TaskContext
858  */
859 static void
860 session_timeout (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
861 {
862   struct Sessionqueue *queue = cls;
863
864   GNUNET_assert (queue != NULL);
865   GNUNET_assert(queue->content != NULL);
866   queue->content->timeout_task = GNUNET_SCHEDULER_NO_TASK;
867   if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
868   {
869     return;
870   }
871   if (GNUNET_TIME_absolute_get_remaining
872       (GNUNET_TIME_absolute_add
873        (queue->content->last_activity, SESSION_TIMEOUT)).rel_value == 0)
874   {
875
876     GNUNET_assert(queue->content->mac != NULL);
877     GNUNET_assert(queue->content->mac->plugin != NULL);
878     GNUNET_STATISTICS_update (queue->content->mac->plugin->env->stats, _("# wlan session timeouts"), 1, GNUNET_NO);
879     free_session (queue->content->mac->plugin, queue, GNUNET_YES);
880   }
881   else
882   {
883     queue->content->timeout_task =
884         GNUNET_SCHEDULER_add_delayed (SESSION_TIMEOUT, &session_timeout, queue);
885   }
886 }
887
888 /**
889  * create a new session
890  *
891  * @param plugin pointer to the plugin struct
892  * @param endpoint pointer to the mac endpoint of the peer
893  * @param peer peer identity to use for this session
894  * @return returns the session
895  */
896
897 static struct Session *
898 create_session (struct Plugin *plugin, struct MacEndpoint *endpoint,
899                 const struct GNUNET_PeerIdentity *peer)
900 {
901   GNUNET_assert (endpoint != NULL);
902   GNUNET_assert (plugin != NULL);
903   GNUNET_STATISTICS_update (plugin->env->stats, _("# wlan session created"), 1, GNUNET_NO);
904   struct Sessionqueue *queue =
905       GNUNET_malloc (sizeof (struct Sessionqueue) + sizeof (struct Session));
906
907   GNUNET_CONTAINER_DLL_insert_tail (endpoint->sessions_head,
908                                     endpoint->sessions_tail, queue);
909
910   queue->content = (struct Session *) &queue[1];
911   queue->content->mac = endpoint;
912   memcpy (&(queue->content->target), peer, sizeof (struct GNUNET_PeerIdentity));
913   queue->content->last_activity = GNUNET_TIME_absolute_get ();
914   queue->content->timeout_task =
915       GNUNET_SCHEDULER_add_delayed (SESSION_TIMEOUT, &session_timeout, queue);
916
917 #if DEBUG_wlan
918   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
919                    "New session %p with endpoint %p: %s\n", queue->content,
920                    endpoint, wlan_plugin_address_to_string (NULL,
921                                                             endpoint->addr.mac,
922                                                             6));
923 #endif
924
925   return queue->content;
926 }
927
928 /**
929  * Get session from address, create if no session exists
930  *
931  * @param plugin pointer to the plugin struct
932  * @param addr pointer to the mac address of the peer
933  * @param peer pointer to the peerid
934  * @return returns the session
935  */
936 static struct Session *
937 get_session (struct Plugin *plugin, const struct MacAddress *addr,
938              const struct GNUNET_PeerIdentity *peer)
939 {
940   struct MacEndpoint *mac;
941
942   mac = get_macendpoint (plugin, addr, GNUNET_YES);
943   struct Session *session = search_session (plugin, mac, peer);
944
945   if (session != NULL)
946     return session;
947   return create_session (plugin, mac, peer);
948 }
949
950 /**
951  * Queue the session to send data
952  * checks if there is a message pending
953  * checks if this session is not allready in the queue
954  * @param plugin pointer to the plugin
955  * @param session pointer to the session to add
956  */
957 static void
958 queue_session (struct Plugin *plugin, struct Session *session)
959 {
960   struct Sessionqueue *queue = plugin->pending_Sessions_head;
961
962   if (session->pending_message_head != NULL)
963   {
964     while (queue != NULL)
965     {
966       // content is never NULL
967       GNUNET_assert (queue->content != NULL);
968       // is session already in queue?
969       if (session == queue->content)
970       {
971         return;
972       }
973       // try next
974       queue = queue->next;
975     }
976
977     // Session is not in the queue
978
979     queue = GNUNET_malloc (sizeof (struct Sessionqueue));
980     queue->content = session;
981
982     //insert at the tail
983     GNUNET_CONTAINER_DLL_insert_tail (plugin->pending_Sessions_head,
984                                       plugin->pending_Sessions_tail, queue);
985     plugin->pendingsessions++;
986     GNUNET_STATISTICS_set(plugin->env->stats, _("# wlan pending sessions"), plugin->pendingsessions, GNUNET_NO);
987   }
988
989 }
990
991 /**
992  * Function to schedule the write task, executed after a delay
993  * @param cls pointer to the plugin struct
994  * @param tc GNUNET_SCHEDULER_TaskContext pointer
995  */
996 static void
997 delay_fragment_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
998 {
999   struct Plugin *plugin = cls;
1000
1001   plugin->server_write_delay_task = GNUNET_SCHEDULER_NO_TASK;
1002
1003   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1004     return;
1005
1006   // GNUNET_TIME_UNIT_FOREVER_REL is needed to clean up old msg
1007   if (plugin->server_write_task == GNUNET_SCHEDULER_NO_TASK)
1008   {
1009     plugin->server_write_task =
1010         GNUNET_SCHEDULER_add_write_file (GNUNET_TIME_UNIT_FOREVER_REL,
1011                                          plugin->server_stdin_handle,
1012                                          &do_transmit, plugin);
1013   }
1014 }
1015
1016 /**
1017  * Function to calculate the time of the next periodic "hello-beacon"
1018  * @param plugin pointer to the plugin struct
1019  */
1020
1021 static void
1022 set_next_beacon_time (struct Plugin *const plugin)
1023 {
1024   //under 10 known peers: once a second
1025   if (plugin->mac_count < 10)
1026   {
1027     plugin->beacon_time =
1028         GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get (),
1029                                   GNUNET_TIME_relative_multiply
1030                                   (GNUNET_TIME_UNIT_SECONDS,
1031                                    HELLO_BEACON_SCALING_FACTOR));
1032   }
1033   //under 30 known peers: every 10 seconds
1034   else if (plugin->mac_count < 30)
1035   {
1036     plugin->beacon_time =
1037         GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get (),
1038                                   GNUNET_TIME_relative_multiply
1039                                   (GNUNET_TIME_UNIT_SECONDS,
1040                                    10 * HELLO_BEACON_SCALING_FACTOR));
1041   }
1042   //over 30 known peers: once a minute
1043   else
1044   {
1045     plugin->beacon_time =
1046         GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get (),
1047                                   GNUNET_TIME_relative_multiply
1048                                   (GNUNET_TIME_UNIT_MINUTES,
1049                                    HELLO_BEACON_SCALING_FACTOR));
1050   }
1051 }
1052
1053 /**
1054  * Function to set the timer for the next timeout of the fragment queue
1055  * @param plugin the handle to the plugin struct
1056  */
1057
1058 static void
1059 set_next_send (struct Plugin *const plugin)
1060 {
1061   struct GNUNET_TIME_Relative next_send;
1062
1063   //cancel old task
1064   if (plugin->server_write_delay_task != GNUNET_SCHEDULER_NO_TASK)
1065   {
1066     GNUNET_SCHEDULER_cancel (plugin->server_write_delay_task);
1067     plugin->server_write_delay_task = GNUNET_SCHEDULER_NO_TASK;
1068   }
1069
1070   //check if some acks are in the queue
1071   if (plugin->ack_send_queue_head != NULL)
1072   {
1073     next_send = GNUNET_TIME_UNIT_ZERO;
1074   }
1075
1076   //check if there are some fragments in the queue
1077   else if (plugin->sending_messages_head != NULL)
1078   {
1079     next_send = GNUNET_TIME_UNIT_ZERO;
1080   }
1081   else
1082   {
1083     next_send = GNUNET_TIME_absolute_get_remaining (plugin->beacon_time);
1084   }
1085
1086 #if DEBUG_wlan
1087   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
1088                    "Next packet is send in: %u\n", next_send.rel_value);
1089 #endif
1090
1091   if (next_send.rel_value == GNUNET_TIME_UNIT_ZERO.rel_value)
1092   {
1093     if (plugin->server_write_task == GNUNET_SCHEDULER_NO_TASK)
1094     {
1095       plugin->server_write_task =
1096           GNUNET_SCHEDULER_add_write_file (GNUNET_TIME_UNIT_FOREVER_REL,
1097                                            plugin->server_stdin_handle,
1098                                            &do_transmit, plugin);
1099     }
1100   }
1101   else
1102   {
1103     if (plugin->server_write_delay_task == GNUNET_SCHEDULER_NO_TASK)
1104     {
1105       plugin->server_write_delay_task =
1106           GNUNET_SCHEDULER_add_delayed (next_send, &delay_fragment_task,
1107                                         plugin);
1108     }
1109   }
1110 }
1111
1112 /**
1113  * Function to get the next queued Session, removes the session from the queue
1114  * @param plugin pointer to the plugin struct
1115  * @return pointer to the session found, returns NULL if there is now session in the queue
1116  */
1117 static struct Session *
1118 get_next_queue_session (struct Plugin *plugin)
1119 {
1120   struct Session *session;
1121   struct Sessionqueue *sessionqueue;
1122   struct Sessionqueue *sessionqueue_alt;
1123   struct PendingMessage *pm;
1124
1125   sessionqueue = plugin->pending_Sessions_head;
1126
1127   while (sessionqueue != NULL)
1128   {
1129     session = sessionqueue->content;
1130
1131     GNUNET_assert (session != NULL);
1132     pm = session->pending_message_head;
1133
1134     if (pm == NULL)
1135         {
1136 #if DEBUG_wlan
1137           GNUNET_log_from(GNUNET_ERROR_TYPE_ERROR, PLUGIN_LOG_NAME,
1138               "pending message is empty, should not happen. session %p\n",
1139               session);
1140 #endif
1141           sessionqueue_alt = sessionqueue;
1142           sessionqueue = sessionqueue->next;
1143           plugin->pendingsessions--;
1144           GNUNET_STATISTICS_set(plugin->env->stats, _("# wlan pending sessions"), plugin->pendingsessions, GNUNET_NO);
1145           GNUNET_CONTAINER_DLL_remove (plugin->pending_Sessions_head,
1146               plugin->pending_Sessions_tail,
1147               sessionqueue_alt);
1148
1149           GNUNET_free (sessionqueue_alt);
1150           continue;
1151
1152         }
1153
1154     //check for message timeout
1155     if (GNUNET_TIME_absolute_get_remaining (pm->timeout).rel_value > 0)
1156     {
1157       //check if session has no message in the fragment queue
1158       if ((session->mac->fragment_messages_out_count <
1159            FRAGMENT_QUEUE_MESSAGES_OUT_PER_MACENDPOINT) &&
1160           (session->fragment_messages_out_count <
1161            FRAGMENT_QUEUE_MESSAGES_OUT_PER_SESSION))
1162       {
1163         plugin->pendingsessions--;
1164         GNUNET_STATISTICS_set(plugin->env->stats, _("# wlan pending sessions"), plugin->pendingsessions, GNUNET_NO);
1165         GNUNET_CONTAINER_DLL_remove (plugin->pending_Sessions_head,
1166                                      plugin->pending_Sessions_tail,
1167                                      sessionqueue);
1168         GNUNET_free (sessionqueue);
1169
1170         return session;
1171       }
1172       else
1173       {
1174         sessionqueue = sessionqueue->next;
1175       }
1176     }
1177     else
1178     {
1179       GNUNET_CONTAINER_DLL_remove (session->pending_message_head,
1180                                    session->pending_message_tail, pm);
1181
1182       //call the cont func that it did not work
1183       if (pm->transmit_cont != NULL)
1184         pm->transmit_cont (pm->transmit_cont_cls, &(session->target),
1185                            GNUNET_SYSERR);
1186       GNUNET_free (pm->msg);
1187       GNUNET_free (pm);
1188
1189       if (session->pending_message_head == NULL)
1190       {
1191         sessionqueue_alt = sessionqueue;
1192         sessionqueue = sessionqueue->next;
1193         plugin->pendingsessions--;
1194         GNUNET_STATISTICS_set(plugin->env->stats, _("# wlan pending sessions"), plugin->pendingsessions, GNUNET_NO);
1195         GNUNET_CONTAINER_DLL_remove (plugin->pending_Sessions_head,
1196                                      plugin->pending_Sessions_tail,
1197                                      sessionqueue_alt);
1198
1199         GNUNET_free (sessionqueue_alt);
1200       }
1201     }
1202
1203   }
1204   return NULL;
1205 }
1206
1207 /**
1208  * frees the space of a message in the fragment queue (send queue)
1209  * @param plugin the plugin struct
1210  * @param fm message to free
1211  */
1212 static void
1213 free_fragment_message (struct Plugin *plugin, struct FragmentMessage *fm)
1214 {
1215   struct Session *session = fm->session;
1216   struct MacEndpoint *endpoint = session->mac;
1217   struct FragmentMessage_queue *fmq;
1218   struct FragmentMessage_queue *fmq_next;
1219
1220   if (fm != NULL)
1221   {
1222     fmq = plugin->sending_messages_head;
1223     while (fmq != NULL)
1224     {
1225       fmq_next = fmq->next;
1226       if (fmq->content == fm)
1227       {
1228         GNUNET_CONTAINER_DLL_remove (plugin->sending_messages_head,
1229                                      plugin->sending_messages_tail, fmq);
1230         GNUNET_free (fmq);
1231       }
1232       fmq = fmq_next;
1233     }
1234
1235     (session->mac->fragment_messages_out_count)--;
1236     session->fragment_messages_out_count--;
1237     plugin->pending_Fragment_Messages--;
1238     GNUNET_STATISTICS_set(plugin->env->stats, _("# wlan pending fragments"), plugin->pending_Fragment_Messages, GNUNET_NO);
1239     GNUNET_CONTAINER_DLL_remove (endpoint->sending_messages_head,
1240                                  endpoint->sending_messages_tail, fm);
1241     GNUNET_FRAGMENT_context_destroy (fm->fragcontext);
1242     if (fm->timeout_task != GNUNET_SCHEDULER_NO_TASK){
1243         GNUNET_SCHEDULER_cancel (fm->timeout_task);
1244         fm->timeout_task = GNUNET_SCHEDULER_NO_TASK;
1245     }
1246
1247     GNUNET_free (fm);
1248
1249     queue_session (plugin, session);
1250 #if DEBUG_wlan
1251     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
1252                      "Free pending fragment messages %p, session %p\n", fm,
1253                      session);
1254 #endif
1255   }
1256 }
1257
1258 /**
1259  * function to fill the radiotap header
1260  * @param plugin pointer to the plugin struct
1261  * @param endpoint pointer to the endpoint
1262  * @param header pointer to the radiotap header
1263  * @return GNUNET_YES at success
1264  */
1265 static int
1266 getRadiotapHeader (struct Plugin *plugin, struct MacEndpoint *endpoint,
1267                    struct Radiotap_Send *header)
1268 {
1269
1270   if (endpoint != NULL)
1271   {
1272     header->rate = endpoint->rate;
1273     header->tx_power = endpoint->tx_power;
1274     header->antenna = endpoint->antenna;
1275   }
1276   else
1277   {
1278     header->rate = 255;
1279     header->tx_power = 0;
1280     header->antenna = 0;
1281   }
1282
1283   return GNUNET_YES;
1284 }
1285
1286 /**
1287  * function to generate the wlan hardware header for one packet
1288  * @param Header address to write the header to
1289  * @param to_mac_addr address of the recipient
1290  * @param plugin pointer to the plugin struct
1291  * @param size size of the whole packet, needed to calculate the time to send the packet
1292  * @return GNUNET_YES if there was no error
1293  */
1294 static int
1295 getWlanHeader (struct ieee80211_frame *Header,
1296                const struct MacAddress *to_mac_addr, struct Plugin *plugin,
1297                unsigned int size)
1298 {
1299   uint16_t *tmp16;
1300   const int rate = 11000000;
1301
1302   Header->i_fc[0] = IEEE80211_FC0_TYPE_DATA;
1303   Header->i_fc[1] = 0x00;
1304   memcpy (&Header->i_addr3, &mac_bssid, sizeof (mac_bssid));
1305   memcpy (&Header->i_addr2, plugin->mac_address.mac,
1306           sizeof (plugin->mac_address));
1307   memcpy (&Header->i_addr1, to_mac_addr, sizeof (struct MacAddress));
1308
1309   tmp16 = (uint16_t *) Header->i_dur;
1310   *tmp16 = (uint16_t) htole16 ((size * 1000000) / rate + 290);
1311   Header->llc[0] = WLAN_LLC_DSAP_FIELD;
1312   Header->llc[1] = WLAN_LLC_SSAP_FIELD;
1313
1314 #if DEBUG_wlan_ip_udp_packets_on_air > 1
1315   uint crc = 0;
1316   uint16_t *x;
1317   int count;
1318
1319   Header->ip.ip_dst.s_addr = *((uint32_t *) & to_mac_addr->mac[2]);
1320   Header->ip.ip_src.s_addr = *((uint32_t *) & plugin->mac_address.mac[2]);
1321   Header->ip.ip_v = 4;
1322   Header->ip.ip_hl = 5;
1323   Header->ip.ip_p = 17;
1324   Header->ip.ip_ttl = 1;
1325   Header->ip.ip_len = htons (size + 8);
1326   Header->ip.ip_sum = 0;
1327   x = (uint16_t *) & Header->ip;
1328   count = sizeof (struct iph);
1329   while (count > 1)
1330   {
1331     /* This is the inner loop */
1332     crc += (unsigned short) *x++;
1333     count -= 2;
1334   }
1335   /* Add left-over byte, if any */
1336   if (count > 0)
1337     crc += *(unsigned char *) x;
1338   crc = (crc & 0xffff) + (crc >> 16);
1339   Header->ip.ip_sum = htons (~(unsigned short) crc);
1340   Header->udp.len = htons (size - sizeof (struct ieee80211_frame));
1341
1342 #endif
1343
1344   return GNUNET_YES;
1345 }
1346
1347 /**
1348  * 32bit CRC
1349  *
1350  * @param msgbuf pointer tor the data
1351  * @param msgbuf_size size of the data
1352  *
1353  * @return 32bit crc value
1354  */
1355
1356 uint32_t
1357 getcrc32 (const char *msgbuf, size_t msgbuf_size)
1358 {
1359
1360   return GNUNET_CRYPTO_crc32_n (msgbuf, msgbuf_size);;
1361 }
1362
1363 /**
1364  * 16bit CRC
1365  *
1366  * @param msgbuf pointer tor the data
1367  * @param msgbuf_size size of the data
1368  *
1369  * @return 16bit crc value
1370  */
1371
1372 uint16_t
1373 getcrc16 (const char *msgbuf, size_t msgbuf_size)
1374 {
1375   //TODO calc some crc
1376   return 0;
1377 }
1378
1379 /**
1380  * function to add a fragment of a message to send
1381  * @param cls FragmentMessage this message belongs to
1382  * @param hdr pointer to the start of the message
1383  */
1384
1385 void
1386 add_message_for_send (void *cls, const struct GNUNET_MessageHeader *hdr)
1387 {
1388
1389   struct FragmentMessage *fm = cls;
1390   struct FragmentMessage_queue *fmqueue;
1391
1392   GNUNET_assert (cls != NULL);
1393   GNUNET_assert (fm->frag == NULL);
1394   struct MacEndpoint *endpoint = fm->session->mac;
1395   struct Plugin *plugin = endpoint->plugin;
1396   struct GNUNET_MessageHeader *msgheader;
1397   struct GNUNET_MessageHeader *msgheader2;
1398   uint16_t size;
1399
1400 #if DEBUG_wlan_retransmission > 1
1401   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
1402                    "Adding fragment of message %p to send, session %p, endpoint %p, type %u\n",
1403                    fm, fm->session, endpoint, hdr->type);
1404 #endif
1405
1406   size =
1407       sizeof (struct GNUNET_MessageHeader) + sizeof (struct Radiotap_Send) +
1408       sizeof (struct ieee80211_frame) + ntohs (hdr->size);
1409   fm->frag = GNUNET_malloc (size);
1410   fm->size = size;
1411
1412   msgheader = (struct GNUNET_MessageHeader *) fm->frag;
1413   msgheader->size = htons (size);
1414   msgheader->type = htons (GNUNET_MESSAGE_TYPE_WLAN_HELPER_DATA);
1415
1416   fm->radioHeader = (struct Radiotap_Send *) &msgheader[1];
1417   fm->ieeewlanheader = (struct ieee80211_frame *) &fm->radioHeader[1];
1418   msgheader2 = (struct GNUNET_MessageHeader *) &fm->ieeewlanheader[1];
1419   memcpy (msgheader2, hdr, ntohs (hdr->size));
1420
1421   fmqueue = GNUNET_malloc (sizeof (struct FragmentMessage_queue));
1422   fmqueue->content = fm;
1423
1424   GNUNET_CONTAINER_DLL_insert_tail (plugin->sending_messages_head,
1425                                     plugin->sending_messages_tail, fmqueue);
1426   set_next_send (plugin);
1427 }
1428
1429
1430 /**
1431  * We have been notified that wlan-helper has written something to stdout.
1432  * Handle the output, then reschedule this function to be called again once
1433  * more is available.
1434  *
1435  * @param cls the plugin handle
1436  * @param tc the scheduling context
1437  */
1438 static void
1439 wlan_plugin_helper_read (void *cls,
1440                          const struct GNUNET_SCHEDULER_TaskContext *tc)
1441 {
1442   struct Plugin *plugin = cls;
1443
1444   plugin->server_read_task = GNUNET_SCHEDULER_NO_TASK;
1445
1446   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1447     return;
1448
1449   char mybuf[WLAN_MTU + sizeof (struct GNUNET_MessageHeader)];
1450   ssize_t bytes;
1451
1452   bytes =
1453       GNUNET_DISK_file_read (plugin->server_stdout_handle, mybuf,
1454                              sizeof (mybuf));
1455   if (bytes <= 0)
1456   {
1457 #if DEBUG_wlan
1458     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
1459                      _
1460                      ("Finished reading from wlan-helper stdout with code: %d\n"),
1461                      bytes);
1462 #endif
1463     return;
1464   }
1465   GNUNET_SERVER_mst_receive (plugin->suid_tokenizer, NULL, mybuf, bytes,
1466                              GNUNET_NO, GNUNET_NO);
1467
1468   GNUNET_assert (plugin->server_read_task == GNUNET_SCHEDULER_NO_TASK);
1469   plugin->server_read_task =
1470       GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL,
1471                                       plugin->server_stdout_handle,
1472                                       &wlan_plugin_helper_read, plugin);
1473 }
1474
1475 /**
1476  * Start the gnunet-wlan-helper process.
1477  *
1478  * @param plugin the transport plugin
1479  * @return GNUNET_YES if process was started, GNUNET_SYSERR on error
1480  */
1481 static int
1482 wlan_transport_start_wlan_helper (struct Plugin *plugin)
1483 {
1484   const char *filenamehw = "gnunet-transport-wlan-helper";
1485   char *filenameloopback = "gnunet-transport-wlan-helper-dummy";
1486   char *absolute_filename = NULL;
1487
1488   plugin->server_stdout = GNUNET_DISK_pipe (GNUNET_YES, GNUNET_NO, GNUNET_YES);
1489   if (plugin->server_stdout == NULL)
1490     return GNUNET_SYSERR;
1491
1492   plugin->server_stdin = GNUNET_DISK_pipe (GNUNET_YES, GNUNET_YES, GNUNET_NO);
1493   if (plugin->server_stdin == NULL)
1494     return GNUNET_SYSERR;
1495
1496   if ((plugin->testmode == 1) || (plugin->testmode == 2))
1497   {
1498     if (GNUNET_OS_check_helper_binary (filenameloopback) == GNUNET_YES)
1499     {
1500       absolute_filename = strdup (filenameloopback);
1501     }
1502     else
1503     {
1504       char cwd[FILENAME_MAX];
1505       GNUNET_assert (getcwd(cwd, sizeof(cwd)) != NULL);
1506
1507       GNUNET_asprintf (&absolute_filename, "%s%s%s", cwd, DIR_SEPARATOR_STR, filenameloopback);
1508
1509       if (GNUNET_DISK_file_test (filenameloopback) != GNUNET_YES)
1510       {
1511         GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, PLUGIN_LOG_NAME,
1512                          "Helper `%s' not found! %i\n", absolute_filename);
1513         GNUNET_break(0);
1514       }
1515     }
1516   }
1517
1518   /* Start the server process */
1519
1520   if (plugin->testmode == 0)
1521   {
1522
1523 #if DEBUG_wlan
1524     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
1525                      "Starting gnunet-wlan-helper process cmd: %s %s %i\n",
1526                      filenamehw, plugin->interface, plugin->testmode);
1527 #endif
1528
1529     if (GNUNET_OS_check_helper_binary (filenamehw) == GNUNET_YES)
1530     {
1531       plugin->server_proc =
1532           GNUNET_OS_start_process (plugin->server_stdin, plugin->server_stdout,
1533                                    filenamehw, filenamehw, plugin->interface,
1534                                    NULL);
1535     }
1536     else if (GNUNET_OS_check_helper_binary (filenamehw) == GNUNET_NO)
1537     {
1538       GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, PLUGIN_LOG_NAME,
1539                        "gnunet-transport-wlan-helper is not suid, please change it or look at the doku\n");
1540       GNUNET_break (0);
1541     }
1542     else
1543     {
1544       GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, PLUGIN_LOG_NAME,
1545                        "gnunet-transport-wlan-helper not found, please look if it exists and is the $PATH variable!\n");
1546       GNUNET_break (0);
1547     }
1548
1549   }
1550   else if (plugin->testmode == 1)
1551   {
1552
1553 #if DEBUG_wlan
1554 #endif
1555     GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, PLUGIN_LOG_NAME,
1556                      "Starting gnunet-wlan-helper loopback 1 process cmd: %s %s %i\n",
1557                      absolute_filename, plugin->interface, plugin->testmode);
1558
1559     plugin->server_proc = GNUNET_OS_start_process (plugin->server_stdin, plugin->server_stdout,
1560                                   absolute_filename, absolute_filename, "1",
1561                                   NULL);
1562     if (plugin->server_proc == NULL)
1563     {
1564     GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, PLUGIN_LOG_NAME,
1565                      "`%s' not found, please look if it exists and is in the $PATH variable!\n", absolute_filename);
1566     GNUNET_break (0);
1567     }
1568   }
1569   else if (plugin->testmode == 2)
1570   {
1571 #if DEBUG_wlan
1572 #endif
1573     GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, PLUGIN_LOG_NAME,
1574                      "Starting gnunet-wlan-helper loopback 2 process cmd: %s %s %i\n",
1575                      absolute_filename, plugin->interface, plugin->testmode);
1576
1577
1578       plugin->server_proc = GNUNET_OS_start_process (plugin->server_stdin, plugin->server_stdout,
1579                                    absolute_filename, absolute_filename, "2",
1580                                    NULL);
1581       if (plugin->server_proc == NULL)
1582       {
1583         GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, PLUGIN_LOG_NAME,
1584                          "`%s' not found, please look if it exists and is in the $PATH variable!\n", absolute_filename);
1585       GNUNET_break (0);
1586       }
1587   }
1588   if (absolute_filename != NULL)
1589     GNUNET_free(absolute_filename);
1590   if (plugin->server_proc == NULL)
1591   {
1592 #if DEBUG_wlan
1593     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
1594                      "Failed to start gnunet-wlan-helper process\n");
1595 #endif
1596     return GNUNET_SYSERR;
1597   }
1598
1599
1600
1601   /* Close the write end of the read pipe */
1602   GNUNET_DISK_pipe_close_end (plugin->server_stdout,
1603                               GNUNET_DISK_PIPE_END_WRITE);
1604
1605   /* Close the read end of the write pipe */
1606   GNUNET_DISK_pipe_close_end (plugin->server_stdin, GNUNET_DISK_PIPE_END_READ);
1607
1608   plugin->server_stdout_handle =
1609       GNUNET_DISK_pipe_handle (plugin->server_stdout,
1610                                GNUNET_DISK_PIPE_END_READ);
1611   plugin->server_stdin_handle =
1612       GNUNET_DISK_pipe_handle (plugin->server_stdin,
1613                                GNUNET_DISK_PIPE_END_WRITE);
1614
1615   GNUNET_assert (plugin->server_read_task == GNUNET_SCHEDULER_NO_TASK);
1616
1617 #if DEBUG_wlan
1618   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
1619                    "Adding server_read_task for the wlan-helper\n");
1620 #endif
1621
1622   plugin->server_read_task =
1623       GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL,
1624                                       plugin->server_stdout_handle,
1625                                       &wlan_plugin_helper_read, plugin);
1626
1627   return GNUNET_YES;
1628 }
1629
1630 /**
1631  * Stops the gnunet-wlan-helper process.
1632  *
1633  * @param plugin the transport plugin
1634  * @return GNUNET_YES if process was started, GNUNET_SYSERR on error
1635  */
1636 static int
1637 wlan_transport_stop_wlan_helper (struct Plugin *plugin)
1638 {
1639 #if DEBUG_wlan
1640     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
1641                      "Stoping WLAN helper process\n");
1642 #endif
1643
1644   if (plugin->server_write_delay_task != GNUNET_SCHEDULER_NO_TASK)
1645   {
1646     GNUNET_SCHEDULER_cancel (plugin->server_write_delay_task);
1647     plugin->server_write_delay_task = GNUNET_SCHEDULER_NO_TASK;
1648   }
1649
1650   if (plugin->server_write_task != GNUNET_SCHEDULER_NO_TASK)
1651   {
1652     GNUNET_SCHEDULER_cancel (plugin->server_write_task);
1653     plugin->server_write_task = GNUNET_SCHEDULER_NO_TASK;
1654   }
1655
1656   if (plugin->server_read_task != GNUNET_SCHEDULER_NO_TASK)
1657   {
1658     GNUNET_SCHEDULER_cancel (plugin->server_read_task);
1659     plugin->server_read_task = GNUNET_SCHEDULER_NO_TASK;
1660   }
1661
1662   GNUNET_DISK_pipe_close (plugin->server_stdout);
1663   GNUNET_DISK_pipe_close (plugin->server_stdin);
1664   GNUNET_OS_process_kill (plugin->server_proc, SIGKILL);
1665   GNUNET_OS_process_wait(plugin->server_proc);
1666   GNUNET_OS_process_close (plugin->server_proc);
1667
1668   return GNUNET_YES;
1669 }
1670
1671 /**
1672  * function for delayed restart of the helper process
1673  * @param cls Finish_send struct if message should be finished
1674  * @param tc TaskContext
1675  */
1676 static void
1677 delay_restart_helper (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1678 {
1679   struct Finish_send *finish = cls;
1680   struct Plugin *plugin;
1681   plugin = finish->plugin;
1682
1683   plugin->server_write_task = GNUNET_SCHEDULER_NO_TASK;
1684   if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
1685   {
1686     GNUNET_free_non_null(finish->msgstart);
1687     GNUNET_free (finish);
1688     return;
1689   }
1690
1691   wlan_transport_start_wlan_helper(plugin);
1692
1693   if (finish->size != 0)
1694     {
1695       plugin->server_write_task =
1696                       GNUNET_SCHEDULER_add_write_file (GNUNET_TIME_UNIT_FOREVER_REL,
1697                                                        plugin->server_stdin_handle,
1698                                                        &finish_sending, finish);
1699     }
1700   else
1701     {
1702       set_next_send (plugin);
1703       GNUNET_free_non_null(finish->msgstart);
1704       GNUNET_free (finish);
1705     }
1706
1707 }
1708
1709 /**
1710  * Function to restart the helper
1711  * @param plugin pointer to the global plugin struct
1712  * @param finish pointer to the Finish_send struct to finish
1713  */
1714 static void
1715 restart_helper(struct Plugin *plugin, struct Finish_send *finish)
1716 {
1717   static struct GNUNET_TIME_Relative next_try = {1000};
1718   GNUNET_assert(finish != NULL);
1719
1720   wlan_transport_stop_wlan_helper(plugin);
1721   plugin->server_write_task = GNUNET_SCHEDULER_add_delayed (next_try, &delay_restart_helper, finish);
1722   GNUNET_TIME_relative_multiply(next_try, HELPER_RESTART_SCALING_FACTOR);
1723
1724 }
1725
1726 /**
1727  * function to finish a sending if not all could have been writen befor
1728  * @param cls pointer to the Finish_send struct
1729  * @param tc TaskContext
1730  */
1731 static void
1732 finish_sending (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1733 {
1734   struct Finish_send *finish = cls;
1735   struct Plugin *plugin;
1736   ssize_t bytes;
1737
1738   plugin = finish->plugin;
1739   plugin->server_write_task = GNUNET_SCHEDULER_NO_TASK;
1740
1741   if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
1742   {
1743     GNUNET_free (finish->msgstart);
1744     GNUNET_free (finish);
1745     return;
1746   }
1747   bytes =
1748       GNUNET_DISK_file_write (plugin->server_stdin_handle, finish->head_of_next_write,
1749                               finish->size);
1750
1751   if (bytes != finish->size)
1752   {
1753     if (bytes != GNUNET_SYSERR)
1754       {
1755       finish->head_of_next_write += bytes;
1756       finish->size -= bytes;
1757       plugin->server_write_task =
1758           GNUNET_SCHEDULER_add_write_file (GNUNET_TIME_UNIT_FOREVER_REL,
1759                                            plugin->server_stdin_handle,
1760                                            &finish_sending, finish);
1761       }
1762     else
1763       {
1764        restart_helper(plugin, finish);
1765       }
1766   }
1767   else
1768   {
1769     GNUNET_free (finish->msgstart);
1770     GNUNET_free (finish);
1771     set_next_send (plugin);
1772   }
1773 }
1774
1775 /**
1776  * function to send a hello beacon
1777  * @param plugin pointer to the plugin struct
1778  */
1779 static void
1780 send_hello_beacon (struct Plugin *plugin)
1781 {
1782
1783 #if DEBUG_wlan
1784   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
1785                    "Sending hello beacon\n");
1786 #endif
1787
1788   uint16_t size;
1789   ssize_t bytes;
1790   uint16_t hello_size;
1791   struct GNUNET_MessageHeader *msgheader;
1792   struct ieee80211_frame *ieeewlanheader;
1793   struct Radiotap_Send *radioHeader;
1794   struct GNUNET_MessageHeader *msgheader2;
1795   const struct GNUNET_MessageHeader *hello;
1796   struct Finish_send * finish;
1797
1798   GNUNET_assert (plugin != NULL);
1799
1800   GNUNET_STATISTICS_update (plugin->env->stats, _("# wlan hello beacons send"), 1, GNUNET_NO);
1801
1802   hello = plugin->env->get_our_hello ();
1803   hello_size = GNUNET_HELLO_size ((struct GNUNET_HELLO_Message *) hello);
1804   GNUNET_assert (sizeof (struct WlanHeader) + hello_size <= WLAN_MTU);
1805   size =
1806       sizeof (struct GNUNET_MessageHeader) + sizeof (struct Radiotap_Send) +
1807       sizeof (struct ieee80211_frame) + hello_size;
1808
1809   msgheader = GNUNET_malloc (size);
1810   msgheader->size = htons (size);
1811   msgheader->type = htons (GNUNET_MESSAGE_TYPE_WLAN_HELPER_DATA);
1812
1813   radioHeader = (struct Radiotap_Send *) &msgheader[1];
1814   getRadiotapHeader (plugin, NULL, radioHeader);
1815   ieeewlanheader = (struct ieee80211_frame *) &radioHeader[1];
1816   getWlanHeader (ieeewlanheader, &bc_all_mac, plugin, size);
1817
1818   msgheader2 = (struct GNUNET_MessageHeader *) &ieeewlanheader[1];
1819   /*msgheader2->size =
1820       htons (GNUNET_HELLO_size ((struct GNUNET_HELLO_Message *) hello) +
1821              sizeof (struct GNUNET_MessageHeader));
1822
1823   msgheader2->type = htons (GNUNET_MESSAGE_TYPE_WLAN_ADVERTISEMENT);*/
1824   memcpy (msgheader2, hello, hello_size);
1825
1826   bytes = GNUNET_DISK_file_write (plugin->server_stdin_handle, msgheader, size);
1827
1828   if (bytes == GNUNET_SYSERR)
1829   {
1830     GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, PLUGIN_LOG_NAME,
1831                      _
1832                      ("Error writing to wlan healper. errno == %d, ERROR: %s\n"),
1833                      errno, strerror (errno));
1834     finish = GNUNET_malloc (sizeof (struct Finish_send));
1835     finish->plugin = plugin;
1836     finish->head_of_next_write = NULL;
1837     finish->size = 0;
1838     finish->msgstart = NULL;
1839     restart_helper(plugin, finish);
1840
1841     set_next_beacon_time (plugin);
1842
1843   }
1844   else
1845     {
1846     GNUNET_assert (bytes == size);
1847     set_next_beacon_time (plugin);
1848     set_next_send (plugin);
1849     }
1850   GNUNET_free (msgheader);
1851
1852
1853 }
1854
1855 /**
1856  * function to add an ack to send it for a received fragment
1857  * @param cls MacEndpoint this ack belongs to
1858  * @param msg_id id of the message
1859  * @param hdr pointer to the hdr where the ack is stored
1860  *
1861  */
1862
1863 static void
1864 add_ack_for_send (void *cls, uint32_t msg_id,
1865                   const struct GNUNET_MessageHeader *hdr)
1866 {
1867
1868   struct AckSendQueue *ack;
1869
1870   GNUNET_assert (cls != NULL);
1871   struct MacEndpoint *endpoint = cls;
1872   struct Plugin *plugin = endpoint->plugin;
1873   struct GNUNET_MessageHeader *msgheader;
1874   struct GNUNET_MessageHeader *msgheader2;
1875   uint16_t size;
1876
1877   size =
1878       sizeof (struct GNUNET_MessageHeader) + sizeof (struct Radiotap_Send) +
1879       sizeof (struct ieee80211_frame) + ntohs (hdr->size) +
1880       sizeof (struct AckSendQueue);
1881
1882   ack = GNUNET_malloc (size);
1883   ack->message_id = msg_id;
1884   ack->endpoint = endpoint;
1885
1886   size =
1887       sizeof (struct GNUNET_MessageHeader) + sizeof (struct Radiotap_Send) +
1888       sizeof (struct ieee80211_frame) + ntohs (hdr->size);
1889
1890   msgheader = (struct GNUNET_MessageHeader *) &ack[1];
1891   ack->hdr = (struct GNUNET_MessageHeader *) &ack[1];
1892   msgheader->size = htons (size);
1893   msgheader->type = htons (GNUNET_MESSAGE_TYPE_WLAN_HELPER_DATA);
1894
1895   ack->radioHeader = (struct Radiotap_Send *) &msgheader[1];
1896   ack->ieeewlanheader = (struct ieee80211_frame *) &(ack->radioHeader)[1];
1897   msgheader2 = (struct GNUNET_MessageHeader *) &(ack->ieeewlanheader)[1];
1898   memcpy (msgheader2, hdr, ntohs (hdr->size));
1899
1900   GNUNET_CONTAINER_DLL_insert_tail (plugin->ack_send_queue_head,
1901                                     plugin->ack_send_queue_tail, ack);
1902
1903 #if DEBUG_wlan_retransmission > 1
1904   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
1905                    "Adding ack with message id %u to send, AckSendQueue %p, endpoint %p\n",
1906                    msg_id, ack, endpoint);
1907 #endif
1908
1909   set_next_send (plugin);
1910 }
1911
1912 /**
1913  * Function for the scheduler if a FragmentMessage times out
1914  * @param cls pointer to the FragmentMessage
1915  * @param tc pointer to the GNUNET_SCHEDULER_TaskContext
1916  */
1917 static void
1918 fragmentmessage_timeout (void *cls,
1919                          const struct GNUNET_SCHEDULER_TaskContext *tc)
1920 {
1921   struct FragmentMessage *fm = cls;
1922
1923   GNUNET_assert (fm != NULL);
1924   fm->timeout_task = GNUNET_SCHEDULER_NO_TASK;
1925   if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
1926   {
1927     return;
1928   }
1929   free_fragment_message (fm->session->mac->plugin, fm);
1930 }
1931
1932 /**
1933  * Function to check if there is some space in the fragment queue
1934  * inserts a message if space is available
1935  * @param plugin the plugin struct
1936  */
1937
1938 static void
1939 check_fragment_queue (struct Plugin *plugin)
1940 {
1941   struct Session *session;
1942   struct FragmentMessage *fm;
1943   struct GNUNET_PeerIdentity pid;
1944
1945   struct PendingMessage *pm;
1946
1947   if (plugin->pending_Fragment_Messages < FRAGMENT_QUEUE_SIZE)
1948   {
1949     session = get_next_queue_session (plugin);
1950     if (session != NULL)
1951     {
1952       pm = session->pending_message_head;
1953       GNUNET_assert (pm != NULL);
1954       GNUNET_CONTAINER_DLL_remove (session->pending_message_head,
1955                                    session->pending_message_tail, pm);
1956       session->mac->fragment_messages_out_count++;
1957       session->fragment_messages_out_count++;
1958       plugin->pending_Fragment_Messages++;
1959       GNUNET_STATISTICS_set(plugin->env->stats, _("# wlan pending fragments"), plugin->pending_Fragment_Messages, GNUNET_NO);
1960
1961       fm = GNUNET_malloc (sizeof (struct FragmentMessage));
1962       fm->session = session;
1963       fm->timeout.abs_value = pm->timeout.abs_value;
1964       fm->frag = NULL;
1965       fm->fragcontext =
1966           GNUNET_FRAGMENT_context_create (plugin->env->stats, WLAN_MTU,
1967                                           &plugin->tracker,
1968                                           GNUNET_TIME_UNIT_SECONDS,
1969                                           &(pm->msg->header),
1970                                           &add_message_for_send, fm);
1971       fm->timeout_task =
1972           GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_absolute_get_remaining
1973                                         (fm->timeout), fragmentmessage_timeout,
1974                                         fm);
1975       GNUNET_CONTAINER_DLL_insert_tail (session->mac->sending_messages_head,
1976                                         session->mac->sending_messages_tail,
1977                                         fm);
1978
1979       if (pm->transmit_cont != NULL)
1980       {
1981         pid = session->target;
1982         pm->transmit_cont (pm->transmit_cont_cls, &pid, GNUNET_OK);
1983 #if DEBUG_wlan
1984         GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
1985                          "called pm->transmit_cont for %p\n", session);
1986 #endif
1987       }
1988       else
1989       {
1990 #if DEBUG_wlan
1991         GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
1992                          "no pm->transmit_cont for %p\n", session);
1993 #endif
1994       }
1995       GNUNET_free (pm);
1996
1997       if (session->pending_message_head != NULL)
1998       {
1999         //requeue session
2000         queue_session (plugin, session);
2001       }
2002
2003     }
2004   }
2005
2006   //check if timeout changed
2007   set_next_send (plugin);
2008 }
2009
2010 /**
2011  * Function to send an ack, does not free the ack
2012  * @param plugin pointer to the plugin
2013  */
2014 static void
2015 send_ack (struct Plugin *plugin)
2016 {
2017
2018   ssize_t bytes;
2019   struct AckSendQueue *ack;
2020   struct Finish_send * finish;
2021
2022   ack = plugin->ack_send_queue_head;
2023
2024
2025 #if DEBUG_wlan
2026   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
2027                    "Sending ack for message_id %u for mac endpoint %p, size %u\n",
2028                    ack->message_id, ack->endpoint,
2029                    ntohs (ack->hdr->size) - sizeof (struct Radiotap_Send));
2030 #endif
2031
2032   GNUNET_assert (plugin != NULL);
2033   GNUNET_STATISTICS_update (plugin->env->stats, _("# wlan acks send"), 1, GNUNET_NO);
2034
2035   getRadiotapHeader (plugin, ack->endpoint, ack->radioHeader);
2036   getWlanHeader (ack->ieeewlanheader, &ack->endpoint->addr, plugin,
2037                  ntohs (ack->hdr->size));
2038
2039   bytes =
2040       GNUNET_DISK_file_write (plugin->server_stdin_handle, ack->hdr,
2041                               ntohs (ack->hdr->size));
2042   if (bytes == GNUNET_SYSERR)
2043   {
2044     GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, PLUGIN_LOG_NAME,
2045                      _
2046                      ("Error writing to wlan healper. errno == %d, ERROR: %s\n"),
2047                      errno, strerror (errno));
2048     finish = GNUNET_malloc (sizeof (struct Finish_send));
2049     finish->plugin = plugin;
2050     finish->head_of_next_write = NULL;
2051     finish->size = 0;
2052     finish->msgstart = NULL;
2053     restart_helper(plugin, finish);
2054   }
2055   else
2056   {
2057     GNUNET_assert (bytes == ntohs (ack->hdr->size));
2058     GNUNET_CONTAINER_DLL_remove (plugin->ack_send_queue_head,
2059                                  plugin->ack_send_queue_tail, ack);
2060     GNUNET_free (ack);
2061     set_next_send (plugin);
2062   }
2063 }
2064
2065 /**
2066  * Function called when wlan helper is ready to get some data
2067  *
2068  * @param cls closure
2069  * @param tc GNUNET_SCHEDULER_TaskContext
2070  */
2071 static void
2072 do_transmit (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2073 {
2074   struct Plugin *plugin = cls;
2075   GNUNET_assert (plugin != NULL);
2076
2077   plugin->server_write_task = GNUNET_SCHEDULER_NO_TASK;
2078   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
2079     return;
2080
2081   struct Session *session;
2082   struct FragmentMessage *fm;
2083   struct Finish_send *finish;
2084   struct FragmentMessage_queue *fmq;
2085   ssize_t bytes;
2086
2087   if (plugin->ack_send_queue_head != NULL)
2088   {
2089     send_ack (plugin);
2090     return;
2091   }
2092
2093   //test if a "hello-beacon" has to be send
2094   if (GNUNET_TIME_absolute_get_remaining (plugin->beacon_time).rel_value == 0)
2095   {
2096     send_hello_beacon (plugin);
2097     return;
2098   }
2099
2100   if (plugin->sending_messages_head != NULL)
2101   {
2102     GNUNET_STATISTICS_update (plugin->env->stats, _("# wlan fragments send"), 1, GNUNET_NO);
2103
2104     fmq = plugin->sending_messages_head;
2105     fm = fmq->content;
2106     GNUNET_CONTAINER_DLL_remove (plugin->sending_messages_head,
2107                                  plugin->sending_messages_tail, fmq);
2108     GNUNET_free (fmq);
2109
2110     session = fm->session;
2111     GNUNET_assert (session != NULL);
2112
2113 #if DEBUG_wlan
2114     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
2115                      "Sending GNUNET_MESSAGE_TYPE_WLAN_FRAGMENT for fragment message %p, size: %u\n",
2116                      fm, fm->size);
2117 #endif
2118
2119     getRadiotapHeader (plugin, session->mac, fm->radioHeader);
2120     getWlanHeader (fm->ieeewlanheader, &(fm->session->mac->addr), plugin,
2121                    fm->size);
2122
2123     bytes =
2124         GNUNET_DISK_file_write (plugin->server_stdin_handle, fm->frag,
2125                                 fm->size);
2126
2127
2128     if (bytes != fm->size)
2129     {
2130       finish = GNUNET_malloc (sizeof (struct Finish_send));
2131       finish->plugin = plugin;
2132       finish->msgstart = (struct GNUNET_MessageHeader *) fm->frag;
2133       GNUNET_assert (plugin->server_write_task == GNUNET_SCHEDULER_NO_TASK);
2134
2135       if (bytes == GNUNET_SYSERR)
2136       {
2137         GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, PLUGIN_LOG_NAME,
2138                          _
2139                          ("Error writing to wlan healper. errno == %d, ERROR: %s\n"),
2140                          errno, strerror (errno));
2141
2142         finish->head_of_next_write = fm->frag;
2143         finish->size = fm->size;
2144         restart_helper(plugin, finish);
2145       }
2146       else
2147       {
2148         finish->head_of_next_write = fm->frag + bytes;
2149         finish->size = fm->size - bytes;
2150         plugin->server_write_task =
2151                   GNUNET_SCHEDULER_add_write_file (GNUNET_TIME_UNIT_FOREVER_REL,
2152                                                    plugin->server_stdin_handle,
2153                                                    &finish_sending, finish);
2154       }
2155
2156       fm->frag = NULL;
2157     }
2158     else
2159     {
2160       GNUNET_free (fm->frag);
2161       fm->frag = NULL;
2162       set_next_send (plugin);
2163     }
2164     GNUNET_FRAGMENT_context_transmission_done (fm->fragcontext);
2165     return;
2166   }
2167
2168   GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, PLUGIN_LOG_NAME,
2169                    "do_transmit did nothing, should not happen!\n");
2170 }
2171
2172 /**
2173  * Another peer has suggested an address for this
2174  * peer and transport plugin.  Check that this could be a valid
2175  * address.  If so, consider adding it to the list
2176  * of addresses.
2177  *
2178  * @param cls closure
2179  * @param addr pointer to the address
2180  * @param addrlen length of addr
2181  * @return GNUNET_OK if this is a plausible address for this peer
2182  *         and transport
2183  */
2184 static int
2185 wlan_plugin_address_suggested (void *cls, const void *addr, size_t addrlen)
2186 {
2187   //struct Plugin *plugin = cls;
2188
2189   /* check if the address is plausible; if so,
2190    * add it to our list! */
2191
2192   GNUNET_assert (cls != NULL);
2193   //FIXME mitm is not checked
2194   //Mac Address has 6 bytes
2195   if (addrlen == 6)
2196   {
2197     /* TODO check for bad addresses like multicast, broadcast, etc */
2198 #if DEBUG_wlan
2199     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
2200                          "wlan_plugin_address_suggested got good address, size %u!\n", addrlen);
2201 #endif
2202     return GNUNET_OK;
2203   }
2204 #if DEBUG_wlan
2205     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
2206                          "wlan_plugin_address_suggested got bad address, size %u!\n", addrlen);
2207 #endif
2208   return GNUNET_SYSERR;
2209 }
2210
2211 /**
2212  * Function that can be used by the transport service to transmit
2213  * a message using the plugin.
2214  *
2215  * @param cls closure
2216  * @param target who should receive this message
2217  * @param priority how important is the message
2218  * @param msgbuf the message to transmit
2219  * @param msgbuf_size number of bytes in 'msgbuf'
2220  * @param timeout when should we time out
2221  * @param session which session must be used (or NULL for "any")
2222  * @param addr the address to use (can be NULL if the plugin
2223  *                is "on its own" (i.e. re-use existing TCP connection))
2224  * @param addrlen length of the address in bytes
2225  * @param force_address GNUNET_YES if the plugin MUST use the given address,
2226  *                otherwise the plugin may use other addresses or
2227  *                existing connections (if available)
2228  * @param cont continuation to call once the message has
2229  *        been transmitted (or if the transport is ready
2230  *        for the next transmission call; or if the
2231  *        peer disconnected...)
2232  * @param cont_cls closure for cont
2233  * @return number of bytes used (on the physical network, with overheads);
2234  *         -1 on hard errors (i.e. address invalid); 0 is a legal value
2235  *         and does NOT mean that the message was not transmitted (DV)
2236  */
2237 static ssize_t
2238 wlan_plugin_send (void *cls, const struct GNUNET_PeerIdentity *target,
2239                   const char *msgbuf, size_t msgbuf_size, unsigned int priority,
2240                   struct GNUNET_TIME_Relative timeout, struct Session *session,
2241                   const void *addr, size_t addrlen, int force_address,
2242                   GNUNET_TRANSPORT_TransmitContinuation cont, void *cont_cls)
2243 {
2244   struct Plugin *plugin = cls;
2245   struct PendingMessage *newmsg;
2246   struct WlanHeader *wlanheader;
2247   GNUNET_assert (plugin != NULL);
2248   //check if msglen > 0
2249   GNUNET_assert (msgbuf_size > 0);
2250
2251   //get session if needed
2252   if (session == NULL)
2253   {
2254     if (wlan_plugin_address_suggested (plugin, addr, addrlen) == GNUNET_OK)
2255     {
2256       session = get_session (plugin, addr, target);
2257     }
2258     else
2259     {
2260       GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, PLUGIN_LOG_NAME,
2261                        _("Wlan Address len %d is wrong\n"), addrlen);
2262       return -1;
2263     }
2264   }
2265
2266   GNUNET_STATISTICS_update (plugin->env->stats, _("# wlan messages queued"), 1, GNUNET_NO);
2267
2268   //queue message:
2269
2270   //queue message in session
2271   //test if there is no other message in the "queue"
2272   //FIXME: to many send requests
2273   if (session->pending_message_head != NULL)
2274   {
2275     newmsg = session->pending_message_head;
2276     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
2277                      "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",
2278                      GNUNET_TIME_absolute_get_remaining (newmsg->
2279                                                          timeout).rel_value,
2280                      session->mac->fragment_messages_out_count);
2281   }
2282
2283   newmsg = GNUNET_malloc (sizeof (struct PendingMessage));
2284   newmsg->msg = GNUNET_malloc (msgbuf_size + sizeof (struct WlanHeader));
2285   wlanheader = newmsg->msg;
2286   //copy msg to buffer, not fragmented / segmented yet, but with message header
2287   wlanheader->header.size = htons (msgbuf_size + sizeof (struct WlanHeader));
2288   wlanheader->header.type = htons (GNUNET_MESSAGE_TYPE_WLAN_DATA);
2289   memcpy (&(wlanheader->target), target, sizeof (struct GNUNET_PeerIdentity));
2290   memcpy (&(wlanheader->source), plugin->env->my_identity,
2291           sizeof (struct GNUNET_PeerIdentity));
2292   wlanheader->crc = 0;
2293   memcpy (&wlanheader[1], msgbuf, msgbuf_size);
2294   wlanheader->crc =
2295       htonl (getcrc32
2296              ((char *) wlanheader, msgbuf_size + sizeof (struct WlanHeader)));
2297   //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);
2298   //hexdump(newmsg->msg, msgbuf_size + sizeof(struct WlanHeader));
2299
2300   newmsg->transmit_cont = cont;
2301   newmsg->transmit_cont_cls = cont_cls;
2302   newmsg->timeout = GNUNET_TIME_relative_to_absolute (timeout);
2303
2304   newmsg->timeout.abs_value = newmsg->timeout.abs_value - 500;
2305
2306   newmsg->message_size = msgbuf_size + sizeof (struct WlanHeader);
2307
2308   GNUNET_CONTAINER_DLL_insert_tail (session->pending_message_head,
2309                                     session->pending_message_tail, newmsg);
2310
2311 #if DEBUG_wlan
2312   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
2313                    "New message for %p with size (incl wlan header) %u added\n",
2314                    session, newmsg->message_size);
2315 #endif
2316 #if DEBUG_wlan_msg_dump > 1
2317   hexdump (msgbuf, GNUNET_MIN (msgbuf_size, 256));
2318 #endif
2319   //queue session
2320   queue_session (plugin, session);
2321
2322   check_fragment_queue (plugin);
2323   //FIXME not the correct size
2324   return msgbuf_size;
2325
2326 }
2327
2328 /**
2329  * function to free a mac endpoint
2330  * @param plugin pointer to the plugin struct
2331  * @param endpoint pointer to the MacEndpoint to free
2332  */
2333 static void
2334 free_macendpoint (struct Plugin *plugin, struct MacEndpoint *endpoint)
2335 {
2336   struct Sessionqueue *sessions;
2337   struct Sessionqueue *sessions_next;
2338
2339   GNUNET_assert (endpoint != NULL);
2340
2341   sessions = endpoint->sessions_head;
2342   while (sessions != NULL)
2343   {
2344     sessions_next = sessions->next;
2345     free_session (plugin, sessions, GNUNET_NO);
2346     sessions = sessions_next;
2347   }
2348
2349   GNUNET_CONTAINER_DLL_remove (plugin->mac_head, plugin->mac_tail, endpoint);
2350   if (endpoint->timeout_task != GNUNET_SCHEDULER_NO_TASK)
2351   {
2352     GNUNET_SCHEDULER_cancel (endpoint->timeout_task);
2353     endpoint->timeout_task = GNUNET_SCHEDULER_NO_TASK;
2354   }
2355   plugin->mac_count--;
2356   GNUNET_STATISTICS_set(plugin->env->stats, _("# wlan mac endpoints"), plugin->mac_count, GNUNET_NO);
2357   GNUNET_free (endpoint);
2358
2359 }
2360
2361 /**
2362  * function to free a session
2363  * @param plugin pointer to the plugin
2364  * @param queue pointer to the sessionqueue element to free
2365  * @param free_macendpoint if GNUNET_YES and mac endpoint would be empty, free mac endpoint
2366  */
2367 static void
2368 free_session (struct Plugin *plugin, struct Sessionqueue *queue,
2369               int do_free_macendpoint)
2370 {
2371   struct Sessionqueue *pendingsession;
2372   struct Sessionqueue *pendingsession_tmp;
2373   struct PendingMessage *pm;
2374   struct MacEndpoint *endpoint;
2375   struct FragmentMessage *fm;
2376   struct FragmentMessage *fmnext;
2377   int check = 0;
2378
2379   GNUNET_assert (plugin != NULL);
2380   GNUNET_assert (queue != NULL);
2381   GNUNET_assert (queue->content != NULL);
2382
2383   //session found
2384   //is this session pending for send
2385   pendingsession = plugin->pending_Sessions_head;
2386   while (pendingsession != NULL)
2387   {
2388     pendingsession_tmp = pendingsession;
2389     pendingsession = pendingsession->next;
2390     GNUNET_assert (pendingsession_tmp->content != NULL);
2391     if (pendingsession_tmp->content == queue->content)
2392     {
2393       plugin->pendingsessions--;
2394       GNUNET_STATISTICS_set(plugin->env->stats, _("# wlan pending sessions"), plugin->pendingsessions, GNUNET_NO);
2395       GNUNET_CONTAINER_DLL_remove (plugin->pending_Sessions_head,
2396                                    plugin->pending_Sessions_tail,
2397                                    pendingsession_tmp);
2398       GNUNET_free (pendingsession_tmp);
2399
2400       GNUNET_assert (check == 0);
2401       check = 1;
2402     }
2403   }
2404
2405   endpoint = queue->content->mac;
2406   fm = endpoint->sending_messages_head;
2407   while (fm != NULL)
2408   {
2409     fmnext = fm->next;
2410     if (fm->session == queue->content)
2411     {
2412       free_fragment_message (plugin, fm);
2413     }
2414     fm = fmnext;
2415   }
2416
2417   // remove PendingMessage
2418   pm = queue->content->pending_message_head;
2419   while (pm != NULL)
2420   {
2421     GNUNET_CONTAINER_DLL_remove (queue->content->pending_message_head,
2422                                  queue->content->pending_message_tail, pm);
2423     GNUNET_free (pm->msg);
2424     GNUNET_free (pm);
2425     pm = queue->content->pending_message_head;
2426   }
2427
2428   GNUNET_CONTAINER_DLL_remove (endpoint->sessions_head, endpoint->sessions_tail,
2429                                queue);
2430   //Check that no ohter session on this endpoint for this session exits
2431   GNUNET_assert(search_session(plugin, endpoint, &queue->content->target) == NULL);
2432   if (endpoint->sessions_head == NULL && do_free_macendpoint == GNUNET_YES)
2433   {
2434     free_macendpoint (plugin, endpoint);
2435     //check if no endpoint with the same address exists
2436     GNUNET_assert(get_macendpoint(plugin, &endpoint->addr, GNUNET_NO) == NULL);
2437   }
2438
2439   if (queue->content->timeout_task != GNUNET_SCHEDULER_NO_TASK)
2440   {
2441     GNUNET_SCHEDULER_cancel (queue->content->timeout_task);
2442     queue->content->timeout_task = GNUNET_SCHEDULER_NO_TASK;
2443   }
2444   GNUNET_free (queue);
2445
2446   check_fragment_queue (plugin);
2447 }
2448
2449 /**
2450  * Function that can be used to force the plugin to disconnect
2451  * from the given peer and cancel all previous transmissions
2452  * (and their continuation).
2453  *
2454  * @param cls closure
2455  * @param target peer from which to disconnect
2456  */
2457 static void
2458 wlan_plugin_disconnect (void *cls, const struct GNUNET_PeerIdentity *target)
2459 {
2460   struct Plugin *plugin = cls;
2461   struct Sessionqueue *queue;
2462   struct Sessionqueue *queue_next;
2463   struct MacEndpoint *endpoint = plugin->mac_head;
2464   struct MacEndpoint *endpoint_next;
2465
2466   // just look at all the session for the needed one
2467   while (endpoint != NULL)
2468   {
2469     queue = endpoint->sessions_head;
2470     endpoint_next = endpoint->next;
2471     while (queue != NULL)
2472     {
2473       // content is never NULL
2474       GNUNET_assert (queue->content != NULL);
2475       queue_next = queue->next;
2476       if (memcmp
2477           (target, &(queue->content->target),
2478            sizeof (struct GNUNET_PeerIdentity)) == 0)
2479       {
2480         free_session (plugin, queue, GNUNET_YES);
2481       }
2482       // try next
2483       queue = queue_next;
2484     }
2485     endpoint = endpoint_next;
2486   }
2487 }
2488
2489 /**
2490  * Convert the transports address to a nice, human-readable
2491  * format.
2492  *
2493  * @param cls closure
2494  * @param type name of the transport that generated the address
2495  * @param addr one of the addresses of the host, NULL for the last address
2496  *        the specific address format depends on the transport
2497  * @param addrlen length of the address
2498  * @param numeric should (IP) addresses be displayed in numeric form?
2499  * @param timeout after how long should we give up?
2500  * @param asc function to call on each string
2501  * @param asc_cls closure for asc
2502  */
2503 static void
2504 wlan_plugin_address_pretty_printer (void *cls, const char *type,
2505                                     const void *addr, size_t addrlen,
2506                                     int numeric,
2507                                     struct GNUNET_TIME_Relative timeout,
2508                                     GNUNET_TRANSPORT_AddressStringCallback asc,
2509                                     void *asc_cls)
2510 {
2511   char *ret;
2512   const unsigned char *input;
2513
2514   //GNUNET_assert(cls !=NULL);
2515   if (addrlen != sizeof(struct MacAddress))
2516   {
2517     /* invalid address (MAC addresses have 6 bytes) */
2518     //GNUNET_break (0);
2519 #if DEBUG_wlan
2520       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
2521                    "Func wlan_plugin_address_pretty_printer got size: %u, worng size!\n",
2522                    addrlen);
2523 #endif
2524     asc(asc_cls, NULL);
2525     return;
2526   }
2527   input = (const unsigned char *) addr;
2528   GNUNET_asprintf (&ret,
2529                    "Transport %s: %s Mac-Address %.2X:%.2X:%.2X:%.2X:%.2X:%.2X",type,
2530                    PROTOCOL_PREFIX, input[0], input[1], input[2], input[3],
2531                    input[4], input[5]);
2532 #if DEBUG_wlan
2533   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
2534                    "Func wlan_plugin_address_pretty_printer got size: %u, nummeric %u, type %s; made string: %s\n",
2535                    addrlen, numeric, type, ret);
2536 #endif
2537   asc ( asc_cls, ret);
2538   //only one mac address per plugin
2539   asc ( asc_cls, NULL);
2540 }
2541
2542
2543
2544 /**
2545  * handels the data after all fragments are put together
2546  * @param cls macendpoint this messages belongs to
2547  * @param hdr pointer to the data
2548  */
2549 static void
2550 wlan_data_message_handler (void *cls, const struct GNUNET_MessageHeader *hdr)
2551 {
2552   struct MacEndpoint *endpoint = (struct MacEndpoint *) cls;
2553   struct Plugin *plugin = endpoint->plugin;
2554   struct WlanHeader *wlanheader;
2555   struct Session *session;
2556
2557   const struct GNUNET_MessageHeader *temp_hdr;
2558   struct GNUNET_PeerIdentity tmpsource;
2559   int crc;
2560
2561   GNUNET_assert (plugin != NULL);
2562
2563   if (ntohs (hdr->type) == GNUNET_MESSAGE_TYPE_WLAN_DATA)
2564   {
2565
2566 #if DEBUG_wlan
2567     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
2568                      "Func wlan_data_message_handler got GNUNET_MESSAGE_TYPE_WLAN_DATA size: %u\n",
2569                      ntohs (hdr->size));
2570 #endif
2571
2572     if (ntohs (hdr->size) <
2573         sizeof (struct WlanHeader) + sizeof (struct GNUNET_MessageHeader))
2574     {
2575       //packet not big enought
2576       return;
2577     }
2578
2579     GNUNET_STATISTICS_update (plugin->env->stats, _("# wlan whole messages received"), 1, GNUNET_NO);
2580     wlanheader = (struct WlanHeader *) hdr;
2581
2582     session = search_session (plugin, endpoint, &wlanheader->source);
2583
2584     temp_hdr = (const struct GNUNET_MessageHeader *) &wlanheader[1];
2585     crc = ntohl (wlanheader->crc);
2586     wlanheader->crc = 0;
2587     if (getcrc32 ((char *) wlanheader, ntohs (wlanheader->header.size)) != crc)
2588     {
2589       //wrong crc, dispose message
2590       GNUNET_log_from (GNUNET_ERROR_TYPE_INFO, PLUGIN_LOG_NAME,
2591                        "Wlan message header crc was wrong: %u != %u\n",
2592                        getcrc32 ((char *) wlanheader,
2593                                  ntohs (wlanheader->header.size)), crc);
2594       hexdump ((void *) hdr, ntohs (hdr->size));
2595       return;
2596     }
2597
2598     //if not in session list
2599     if (session == NULL)
2600     {
2601 #if DEBUG_wlan
2602       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
2603                        "WLAN client not in session list: packet size = %u, inner size = %u, header size = %u\n",
2604                        ntohs (wlanheader->header.size), ntohs (temp_hdr->size),
2605                        sizeof (struct WlanHeader));
2606 #endif
2607       //try if it is a hello message
2608       if (ntohs (wlanheader->header.size) >=
2609           ntohs (temp_hdr->size) + sizeof (struct WlanHeader))
2610       {
2611         if (ntohs (temp_hdr->type) == GNUNET_MESSAGE_TYPE_HELLO)
2612         {
2613           if (GNUNET_HELLO_get_id
2614               ((const struct GNUNET_HELLO_Message *) temp_hdr,
2615                &tmpsource) == GNUNET_OK)
2616           {
2617             session = create_session (plugin, endpoint, &tmpsource);
2618           }
2619           else
2620           {
2621             GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, PLUGIN_LOG_NAME,
2622                              "WLAN client not in session list and hello message is not okay\n");
2623             return;
2624           }
2625
2626         }
2627         else
2628         {
2629           GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, PLUGIN_LOG_NAME,
2630                            "WLAN client not in session list and not a hello message\n");
2631           return;
2632         }
2633       }
2634       else
2635       {
2636         GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, PLUGIN_LOG_NAME,
2637                          "WLAN client not in session list and message size in does not fit\npacket size = %u, inner size = %u, header size = %u\n",
2638                          ntohs (wlanheader->header.size),
2639                          ntohs (temp_hdr->size), sizeof (struct WlanHeader));
2640         return;
2641       }
2642     }
2643
2644     //"receive" the message
2645
2646     if (memcmp
2647         (&wlanheader->source, &session->target,
2648          sizeof (struct GNUNET_PeerIdentity)) != 0)
2649     {
2650       //wrong peer id
2651 #if DEBUG_wlan
2652       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
2653                        "WLAN peer source id doesn't match packet peer source id: session %p\n",
2654                        session);
2655 #endif
2656       return;
2657     }
2658
2659     if (memcmp
2660         (&wlanheader->target, plugin->env->my_identity,
2661          sizeof (struct GNUNET_PeerIdentity)) != 0)
2662     {
2663       //wrong peer id
2664 #if DEBUG_wlan
2665       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
2666                        "WLAN peer target id doesn't match our peer id: session %p\n",
2667                        session);
2668 #endif
2669       return;
2670     }
2671
2672     GNUNET_SERVER_mst_receive (plugin->data_tokenizer, session,
2673                                (const char *) temp_hdr,
2674                                ntohs (hdr->size) - sizeof (struct WlanHeader),
2675                                GNUNET_YES, GNUNET_NO);
2676
2677     return;
2678   }
2679   else
2680   {
2681     GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, PLUGIN_LOG_NAME,
2682                      "wlan_data_message_handler got wrong message type: %u\n",
2683                      ntohs (hdr->size));
2684     return;
2685   }
2686 }
2687
2688 /**
2689  * function to process the a message, give it to the higher layer
2690  * @param cls pointer to the plugin
2691  * @param client pointer to the session this message belongs to
2692  * @param hdr start of the message
2693  */
2694 //TODO ATS informations
2695 static void
2696 process_data (void *cls, void *client, const struct GNUNET_MessageHeader *hdr)
2697 {
2698
2699   GNUNET_assert (client != NULL);
2700   GNUNET_assert (cls != NULL);
2701   struct Session *session = (struct Session *) client;
2702   struct Plugin *plugin = (struct Plugin *) cls;
2703
2704   struct GNUNET_ATS_Information distance;
2705
2706   distance.type = htonl (GNUNET_ATS_QUALITY_NET_DISTANCE);
2707   distance.value = htonl (1);
2708
2709 #if DEBUG_wlan
2710   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
2711                    "Calling plugin->env->receive for session %p; %s; size: %u\n",
2712                    session, wlan_plugin_address_to_string (NULL,
2713                                                            session->mac->
2714                                                            addr.mac, 6),
2715                    htons (hdr->size));
2716 #endif
2717
2718   plugin->env->receive (plugin->env->cls, &(session->target), hdr,
2719                         (const struct GNUNET_ATS_Information *)
2720                         &distance, 1, session,
2721                         (const char *) &session->mac->addr,
2722                         sizeof (session->mac->addr));
2723 }
2724
2725 /**
2726  * Function used for to process the data received from the wlan interface
2727  *
2728  * @param cls the plugin handle
2729  * @param session_light pointer to the struct holding known informations
2730  * @param hdr hdr of the GNUNET_MessageHeader
2731  * @param rxinfo pointer to the radiotap informations got with this packet FIXME: give ATS for info
2732  */
2733 static void
2734 wlan_data_helper (void *cls, struct Session_light *session_light,
2735                   const struct GNUNET_MessageHeader *hdr,
2736                   const struct Radiotap_rx *rxinfo)
2737 {
2738   struct Plugin *plugin = cls;
2739   struct FragmentMessage *fm;
2740   struct FragmentMessage *fm2;
2741   struct GNUNET_PeerIdentity tmpsource;
2742
2743   GNUNET_assert(plugin != NULL);
2744
2745   //ADVERTISEMENT
2746   if (ntohs (hdr->type) == GNUNET_MESSAGE_TYPE_HELLO)
2747   {
2748
2749     //TODO better DOS protection, error handling
2750     //TODO test first than create session
2751     GNUNET_assert (session_light != NULL);
2752
2753 #if DEBUG_wlan
2754     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
2755                      "Func wlan_data_helper got GNUNET_MESSAGE_TYPE_HELLO size: %u; %s\n",
2756                      ntohs (hdr->size), wlan_plugin_address_to_string (NULL,
2757                                                                        session_light->addr.
2758                                                                        mac, 6));
2759 #endif
2760
2761     if (session_light->macendpoint == NULL)
2762     {
2763       session_light->macendpoint =
2764           get_macendpoint (plugin, &session_light->addr, GNUNET_YES);
2765     }
2766
2767
2768     if (GNUNET_HELLO_get_id
2769         ((const struct GNUNET_HELLO_Message *) hdr,
2770          &tmpsource) == GNUNET_OK)
2771     {
2772         session_light->session = search_session (plugin, session_light->macendpoint, &tmpsource);
2773       if (session_light->session == NULL)
2774         {
2775           session_light->session = create_session (plugin, session_light->macendpoint, &tmpsource);
2776         }
2777       GNUNET_STATISTICS_update (plugin->env->stats, _("# wlan hello messages received"), 1, GNUNET_NO);
2778       plugin->env->receive(plugin->env->cls,&session_light->session->target,hdr, NULL, 0, session_light->session,
2779           (const char *) &session_light->session->mac->addr,
2780           sizeof (session_light->session->mac->addr));
2781     }
2782     else
2783     {
2784       GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, PLUGIN_LOG_NAME,
2785                        "WLAN client not in session list and hello message is not okay\n");
2786       return;
2787     }
2788   }
2789
2790   //FRAGMENT
2791
2792   else if (ntohs (hdr->type) == GNUNET_MESSAGE_TYPE_FRAGMENT)
2793   {
2794
2795     GNUNET_assert (session_light != NULL);
2796     if (session_light->macendpoint == NULL)
2797     {
2798       session_light->macendpoint =
2799           get_macendpoint (plugin, &session_light->addr, GNUNET_YES);
2800     }
2801
2802 #if DEBUG_wlan
2803     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
2804                      "Func wlan_data_helper got GNUNET_MESSAGE_TYPE_FRAGMENT with size: %u; mac endpoint %p: %s\n",
2805                      ntohs (hdr->size), session_light->macendpoint,
2806                      wlan_plugin_address_to_string (NULL,
2807                                                     session_light->addr.mac,
2808                                                     6));
2809 #endif
2810
2811     GNUNET_STATISTICS_update (plugin->env->stats, _("# wlan fragments received"), 1, GNUNET_NO);
2812     int ret =
2813         GNUNET_DEFRAGMENT_process_fragment (session_light->macendpoint->defrag,
2814                                             hdr);
2815
2816     if (ret == GNUNET_NO)
2817     {
2818       session_light->macendpoint->dups++;
2819     }
2820     else if (ret == GNUNET_OK)
2821     {
2822       session_light->macendpoint->fragc++;
2823     }
2824     set_next_send (plugin);
2825
2826   }
2827
2828   //ACK
2829
2830   else if (ntohs (hdr->type) == GNUNET_MESSAGE_TYPE_FRAGMENT_ACK)
2831   {
2832     GNUNET_assert (session_light != NULL);
2833     if (session_light->macendpoint == NULL)
2834     {
2835       session_light->macendpoint =
2836           get_macendpoint (plugin, &session_light->addr, GNUNET_NO);
2837     }
2838
2839     if (session_light->macendpoint == NULL)
2840     {
2841 #if DEBUG_wlan
2842       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
2843                        "Macendpoint does not exist for this GNUNET_MESSAGE_TYPE_FRAGMENT_ACK size: %u; %s\n",
2844                        ntohs (hdr->size), wlan_plugin_address_to_string (NULL,
2845                                                                          session_light->addr.mac,
2846                                                                          6));
2847 #endif
2848       return;
2849     }
2850
2851 #if DEBUG_wlan
2852     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
2853                      "Func wlan_data_helper got GNUNET_MESSAGE_TYPE_FRAGMENT_ACK size: %u; mac endpoint: %p; %s\n",
2854                      ntohs (hdr->size), session_light->macendpoint,
2855                      wlan_plugin_address_to_string (NULL,
2856                                                     session_light->addr.mac,
2857                                                     6));
2858 #endif
2859     fm = session_light->macendpoint->sending_messages_head;
2860     while (fm != NULL)
2861     {
2862       fm2 = fm->next;
2863       GNUNET_STATISTICS_update (plugin->env->stats, _("# wlan acks received"), 1, GNUNET_NO);
2864       int ret = GNUNET_FRAGMENT_process_ack (fm->fragcontext, hdr);
2865
2866       if (ret == GNUNET_OK)
2867       {
2868 #if DEBUG_wlan_retransmission > 1
2869         GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
2870                          "Got last ack, finished fragment message %p\n", fm);
2871 #endif
2872         session_light->macendpoint->acks++;
2873         fm->session->last_activity = GNUNET_TIME_absolute_get ();
2874         session_light->macendpoint->last_activity = fm->session->last_activity;
2875         free_fragment_message (plugin, fm);
2876         check_fragment_queue (plugin);
2877         return;
2878       }
2879       if (ret == GNUNET_NO)
2880       {
2881 #if DEBUG_wlan_retransmission > 1
2882         GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
2883                          "Got ack for: %p\n", fm);
2884 #endif
2885         session_light->macendpoint->acks++;
2886         return;
2887       }
2888       if (ret == GNUNET_SYSERR)
2889       {
2890
2891       }
2892
2893       fm = fm2;
2894     }
2895
2896 #if DEBUG_wlan_retransmission > 1
2897     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
2898                      "WLAN fragment not in fragment list\n");
2899 #endif
2900     return;
2901
2902   }
2903   else
2904   {
2905     // TODO Wrong data?
2906     GNUNET_log_from (GNUNET_ERROR_TYPE_INFO, PLUGIN_LOG_NAME,
2907                      "WLAN packet inside the WLAN helper packet has not the right type: %u size: %u\n",
2908                      ntohs (hdr->type), ntohs (hdr->size));
2909     GNUNET_break (0);
2910     return;
2911   }
2912
2913 #if 0
2914   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
2915                    "Helper finished\n");
2916 #endif
2917
2918 }
2919
2920 /**
2921  * Function to print mac addresses nice *
2922  * @param pointer to 6 byte with the mac address
2923  * @return pointer to the chars which hold the print out
2924  */
2925 const char *
2926 macprinter (const u_int8_t * mac)
2927 {
2928   static char macstr[20];
2929
2930   GNUNET_snprintf (macstr, sizeof (macstr), "%X:%X:%X:%X:%X:%X", mac[0], mac[1],
2931                    mac[2], mac[3], mac[4], mac[5]);
2932   return macstr;
2933 }
2934
2935 /**
2936  * Function for the scheduler if a mac endpoint times out
2937  * @param cls pointer to the MacEndpoint
2938  * @param tc pointer to the GNUNET_SCHEDULER_TaskContext
2939  */
2940 static void
2941 macendpoint_timeout (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2942 {
2943   struct MacEndpoint *endpoint = cls;
2944
2945   GNUNET_assert (endpoint != NULL);
2946   endpoint->timeout_task = GNUNET_SCHEDULER_NO_TASK;
2947   if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
2948   {
2949     return;
2950   }
2951   if (GNUNET_TIME_absolute_get_remaining
2952       (GNUNET_TIME_absolute_add
2953        (endpoint->last_activity, MACENDPOINT_TIMEOUT)).rel_value == 0)
2954   {
2955     GNUNET_assert(endpoint->plugin != NULL);
2956     GNUNET_STATISTICS_update (endpoint->plugin->env->stats, _("# wlan mac endpoints timeouts"), 1, GNUNET_NO);
2957     free_macendpoint (endpoint->plugin, endpoint);
2958   }
2959   else
2960   {
2961     endpoint->timeout_task =
2962         GNUNET_SCHEDULER_add_delayed (MACENDPOINT_TIMEOUT, &macendpoint_timeout,
2963                                       endpoint);
2964   }
2965 }
2966
2967 /**
2968  * function to create an macendpoint
2969  * @param plugin pointer to the plugin struct
2970  * @param addr pointer to the macaddress
2971  * @return returns a macendpoint
2972  */
2973 static struct MacEndpoint *
2974 create_macendpoint (struct Plugin *plugin, const struct MacAddress *addr)
2975 {
2976   struct MacEndpoint *newend = GNUNET_malloc (sizeof (struct MacEndpoint));
2977
2978   GNUNET_assert(plugin != NULL);
2979   GNUNET_STATISTICS_update (plugin->env->stats, _("# wlan mac endpoints created"), 1, GNUNET_NO);
2980   newend->addr = *addr;
2981   newend->plugin = plugin;
2982   newend->addr = *addr;
2983   newend->fragment_messages_out_count = 0;
2984   newend->defrag =
2985       GNUNET_DEFRAGMENT_context_create (plugin->env->stats, WLAN_MTU,
2986                                         MESSAGES_IN_DEFRAG_QUEUE_PER_MAC,
2987                                         newend, &wlan_data_message_handler,
2988                                         &add_ack_for_send);
2989   newend->last_activity = GNUNET_TIME_absolute_get ();
2990   newend->timeout_task =
2991       GNUNET_SCHEDULER_add_delayed (MACENDPOINT_TIMEOUT, &macendpoint_timeout,
2992                                     newend);
2993
2994   plugin->mac_count++;
2995   GNUNET_STATISTICS_set(plugin->env->stats, _("# wlan mac endpoints"), plugin->mac_count, GNUNET_NO);
2996   GNUNET_CONTAINER_DLL_insert_tail (plugin->mac_head, plugin->mac_tail, newend);
2997 #if DEBUG_wlan
2998   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
2999                    "New Mac Endpoint %p: %s\n", newend,
3000                    wlan_plugin_address_to_string (NULL, newend->addr.mac, 6));
3001 #endif
3002   return newend;
3003 }
3004
3005 /**
3006  * Function used for to process the data from the suid process
3007  *
3008  * @param cls the plugin handle
3009  * @param client client that send the data (not used)
3010  * @param hdr header of the GNUNET_MessageHeader
3011  */
3012 static void
3013 wlan_process_helper (void *cls, void *client,
3014                      const struct GNUNET_MessageHeader *hdr)
3015 {
3016   struct Plugin *plugin = cls;
3017   struct ieee80211_frame *wlanIeeeHeader = NULL;
3018   struct Session_light *session_light = NULL;
3019   struct Radiotap_rx *rxinfo;
3020   const struct GNUNET_MessageHeader *temp_hdr = NULL;
3021
3022   int datasize = 0;
3023   int pos;
3024
3025   GNUNET_assert(plugin != NULL);
3026   switch (ntohs (hdr->type))
3027   {
3028   case GNUNET_MESSAGE_TYPE_WLAN_HELPER_DATA:
3029 #if DEBUG_wlan
3030     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
3031                      "Func wlan_process_helper got GNUNET_MESSAGE_TYPE_WLAN_HELPER_DATA size: %u\n",
3032                      ntohs (hdr->size));
3033 #endif
3034
3035     GNUNET_STATISTICS_update (plugin->env->stats, _("# wlan WLAN_HELPER_DATA received"), 1, GNUNET_NO);
3036     //call wlan_process_helper with the message inside, later with wlan: analyze signal
3037     if (ntohs (hdr->size) <
3038         sizeof (struct ieee80211_frame) + 2*sizeof (struct GNUNET_MessageHeader) +
3039         sizeof (struct Radiotap_rx))
3040     {
3041 #if DEBUG_wlan
3042       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
3043                        "Size of packet is too small; size: %u min size: %u\n",
3044                        ntohs (hdr->size),
3045                        sizeof (struct ieee80211_frame) +
3046                        sizeof (struct GNUNET_MessageHeader));
3047 #endif
3048       //GNUNET_break (0);
3049       /* FIXME: restart SUID process */
3050       return;
3051     }
3052
3053     rxinfo = (struct Radiotap_rx *) &hdr[1];
3054     wlanIeeeHeader = (struct ieee80211_frame *) &rxinfo[1];
3055
3056     //process only if it is an broadcast or for this computer both with the gnunet bssid
3057
3058     //check for bssid
3059     if (memcmp
3060         (&(wlanIeeeHeader->i_addr3), &mac_bssid,
3061          sizeof (struct MacAddress)) == 0)
3062     {
3063       //check for broadcast or mac
3064       if ((memcmp
3065           (&(wlanIeeeHeader->i_addr1), &bc_all_mac,
3066            sizeof (struct MacAddress)) == 0) ||
3067           (memcmp (&(wlanIeeeHeader->i_addr1), &(plugin->mac_address),
3068                   sizeof (struct MacAddress)) == 0))
3069       {
3070           //if packet is from us return
3071           if ((memcmp (&(wlanIeeeHeader->i_addr2), &(plugin->mac_address),
3072                   sizeof (struct MacAddress)) == 0)){
3073               return;
3074           }
3075         // process the inner data
3076
3077
3078         datasize =
3079             ntohs (hdr->size) - sizeof (struct ieee80211_frame) -
3080             sizeof (struct GNUNET_MessageHeader) - sizeof (struct Radiotap_rx);
3081
3082         session_light = GNUNET_malloc (sizeof (struct Session_light));
3083         memcpy (&session_light->addr, &(wlanIeeeHeader->i_addr2),
3084                 sizeof (struct MacAddress));
3085         //session_light->session = search_session(plugin,session_light->addr);
3086         GNUNET_STATISTICS_update (plugin->env->stats, _("# wlan messages for this client received"), 1, GNUNET_NO);
3087
3088         pos = 0;
3089         while (pos < datasize)
3090         {
3091           temp_hdr = (struct GNUNET_MessageHeader *) &wlanIeeeHeader[1] + pos;
3092           if (ntohs(temp_hdr->size) <= datasize + pos)
3093             {
3094               GNUNET_STATISTICS_update (plugin->env->stats, _("# wlan messages inside WLAN_HELPER_DATA received"), 1, GNUNET_NO);
3095               wlan_data_helper (plugin, session_light, temp_hdr, rxinfo);
3096             }
3097           else
3098             {
3099 #if DEBUG_wlan
3100             GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
3101                        "Size of packet is too small; size: %u > size of packet: %u\n",
3102                        ntohs(temp_hdr->size),datasize + pos);
3103 #endif
3104             }
3105           pos += ntohs (temp_hdr->size);
3106
3107         }
3108
3109         //clean up
3110         GNUNET_free (session_light);
3111       }
3112       else
3113       {
3114 #if DEBUG_wlan
3115         GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
3116                          "Func wlan_process_helper got wrong MAC: %s\n",
3117                          macprinter (wlanIeeeHeader->i_addr1));
3118 #endif
3119       }
3120     }
3121     else
3122     {
3123 #if DEBUG_wlan
3124       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
3125                        "Func wlan_process_helper got wrong BSSID: %s\n",
3126                        macprinter (wlanIeeeHeader->i_addr2));
3127 #endif
3128     }
3129     break;
3130   case GNUNET_MESSAGE_TYPE_WLAN_HELPER_CONTROL:
3131     //TODO more control messages
3132     if (ntohs (hdr->size) != sizeof (struct Wlan_Helper_Control_Message))
3133     {
3134       GNUNET_break (0);
3135       /* FIXME: restart SUID process */
3136       return;
3137     }
3138     memcpy (&plugin->mac_address, &hdr[1], sizeof (struct MacAddress));
3139 #if DEBUG_wlan
3140     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
3141                      "Received WLAN_HELPER_CONTROL message with transport of address %s\n",
3142                      wlan_plugin_address_to_string (cls, &plugin->mac_address,
3143                                                     sizeof (struct
3144                                                             MacAddress)));
3145 #endif
3146     plugin->env->notify_address (plugin->env->cls, GNUNET_YES,
3147                                  &plugin->mac_address,
3148                                  sizeof (struct MacAddress));
3149     break;
3150   default:
3151 #if DEBUG_wlan
3152     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
3153                      "Func wlan_process_helper got unknown message with number %u, size %u\n",
3154                      ntohs (hdr->type), ntohs (hdr->size));
3155
3156 #endif
3157 #if DEBUG_wlan_msg_dump > 1
3158     hexdump (hdr, GNUNET_MIN (ntohs (hdr->size), 256));
3159 #endif
3160     GNUNET_break (0);
3161     return;
3162   }
3163 }
3164
3165 /**
3166  * Exit point from the plugin.
3167  * @param cls pointer to the api struct
3168  */
3169
3170 //FIXME cleanup
3171 void *
3172 libgnunet_plugin_transport_wlan_done (void *cls)
3173 {
3174   struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
3175   struct Plugin *plugin = api->cls;
3176   struct MacEndpoint *endpoint = plugin->mac_head;
3177   struct MacEndpoint *endpoint_next;
3178
3179 #if DEBUG_wlan
3180   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
3181                    "libgnunet_plugin_transport_wlan_done started\n");
3182 #endif
3183
3184   wlan_transport_stop_wlan_helper(plugin);
3185
3186   GNUNET_assert (cls != NULL);
3187   //free sessions
3188   while (endpoint != NULL)
3189   {
3190     endpoint_next = endpoint->next;
3191     free_macendpoint (plugin, endpoint);
3192     endpoint = endpoint_next;
3193
3194   }
3195
3196
3197   if (plugin->suid_tokenizer != NULL)
3198     GNUNET_SERVER_mst_destroy (plugin->suid_tokenizer);
3199
3200   if (plugin->data_tokenizer != NULL)
3201     GNUNET_SERVER_mst_destroy (plugin->data_tokenizer);
3202
3203   GNUNET_free_non_null (plugin->interface);
3204   GNUNET_free (plugin);
3205   GNUNET_free (api);
3206   return NULL;
3207 }
3208
3209 /**
3210  * Entry point for the plugin.
3211  *
3212  * @param cls closure, the 'struct GNUNET_TRANSPORT_PluginEnvironment*'
3213  * @return the 'struct GNUNET_TRANSPORT_PluginFunctions*' or NULL on error
3214  */
3215 void *
3216 libgnunet_plugin_transport_wlan_init (void *cls)
3217 {
3218   //struct GNUNET_SERVICE_Context *service;
3219   struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
3220   struct GNUNET_TRANSPORT_PluginFunctions *api;
3221   struct Plugin *plugin;
3222
3223   GNUNET_assert (cls != NULL);
3224
3225   plugin = GNUNET_malloc (sizeof (struct Plugin));
3226   plugin->env = env;
3227   plugin->pendingsessions = 0;
3228   GNUNET_STATISTICS_set(plugin->env->stats, _("# wlan pending sessions"), plugin->pendingsessions, GNUNET_NO);
3229   plugin->mac_count = 0;
3230   GNUNET_STATISTICS_set(plugin->env->stats, _("# wlan mac endpoints"), plugin->mac_count, GNUNET_NO);
3231   plugin->server_write_task = GNUNET_SCHEDULER_NO_TASK;
3232   plugin->server_read_task = GNUNET_SCHEDULER_NO_TASK;
3233   plugin->server_write_delay_task = GNUNET_SCHEDULER_NO_TASK;
3234   GNUNET_BANDWIDTH_tracker_init (&plugin->tracker,
3235                                  GNUNET_BANDWIDTH_value_init (100 * 1024 *
3236                                                               1024 / 8), 100);
3237
3238   plugin->suid_tokenizer =
3239       GNUNET_SERVER_mst_create (&wlan_process_helper, plugin);
3240
3241   plugin->data_tokenizer = GNUNET_SERVER_mst_create (&process_data, plugin);
3242
3243   //plugin->sessions = GNUNET_malloc (sizeof (struct Sessionqueue));
3244   //plugin->pending_Sessions_head = GNUNET_malloc (sizeof (struct Sessionqueue));
3245
3246   api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
3247   api->cls = plugin;
3248   api->send = &wlan_plugin_send;
3249   api->disconnect = &wlan_plugin_disconnect;
3250   api->address_pretty_printer = &wlan_plugin_address_pretty_printer;
3251   api->check_address = &wlan_plugin_address_suggested;
3252   api->address_to_string = &wlan_plugin_address_to_string;
3253
3254   //read config
3255
3256   if (GNUNET_CONFIGURATION_have_value (env->cfg, "transport-wlan", "TESTMODE"))
3257   {
3258     if (GNUNET_SYSERR ==
3259         GNUNET_CONFIGURATION_get_value_number (env->cfg, "transport-wlan",
3260                                                "TESTMODE", &(plugin->testmode)))
3261       plugin->testmode = 0;             //default value
3262   }
3263
3264   if (GNUNET_CONFIGURATION_have_value (env->cfg, "transport-wlan", "INTERFACE"))
3265   {
3266     if (GNUNET_CONFIGURATION_get_value_string
3267         (env->cfg, "transport-wlan", "INTERFACE",
3268          &(plugin->interface)) != GNUNET_YES)
3269     {
3270       libgnunet_plugin_transport_wlan_done (api);
3271       return NULL;
3272     }
3273   }
3274
3275   //start the plugin
3276   wlan_transport_start_wlan_helper (plugin);
3277   set_next_beacon_time (plugin);
3278   set_next_send(plugin);
3279 #if DEBUG_wlan
3280   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
3281                    "wlan init finished\n");
3282 #endif
3283
3284   return api;
3285 }
3286
3287 /* end of plugin_transport_wlan.c */