- fix error messages
[oweals/gnunet.git] / src / transport / plugin_transport_bluetooth.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_bluetooth.c
23  * @brief transport plugin for bluetooth
24  * @author David Brodski
25  * @author Christian Grothoff
26  *
27  * THIS IS A COPY OF plugin_transport_wlan.c
28  */
29 #include "platform.h"
30 #include "gnunet_hello_lib.h"
31 #include "gnunet_protocols.h"
32 #include "gnunet_util_lib.h"
33 #include "gnunet_statistics_service.h"
34 #include "gnunet_transport_service.h"
35 #include "gnunet_transport_plugin.h"
36 #include "plugin_transport_wlan.h"
37 #include "gnunet_common.h"
38 #include "gnunet_crypto_lib.h"
39 #include "gnunet_fragmentation_lib.h"
40 #include "gnunet_constants.h"
41
42 #ifdef MINGW
43  #undef interface
44 #endif
45
46 #define LOG(kind,...) GNUNET_log_from (kind, "transport-bluetooth",__VA_ARGS__)
47
48 #define PLUGIN_NAME "bluetooth"
49
50 /**
51  * Max size of packet (that we give to the WLAN driver for transmission)
52  */
53 #define WLAN_MTU 1430
54
55 /**
56  * time out of a mac endpoint
57  */
58 #define MACENDPOINT_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, 60)
59
60 /**
61  * We reduce the frequence of HELLO beacons in relation to
62  * the number of MAC addresses currently visible to us.
63  * This is the multiplication factor.
64  */
65 #define HELLO_BEACON_SCALING_FACTOR GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 60)
66
67 /**
68  * Maximum number of messages in defragmentation queue per MAC
69  */
70 #define MESSAGES_IN_DEFRAG_QUEUE_PER_MAC 2
71
72 /**
73  * Link layer control fields for better compatibility
74  * (i.e. GNUnet over WLAN is not IP-over-WLAN).
75  */
76 #define WLAN_LLC_DSAP_FIELD 0x1f
77 #define WLAN_LLC_SSAP_FIELD 0x1f
78
79
80 GNUNET_NETWORK_STRUCT_BEGIN
81 /**
82  * Header for messages which need fragmentation.  This is the format of
83  * a message we obtain AFTER defragmentation.  We then need to check
84  * the CRC and then tokenize the payload and pass it to the
85  * 'receive' callback.
86  */
87 struct WlanHeader
88 {
89
90   /**
91    * Message type is GNUNET_MESSAGE_TYPE_WLAN_DATA.
92    */
93   struct GNUNET_MessageHeader header;
94
95   /**
96    * CRC32 checksum (only over the payload), in NBO.
97    */
98   uint32_t crc GNUNET_PACKED;
99
100   /**
101    * Sender of the message.
102    */
103   struct GNUNET_PeerIdentity sender;
104
105   /**
106    * Target of the message.
107    */
108   struct GNUNET_PeerIdentity target;
109
110   /* followed by payload, possibly including
111      multiple messages! */
112
113 };
114
115
116 struct WlanAddress
117 {
118   uint32_t options GNUNET_PACKED;
119
120   struct GNUNET_TRANSPORT_WLAN_MacAddress mac;
121 };
122
123
124 GNUNET_NETWORK_STRUCT_END
125
126
127 /**
128  * Information kept for each message that is yet to be fragmented and
129  * transmitted.
130  */
131 struct PendingMessage
132 {
133   /**
134    * next entry in the DLL
135    */
136   struct PendingMessage *next;
137
138   /**
139    * previous entry in the DLL
140    */
141   struct PendingMessage *prev;
142
143   /**
144    * The pending message
145    */
146   struct WlanHeader *msg;
147
148   /**
149    * Continuation function to call once the message
150    * has been sent.  Can be NULL if there is no
151    * continuation to call.
152    */
153   GNUNET_TRANSPORT_TransmitContinuation transmit_cont;
154
155   /**
156    * Cls for transmit_cont
157    */
158   void *transmit_cont_cls;
159
160   /**
161    * Timeout task (for this message).
162    */
163   GNUNET_SCHEDULER_TaskIdentifier timeout_task;
164
165 };
166
167
168 /**
169  * Session handle for connections with other peers.
170  */
171 struct Session
172 {
173   /**
174    * To whom are we talking to (set to our identity
175    * if we are still waiting for the welcome message)
176    */
177   struct GNUNET_PeerIdentity target;
178
179   /**
180    * API requirement (must be first).
181    */
182   struct SessionHeader header;
183
184   /**
185    * We keep all sessions in a DLL at their respective
186    * 'struct MACEndpoint'.
187    */
188   struct Session *next;
189
190   /**
191    * We keep all sessions in a DLL at their respective
192    * 'struct MACEndpoint'.
193    */
194   struct Session *prev;
195
196   /**
197    * MAC endpoint with the address of this peer.
198    */
199   struct MacEndpoint *mac;
200
201   /**
202    * Head of messages currently pending for transmission to this peer.
203    */
204   struct PendingMessage *pending_message_head;
205
206   /**
207    * Tail of messages currently pending for transmission to this peer.
208    */
209   struct PendingMessage *pending_message_tail;
210
211   /**
212    * When should this session time out?
213    */
214   struct GNUNET_TIME_Absolute timeout;
215
216   /**
217    * Timeout task (for the session).
218    */
219   GNUNET_SCHEDULER_TaskIdentifier timeout_task;
220
221 };
222
223
224 /**
225  * Struct for messages that are being fragmented in a MAC's transmission queue.
226  */
227 struct FragmentMessage
228 {
229
230   /**
231    * This is a doubly-linked list.
232    */
233   struct FragmentMessage *next;
234
235   /**
236    * This is a doubly-linked list.
237    */
238   struct FragmentMessage *prev;
239
240   /**
241    * MAC endpoint this message belongs to
242    */
243   struct MacEndpoint *macendpoint;
244
245   /**
246    * Fragmentation context
247    */
248   struct GNUNET_FRAGMENT_Context *fragcontext;
249
250   /**
251    * Transmission handle to helper (to cancel if the frag context
252    * is destroyed early for some reason).
253    */
254   struct GNUNET_HELPER_SendHandle *sh;
255
256   /**
257    * Intended recipient.
258    */
259   struct GNUNET_PeerIdentity target;
260
261   /**
262    * Timeout value for the message.
263    */
264   struct GNUNET_TIME_Absolute timeout;
265
266   /**
267    * Timeout task.
268    */
269   GNUNET_SCHEDULER_TaskIdentifier timeout_task;
270
271   /**
272    * Continuation to call when we're done with this message.
273    */
274   GNUNET_TRANSPORT_TransmitContinuation cont;
275
276   /**
277    * Closure for 'cont'
278    */
279   void *cont_cls;
280
281   /**
282    * Size of original message
283    */
284   size_t size_payload;
285
286   /**
287    * Number of bytes used to transmit message
288    */
289   size_t size_on_wire;
290
291 };
292
293
294 /**
295  * Struct to represent one network card connection
296  */
297 struct MacEndpoint
298 {
299
300   /**
301    * We keep all MACs in a DLL in the plugin.
302    */
303   struct MacEndpoint *next;
304
305   /**
306    * We keep all MACs in a DLL in the plugin.
307    */
308   struct MacEndpoint *prev;
309
310   /**
311    * Pointer to the global plugin struct.
312    */
313   struct Plugin *plugin;
314
315   /**
316    * Head of sessions that use this MAC.
317    */
318   struct Session *sessions_head;
319
320   /**
321    * Tail of sessions that use this MAC.
322    */
323   struct Session *sessions_tail;
324
325   /**
326    * Head of messages we are currently sending to this MAC.
327    */
328   struct FragmentMessage *sending_messages_head;
329
330   /**
331    * Tail of messages we are currently sending to this MAC.
332    */
333   struct FragmentMessage *sending_messages_tail;
334
335   /**
336    * Defrag context for this MAC
337    */
338   struct GNUNET_DEFRAGMENT_Context *defrag;
339
340   /**
341    * When should this endpoint time out?
342    */
343   struct GNUNET_TIME_Absolute timeout;
344
345   /**
346    * Timeout task.
347    */
348   GNUNET_SCHEDULER_TaskIdentifier timeout_task;
349
350   /**
351    * count of messages in the fragment out queue for this mac endpoint
352    */
353   unsigned int fragment_messages_out_count;
354
355   /**
356    * peer mac address
357    */
358   struct WlanAddress addr;
359
360   /**
361    * Message delay for fragmentation context
362    */
363   struct GNUNET_TIME_Relative msg_delay;
364
365   /**
366    * ACK delay for fragmentation context
367    */
368   struct GNUNET_TIME_Relative ack_delay;
369
370   /**
371    * Desired transmission power for this MAC
372    */
373   uint16_t tx_power;
374
375   /**
376    * Desired transmission rate for this MAC
377    */
378   uint8_t rate;
379
380   /**
381    * Antenna we should use for this MAC
382    */
383   uint8_t antenna;
384
385 };
386
387
388 /**
389  * Encapsulation of all of the state of the plugin.
390  */
391 struct Plugin
392 {
393   /**
394    * Our environment.
395    */
396   struct GNUNET_TRANSPORT_PluginEnvironment *env;
397
398   /**
399    * Handle to helper process for priviledged operations.
400    */
401   struct GNUNET_HELPER_Handle *suid_helper;
402
403   /**
404    * ARGV-vector for the helper (all helpers take only the binary
405    * name, one actual argument, plus the NULL terminator for 'argv').
406    */
407   char * helper_argv[3];
408
409   /**
410    * The interface of the wlan card given to us by the user.
411    */
412   char *interface;
413
414   /**
415    * Tokenizer for demultiplexing of data packets resulting from defragmentation.
416    */
417   struct GNUNET_SERVER_MessageStreamTokenizer *fragment_data_tokenizer;
418
419   /**
420    * Tokenizer for demultiplexing of data packets received from the suid helper
421    */
422   struct GNUNET_SERVER_MessageStreamTokenizer *helper_payload_tokenizer;
423
424   /**
425    * Tokenizer for demultiplexing of data packets that follow the WLAN Header
426    */
427   struct GNUNET_SERVER_MessageStreamTokenizer *wlan_header_payload_tokenizer;
428
429   /**
430    * Head of list of open connections.
431    */
432   struct MacEndpoint *mac_head;
433
434   /**
435    * Tail of list of open connections.
436    */
437   struct MacEndpoint *mac_tail;
438
439   /**
440    * Number of connections
441    */
442   unsigned int mac_count;
443
444   /**
445    * Task that periodically sends a HELLO beacon via the helper.
446    */
447   GNUNET_SCHEDULER_TaskIdentifier beacon_task;
448
449   /**
450    * Tracker for bandwidth limit
451    */
452   struct GNUNET_BANDWIDTH_Tracker tracker;
453
454   /**
455    * The mac_address of the wlan card given to us by the helper.
456    */
457   struct GNUNET_TRANSPORT_WLAN_MacAddress mac_address;
458
459   /**
460    * Have we received a control message with our MAC address yet?
461    */
462   int have_mac;
463
464   /**
465    * Options for addresses
466    */
467   uint32_t options;
468
469 };
470
471
472 /**
473  * Information associated with a message.  Can contain
474  * the session or the MAC endpoint associated with the
475  * message (or both).
476  */
477 struct MacAndSession
478 {
479   /**
480    * NULL if the identity of the other peer is not known.
481    */
482   struct Session *session;
483
484   /**
485    * MAC address of the other peer, NULL if not known.
486    */
487   struct MacEndpoint *endpoint;
488 };
489
490 /**
491  * Function called for a quick conversion of the binary address to
492  * a numeric address.  Note that the caller must not free the
493  * address and that the next call to this function is allowed
494  * to override the address again.
495  *
496  * @param cls closure
497  * @param addr binary address
498  * @param addrlen length of the address
499  * @return string representing the same address
500  */
501 static const char *
502 bluetooth_plugin_address_to_string (void *cls, const void *addr, size_t addrlen);
503
504 /**
505  * Print MAC addresses nicely.
506  *
507  * @param mac the mac address
508  * @return string to a static buffer with the human-readable mac, will be overwritten during the next call to this function
509  */
510 static const char *
511 mac_to_string (const struct GNUNET_TRANSPORT_WLAN_MacAddress * mac)
512 {
513   static char macstr[20];
514
515   GNUNET_snprintf (macstr, sizeof (macstr), "%.2X:%.2X:%.2X:%.2X:%.2X:%.2X",
516                                                                  mac->mac[0], mac->mac[1],
517                    mac->mac[2], mac->mac[3], mac->mac[4], mac->mac[5]);
518   return macstr;
519 }
520
521
522 /**
523  * Fill the radiotap header
524  *
525  * @param endpoint pointer to the endpoint, can be NULL
526  * @param header pointer to the radiotap header
527  * @param size total message size
528  */
529 static void
530 get_radiotap_header (struct MacEndpoint *endpoint,
531                      struct GNUNET_TRANSPORT_WLAN_RadiotapSendMessage *header,
532                      uint16_t size)
533 {
534   header->header.type = ntohs (GNUNET_MESSAGE_TYPE_WLAN_DATA_TO_HELPER);
535   header->header.size = ntohs (size);
536   if (NULL != endpoint)
537   {
538     header->rate = endpoint->rate;
539     header->tx_power = endpoint->tx_power;
540     header->antenna = endpoint->antenna;
541   }
542   else
543   {
544     header->rate = 255;
545     header->tx_power = 0;
546     header->antenna = 0;
547   }
548 }
549
550
551 /**
552  * Generate the WLAN hardware header for one packet
553  *
554  * @param plugin the plugin handle
555  * @param header address to write the header to
556  * @param to_mac_addr address of the recipient
557  * @param size size of the whole packet, needed to calculate the time to send the packet
558  */
559 static void
560 get_wlan_header (struct Plugin *plugin,
561                  struct GNUNET_TRANSPORT_WLAN_Ieee80211Frame *header,
562                  const struct GNUNET_TRANSPORT_WLAN_MacAddress *to_mac_addr,
563                  unsigned int size)
564 {
565   const int rate = 11000000;
566
567   header->frame_control = htons (IEEE80211_FC0_TYPE_DATA);
568   header->addr1 = *to_mac_addr;
569   header->addr2 = plugin->mac_address;
570   header->addr3 = mac_bssid_gnunet;
571   header->duration = GNUNET_htole16 ((size * 1000000) / rate + 290);
572   header->sequence_control = 0; // FIXME?
573   header->llc[0] = WLAN_LLC_DSAP_FIELD;
574   header->llc[1] = WLAN_LLC_SSAP_FIELD;
575   header->llc[2] = 0;  // FIXME?
576   header->llc[3] = 0;  // FIXME?
577 }
578
579
580 /**
581  * Send an ACK for a fragment we received.
582  *
583  * @param cls the 'struct MacEndpoint' the ACK must be sent to
584  * @param msg_id id of the message
585  * @param hdr pointer to the hdr where the ack is stored
586  */
587 static void
588 send_ack (void *cls, uint32_t msg_id,
589           const struct GNUNET_MessageHeader *hdr)
590 {
591   struct MacEndpoint *endpoint = cls;
592   struct GNUNET_TRANSPORT_WLAN_RadiotapSendMessage* radio_header;
593   uint16_t msize = ntohs (hdr->size);
594   size_t size = sizeof (struct GNUNET_TRANSPORT_WLAN_RadiotapSendMessage) + msize;
595   char buf[size];
596
597   if (size >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
598   {
599     GNUNET_break (0);
600     return;
601   }
602   LOG (GNUNET_ERROR_TYPE_DEBUG,
603        "Sending ACK to helper\n");
604   radio_header = (struct GNUNET_TRANSPORT_WLAN_RadiotapSendMessage *) buf;
605   get_radiotap_header (endpoint, radio_header, size);
606   get_wlan_header (endpoint->plugin,
607                    &radio_header->frame,
608                    &endpoint->addr.mac,
609                    size);
610   memcpy (&radio_header[1], hdr, msize);
611   if (NULL !=
612       GNUNET_HELPER_send (endpoint->plugin->suid_helper,
613                           &radio_header->header,
614                           GNUNET_NO /* dropping ACKs is bad */,
615                           NULL, NULL))
616     GNUNET_STATISTICS_update (endpoint->plugin->env->stats, _("# Bluetooth ACKs sent"),
617                               1, GNUNET_NO);
618 }
619
620
621 /**
622  * Handles the data after all fragments are put together
623  *
624  * @param cls macendpoint this messages belongs to
625  * @param hdr pointer to the data
626  */
627 static void
628 bluetooth_data_message_handler (void *cls, const struct GNUNET_MessageHeader *hdr)
629 {
630   struct MacEndpoint *endpoint = cls;
631   struct Plugin *plugin = endpoint->plugin;
632   struct MacAndSession mas;
633
634   GNUNET_STATISTICS_update (plugin->env->stats,
635                             _("# Bluetooth messages defragmented"), 1,
636                             GNUNET_NO);
637   mas.session = NULL;
638   mas.endpoint = endpoint;
639   (void) GNUNET_SERVER_mst_receive (plugin->fragment_data_tokenizer,
640                                     &mas,
641                                     (const char *) hdr,
642                                     ntohs (hdr->size),
643                                     GNUNET_YES, GNUNET_NO);
644 }
645
646
647 /**
648  * Free a session
649  *
650  * @param session the session free
651  */
652 static void
653 free_session (struct Session *session)
654 {
655   struct MacEndpoint *endpoint = session->mac;
656   struct PendingMessage *pm;
657
658   endpoint->plugin->env->session_end (endpoint->plugin->env->cls,
659                                       &session->target,
660                                       session);
661   while (NULL != (pm = session->pending_message_head))
662   {
663     GNUNET_CONTAINER_DLL_remove (session->pending_message_head,
664                                  session->pending_message_tail, pm);
665     if (GNUNET_SCHEDULER_NO_TASK != pm->timeout_task)
666     {
667       GNUNET_SCHEDULER_cancel (pm->timeout_task);
668       pm->timeout_task = GNUNET_SCHEDULER_NO_TASK;
669     }
670     GNUNET_free (pm->msg);
671     GNUNET_free (pm);
672   }
673   GNUNET_CONTAINER_DLL_remove (endpoint->sessions_head,
674                                endpoint->sessions_tail,
675                                session);
676   if (session->timeout_task != GNUNET_SCHEDULER_NO_TASK)
677   {
678     GNUNET_SCHEDULER_cancel (session->timeout_task);
679     session->timeout_task = GNUNET_SCHEDULER_NO_TASK;
680   }
681   GNUNET_STATISTICS_update (endpoint->plugin->env->stats, _("# Bluetooth sessions allocated"), -1,
682                             GNUNET_NO);
683   GNUNET_free (session);
684 }
685
686
687 /**
688  * A session is timing out.  Clean up.
689  *
690  * @param cls pointer to the Session
691  * @param tc pointer to the GNUNET_SCHEDULER_TaskContext
692  */
693 static void
694 session_timeout (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
695 {
696   struct Session * session = cls;
697   struct GNUNET_TIME_Relative timeout;
698
699   session->timeout_task = GNUNET_SCHEDULER_NO_TASK;
700   timeout = GNUNET_TIME_absolute_get_remaining (session->timeout);
701   if (0 == timeout.rel_value_us)
702   {
703     free_session (session);
704     return;
705   }
706   session->timeout_task =
707     GNUNET_SCHEDULER_add_delayed (timeout, &session_timeout, session);
708 }
709
710
711 /**
712  * Create a new session
713  *
714  * @param endpoint pointer to the mac endpoint of the peer
715  * @param peer peer identity to use for this session
716  * @return returns the session
717  */
718 static struct Session *
719 create_session (struct MacEndpoint *endpoint,
720                 const struct GNUNET_PeerIdentity *peer)
721 {
722   struct Session *session;
723
724   for (session = endpoint->sessions_head; NULL != session; session = session->next)
725     if (0 == memcmp (peer, &session->target,
726                      sizeof (struct GNUNET_PeerIdentity)))
727     {
728       session->timeout = GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
729       return session;
730     }
731   GNUNET_STATISTICS_update (endpoint->plugin->env->stats, _("# Bluetooth sessions allocated"), 1,
732                             GNUNET_NO);
733   session = GNUNET_new (struct Session);
734   GNUNET_CONTAINER_DLL_insert_tail (endpoint->sessions_head,
735                                     endpoint->sessions_tail,
736                                     session);
737   session->mac = endpoint;
738   session->target = *peer;
739   session->timeout = GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT);
740   session->timeout_task =
741       GNUNET_SCHEDULER_add_delayed (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, &session_timeout, session);
742   LOG (GNUNET_ERROR_TYPE_DEBUG,
743        "Created new session for peer `%s' with endpoint %s\n",
744        GNUNET_i2s (peer),
745        mac_to_string (&endpoint->addr.mac));
746   return session;
747 }
748
749
750 /**
751  * Function called once we have successfully given the fragment
752  * message to the SUID helper process and we are thus ready for
753  * the next fragment.
754  *
755  * @param cls the 'struct FragmentMessage'
756  * @param result result of the operation (GNUNET_OK on success, GNUNET_NO if the helper died, GNUNET_SYSERR
757  *        if the helper was stopped)
758  */
759 static void
760 fragment_transmission_done (void *cls,
761                             int result)
762 {
763   struct FragmentMessage *fm = cls;
764
765
766   fm->sh = NULL;
767   GNUNET_FRAGMENT_context_transmission_done (fm->fragcontext);
768 }
769
770
771 /**
772  * Transmit a fragment of a message.
773  *
774  * @param cls 'struct FragmentMessage' this fragment message belongs to
775  * @param hdr pointer to the start of the fragment message
776  */
777 static void
778 transmit_fragment (void *cls,
779                    const struct GNUNET_MessageHeader *hdr)
780 {
781   struct FragmentMessage *fm = cls;
782   struct MacEndpoint *endpoint = fm->macendpoint;
783   size_t size;
784   uint16_t msize;
785
786   msize = ntohs (hdr->size);
787   size = sizeof (struct GNUNET_TRANSPORT_WLAN_RadiotapSendMessage) + msize;
788   {
789     char buf[size];
790     struct GNUNET_TRANSPORT_WLAN_RadiotapSendMessage *radio_header;
791
792     radio_header = (struct GNUNET_TRANSPORT_WLAN_RadiotapSendMessage *) buf;
793     get_radiotap_header (endpoint, radio_header, size);
794     get_wlan_header (endpoint->plugin,
795                      &radio_header->frame,
796                      &endpoint->addr.mac,
797                      size);
798     memcpy (&radio_header[1], hdr, msize);
799     GNUNET_assert (NULL == fm->sh);
800     fm->sh = GNUNET_HELPER_send (endpoint->plugin->suid_helper,
801                                  &radio_header->header,
802                                  GNUNET_NO,
803                                  &fragment_transmission_done, fm);
804     fm->size_on_wire += size;
805     if (NULL != fm->sh)
806       GNUNET_STATISTICS_update (endpoint->plugin->env->stats, _("# Bluetooth message fragments sent"),
807                                 1, GNUNET_NO);
808     else
809       GNUNET_FRAGMENT_context_transmission_done (fm->fragcontext);
810     GNUNET_STATISTICS_update (endpoint->plugin->env->stats,
811                               "# bytes currently in Bluetooth buffers",
812                               -msize, GNUNET_NO);
813     GNUNET_STATISTICS_update (endpoint->plugin->env->stats,
814                               "# bytes transmitted via Bluetooth",
815                               msize, GNUNET_NO);
816   }
817 }
818
819
820 /**
821  * Frees the space of a message in the fragment queue (send queue)
822  *
823  * @param fm message to free
824  */
825 static void
826 free_fragment_message (struct FragmentMessage *fm)
827 {
828   struct MacEndpoint *endpoint = fm->macendpoint;
829
830   GNUNET_STATISTICS_update (endpoint->plugin->env->stats, _("# Bluetooth messages pending (with fragmentation)"),
831                             -1, GNUNET_NO);
832   GNUNET_CONTAINER_DLL_remove (endpoint->sending_messages_head,
833                                endpoint->sending_messages_tail, fm);
834   if (NULL != fm->sh)
835   {
836     GNUNET_HELPER_send_cancel (fm->sh);
837     fm->sh = NULL;
838   }
839   GNUNET_FRAGMENT_context_destroy (fm->fragcontext,
840                                                                    &endpoint->msg_delay,
841                                                                    &endpoint->ack_delay);
842   if (fm->timeout_task != GNUNET_SCHEDULER_NO_TASK)
843   {
844     GNUNET_SCHEDULER_cancel (fm->timeout_task);
845     fm->timeout_task = GNUNET_SCHEDULER_NO_TASK;
846   }
847   GNUNET_free (fm);
848 }
849
850
851 /**
852  * A FragmentMessage has timed out.  Remove it.
853  *
854  * @param cls pointer to the 'struct FragmentMessage'
855  * @param tc pointer to the GNUNET_SCHEDULER_TaskContext
856  */
857 static void
858 fragmentmessage_timeout (void *cls,
859                          const struct GNUNET_SCHEDULER_TaskContext *tc)
860 {
861   struct FragmentMessage *fm = cls;
862
863   fm->timeout_task = GNUNET_SCHEDULER_NO_TASK;
864   if (NULL != fm->cont)
865   {
866     fm->cont (fm->cont_cls, &fm->target, GNUNET_SYSERR, fm->size_payload, fm->size_on_wire);
867     fm->cont = NULL;
868   }
869   free_fragment_message (fm);
870 }
871
872
873 /**
874  * Transmit a message to the given destination with fragmentation.
875  *
876  * @param endpoint desired destination
877  * @param timeout how long can the message wait?
878  * @param target peer that should receive the message
879  * @param msg message to transmit
880  * @param payload_size bytes of payload
881  * @param cont continuation to call once the message has
882  *        been transmitted (or if the transport is ready
883  *        for the next transmission call; or if the
884  *        peer disconnected...); can be NULL
885  * @param cont_cls closure for cont
886  */
887 static void
888 send_with_fragmentation (struct MacEndpoint *endpoint,
889                          struct GNUNET_TIME_Relative timeout,
890                          const struct GNUNET_PeerIdentity *target,
891                          const struct GNUNET_MessageHeader *msg,
892                          size_t payload_size,
893                          GNUNET_TRANSPORT_TransmitContinuation cont, void *cont_cls)
894
895 {
896   struct FragmentMessage *fm;
897   struct Plugin *plugin;
898
899   plugin = endpoint->plugin;
900   fm = GNUNET_new (struct FragmentMessage);
901   fm->macendpoint = endpoint;
902   fm->target = *target;
903   fm->size_payload = payload_size;
904   fm->size_on_wire = 0;
905   fm->timeout = GNUNET_TIME_relative_to_absolute (timeout);
906   fm->cont = cont;
907   fm->cont_cls = cont_cls;
908   /* 1 MBit/s typical data rate, 1430 byte fragments => ~100 ms per message */
909   fm->fragcontext =
910     GNUNET_FRAGMENT_context_create (plugin->env->stats, WLAN_MTU,
911                                     &plugin->tracker,
912                                     endpoint->msg_delay,
913                                     endpoint->ack_delay,
914                                     msg,
915                                     &transmit_fragment, fm);
916   fm->timeout_task =
917     GNUNET_SCHEDULER_add_delayed (timeout,
918                                   &fragmentmessage_timeout, fm);
919   GNUNET_CONTAINER_DLL_insert_tail (endpoint->sending_messages_head,
920                                     endpoint->sending_messages_tail,
921                                     fm);
922 }
923
924
925 /**
926  * Free a MAC endpoint.
927  *
928  * @param endpoint pointer to the MacEndpoint to free
929  */
930 static void
931 free_macendpoint (struct MacEndpoint *endpoint)
932 {
933   struct Plugin *plugin = endpoint->plugin;
934   struct FragmentMessage *fm;
935   struct Session *session;
936
937   GNUNET_STATISTICS_update (plugin->env->stats,
938                             _("# Bluetooth MAC endpoints allocated"), -1, GNUNET_NO);
939   while (NULL != (session = endpoint->sessions_head))
940     free_session (session);
941   while (NULL != (fm = endpoint->sending_messages_head))
942     free_fragment_message (fm);
943   GNUNET_CONTAINER_DLL_remove (plugin->mac_head,
944                                plugin->mac_tail,
945                                endpoint);
946
947   if (NULL != endpoint->defrag)
948   {
949     GNUNET_DEFRAGMENT_context_destroy(endpoint->defrag);
950     endpoint->defrag = NULL;
951   }
952
953   plugin->mac_count--;
954   if (GNUNET_SCHEDULER_NO_TASK != endpoint->timeout_task)
955   {
956     GNUNET_SCHEDULER_cancel (endpoint->timeout_task);
957     endpoint->timeout_task = GNUNET_SCHEDULER_NO_TASK;
958   }
959   GNUNET_free (endpoint);
960 }
961
962
963 /**
964  * A MAC endpoint is timing out.  Clean up.
965  *
966  * @param cls pointer to the MacEndpoint
967  * @param tc pointer to the GNUNET_SCHEDULER_TaskContext
968  */
969 static void
970 macendpoint_timeout (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
971 {
972   struct MacEndpoint *endpoint = cls;
973   struct GNUNET_TIME_Relative timeout;
974
975   endpoint->timeout_task = GNUNET_SCHEDULER_NO_TASK;
976   timeout = GNUNET_TIME_absolute_get_remaining (endpoint->timeout);
977   if (0 == timeout.rel_value_us)
978   {
979     free_macendpoint (endpoint);
980     return;
981   }
982   endpoint->timeout_task =
983     GNUNET_SCHEDULER_add_delayed (timeout, &macendpoint_timeout,
984                                   endpoint);
985 }
986
987
988 /**
989  * Find (or create) a MacEndpoint with a specific MAC address
990  *
991  * @param plugin pointer to the plugin struct
992  * @param addr the MAC address of the endpoint
993  * @return handle to our data structure for this MAC
994  */
995 static struct MacEndpoint *
996 create_macendpoint (struct Plugin *plugin,
997                     const struct WlanAddress *addr)
998 {
999   struct MacEndpoint *pos;
1000
1001   for (pos = plugin->mac_head; NULL != pos; pos = pos->next)
1002     if (0 == memcmp (addr, &pos->addr, sizeof (struct WlanAddress)))
1003       return pos;
1004   pos = GNUNET_new (struct MacEndpoint);
1005   pos->addr = *addr;
1006   pos->plugin = plugin;
1007   pos->defrag =
1008     GNUNET_DEFRAGMENT_context_create (plugin->env->stats, WLAN_MTU,
1009                                       MESSAGES_IN_DEFRAG_QUEUE_PER_MAC,
1010                                       pos,
1011                                       &bluetooth_data_message_handler,
1012                                       &send_ack);
1013
1014   pos->msg_delay = GNUNET_TIME_UNIT_MILLISECONDS;
1015   pos->ack_delay = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS,
1016                                                                                                   100);
1017   pos->timeout = GNUNET_TIME_relative_to_absolute (MACENDPOINT_TIMEOUT);
1018   pos->timeout_task =
1019       GNUNET_SCHEDULER_add_delayed (MACENDPOINT_TIMEOUT, &macendpoint_timeout,
1020                                     pos);
1021   GNUNET_CONTAINER_DLL_insert (plugin->mac_head, plugin->mac_tail, pos);
1022   plugin->mac_count++;
1023   GNUNET_STATISTICS_update (plugin->env->stats, _("# Bluetooth MAC endpoints allocated"),
1024                             1, GNUNET_NO);
1025   LOG (GNUNET_ERROR_TYPE_DEBUG,
1026        "New MAC endpoint `%s'\n",
1027        bluetooth_plugin_address_to_string(NULL, addr, sizeof (struct WlanAddress)));
1028   return pos;
1029 }
1030
1031
1032 /**
1033  * Function obtain the network type for a session
1034  *
1035  * @param cls closure ('struct Plugin*')
1036  * @param session the session
1037  * @return the network type in HBO or GNUNET_SYSERR
1038  */
1039 static enum GNUNET_ATS_Network_Type
1040 bluetooth_get_network (void *cls,
1041                        struct Session *session)
1042 {
1043   GNUNET_assert (NULL != session);
1044   return GNUNET_ATS_NET_BT;
1045 }
1046
1047
1048 /**
1049  * Creates a new outbound session the transport service will use to send data to the
1050  * peer
1051  *
1052  * @param cls the plugin
1053  * @param address the address
1054  * @return the session or NULL of max connections exceeded
1055  */
1056 static struct Session *
1057 bluetooth_plugin_get_session (void *cls,
1058                          const struct GNUNET_HELLO_Address *address)
1059 {
1060   struct Plugin *plugin = cls;
1061   struct MacEndpoint *endpoint;
1062
1063   if (NULL == address)
1064     return NULL;
1065   if (sizeof (struct WlanAddress) != address->address_length)
1066   {
1067     GNUNET_break (0);
1068     return NULL;
1069   }
1070   LOG (GNUNET_ERROR_TYPE_DEBUG,
1071        "Service asked to create session for peer `%s' with MAC `%s'\n",
1072        GNUNET_i2s (&address->peer),
1073        bluetooth_plugin_address_to_string(NULL, address->address, address->address_length));
1074   endpoint = create_macendpoint (plugin, address->address);
1075   return create_session (endpoint, &address->peer);
1076 }
1077
1078
1079 /**
1080  * Function that can be used to force the plugin to disconnect
1081  * from the given peer and cancel all previous transmissions
1082  * (and their continuation).
1083  *
1084  * @param cls closure
1085  * @param target peer from which to disconnect
1086  */
1087 static void
1088 bluetooth_plugin_disconnect_peer (void *cls, const struct GNUNET_PeerIdentity *target)
1089 {
1090   struct Plugin *plugin = cls;
1091   struct Session *session;
1092   struct MacEndpoint *endpoint;
1093
1094   for (endpoint = plugin->mac_head; NULL != endpoint; endpoint = endpoint->next)
1095     for (session = endpoint->sessions_head; NULL != session; session = session->next)
1096       if (0 == memcmp (target, &session->target,
1097         sizeof (struct GNUNET_PeerIdentity)))
1098       {
1099         free_session (session);
1100         break; /* inner-loop only (in case peer has another MAC as well!) */
1101       }
1102 }
1103
1104
1105 /**
1106  * Function that can be used to force the plugin to disconnect
1107  * from the given peer and cancel all previous transmissions
1108  * (and their continuation).
1109  *
1110  * @param cls closure
1111  * @param session session to disconnect
1112  */
1113 static int
1114 bluetooth_plugin_disconnect_session (void *cls,
1115                                      struct Session *session)
1116 {
1117   free_session (session);
1118   return GNUNET_OK;
1119 }
1120
1121
1122 /**
1123  * Function that is called to get the keepalive factor.
1124  * GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT is divided by this number to
1125  * calculate the interval between keepalive packets.
1126  *
1127  * @param cls closure with the `struct Plugin`
1128  * @return keepalive factor
1129  */
1130 static unsigned int
1131 bluetooth_query_keepalive_factor (void *cls)
1132 {
1133   return 3;
1134 }
1135
1136
1137 /**
1138  * Function that can be used by the transport service to transmit
1139  * a message using the plugin.   Note that in the case of a
1140  * peer disconnecting, the continuation MUST be called
1141  * prior to the disconnect notification itself.  This function
1142  * will be called with this peer's HELLO message to initiate
1143  * a fresh connection to another peer.
1144  *
1145  * @param cls closure
1146  * @param session which session must be used
1147  * @param msgbuf the message to transmit
1148  * @param msgbuf_size number of bytes in 'msgbuf'
1149  * @param priority how important is the message (most plugins will
1150  *                 ignore message priority and just FIFO)
1151  * @param to how long to wait at most for the transmission (does not
1152  *                require plugins to discard the message after the timeout,
1153  *                just advisory for the desired delay; most plugins will ignore
1154  *                this as well)
1155  * @param cont continuation to call once the message has
1156  *        been transmitted (or if the transport is ready
1157  *        for the next transmission call; or if the
1158  *        peer disconnected...); can be NULL
1159  * @param cont_cls closure for cont
1160  * @return number of bytes used (on the physical network, with overheads);
1161  *         -1 on hard errors (i.e. address invalid); 0 is a legal value
1162  *         and does NOT mean that the message was not transmitted (DV)
1163  */
1164 static ssize_t
1165 bluetooth_plugin_send (void *cls,
1166                   struct Session *session,
1167                   const char *msgbuf, size_t msgbuf_size,
1168                   unsigned int priority,
1169                   struct GNUNET_TIME_Relative to,
1170                   GNUNET_TRANSPORT_TransmitContinuation cont, void *cont_cls)
1171 {
1172   struct Plugin *plugin = cls;
1173   struct WlanHeader *wlanheader;
1174   size_t size = msgbuf_size + sizeof (struct WlanHeader);
1175   char buf[size] GNUNET_ALIGN;
1176
1177   LOG (GNUNET_ERROR_TYPE_DEBUG,
1178        "Transmitting %u bytes of payload to peer `%s' (starting with %u byte message of type %u)\n",
1179        msgbuf_size,
1180        GNUNET_i2s (&session->target),
1181        (unsigned int) ntohs (((struct GNUNET_MessageHeader*)msgbuf)->size),
1182        (unsigned int) ntohs (((struct GNUNET_MessageHeader*)msgbuf)->type));
1183   wlanheader = (struct WlanHeader *) buf;
1184   wlanheader->header.size = htons (msgbuf_size + sizeof (struct WlanHeader));
1185   wlanheader->header.type = htons (GNUNET_MESSAGE_TYPE_WLAN_DATA);
1186   wlanheader->sender = *plugin->env->my_identity;
1187   wlanheader->target = session->target;
1188   wlanheader->crc = htonl (GNUNET_CRYPTO_crc32_n (msgbuf, msgbuf_size));
1189   memcpy (&wlanheader[1], msgbuf, msgbuf_size);
1190
1191   GNUNET_STATISTICS_update (plugin->env->stats,
1192                             "# bytes currently in Bluetooth buffers",
1193                             msgbuf_size, GNUNET_NO);
1194
1195   send_with_fragmentation (session->mac,
1196                            to,
1197                            &session->target,
1198                            &wlanheader->header,
1199                            msgbuf_size,
1200                            cont, cont_cls);
1201   return size;
1202 }
1203
1204
1205 /**
1206  * We have received data from the WLAN via some session.  Process depending
1207  * on the message type (HELLO, DATA, FRAGMENTATION or FRAGMENTATION-ACK).
1208  *
1209  * @param cls pointer to the plugin
1210  * @param client pointer to the session this message belongs to
1211  * @param hdr start of the message
1212  */
1213 static int
1214 process_data (void *cls, void *client, const struct GNUNET_MessageHeader *hdr)
1215 {
1216   struct Plugin *plugin = cls;
1217   struct MacAndSession *mas = client;
1218   struct MacAndSession xmas;
1219   struct GNUNET_ATS_Information ats;
1220   struct FragmentMessage *fm;
1221   struct GNUNET_PeerIdentity tmpsource;
1222   const struct WlanHeader *wlanheader;
1223   int ret;
1224   uint16_t msize;
1225
1226   ats.type = htonl (GNUNET_ATS_NETWORK_TYPE);
1227   ats.value = htonl (GNUNET_ATS_NET_BT);
1228   msize = ntohs (hdr->size);
1229
1230   GNUNET_STATISTICS_update (plugin->env->stats,
1231                             "# bytes received via Bluetooth",
1232                             msize, GNUNET_NO);
1233
1234   switch (ntohs (hdr->type))
1235   {
1236   case GNUNET_MESSAGE_TYPE_HELLO:
1237     if (GNUNET_OK !=
1238         GNUNET_HELLO_get_id ((const struct GNUNET_HELLO_Message *) hdr, &tmpsource))
1239     {
1240       GNUNET_break_op (0);
1241       break;
1242     }
1243     LOG (GNUNET_ERROR_TYPE_DEBUG,
1244          "Processing %u bytes of HELLO from peer `%s' at MAC %s\n",
1245          (unsigned int) msize,
1246          GNUNET_i2s (&tmpsource),
1247          bluetooth_plugin_address_to_string (NULL, &mas->endpoint->addr, sizeof (struct WlanAddress)));
1248
1249     GNUNET_STATISTICS_update (plugin->env->stats,
1250                               _("# HELLO messages received via Bluetooth"), 1,
1251                               GNUNET_NO);
1252     plugin->env->receive (plugin->env->cls,
1253                           &tmpsource,
1254                           hdr,
1255                           mas->session,
1256                           (mas->endpoint == NULL) ? NULL : (const char *) &mas->endpoint->addr,
1257                           (mas->endpoint == NULL) ? 0 : sizeof (struct GNUNET_TRANSPORT_WLAN_MacAddress));
1258     plugin->env->update_address_metrics (plugin->env->cls,
1259                                          &tmpsource,
1260                                          (mas->endpoint == NULL) ? NULL : (const char *) &mas->endpoint->addr,
1261                                          (mas->endpoint == NULL) ? 0 : sizeof (struct GNUNET_TRANSPORT_WLAN_MacAddress),
1262                                          mas->session,
1263                                          &ats, 1);
1264     break;
1265   case GNUNET_MESSAGE_TYPE_FRAGMENT:
1266     if (NULL == mas->endpoint)
1267     {
1268       GNUNET_break (0);
1269       break;
1270     }
1271     LOG (GNUNET_ERROR_TYPE_DEBUG,
1272          "Processing %u bytes of FRAGMENT from MAC %s\n",
1273          (unsigned int) msize,
1274          bluetooth_plugin_address_to_string (NULL, &mas->endpoint->addr, sizeof (struct WlanAddress)));
1275     GNUNET_STATISTICS_update (plugin->env->stats,
1276                               _("# fragments received via Bluetooth"), 1, GNUNET_NO);
1277     (void) GNUNET_DEFRAGMENT_process_fragment (mas->endpoint->defrag,
1278                                               hdr);
1279     break;
1280   case GNUNET_MESSAGE_TYPE_FRAGMENT_ACK:
1281     if (NULL == mas->endpoint)
1282     {
1283       GNUNET_break (0);
1284       break;
1285     }
1286     GNUNET_STATISTICS_update (plugin->env->stats, _("# ACKs received via Bluetooth"),
1287                               1, GNUNET_NO);
1288     for (fm = mas->endpoint->sending_messages_head; NULL != fm; fm = fm->next)
1289     {
1290       ret = GNUNET_FRAGMENT_process_ack (fm->fragcontext, hdr);
1291       if (GNUNET_OK == ret)
1292       {
1293         LOG (GNUNET_ERROR_TYPE_DEBUG,
1294              "Got last ACK, finished message transmission to `%s' (%p)\n",
1295                  bluetooth_plugin_address_to_string (NULL, &mas->endpoint->addr, sizeof (struct WlanAddress)),
1296              fm);
1297         mas->endpoint->timeout = GNUNET_TIME_relative_to_absolute (MACENDPOINT_TIMEOUT);
1298         if (NULL != fm->cont)
1299         {
1300           fm->cont (fm->cont_cls, &fm->target, GNUNET_OK, fm->size_payload, fm->size_on_wire);
1301           fm->cont = NULL;
1302         }
1303         free_fragment_message (fm);
1304         break;
1305       }
1306       if (GNUNET_NO == ret)
1307       {
1308         LOG (GNUNET_ERROR_TYPE_DEBUG,
1309              "Got an ACK, message transmission to `%s' not yet finished\n",
1310                   bluetooth_plugin_address_to_string (NULL, &mas->endpoint->addr, sizeof (struct WlanAddress)));
1311         break;
1312       }
1313     }
1314     LOG (GNUNET_ERROR_TYPE_DEBUG,
1315          "ACK not matched against any active fragmentation with MAC `%s'\n",
1316          bluetooth_plugin_address_to_string (NULL, &mas->endpoint->addr, sizeof (struct WlanAddress)));
1317     break;
1318   case GNUNET_MESSAGE_TYPE_WLAN_DATA:
1319     if (NULL == mas->endpoint)
1320     {
1321       GNUNET_break (0);
1322       break;
1323     }
1324     if (msize < sizeof (struct WlanHeader))
1325     {
1326       GNUNET_break (0);
1327       break;
1328     }
1329     wlanheader = (const struct WlanHeader *) hdr;
1330     if (0 != memcmp (&wlanheader->target,
1331                      plugin->env->my_identity,
1332                      sizeof (struct GNUNET_PeerIdentity)))
1333     {
1334       LOG (GNUNET_ERROR_TYPE_DEBUG,
1335            "Bluetooth data for `%s', not for me, ignoring\n",
1336            GNUNET_i2s (&wlanheader->target));
1337       break;
1338     }
1339     if (ntohl (wlanheader->crc) !=
1340         GNUNET_CRYPTO_crc32_n (&wlanheader[1], msize - sizeof (struct WlanHeader)))
1341     {
1342       GNUNET_STATISTICS_update (plugin->env->stats,
1343                                 _("# Bluetooth DATA messages discarded due to CRC32 error"), 1,
1344                                 GNUNET_NO);
1345       break;
1346     }
1347     xmas.endpoint = mas->endpoint;
1348     xmas.session = create_session (mas->endpoint, &wlanheader->sender);
1349     LOG (GNUNET_ERROR_TYPE_DEBUG,
1350          "Processing %u bytes of BLUETOOTH DATA from peer `%s'\n",
1351          (unsigned int) msize,
1352          GNUNET_i2s (&wlanheader->sender));
1353     (void) GNUNET_SERVER_mst_receive (plugin->wlan_header_payload_tokenizer,
1354                                       &xmas,
1355                                       (const char *) &wlanheader[1],
1356                                       msize - sizeof (struct WlanHeader),
1357                                       GNUNET_YES, GNUNET_NO);
1358     break;
1359   default:
1360     if (NULL == mas->endpoint)
1361     {
1362       GNUNET_break (0);
1363       break;
1364     }
1365     if (NULL == mas->session)
1366     {
1367       GNUNET_break (0);
1368       break;
1369     }
1370     LOG (GNUNET_ERROR_TYPE_DEBUG,
1371          "Received packet with %u bytes of type %u from peer %s\n",
1372          (unsigned int) msize,
1373          (unsigned int) ntohs (hdr->type),
1374          GNUNET_i2s (&mas->session->target));
1375     plugin->env->receive (plugin->env->cls,
1376                           &mas->session->target,
1377                           hdr,
1378                           mas->session,
1379                           (mas->endpoint == NULL) ? NULL : (const char *) &mas->endpoint->addr,
1380                           (mas->endpoint == NULL) ? 0 : sizeof (struct WlanAddress));
1381     plugin->env->update_address_metrics (plugin->env->cls,
1382                                          &mas->session->target,
1383                                          (mas->endpoint == NULL) ? NULL : (const char *) &mas->endpoint->addr,
1384                                          (mas->endpoint == NULL) ? 0 : sizeof (struct WlanAddress),
1385                                          mas->session,
1386                                          &ats, 1);
1387     break;
1388   }
1389   return GNUNET_OK;
1390 }
1391
1392
1393 /**
1394  * Function used for to process the data from the suid process
1395  *
1396  * @param cls the plugin handle
1397  * @param client client that send the data (not used)
1398  * @param hdr header of the GNUNET_MessageHeader
1399  */
1400 static int
1401 handle_helper_message (void *cls, void *client,
1402                        const struct GNUNET_MessageHeader *hdr)
1403 {
1404   struct Plugin *plugin = cls;
1405   const struct GNUNET_TRANSPORT_WLAN_RadiotapReceiveMessage *rxinfo;
1406   const struct GNUNET_TRANSPORT_WLAN_HelperControlMessage *cm;
1407   struct WlanAddress wa;
1408   struct MacAndSession mas;
1409   uint16_t msize;
1410
1411   msize = ntohs (hdr->size);
1412   switch (ntohs (hdr->type))
1413   {
1414   case GNUNET_MESSAGE_TYPE_WLAN_HELPER_CONTROL:
1415     if (msize != sizeof (struct GNUNET_TRANSPORT_WLAN_HelperControlMessage))
1416     {
1417       GNUNET_break (0);
1418       break;
1419     }
1420     cm = (const struct GNUNET_TRANSPORT_WLAN_HelperControlMessage *) hdr;
1421     if (GNUNET_YES == plugin->have_mac)
1422     {
1423       if (0 == memcmp (&plugin->mac_address,
1424                        &cm->mac,
1425                        sizeof (struct GNUNET_TRANSPORT_WLAN_MacAddress)))
1426         break; /* no change */
1427       /* remove old address */
1428       memset (&wa, 0, sizeof (struct WlanAddress));
1429       wa.mac = plugin->mac_address;
1430       wa.options = htonl(plugin->options);
1431       plugin->env->notify_address (plugin->env->cls, GNUNET_NO,
1432                                    &wa,
1433                                    sizeof (wa),
1434                                    "bluetooth");
1435     }
1436     plugin->mac_address = cm->mac;
1437     plugin->have_mac = GNUNET_YES;
1438     memset (&wa, 0, sizeof (struct WlanAddress));
1439     wa.mac = plugin->mac_address;
1440     wa.options = htonl(plugin->options);
1441     LOG (GNUNET_ERROR_TYPE_DEBUG,
1442          "Received BT_HELPER_CONTROL message with MAC address `%s' for peer `%s'\n",
1443          mac_to_string (&cm->mac),
1444          GNUNET_i2s (plugin->env->my_identity));
1445     plugin->env->notify_address (plugin->env->cls, GNUNET_YES,
1446                                  &wa,
1447                                  sizeof (struct WlanAddress),
1448                                  "bluetooth");
1449     break;
1450   case GNUNET_MESSAGE_TYPE_WLAN_DATA_FROM_HELPER:
1451     LOG (GNUNET_ERROR_TYPE_DEBUG,
1452          "Got data message from helper with %u bytes\n",
1453          msize);
1454     GNUNET_STATISTICS_update (plugin->env->stats,
1455                               _("# DATA messages received via Bluetooth"), 1,
1456                               GNUNET_NO);
1457     if (msize < sizeof (struct GNUNET_TRANSPORT_WLAN_RadiotapReceiveMessage))
1458     {
1459       GNUNET_break (0);
1460       LOG (GNUNET_ERROR_TYPE_DEBUG,
1461            "Size of packet is too small (%u bytes)\n",
1462            msize);
1463       break;
1464     }
1465     rxinfo = (const struct GNUNET_TRANSPORT_WLAN_RadiotapReceiveMessage *) hdr;
1466
1467     /* check if message is actually for us */
1468     if (0 != memcmp (&rxinfo->frame.addr3, &mac_bssid_gnunet,
1469                      sizeof (struct GNUNET_TRANSPORT_WLAN_MacAddress)))
1470     {
1471       /* Not the GNUnet BSSID */
1472       break;
1473     }
1474     if ( (0 != memcmp (&rxinfo->frame.addr1, &bc_all_mac,
1475                        sizeof (struct GNUNET_TRANSPORT_WLAN_MacAddress))) &&
1476          (0 != memcmp (&rxinfo->frame.addr1, &plugin->mac_address,
1477                        sizeof (struct GNUNET_TRANSPORT_WLAN_MacAddress))) )
1478     {
1479       /* Neither broadcast nor specifically for us */
1480       break;
1481     }
1482     if (0 == memcmp (&rxinfo->frame.addr2, &plugin->mac_address,
1483                      sizeof (struct GNUNET_TRANSPORT_WLAN_MacAddress)))
1484     {
1485       /* packet is FROM us, thus not FOR us */
1486       break;
1487     }
1488
1489     GNUNET_STATISTICS_update (plugin->env->stats,
1490                               _("# Bluetooth DATA messages processed"),
1491                               1, GNUNET_NO);
1492     LOG (GNUNET_ERROR_TYPE_DEBUG,
1493          "Receiving %u bytes of data from MAC `%s'\n",
1494          (unsigned int) (msize - sizeof (struct GNUNET_TRANSPORT_WLAN_RadiotapReceiveMessage)),
1495          mac_to_string (&rxinfo->frame.addr2));
1496     wa.mac = rxinfo->frame.addr2;
1497     wa.options = htonl (0);
1498     mas.endpoint = create_macendpoint (plugin, &wa);
1499     mas.session = NULL;
1500     (void) GNUNET_SERVER_mst_receive (plugin->helper_payload_tokenizer,
1501                                       &mas,
1502                                       (const char*) &rxinfo[1],
1503                                       msize - sizeof (struct GNUNET_TRANSPORT_WLAN_RadiotapReceiveMessage),
1504                                       GNUNET_YES, GNUNET_NO);
1505     break;
1506   default:
1507     GNUNET_break (0);
1508     LOG (GNUNET_ERROR_TYPE_DEBUG,
1509          "Unexpected message of type %u (%u bytes)",
1510          ntohs (hdr->type), ntohs (hdr->size));
1511     break;
1512   }
1513   return GNUNET_OK;
1514 }
1515
1516
1517
1518 /**
1519  * Task to (periodically) send a HELLO beacon
1520  *
1521  * @param cls pointer to the plugin struct
1522  * @param tc scheduler context
1523  */
1524 static void
1525 send_hello_beacon (void *cls,
1526                    const struct GNUNET_SCHEDULER_TaskContext *tc)
1527 {
1528   struct Plugin *plugin = cls;
1529   uint16_t size;
1530   uint16_t hello_size;
1531   struct GNUNET_TRANSPORT_WLAN_RadiotapSendMessage *radioHeader;
1532   const struct GNUNET_MessageHeader *hello;
1533
1534   hello = plugin->env->get_our_hello ();
1535   hello_size = GNUNET_HELLO_size ((struct GNUNET_HELLO_Message *) hello);
1536   GNUNET_assert (sizeof (struct WlanHeader) + hello_size <= WLAN_MTU);
1537   size = sizeof (struct GNUNET_TRANSPORT_WLAN_RadiotapSendMessage) + hello_size;
1538   {
1539     char buf[size] GNUNET_ALIGN;
1540
1541     LOG (GNUNET_ERROR_TYPE_DEBUG,
1542          "Sending %u byte HELLO beacon\n",
1543          (unsigned int) size);
1544     radioHeader = (struct GNUNET_TRANSPORT_WLAN_RadiotapSendMessage*) buf;
1545     get_radiotap_header (NULL, radioHeader, size);
1546     get_wlan_header (plugin, &radioHeader->frame, &bc_all_mac, size);
1547     memcpy (&radioHeader[1], hello, hello_size);
1548     if (NULL !=
1549         GNUNET_HELPER_send (plugin->suid_helper,
1550                             &radioHeader->header,
1551                             GNUNET_YES /* can drop */,
1552                             NULL, NULL))
1553       GNUNET_STATISTICS_update (plugin->env->stats, _("# HELLO beacons sent via Bluetooth"),
1554                                 1, GNUNET_NO);
1555   }
1556   plugin->beacon_task =
1557     GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply
1558                                   (HELLO_BEACON_SCALING_FACTOR,
1559                                    plugin->mac_count + 1),
1560                                   &send_hello_beacon,
1561                                   plugin);
1562
1563 }
1564
1565
1566 /**
1567  * Another peer has suggested an address for this
1568  * peer and transport plugin.  Check that this could be a valid
1569  * address.  If so, consider adding it to the list
1570  * of addresses.
1571  *
1572  * @param cls closure
1573  * @param addr pointer to the address
1574  * @param addrlen length of addr
1575  * @return GNUNET_OK if this is a plausible address for this peer
1576  *         and transport
1577  */
1578 static int
1579 bluetooth_plugin_address_suggested (void *cls, const void *addr, size_t addrlen)
1580 {
1581   struct Plugin *plugin = cls;
1582   struct WlanAddress *wa = (struct WlanAddress *) addr;
1583
1584   if (addrlen != sizeof (struct WlanAddress))
1585   {
1586     GNUNET_break_op (0);
1587     return GNUNET_SYSERR;
1588   }
1589   if (GNUNET_YES != plugin->have_mac)
1590   {
1591     LOG (GNUNET_ERROR_TYPE_DEBUG,
1592          "Rejecting MAC `%s': I don't know my MAC!\n",
1593          mac_to_string (addr));
1594     return GNUNET_NO; /* don't know my MAC */
1595   }
1596   if (0 != memcmp (&wa->mac,
1597                    &plugin->mac_address,
1598                    sizeof (wa->mac)))
1599   {
1600     LOG (GNUNET_ERROR_TYPE_DEBUG,
1601          "Rejecting MAC `%s': not my MAC!\n",
1602          mac_to_string (addr));
1603     return GNUNET_NO; /* not my MAC */
1604   }
1605   return GNUNET_OK;
1606 }
1607
1608
1609 /**
1610  * Function called for a quick conversion of the binary address to
1611  * a numeric address.  Note that the caller must not free the
1612  * address and that the next call to this function is allowed
1613  * to override the address again.
1614  *
1615  * @param cls closure
1616  * @param addr binary address
1617  * @param addrlen length of the address
1618  * @return string representing the same address
1619  */
1620 static const char *
1621 bluetooth_plugin_address_to_string (void *cls, const void *addr, size_t addrlen)
1622 {
1623   const struct GNUNET_TRANSPORT_WLAN_MacAddress *mac;
1624   static char macstr[36];
1625
1626   if (sizeof (struct WlanAddress) != addrlen)
1627   {
1628     GNUNET_break (0);
1629     return NULL;
1630   }
1631   mac = &((struct WlanAddress *) addr)->mac;
1632   GNUNET_snprintf (macstr, sizeof (macstr), "%s.%u.%s",
1633                 PLUGIN_NAME, ntohl (((struct WlanAddress *) addr)->options),
1634                 mac_to_string (mac));
1635   return macstr;
1636 }
1637
1638
1639 /**
1640  * Convert the transports address to a nice, human-readable format.
1641  *
1642  * @param cls closure
1643  * @param type name of the transport that generated the address
1644  * @param addr one of the addresses of the host, NULL for the last address
1645  *        the specific address format depends on the transport
1646  * @param addrlen length of the address
1647  * @param numeric should (IP) addresses be displayed in numeric form?
1648  * @param timeout after how long should we give up?
1649  * @param asc function to call on each string
1650  * @param asc_cls closure for asc
1651  */
1652 static void
1653 bluetooth_plugin_address_pretty_printer (void *cls, const char *type,
1654                                     const void *addr, size_t addrlen,
1655                                     int numeric,
1656                                     struct GNUNET_TIME_Relative timeout,
1657                                     GNUNET_TRANSPORT_AddressStringCallback asc,
1658                                     void *asc_cls)
1659 {
1660   char *ret;
1661
1662   if (sizeof (struct WlanAddress) != addrlen)
1663   {
1664     /* invalid address  */
1665     LOG (GNUNET_ERROR_TYPE_WARNING,
1666          _("Bluetooth address with invalid size encountered\n"));
1667     asc (asc_cls, NULL);
1668     return;
1669   }
1670   ret = GNUNET_strdup (bluetooth_plugin_address_to_string(NULL, addr, addrlen));
1671   asc (asc_cls, ret);
1672   GNUNET_free (ret);
1673   asc (asc_cls, NULL);
1674 }
1675
1676
1677 /**
1678  * Exit point from the plugin.
1679  *
1680  * @param cls pointer to the api struct
1681  */
1682 void *
1683 libgnunet_plugin_transport_bluetooth_done (void *cls)
1684 {
1685         struct WlanAddress wa;
1686   struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
1687   struct Plugin *plugin = api->cls;
1688   struct MacEndpoint *endpoint;
1689   struct MacEndpoint *endpoint_next;
1690
1691   if (NULL == plugin)
1692   {
1693     GNUNET_free (api);
1694     return NULL;
1695   }
1696
1697   if (GNUNET_YES == plugin->have_mac)
1698   {
1699                 memset (&wa, 0, sizeof (wa));
1700                 wa.options = htonl (plugin->options);
1701                 wa.mac = plugin->mac_address;
1702       plugin->env->notify_address (plugin->env->cls, GNUNET_NO,
1703                                &wa,
1704                                sizeof (struct WlanAddress),
1705                                "bluetooth");
1706       plugin->have_mac = GNUNET_NO;
1707   }
1708
1709   if (GNUNET_SCHEDULER_NO_TASK != plugin->beacon_task)
1710   {
1711     GNUNET_SCHEDULER_cancel (plugin->beacon_task);
1712     plugin->beacon_task = GNUNET_SCHEDULER_NO_TASK;
1713   }
1714   if (NULL != plugin->suid_helper)
1715   {
1716     GNUNET_HELPER_stop (plugin->suid_helper, GNUNET_NO);
1717     plugin->suid_helper = NULL;
1718   }
1719   endpoint_next = plugin->mac_head;
1720   while (NULL != (endpoint = endpoint_next))
1721   {
1722     endpoint_next = endpoint->next;
1723     free_macendpoint (endpoint);
1724   }
1725   if (NULL != plugin->fragment_data_tokenizer)
1726   {
1727     GNUNET_SERVER_mst_destroy (plugin->fragment_data_tokenizer);
1728     plugin->fragment_data_tokenizer = NULL;
1729   }
1730   if (NULL != plugin->wlan_header_payload_tokenizer)
1731   {
1732     GNUNET_SERVER_mst_destroy (plugin->wlan_header_payload_tokenizer);
1733     plugin->wlan_header_payload_tokenizer = NULL;
1734   }
1735   if (NULL != plugin->helper_payload_tokenizer)
1736   {
1737     GNUNET_SERVER_mst_destroy (plugin->helper_payload_tokenizer);
1738     plugin->helper_payload_tokenizer = NULL;
1739   }
1740   GNUNET_free_non_null (plugin->interface);
1741   GNUNET_free (plugin);
1742   GNUNET_free (api);
1743   return NULL;
1744 }
1745
1746
1747 /**
1748  * Function called to convert a string address to
1749  * a binary address.
1750  *
1751  * @param cls closure ('struct Plugin*')
1752  * @param addr string address
1753  * @param addrlen length of the address
1754  * @param buf location to store the buffer
1755  * @param added location to store the number of bytes in the buffer.
1756  *        If the function returns GNUNET_SYSERR, its contents are undefined.
1757  * @return GNUNET_OK on success, GNUNET_SYSERR on failure
1758  */
1759 static int
1760 bluetooth_string_to_address (void *cls, const char *addr, uint16_t addrlen,
1761                         void **buf, size_t *added)
1762 {
1763   struct WlanAddress *wa;
1764   unsigned int a[6];
1765   unsigned int i;
1766   char plugin[10];
1767   uint32_t options;
1768
1769   if ((NULL == addr) || (addrlen == 0))
1770   {
1771     GNUNET_break (0);
1772     return GNUNET_SYSERR;
1773   }
1774   if ('\0' != addr[addrlen - 1])
1775   {
1776     GNUNET_break (0);
1777     return GNUNET_SYSERR;
1778   }
1779   if (strlen (addr) != addrlen - 1)
1780   {
1781     GNUNET_break (0);
1782     return GNUNET_SYSERR;
1783   }
1784
1785   if (8 != SSCANF (addr,
1786                    "%9s.%u.%X:%X:%X:%X:%X:%X",
1787                    plugin, &options,
1788                    &a[0], &a[1], &a[2], &a[3], &a[4], &a[5]))
1789   {
1790     GNUNET_break (0);
1791     return GNUNET_SYSERR;
1792   }
1793   wa = GNUNET_new (struct WlanAddress);
1794   for (i=0;i<6;i++)
1795     wa->mac.mac[i] = a[i];
1796   wa->options = htonl (0);
1797   *buf = wa;
1798   *added = sizeof (struct WlanAddress);
1799   return GNUNET_OK;
1800 }
1801
1802 static void
1803 bluetooth_plugin_update_session_timeout (void *cls,
1804                                   const struct GNUNET_PeerIdentity *peer,
1805                                   struct Session *session)
1806 {
1807   if (GNUNET_SCHEDULER_NO_TASK != session->timeout_task)
1808     GNUNET_SCHEDULER_cancel (session->timeout_task);
1809   session->timeout_task = GNUNET_SCHEDULER_add_delayed (
1810       GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT, &session_timeout, session);
1811 }
1812
1813
1814
1815 /**
1816  * Entry point for the plugin.
1817  *
1818  * @param cls closure, the 'struct GNUNET_TRANSPORT_PluginEnvironment*'
1819  * @return the 'struct GNUNET_TRANSPORT_PluginFunctions*' or NULL on error
1820  */
1821 void *
1822 libgnunet_plugin_transport_bluetooth_init (void *cls)
1823 {
1824   struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
1825   struct GNUNET_TRANSPORT_PluginFunctions *api;
1826   struct Plugin *plugin;
1827   char *interface;
1828   unsigned long long testmode;
1829   char *binary;
1830
1831   /* check for 'special' mode */
1832   if (NULL == env->receive)
1833   {
1834     /* run in 'stub' mode (i.e. as part of gnunet-peerinfo), don't fully
1835        initialze the plugin or the API */
1836     api = GNUNET_new (struct GNUNET_TRANSPORT_PluginFunctions);
1837     api->cls = NULL;
1838     api->address_pretty_printer = &bluetooth_plugin_address_pretty_printer;
1839     api->address_to_string = &bluetooth_plugin_address_to_string;
1840     api->string_to_address = &bluetooth_string_to_address;
1841     return api;
1842   }
1843
1844   testmode = 0;
1845   /* check configuration */
1846   if ( (GNUNET_YES ==
1847         GNUNET_CONFIGURATION_have_value (env->cfg, "transport-bluetooth", "TESTMODE")) &&
1848        ( (GNUNET_SYSERR ==
1849           GNUNET_CONFIGURATION_get_value_number (env->cfg, "transport-bluetooth",
1850                                                  "TESTMODE", &testmode)) ||
1851          (testmode > 2) ) )
1852   {
1853     GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
1854                                "transport-bluetooth", "TESTMODE");
1855     return NULL;
1856   }
1857   binary = GNUNET_OS_get_libexec_binary_path ("gnunet-helper-transport-bluetooth");
1858   if ( (0 == testmode) &&
1859        (GNUNET_YES != GNUNET_OS_check_helper_binary (binary, GNUNET_YES, NULL)) )
1860   {
1861     LOG (GNUNET_ERROR_TYPE_ERROR,
1862          _("Helper binary `%s' not SUID, cannot run bluetooth transport\n"),
1863          "gnunet-helper-transport-bluetooth");
1864     GNUNET_free (binary);
1865     return NULL;
1866   }
1867     GNUNET_free (binary);
1868   if (GNUNET_YES !=
1869       GNUNET_CONFIGURATION_get_value_string
1870       (env->cfg, "transport-bluetooth", "INTERFACE",
1871        &interface))
1872   {
1873     GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
1874                                "transport-bluetooth", "INTERFACE");
1875     return NULL;
1876   }
1877
1878   plugin = GNUNET_new (struct Plugin);
1879   plugin->interface = interface;
1880   plugin->env = env;
1881   GNUNET_STATISTICS_set (plugin->env->stats, _("# Bluetooth sessions allocated"),
1882                          0, GNUNET_NO);
1883   GNUNET_STATISTICS_set (plugin->env->stats, _("# Bluetooth MAC endpoints allocated"),
1884                          0, 0);
1885   GNUNET_BANDWIDTH_tracker_init (&plugin->tracker,
1886                                  GNUNET_BANDWIDTH_value_init (100 * 1024 *
1887                                                               1024 / 8), 100);
1888   plugin->fragment_data_tokenizer = GNUNET_SERVER_mst_create (&process_data, plugin);
1889   plugin->wlan_header_payload_tokenizer = GNUNET_SERVER_mst_create (&process_data, plugin);
1890   plugin->helper_payload_tokenizer = GNUNET_SERVER_mst_create (&process_data, plugin);
1891   plugin->beacon_task = GNUNET_SCHEDULER_add_now (&send_hello_beacon,
1892                                                   plugin);
1893
1894   plugin->options = 0;
1895
1896   /* some compilers do not like switch on 'long long'... */
1897   switch ((unsigned int) testmode)
1898   {
1899   case 0: /* normal */
1900     plugin->helper_argv[0] = (char *) "gnunet-helper-transport-bluetooth";
1901     plugin->helper_argv[1] = interface;
1902     plugin->helper_argv[2] = NULL;
1903     plugin->suid_helper = GNUNET_HELPER_start (GNUNET_NO,
1904                                                "gnunet-helper-transport-bluetooth",
1905                                                plugin->helper_argv,
1906                                                &handle_helper_message,
1907                                                NULL,
1908                                                plugin);
1909     break;
1910   case 1: /* testmode, peer 1 */
1911     plugin->helper_argv[0] = (char *) "gnunet-helper-transport-wlan-dummy";
1912     plugin->helper_argv[1] = (char *) "1";
1913     plugin->helper_argv[2] = NULL;
1914     plugin->suid_helper = GNUNET_HELPER_start (GNUNET_NO,
1915                  "gnunet-helper-transport-wlan-dummy",
1916                  plugin->helper_argv,
1917                  &handle_helper_message,
1918                  NULL,
1919                  plugin);
1920     break;
1921   case 2: /* testmode, peer 2 */
1922     plugin->helper_argv[0] = (char *) "gnunet-helper-transport-wlan-dummy";
1923     plugin->helper_argv[1] = (char *) "2";
1924     plugin->helper_argv[2] = NULL;
1925     plugin->suid_helper = GNUNET_HELPER_start (GNUNET_NO,
1926                  "gnunet-helper-transport-wlan-dummy",
1927                  plugin->helper_argv,
1928                  &handle_helper_message,
1929                  NULL,
1930                  plugin);
1931     break;
1932   default:
1933     GNUNET_assert (0);
1934   }
1935
1936   api = GNUNET_new (struct GNUNET_TRANSPORT_PluginFunctions);
1937   api->cls = plugin;
1938   api->send = &bluetooth_plugin_send;
1939   api->get_session = &bluetooth_plugin_get_session;
1940   api->disconnect_peer = &bluetooth_plugin_disconnect_peer;
1941   api->disconnect_session = &bluetooth_plugin_disconnect_session;
1942   api->query_keepalive_factor = &bluetooth_query_keepalive_factor;
1943   api->address_pretty_printer = &bluetooth_plugin_address_pretty_printer;
1944   api->check_address = &bluetooth_plugin_address_suggested;
1945   api->address_to_string = &bluetooth_plugin_address_to_string;;
1946   api->string_to_address = &bluetooth_string_to_address;
1947   api->get_network = &bluetooth_get_network;
1948   api->update_session_timeout = &bluetooth_plugin_update_session_timeout;
1949
1950   return api;
1951 }
1952
1953
1954 /* end of plugin_transport_bluetooth.c */