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