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