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