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