options support for unix
[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 addr address to look for
453  * @return NULL if session was not found
454  */
455 static struct Session *
456 lookup_session (struct Plugin *plugin, 
457                 const struct GNUNET_PeerIdentity *sender, 
458                 const struct UnixAddress *ua, size_t ua_len)
459 {
460   struct LookupCtx lctx;
461
462   GNUNET_assert (NULL != plugin);
463   GNUNET_assert (NULL != sender);
464   GNUNET_assert (NULL != ua);
465   lctx.s = NULL;
466   lctx.ua = ua;
467   lctx.ua_len = ua_len;
468   GNUNET_CONTAINER_multihashmap_get_multiple (plugin->session_map, 
469                                               &sender->hashPubKey,
470                                               &lookup_session_it, &lctx);
471   return lctx.s;
472 }
473
474
475 /**
476  * Functions with this signature are called whenever we need
477  * to close a session due to a disconnect or failure to
478  * establish a connection.
479  *
480  * @param s session to close down
481  */
482 static void
483 disconnect_session (struct Session *s)
484 {
485   struct Plugin *plugin = s->plugin;
486   struct UNIXMessageWrapper *msgw;
487   struct UNIXMessageWrapper *next;
488   int removed;
489
490   LOG (GNUNET_ERROR_TYPE_DEBUG, 
491        "Disconnecting session for peer `%s' `%s'\n",
492        GNUNET_i2s (&s->target), 
493        s->addr);
494   plugin->env->session_end (plugin->env->cls, &s->target, s);
495   removed = GNUNET_NO;
496   next = plugin->msg_head;
497   while (NULL != next)
498   {
499     msgw = next;
500     next = msgw->next;
501     if (msgw->session != s)
502       continue;
503     GNUNET_CONTAINER_DLL_remove (plugin->msg_head, plugin->msg_tail, msgw);
504     if (NULL != msgw->cont)
505       msgw->cont (msgw->cont_cls,  &msgw->session->target, GNUNET_SYSERR,
506                   msgw->payload, 0);
507     GNUNET_free (msgw->msg);
508     GNUNET_free (msgw);
509     removed = GNUNET_YES;    
510   }
511   GNUNET_assert (GNUNET_YES ==
512                  GNUNET_CONTAINER_multihashmap_remove (plugin->session_map, 
513                                                        &s->target.hashPubKey, 
514                                                        s));
515   GNUNET_STATISTICS_set (plugin->env->stats,
516                          "# UNIX sessions active",
517                          GNUNET_CONTAINER_multihashmap_size (plugin->session_map),
518                          GNUNET_NO);
519   if ((GNUNET_YES == removed) && (NULL == plugin->msg_head))
520     reschedule_select (plugin);
521   if (GNUNET_SCHEDULER_NO_TASK != s->timeout_task)
522   {
523     GNUNET_SCHEDULER_cancel (s->timeout_task);
524     s->timeout_task = GNUNET_SCHEDULER_NO_TASK;
525   }
526   GNUNET_free (s);
527 }
528
529
530 /**
531  * Actually send out the message, assume we've got the address and
532  * send_handle squared away!
533  *
534  * @param cls closure
535  * @param send_handle which handle to send message on
536  * @param target who should receive this message (ignored by UNIX)
537  * @param msgbuf one or more GNUNET_MessageHeader(s) strung together
538  * @param msgbuf_size the size of the msgbuf to send
539  * @param priority how important is the message (ignored by UNIX)
540  * @param timeout when should we time out (give up) if we can not transmit?
541  * @param addr the addr to send the message to, needs to be a sockaddr for us
542  * @param addrlen the len of addr
543  * @param payload bytes payload to send
544  * @param cont continuation to call once the message has
545  *        been transmitted (or if the transport is ready
546  *        for the next transmission call; or if the
547  *        peer disconnected...)
548  * @param cont_cls closure for cont
549  * @return on success the number of bytes written, RETRY for retry, -1 on errors
550  */
551 static ssize_t
552 unix_real_send (void *cls,
553                 struct GNUNET_NETWORK_Handle *send_handle,
554                 const struct GNUNET_PeerIdentity *target, const char *msgbuf,
555                 size_t msgbuf_size, unsigned int priority,
556                 struct GNUNET_TIME_Absolute timeout,
557                 const struct UnixAddress *addr,
558                 size_t addrlen,
559                 size_t payload,
560                 GNUNET_TRANSPORT_TransmitContinuation cont,
561                 void *cont_cls)
562 {
563   struct Plugin *plugin = cls;
564   ssize_t sent;
565   const void *sb;
566   size_t sbs;
567   struct sockaddr_un un;
568   size_t slen;
569   const char *unix_path;
570
571
572   GNUNET_assert (NULL != plugin);
573   if (NULL == send_handle)
574   {
575     GNUNET_break (0); /* We do not have a send handle */
576     return GNUNET_SYSERR;
577   }
578   if ((NULL == addr) || (0 == addrlen))
579   {
580     GNUNET_break (0); /* Can never send if we don't have an address */
581     return GNUNET_SYSERR;
582   }
583
584   /* Prepare address */
585   unix_path = (const char *)  &addr[1];
586   memset (&un, 0, sizeof (un));
587   un.sun_family = AF_UNIX;
588   slen =  strlen (unix_path);
589   if (slen >= sizeof (un.sun_path))
590     slen = sizeof (un.sun_path) - 1;
591   GNUNET_assert (slen < sizeof (un.sun_path));
592   memcpy (un.sun_path, unix_path, slen);
593   un.sun_path[slen] = '\0';
594   slen = sizeof (struct sockaddr_un);
595 #if LINUX
596   un.sun_path[0] = '\0';
597 #endif
598 #if HAVE_SOCKADDR_IN_SIN_LEN
599   un.sun_len = (u_char) slen;
600 #endif
601   sb = (struct sockaddr *) &un;
602   sbs = slen;
603
604 resend:
605   /* Send the data */
606   sent = 0;
607   sent = GNUNET_NETWORK_socket_sendto (send_handle, msgbuf, msgbuf_size, sb, sbs);
608
609   if (GNUNET_SYSERR == sent)
610   {
611     if ( (EAGAIN == errno) ||
612          (ENOBUFS == errno) )
613       return RETRY; /* We have to retry later  */
614     if (EMSGSIZE == errno)
615     {
616       socklen_t size = 0;
617       socklen_t len = sizeof (size);
618
619       GNUNET_NETWORK_socket_getsockopt ((struct GNUNET_NETWORK_Handle *)
620                                         send_handle, SOL_SOCKET, SO_SNDBUF, &size,
621                                         &len);
622       if (size < msgbuf_size)
623       {
624         LOG (GNUNET_ERROR_TYPE_DEBUG,
625                     "Trying to increase socket buffer size from %i to %i for message size %i\n",
626                     size, ((msgbuf_size / 1000) + 2) * 1000, msgbuf_size);
627         size = ((msgbuf_size / 1000) + 2) * 1000;
628         if (GNUNET_OK == GNUNET_NETWORK_socket_setsockopt
629             ((struct GNUNET_NETWORK_Handle *) send_handle, SOL_SOCKET, SO_SNDBUF,
630              &size, sizeof (size)))
631           goto resend; /* Increased buffer size, retry sending */
632         else
633         {
634           /* Could not increase buffer size: error, no retry */
635           GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "setsockopt");
636           return GNUNET_SYSERR;
637         }
638       }
639       else
640       {
641         /* Buffer is bigger than message:  error, no retry
642          * This should never happen!*/
643         GNUNET_break (0);
644         return GNUNET_SYSERR;
645       }
646     }
647   }
648
649   LOG (GNUNET_ERROR_TYPE_DEBUG,
650        "UNIX transmit %u-byte message to %s (%d: %s)\n",
651        (unsigned int) msgbuf_size, 
652        GNUNET_a2s (sb, sbs), 
653        (int) sent,
654        (sent < 0) ? STRERROR (errno) : "ok");
655   return sent;
656 }
657
658
659 /**
660  * Closure for 'get_session_it'.
661  */
662 struct GetSessionIteratorContext
663
664   /**
665    * Location to store the session, if found.
666    */
667   struct Session *res;
668
669   /**
670    * Address information.
671    */
672   const char *address;
673
674   /**
675    * Number of bytes in 'address'
676    */
677   size_t addrlen;
678 };
679
680
681 /**
682  * Function called to find a session by address.
683  *
684  * @param cls the 'struct LookupCtx'
685  * @param key peer we are looking for (unused)
686  * @param value a session
687  * @return GNUNET_YES if not found (continue looking), GNUNET_NO on success
688  */
689 static int
690 get_session_it (void *cls, 
691                 const struct GNUNET_HashCode *key, 
692                 void *value)
693 {
694   struct GetSessionIteratorContext *gsi = cls;
695   struct Session *s = value;
696
697   if ( (gsi->addrlen == s->addrlen) &&
698        (0 == memcmp (gsi->address, s->addr, s->addrlen)) )
699   {
700     gsi->res = s;
701     return GNUNET_NO;
702   }
703   return GNUNET_YES;
704 }
705
706
707 /**
708  * Session was idle for too long, so disconnect it
709  *
710  * @param cls the 'struct Session' to disconnect
711  * @param tc scheduler context
712  */
713 static void
714 session_timeout (void *cls, 
715                  const struct GNUNET_SCHEDULER_TaskContext *tc)
716 {
717   struct Session *s = cls;
718   
719   s->timeout_task = GNUNET_SCHEDULER_NO_TASK;
720   LOG (GNUNET_ERROR_TYPE_DEBUG,
721        "Session %p was idle for %s, disconnecting\n",
722        s,
723        GNUNET_STRINGS_relative_time_to_string (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
724                                                GNUNET_YES));
725   disconnect_session (s);
726 }
727
728
729 /**
730  * Creates a new outbound session the transport service will use to send data to the
731  * peer
732  *
733  * @param cls the plugin
734  * @param address the address
735  * @return the session or NULL of max connections exceeded
736  */
737 static struct Session *
738 unix_plugin_get_session (void *cls,
739                          const struct GNUNET_HELLO_Address *address)
740 {
741   struct Plugin *plugin = cls;
742   struct Session *s;
743   struct GetSessionIteratorContext gsi;
744   struct UnixAddress *ua;
745   char * addrstr;
746   uint32_t addr_str_len;
747
748   GNUNET_assert (NULL != plugin);
749   GNUNET_assert (NULL != address);
750
751   ua = (struct UnixAddress *) address->address;
752   if ((NULL == address->address) || (0 == address->address_length) ||
753                 (sizeof (struct UnixAddress) > address->address_length))
754   {
755     GNUNET_break (0);
756     return NULL;
757   }
758         addrstr = (char *) &ua[1];
759         addr_str_len = ntohl (ua->addrlen);
760         if (addr_str_len != address->address_length - sizeof (struct UnixAddress *))
761   {
762                 /* This can be a legacy address */
763     return NULL;
764   }
765
766   if ('\0' != addrstr[addr_str_len - 1])
767   {
768     GNUNET_break (0);
769     return NULL;
770   }
771   if (strlen (addrstr) + 1 != addr_str_len)
772   {
773     GNUNET_break (0);
774     return NULL;
775   }
776
777   /* Check if already existing */
778   gsi.address = (const char *) address->address;
779   gsi.addrlen = address->address_length;
780   gsi.res = NULL;
781   GNUNET_CONTAINER_multihashmap_get_multiple (plugin->session_map, 
782                                               &address->peer.hashPubKey, 
783                                               &get_session_it, &gsi);
784   if (NULL != gsi.res)
785   {
786     LOG (GNUNET_ERROR_TYPE_DEBUG, 
787          "Found existing session\n");
788     return gsi.res;
789   }
790
791   /* create a new session */
792   s = GNUNET_malloc (sizeof (struct Session) + address->address_length);
793   s->addr = (struct UnixAddress *) &s[1];
794   s->addrlen = address->address_length;
795   s->plugin = plugin;
796   memcpy (s->addr, address->address, address->address_length);
797   memcpy (&s->target, &address->peer, sizeof (struct GNUNET_PeerIdentity));
798   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == s->timeout_task);
799   s->timeout_task = GNUNET_SCHEDULER_add_delayed (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
800                                                   &session_timeout,
801                                                   s);
802   LOG (GNUNET_ERROR_TYPE_DEBUG,
803        "Creating a new session %p for address `%s'\n",
804        s,  unix_address_to_string (NULL, address->address, address->address_length));
805   (void) GNUNET_CONTAINER_multihashmap_put (plugin->session_map,
806                                             &address->peer.hashPubKey, s,
807                                             GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
808   GNUNET_STATISTICS_set (plugin->env->stats,
809                          "# UNIX sessions active",
810                          GNUNET_CONTAINER_multihashmap_size (plugin->session_map),
811                          GNUNET_NO);
812   return s;
813 }
814
815
816 /**
817  * Function that can be used by the transport service to transmit
818  * a message using the plugin.   Note that in the case of a
819  * peer disconnecting, the continuation MUST be called
820  * prior to the disconnect notification itself.  This function
821  * will be called with this peer's HELLO message to initiate
822  * a fresh connection to another peer.
823  *
824  * @param cls closure
825  * @param session which session must be used
826  * @param msgbuf the message to transmit
827  * @param msgbuf_size number of bytes in 'msgbuf'
828  * @param priority how important is the message (most plugins will
829  *                 ignore message priority and just FIFO)
830  * @param to how long to wait at most for the transmission (does not
831  *                require plugins to discard the message after the timeout,
832  *                just advisory for the desired delay; most plugins will ignore
833  *                this as well)
834  * @param cont continuation to call once the message has
835  *        been transmitted (or if the transport is ready
836  *        for the next transmission call; or if the
837  *        peer disconnected...); can be NULL
838  * @param cont_cls closure for cont
839  * @return number of bytes used (on the physical network, with overheads);
840  *         -1 on hard errors (i.e. address invalid); 0 is a legal value
841  *         and does NOT mean that the message was not transmitted (DV)
842  */
843 static ssize_t
844 unix_plugin_send (void *cls,
845                   struct Session *session,
846                   const char *msgbuf, size_t msgbuf_size,
847                   unsigned int priority,
848                   struct GNUNET_TIME_Relative to,
849                   GNUNET_TRANSPORT_TransmitContinuation cont, void *cont_cls)
850 {
851   struct Plugin *plugin = cls;
852   struct UNIXMessageWrapper *wrapper;
853   struct UNIXMessage *message;
854   int ssize;
855   
856   GNUNET_assert (NULL != plugin);
857   GNUNET_assert (NULL != session);
858
859   if (GNUNET_OK != 
860       GNUNET_CONTAINER_multihashmap_contains_value (plugin->session_map,
861                                                     &session->target.hashPubKey,
862                                                     session))
863   {
864     LOG (GNUNET_ERROR_TYPE_ERROR, 
865          "Invalid session for peer `%s' `%s'\n",
866          GNUNET_i2s (&session->target),
867          (const char *) session->addr);
868     GNUNET_break (0);
869     return GNUNET_SYSERR;
870   }
871   LOG (GNUNET_ERROR_TYPE_DEBUG, 
872        "Sending %u bytes with session for peer `%s' `%s'\n",
873        msgbuf_size,
874        GNUNET_i2s (&session->target),
875        (const char *) session->addr);
876   ssize = sizeof (struct UNIXMessage) + msgbuf_size;
877   message = GNUNET_malloc (sizeof (struct UNIXMessage) + msgbuf_size);
878   message->header.size = htons (ssize);
879   message->header.type = htons (0);
880   memcpy (&message->sender, plugin->env->my_identity,
881           sizeof (struct GNUNET_PeerIdentity));
882   memcpy (&message[1], msgbuf, msgbuf_size);
883   reschedule_session_timeout (session);
884   wrapper = GNUNET_malloc (sizeof (struct UNIXMessageWrapper));
885   wrapper->msg = message;
886   wrapper->msgsize = ssize;
887   wrapper->payload = msgbuf_size;
888   wrapper->priority = priority;
889   wrapper->timeout = GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get(), to);
890   wrapper->cont = cont;
891   wrapper->cont_cls = cont_cls;
892   wrapper->session = session;
893   GNUNET_CONTAINER_DLL_insert (plugin->msg_head, 
894                                plugin->msg_tail,
895                                wrapper);
896   plugin->bytes_in_queue += ssize;
897   GNUNET_STATISTICS_set (plugin->env->stats,
898                          "# bytes currently in UNIX buffers",
899                          plugin->bytes_in_queue, 
900                          GNUNET_NO);
901   if (GNUNET_NO == plugin->with_ws)
902     reschedule_select (plugin);
903   return ssize;
904 }
905
906
907 /**
908  * Demultiplexer for UNIX messages
909  *
910  * @param plugin the main plugin for this transport
911  * @param sender from which peer the message was received
912  * @param currhdr pointer to the header of the message
913  * @param un the address from which the message was received
914  * @param fromlen the length of the address
915  */
916 static void
917 unix_demultiplexer (struct Plugin *plugin, struct GNUNET_PeerIdentity *sender,
918                     const struct GNUNET_MessageHeader *currhdr,
919                     const struct UnixAddress *ua, size_t ua_len)
920 {
921   struct Session *s = NULL;
922   struct GNUNET_HELLO_Address * addr;
923
924   GNUNET_break (ntohl(plugin->ats_network.value) != GNUNET_ATS_NET_UNSPECIFIED);
925
926   GNUNET_assert (ua_len >= sizeof (struct UnixAddress));
927
928   LOG (GNUNET_ERROR_TYPE_DEBUG, 
929        "Received message from %s\n",
930        unix_address_to_string(NULL, ua, ua_len));
931   GNUNET_STATISTICS_update (plugin->env->stats,
932                             "# bytes received via UNIX",
933                             ntohs (currhdr->size),
934                             GNUNET_NO);
935
936   addr = GNUNET_HELLO_address_allocate (sender,
937                                         "unix",
938                                         ua,
939                                         ua_len);
940   s = lookup_session (plugin, sender, ua, ua_len);
941   if (NULL == s)
942     s = unix_plugin_get_session (plugin, addr);
943   reschedule_session_timeout (s);
944
945   plugin->env->receive (plugin->env->cls, sender, currhdr,
946                         s, (const char *) ua, ua_len);
947
948   plugin->env->update_address_metrics (plugin->env->cls,
949                                        sender,
950                                        (const char *) ua, ua_len,
951                                        s,
952                                        &plugin->ats_network, 1);
953
954   GNUNET_free (addr);
955 }
956
957
958 /**
959  * Read from UNIX domain socket (it is ready).
960  *
961  * @param plugin the plugin
962  */
963 static void
964 unix_plugin_select_read (struct Plugin *plugin)
965 {
966   char buf[65536] GNUNET_ALIGN;
967   struct UnixAddress *ua;
968   struct UNIXMessage *msg;
969   struct GNUNET_PeerIdentity sender;
970   struct sockaddr_un un;
971   socklen_t addrlen;
972   ssize_t ret;
973   int offset;
974   int tsize;
975   char *msgbuf;
976   const struct GNUNET_MessageHeader *currhdr;
977   uint16_t csize;
978   size_t ua_len;
979
980   addrlen = sizeof (un);
981   memset (&un, 0, sizeof (un));
982
983   ret =
984       GNUNET_NETWORK_socket_recvfrom (plugin->unix_sock.desc, buf, sizeof (buf),
985                                       (struct sockaddr *) &un, &addrlen);
986
987   if ((GNUNET_SYSERR == ret) && ((errno == EAGAIN) || (errno == ENOBUFS)))
988     return;
989
990   if (ret == GNUNET_SYSERR)
991   {
992     GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "recvfrom");
993     return;
994   }
995   else
996   {
997 #if LINUX
998     un.sun_path[0] = '/';
999 #endif
1000     LOG (GNUNET_ERROR_TYPE_DEBUG, "Read %d bytes from socket %s\n", ret,
1001                 &un.sun_path[0]);
1002   }
1003
1004   GNUNET_assert (AF_UNIX == (un.sun_family));
1005   ua_len = sizeof (struct UnixAddress) + strlen (&un.sun_path[0]) +1;
1006   ua = GNUNET_malloc (ua_len);
1007   ua->addrlen = htonl (strlen (&un.sun_path[0]) +1);
1008   ua->options = htonl (0);
1009   memcpy (&ua[1], &un.sun_path[0], strlen (&un.sun_path[0]) +1);
1010
1011   msg = (struct UNIXMessage *) buf;
1012   csize = ntohs (msg->header.size);
1013   if ((csize < sizeof (struct UNIXMessage)) || (csize > ret))
1014   {
1015     GNUNET_break_op (0);
1016     return;
1017   }
1018   msgbuf = (char *) &msg[1];
1019   memcpy (&sender, &msg->sender, sizeof (struct GNUNET_PeerIdentity));
1020   offset = 0;
1021   tsize = csize - sizeof (struct UNIXMessage);
1022   while (offset + sizeof (struct GNUNET_MessageHeader) <= tsize)
1023   {
1024     currhdr = (struct GNUNET_MessageHeader *) &msgbuf[offset];
1025     csize = ntohs (currhdr->size);
1026     if ((csize < sizeof (struct GNUNET_MessageHeader)) ||
1027         (csize > tsize - offset))
1028     {
1029       GNUNET_break_op (0);
1030       break;
1031     }
1032     unix_demultiplexer (plugin, &sender, currhdr, ua, ua_len);
1033     offset += csize;
1034   }
1035   GNUNET_free (ua);
1036 }
1037
1038
1039 /**
1040  * Write to UNIX domain socket (it is ready).
1041  *
1042  * @param plugin the plugin
1043  */
1044 static void
1045 unix_plugin_select_write (struct Plugin *plugin)
1046 {
1047   int sent = 0;
1048   struct UNIXMessageWrapper * msgw;
1049
1050   while (NULL != (msgw = plugin->msg_tail))
1051   {
1052     if (GNUNET_TIME_absolute_get_remaining (msgw->timeout).rel_value > 0)
1053       break; /* Message is ready for sending */
1054     /* Message has a timeout */
1055     LOG (GNUNET_ERROR_TYPE_DEBUG,
1056          "Timeout for message with %u bytes \n", 
1057          (unsigned int) msgw->msgsize);
1058     GNUNET_CONTAINER_DLL_remove (plugin->msg_head, plugin->msg_tail, msgw);
1059     plugin->bytes_in_queue -= msgw->msgsize;
1060     GNUNET_STATISTICS_set (plugin->env->stats, 
1061                            "# bytes currently in UNIX buffers",
1062                            plugin->bytes_in_queue, GNUNET_NO);    
1063     GNUNET_STATISTICS_update (plugin->env->stats,
1064                               "# UNIX bytes discarded",
1065                               msgw->msgsize,
1066                               GNUNET_NO);
1067     if (NULL != msgw->cont)
1068       msgw->cont (msgw->cont_cls,
1069                   &msgw->session->target, 
1070                   GNUNET_SYSERR, 
1071                   msgw->payload, 
1072                   0);    
1073     GNUNET_free (msgw->msg);
1074     GNUNET_free (msgw);  
1075   }
1076   if (NULL == msgw)
1077     return; /* Nothing to send at the moment */
1078
1079   sent = unix_real_send (plugin,
1080                          plugin->unix_sock.desc,
1081                          &msgw->session->target,
1082                          (const char *) msgw->msg,
1083                          msgw->msgsize,
1084                          msgw->priority,
1085                          msgw->timeout,
1086                          msgw->session->addr,
1087                          msgw->session->addrlen,
1088                          msgw->payload,
1089                          msgw->cont, msgw->cont_cls);
1090
1091   if (RETRY == sent)
1092   {
1093     GNUNET_STATISTICS_update (plugin->env->stats,
1094                               "# UNIX retry attempts",
1095                               1, GNUNET_NO);
1096     return;
1097   }
1098   if (GNUNET_SYSERR == sent)
1099   {
1100     /* failed and no retry */
1101     if (NULL != msgw->cont)
1102       msgw->cont (msgw->cont_cls, &msgw->session->target, GNUNET_SYSERR, msgw->payload, 0);
1103
1104     GNUNET_CONTAINER_DLL_remove(plugin->msg_head, plugin->msg_tail, msgw);
1105
1106     GNUNET_assert (plugin->bytes_in_queue >= msgw->msgsize);
1107     plugin->bytes_in_queue -= msgw->msgsize;
1108     GNUNET_STATISTICS_set (plugin->env->stats, 
1109                            "# bytes currently in UNIX buffers",
1110                            plugin->bytes_in_queue, GNUNET_NO);
1111     GNUNET_STATISTICS_update (plugin->env->stats,
1112                               "# UNIX bytes discarded",
1113                               msgw->msgsize,
1114                               GNUNET_NO);
1115
1116     GNUNET_free (msgw->msg);
1117     GNUNET_free (msgw);
1118     return;
1119   }
1120   /* successfully sent bytes */
1121   GNUNET_break (sent > 0);
1122   GNUNET_CONTAINER_DLL_remove (plugin->msg_head, 
1123                                plugin->msg_tail, 
1124                                msgw); 
1125   GNUNET_assert (plugin->bytes_in_queue >= msgw->msgsize);
1126   plugin->bytes_in_queue -= msgw->msgsize;
1127   GNUNET_STATISTICS_set (plugin->env->stats,
1128                          "# bytes currently in UNIX buffers",
1129                          plugin->bytes_in_queue,
1130                          GNUNET_NO);
1131   GNUNET_STATISTICS_update (plugin->env->stats,
1132                             "# bytes transmitted via UNIX",
1133                             msgw->msgsize,
1134                             GNUNET_NO);  
1135   if (NULL != msgw->cont)
1136     msgw->cont (msgw->cont_cls, &msgw->session->target, 
1137                 GNUNET_OK,
1138                 msgw->payload, 
1139                 msgw->msgsize);  
1140   GNUNET_free (msgw->msg);
1141   GNUNET_free (msgw);
1142 }
1143
1144
1145 /**
1146  * We have been notified that our writeset has something to read.  We don't
1147  * know which socket needs to be read, so we have to check each one
1148  * Then reschedule this function to be called again once more is available.
1149  *
1150  * @param cls the plugin handle
1151  * @param tc the scheduling context (for rescheduling this function again)
1152  */
1153 static void
1154 unix_plugin_select (void *cls,
1155                     const struct GNUNET_SCHEDULER_TaskContext *tc)
1156 {
1157   struct Plugin *plugin = cls;
1158
1159   plugin->select_task = GNUNET_SCHEDULER_NO_TASK;
1160   if ((tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
1161     return;
1162
1163   if ((tc->reason & GNUNET_SCHEDULER_REASON_WRITE_READY) != 0)
1164   {
1165     /* Ready to send data */
1166     GNUNET_assert (GNUNET_NETWORK_fdset_isset
1167                    (tc->write_ready, plugin->unix_sock.desc));
1168     if (NULL != plugin->msg_head)
1169       unix_plugin_select_write (plugin);
1170   }
1171
1172   if ((tc->reason & GNUNET_SCHEDULER_REASON_READ_READY) != 0)
1173   {
1174     /* Ready to receive data */
1175     GNUNET_assert (GNUNET_NETWORK_fdset_isset
1176                    (tc->read_ready, plugin->unix_sock.desc));
1177     unix_plugin_select_read (plugin);
1178   }
1179   reschedule_select (plugin);
1180 }
1181
1182
1183 /**
1184  * Create a slew of UNIX sockets.  If possible, use IPv6 and IPv4.
1185  *
1186  * @param cls closure for server start, should be a struct Plugin *
1187  * @return number of sockets created or GNUNET_SYSERR on error
1188  */
1189 static int
1190 unix_transport_server_start (void *cls)
1191 {
1192   struct Plugin *plugin = cls;
1193   struct sockaddr *serverAddr;
1194   socklen_t addrlen;
1195   struct sockaddr_un un;
1196   size_t slen;
1197
1198   memset (&un, 0, sizeof (un));
1199   un.sun_family = AF_UNIX;
1200   slen = strlen (plugin->unix_socket_path) + 1;
1201   if (slen >= sizeof (un.sun_path))
1202     slen = sizeof (un.sun_path) - 1;
1203
1204   memcpy (un.sun_path, plugin->unix_socket_path, slen);
1205   un.sun_path[slen] = '\0';
1206   slen = sizeof (struct sockaddr_un);
1207 #if HAVE_SOCKADDR_IN_SIN_LEN
1208   un.sun_len = (u_char) slen;
1209 #endif
1210
1211   serverAddr = (struct sockaddr *) &un;
1212   addrlen = slen;
1213 #if LINUX
1214   un.sun_path[0] = '\0';
1215 #endif
1216   plugin->ats_network = plugin->env->get_address_type (plugin->env->cls, serverAddr, addrlen);
1217   plugin->unix_sock.desc =
1218       GNUNET_NETWORK_socket_create (AF_UNIX, SOCK_DGRAM, 0);
1219   if (NULL == plugin->unix_sock.desc)
1220   {
1221     GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "socket");
1222     return GNUNET_SYSERR;
1223   }
1224   if (GNUNET_NETWORK_socket_bind (plugin->unix_sock.desc, serverAddr, addrlen, 0)
1225       != GNUNET_OK)
1226   {
1227     GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "bind");
1228     GNUNET_NETWORK_socket_close (plugin->unix_sock.desc);
1229     plugin->unix_sock.desc = NULL;
1230     return GNUNET_SYSERR;
1231   }
1232   LOG (GNUNET_ERROR_TYPE_DEBUG, "Bound to `%s'\n", plugin->unix_socket_path);
1233   plugin->rs = GNUNET_NETWORK_fdset_create ();
1234   plugin->ws = GNUNET_NETWORK_fdset_create ();
1235   GNUNET_NETWORK_fdset_zero (plugin->rs);
1236   GNUNET_NETWORK_fdset_zero (plugin->ws);
1237   GNUNET_NETWORK_fdset_set (plugin->rs, plugin->unix_sock.desc);
1238   GNUNET_NETWORK_fdset_set (plugin->ws, plugin->unix_sock.desc);
1239
1240   reschedule_select (plugin);
1241
1242   return 1;
1243 }
1244
1245
1246 /**
1247  * Function called for a quick conversion of the binary address to
1248  * a numeric address.  Note that the caller must not free the
1249  * address and that the next call to this function is allowed
1250  * to override the address again.
1251  *
1252  * @param cls closure
1253  * @param addr binary address
1254  * @param addrlen length of the address
1255  * @return string representing the same address
1256  */
1257 static const char *
1258 unix_address_to_string (void *cls, const void *addr, size_t addrlen)
1259 {
1260   static char rbuf[1024];
1261         struct UnixAddress *ua = (struct UnixAddress *) addr;
1262         char *addrstr;
1263         char *tmp;
1264         size_t addr_str_len;
1265
1266   if ((NULL == addr) || (0 == addrlen) || (sizeof (struct UnixAddress) > addrlen))
1267   {
1268     GNUNET_break (0);
1269     return NULL;
1270   }
1271         addrstr = (char *) &ua[1];
1272         addr_str_len = ntohl (ua->addrlen);
1273
1274         if (addr_str_len != addrlen - sizeof (struct UnixAddress *))
1275   {
1276     GNUNET_break (0);
1277     return NULL;
1278   }
1279
1280   if ('\0' != addrstr[addr_str_len - 1])
1281   {
1282     GNUNET_break (0);
1283     return NULL;
1284   }
1285   if (strlen (addrstr) + 1 != addr_str_len)
1286   {
1287     GNUNET_break (0);
1288     return NULL;
1289   }
1290
1291   GNUNET_asprintf(&tmp, "%s.%u.%s", PLUGIN_NAME, ntohl (ua->options), addrstr);
1292   memcpy (rbuf, tmp, strlen (tmp) + 1);
1293   GNUNET_free (tmp);
1294   return rbuf;
1295 }
1296
1297 /**
1298  * Function that will be called to check if a binary address for this
1299  * plugin is well-formed and corresponds to an address for THIS peer
1300  * (as per our configuration).  Naturally, if absolutely necessary,
1301  * plugins can be a bit conservative in their answer, but in general
1302  * plugins should make sure that the address does not redirect
1303  * traffic to a 3rd party that might try to man-in-the-middle our
1304  * traffic.
1305  *
1306  * @param cls closure, should be our handle to the Plugin
1307  * @param addr pointer to the address
1308  * @param addrlen length of addr
1309  * @return GNUNET_OK if this is a plausible address for this peer
1310  *         and transport, GNUNET_SYSERR if not
1311  *
1312  */
1313 static int
1314 unix_check_address (void *cls, const void *addr, size_t addrlen)
1315 {
1316         struct Plugin* plugin = cls;
1317         struct UnixAddress *ua = (struct UnixAddress *) addr;
1318         char *addrstr;
1319         size_t addr_str_len;
1320
1321   if ((NULL == addr) || (0 == addrlen) || (sizeof (struct UnixAddress) > addrlen))
1322   {
1323     GNUNET_break (0);
1324     return GNUNET_SYSERR;
1325   }
1326         addrstr = (char *) &ua[1];
1327         addr_str_len = ntohl (ua->addrlen);
1328   if ('\0' != addrstr[addr_str_len - 1])
1329   {
1330     GNUNET_break (0);
1331     return GNUNET_SYSERR;
1332   }
1333   if (strlen (addrstr) + 1 != addr_str_len)
1334   {
1335     GNUNET_break (0);
1336     return GNUNET_SYSERR;
1337   }
1338
1339   if (0 == strcmp (plugin->unix_socket_path, addrstr))
1340         return GNUNET_OK;
1341   return GNUNET_SYSERR;
1342 }
1343
1344
1345 /**
1346  * Convert the transports address to a nice, human-readable
1347  * format.
1348  *
1349  * @param cls closure
1350  * @param type name of the transport that generated the address
1351  * @param addr one of the addresses of the host, NULL for the last address
1352  *        the specific address format depends on the transport
1353  * @param addrlen length of the address
1354  * @param numeric should (IP) addresses be displayed in numeric form?
1355  * @param timeout after how long should we give up?
1356  * @param asc function to call on each string
1357  * @param asc_cls closure for asc
1358  */
1359 static void
1360 unix_plugin_address_pretty_printer (void *cls, const char *type,
1361                                     const void *addr, size_t addrlen,
1362                                     int numeric,
1363                                     struct GNUNET_TIME_Relative timeout,
1364                                     GNUNET_TRANSPORT_AddressStringCallback asc,
1365                                     void *asc_cls)
1366 {
1367   if ((NULL != addr) && (addrlen > 0))
1368   {
1369     asc (asc_cls, unix_address_to_string (NULL, addr, addrlen));
1370   }
1371   else
1372   {
1373     GNUNET_break (0);
1374     asc (asc_cls, "<invalid UNIX address>");
1375   }
1376   asc (asc_cls, NULL);
1377 }
1378
1379
1380 /**
1381  * Function called to convert a string address to
1382  * a binary address.
1383  *
1384  * @param cls closure ('struct Plugin*')
1385  * @param addr string address
1386  * @param addrlen length of the address (strlen(addr) + '\0')
1387  * @param buf location to store the buffer
1388  *        If the function returns GNUNET_SYSERR, its contents are undefined.
1389  * @param added length of created address
1390  * @return GNUNET_OK on success, GNUNET_SYSERR on failure
1391  */
1392 static int
1393 unix_string_to_address (void *cls, const char *addr, uint16_t addrlen,
1394     void **buf, size_t *added)
1395 {
1396         struct UnixAddress *ua;
1397   char *address;
1398   char *plugin;
1399   char *optionstr;
1400   uint32_t options;
1401   size_t ua_size;
1402
1403   /* Format unix.options.address */
1404   address = NULL;
1405   plugin = NULL;
1406   optionstr = NULL;
1407   options = 0;
1408   if ((NULL == addr) || (addrlen == 0))
1409   {
1410     GNUNET_break (0);
1411     return GNUNET_SYSERR;
1412   }
1413   if ('\0' != addr[addrlen - 1])
1414   {
1415     GNUNET_break (0);
1416     return GNUNET_SYSERR;
1417   }
1418   if (strlen (addr) != addrlen - 1)
1419   {
1420     GNUNET_break (0);
1421     return GNUNET_SYSERR;
1422   }
1423   plugin = GNUNET_strdup (addr);
1424   optionstr = strchr (plugin, '.');
1425   if (NULL == optionstr)
1426   {
1427     GNUNET_break (0);
1428     GNUNET_free (plugin);
1429     return GNUNET_SYSERR;
1430   }
1431   optionstr[0] = '\0';
1432   optionstr ++;
1433   options = atol (optionstr);
1434   address = strchr (optionstr, '.');
1435   if (NULL == address)
1436   {
1437     GNUNET_break (0);
1438     GNUNET_free (plugin);
1439     return GNUNET_SYSERR;
1440   }
1441   address[0] = '\0';
1442   address ++;
1443   if (0 != strcmp(plugin, PLUGIN_NAME))
1444   {
1445     GNUNET_break (0);
1446     GNUNET_free (plugin);
1447     return GNUNET_SYSERR;
1448   }
1449
1450   ua_size = sizeof (struct UnixAddress) + strlen (address) + 1;
1451   ua = GNUNET_malloc (ua_size);
1452   ua->options = htonl (options);
1453   ua->addrlen = htonl (strlen (address) + 1);
1454   memcpy (&ua[1], address, strlen (address) + 1);
1455   GNUNET_free (plugin);
1456
1457   (*buf) = ua;
1458   (*added) = ua_size;
1459   return GNUNET_OK;
1460 }
1461
1462
1463 /**
1464  * Notify transport service about address
1465  *
1466  * @param cls the plugin
1467  * @param tc unused
1468  */
1469 static void
1470 address_notification (void *cls,
1471                       const struct GNUNET_SCHEDULER_TaskContext *tc)
1472 {
1473   struct Plugin *plugin = cls;
1474   size_t len;
1475   struct UnixAddress *ua;
1476
1477   len = sizeof (struct UnixAddress) + strlen (plugin->unix_socket_path) + 1;
1478   ua = GNUNET_malloc (len);
1479   ua->options = htonl (myoptions);
1480   ua->addrlen = htonl(strlen (plugin->unix_socket_path) + 1);
1481   memcpy (&ua[1], plugin->unix_socket_path, strlen (plugin->unix_socket_path) + 1);
1482
1483   plugin->address_update_task = GNUNET_SCHEDULER_NO_TASK;
1484   plugin->env->notify_address (plugin->env->cls, GNUNET_YES,
1485                                ua, len, "unix");
1486   GNUNET_free (ua);
1487 }
1488
1489
1490 /**
1491  * Increment session timeout due to activity
1492  *
1493  * @param s session for which the timeout should be moved
1494  */
1495 static void
1496 reschedule_session_timeout (struct Session *s)
1497 {
1498   GNUNET_assert (NULL != s);
1499   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK != s->timeout_task);
1500   GNUNET_SCHEDULER_cancel (s->timeout_task);
1501   s->timeout_task =  GNUNET_SCHEDULER_add_delayed (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
1502                                                    &session_timeout,
1503                                                    s);
1504   LOG (GNUNET_ERROR_TYPE_DEBUG,
1505        "Timeout rescheduled for session %p set to %s\n",
1506        s,
1507        GNUNET_STRINGS_relative_time_to_string (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT,
1508                                                GNUNET_YES));
1509 }
1510
1511
1512 /**
1513  * Function called on sessions to disconnect
1514  *
1515  * @param cls the plugin (unused)
1516  * @param key peer identity (unused)
1517  * @param value the 'struct Session' to disconnect
1518  * @return GNUNET_YES (always, continue to iterate)
1519  */
1520 static int
1521 get_session_delete_it (void *cls, const struct GNUNET_HashCode * key, void *value)
1522 {
1523   struct Session *s = value;
1524
1525   disconnect_session (s);
1526   return GNUNET_YES;
1527 }
1528
1529
1530 /**
1531  * Disconnect from a remote node.  Clean up session if we have one for this peer
1532  *
1533  * @param cls closure for this call (should be handle to Plugin)
1534  * @param target the peeridentity of the peer to disconnect
1535  * @return GNUNET_OK on success, GNUNET_SYSERR if the operation failed
1536  */
1537 static void
1538 unix_disconnect (void *cls, 
1539                  const struct GNUNET_PeerIdentity *target)
1540 {
1541   struct Plugin *plugin = cls;
1542
1543   GNUNET_assert (plugin != NULL);
1544   GNUNET_CONTAINER_multihashmap_get_multiple (plugin->session_map,
1545                                               &target->hashPubKey, 
1546                                               &get_session_delete_it, plugin);
1547 }
1548
1549
1550 /**
1551  * The exported method.  Initializes the plugin and returns a
1552  * struct with the callbacks.
1553  *
1554  * @param cls the plugin's execution environment
1555  * @return NULL on error, plugin functions otherwise
1556  */
1557 void *
1558 libgnunet_plugin_transport_unix_init (void *cls)
1559 {
1560   struct GNUNET_TRANSPORT_PluginEnvironment *env = cls;
1561   unsigned long long port;
1562   struct GNUNET_TRANSPORT_PluginFunctions *api;
1563   struct Plugin *plugin;
1564   int sockets_created;
1565
1566   if (NULL == env->receive)
1567   {
1568     /* run in 'stub' mode (i.e. as part of gnunet-peerinfo), don't fully
1569        initialze the plugin or the API */
1570     api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
1571     api->cls = NULL;
1572     api->address_pretty_printer = &unix_plugin_address_pretty_printer;
1573     api->address_to_string = &unix_address_to_string;
1574     api->string_to_address = &unix_string_to_address;
1575     return api;
1576   }
1577   if (GNUNET_OK !=
1578       GNUNET_CONFIGURATION_get_value_number (env->cfg, "transport-unix", "PORT",
1579                                              &port))
1580     port = UNIX_NAT_DEFAULT_PORT;
1581   plugin = GNUNET_malloc (sizeof (struct Plugin));
1582   plugin->port = port;
1583   plugin->env = env;
1584   GNUNET_asprintf (&plugin->unix_socket_path, 
1585                    "/tmp/unix-plugin-sock.%d",
1586                    plugin->port);
1587
1588   /* Initialize my flags */
1589   myoptions = 0;
1590
1591   api = GNUNET_malloc (sizeof (struct GNUNET_TRANSPORT_PluginFunctions));
1592   api->cls = plugin;
1593
1594   api->get_session = &unix_plugin_get_session;
1595   api->send = &unix_plugin_send;
1596   api->disconnect = &unix_disconnect;
1597   api->address_pretty_printer = &unix_plugin_address_pretty_printer;
1598   api->address_to_string = &unix_address_to_string;
1599   api->check_address = &unix_check_address;
1600   api->string_to_address = &unix_string_to_address;
1601   sockets_created = unix_transport_server_start (plugin);
1602   if (0 == sockets_created)
1603     LOG (GNUNET_ERROR_TYPE_WARNING,
1604          _("Failed to open UNIX listen socket\n"));
1605   plugin->session_map = GNUNET_CONTAINER_multihashmap_create (10, GNUNET_NO);
1606   plugin->address_update_task = GNUNET_SCHEDULER_add_now (&address_notification, plugin);
1607   return api;
1608 }
1609
1610
1611 /**
1612  * Shutdown the plugin.
1613  *
1614  * @param cls the plugin API returned from the initialization function
1615  * @return NULL (always)
1616  */
1617 void *
1618 libgnunet_plugin_transport_unix_done (void *cls)
1619 {
1620   struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
1621   struct Plugin *plugin = api->cls;
1622   struct UNIXMessageWrapper * msgw;
1623   struct UnixAddress *ua;
1624   size_t len;
1625
1626   if (NULL == plugin)
1627   {
1628     GNUNET_free (api);
1629     return NULL;
1630   }
1631
1632   len = sizeof (struct UnixAddress) + strlen (plugin->unix_socket_path) + 1;
1633   ua = GNUNET_malloc (len);
1634   ua->options = htonl (myoptions);
1635   ua->addrlen = htonl(strlen (plugin->unix_socket_path) + 1);
1636   memcpy (&ua[1], plugin->unix_socket_path, strlen (plugin->unix_socket_path) + 1);
1637
1638   plugin->env->notify_address (plugin->env->cls, GNUNET_NO,
1639                                                                                                                  ua, len, "unix");
1640   GNUNET_free (ua);
1641   while (NULL != (msgw = plugin->msg_head))
1642   {
1643     GNUNET_CONTAINER_DLL_remove (plugin->msg_head, plugin->msg_tail, msgw);
1644     if (msgw->cont != NULL)
1645       msgw->cont (msgw->cont_cls,  &msgw->session->target, GNUNET_SYSERR,
1646                   msgw->payload, 0);
1647     GNUNET_free (msgw->msg);
1648     GNUNET_free (msgw);
1649   }
1650
1651   if (GNUNET_SCHEDULER_NO_TASK != plugin->select_task)
1652   {
1653     GNUNET_SCHEDULER_cancel (plugin->select_task);
1654     plugin->select_task = GNUNET_SCHEDULER_NO_TASK;
1655   }
1656   if (GNUNET_SCHEDULER_NO_TASK != plugin->address_update_task)
1657   {
1658     GNUNET_SCHEDULER_cancel (plugin->address_update_task);
1659     plugin->address_update_task = GNUNET_SCHEDULER_NO_TASK;
1660   }
1661   if (NULL != plugin->unix_sock.desc)
1662   {
1663     GNUNET_break (GNUNET_OK ==
1664                   GNUNET_NETWORK_socket_close (plugin->unix_sock.desc));
1665     plugin->unix_sock.desc = NULL;
1666     plugin->with_ws = GNUNET_NO;
1667   }
1668   GNUNET_CONTAINER_multihashmap_iterate (plugin->session_map,
1669                                          &get_session_delete_it, plugin);
1670   GNUNET_CONTAINER_multihashmap_destroy (plugin->session_map);
1671   if (NULL != plugin->rs)
1672     GNUNET_NETWORK_fdset_destroy (plugin->rs);
1673   if (NULL != plugin->ws)
1674     GNUNET_NETWORK_fdset_destroy (plugin->ws);
1675   GNUNET_free (plugin->unix_socket_path);
1676   GNUNET_free (plugin);
1677   GNUNET_free (api);
1678   return NULL;
1679 }
1680
1681 /* end of plugin_transport_unix.c */