changed return type to enum
[oweals/gnunet.git] / src / transport / plugin_transport_unix.c
1 /*
2      This file is part of GNUnet
3      (C) 2010, 2013 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_unix.c
23  * @brief Transport plugin using unix domain sockets (!)
24  *        Clearly, can only be used locally on Unix/Linux hosts...
25  *        ONLY INTENDED FOR TESTING!!!
26  * @author Christian Grothoff
27  * @author Nathan Evans
28  */
29 #include "platform.h"
30 #include "gnunet_hello_lib.h"
31 #include "gnunet_util_lib.h"
32 #include "gnunet_protocols.h"
33 #include "gnunet_statistics_service.h"
34 #include "gnunet_transport_service.h"
35 #include "gnunet_transport_plugin.h"
36 #include "transport.h"
37
38
39 /**
40  * Return code we give on 'send' if we failed to send right now
41  * but it makes sense to retry later. (Note: we might want to
42  * move this to the plugin API!?).
43  */
44 #define RETRY 0
45
46 #define PLUGIN_NAME "unix"
47
48 /**
49  * How long until we give up on transmitting the welcome message?
50  */
51 #define HOSTNAME_RESOLVE_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 5)
52
53 /**
54  * Default "port" to use, if configuration does not specify.
55  * Essentially just a number appended to the UNIX path.
56  */
57 #define UNIX_NAT_DEFAULT_PORT 22086
58
59
60 #define LOG(kind,...) GNUNET_log_from (kind, "transport-unix",__VA_ARGS__)
61
62
63 GNUNET_NETWORK_STRUCT_BEGIN
64
65 struct UnixAddress
66 {
67         uint32_t options GNUNET_PACKED;
68
69         uint32_t addrlen GNUNET_PACKED;
70 };
71
72
73 /**
74  * UNIX Message-Packet header.
75  */
76 struct UNIXMessage
77 {
78   /**
79    * Message header.
80    */
81   struct GNUNET_MessageHeader header;
82
83   /**
84    * What is the identity of the sender (GNUNET_hash of public key)
85    */
86   struct GNUNET_PeerIdentity sender;
87
88 };
89
90 GNUNET_NETWORK_STRUCT_END
91
92 /**
93  * Address options
94  */
95 static uint32_t myoptions;
96
97 /**
98  * Handle for a session.
99  */
100 struct Session
101 {
102   struct GNUNET_PeerIdentity target;
103
104   struct Plugin * plugin;
105
106   struct UnixAddress *addr;
107
108   size_t addrlen;
109
110   /**
111    * Session timeout task
112    */
113   GNUNET_SCHEDULER_TaskIdentifier timeout_task;
114 };
115
116
117 struct UNIXMessageWrapper
118 {
119   /**
120    * We keep messages in a doubly linked list.
121    */
122   struct UNIXMessageWrapper *next;
123
124   /**
125    * We keep messages in a doubly linked list.
126    */
127   struct UNIXMessageWrapper *prev;
128
129   /**
130    * The actual payload (allocated separately right now).
131    */
132   struct UNIXMessage * msg;
133
134   /**
135    * Session this message belongs to.
136    */
137   struct Session *session;
138
139   /**
140    * Function to call upon transmission.
141    */
142   GNUNET_TRANSPORT_TransmitContinuation cont;
143
144   /**
145    * Closure for 'cont'.
146    */
147   void *cont_cls;
148
149   /**
150    * Timeout for this message.
151    */
152   struct GNUNET_TIME_Absolute timeout;
153
154   /**
155    * Number of bytes in 'msg'.
156    */
157   size_t msgsize;
158
159   /**
160    * Number of bytes of payload encapsulated in 'msg'.
161    */
162   size_t payload;
163
164   /**
165    * Priority of the message (ignored, just dragged along in UNIX).
166    */
167   unsigned int priority;
168 };
169
170
171 /**
172  * Encapsulation of all of the state of the plugin.
173  */
174 struct Plugin;
175
176
177 /**
178  * UNIX "Session"
179  */
180 struct PeerSession
181 {
182
183   /**
184    * Stored in a linked list.
185    */
186   struct PeerSession *next;
187
188   /**
189    * Pointer to the global plugin struct.
190    */
191   struct Plugin *plugin;
192
193   /**
194    * To whom are we talking to (set to our identity
195    * if we are still waiting for the welcome message)
196    */
197   struct GNUNET_PeerIdentity target;
198
199   /**
200    * Address of the other peer (either based on our 'connect'
201    * call or on our 'accept' call).
202    */
203   void *connect_addr;
204
205   /**
206    * Length of connect_addr.
207    */
208   size_t connect_alen;
209
210   /**
211    * Are we still expecting the welcome message? (GNUNET_YES/GNUNET_NO)
212    */
213   int expecting_welcome;
214
215   /**
216    * From which socket do we need to send to this peer?
217    */
218   struct GNUNET_NETWORK_Handle *sock;
219
220   /*
221    * Queue of messages for this peer, in the case that
222    * we have to await a connection...
223    */
224   struct MessageQueue *messages;
225
226 };
227
228
229 /**
230  * Information we keep for each of our listen sockets.
231  */
232 struct UNIX_Sock_Info
233 {
234   /**
235    * The network handle
236    */
237   struct GNUNET_NETWORK_Handle *desc;
238
239   /**
240    * The port we bound to (not an actual PORT, as UNIX domain sockets
241    * don't have ports, but rather a number in the path name to make this
242    * one unique).
243    */
244   uint16_t port;
245 };
246
247
248 /**
249  * Encapsulation of all of the state of the plugin.
250  */
251 struct Plugin
252 {
253
254   /**
255    * ID of task used to update our addresses when one expires.
256    */
257   GNUNET_SCHEDULER_TaskIdentifier address_update_task;
258
259   /**
260    * ID of select task
261    */
262   GNUNET_SCHEDULER_TaskIdentifier select_task;
263
264   /**
265    * Number of bytes we currently have in our write queue.
266    */
267   unsigned long long bytes_in_queue;
268
269   /**
270    * Our environment.
271    */
272   struct GNUNET_TRANSPORT_PluginEnvironment *env;
273
274   /**
275    * Sessions
276    */
277   struct GNUNET_CONTAINER_MultiHashMap *session_map;
278
279   /**
280    * FD Read set
281    */
282   struct GNUNET_NETWORK_FDSet *rs;
283
284   /**
285    * FD Write set
286    */
287   struct GNUNET_NETWORK_FDSet *ws;
288
289   /**
290    * Path of our unix domain socket (/tmp/unix-plugin-PORT)
291    */
292   char *unix_socket_path;
293
294   /**
295    * Head of queue of messages to transmit.
296    */
297   struct UNIXMessageWrapper *msg_head;
298
299   /**
300    * Tail of queue of messages to transmit.
301    */
302   struct UNIXMessageWrapper *msg_tail;
303
304   /**
305    * socket that we transmit all data with
306    */
307   struct UNIX_Sock_Info unix_sock;
308
309   /**
310    * ATS network
311    */
312   struct GNUNET_ATS_Information ats_network;
313
314   /**
315    * Is the write set in the current 'select' task?  GNUNET_NO if the
316    * write queue was empty when the main task was scheduled,
317    * GNUNET_YES if we're already waiting for being allowed to write.
318    */
319   int with_ws;
320
321   /**
322    * Integer to append to unix domain socket.
323    */
324   uint16_t port;
325
326 };
327
328
329 /**
330  * Increment session timeout due to activity
331  *
332  * @param s session for which the timeout should be moved
333  */
334 static void
335 reschedule_session_timeout (struct Session *s);
336
337
338 /**
339  * We have been notified that our writeset has something to read.  We don't
340  * know which socket needs to be read, so we have to check each one
341  * Then reschedule this function to be called again once more is available.
342  *
343  * @param cls the plugin handle
344  * @param tc the scheduling context (for rescheduling this function again)
345  */
346 static void
347 unix_plugin_select (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
348
349 /**
350  * Function called for a quick conversion of the binary address to
351  * a numeric address.  Note that the caller must not free the
352  * address and that the next call to this function is allowed
353  * to override the address again.
354  *
355  * @param cls closure
356  * @param addr binary address
357  * @param addrlen length of the address
358  * @return string representing the same address
359  */
360 static const char *
361 unix_address_to_string (void *cls, const void *addr, size_t addrlen);
362
363 /**
364  * Re-schedule the main 'select' callback (unix_plugin_select)
365  * for this plugin.
366  *
367  * @param plugin the plugin context
368  */
369 static void
370 reschedule_select (struct Plugin * plugin)
371 {
372   if (plugin->select_task != GNUNET_SCHEDULER_NO_TASK)
373   {
374     GNUNET_SCHEDULER_cancel (plugin->select_task);
375     plugin->select_task = GNUNET_SCHEDULER_NO_TASK;
376   }
377   if (NULL != plugin->msg_head)
378   {
379     plugin->select_task =
380       GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
381                                    GNUNET_TIME_UNIT_FOREVER_REL,
382                                    plugin->rs,
383                                    plugin->ws,
384                                    &unix_plugin_select, plugin);
385     plugin->with_ws = GNUNET_YES;
386   }
387   else
388   {
389     plugin->select_task =
390       GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
391                                    GNUNET_TIME_UNIT_FOREVER_REL,
392                                    plugin->rs,
393                                    NULL,
394                                    &unix_plugin_select, plugin);
395     plugin->with_ws = GNUNET_NO;
396   }
397 }
398
399
400 /**
401  * Closure to 'lookup_session_it'.
402  */
403 struct LookupCtx
404 {
405   /**
406    * Location to store the session, if found.
407    */
408   struct Session *s;
409
410   /**
411    * Address we are looking for.
412    */
413   const struct UnixAddress *ua;
414
415   size_t ua_len;
416 };
417
418
419 /**
420  * Function called to find a session by address.
421  *
422  * @param cls the 'struct LookupCtx'
423  * @param key peer we are looking for (unused)
424  * @param value a session
425  * @return GNUNET_YES if not found (continue looking), GNUNET_NO on success
426  */
427 static int 
428 lookup_session_it (void *cls,
429                    const struct GNUNET_HashCode * key,
430                    void *value)
431 {
432   struct LookupCtx *lctx = cls;
433   struct Session *t = value;
434
435   if (t->addrlen != lctx->ua_len)
436     return GNUNET_YES;
437
438   if (0 == memcmp (&t->addr, lctx->ua, lctx->ua_len))
439   {
440     lctx->s = t;
441     return GNUNET_NO;
442   }
443   return GNUNET_YES;
444 }
445
446
447 /**
448  * Find an existing session by address.
449  *
450  * @param plugin the plugin
451  * @param sender for which peer should the session be?
452  * @param ua address to look for
453  * @param ua_len length of the address
454  * @return NULL if session was not found
455  */
456 static struct Session *
457 lookup_session (struct Plugin *plugin, 
458                 const struct GNUNET_PeerIdentity *sender, 
459                 const struct UnixAddress *ua, size_t ua_len)
460 {
461   struct LookupCtx lctx;
462
463   GNUNET_assert (NULL != plugin);
464   GNUNET_assert (NULL != sender);
465   GNUNET_assert (NULL != ua);
466   lctx.s = NULL;
467   lctx.ua = ua;
468   lctx.ua_len = ua_len;
469   GNUNET_CONTAINER_multihashmap_get_multiple (plugin->session_map, 
470                                               &sender->hashPubKey,
471                                               &lookup_session_it, &lctx);
472   return lctx.s;
473 }
474
475
476 /**
477  * Functions with this signature are called whenever we need
478  * to close a session due to a disconnect or failure to
479  * establish a connection.
480  *
481  * @param s session to close down
482  */
483 static void
484 disconnect_session (struct Session *s)
485 {
486   struct Plugin *plugin = s->plugin;
487   struct UNIXMessageWrapper *msgw;
488   struct UNIXMessageWrapper *next;
489   int removed;
490
491   LOG (GNUNET_ERROR_TYPE_DEBUG, 
492        "Disconnecting session for peer `%s' `%s'\n",
493        GNUNET_i2s (&s->target), 
494        s->addr);
495   plugin->env->session_end (plugin->env->cls, &s->target, s);
496   removed = GNUNET_NO;
497   next = plugin->msg_head;
498   while (NULL != next)
499   {
500     msgw = next;
501     next = msgw->next;
502     if (msgw->session != s)
503       continue;
504     GNUNET_CONTAINER_DLL_remove (plugin->msg_head, plugin->msg_tail, msgw);
505     if (NULL != msgw->cont)
506       msgw->cont (msgw->cont_cls,  &msgw->session->target, GNUNET_SYSERR,
507                   msgw->payload, 0);
508     GNUNET_free (msgw->msg);
509     GNUNET_free (msgw);
510     removed = GNUNET_YES;    
511   }
512   GNUNET_assert (GNUNET_YES ==
513                  GNUNET_CONTAINER_multihashmap_remove (plugin->session_map, 
514                                                        &s->target.hashPubKey, 
515                                                        s));
516   GNUNET_STATISTICS_set (plugin->env->stats,
517                          "# UNIX sessions active",
518                          GNUNET_CONTAINER_multihashmap_size (plugin->session_map),
519                          GNUNET_NO);
520   if ((GNUNET_YES == removed) && (NULL == plugin->msg_head))
521     reschedule_select (plugin);
522   if (GNUNET_SCHEDULER_NO_TASK != s->timeout_task)
523   {
524     GNUNET_SCHEDULER_cancel (s->timeout_task);
525     s->timeout_task = GNUNET_SCHEDULER_NO_TASK;
526   }
527   GNUNET_free (s);
528 }
529
530
531 /**
532  * Actually send out the message, assume we've got the address and
533  * send_handle squared away!
534  *
535  * @param cls closure
536  * @param send_handle which handle to send message on
537  * @param target who should receive this message (ignored by UNIX)
538  * @param msgbuf one or more GNUNET_MessageHeader(s) strung together
539  * @param msgbuf_size the size of the msgbuf to send
540  * @param priority how important is the message (ignored by UNIX)
541  * @param timeout when should we time out (give up) if we can not transmit?
542  * @param addr the addr to send the message to, needs to be a sockaddr for us
543  * @param addrlen the len of addr
544  * @param payload bytes payload to send
545  * @param cont continuation to call once the message has
546  *        been transmitted (or if the transport is ready
547  *        for the next transmission call; or if the
548  *        peer disconnected...)
549  * @param cont_cls closure for cont
550  * @return on success the number of bytes written, RETRY for retry, -1 on errors
551  */
552 static ssize_t
553 unix_real_send (void *cls,
554                 struct GNUNET_NETWORK_Handle *send_handle,
555                 const struct GNUNET_PeerIdentity *target, const char *msgbuf,
556                 size_t msgbuf_size, unsigned int priority,
557                 struct GNUNET_TIME_Absolute timeout,
558                 const struct UnixAddress *addr,
559                 size_t addrlen,
560                 size_t payload,
561                 GNUNET_TRANSPORT_TransmitContinuation cont,
562                 void *cont_cls)
563 {
564   struct Plugin *plugin = cls;
565   ssize_t sent;
566   const void *sb;
567   size_t sbs;
568   struct sockaddr_un un;
569   size_t slen;
570   const char *unix_path;
571
572
573   GNUNET_assert (NULL != plugin);
574   if (NULL == send_handle)
575   {
576     GNUNET_break (0); /* We do not have a send handle */
577     return GNUNET_SYSERR;
578   }
579   if ((NULL == addr) || (0 == addrlen))
580   {
581     GNUNET_break (0); /* Can never send if we don't have an address */
582     return GNUNET_SYSERR;
583   }
584
585   /* Prepare address */
586   unix_path = (const char *)  &addr[1];
587   memset (&un, 0, sizeof (un));
588   un.sun_family = AF_UNIX;
589   slen =  strlen (unix_path);
590   if (slen >= sizeof (un.sun_path))
591     slen = sizeof (un.sun_path) - 1;
592   GNUNET_assert (slen < sizeof (un.sun_path));
593   memcpy (un.sun_path, unix_path, slen);
594   un.sun_path[slen] = '\0';
595   slen = sizeof (struct sockaddr_un);
596 #if LINUX
597   un.sun_path[0] = '\0';
598 #endif
599 #if HAVE_SOCKADDR_IN_SIN_LEN
600   un.sun_len = (u_char) slen;
601 #endif
602   sb = (struct sockaddr *) &un;
603   sbs = slen;
604
605 resend:
606   /* Send the data */
607   sent = 0;
608   sent = GNUNET_NETWORK_socket_sendto (send_handle, msgbuf, msgbuf_size, sb, sbs);
609
610   if (GNUNET_SYSERR == sent)
611   {
612     if ( (EAGAIN == errno) ||
613          (ENOBUFS == errno) )
614       return RETRY; /* We have to retry later  */
615     if (EMSGSIZE == errno)
616     {
617       socklen_t size = 0;
618       socklen_t len = sizeof (size);
619
620       GNUNET_NETWORK_socket_getsockopt ((struct GNUNET_NETWORK_Handle *)
621                                         send_handle, SOL_SOCKET, SO_SNDBUF, &size,
622                                         &len);
623       if (size < msgbuf_size)
624       {
625         LOG (GNUNET_ERROR_TYPE_DEBUG,
626                     "Trying to increase socket buffer size from %i to %i for message size %i\n",
627                     size, ((msgbuf_size / 1000) + 2) * 1000, msgbuf_size);
628         size = ((msgbuf_size / 1000) + 2) * 1000;
629         if (GNUNET_OK == GNUNET_NETWORK_socket_setsockopt
630             ((struct GNUNET_NETWORK_Handle *) send_handle, SOL_SOCKET, SO_SNDBUF,
631              &size, sizeof (size)))
632           goto resend; /* Increased buffer size, retry sending */
633         else
634         {
635           /* Could not increase buffer size: error, no retry */
636           GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "setsockopt");
637           return GNUNET_SYSERR;
638         }
639       }
640       else
641       {
642         /* Buffer is bigger than message:  error, no retry
643          * This should never happen!*/
644         GNUNET_break (0);
645         return GNUNET_SYSERR;
646       }
647     }
648   }
649
650   LOG (GNUNET_ERROR_TYPE_DEBUG,
651        "UNIX transmit %u-byte message to %s (%d: %s)\n",
652        (unsigned int) msgbuf_size, 
653        GNUNET_a2s (sb, sbs), 
654        (int) sent,
655        (sent < 0) ? STRERROR (errno) : "ok");
656   return sent;
657 }
658
659
660 /**
661  * Closure for 'get_session_it'.
662  */
663 struct GetSessionIteratorContext
664
665   /**
666    * Location to store the session, if found.
667    */
668   struct Session *res;
669
670   /**
671    * Address information.
672    */
673   const char *address;
674
675   /**
676    * Number of bytes in 'address'
677    */
678   size_t addrlen;
679 };
680
681
682 /**
683  * Function called to find a session by address.
684  *
685  * @param cls the 'struct LookupCtx'
686  * @param key peer we are looking for (unused)
687  * @param value a session
688  * @return GNUNET_YES if not found (continue looking), GNUNET_NO on success
689  */
690 static int
691 get_session_it (void *cls, 
692                 const struct GNUNET_HashCode *key, 
693                 void *value)
694 {
695   struct GetSessionIteratorContext *gsi = cls;
696   struct Session *s = value;
697
698   if ( (gsi->addrlen == s->addrlen) &&
699        (0 == memcmp (gsi->address, s->addr, s->addrlen)) )
700   {
701     gsi->res = s;
702     return GNUNET_NO;
703   }
704   return GNUNET_YES;
705 }
706
707
708 /**
709  * Session was idle for too long, so disconnect it
710  *
711  * @param cls the 'struct Session' to disconnect
712  * @param tc scheduler context
713  */
714 static void
715 session_timeout (void *cls, 
716                  const struct GNUNET_SCHEDULER_TaskContext *tc)
717 {
718   struct Session *s = cls;
719   
720   s->timeout_task = GNUNET_SCHEDULER_NO_TASK;
721   LOG (GNUNET_ERROR_TYPE_DEBUG,
722        "Session %p was idle for %s, disconnecting\n",
723        s,
724        GNUNET_STRINGS_relative_time_to_string (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
725                                                GNUNET_YES));
726   disconnect_session (s);
727 }
728
729 /**
730  * Function obtain the network type for a session
731  *
732  * @param cls closure ('struct Plugin*')
733  * @param session the session
734  * @return the network type in HBO or GNUNET_SYSERR
735  */
736 static enum GNUNET_ATS_Network_Type
737 unix_get_network (void *cls, void *session)
738 {
739         GNUNET_assert (NULL != session);
740         return GNUNET_ATS_NET_LOOPBACK;
741 }
742
743
744 /**
745  * Creates a new outbound session the transport service will use to send data to the
746  * peer
747  *
748  * @param cls the plugin
749  * @param address the address
750  * @return the session or NULL of max connections exceeded
751  */
752 static struct Session *
753 unix_plugin_get_session (void *cls,
754                          const struct GNUNET_HELLO_Address *address)
755 {
756   struct Plugin *plugin = cls;
757   struct Session *s;
758   struct GetSessionIteratorContext gsi;
759   struct UnixAddress *ua;
760   char * addrstr;
761   uint32_t addr_str_len;
762
763   GNUNET_assert (NULL != plugin);
764   GNUNET_assert (NULL != address);
765
766   ua = (struct UnixAddress *) address->address;
767   if ((NULL == address->address) || (0 == address->address_length) ||
768                 (sizeof (struct UnixAddress) > address->address_length))
769   {
770     GNUNET_break (0);
771     return NULL;
772   }
773         addrstr = (char *) &ua[1];
774         addr_str_len = ntohl (ua->addrlen);
775         if (addr_str_len != address->address_length - sizeof (struct UnixAddress))
776   {
777                 /* This can be a legacy address */
778     return NULL;
779   }
780
781   if ('\0' != addrstr[addr_str_len - 1])
782   {
783     GNUNET_break (0);
784     return NULL;
785   }
786   if (strlen (addrstr) + 1 != addr_str_len)
787   {
788     GNUNET_break (0);
789     return NULL;
790   }
791
792   /* Check if already existing */
793   gsi.address = (const char *) address->address;
794   gsi.addrlen = address->address_length;
795   gsi.res = NULL;
796   GNUNET_CONTAINER_multihashmap_get_multiple (plugin->session_map, 
797                                               &address->peer.hashPubKey, 
798                                               &get_session_it, &gsi);
799   if (NULL != gsi.res)
800   {
801     LOG (GNUNET_ERROR_TYPE_DEBUG, 
802          "Found existing session\n");
803     return gsi.res;
804   }
805
806   /* create a new session */
807   s = GNUNET_malloc (sizeof (struct Session) + address->address_length);
808   s->addr = (struct UnixAddress *) &s[1];
809   s->addrlen = address->address_length;
810   s->plugin = plugin;
811   memcpy (s->addr, address->address, address->address_length);
812   memcpy (&s->target, &address->peer, sizeof (struct GNUNET_PeerIdentity));
813   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == s->timeout_task);
814   s->timeout_task = GNUNET_SCHEDULER_add_delayed (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
815                                                   &session_timeout,
816                                                   s);
817   LOG (GNUNET_ERROR_TYPE_DEBUG,
818        "Creating a new session %p for address `%s'\n",
819        s,  unix_address_to_string (NULL, address->address, address->address_length));
820   (void) GNUNET_CONTAINER_multihashmap_put (plugin->session_map,
821                                             &address->peer.hashPubKey, s,
822                                             GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
823   GNUNET_STATISTICS_set (plugin->env->stats,
824                          "# UNIX sessions active",
825                          GNUNET_CONTAINER_multihashmap_size (plugin->session_map),
826                          GNUNET_NO);
827   return s;
828 }
829
830
831 /**
832  * Function that can be used by the transport service to transmit
833  * a message using the plugin.   Note that in the case of a
834  * peer disconnecting, the continuation MUST be called
835  * prior to the disconnect notification itself.  This function
836  * will be called with this peer's HELLO message to initiate
837  * a fresh connection to another peer.
838  *
839  * @param cls closure
840  * @param session which session must be used
841  * @param msgbuf the message to transmit
842  * @param msgbuf_size number of bytes in 'msgbuf'
843  * @param priority how important is the message (most plugins will
844  *                 ignore message priority and just FIFO)
845  * @param to how long to wait at most for the transmission (does not
846  *                require plugins to discard the message after the timeout,
847  *                just advisory for the desired delay; most plugins will ignore
848  *                this as well)
849  * @param cont continuation to call once the message has
850  *        been transmitted (or if the transport is ready
851  *        for the next transmission call; or if the
852  *        peer disconnected...); can be NULL
853  * @param cont_cls closure for cont
854  * @return number of bytes used (on the physical network, with overheads);
855  *         -1 on hard errors (i.e. address invalid); 0 is a legal value
856  *         and does NOT mean that the message was not transmitted (DV)
857  */
858 static ssize_t
859 unix_plugin_send (void *cls,
860                   struct Session *session,
861                   const char *msgbuf, size_t msgbuf_size,
862                   unsigned int priority,
863                   struct GNUNET_TIME_Relative to,
864                   GNUNET_TRANSPORT_TransmitContinuation cont, void *cont_cls)
865 {
866   struct Plugin *plugin = cls;
867   struct UNIXMessageWrapper *wrapper;
868   struct UNIXMessage *message;
869   int ssize;
870   
871   GNUNET_assert (NULL != plugin);
872   GNUNET_assert (NULL != session);
873
874   if (GNUNET_OK != 
875       GNUNET_CONTAINER_multihashmap_contains_value (plugin->session_map,
876                                                     &session->target.hashPubKey,
877                                                     session))
878   {
879     LOG (GNUNET_ERROR_TYPE_ERROR, 
880          "Invalid session for peer `%s' `%s'\n",
881          GNUNET_i2s (&session->target),
882          (const char *) session->addr);
883     GNUNET_break (0);
884     return GNUNET_SYSERR;
885   }
886   LOG (GNUNET_ERROR_TYPE_DEBUG, 
887        "Sending %u bytes with session for peer `%s' `%s'\n",
888        msgbuf_size,
889        GNUNET_i2s (&session->target),
890        (const char *) session->addr);
891   ssize = sizeof (struct UNIXMessage) + msgbuf_size;
892   message = GNUNET_malloc (sizeof (struct UNIXMessage) + msgbuf_size);
893   message->header.size = htons (ssize);
894   message->header.type = htons (0);
895   memcpy (&message->sender, plugin->env->my_identity,
896           sizeof (struct GNUNET_PeerIdentity));
897   memcpy (&message[1], msgbuf, msgbuf_size);
898   reschedule_session_timeout (session);
899   wrapper = GNUNET_malloc (sizeof (struct UNIXMessageWrapper));
900   wrapper->msg = message;
901   wrapper->msgsize = ssize;
902   wrapper->payload = msgbuf_size;
903   wrapper->priority = priority;
904   wrapper->timeout = GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get(), to);
905   wrapper->cont = cont;
906   wrapper->cont_cls = cont_cls;
907   wrapper->session = session;
908   GNUNET_CONTAINER_DLL_insert (plugin->msg_head, 
909                                plugin->msg_tail,
910                                wrapper);
911   plugin->bytes_in_queue += ssize;
912   GNUNET_STATISTICS_set (plugin->env->stats,
913                          "# bytes currently in UNIX buffers",
914                          plugin->bytes_in_queue, 
915                          GNUNET_NO);
916   if (GNUNET_NO == plugin->with_ws)
917     reschedule_select (plugin);
918   return ssize;
919 }
920
921
922 /**
923  * Demultiplexer for UNIX messages
924  *
925  * @param plugin the main plugin for this transport
926  * @param sender from which peer the message was received
927  * @param currhdr pointer to the header of the message
928  * @param ua address to look for
929  * @param ua_len length of the address
930  */
931 static void
932 unix_demultiplexer (struct Plugin *plugin, struct GNUNET_PeerIdentity *sender,
933                     const struct GNUNET_MessageHeader *currhdr,
934                     const struct UnixAddress *ua, size_t ua_len)
935 {
936   struct Session *s = NULL;
937   struct GNUNET_HELLO_Address * addr;
938
939   GNUNET_break (ntohl(plugin->ats_network.value) != GNUNET_ATS_NET_UNSPECIFIED);
940
941   GNUNET_assert (ua_len >= sizeof (struct UnixAddress));
942
943   LOG (GNUNET_ERROR_TYPE_DEBUG, 
944        "Received message from %s\n",
945        unix_address_to_string(NULL, ua, ua_len));
946   GNUNET_STATISTICS_update (plugin->env->stats,
947                             "# bytes received via UNIX",
948                             ntohs (currhdr->size),
949                             GNUNET_NO);
950
951   addr = GNUNET_HELLO_address_allocate (sender,
952                                         "unix",
953                                         ua,
954                                         ua_len);
955   s = lookup_session (plugin, sender, ua, ua_len);
956   if (NULL == s)
957   {
958     s = unix_plugin_get_session (plugin, addr);
959     /* Notify transport and ATS about new session */
960     plugin->env->session_start (NULL, sender,
961                 PLUGIN_NAME, ua, ua_len, s, &plugin->ats_network, 1);
962   }
963   reschedule_session_timeout (s);
964
965   plugin->env->receive (plugin->env->cls, sender, currhdr,
966                         s, (const char *) ua, ua_len);
967
968   plugin->env->update_address_metrics (plugin->env->cls,
969                                        sender,
970                                        (const char *) ua, ua_len,
971                                        s,
972                                        &plugin->ats_network, 1);
973
974   GNUNET_free (addr);
975 }
976
977
978 /**
979  * Read from UNIX domain socket (it is ready).
980  *
981  * @param plugin the plugin
982  */
983 static void
984 unix_plugin_select_read (struct Plugin *plugin)
985 {
986   char buf[65536] GNUNET_ALIGN;
987   struct UnixAddress *ua;
988   struct UNIXMessage *msg;
989   struct GNUNET_PeerIdentity sender;
990   struct sockaddr_un un;
991   socklen_t addrlen;
992   ssize_t ret;
993   int offset;
994   int tsize;
995   char *msgbuf;
996   const struct GNUNET_MessageHeader *currhdr;
997   uint16_t csize;
998   size_t ua_len;
999
1000   addrlen = sizeof (un);
1001   memset (&un, 0, sizeof (un));
1002
1003   ret =
1004       GNUNET_NETWORK_socket_recvfrom (plugin->unix_sock.desc, buf, sizeof (buf),
1005                                       (struct sockaddr *) &un, &addrlen);
1006
1007   if ((GNUNET_SYSERR == ret) && ((errno == EAGAIN) || (errno == ENOBUFS)))
1008     return;
1009
1010   if (ret == GNUNET_SYSERR)
1011   {
1012     GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "recvfrom");
1013     return;
1014   }
1015   else
1016   {
1017 #if LINUX
1018     un.sun_path[0] = '/';
1019 #endif
1020     LOG (GNUNET_ERROR_TYPE_DEBUG, "Read %d bytes from socket %s\n", ret,
1021                 &un.sun_path[0]);
1022   }
1023
1024   GNUNET_assert (AF_UNIX == (un.sun_family));
1025   ua_len = sizeof (struct UnixAddress) + strlen (&un.sun_path[0]) +1;
1026   ua = GNUNET_malloc (ua_len);
1027   ua->addrlen = htonl (strlen (&un.sun_path[0]) +1);
1028   ua->options = htonl (0);
1029   memcpy (&ua[1], &un.sun_path[0], strlen (&un.sun_path[0]) +1);
1030
1031   msg = (struct UNIXMessage *) buf;
1032   csize = ntohs (msg->header.size);
1033   if ((csize < sizeof (struct UNIXMessage)) || (csize > ret))
1034   {
1035     GNUNET_break_op (0);
1036     return;
1037   }
1038   msgbuf = (char *) &msg[1];
1039   memcpy (&sender, &msg->sender, sizeof (struct GNUNET_PeerIdentity));
1040   offset = 0;
1041   tsize = csize - sizeof (struct UNIXMessage);
1042   while (offset + sizeof (struct GNUNET_MessageHeader) <= tsize)
1043   {
1044     currhdr = (struct GNUNET_MessageHeader *) &msgbuf[offset];
1045     csize = ntohs (currhdr->size);
1046     if ((csize < sizeof (struct GNUNET_MessageHeader)) ||
1047         (csize > tsize - offset))
1048     {
1049       GNUNET_break_op (0);
1050       break;
1051     }
1052     unix_demultiplexer (plugin, &sender, currhdr, ua, ua_len);
1053     offset += csize;
1054   }
1055   GNUNET_free (ua);
1056 }
1057
1058
1059 /**
1060  * Write to UNIX domain socket (it is ready).
1061  *
1062  * @param plugin the plugin
1063  */
1064 static void
1065 unix_plugin_select_write (struct Plugin *plugin)
1066 {
1067   int sent = 0;
1068   struct UNIXMessageWrapper * msgw;
1069
1070   while (NULL != (msgw = plugin->msg_tail))
1071   {
1072     if (GNUNET_TIME_absolute_get_remaining (msgw->timeout).rel_value > 0)
1073       break; /* Message is ready for sending */
1074     /* Message has a timeout */
1075     LOG (GNUNET_ERROR_TYPE_DEBUG,
1076          "Timeout for message with %u bytes \n", 
1077          (unsigned int) msgw->msgsize);
1078     GNUNET_CONTAINER_DLL_remove (plugin->msg_head, plugin->msg_tail, msgw);
1079     plugin->bytes_in_queue -= msgw->msgsize;
1080     GNUNET_STATISTICS_set (plugin->env->stats, 
1081                            "# bytes currently in UNIX buffers",
1082                            plugin->bytes_in_queue, GNUNET_NO);    
1083     GNUNET_STATISTICS_update (plugin->env->stats,
1084                               "# UNIX bytes discarded",
1085                               msgw->msgsize,
1086                               GNUNET_NO);
1087     if (NULL != msgw->cont)
1088       msgw->cont (msgw->cont_cls,
1089                   &msgw->session->target, 
1090                   GNUNET_SYSERR, 
1091                   msgw->payload, 
1092                   0);    
1093     GNUNET_free (msgw->msg);
1094     GNUNET_free (msgw);  
1095   }
1096   if (NULL == msgw)
1097     return; /* Nothing to send at the moment */
1098
1099   sent = unix_real_send (plugin,
1100                          plugin->unix_sock.desc,
1101                          &msgw->session->target,
1102                          (const char *) msgw->msg,
1103                          msgw->msgsize,
1104                          msgw->priority,
1105                          msgw->timeout,
1106                          msgw->session->addr,
1107                          msgw->session->addrlen,
1108                          msgw->payload,
1109                          msgw->cont, msgw->cont_cls);
1110
1111   if (RETRY == sent)
1112   {
1113     GNUNET_STATISTICS_update (plugin->env->stats,
1114                               "# UNIX retry attempts",
1115                               1, GNUNET_NO);
1116     return;
1117   }
1118   if (GNUNET_SYSERR == sent)
1119   {
1120     /* failed and no retry */
1121     if (NULL != msgw->cont)
1122       msgw->cont (msgw->cont_cls, &msgw->session->target, GNUNET_SYSERR, msgw->payload, 0);
1123
1124     GNUNET_CONTAINER_DLL_remove(plugin->msg_head, plugin->msg_tail, msgw);
1125
1126     GNUNET_assert (plugin->bytes_in_queue >= msgw->msgsize);
1127     plugin->bytes_in_queue -= msgw->msgsize;
1128     GNUNET_STATISTICS_set (plugin->env->stats, 
1129                            "# bytes currently in UNIX buffers",
1130                            plugin->bytes_in_queue, GNUNET_NO);
1131     GNUNET_STATISTICS_update (plugin->env->stats,
1132                               "# UNIX bytes discarded",
1133                               msgw->msgsize,
1134                               GNUNET_NO);
1135
1136     GNUNET_free (msgw->msg);
1137     GNUNET_free (msgw);
1138     return;
1139   }
1140   /* successfully sent bytes */
1141   GNUNET_break (sent > 0);
1142   GNUNET_CONTAINER_DLL_remove (plugin->msg_head, 
1143                                plugin->msg_tail, 
1144                                msgw); 
1145   GNUNET_assert (plugin->bytes_in_queue >= msgw->msgsize);
1146   plugin->bytes_in_queue -= msgw->msgsize;
1147   GNUNET_STATISTICS_set (plugin->env->stats,
1148                          "# bytes currently in UNIX buffers",
1149                          plugin->bytes_in_queue,
1150                          GNUNET_NO);
1151   GNUNET_STATISTICS_update (plugin->env->stats,
1152                             "# bytes transmitted via UNIX",
1153                             msgw->msgsize,
1154                             GNUNET_NO);  
1155   if (NULL != msgw->cont)
1156     msgw->cont (msgw->cont_cls, &msgw->session->target, 
1157                 GNUNET_OK,
1158                 msgw->payload, 
1159                 msgw->msgsize);  
1160   GNUNET_free (msgw->msg);
1161   GNUNET_free (msgw);
1162 }
1163
1164
1165 /**
1166  * We have been notified that our writeset has something to read.  We don't
1167  * know which socket needs to be read, so we have to check each one
1168  * Then reschedule this function to be called again once more is available.
1169  *
1170  * @param cls the plugin handle
1171  * @param tc the scheduling context (for rescheduling this function again)
1172  */
1173 static void
1174 unix_plugin_select (void *cls,
1175                     const struct GNUNET_SCHEDULER_TaskContext *tc)
1176 {
1177   struct Plugin *plugin = cls;
1178
1179   plugin->select_task = GNUNET_SCHEDULER_NO_TASK;
1180   if ((tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
1181     return;
1182
1183   if ((tc->reason & GNUNET_SCHEDULER_REASON_WRITE_READY) != 0)
1184   {
1185     /* Ready to send data */
1186     GNUNET_assert (GNUNET_NETWORK_fdset_isset
1187                    (tc->write_ready, plugin->unix_sock.desc));
1188     if (NULL != plugin->msg_head)
1189       unix_plugin_select_write (plugin);
1190   }
1191
1192   if ((tc->reason & GNUNET_SCHEDULER_REASON_READ_READY) != 0)
1193   {
1194     /* Ready to receive data */
1195     GNUNET_assert (GNUNET_NETWORK_fdset_isset
1196                    (tc->read_ready, plugin->unix_sock.desc));
1197     unix_plugin_select_read (plugin);
1198   }
1199   reschedule_select (plugin);
1200 }
1201
1202
1203 /**
1204  * Create a slew of UNIX sockets.  If possible, use IPv6 and IPv4.
1205  *
1206  * @param cls closure for server start, should be a struct Plugin *
1207  * @return number of sockets created or GNUNET_SYSERR on error
1208  */
1209 static int
1210 unix_transport_server_start (void *cls)
1211 {
1212   struct Plugin *plugin = cls;
1213   struct sockaddr *serverAddr;
1214   socklen_t addrlen;
1215   struct sockaddr_un un;
1216   size_t slen;
1217
1218   memset (&un, 0, sizeof (un));
1219   un.sun_family = AF_UNIX;
1220   slen = strlen (plugin->unix_socket_path) + 1;
1221   if (slen >= sizeof (un.sun_path))
1222     slen = sizeof (un.sun_path) - 1;
1223
1224   memcpy (un.sun_path, plugin->unix_socket_path, slen);
1225   un.sun_path[slen] = '\0';
1226   slen = sizeof (struct sockaddr_un);
1227 #if HAVE_SOCKADDR_IN_SIN_LEN
1228   un.sun_len = (u_char) slen;
1229 #endif
1230
1231   serverAddr = (struct sockaddr *) &un;
1232   addrlen = slen;
1233 #if LINUX
1234   un.sun_path[0] = '\0';
1235 #endif
1236   plugin->ats_network = plugin->env->get_address_type (plugin->env->cls, serverAddr, addrlen);
1237   plugin->unix_sock.desc =
1238       GNUNET_NETWORK_socket_create (AF_UNIX, SOCK_DGRAM, 0);
1239   if (NULL == plugin->unix_sock.desc)
1240   {
1241     GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "socket");
1242     return GNUNET_SYSERR;
1243   }
1244   if (GNUNET_NETWORK_socket_bind (plugin->unix_sock.desc, serverAddr, addrlen, 0)
1245       != GNUNET_OK)
1246   {
1247     GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "bind");
1248     GNUNET_NETWORK_socket_close (plugin->unix_sock.desc);
1249     plugin->unix_sock.desc = NULL;
1250     return GNUNET_SYSERR;
1251   }
1252   LOG (GNUNET_ERROR_TYPE_DEBUG, "Bound to `%s'\n", plugin->unix_socket_path);
1253   plugin->rs = GNUNET_NETWORK_fdset_create ();
1254   plugin->ws = GNUNET_NETWORK_fdset_create ();
1255   GNUNET_NETWORK_fdset_zero (plugin->rs);
1256   GNUNET_NETWORK_fdset_zero (plugin->ws);
1257   GNUNET_NETWORK_fdset_set (plugin->rs, plugin->unix_sock.desc);
1258   GNUNET_NETWORK_fdset_set (plugin->ws, plugin->unix_sock.desc);
1259
1260   reschedule_select (plugin);
1261
1262   return 1;
1263 }
1264
1265
1266 /**
1267  * Function called for a quick conversion of the binary address to
1268  * a numeric address.  Note that the caller must not free the
1269  * address and that the next call to this function is allowed
1270  * to override the address again.
1271  *
1272  * @param cls closure
1273  * @param addr binary address
1274  * @param addrlen length of the address
1275  * @return string representing the same address
1276  */
1277 static const char *
1278 unix_address_to_string (void *cls, const void *addr, size_t addrlen)
1279 {
1280   static char rbuf[1024];
1281         struct UnixAddress *ua = (struct UnixAddress *) addr;
1282         char *addrstr;
1283         char *tmp;
1284         size_t addr_str_len;
1285
1286   if ((NULL == addr) || (0 == addrlen) || (sizeof (struct UnixAddress) > addrlen))
1287   {
1288     GNUNET_break (0);
1289     return NULL;
1290   }
1291         addrstr = (char *) &ua[1];
1292         addr_str_len = ntohl (ua->addrlen);
1293
1294         if (addr_str_len != addrlen - sizeof (struct UnixAddress))
1295   {
1296     GNUNET_break (0);
1297     return NULL;
1298   }
1299
1300   if ('\0' != addrstr[addr_str_len - 1])
1301   {
1302     GNUNET_break (0);
1303     return NULL;
1304   }
1305   if (strlen (addrstr) + 1 != addr_str_len)
1306   {
1307     GNUNET_break (0);
1308     return NULL;
1309   }
1310
1311   GNUNET_asprintf(&tmp, "%s.%u.%s", PLUGIN_NAME, ntohl (ua->options), addrstr);
1312   memcpy (rbuf, tmp, strlen (tmp) + 1);
1313   GNUNET_free (tmp);
1314   return rbuf;
1315 }
1316
1317 /**
1318  * Function that will be called to check if a binary address for this
1319  * plugin is well-formed and corresponds to an address for THIS peer
1320  * (as per our configuration).  Naturally, if absolutely necessary,
1321  * plugins can be a bit conservative in their answer, but in general
1322  * plugins should make sure that the address does not redirect
1323  * traffic to a 3rd party that might try to man-in-the-middle our
1324  * traffic.
1325  *
1326  * @param cls closure, should be our handle to the Plugin
1327  * @param addr pointer to the address
1328  * @param addrlen length of addr
1329  * @return GNUNET_OK if this is a plausible address for this peer
1330  *         and transport, GNUNET_SYSERR if not
1331  *
1332  */
1333 static int
1334 unix_check_address (void *cls, const void *addr, size_t addrlen)
1335 {
1336         struct Plugin* plugin = cls;
1337         struct UnixAddress *ua = (struct UnixAddress *) addr;
1338         char *addrstr;
1339         size_t addr_str_len;
1340
1341   if ((NULL == addr) || (0 == addrlen) || (sizeof (struct UnixAddress) > addrlen))
1342   {
1343     GNUNET_break (0);
1344     return GNUNET_SYSERR;
1345   }
1346         addrstr = (char *) &ua[1];
1347         addr_str_len = ntohl (ua->addrlen);
1348   if ('\0' != addrstr[addr_str_len - 1])
1349   {
1350     GNUNET_break (0);
1351     return GNUNET_SYSERR;
1352   }
1353   if (strlen (addrstr) + 1 != addr_str_len)
1354   {
1355     GNUNET_break (0);
1356     return GNUNET_SYSERR;
1357   }
1358
1359   if (0 == strcmp (plugin->unix_socket_path, addrstr))
1360         return GNUNET_OK;
1361   return GNUNET_SYSERR;
1362 }
1363
1364
1365 /**
1366  * Convert the transports address to a nice, human-readable
1367  * format.
1368  *
1369  * @param cls closure
1370  * @param type name of the transport that generated the address
1371  * @param addr one of the addresses of the host, NULL for the last address
1372  *        the specific address format depends on the transport
1373  * @param addrlen length of the address
1374  * @param numeric should (IP) addresses be displayed in numeric form?
1375  * @param timeout after how long should we give up?
1376  * @param asc function to call on each string
1377  * @param asc_cls closure for asc
1378  */
1379 static void
1380 unix_plugin_address_pretty_printer (void *cls, const char *type,
1381                                     const void *addr, size_t addrlen,
1382                                     int numeric,
1383                                     struct GNUNET_TIME_Relative timeout,
1384                                     GNUNET_TRANSPORT_AddressStringCallback asc,
1385                                     void *asc_cls)
1386 {
1387   if ((NULL != addr) && (addrlen > 0))
1388   {
1389     asc (asc_cls, unix_address_to_string (NULL, addr, addrlen));
1390   }
1391   else
1392   {
1393     GNUNET_break (0);
1394     asc (asc_cls, "<invalid UNIX address>");
1395   }
1396   asc (asc_cls, NULL);
1397 }
1398
1399
1400 /**
1401  * Function called to convert a string address to
1402  * a binary address.
1403  *
1404  * @param cls closure ('struct Plugin*')
1405  * @param addr string address
1406  * @param addrlen length of the address (strlen(addr) + '\0')
1407  * @param buf location to store the buffer
1408  *        If the function returns GNUNET_SYSERR, its contents are undefined.
1409  * @param added length of created address
1410  * @return GNUNET_OK on success, GNUNET_SYSERR on failure
1411  */
1412 static int
1413 unix_string_to_address (void *cls, const char *addr, uint16_t addrlen,
1414     void **buf, size_t *added)
1415 {
1416         struct UnixAddress *ua;
1417   char *address;
1418   char *plugin;
1419   char *optionstr;
1420   uint32_t options;
1421   size_t ua_size;
1422
1423   /* Format unix.options.address */
1424   address = NULL;
1425   plugin = NULL;
1426   optionstr = NULL;
1427   options = 0;
1428   if ((NULL == addr) || (addrlen == 0))
1429   {
1430     GNUNET_break (0);
1431     return GNUNET_SYSERR;
1432   }
1433   if ('\0' != addr[addrlen - 1])
1434   {
1435     GNUNET_break (0);
1436     return GNUNET_SYSERR;
1437   }
1438   if (strlen (addr) != addrlen - 1)
1439   {
1440     GNUNET_break (0);
1441     return GNUNET_SYSERR;
1442   }
1443   plugin = GNUNET_strdup (addr);
1444   optionstr = strchr (plugin, '.');
1445   if (NULL == optionstr)
1446   {
1447     GNUNET_break (0);
1448     GNUNET_free (plugin);
1449     return GNUNET_SYSERR;
1450   }
1451   optionstr[0] = '\0';
1452   optionstr ++;
1453   options = atol (optionstr);
1454   address = strchr (optionstr, '.');
1455   if (NULL == address)
1456   {
1457     GNUNET_break (0);
1458     GNUNET_free (plugin);
1459     return GNUNET_SYSERR;
1460   }
1461   address[0] = '\0';
1462   address ++;
1463   if (0 != strcmp(plugin, PLUGIN_NAME))
1464   {
1465     GNUNET_break (0);
1466     GNUNET_free (plugin);
1467     return GNUNET_SYSERR;
1468   }
1469
1470   ua_size = sizeof (struct UnixAddress) + strlen (address) + 1;
1471   ua = GNUNET_malloc (ua_size);
1472   ua->options = htonl (options);
1473   ua->addrlen = htonl (strlen (address) + 1);
1474   memcpy (&ua[1], address, strlen (address) + 1);
1475   GNUNET_free (plugin);
1476
1477   (*buf) = ua;
1478   (*added) = ua_size;
1479   return GNUNET_OK;
1480 }
1481
1482
1483 /**
1484  * Notify transport service about address
1485  *
1486  * @param cls the plugin
1487  * @param tc unused
1488  */
1489 static void
1490 address_notification (void *cls,
1491                       const struct GNUNET_SCHEDULER_TaskContext *tc)
1492 {
1493   struct Plugin *plugin = cls;
1494   size_t len;
1495   struct UnixAddress *ua;
1496
1497   len = sizeof (struct UnixAddress) + strlen (plugin->unix_socket_path) + 1;
1498   ua = GNUNET_malloc (len);
1499   ua->options = htonl (myoptions);
1500   ua->addrlen = htonl(strlen (plugin->unix_socket_path) + 1);
1501   memcpy (&ua[1], plugin->unix_socket_path, strlen (plugin->unix_socket_path) + 1);
1502
1503   plugin->address_update_task = GNUNET_SCHEDULER_NO_TASK;
1504   plugin->env->notify_address (plugin->env->cls, GNUNET_YES,
1505                                ua, len, "unix");
1506   GNUNET_free (ua);
1507 }
1508
1509
1510 /**
1511  * Increment session timeout due to activity
1512  *
1513  * @param s session for which the timeout should be moved
1514  */
1515 static void
1516 reschedule_session_timeout (struct Session *s)
1517 {
1518   GNUNET_assert (NULL != s);
1519   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK != s->timeout_task);
1520   GNUNET_SCHEDULER_cancel (s->timeout_task);
1521   s->timeout_task =  GNUNET_SCHEDULER_add_delayed (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
1522                                                    &session_timeout,
1523                                                    s);
1524   LOG (GNUNET_ERROR_TYPE_DEBUG,
1525        "Timeout rescheduled for session %p set to %s\n",
1526        s,
1527        GNUNET_STRINGS_relative_time_to_string (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
1528                                                GNUNET_YES));
1529 }
1530
1531
1532 /**
1533  * Function called on sessions to disconnect
1534  *
1535  * @param cls the plugin (unused)
1536  * @param key peer identity (unused)
1537  * @param value the 'struct Session' to disconnect
1538  * @return GNUNET_YES (always, continue to iterate)
1539  */
1540 static int
1541 get_session_delete_it (void *cls, const struct GNUNET_HashCode * key, void *value)
1542 {
1543   struct Session *s = value;
1544
1545   disconnect_session (s);
1546   return GNUNET_YES;
1547 }
1548
1549
1550 /**
1551  * Disconnect from a remote node.  Clean up session if we have one for this peer
1552  *
1553  * @param cls closure for this call (should be handle to Plugin)
1554  * @param target the peeridentity of the peer to disconnect
1555  * @return GNUNET_OK on success, GNUNET_SYSERR if the operation failed
1556  */
1557 static void
1558 unix_disconnect (void *cls, 
1559                  const struct GNUNET_PeerIdentity *target)
1560 {
1561   struct Plugin *plugin = cls;
1562
1563   GNUNET_assert (plugin != NULL);
1564   GNUNET_CONTAINER_multihashmap_get_multiple (plugin->session_map,
1565                                               &target->hashPubKey, 
1566                                               &get_session_delete_it, plugin);
1567 }
1568
1569
1570 /**
1571  * The exported method.  Initializes the plugin and returns a
1572  * struct with the callbacks.
1573  *
1574  * @param cls the plugin's execution environment
1575  * @return NULL on error, plugin functions otherwise
1576  */
1577 void *
1578 libgnunet_plugin_transport_unix_init (void *cls)
1579 {
1580   struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
1581   unsigned long long port;
1582   struct GNUNET_TRANSPORT_PluginFunctions *api;
1583   struct Plugin *plugin;
1584   int sockets_created;
1585
1586   if (NULL == env->receive)
1587   {
1588     /* run in 'stub' mode (i.e. as part of gnunet-peerinfo), don't fully
1589        initialze the plugin or the API */
1590     api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
1591     api->cls = NULL;
1592     api->address_pretty_printer = &unix_plugin_address_pretty_printer;
1593     api->address_to_string = &unix_address_to_string;
1594     api->string_to_address = &unix_string_to_address;
1595     return api;
1596   }
1597   if (GNUNET_OK !=
1598       GNUNET_CONFIGURATION_get_value_number (env->cfg, "transport-unix", "PORT",
1599                                              &port))
1600     port = UNIX_NAT_DEFAULT_PORT;
1601   plugin = GNUNET_malloc (sizeof (struct Plugin));
1602   plugin->port = port;
1603   plugin->env = env;
1604   GNUNET_asprintf (&plugin->unix_socket_path, 
1605                    "/tmp/unix-plugin-sock.%d",
1606                    plugin->port);
1607
1608   /* Initialize my flags */
1609   myoptions = 0;
1610
1611   api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
1612   api->cls = plugin;
1613
1614   api->get_session = &unix_plugin_get_session;
1615   api->send = &unix_plugin_send;
1616   api->disconnect = &unix_disconnect;
1617   api->address_pretty_printer = &unix_plugin_address_pretty_printer;
1618   api->address_to_string = &unix_address_to_string;
1619   api->check_address = &unix_check_address;
1620   api->string_to_address = &unix_string_to_address;
1621   api->get_network = &unix_get_network;
1622   sockets_created = unix_transport_server_start (plugin);
1623   if (0 == sockets_created)
1624     LOG (GNUNET_ERROR_TYPE_WARNING,
1625          _("Failed to open UNIX listen socket\n"));
1626   plugin->session_map = GNUNET_CONTAINER_multihashmap_create (10, GNUNET_NO);
1627   plugin->address_update_task = GNUNET_SCHEDULER_add_now (&address_notification, plugin);
1628   return api;
1629 }
1630
1631
1632 /**
1633  * Shutdown the plugin.
1634  *
1635  * @param cls the plugin API returned from the initialization function
1636  * @return NULL (always)
1637  */
1638 void *
1639 libgnunet_plugin_transport_unix_done (void *cls)
1640 {
1641   struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
1642   struct Plugin *plugin = api->cls;
1643   struct UNIXMessageWrapper * msgw;
1644   struct UnixAddress *ua;
1645   size_t len;
1646
1647   if (NULL == plugin)
1648   {
1649     GNUNET_free (api);
1650     return NULL;
1651   }
1652
1653   len = sizeof (struct UnixAddress) + strlen (plugin->unix_socket_path) + 1;
1654   ua = GNUNET_malloc (len);
1655   ua->options = htonl (myoptions);
1656   ua->addrlen = htonl(strlen (plugin->unix_socket_path) + 1);
1657   memcpy (&ua[1], plugin->unix_socket_path, strlen (plugin->unix_socket_path) + 1);
1658
1659   plugin->env->notify_address (plugin->env->cls, GNUNET_NO,
1660                                                                                                                  ua, len, "unix");
1661   GNUNET_free (ua);
1662   while (NULL != (msgw = plugin->msg_head))
1663   {
1664     GNUNET_CONTAINER_DLL_remove (plugin->msg_head, plugin->msg_tail, msgw);
1665     if (msgw->cont != NULL)
1666       msgw->cont (msgw->cont_cls,  &msgw->session->target, GNUNET_SYSERR,
1667                   msgw->payload, 0);
1668     GNUNET_free (msgw->msg);
1669     GNUNET_free (msgw);
1670   }
1671
1672   if (GNUNET_SCHEDULER_NO_TASK != plugin->select_task)
1673   {
1674     GNUNET_SCHEDULER_cancel (plugin->select_task);
1675     plugin->select_task = GNUNET_SCHEDULER_NO_TASK;
1676   }
1677   if (GNUNET_SCHEDULER_NO_TASK != plugin->address_update_task)
1678   {
1679     GNUNET_SCHEDULER_cancel (plugin->address_update_task);
1680     plugin->address_update_task = GNUNET_SCHEDULER_NO_TASK;
1681   }
1682   if (NULL != plugin->unix_sock.desc)
1683   {
1684     GNUNET_break (GNUNET_OK ==
1685                   GNUNET_NETWORK_socket_close (plugin->unix_sock.desc));
1686     plugin->unix_sock.desc = NULL;
1687     plugin->with_ws = GNUNET_NO;
1688   }
1689   GNUNET_CONTAINER_multihashmap_iterate (plugin->session_map,
1690                                          &get_session_delete_it, plugin);
1691   GNUNET_CONTAINER_multihashmap_destroy (plugin->session_map);
1692   if (NULL != plugin->rs)
1693     GNUNET_NETWORK_fdset_destroy (plugin->rs);
1694   if (NULL != plugin->ws)
1695     GNUNET_NETWORK_fdset_destroy (plugin->ws);
1696   GNUNET_free (plugin->unix_socket_path);
1697   GNUNET_free (plugin);
1698   GNUNET_free (api);
1699   return NULL;
1700 }
1701
1702 /* end of plugin_transport_unix.c */