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