complete state reset functionality
[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     set_next_beacon_time (plugin);
1813
1814   }
1815   else
1816     {
1817     GNUNET_assert (bytes == size);
1818     set_next_beacon_time (plugin);
1819     set_next_send (plugin);
1820     }
1821   GNUNET_free (msgheader);
1822
1823
1824 }
1825
1826 /**
1827  * function to add an ack to send it for a received fragment
1828  * @param cls MacEndpoint this ack belongs to
1829  * @param msg_id id of the message
1830  * @param hdr pointer to the hdr where the ack is stored
1831  *
1832  */
1833
1834 static void
1835 add_ack_for_send (void *cls, uint32_t msg_id,
1836                   const struct GNUNET_MessageHeader *hdr)
1837 {
1838
1839   struct AckSendQueue *ack;
1840
1841   GNUNET_assert (cls != NULL);
1842   struct MacEndpoint *endpoint = cls;
1843   struct Plugin *plugin = endpoint->plugin;
1844   struct GNUNET_MessageHeader *msgheader;
1845   struct GNUNET_MessageHeader *msgheader2;
1846   uint16_t size;
1847
1848   size =
1849       sizeof (struct GNUNET_MessageHeader) + sizeof (struct Radiotap_Send) +
1850       sizeof (struct ieee80211_frame) + ntohs (hdr->size) +
1851       sizeof (struct AckSendQueue);
1852
1853   ack = GNUNET_malloc (size);
1854   ack->message_id = msg_id;
1855   ack->endpoint = endpoint;
1856
1857   size =
1858       sizeof (struct GNUNET_MessageHeader) + sizeof (struct Radiotap_Send) +
1859       sizeof (struct ieee80211_frame) + ntohs (hdr->size);
1860
1861   msgheader = (struct GNUNET_MessageHeader *) &ack[1];
1862   ack->hdr = (struct GNUNET_MessageHeader *) &ack[1];
1863   msgheader->size = htons (size);
1864   msgheader->type = htons (GNUNET_MESSAGE_TYPE_WLAN_HELPER_DATA);
1865
1866   ack->radioHeader = (struct Radiotap_Send *) &msgheader[1];
1867   ack->ieeewlanheader = (struct ieee80211_frame *) &(ack->radioHeader)[1];
1868   msgheader2 = (struct GNUNET_MessageHeader *) &(ack->ieeewlanheader)[1];
1869   memcpy (msgheader2, hdr, ntohs (hdr->size));
1870
1871   GNUNET_CONTAINER_DLL_insert_tail (plugin->ack_send_queue_head,
1872                                     plugin->ack_send_queue_tail, ack);
1873
1874 #if DEBUG_wlan_retransmission > 1
1875   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
1876                    "Adding ack with message id %u to send, AckSendQueue %p, endpoint %p\n",
1877                    msg_id, ack, endpoint);
1878 #endif
1879
1880   set_next_send (plugin);
1881 }
1882
1883 /**
1884  * Function for the scheduler if a FragmentMessage times out
1885  * @param cls pointer to the FragmentMessage
1886  * @param tc pointer to the GNUNET_SCHEDULER_TaskContext
1887  */
1888 static void
1889 fragmentmessage_timeout (void *cls,
1890                          const struct GNUNET_SCHEDULER_TaskContext *tc)
1891 {
1892   struct FragmentMessage *fm = cls;
1893
1894   GNUNET_assert (fm != NULL);
1895   fm->timeout_task = GNUNET_SCHEDULER_NO_TASK;
1896   if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
1897   {
1898     return;
1899   }
1900   free_fragment_message (fm->session->mac->plugin, fm);
1901 }
1902
1903 /**
1904  * Function to check if there is some space in the fragment queue
1905  * inserts a message if space is available
1906  * @param plugin the plugin struct
1907  */
1908
1909 static void
1910 check_fragment_queue (struct Plugin *plugin)
1911 {
1912   struct Session *session;
1913   struct FragmentMessage *fm;
1914   struct GNUNET_PeerIdentity pid;
1915
1916   struct PendingMessage *pm;
1917
1918   if (plugin->pending_Fragment_Messages < FRAGMENT_QUEUE_SIZE)
1919   {
1920     session = get_next_queue_session (plugin);
1921     if (session != NULL)
1922     {
1923       pm = session->pending_message_head;
1924       GNUNET_assert (pm != NULL);
1925       GNUNET_CONTAINER_DLL_remove (session->pending_message_head,
1926                                    session->pending_message_tail, pm);
1927       session->mac->fragment_messages_out_count++;
1928       session->fragment_messages_out_count++;
1929       plugin->pending_Fragment_Messages++;
1930
1931       fm = GNUNET_malloc (sizeof (struct FragmentMessage));
1932       fm->session = session;
1933       fm->timeout.abs_value = pm->timeout.abs_value;
1934       fm->frag = NULL;
1935       fm->fragcontext =
1936           GNUNET_FRAGMENT_context_create (plugin->env->stats, WLAN_MTU,
1937                                           &plugin->tracker,
1938                                           GNUNET_TIME_UNIT_SECONDS,
1939                                           &(pm->msg->header),
1940                                           &add_message_for_send, fm);
1941       fm->timeout_task =
1942           GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_absolute_get_remaining
1943                                         (fm->timeout), fragmentmessage_timeout,
1944                                         fm);
1945       GNUNET_CONTAINER_DLL_insert_tail (session->mac->sending_messages_head,
1946                                         session->mac->sending_messages_tail,
1947                                         fm);
1948
1949       if (pm->transmit_cont != NULL)
1950       {
1951         pid = session->target;
1952         pm->transmit_cont (pm->transmit_cont_cls, &pid, GNUNET_OK);
1953 #if DEBUG_wlan
1954         GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
1955                          "called pm->transmit_cont for %p\n", session);
1956 #endif
1957       }
1958       else
1959       {
1960 #if DEBUG_wlan
1961         GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
1962                          "no pm->transmit_cont for %p\n", session);
1963 #endif
1964       }
1965       GNUNET_free (pm);
1966
1967       if (session->pending_message_head != NULL)
1968       {
1969         //requeue session
1970         queue_session (plugin, session);
1971       }
1972
1973     }
1974   }
1975
1976   //check if timeout changed
1977   set_next_send (plugin);
1978 }
1979
1980 /**
1981  * Function to send an ack, does not free the ack
1982  * @param plugin pointer to the plugin
1983  */
1984 static void
1985 send_ack (struct Plugin *plugin)
1986 {
1987
1988   ssize_t bytes;
1989   struct AckSendQueue *ack;
1990   struct Finish_send * finish;
1991
1992   ack = plugin->ack_send_queue_head;
1993
1994
1995 #if DEBUG_wlan
1996   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
1997                    "Sending ack for message_id %u for mac endpoint %p, size %u\n",
1998                    ack->message_id, ack->endpoint,
1999                    ntohs (ack->hdr->size) - sizeof (struct Radiotap_Send));
2000 #endif
2001
2002   GNUNET_assert (plugin != NULL);
2003   GNUNET_STATISTICS_update (plugin->env->stats, _("# wlan acks send"), 1, GNUNET_NO);
2004
2005   getRadiotapHeader (plugin, ack->endpoint, ack->radioHeader);
2006   getWlanHeader (ack->ieeewlanheader, &ack->endpoint->addr, plugin,
2007                  ntohs (ack->hdr->size));
2008
2009   bytes =
2010       GNUNET_DISK_file_write (plugin->server_stdin_handle, ack->hdr,
2011                               ntohs (ack->hdr->size));
2012   if (bytes == GNUNET_SYSERR)
2013   {
2014     GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, PLUGIN_LOG_NAME,
2015                      _
2016                      ("Error writing to wlan healper. errno == %d, ERROR: %s\n"),
2017                      errno, strerror (errno));
2018     finish = GNUNET_malloc (sizeof (struct Finish_send));
2019     finish->plugin = plugin;
2020     finish->head_of_next_write = NULL;
2021     finish->size = 0;
2022     finish->msgstart = NULL;
2023     restart_helper(plugin, finish);
2024   }
2025   else
2026   {
2027     GNUNET_assert (bytes == ntohs (ack->hdr->size));
2028     GNUNET_CONTAINER_DLL_remove (plugin->ack_send_queue_head,
2029                                  plugin->ack_send_queue_tail, ack);
2030     GNUNET_free (ack);
2031     set_next_send (plugin);
2032   }
2033 }
2034
2035 /**
2036  * Function called when wlan helper is ready to get some data
2037  *
2038  * @param cls closure
2039  * @param tc GNUNET_SCHEDULER_TaskContext
2040  */
2041 static void
2042 do_transmit (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2043 {
2044   struct Plugin *plugin = cls;
2045   GNUNET_assert (plugin != NULL);
2046
2047   plugin->server_write_task = GNUNET_SCHEDULER_NO_TASK;
2048   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
2049     return;
2050
2051   struct Session *session;
2052   struct FragmentMessage *fm;
2053   struct Finish_send *finish;
2054   struct FragmentMessage_queue *fmq;
2055   ssize_t bytes;
2056
2057   if (plugin->ack_send_queue_head != NULL)
2058   {
2059     send_ack (plugin);
2060     return;
2061   }
2062
2063   //test if a "hello-beacon" has to be send
2064   if (GNUNET_TIME_absolute_get_remaining (plugin->beacon_time).rel_value == 0)
2065   {
2066     send_hello_beacon (plugin);
2067     return;
2068   }
2069
2070   if (plugin->sending_messages_head != NULL)
2071   {
2072     GNUNET_STATISTICS_update (plugin->env->stats, _("# wlan fragments send"), 1, GNUNET_NO);
2073
2074     fmq = plugin->sending_messages_head;
2075     fm = fmq->content;
2076     GNUNET_CONTAINER_DLL_remove (plugin->sending_messages_head,
2077                                  plugin->sending_messages_tail, fmq);
2078     GNUNET_free (fmq);
2079
2080     session = fm->session;
2081     GNUNET_assert (session != NULL);
2082
2083 #if DEBUG_wlan
2084     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
2085                      "Sending GNUNET_MESSAGE_TYPE_WLAN_FRAGMENT for fragment message %p, size: %u\n",
2086                      fm, fm->size);
2087 #endif
2088
2089     getRadiotapHeader (plugin, session->mac, fm->radioHeader);
2090     getWlanHeader (fm->ieeewlanheader, &(fm->session->mac->addr), plugin,
2091                    fm->size);
2092
2093     bytes =
2094         GNUNET_DISK_file_write (plugin->server_stdin_handle, fm->frag,
2095                                 fm->size);
2096
2097
2098     if (bytes != fm->size)
2099     {
2100       finish = GNUNET_malloc (sizeof (struct Finish_send));
2101       finish->plugin = plugin;
2102       finish->msgstart = (struct GNUNET_MessageHeader *) fm->frag;
2103       GNUNET_assert (plugin->server_write_task == GNUNET_SCHEDULER_NO_TASK);
2104
2105       if (bytes == GNUNET_SYSERR)
2106       {
2107         GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, PLUGIN_LOG_NAME,
2108                          _
2109                          ("Error writing to wlan healper. errno == %d, ERROR: %s\n"),
2110                          errno, strerror (errno));
2111
2112         finish->head_of_next_write = fm->frag;
2113         finish->size = fm->size;
2114         restart_helper(plugin, finish);
2115       }
2116       else
2117       {
2118         finish->head_of_next_write = fm->frag + bytes;
2119         finish->size = fm->size - bytes;
2120         plugin->server_write_task =
2121                   GNUNET_SCHEDULER_add_write_file (GNUNET_TIME_UNIT_FOREVER_REL,
2122                                                    plugin->server_stdin_handle,
2123                                                    &finish_sending, finish);
2124       }
2125
2126       fm->frag = NULL;
2127     }
2128     else
2129     {
2130       GNUNET_free (fm->frag);
2131       fm->frag = NULL;
2132       set_next_send (plugin);
2133     }
2134     GNUNET_FRAGMENT_context_transmission_done (fm->fragcontext);
2135     return;
2136   }
2137
2138   GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, PLUGIN_LOG_NAME,
2139                    "do_transmit did nothing, should not happen!\n");
2140 }
2141
2142 /**
2143  * Another peer has suggested an address for this
2144  * peer and transport plugin.  Check that this could be a valid
2145  * address.  If so, consider adding it to the list
2146  * of addresses.
2147  *
2148  * @param cls closure
2149  * @param addr pointer to the address
2150  * @param addrlen length of addr
2151  * @return GNUNET_OK if this is a plausible address for this peer
2152  *         and transport
2153  */
2154 static int
2155 wlan_plugin_address_suggested (void *cls, const void *addr, size_t addrlen)
2156 {
2157   //struct Plugin *plugin = cls;
2158
2159   /* check if the address is plausible; if so,
2160    * add it to our list! */
2161
2162   GNUNET_assert (cls != NULL);
2163   //FIXME mitm is not checked
2164   //Mac Address has 6 bytes
2165   if (addrlen == 6)
2166   {
2167     /* TODO check for bad addresses like multicast, broadcast, etc */
2168 #if DEBUG_wlan
2169     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
2170                          "wlan_plugin_address_suggested got good address, size %u!\n", addrlen);
2171 #endif
2172     return GNUNET_OK;
2173   }
2174 #if DEBUG_wlan
2175     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
2176                          "wlan_plugin_address_suggested got bad address, size %u!\n", addrlen);
2177 #endif
2178   return GNUNET_SYSERR;
2179 }
2180
2181 /**
2182  * Function that can be used by the transport service to transmit
2183  * a message using the plugin.
2184  *
2185  * @param cls closure
2186  * @param target who should receive this message
2187  * @param priority how important is the message
2188  * @param msgbuf the message to transmit
2189  * @param msgbuf_size number of bytes in 'msgbuf'
2190  * @param timeout when should we time out
2191  * @param session which session must be used (or NULL for "any")
2192  * @param addr the address to use (can be NULL if the plugin
2193  *                is "on its own" (i.e. re-use existing TCP connection))
2194  * @param addrlen length of the address in bytes
2195  * @param force_address GNUNET_YES if the plugin MUST use the given address,
2196  *                otherwise the plugin may use other addresses or
2197  *                existing connections (if available)
2198  * @param cont continuation to call once the message has
2199  *        been transmitted (or if the transport is ready
2200  *        for the next transmission call; or if the
2201  *        peer disconnected...)
2202  * @param cont_cls closure for cont
2203  * @return number of bytes used (on the physical network, with overheads);
2204  *         -1 on hard errors (i.e. address invalid); 0 is a legal value
2205  *         and does NOT mean that the message was not transmitted (DV)
2206  */
2207 static ssize_t
2208 wlan_plugin_send (void *cls, const struct GNUNET_PeerIdentity *target,
2209                   const char *msgbuf, size_t msgbuf_size, unsigned int priority,
2210                   struct GNUNET_TIME_Relative timeout, struct Session *session,
2211                   const void *addr, size_t addrlen, int force_address,
2212                   GNUNET_TRANSPORT_TransmitContinuation cont, void *cont_cls)
2213 {
2214   struct Plugin *plugin = cls;
2215   struct PendingMessage *newmsg;
2216   struct WlanHeader *wlanheader;
2217   GNUNET_assert (plugin != NULL);
2218   //check if msglen > 0
2219   GNUNET_assert (msgbuf_size > 0);
2220
2221   //get session if needed
2222   if (session == NULL)
2223   {
2224     if (wlan_plugin_address_suggested (plugin, addr, addrlen) == GNUNET_OK)
2225     {
2226       session = get_session (plugin, addr, target);
2227     }
2228     else
2229     {
2230       GNUNET_log_from (GNUNET_ERROR_TYPE_ERROR, PLUGIN_LOG_NAME,
2231                        _("Wlan Address len %d is wrong\n"), addrlen);
2232       return -1;
2233     }
2234   }
2235
2236   GNUNET_STATISTICS_update (plugin->env->stats, _("# wlan messages queued"), 1, GNUNET_NO);
2237
2238   //queue message:
2239
2240   //queue message in session
2241   //test if there is no other message in the "queue"
2242   //FIXME: to many send requests
2243   if (session->pending_message_head != NULL)
2244   {
2245     newmsg = session->pending_message_head;
2246     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
2247                      "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",
2248                      GNUNET_TIME_absolute_get_remaining (newmsg->
2249                                                          timeout).rel_value,
2250                      session->mac->fragment_messages_out_count);
2251   }
2252
2253   newmsg = GNUNET_malloc (sizeof (struct PendingMessage));
2254   newmsg->msg = GNUNET_malloc (msgbuf_size + sizeof (struct WlanHeader));
2255   wlanheader = newmsg->msg;
2256   //copy msg to buffer, not fragmented / segmented yet, but with message header
2257   wlanheader->header.size = htons (msgbuf_size + sizeof (struct WlanHeader));
2258   wlanheader->header.type = htons (GNUNET_MESSAGE_TYPE_WLAN_DATA);
2259   memcpy (&(wlanheader->target), target, sizeof (struct GNUNET_PeerIdentity));
2260   memcpy (&(wlanheader->source), plugin->env->my_identity,
2261           sizeof (struct GNUNET_PeerIdentity));
2262   wlanheader->crc = 0;
2263   memcpy (&wlanheader[1], msgbuf, msgbuf_size);
2264   wlanheader->crc =
2265       htonl (getcrc32
2266              ((char *) wlanheader, msgbuf_size + sizeof (struct WlanHeader)));
2267   //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);
2268   //hexdump(newmsg->msg, msgbuf_size + sizeof(struct WlanHeader));
2269
2270   newmsg->transmit_cont = cont;
2271   newmsg->transmit_cont_cls = cont_cls;
2272   newmsg->timeout = GNUNET_TIME_relative_to_absolute (timeout);
2273
2274   newmsg->timeout.abs_value = newmsg->timeout.abs_value - 500;
2275
2276   newmsg->message_size = msgbuf_size + sizeof (struct WlanHeader);
2277
2278   GNUNET_CONTAINER_DLL_insert_tail (session->pending_message_head,
2279                                     session->pending_message_tail, newmsg);
2280
2281 #if DEBUG_wlan
2282   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
2283                    "New message for %p with size (incl wlan header) %u added\n",
2284                    session, newmsg->message_size);
2285 #endif
2286 #if DEBUG_wlan_msg_dump > 1
2287   hexdump (msgbuf, GNUNET_MIN (msgbuf_size, 256));
2288 #endif
2289   //queue session
2290   queue_session (plugin, session);
2291
2292   check_fragment_queue (plugin);
2293   //FIXME not the correct size
2294   return msgbuf_size;
2295
2296 }
2297
2298 /**
2299  * function to free a mac endpoint
2300  * @param plugin pointer to the plugin struct
2301  * @param endpoint pointer to the MacEndpoint to free
2302  */
2303 static void
2304 free_macendpoint (struct Plugin *plugin, struct MacEndpoint *endpoint)
2305 {
2306   struct Sessionqueue *sessions;
2307   struct Sessionqueue *sessions_next;
2308
2309   GNUNET_assert (endpoint != NULL);
2310
2311   sessions = endpoint->sessions_head;
2312   while (sessions != NULL)
2313   {
2314     sessions_next = sessions->next;
2315     free_session (plugin, sessions, GNUNET_NO);
2316     sessions = sessions_next;
2317   }
2318
2319   GNUNET_CONTAINER_DLL_remove (plugin->mac_head, plugin->mac_tail, endpoint);
2320   if (endpoint->timeout_task != GNUNET_SCHEDULER_NO_TASK)
2321     GNUNET_SCHEDULER_cancel (endpoint->timeout_task);
2322   plugin->mac_count--;
2323   GNUNET_STATISTICS_set(plugin->env->stats, _("# wlan mac endpoints"), plugin->mac_count, GNUNET_NO);
2324   GNUNET_free (endpoint);
2325
2326 }
2327
2328 /**
2329  * function to free a session
2330  * @param plugin pointer to the plugin
2331  * @param queue pointer to the sessionqueue element to free
2332  * @param free_macendpoint if GNUNET_YES and mac endpoint would be empty, free mac endpoint
2333  */
2334 static void
2335 free_session (struct Plugin *plugin, struct Sessionqueue *queue,
2336               int do_free_macendpoint)
2337 {
2338   struct Sessionqueue *pendingsession;
2339   struct Sessionqueue *pendingsession_tmp;
2340   struct PendingMessage *pm;
2341   struct MacEndpoint *endpoint;
2342   struct FragmentMessage *fm;
2343   struct FragmentMessage *fmnext;
2344   int check = 0;
2345
2346   GNUNET_assert (plugin != NULL);
2347   GNUNET_assert (queue != NULL);
2348   GNUNET_assert (queue->content != NULL);
2349
2350   //session found
2351   //is this session pending for send
2352   pendingsession = plugin->pending_Sessions_head;
2353   while (pendingsession != NULL)
2354   {
2355     pendingsession_tmp = pendingsession;
2356     pendingsession = pendingsession->next;
2357     GNUNET_assert (pendingsession_tmp->content != NULL);
2358     if (pendingsession_tmp->content == queue->content)
2359     {
2360       plugin->pendingsessions--;
2361       GNUNET_STATISTICS_set(plugin->env->stats, _("# wlan pending sessions"), plugin->pendingsessions, GNUNET_NO);
2362       GNUNET_CONTAINER_DLL_remove (plugin->pending_Sessions_head,
2363                                    plugin->pending_Sessions_tail,
2364                                    pendingsession_tmp);
2365       GNUNET_free (pendingsession_tmp);
2366
2367       GNUNET_assert (check == 0);
2368       check = 1;
2369     }
2370   }
2371
2372   endpoint = queue->content->mac;
2373   fm = endpoint->sending_messages_head;
2374   while (fm != NULL)
2375   {
2376     fmnext = fm->next;
2377     if (fm->session == queue->content)
2378     {
2379       free_fragment_message (plugin, fm);
2380     }
2381     fm = fmnext;
2382   }
2383
2384   // remove PendingMessage
2385   pm = queue->content->pending_message_head;
2386   while (pm != NULL)
2387   {
2388     GNUNET_CONTAINER_DLL_remove (queue->content->pending_message_head,
2389                                  queue->content->pending_message_tail, pm);
2390     GNUNET_free (pm->msg);
2391     GNUNET_free (pm);
2392     pm = queue->content->pending_message_head;
2393   }
2394
2395   GNUNET_CONTAINER_DLL_remove (endpoint->sessions_head, endpoint->sessions_tail,
2396                                queue);
2397   //Check that no ohter session on this endpoint for this session exits
2398   GNUNET_assert(search_session(plugin, endpoint, &queue->content->target) == NULL);
2399   if (endpoint->sessions_head == NULL && do_free_macendpoint == GNUNET_YES)
2400   {
2401     free_macendpoint (plugin, endpoint);
2402     //check if no endpoint with the same address exists
2403     GNUNET_assert(get_macendpoint(plugin, &endpoint->addr, GNUNET_NO) == NULL);
2404   }
2405
2406   if (queue->content->timeout_task != GNUNET_SCHEDULER_NO_TASK)
2407     GNUNET_SCHEDULER_cancel (queue->content->timeout_task);
2408   GNUNET_free (queue);
2409
2410   check_fragment_queue (plugin);
2411 }
2412
2413 /**
2414  * Function that can be used to force the plugin to disconnect
2415  * from the given peer and cancel all previous transmissions
2416  * (and their continuation).
2417  *
2418  * @param cls closure
2419  * @param target peer from which to disconnect
2420  */
2421 static void
2422 wlan_plugin_disconnect (void *cls, const struct GNUNET_PeerIdentity *target)
2423 {
2424   struct Plugin *plugin = cls;
2425   struct Sessionqueue *queue;
2426   struct Sessionqueue *queue_next;
2427   struct MacEndpoint *endpoint = plugin->mac_head;
2428   struct MacEndpoint *endpoint_next;
2429
2430   // just look at all the session for the needed one
2431   while (endpoint != NULL)
2432   {
2433     queue = endpoint->sessions_head;
2434     endpoint_next = endpoint->next;
2435     while (queue != NULL)
2436     {
2437       // content is never NULL
2438       GNUNET_assert (queue->content != NULL);
2439       queue_next = queue->next;
2440       if (memcmp
2441           (target, &(queue->content->target),
2442            sizeof (struct GNUNET_PeerIdentity)) == 0)
2443       {
2444         free_session (plugin, queue, GNUNET_YES);
2445       }
2446       // try next
2447       queue = queue_next;
2448     }
2449     endpoint = endpoint_next;
2450   }
2451 }
2452
2453 /**
2454  * Convert the transports address to a nice, human-readable
2455  * format.
2456  *
2457  * @param cls closure
2458  * @param type name of the transport that generated the address
2459  * @param addr one of the addresses of the host, NULL for the last address
2460  *        the specific address format depends on the transport
2461  * @param addrlen length of the address
2462  * @param numeric should (IP) addresses be displayed in numeric form?
2463  * @param timeout after how long should we give up?
2464  * @param asc function to call on each string
2465  * @param asc_cls closure for asc
2466  */
2467 static void
2468 wlan_plugin_address_pretty_printer (void *cls, const char *type,
2469                                     const void *addr, size_t addrlen,
2470                                     int numeric,
2471                                     struct GNUNET_TIME_Relative timeout,
2472                                     GNUNET_TRANSPORT_AddressStringCallback asc,
2473                                     void *asc_cls)
2474 {
2475   char *ret;
2476   const unsigned char *input;
2477
2478   //GNUNET_assert(cls !=NULL);
2479   if (addrlen != sizeof(struct MacAddress))
2480   {
2481     /* invalid address (MAC addresses have 6 bytes) */
2482     //GNUNET_break (0);
2483 #if DEBUG_wlan
2484       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
2485                    "Func wlan_plugin_address_pretty_printer got size: %u, worng size!\n",
2486                    addrlen);
2487 #endif
2488     asc(asc_cls, NULL);
2489     return;
2490   }
2491   input = (const unsigned char *) addr;
2492   GNUNET_asprintf (&ret,
2493                    "Transport %s: %s Mac-Address %.2X:%.2X:%.2X:%.2X:%.2X:%.2X",type,
2494                    PROTOCOL_PREFIX, input[0], input[1], input[2], input[3],
2495                    input[4], input[5]);
2496 #if DEBUG_wlan
2497   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
2498                    "Func wlan_plugin_address_pretty_printer got size: %u, nummeric %u, type %s; made string: %s\n",
2499                    addrlen, numeric, type, ret);
2500 #endif
2501   asc ( asc_cls, ret);
2502   //only one mac address per plugin
2503   asc ( asc_cls, NULL);
2504 }
2505
2506
2507
2508 /**
2509  * handels the data after all fragments are put together
2510  * @param cls macendpoint this messages belongs to
2511  * @param hdr pointer to the data
2512  */
2513 static void
2514 wlan_data_message_handler (void *cls, const struct GNUNET_MessageHeader *hdr)
2515 {
2516   struct MacEndpoint *endpoint = (struct MacEndpoint *) cls;
2517   struct Plugin *plugin = endpoint->plugin;
2518   struct WlanHeader *wlanheader;
2519   struct Session *session;
2520
2521   const struct GNUNET_MessageHeader *temp_hdr;
2522   struct GNUNET_PeerIdentity tmpsource;
2523   int crc;
2524
2525   GNUNET_assert (plugin != NULL);
2526
2527   if (ntohs (hdr->type) == GNUNET_MESSAGE_TYPE_WLAN_DATA)
2528   {
2529
2530 #if DEBUG_wlan
2531     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
2532                      "Func wlan_data_message_handler got GNUNET_MESSAGE_TYPE_WLAN_DATA size: %u\n",
2533                      ntohs (hdr->size));
2534 #endif
2535
2536     if (ntohs (hdr->size) <
2537         sizeof (struct WlanHeader) + sizeof (struct GNUNET_MessageHeader))
2538     {
2539       //packet not big enought
2540       return;
2541     }
2542
2543     GNUNET_STATISTICS_update (plugin->env->stats, _("# wlan whole messages received"), 1, GNUNET_NO);
2544     wlanheader = (struct WlanHeader *) hdr;
2545
2546     session = search_session (plugin, endpoint, &wlanheader->source);
2547
2548     temp_hdr = (const struct GNUNET_MessageHeader *) &wlanheader[1];
2549     crc = ntohl (wlanheader->crc);
2550     wlanheader->crc = 0;
2551     if (getcrc32 ((char *) wlanheader, ntohs (wlanheader->header.size)) != crc)
2552     {
2553       //wrong crc, dispose message
2554       GNUNET_log_from (GNUNET_ERROR_TYPE_INFO, PLUGIN_LOG_NAME,
2555                        "Wlan message header crc was wrong: %u != %u\n",
2556                        getcrc32 ((char *) wlanheader,
2557                                  ntohs (wlanheader->header.size)), crc);
2558       hexdump ((void *) hdr, ntohs (hdr->size));
2559       return;
2560     }
2561
2562     //if not in session list
2563     if (session == NULL)
2564     {
2565 #if DEBUG_wlan
2566       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
2567                        "WLAN client not in session list: packet size = %u, inner size = %u, header size = %u\n",
2568                        ntohs (wlanheader->header.size), ntohs (temp_hdr->size),
2569                        sizeof (struct WlanHeader));
2570 #endif
2571       //try if it is a hello message
2572       if (ntohs (wlanheader->header.size) >=
2573           ntohs (temp_hdr->size) + sizeof (struct WlanHeader))
2574       {
2575         if (ntohs (temp_hdr->type) == GNUNET_MESSAGE_TYPE_HELLO)
2576         {
2577           if (GNUNET_HELLO_get_id
2578               ((const struct GNUNET_HELLO_Message *) temp_hdr,
2579                &tmpsource) == GNUNET_OK)
2580           {
2581             session = create_session (plugin, endpoint, &tmpsource);
2582           }
2583           else
2584           {
2585             GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, PLUGIN_LOG_NAME,
2586                              "WLAN client not in session list and hello message is not okay\n");
2587             return;
2588           }
2589
2590         }
2591         else
2592         {
2593           GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, PLUGIN_LOG_NAME,
2594                            "WLAN client not in session list and not a hello message\n");
2595           return;
2596         }
2597       }
2598       else
2599       {
2600         GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, PLUGIN_LOG_NAME,
2601                          "WLAN client not in session list and message size in does not fit\npacket size = %u, inner size = %u, header size = %u\n",
2602                          ntohs (wlanheader->header.size),
2603                          ntohs (temp_hdr->size), sizeof (struct WlanHeader));
2604         return;
2605       }
2606     }
2607
2608     //"receive" the message
2609
2610     if (memcmp
2611         (&wlanheader->source, &session->target,
2612          sizeof (struct GNUNET_PeerIdentity)) != 0)
2613     {
2614       //wrong peer id
2615 #if DEBUG_wlan
2616       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
2617                        "WLAN peer source id doesn't match packet peer source id: session %p\n",
2618                        session);
2619 #endif
2620       return;
2621     }
2622
2623     if (memcmp
2624         (&wlanheader->target, plugin->env->my_identity,
2625          sizeof (struct GNUNET_PeerIdentity)) != 0)
2626     {
2627       //wrong peer id
2628 #if DEBUG_wlan
2629       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
2630                        "WLAN peer target id doesn't match our peer id: session %p\n",
2631                        session);
2632 #endif
2633       return;
2634     }
2635
2636     GNUNET_SERVER_mst_receive (plugin->data_tokenizer, session,
2637                                (const char *) temp_hdr,
2638                                ntohs (hdr->size) - sizeof (struct WlanHeader),
2639                                GNUNET_YES, GNUNET_NO);
2640
2641     return;
2642   }
2643   else
2644   {
2645     GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, PLUGIN_LOG_NAME,
2646                      "wlan_data_message_handler got wrong message type: %u\n",
2647                      ntohs (hdr->size));
2648     return;
2649   }
2650 }
2651
2652 /**
2653  * function to process the a message, give it to the higher layer
2654  * @param cls pointer to the plugin
2655  * @param client pointer to the session this message belongs to
2656  * @param hdr start of the message
2657  */
2658 //TODO ATS informations
2659 static void
2660 process_data (void *cls, void *client, const struct GNUNET_MessageHeader *hdr)
2661 {
2662
2663   GNUNET_assert (client != NULL);
2664   GNUNET_assert (cls != NULL);
2665   struct Session *session = (struct Session *) client;
2666   struct Plugin *plugin = (struct Plugin *) cls;
2667
2668   struct GNUNET_ATS_Information distance;
2669
2670   distance.type = htonl (GNUNET_ATS_QUALITY_NET_DISTANCE);
2671   distance.value = htonl (1);
2672
2673 #if DEBUG_wlan
2674   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
2675                    "Calling plugin->env->receive for session %p; %s; size: %u\n",
2676                    session, wlan_plugin_address_to_string (NULL,
2677                                                            session->mac->
2678                                                            addr.mac, 6),
2679                    htons (hdr->size));
2680 #endif
2681
2682   plugin->env->receive (plugin->env->cls, &(session->target), hdr,
2683                         (const struct GNUNET_ATS_Information *)
2684                         &distance, 1, session,
2685                         (const char *) &session->mac->addr,
2686                         sizeof (session->mac->addr));
2687 }
2688
2689 /**
2690  * Function used for to process the data received from the wlan interface
2691  *
2692  * @param cls the plugin handle
2693  * @param session_light pointer to the struct holding known informations
2694  * @param hdr hdr of the GNUNET_MessageHeader
2695  * @param rxinfo pointer to the radiotap informations got with this packet
2696  */
2697 static void
2698 wlan_data_helper (void *cls, struct Session_light *session_light,
2699                   const struct GNUNET_MessageHeader *hdr,
2700                   const struct Radiotap_rx *rxinfo)
2701 {
2702   struct Plugin *plugin = cls;
2703   struct FragmentMessage *fm;
2704   struct FragmentMessage *fm2;
2705   struct GNUNET_PeerIdentity tmpsource;
2706
2707   GNUNET_assert(plugin != NULL);
2708
2709   //ADVERTISEMENT
2710   if (ntohs (hdr->type) == GNUNET_MESSAGE_TYPE_HELLO)
2711   {
2712
2713     //TODO better DOS protection, error handling
2714     //TODO test first than create session
2715     GNUNET_assert (session_light != NULL);
2716
2717 #if DEBUG_wlan
2718     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
2719                      "Func wlan_data_helper got GNUNET_MESSAGE_TYPE_HELLO size: %u; %s\n",
2720                      ntohs (hdr->size), wlan_plugin_address_to_string (NULL,
2721                                                                        session_light->addr.
2722                                                                        mac, 6));
2723 #endif
2724
2725     if (session_light->macendpoint == NULL)
2726     {
2727       session_light->macendpoint =
2728           get_macendpoint (plugin, &session_light->addr, GNUNET_YES);
2729     }
2730
2731
2732     if (GNUNET_HELLO_get_id
2733         ((const struct GNUNET_HELLO_Message *) hdr,
2734          &tmpsource) == GNUNET_OK)
2735     {
2736         session_light->session = search_session (plugin, session_light->macendpoint, &tmpsource);
2737       if (session_light->session == NULL)
2738         {
2739           session_light->session = create_session (plugin, session_light->macendpoint, &tmpsource);
2740         }
2741       GNUNET_STATISTICS_update (plugin->env->stats, _("# wlan hello messages received"), 1, GNUNET_NO);
2742       plugin->env->receive(plugin->env->cls,&session_light->session->target,hdr, NULL, 0, session_light->session,
2743           (const char *) &session_light->session->mac->addr,
2744           sizeof (session_light->session->mac->addr));
2745     }
2746     else
2747     {
2748       GNUNET_log_from (GNUNET_ERROR_TYPE_WARNING, PLUGIN_LOG_NAME,
2749                        "WLAN client not in session list and hello message is not okay\n");
2750       return;
2751     }
2752   }
2753
2754   //FRAGMENT
2755
2756   else if (ntohs (hdr->type) == GNUNET_MESSAGE_TYPE_FRAGMENT)
2757   {
2758
2759     GNUNET_assert (session_light != NULL);
2760     if (session_light->macendpoint == NULL)
2761     {
2762       session_light->macendpoint =
2763           get_macendpoint (plugin, &session_light->addr, GNUNET_YES);
2764     }
2765
2766 #if DEBUG_wlan
2767     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
2768                      "Func wlan_data_helper got GNUNET_MESSAGE_TYPE_FRAGMENT with size: %u; mac endpoint %p: %s\n",
2769                      ntohs (hdr->size), session_light->macendpoint,
2770                      wlan_plugin_address_to_string (NULL,
2771                                                     session_light->addr.mac,
2772                                                     6));
2773 #endif
2774
2775     GNUNET_STATISTICS_update (plugin->env->stats, _("# wlan fragments received"), 1, GNUNET_NO);
2776     int ret =
2777         GNUNET_DEFRAGMENT_process_fragment (session_light->macendpoint->defrag,
2778                                             hdr);
2779
2780     if (ret == GNUNET_NO)
2781     {
2782       session_light->macendpoint->dups++;
2783     }
2784     else if (ret == GNUNET_OK)
2785     {
2786       session_light->macendpoint->fragc++;
2787     }
2788     set_next_send (plugin);
2789
2790   }
2791
2792   //ACK
2793
2794   else if (ntohs (hdr->type) == GNUNET_MESSAGE_TYPE_FRAGMENT_ACK)
2795   {
2796     GNUNET_assert (session_light != NULL);
2797     if (session_light->macendpoint == NULL)
2798     {
2799       session_light->macendpoint =
2800           get_macendpoint (plugin, &session_light->addr, GNUNET_NO);
2801     }
2802
2803     if (session_light->macendpoint == NULL)
2804     {
2805 #if DEBUG_wlan
2806       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
2807                        "Macendpoint does not exist for this GNUNET_MESSAGE_TYPE_FRAGMENT_ACK size: %u; %s\n",
2808                        ntohs (hdr->size), wlan_plugin_address_to_string (NULL,
2809                                                                          session_light->addr.mac,
2810                                                                          6));
2811 #endif
2812       return;
2813     }
2814
2815 #if DEBUG_wlan
2816     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
2817                      "Func wlan_data_helper got GNUNET_MESSAGE_TYPE_FRAGMENT_ACK size: %u; mac endpoint: %p; %s\n",
2818                      ntohs (hdr->size), session_light->macendpoint,
2819                      wlan_plugin_address_to_string (NULL,
2820                                                     session_light->addr.mac,
2821                                                     6));
2822 #endif
2823     fm = session_light->macendpoint->sending_messages_head;
2824     while (fm != NULL)
2825     {
2826       fm2 = fm->next;
2827       GNUNET_STATISTICS_update (plugin->env->stats, _("# wlan acks received"), 1, GNUNET_NO);
2828       int ret = GNUNET_FRAGMENT_process_ack (fm->fragcontext, hdr);
2829
2830       if (ret == GNUNET_OK)
2831       {
2832 #if DEBUG_wlan_retransmission > 1
2833         GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
2834                          "Got last ack, finished fragment message %p\n", fm);
2835 #endif
2836         session_light->macendpoint->acks++;
2837         fm->session->last_activity = GNUNET_TIME_absolute_get ();
2838         session_light->macendpoint->last_activity = fm->session->last_activity;
2839         free_fragment_message (plugin, fm);
2840         check_fragment_queue (plugin);
2841         return;
2842       }
2843       if (ret == GNUNET_NO)
2844       {
2845 #if DEBUG_wlan_retransmission > 1
2846         GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
2847                          "Got ack for: %p\n", fm);
2848 #endif
2849         session_light->macendpoint->acks++;
2850         return;
2851       }
2852       if (ret == GNUNET_SYSERR)
2853       {
2854
2855       }
2856
2857       fm = fm2;
2858     }
2859
2860 #if DEBUG_wlan_retransmission > 1
2861     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
2862                      "WLAN fragment not in fragment list\n");
2863 #endif
2864     return;
2865
2866   }
2867   else
2868   {
2869     // TODO Wrong data?
2870     GNUNET_log_from (GNUNET_ERROR_TYPE_INFO, PLUGIN_LOG_NAME,
2871                      "WLAN packet inside the WLAN helper packet has not the right type: %u size: %u\n",
2872                      ntohs (hdr->type), ntohs (hdr->size));
2873     GNUNET_break (0);
2874     return;
2875   }
2876
2877 #if 0
2878   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
2879                    "Helper finished\n");
2880 #endif
2881
2882 }
2883
2884 /**
2885  * Function to print mac addresses nice *
2886  * @param pointer to 6 byte with the mac address
2887  * @return pointer to the chars which hold the print out
2888  */
2889 const char *
2890 macprinter (const u_int8_t * mac)
2891 {
2892   static char macstr[20];
2893
2894   GNUNET_snprintf (macstr, sizeof (macstr), "%X:%X:%X:%X:%X:%X", mac[0], mac[1],
2895                    mac[2], mac[3], mac[4], mac[5]);
2896   return macstr;
2897 }
2898
2899 /**
2900  * Function for the scheduler if a mac endpoint times out
2901  * @param cls pointer to the MacEndpoint
2902  * @param tc pointer to the GNUNET_SCHEDULER_TaskContext
2903  */
2904 static void
2905 macendpoint_timeout (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2906 {
2907   struct MacEndpoint *endpoint = cls;
2908
2909   GNUNET_assert (endpoint != NULL);
2910   endpoint->timeout_task = GNUNET_SCHEDULER_NO_TASK;
2911   if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
2912   {
2913     return;
2914   }
2915   if (GNUNET_TIME_absolute_get_remaining
2916       (GNUNET_TIME_absolute_add
2917        (endpoint->last_activity, MACENDPOINT_TIMEOUT)).rel_value == 0)
2918   {
2919     GNUNET_assert(endpoint->plugin != NULL);
2920     GNUNET_STATISTICS_update (endpoint->plugin->env->stats, _("# wlan mac endpoints timeouts"), 1, GNUNET_NO);
2921     free_macendpoint (endpoint->plugin, endpoint);
2922   }
2923   else
2924   {
2925     endpoint->timeout_task =
2926         GNUNET_SCHEDULER_add_delayed (MACENDPOINT_TIMEOUT, &macendpoint_timeout,
2927                                       endpoint);
2928   }
2929 }
2930
2931 /**
2932  * function to create an macendpoint
2933  * @param plugin pointer to the plugin struct
2934  * @param addr pointer to the macaddress
2935  * @return returns a macendpoint
2936  */
2937 static struct MacEndpoint *
2938 create_macendpoint (struct Plugin *plugin, const struct MacAddress *addr)
2939 {
2940   struct MacEndpoint *newend = GNUNET_malloc (sizeof (struct MacEndpoint));
2941
2942   GNUNET_assert(plugin != NULL);
2943   GNUNET_STATISTICS_update (plugin->env->stats, _("# wlan mac endpoints created"), 1, GNUNET_NO);
2944   newend->addr = *addr;
2945   newend->plugin = plugin;
2946   newend->addr = *addr;
2947   newend->fragment_messages_out_count = 0;
2948   newend->defrag =
2949       GNUNET_DEFRAGMENT_context_create (plugin->env->stats, WLAN_MTU,
2950                                         MESSAGES_IN_DEFRAG_QUEUE_PER_MAC,
2951                                         newend, &wlan_data_message_handler,
2952                                         &add_ack_for_send);
2953   newend->last_activity = GNUNET_TIME_absolute_get ();
2954   newend->timeout_task =
2955       GNUNET_SCHEDULER_add_delayed (MACENDPOINT_TIMEOUT, &macendpoint_timeout,
2956                                     newend);
2957
2958   plugin->mac_count++;
2959   GNUNET_STATISTICS_set(plugin->env->stats, _("# wlan mac endpoints"), plugin->mac_count, GNUNET_NO);
2960   GNUNET_CONTAINER_DLL_insert_tail (plugin->mac_head, plugin->mac_tail, newend);
2961 #if DEBUG_wlan
2962   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
2963                    "New Mac Endpoint %p: %s\n", newend,
2964                    wlan_plugin_address_to_string (NULL, newend->addr.mac, 6));
2965 #endif
2966   return newend;
2967 }
2968
2969 /**
2970  * Function used for to process the data from the suid process
2971  *
2972  * @param cls the plugin handle
2973  * @param client client that send the data (not used)
2974  * @param hdr header of the GNUNET_MessageHeader
2975  */
2976 static void
2977 wlan_process_helper (void *cls, void *client,
2978                      const struct GNUNET_MessageHeader *hdr)
2979 {
2980   struct Plugin *plugin = cls;
2981   struct ieee80211_frame *wlanIeeeHeader = NULL;
2982   struct Session_light *session_light = NULL;
2983   struct Radiotap_rx *rxinfo;
2984   const struct GNUNET_MessageHeader *temp_hdr = NULL;
2985
2986   int datasize = 0;
2987   int pos;
2988
2989   GNUNET_assert(plugin != NULL);
2990   switch (ntohs (hdr->type))
2991   {
2992   case GNUNET_MESSAGE_TYPE_WLAN_HELPER_DATA:
2993 #if DEBUG_wlan
2994     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
2995                      "Func wlan_process_helper got GNUNET_MESSAGE_TYPE_WLAN_HELPER_DATA size: %u\n",
2996                      ntohs (hdr->size));
2997 #endif
2998
2999     GNUNET_STATISTICS_update (plugin->env->stats, _("# wlan WLAN_HELPER_DATA received"), 1, GNUNET_NO);
3000     //call wlan_process_helper with the message inside, later with wlan: analyze signal
3001     if (ntohs (hdr->size) <
3002         sizeof (struct ieee80211_frame) + 2*sizeof (struct GNUNET_MessageHeader) +
3003         sizeof (struct Radiotap_rx))
3004     {
3005 #if DEBUG_wlan
3006       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
3007                        "Size of packet is too small; size: %u min size: %u\n",
3008                        ntohs (hdr->size),
3009                        sizeof (struct ieee80211_frame) +
3010                        sizeof (struct GNUNET_MessageHeader));
3011 #endif
3012       //GNUNET_break (0);
3013       /* FIXME: restart SUID process */
3014       return;
3015     }
3016
3017     rxinfo = (struct Radiotap_rx *) &hdr[1];
3018     wlanIeeeHeader = (struct ieee80211_frame *) &rxinfo[1];
3019
3020     //process only if it is an broadcast or for this computer both with the gnunet bssid
3021
3022     //check for bssid
3023     if (memcmp
3024         (&(wlanIeeeHeader->i_addr3), &mac_bssid,
3025          sizeof (struct MacAddress)) == 0)
3026     {
3027       //check for broadcast or mac
3028       if ((memcmp
3029           (&(wlanIeeeHeader->i_addr1), &bc_all_mac,
3030            sizeof (struct MacAddress)) == 0) ||
3031           (memcmp (&(wlanIeeeHeader->i_addr1), &(plugin->mac_address),
3032                   sizeof (struct MacAddress)) == 0))
3033       {
3034           //if packet is from us return
3035           if ((memcmp (&(wlanIeeeHeader->i_addr2), &(plugin->mac_address),
3036                   sizeof (struct MacAddress)) == 0)){
3037               return;
3038           }
3039         // process the inner data
3040
3041
3042         datasize =
3043             ntohs (hdr->size) - sizeof (struct ieee80211_frame) -
3044             sizeof (struct GNUNET_MessageHeader) - sizeof (struct Radiotap_rx);
3045
3046         session_light = GNUNET_malloc (sizeof (struct Session_light));
3047         memcpy (&session_light->addr, &(wlanIeeeHeader->i_addr2),
3048                 sizeof (struct MacAddress));
3049         //session_light->session = search_session(plugin,session_light->addr);
3050         GNUNET_STATISTICS_update (plugin->env->stats, _("# wlan messaged for this client received"), 1, GNUNET_NO);
3051
3052         pos = 0;
3053         while (pos < datasize)
3054         {
3055           temp_hdr = (struct GNUNET_MessageHeader *) &wlanIeeeHeader[1] + pos;
3056           if (ntohs(temp_hdr->size) <= datasize + pos)
3057             {
3058               GNUNET_STATISTICS_update (plugin->env->stats, _("# wlan messaged inside WLAN_HELPER_DATA received"), 1, GNUNET_NO);
3059               wlan_data_helper (plugin, session_light, temp_hdr, rxinfo);
3060             }
3061           else
3062             {
3063 #if DEBUG_wlan
3064             GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
3065                        "Size of packet is too small; size: %u > size of packet: %u\n",
3066                        ntohs(temp_hdr->size),datasize + pos);
3067 #endif
3068             }
3069           pos += ntohs (temp_hdr->size);
3070
3071         }
3072
3073         //clean up
3074         GNUNET_free (session_light);
3075       }
3076       else
3077       {
3078 #if DEBUG_wlan
3079         GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
3080                          "Func wlan_process_helper got wrong MAC: %s\n",
3081                          macprinter (wlanIeeeHeader->i_addr1));
3082 #endif
3083       }
3084     }
3085     else
3086     {
3087 #if DEBUG_wlan
3088       GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
3089                        "Func wlan_process_helper got wrong BSSID: %s\n",
3090                        macprinter (wlanIeeeHeader->i_addr2));
3091 #endif
3092     }
3093     break;
3094   case GNUNET_MESSAGE_TYPE_WLAN_HELPER_CONTROL:
3095     //TODO more control messages
3096     if (ntohs (hdr->size) != sizeof (struct Wlan_Helper_Control_Message))
3097     {
3098       GNUNET_break (0);
3099       /* FIXME: restart SUID process */
3100       return;
3101     }
3102     memcpy (&plugin->mac_address, &hdr[1], sizeof (struct MacAddress));
3103 #if DEBUG_wlan
3104     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
3105                      "Received WLAN_HELPER_CONTROL message with transport of address %s\n",
3106                      wlan_plugin_address_to_string (cls, &plugin->mac_address,
3107                                                     sizeof (struct
3108                                                             MacAddress)));
3109 #endif
3110     plugin->env->notify_address (plugin->env->cls, GNUNET_YES,
3111                                  &plugin->mac_address,
3112                                  sizeof (struct MacAddress));
3113     break;
3114   default:
3115 #if DEBUG_wlan
3116     GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
3117                      "Func wlan_process_helper got unknown message with number %u, size %u\n",
3118                      ntohs (hdr->type), ntohs (hdr->size));
3119
3120 #endif
3121 #if DEBUG_wlan_msg_dump > 1
3122     hexdump (hdr, GNUNET_MIN (ntohs (hdr->size), 256));
3123 #endif
3124     GNUNET_break (0);
3125     return;
3126   }
3127 }
3128
3129 /**
3130  * Exit point from the plugin.
3131  * @param cls pointer to the api struct
3132  */
3133
3134 //FIXME cleanup
3135 void *
3136 libgnunet_plugin_transport_wlan_done (void *cls)
3137 {
3138   struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
3139   struct Plugin *plugin = api->cls;
3140   struct MacEndpoint *endpoint = plugin->mac_head;
3141   struct MacEndpoint *endpoint_next;
3142
3143 #if DEBUG_wlan
3144   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
3145                    "libgnunet_plugin_transport_wlan_done started\n");
3146 #endif
3147
3148   wlan_transport_stop_wlan_helper(plugin);
3149
3150   GNUNET_assert (cls != NULL);
3151   //free sessions
3152   while (endpoint != NULL)
3153   {
3154     endpoint_next = endpoint->next;
3155     free_macendpoint (plugin, endpoint);
3156     endpoint = endpoint_next;
3157
3158   }
3159
3160
3161   if (plugin->suid_tokenizer != NULL)
3162     GNUNET_SERVER_mst_destroy (plugin->suid_tokenizer);
3163
3164   if (plugin->data_tokenizer != NULL)
3165     GNUNET_SERVER_mst_destroy (plugin->data_tokenizer);
3166
3167   GNUNET_free_non_null (plugin->interface);
3168   GNUNET_free (plugin);
3169   GNUNET_free (api);
3170   return NULL;
3171 }
3172
3173 /**
3174  * Entry point for the plugin.
3175  *
3176  * @param cls closure, the 'struct GNUNET_TRANSPORT_PluginEnvironment*'
3177  * @return the 'struct GNUNET_TRANSPORT_PluginFunctions*' or NULL on error
3178  */
3179 void *
3180 libgnunet_plugin_transport_wlan_init (void *cls)
3181 {
3182   //struct GNUNET_SERVICE_Context *service;
3183   struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
3184   struct GNUNET_TRANSPORT_PluginFunctions *api;
3185   struct Plugin *plugin;
3186
3187   GNUNET_assert (cls != NULL);
3188
3189   plugin = GNUNET_malloc (sizeof (struct Plugin));
3190   plugin->env = env;
3191   plugin->pendingsessions = 0;
3192   GNUNET_STATISTICS_set(plugin->env->stats, _("# wlan pending sessions"), plugin->pendingsessions, GNUNET_NO);
3193   plugin->mac_count = 0;
3194   GNUNET_STATISTICS_set(plugin->env->stats, _("# wlan mac endpoints"), plugin->mac_count, GNUNET_NO);
3195   plugin->server_write_task = GNUNET_SCHEDULER_NO_TASK;
3196   plugin->server_read_task = GNUNET_SCHEDULER_NO_TASK;
3197   plugin->server_write_delay_task = GNUNET_SCHEDULER_NO_TASK;
3198   GNUNET_BANDWIDTH_tracker_init (&plugin->tracker,
3199                                  GNUNET_BANDWIDTH_value_init (100 * 1024 *
3200                                                               1024 / 8), 100);
3201
3202   plugin->suid_tokenizer =
3203       GNUNET_SERVER_mst_create (&wlan_process_helper, plugin);
3204
3205   plugin->data_tokenizer = GNUNET_SERVER_mst_create (&process_data, plugin);
3206
3207   //plugin->sessions = GNUNET_malloc (sizeof (struct Sessionqueue));
3208   //plugin->pending_Sessions_head = GNUNET_malloc (sizeof (struct Sessionqueue));
3209
3210   api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
3211   api->cls = plugin;
3212   api->send = &wlan_plugin_send;
3213   api->disconnect = &wlan_plugin_disconnect;
3214   api->address_pretty_printer = &wlan_plugin_address_pretty_printer;
3215   api->check_address = &wlan_plugin_address_suggested;
3216   api->address_to_string = &wlan_plugin_address_to_string;
3217
3218   //read config
3219
3220   if (GNUNET_CONFIGURATION_have_value (env->cfg, "transport-wlan", "TESTMODE"))
3221   {
3222     if (GNUNET_SYSERR ==
3223         GNUNET_CONFIGURATION_get_value_number (env->cfg, "transport-wlan",
3224                                                "TESTMODE", &(plugin->testmode)))
3225       plugin->testmode = 0;             //default value
3226   }
3227
3228   if (GNUNET_CONFIGURATION_have_value (env->cfg, "transport-wlan", "INTERFACE"))
3229   {
3230     if (GNUNET_CONFIGURATION_get_value_string
3231         (env->cfg, "transport-wlan", "INTERFACE",
3232          &(plugin->interface)) != GNUNET_YES)
3233     {
3234       libgnunet_plugin_transport_wlan_done (api);
3235       return NULL;
3236     }
3237   }
3238
3239   //start the plugin
3240   wlan_transport_start_wlan_helper (plugin);
3241   set_next_beacon_time (plugin);
3242   set_next_send(plugin);
3243 #if DEBUG_wlan
3244   GNUNET_log_from (GNUNET_ERROR_TYPE_DEBUG, PLUGIN_LOG_NAME,
3245                    "wlan init finished\n");
3246 #endif
3247
3248   return api;
3249 }
3250
3251 /* end of plugin_transport_wlan.c */