Update plibc header
[oweals/gnunet.git] / src / util / connection.c
1 /*
2      This file is part of GNUnet.
3      (C) 2009-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 util/connection.c
23  * @brief  TCP connection management
24  * @author Christian Grothoff
25  *
26  * This code is rather complex.  Only modify it if you
27  * 1) Have a NEW testcase showing that the new code
28  *    is needed and correct
29  * 2) All EXISTING testcases pass with the new code
30  * These rules should apply in general, but for this
31  * module they are VERY, VERY important.
32  */
33 #include "platform.h"
34 #include "gnunet_util_lib.h"
35 #include "gnunet_resolver_service.h"
36
37
38 #define LOG(kind,...) GNUNET_log_from (kind, "util", __VA_ARGS__)
39
40 #define LOG_STRERROR(kind,syscall) GNUNET_log_from_strerror (kind, "util", syscall)
41
42
43 /**
44  * Transmission handle.  There can only be one for each connection.
45  */
46 struct GNUNET_CONNECTION_TransmitHandle
47 {
48
49   /**
50    * Function to call if the send buffer has notify_size
51    * bytes available.
52    */
53   GNUNET_CONNECTION_TransmitReadyNotify notify_ready;
54
55   /**
56    * Closure for notify_ready.
57    */
58   void *notify_ready_cls;
59
60   /**
61    * Our connection handle.
62    */
63   struct GNUNET_CONNECTION_Handle *connection;
64
65   /**
66    * Timeout for receiving (in absolute time).
67    */
68   struct GNUNET_TIME_Absolute transmit_timeout;
69
70   /**
71    * Task called on timeout.
72    */
73   GNUNET_SCHEDULER_TaskIdentifier timeout_task;
74
75   /**
76    * At what number of bytes available in the
77    * write buffer should the notify method be called?
78    */
79   size_t notify_size;
80
81 };
82
83
84 /**
85  * During connect, we try multiple possible IP addresses
86  * to find out which one might work.
87  */
88 struct AddressProbe
89 {
90
91   /**
92    * This is a linked list.
93    */
94   struct AddressProbe *next;
95
96   /**
97    * This is a doubly-linked list.
98    */
99   struct AddressProbe *prev;
100
101   /**
102    * The address; do not free (allocated at the end of this struct).
103    */
104   const struct sockaddr *addr;
105
106   /**
107    * Underlying OS's socket.
108    */
109   struct GNUNET_NETWORK_Handle *sock;
110
111   /**
112    * Connection for which we are probing.
113    */
114   struct GNUNET_CONNECTION_Handle *connection;
115
116   /**
117    * Lenth of addr.
118    */
119   socklen_t addrlen;
120
121   /**
122    * Task waiting for the connection to finish connecting.
123    */
124   GNUNET_SCHEDULER_TaskIdentifier task;
125 };
126
127
128 /**
129  * @brief handle for a network connection
130  */
131 struct GNUNET_CONNECTION_Handle
132 {
133
134   /**
135    * Configuration to use.
136    */
137   const struct GNUNET_CONFIGURATION_Handle *cfg;
138
139   /**
140    * Linked list of sockets we are currently trying out
141    * (during connect).
142    */
143   struct AddressProbe *ap_head;
144
145   /**
146    * Linked list of sockets we are currently trying out
147    * (during connect).
148    */
149   struct AddressProbe *ap_tail;
150
151   /**
152    * Network address of the other end-point, may be NULL.
153    */
154   struct sockaddr *addr;
155
156   /**
157    * Pointer to the hostname if connection was
158    * created using DNS lookup, otherwise NULL.
159    */
160   char *hostname;
161
162   /**
163    * Underlying OS's socket, set to NULL after fatal errors.
164    */
165   struct GNUNET_NETWORK_Handle *sock;
166
167   /**
168    * Function to call on data received, NULL if no receive is pending.
169    */
170   GNUNET_CONNECTION_Receiver receiver;
171
172   /**
173    * Closure for receiver.
174    */
175   void *receiver_cls;
176
177   /**
178    * Pointer to our write buffer.
179    */
180   char *write_buffer;
181
182   /**
183    * Current size of our write buffer.
184    */
185   size_t write_buffer_size;
186
187   /**
188    * Current write-offset in write buffer (where
189    * would we write next).
190    */
191   size_t write_buffer_off;
192
193   /**
194    * Current read-offset in write buffer (how many
195    * bytes have already been sent).
196    */
197   size_t write_buffer_pos;
198
199   /**
200    * Length of addr.
201    */
202   socklen_t addrlen;
203
204   /**
205    * Read task that we may need to wait for.
206    */
207   GNUNET_SCHEDULER_TaskIdentifier read_task;
208
209   /**
210    * Write task that we may need to wait for.
211    */
212   GNUNET_SCHEDULER_TaskIdentifier write_task;
213
214   /**
215    * Handle to a pending DNS lookup request.
216    */
217   struct GNUNET_RESOLVER_RequestHandle *dns_active;
218
219   /**
220    * The handle we return for GNUNET_CONNECTION_notify_transmit_ready.
221    */
222   struct GNUNET_CONNECTION_TransmitHandle nth;
223
224   /**
225    * Timeout for receiving (in absolute time).
226    */
227   struct GNUNET_TIME_Absolute receive_timeout;
228
229   /**
230    * Maximum number of bytes to read (for receiving).
231    */
232   size_t max;
233
234   /**
235    * Port to connect to.
236    */
237   uint16_t port;
238
239   /**
240    * When shutdown, do not ever actually close the socket, but
241    * free resources.  Only should ever be set if using program
242    * termination as a signal (because only then will the leaked
243    * socket be freed!)
244    */
245   int8_t persist;
246
247   /**
248    * Usually 0.  Set to 1 if this handle is in used and should
249    * 'GNUNET_CONNECTION_destroy' be called right now, the action needs
250    * to be deferred by setting it to -1.
251    */
252   int8_t destroy_later;
253
254 };
255
256
257 /**
258  * Set the persist option on this connection handle.  Indicates
259  * that the underlying socket or fd should never really be closed.
260  * Used for indicating process death.
261  *
262  * @param connection the connection to set persistent
263  */
264 void
265 GNUNET_CONNECTION_persist_ (struct GNUNET_CONNECTION_Handle *connection)
266 {
267   connection->persist = GNUNET_YES;
268 }
269
270
271 /**
272  * Disable the "CORK" feature for communication with the given connection,
273  * forcing the OS to immediately flush the buffer on transmission
274  * instead of potentially buffering multiple messages.  Essentially
275  * reduces the OS send buffers to zero.
276  * Used to make sure that the last messages sent through the connection
277  * reach the other side before the process is terminated.
278  *
279  * @param connection the connection to make flushing and blocking
280  * @return GNUNET_OK on success
281  */
282 int
283 GNUNET_CONNECTION_disable_corking (struct GNUNET_CONNECTION_Handle *connection)
284 {
285   return GNUNET_NETWORK_socket_disable_corking (connection->sock);
286 }
287
288
289 /**
290  * Create a connection handle by boxing an existing OS socket.  The OS
291  * socket should henceforth be no longer used directly.
292  * GNUNET_connection_destroy will close it.
293  *
294  * @param osSocket existing socket to box
295  * @return the boxed connection handle
296  */
297 struct GNUNET_CONNECTION_Handle *
298 GNUNET_CONNECTION_create_from_existing (struct GNUNET_NETWORK_Handle *osSocket)
299 {
300   struct GNUNET_CONNECTION_Handle *connection;
301
302   connection = GNUNET_new (struct GNUNET_CONNECTION_Handle);
303   connection->write_buffer_size = GNUNET_SERVER_MIN_BUFFER_SIZE;
304   connection->write_buffer = GNUNET_malloc (connection->write_buffer_size);
305   connection->sock = osSocket;
306   return connection;
307 }
308
309
310 /**
311  * Create a connection handle by accepting on a listen socket.  This
312  * function may block if the listen socket has no connection ready.
313  *
314  * @param access function to use to check if access is allowed
315  * @param access_cls closure for access
316  * @param lsock listen socket
317  * @return the connection handle, NULL on error
318  */
319 struct GNUNET_CONNECTION_Handle *
320 GNUNET_CONNECTION_create_from_accept (GNUNET_CONNECTION_AccessCheck access,
321                                       void *access_cls,
322                                       struct GNUNET_NETWORK_Handle *lsock)
323 {
324   struct GNUNET_CONNECTION_Handle *connection;
325   char addr[128];
326   socklen_t addrlen;
327   struct GNUNET_NETWORK_Handle *sock;
328   int aret;
329   struct sockaddr_in *v4;
330   struct sockaddr_in6 *v6;
331   struct sockaddr *sa;
332   void *uaddr;
333   struct GNUNET_CONNECTION_Credentials *gcp;
334   struct GNUNET_CONNECTION_Credentials gc;
335 #ifdef SO_PEERCRED
336   struct ucred uc;
337   socklen_t olen;
338 #endif
339
340   addrlen = sizeof (addr);
341   sock =
342       GNUNET_NETWORK_socket_accept (lsock, (struct sockaddr *) &addr, &addrlen);
343   if (NULL == sock)
344   {
345     LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "accept");
346     return NULL;
347   }
348   if ((addrlen > sizeof (addr)) || (addrlen < sizeof (sa_family_t)))
349   {
350     GNUNET_break (0);
351     GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (sock));
352     return NULL;
353   }
354
355   sa = (struct sockaddr *) addr;
356   v6 = (struct sockaddr_in6 *) addr;
357   if ((AF_INET6 == sa->sa_family) && (IN6_IS_ADDR_V4MAPPED (&v6->sin6_addr)))
358   {
359     /* convert to V4 address */
360     v4 = GNUNET_new (struct sockaddr_in);
361     memset (v4, 0, sizeof (struct sockaddr_in));
362     v4->sin_family = AF_INET;
363 #if HAVE_SOCKADDR_IN_SIN_LEN
364     v4->sin_len = (u_char) sizeof (struct sockaddr_in);
365 #endif
366     memcpy (&v4->sin_addr,
367             &((char *) &v6->sin6_addr)[sizeof (struct in6_addr) -
368                                        sizeof (struct in_addr)],
369             sizeof (struct in_addr));
370     v4->sin_port = v6->sin6_port;
371     uaddr = v4;
372     addrlen = sizeof (struct sockaddr_in);
373   }
374   else
375   {
376     uaddr = GNUNET_malloc (addrlen);
377     memcpy (uaddr, addr, addrlen);
378   }
379   gcp = NULL;
380   gc.uid = 0;
381   gc.gid = 0;
382   if (AF_UNIX == sa->sa_family)
383   {
384 #if HAVE_GETPEEREID
385     /* most BSDs */
386     if (0 == getpeereid (GNUNET_NETWORK_get_fd (sock), &gc.uid, &gc.gid))
387       gcp = &gc;
388 #else
389 #ifdef SO_PEERCRED
390     /* largely traditional GNU/Linux */
391     olen = sizeof (uc);
392     if ((0 ==
393          getsockopt (GNUNET_NETWORK_get_fd (sock), SOL_SOCKET, SO_PEERCRED, &uc,
394                      &olen)) && (olen == sizeof (uc)))
395     {
396       gc.uid = uc.uid;
397       gc.gid = uc.gid;
398       gcp = &gc;
399     }
400 #else
401 #if HAVE_GETPEERUCRED
402     /* this is for Solaris 10 */
403     ucred_t *uc;
404
405     uc = NULL;
406     if (0 == getpeerucred (GNUNET_NETWORK_get_fd (sock), &uc))
407     {
408       gc.uid = ucred_geteuid (uc);
409       gc.gid = ucred_getegid (uc);
410       gcp = &gc;
411     }
412     ucred_free (uc);
413 #endif
414 #endif
415 #endif
416   }
417
418   if ((NULL != access) &&
419       (GNUNET_YES != (aret = access (access_cls, gcp, uaddr, addrlen))))
420   {
421     if (GNUNET_NO == aret)
422       LOG (GNUNET_ERROR_TYPE_INFO, _("Access denied to `%s'\n"),
423            GNUNET_a2s (uaddr, addrlen));
424     GNUNET_break (GNUNET_OK ==
425                   GNUNET_NETWORK_socket_shutdown (sock, SHUT_RDWR));
426     GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (sock));
427     GNUNET_free (uaddr);
428     return NULL;
429   }
430   connection = GNUNET_new (struct GNUNET_CONNECTION_Handle);
431   connection->write_buffer_size = GNUNET_SERVER_MIN_BUFFER_SIZE;
432   connection->write_buffer = GNUNET_malloc (connection->write_buffer_size);
433   connection->addr = uaddr;
434   connection->addrlen = addrlen;
435   connection->sock = sock;
436   LOG (GNUNET_ERROR_TYPE_INFO,
437        _("Accepting connection from `%s': %p\n"),
438        GNUNET_a2s (uaddr, addrlen), connection);
439   return connection;
440 }
441
442
443 /**
444  * Obtain the network address of the other party.
445  *
446  * @param connection the client to get the address for
447  * @param addr where to store the address
448  * @param addrlen where to store the length of the address
449  * @return GNUNET_OK on success
450  */
451 int
452 GNUNET_CONNECTION_get_address (struct GNUNET_CONNECTION_Handle *connection,
453                                void **addr, size_t * addrlen)
454 {
455   if ((NULL == connection->addr) || (0 == connection->addrlen))
456     return GNUNET_NO;
457   *addr = GNUNET_malloc (connection->addrlen);
458   memcpy (*addr, connection->addr, connection->addrlen);
459   *addrlen = connection->addrlen;
460   return GNUNET_OK;
461 }
462
463
464 /**
465  * Tell the receiver callback that we had an IO error.
466  *
467  * @param connection connection to signal error
468  * @param errcode error code to send
469  */
470 static void
471 signal_receive_error (struct GNUNET_CONNECTION_Handle *connection, int errcode)
472 {
473   GNUNET_CONNECTION_Receiver receiver;
474
475   LOG (GNUNET_ERROR_TYPE_DEBUG,
476        "Receive encounters error (%s), connection closed (%p)\n",
477        STRERROR (errcode),
478        connection);
479   GNUNET_assert (NULL != (receiver = connection->receiver));
480   connection->receiver = NULL;
481   receiver (connection->receiver_cls, NULL, 0, connection->addr, connection->addrlen, errcode);
482 }
483
484
485 /**
486  * Tell the receiver callback that a timeout was reached.
487  *
488  * @param connection connection to signal for
489  */
490 static void
491 signal_receive_timeout (struct GNUNET_CONNECTION_Handle *connection)
492 {
493   GNUNET_CONNECTION_Receiver receiver;
494
495   LOG (GNUNET_ERROR_TYPE_DEBUG, "Connection signals timeout to receiver (%p)!\n",
496        connection);
497   GNUNET_assert (NULL != (receiver = connection->receiver));
498   connection->receiver = NULL;
499   receiver (connection->receiver_cls, NULL, 0, NULL, 0, 0);
500 }
501
502
503 /**
504  * We failed to transmit data to the service, signal the error.
505  *
506  * @param connection handle that had trouble
507  * @param ecode error code (errno)
508  */
509 static void
510 signal_transmit_error (struct GNUNET_CONNECTION_Handle *connection,
511                        int ecode)
512 {
513   GNUNET_CONNECTION_TransmitReadyNotify notify;
514
515   LOG (GNUNET_ERROR_TYPE_DEBUG,
516        "Transmission encounterd error (%s), connection closed (%p)\n",
517        STRERROR (ecode),
518        connection);
519   if (NULL != connection->sock)
520   {
521     GNUNET_NETWORK_socket_shutdown (connection->sock, SHUT_RDWR);
522     GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (connection->sock));
523     connection->sock = NULL;
524     GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == connection->write_task);
525   }
526   if (GNUNET_SCHEDULER_NO_TASK != connection->read_task)
527   {
528     /* send errors trigger read errors... */
529     GNUNET_SCHEDULER_cancel (connection->read_task);
530     connection->read_task = GNUNET_SCHEDULER_NO_TASK;
531     signal_receive_timeout (connection);
532     return;
533   }
534   if (NULL == connection->nth.notify_ready)
535     return;                     /* nobody to tell about it */
536   notify = connection->nth.notify_ready;
537   connection->nth.notify_ready = NULL;
538   notify (connection->nth.notify_ready_cls, 0, NULL);
539 }
540
541
542 /**
543  * We've failed for good to establish a connection (timeout or
544  * no more addresses to try).
545  *
546  * @param connection the connection we tried to establish
547  */
548 static void
549 connect_fail_continuation (struct GNUNET_CONNECTION_Handle *connection)
550 {
551   LOG (GNUNET_ERROR_TYPE_INFO,
552        _("Failed to establish TCP connection to `%s:%u', no further addresses to try.\n"),
553        connection->hostname, connection->port);
554   GNUNET_break (NULL == connection->ap_head);
555   GNUNET_break (NULL == connection->ap_tail);
556   GNUNET_break (GNUNET_NO == connection->dns_active);
557   GNUNET_break (NULL == connection->sock);
558   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == connection->write_task);
559
560   /* signal errors for jobs that used to wait on the connection */
561   connection->destroy_later = 1;
562   if (NULL != connection->receiver)
563     signal_receive_error (connection, ECONNREFUSED);
564   if (NULL != connection->nth.notify_ready)
565   {
566     GNUNET_assert (connection->nth.timeout_task != GNUNET_SCHEDULER_NO_TASK);
567     GNUNET_SCHEDULER_cancel (connection->nth.timeout_task);
568     connection->nth.timeout_task = GNUNET_SCHEDULER_NO_TASK;
569     signal_transmit_error (connection, ECONNREFUSED);
570   }
571   if (-1 == connection->destroy_later)
572   {
573     /* do it now */
574     connection->destroy_later = 0;
575     GNUNET_CONNECTION_destroy (connection);
576     return;
577   }
578   connection->destroy_later = 0;
579 }
580
581
582 /**
583  * We are ready to transmit (or got a timeout).
584  *
585  * @param cls our connection handle
586  * @param tc task context describing why we are here
587  */
588 static void
589 transmit_ready (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
590
591
592 /**
593  * This function is called once we either timeout or have data ready
594  * to read.
595  *
596  * @param cls connection to read from
597  * @param tc scheduler context
598  */
599 static void
600 receive_ready (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
601
602
603 /**
604  * We've succeeded in establishing a connection.
605  *
606  * @param connection the connection we tried to establish
607  */
608 static void
609 connect_success_continuation (struct GNUNET_CONNECTION_Handle *connection)
610 {
611   LOG (GNUNET_ERROR_TYPE_DEBUG,
612        "Connection to `%s' succeeded! (%p)\n",
613        GNUNET_a2s (connection->addr, connection->addrlen), connection);
614   /* trigger jobs that waited for the connection */
615   if (NULL != connection->receiver)
616   {
617     LOG (GNUNET_ERROR_TYPE_DEBUG,
618          "Connection succeeded, starting with receiving data (%p)\n",
619          connection);
620     GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == connection->read_task);
621     connection->read_task =
622       GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_absolute_get_remaining
623                                      (connection->receive_timeout), connection->sock,
624                                      &receive_ready, connection);
625   }
626   if (NULL != connection->nth.notify_ready)
627   {
628     LOG (GNUNET_ERROR_TYPE_DEBUG,
629          "Connection succeeded, starting with sending data (%p)\n",
630          connection);
631     GNUNET_assert (connection->nth.timeout_task != GNUNET_SCHEDULER_NO_TASK);
632     GNUNET_SCHEDULER_cancel (connection->nth.timeout_task);
633     connection->nth.timeout_task = GNUNET_SCHEDULER_NO_TASK;
634     GNUNET_assert (connection->write_task == GNUNET_SCHEDULER_NO_TASK);
635     connection->write_task =
636         GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_absolute_get_remaining
637                                         (connection->nth.transmit_timeout), connection->sock,
638                                         &transmit_ready, connection);
639   }
640 }
641
642
643 /**
644  * Scheduler let us know that we're either ready to write on the
645  * socket OR connect timed out.  Do the right thing.
646  *
647  * @param cls the "struct AddressProbe*" with the address that we are probing
648  * @param tc success or failure info about the connect attempt.
649  */
650 static void
651 connect_probe_continuation (void *cls,
652                             const struct GNUNET_SCHEDULER_TaskContext *tc)
653 {
654   struct AddressProbe *ap = cls;
655   struct GNUNET_CONNECTION_Handle *connection = ap->connection;
656   struct AddressProbe *pos;
657   int error;
658   socklen_t len;
659
660   GNUNET_assert (NULL != ap->sock);
661   GNUNET_CONTAINER_DLL_remove (connection->ap_head, connection->ap_tail, ap);
662   len = sizeof (error);
663   errno = 0;
664   error = 0;
665   if ((0 == (tc->reason & GNUNET_SCHEDULER_REASON_WRITE_READY)) ||
666       (GNUNET_OK !=
667        GNUNET_NETWORK_socket_getsockopt (ap->sock, SOL_SOCKET, SO_ERROR, &error,
668                                          &len)) || (0 != error))
669   {
670     GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (ap->sock));
671     GNUNET_free (ap);
672     if ((NULL == connection->ap_head) && (GNUNET_NO == connection->dns_active))
673       connect_fail_continuation (connection);
674     return;
675   }
676   GNUNET_assert (NULL == connection->sock);
677   connection->sock = ap->sock;
678   GNUNET_assert (NULL == connection->addr);
679   connection->addr = GNUNET_malloc (ap->addrlen);
680   memcpy (connection->addr, ap->addr, ap->addrlen);
681   connection->addrlen = ap->addrlen;
682   GNUNET_free (ap);
683   /* cancel all other attempts */
684   while (NULL != (pos = connection->ap_head))
685   {
686     GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (pos->sock));
687     GNUNET_SCHEDULER_cancel (pos->task);
688     GNUNET_CONTAINER_DLL_remove (connection->ap_head, connection->ap_tail, pos);
689     GNUNET_free (pos);
690   }
691   connect_success_continuation (connection);
692 }
693
694
695 /**
696  * Try to establish a connection given the specified address.
697  * This function is called by the resolver once we have a DNS reply.
698  *
699  * @param cls our "struct GNUNET_CONNECTION_Handle *"
700  * @param addr address to try, NULL for "last call"
701  * @param addrlen length of addr
702  */
703 static void
704 try_connect_using_address (void *cls, const struct sockaddr *addr,
705                            socklen_t addrlen)
706 {
707   struct GNUNET_CONNECTION_Handle *connection = cls;
708   struct AddressProbe *ap;
709   struct GNUNET_TIME_Relative delay;
710
711   if (NULL == addr)
712   {
713     connection->dns_active = NULL;
714     if ((NULL == connection->ap_head) && (NULL == connection->sock))
715       connect_fail_continuation (connection);
716     return;
717   }
718   if (NULL != connection->sock)
719     return;                     /* already connected */
720   GNUNET_assert (NULL == connection->addr);
721   /* try to connect */
722   LOG (GNUNET_ERROR_TYPE_DEBUG,
723        "Trying to connect using address `%s:%u/%s:%u'\n", connection->hostname, connection->port,
724        GNUNET_a2s (addr, addrlen), connection->port);
725   ap = GNUNET_malloc (sizeof (struct AddressProbe) + addrlen);
726   ap->addr = (const struct sockaddr *) &ap[1];
727   memcpy (&ap[1], addr, addrlen);
728   ap->addrlen = addrlen;
729   ap->connection = connection;
730
731   switch (ap->addr->sa_family)
732   {
733   case AF_INET:
734     ((struct sockaddr_in *) ap->addr)->sin_port = htons (connection->port);
735     break;
736   case AF_INET6:
737     ((struct sockaddr_in6 *) ap->addr)->sin6_port = htons (connection->port);
738     break;
739   default:
740     GNUNET_break (0);
741     GNUNET_free (ap);
742     return;                     /* not supported by us */
743   }
744   ap->sock = GNUNET_NETWORK_socket_create (ap->addr->sa_family, SOCK_STREAM, 0);
745   if (NULL == ap->sock)
746   {
747     GNUNET_free (ap);
748     return;                     /* not supported by OS */
749   }
750   LOG (GNUNET_ERROR_TYPE_INFO, _("Trying to connect to `%s' (%p)\n"),
751        GNUNET_a2s (ap->addr, ap->addrlen), connection);
752   if ((GNUNET_OK !=
753        GNUNET_NETWORK_socket_connect (ap->sock, ap->addr, ap->addrlen)) &&
754       (EINPROGRESS != errno))
755   {
756     /* maybe refused / unsupported address, try next */
757     LOG_STRERROR (GNUNET_ERROR_TYPE_INFO, "connect");
758     GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (ap->sock));
759     GNUNET_free (ap);
760     return;
761   }
762   GNUNET_CONTAINER_DLL_insert (connection->ap_head, connection->ap_tail, ap);
763   delay = GNUNET_CONNECTION_CONNECT_RETRY_TIMEOUT;
764   if (NULL != connection->nth.notify_ready)
765     delay =
766         GNUNET_TIME_relative_min (delay,
767                                   GNUNET_TIME_absolute_get_remaining (connection->
768                                                                       nth.transmit_timeout));
769   if (NULL != connection->receiver)
770     delay =
771         GNUNET_TIME_relative_min (delay,
772                                   GNUNET_TIME_absolute_get_remaining
773                                   (connection->receive_timeout));
774   ap->task =
775       GNUNET_SCHEDULER_add_write_net (delay, ap->sock,
776                                       &connect_probe_continuation, ap);
777 }
778
779
780 /**
781  * Create a connection handle by (asynchronously) connecting to a host.
782  * This function returns immediately, even if the connection has not
783  * yet been established.  This function only creates TCP connections.
784  *
785  * @param cfg configuration to use
786  * @param hostname name of the host to connect to
787  * @param port port to connect to
788  * @return the connection handle
789  */
790 struct GNUNET_CONNECTION_Handle *
791 GNUNET_CONNECTION_create_from_connect (const struct GNUNET_CONFIGURATION_Handle
792                                        *cfg, const char *hostname,
793                                        uint16_t port)
794 {
795   struct GNUNET_CONNECTION_Handle *connection;
796
797   GNUNET_assert (0 < strlen (hostname));        /* sanity check */
798   connection = GNUNET_new (struct GNUNET_CONNECTION_Handle);
799   connection->cfg = cfg;
800   connection->write_buffer_size = GNUNET_SERVER_MIN_BUFFER_SIZE;
801   connection->write_buffer = GNUNET_malloc (connection->write_buffer_size);
802   connection->port = port;
803   connection->hostname = GNUNET_strdup (hostname);
804   connection->dns_active =
805       GNUNET_RESOLVER_ip_get (connection->hostname, AF_UNSPEC,
806                               GNUNET_CONNECTION_CONNECT_RETRY_TIMEOUT,
807                               &try_connect_using_address, connection);
808   return connection;
809 }
810
811
812 /**
813  * Create a connection handle by connecting to a UNIX domain service.
814  * This function returns immediately, even if the connection has not
815  * yet been established.  This function only creates UNIX connections.
816  *
817  * @param cfg configuration to use
818  * @param unixpath path to connect to
819  * @return the connection handle, NULL on systems without UNIX support
820  */
821 struct GNUNET_CONNECTION_Handle *
822 GNUNET_CONNECTION_create_from_connect_to_unixpath (const struct
823                                                    GNUNET_CONFIGURATION_Handle
824                                                    *cfg, const char *unixpath)
825 {
826 #ifdef AF_UNIX
827   struct GNUNET_CONNECTION_Handle *connection;
828   struct sockaddr_un *un;
829   size_t slen;
830
831   GNUNET_assert (0 < strlen (unixpath));        /* sanity check */
832   un = GNUNET_new (struct sockaddr_un);
833   un->sun_family = AF_UNIX;
834   slen = strlen (unixpath);
835   if (slen >= sizeof (un->sun_path))
836     slen = sizeof (un->sun_path) - 1;
837   memcpy (un->sun_path, unixpath, slen);
838   un->sun_path[slen] = '\0';
839   slen = sizeof (struct sockaddr_un);
840 #if HAVE_SOCKADDR_IN_SIN_LEN
841   un->sun_len = (u_char) slen;
842 #endif
843 #if LINUX
844   un->sun_path[0] = '\0';
845 #endif
846   connection = GNUNET_new (struct GNUNET_CONNECTION_Handle);
847   connection->cfg = cfg;
848   connection->write_buffer_size = GNUNET_SERVER_MIN_BUFFER_SIZE;
849   connection->write_buffer = GNUNET_malloc (connection->write_buffer_size);
850   connection->port = 0;
851   connection->hostname = NULL;
852   connection->addr = (struct sockaddr *) un;
853   connection->addrlen = slen;
854   connection->sock = GNUNET_NETWORK_socket_create (AF_UNIX, SOCK_STREAM, 0);
855   if (NULL == connection->sock)
856   {
857     GNUNET_free (connection->addr);
858     GNUNET_free (connection->write_buffer);
859     GNUNET_free (connection);
860     return NULL;
861   }
862   if ( (GNUNET_OK !=
863         GNUNET_NETWORK_socket_connect (connection->sock, connection->addr, connection->addrlen)) &&
864        (EINPROGRESS != errno) )
865   {
866     /* Just return; we expect everything to work eventually so don't fail HARD */
867     GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (connection->sock));
868     connection->sock = NULL;
869     return connection;
870   }
871   connect_success_continuation (connection);
872   return connection;
873 #else
874   return NULL;
875 #endif
876 }
877
878
879 /**
880  * Create a connection handle by (asynchronously) connecting to a host.
881  * This function returns immediately, even if the connection has not
882  * yet been established.  This function only creates TCP connections.
883  *
884  * @param af_family address family to use
885  * @param serv_addr server address
886  * @param addrlen length of server address
887  * @return the connection handle
888  */
889 struct GNUNET_CONNECTION_Handle *
890 GNUNET_CONNECTION_create_from_sockaddr (int af_family,
891                                         const struct sockaddr *serv_addr,
892                                         socklen_t addrlen)
893 {
894   struct GNUNET_NETWORK_Handle *s;
895   struct GNUNET_CONNECTION_Handle *connection;
896
897   s = GNUNET_NETWORK_socket_create (af_family, SOCK_STREAM, 0);
898   if (NULL == s)
899   {
900     LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK, "socket");
901     return NULL;
902   }
903   if ((GNUNET_OK != GNUNET_NETWORK_socket_connect (s, serv_addr, addrlen)) &&
904       (EINPROGRESS != errno))
905   {
906     /* maybe refused / unsupported address, try next */
907     LOG_STRERROR (GNUNET_ERROR_TYPE_INFO, "connect");
908     LOG (GNUNET_ERROR_TYPE_INFO, _("Attempt to connect to `%s' failed\n"),
909          GNUNET_a2s (serv_addr, addrlen));
910     GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (s));
911     return NULL;
912   }
913   connection = GNUNET_CONNECTION_create_from_existing (s);
914   connection->addr = GNUNET_malloc (addrlen);
915   memcpy (connection->addr, serv_addr, addrlen);
916   connection->addrlen = addrlen;
917   LOG (GNUNET_ERROR_TYPE_INFO, _("Trying to connect to `%s' (%p)\n"),
918        GNUNET_a2s (serv_addr, addrlen), connection);
919   return connection;
920 }
921
922
923 /**
924  * Check if connection is valid (no fatal errors have happened so far).
925  * Note that a connection that is still trying to connect is considered
926  * valid.
927  *
928  * @param connection connection to check
929  * @return GNUNET_YES if valid, GNUNET_NO otherwise
930  */
931 int
932 GNUNET_CONNECTION_check (struct GNUNET_CONNECTION_Handle *connection)
933 {
934   if ((NULL != connection->ap_head) || (NULL != connection->dns_active))
935     return GNUNET_YES;          /* still trying to connect */
936   return (NULL == connection->sock) ? GNUNET_NO : GNUNET_YES;
937 }
938
939
940 /**
941  * Close the connection and free associated resources.  There must
942  * not be any pending requests for reading or writing to the
943  * connection at this time.
944  *
945  * @param connection connection to destroy
946  */
947 void
948 GNUNET_CONNECTION_destroy (struct GNUNET_CONNECTION_Handle *connection)
949 {
950   struct AddressProbe *pos;
951
952   if (0 != connection->destroy_later)
953   {
954     connection->destroy_later = -1;
955     return;
956   }
957   LOG (GNUNET_ERROR_TYPE_DEBUG, "Shutting down connection (%p)\n", connection);
958   GNUNET_assert (NULL == connection->nth.notify_ready);
959   GNUNET_assert (NULL == connection->receiver);
960   if (GNUNET_SCHEDULER_NO_TASK != connection->write_task)
961   {
962     GNUNET_SCHEDULER_cancel (connection->write_task);
963     connection->write_task = GNUNET_SCHEDULER_NO_TASK;
964     connection->write_buffer_off = 0;
965   }
966   if (GNUNET_SCHEDULER_NO_TASK != connection->read_task)
967   {
968     GNUNET_SCHEDULER_cancel (connection->read_task);
969     connection->read_task = GNUNET_SCHEDULER_NO_TASK;
970   }
971   if (GNUNET_SCHEDULER_NO_TASK != connection->nth.timeout_task)
972   {
973     GNUNET_SCHEDULER_cancel (connection->nth.timeout_task);
974     connection->nth.timeout_task = GNUNET_SCHEDULER_NO_TASK;
975   }
976   connection->nth.notify_ready = NULL;
977   if (NULL != connection->dns_active)
978   {
979     GNUNET_RESOLVER_request_cancel (connection->dns_active);
980     connection->dns_active = NULL;
981   }
982   while (NULL != (pos = connection->ap_head))
983   {
984     GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (pos->sock));
985     GNUNET_SCHEDULER_cancel (pos->task);
986     GNUNET_CONTAINER_DLL_remove (connection->ap_head, connection->ap_tail, pos);
987     GNUNET_free (pos);
988   }
989   if ( (NULL != connection->sock) &&
990        (GNUNET_YES != connection->persist) )
991   {
992     if ((GNUNET_YES != GNUNET_NETWORK_socket_shutdown (connection->sock, SHUT_RDWR)) &&
993         (ENOTCONN != errno) &&
994         (ECONNRESET != errno) )
995       LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "shutdown");
996   }
997   if (NULL != connection->sock)
998   {
999     if (GNUNET_YES != connection->persist)
1000       GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (connection->sock));
1001     else
1002     {
1003       GNUNET_NETWORK_socket_free_memory_only_ (connection->sock); /* at least no memory leak (we deliberately
1004                                                                    * leak the socket in this special case) ... */
1005     }
1006   }
1007   GNUNET_free_non_null (connection->addr);
1008   GNUNET_free_non_null (connection->hostname);
1009   GNUNET_free (connection->write_buffer);
1010   GNUNET_free (connection);
1011 }
1012
1013
1014 /**
1015  * This function is called once we either timeout
1016  * or have data ready to read.
1017  *
1018  * @param cls connection to read from
1019  * @param tc scheduler context
1020  */
1021 static void
1022 receive_ready (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1023 {
1024   struct GNUNET_CONNECTION_Handle *connection = cls;
1025   char buffer[connection->max];
1026   ssize_t ret;
1027   GNUNET_CONNECTION_Receiver receiver;
1028
1029   connection->read_task = GNUNET_SCHEDULER_NO_TASK;
1030   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1031   {
1032     /* ignore shutdown request, go again immediately */
1033     connection->read_task =
1034         GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_absolute_get_remaining
1035                                        (connection->receive_timeout), connection->sock,
1036                                        &receive_ready, connection);
1037     return;
1038   }
1039   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_TIMEOUT))
1040   {
1041     LOG (GNUNET_ERROR_TYPE_DEBUG,
1042          "Receive from `%s' encounters error: timeout (%s, %p)\n",
1043          GNUNET_a2s (connection->addr, connection->addrlen),
1044          GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_duration (connection->receive_timeout), GNUNET_YES),
1045          connection);
1046     signal_receive_timeout (connection);
1047     return;
1048   }
1049   if (NULL == connection->sock)
1050   {
1051     /* connect failed for good */
1052     signal_receive_error (connection, ECONNREFUSED);
1053     return;
1054   }
1055   GNUNET_assert (GNUNET_NETWORK_fdset_isset (tc->read_ready, connection->sock));
1056 RETRY:
1057   ret = GNUNET_NETWORK_socket_recv (connection->sock, buffer, connection->max);
1058   if (-1 == ret)
1059   {
1060     if (EINTR == errno)
1061       goto RETRY;
1062     signal_receive_error (connection, errno);
1063     return;
1064   }
1065   LOG (GNUNET_ERROR_TYPE_DEBUG,
1066        "receive_ready read %u/%u bytes from `%s' (%p)!\n", (unsigned int) ret,
1067        connection->max, GNUNET_a2s (connection->addr, connection->addrlen), connection);
1068   GNUNET_assert (NULL != (receiver = connection->receiver));
1069   connection->receiver = NULL;
1070   receiver (connection->receiver_cls, buffer, ret, connection->addr, connection->addrlen, 0);
1071 }
1072
1073
1074 /**
1075  * Receive data from the given connection.  Note that this function will
1076  * call "receiver" asynchronously using the scheduler.  It will
1077  * "immediately" return.  Note that there MUST only be one active
1078  * receive call per connection at any given point in time (so do not
1079  * call receive again until the receiver callback has been invoked).
1080  *
1081  * @param connection connection handle
1082  * @param max maximum number of bytes to read
1083  * @param timeout maximum amount of time to wait
1084  * @param receiver function to call with received data
1085  * @param receiver_cls closure for receiver
1086  */
1087 void
1088 GNUNET_CONNECTION_receive (struct GNUNET_CONNECTION_Handle *connection, size_t max,
1089                            struct GNUNET_TIME_Relative timeout,
1090                            GNUNET_CONNECTION_Receiver receiver,
1091                            void *receiver_cls)
1092 {
1093   GNUNET_assert ((GNUNET_SCHEDULER_NO_TASK == connection->read_task) &&
1094                  (NULL == connection->receiver));
1095   GNUNET_assert (NULL != receiver);
1096   connection->receiver = receiver;
1097   connection->receiver_cls = receiver_cls;
1098   connection->receive_timeout = GNUNET_TIME_relative_to_absolute (timeout);
1099   connection->max = max;
1100   if (NULL != connection->sock)
1101   {
1102     connection->read_task =
1103       GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_absolute_get_remaining
1104                                      (connection->receive_timeout), connection->sock,
1105                                      &receive_ready, connection);
1106     return;
1107   }
1108   if ((NULL == connection->dns_active) && (NULL == connection->ap_head))
1109   {
1110     connection->receiver = NULL;
1111     receiver (receiver_cls, NULL, 0, NULL, 0, ETIMEDOUT);
1112     return;
1113   }
1114 }
1115
1116
1117 /**
1118  * Cancel receive job on the given connection.  Note that the
1119  * receiver callback must not have been called yet in order
1120  * for the cancellation to be valid.
1121  *
1122  * @param connection connection handle
1123  * @return closure of the original receiver callback closure
1124  */
1125 void *
1126 GNUNET_CONNECTION_receive_cancel (struct GNUNET_CONNECTION_Handle *connection)
1127 {
1128   if (GNUNET_SCHEDULER_NO_TASK != connection->read_task)
1129   {
1130     GNUNET_assert (connection == GNUNET_SCHEDULER_cancel (connection->read_task));
1131     connection->read_task = GNUNET_SCHEDULER_NO_TASK;
1132   }
1133   connection->receiver = NULL;
1134   return connection->receiver_cls;
1135 }
1136
1137
1138 /**
1139  * Try to call the transmit notify method (check if we do
1140  * have enough space available first)!
1141  *
1142  * @param connection connection for which we should do this processing
1143  * @return GNUNET_YES if we were able to call notify
1144  */
1145 static int
1146 process_notify (struct GNUNET_CONNECTION_Handle *connection)
1147 {
1148   size_t used;
1149   size_t avail;
1150   size_t size;
1151   GNUNET_CONNECTION_TransmitReadyNotify notify;
1152
1153   LOG (GNUNET_ERROR_TYPE_DEBUG, "process_notify is running\n");
1154
1155   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == connection->write_task);
1156   if (NULL == (notify = connection->nth.notify_ready))
1157   {
1158     LOG (GNUNET_ERROR_TYPE_DEBUG, "Noone to notify\n");
1159     return GNUNET_NO;
1160   }
1161   used = connection->write_buffer_off - connection->write_buffer_pos;
1162   avail = connection->write_buffer_size - used;
1163   size = connection->nth.notify_size;
1164   if (size > avail)
1165   {
1166     LOG (GNUNET_ERROR_TYPE_DEBUG, "Not enough buffer\n");
1167     return GNUNET_NO;
1168   }
1169   connection->nth.notify_ready = NULL;
1170   if (connection->write_buffer_size - connection->write_buffer_off < size)
1171   {
1172     /* need to compact */
1173     memmove (connection->write_buffer, &connection->write_buffer[connection->write_buffer_pos],
1174              used);
1175     connection->write_buffer_off -= connection->write_buffer_pos;
1176     connection->write_buffer_pos = 0;
1177   }
1178   avail = connection->write_buffer_size - connection->write_buffer_off;
1179   GNUNET_assert (avail >= size);
1180   size =
1181       notify (connection->nth.notify_ready_cls, avail,
1182               &connection->write_buffer[connection->write_buffer_off]);
1183   GNUNET_assert (size <= avail);
1184   if (0 != size)
1185     connection->write_buffer_off += size;
1186   return GNUNET_YES;
1187 }
1188
1189
1190 /**
1191  * Task invoked by the scheduler when a call to transmit
1192  * is timing out (we never got enough buffer space to call
1193  * the callback function before the specified timeout
1194  * expired).
1195  *
1196  * This task notifies the client about the timeout.
1197  *
1198  * @param cls the 'struct GNUNET_CONNECTION_Handle'
1199  * @param tc scheduler context
1200  */
1201 static void
1202 transmit_timeout (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1203 {
1204   struct GNUNET_CONNECTION_Handle *connection = cls;
1205   GNUNET_CONNECTION_TransmitReadyNotify notify;
1206
1207   connection->nth.timeout_task = GNUNET_SCHEDULER_NO_TASK;
1208   LOG (GNUNET_ERROR_TYPE_DEBUG,
1209        "Transmit to `%s:%u/%s' fails, time out reached (%p).\n",
1210        connection->hostname,
1211        connection->port, GNUNET_a2s (connection->addr, connection->addrlen), connection);
1212   notify = connection->nth.notify_ready;
1213   GNUNET_assert (NULL != notify);
1214   connection->nth.notify_ready = NULL;
1215   notify (connection->nth.notify_ready_cls, 0, NULL);
1216 }
1217
1218
1219 /**
1220  * Task invoked by the scheduler when we failed to connect
1221  * at the time of being asked to transmit.
1222  *
1223  * This task notifies the client about the error.
1224  *
1225  * @param cls the 'struct GNUNET_CONNECTION_Handle'
1226  * @param tc scheduler context
1227  */
1228 static void
1229 connect_error (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1230 {
1231   struct GNUNET_CONNECTION_Handle *connection = cls;
1232   GNUNET_CONNECTION_TransmitReadyNotify notify;
1233
1234   LOG (GNUNET_ERROR_TYPE_DEBUG,
1235        "Transmission request of size %u fails (%s/%u), connection failed (%p).\n",
1236        connection->nth.notify_size, connection->hostname, connection->port, connection);
1237   connection->write_task = GNUNET_SCHEDULER_NO_TASK;
1238   notify = connection->nth.notify_ready;
1239   connection->nth.notify_ready = NULL;
1240   notify (connection->nth.notify_ready_cls, 0, NULL);
1241 }
1242
1243
1244 /**
1245  * We are ready to transmit (or got a timeout).
1246  *
1247  * @param cls our connection handle
1248  * @param tc task context describing why we are here
1249  */
1250 static void
1251 transmit_ready (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1252 {
1253   struct GNUNET_CONNECTION_Handle *connection = cls;
1254   GNUNET_CONNECTION_TransmitReadyNotify notify;
1255   ssize_t ret;
1256   size_t have;
1257
1258   LOG (GNUNET_ERROR_TYPE_DEBUG, "transmit_ready running (%p).\n", connection);
1259   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK != connection->write_task);
1260   connection->write_task = GNUNET_SCHEDULER_NO_TASK;
1261   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == connection->nth.timeout_task);
1262   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1263   {
1264     if (NULL != connection->sock)
1265       goto SCHEDULE_WRITE;      /* ignore shutdown, go again immediately */
1266     LOG (GNUNET_ERROR_TYPE_DEBUG,
1267          "Transmit to `%s' fails, shutdown happened (%p).\n",
1268          GNUNET_a2s (connection->addr, connection->addrlen), connection);
1269     notify = connection->nth.notify_ready;
1270     if (NULL != notify)
1271     {
1272       connection->nth.notify_ready = NULL;
1273       notify (connection->nth.notify_ready_cls, 0, NULL);
1274     }
1275     return;
1276   }
1277   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_TIMEOUT))
1278   {
1279     LOG (GNUNET_ERROR_TYPE_DEBUG,
1280          "Transmit to `%s' fails, time out reached (%p).\n",
1281          GNUNET_a2s (connection->addr, connection->addrlen), connection);
1282     notify = connection->nth.notify_ready;
1283     GNUNET_assert (NULL != notify);
1284     connection->nth.notify_ready = NULL;
1285     notify (connection->nth.notify_ready_cls, 0, NULL);
1286     return;
1287   }
1288   GNUNET_assert (NULL != connection->sock);
1289   if (NULL == tc->write_ready)
1290   {
1291     /* special circumstances (in particular, PREREQ_DONE after
1292      * connect): not yet ready to write, but no "fatal" error either.
1293      * Hence retry.  */
1294     goto SCHEDULE_WRITE;
1295   }
1296   if (!GNUNET_NETWORK_fdset_isset (tc->write_ready, connection->sock))
1297   {
1298     GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == connection->write_task);
1299     /* special circumstances (in particular, shutdown): not yet ready
1300      * to write, but no "fatal" error either.  Hence retry.  */
1301     goto SCHEDULE_WRITE;
1302   }
1303   GNUNET_assert (connection->write_buffer_off >= connection->write_buffer_pos);
1304   if ((NULL != connection->nth.notify_ready) &&
1305       (connection->write_buffer_size < connection->nth.notify_size))
1306   {
1307     connection->write_buffer =
1308         GNUNET_realloc (connection->write_buffer, connection->nth.notify_size);
1309     connection->write_buffer_size = connection->nth.notify_size;
1310   }
1311   process_notify (connection);
1312   have = connection->write_buffer_off - connection->write_buffer_pos;
1313   if (0 == have)
1314   {
1315     /* no data ready for writing, terminate write loop */
1316     return;
1317   }
1318   GNUNET_assert (have <= connection->write_buffer_size);
1319   GNUNET_assert (have + connection->write_buffer_pos <= connection->write_buffer_size);
1320   GNUNET_assert (connection->write_buffer_pos <= connection->write_buffer_size);
1321 RETRY:
1322   ret =
1323       GNUNET_NETWORK_socket_send (connection->sock,
1324                                   &connection->write_buffer[connection->write_buffer_pos],
1325                                   have);
1326   if (-1 == ret)
1327   {
1328     if (EINTR == errno)
1329       goto RETRY;
1330     if (GNUNET_SCHEDULER_NO_TASK != connection->write_task)
1331     {
1332       GNUNET_SCHEDULER_cancel (connection->write_task);
1333       connection->write_task = GNUNET_SCHEDULER_NO_TASK;
1334     }
1335     signal_transmit_error (connection, errno);
1336     return;
1337   }
1338   LOG (GNUNET_ERROR_TYPE_DEBUG,
1339        "Connection transmitted %u/%u bytes to `%s' (%p)\n",
1340        (unsigned int) ret, have, GNUNET_a2s (connection->addr, connection->addrlen), connection);
1341   connection->write_buffer_pos += ret;
1342   if (connection->write_buffer_pos == connection->write_buffer_off)
1343   {
1344     /* transmitted all pending data */
1345     connection->write_buffer_pos = 0;
1346     connection->write_buffer_off = 0;
1347   }
1348   if ((0 == connection->write_buffer_off) && (NULL == connection->nth.notify_ready))
1349     return;                     /* all data sent! */
1350   /* not done writing, schedule more */
1351 SCHEDULE_WRITE:
1352   LOG (GNUNET_ERROR_TYPE_DEBUG,
1353        "Re-scheduling transmit_ready (more to do) (%p).\n", connection);
1354   have = connection->write_buffer_off - connection->write_buffer_pos;
1355   GNUNET_assert ((NULL != connection->nth.notify_ready) || (have > 0));
1356   if (GNUNET_SCHEDULER_NO_TASK == connection->write_task)
1357     connection->write_task =
1358         GNUNET_SCHEDULER_add_write_net ((connection->nth.notify_ready ==
1359                                          NULL) ? GNUNET_TIME_UNIT_FOREVER_REL :
1360                                         GNUNET_TIME_absolute_get_remaining
1361                                         (connection->nth.transmit_timeout),
1362                                         connection->sock, &transmit_ready, connection);
1363 }
1364
1365
1366 /**
1367  * Ask the connection to call us once the specified number of bytes
1368  * are free in the transmission buffer.  May call the notify
1369  * method immediately if enough space is available.
1370  *
1371  * @param connection connection
1372  * @param size number of bytes to send
1373  * @param timeout after how long should we give up (and call
1374  *        notify with buf NULL and size 0)?
1375  * @param notify function to call
1376  * @param notify_cls closure for notify
1377  * @return non-NULL if the notify callback was queued,
1378  *         NULL if we are already going to notify someone else (busy)
1379  */
1380 struct GNUNET_CONNECTION_TransmitHandle *
1381 GNUNET_CONNECTION_notify_transmit_ready (struct GNUNET_CONNECTION_Handle *connection,
1382                                          size_t size,
1383                                          struct GNUNET_TIME_Relative timeout,
1384                                          GNUNET_CONNECTION_TransmitReadyNotify
1385                                          notify, void *notify_cls)
1386 {
1387   if (NULL != connection->nth.notify_ready)
1388   {
1389     GNUNET_assert (0);
1390     return NULL;
1391   }
1392   GNUNET_assert (NULL != notify);
1393   GNUNET_assert (size < GNUNET_SERVER_MAX_MESSAGE_SIZE);
1394   GNUNET_assert (connection->write_buffer_off <= connection->write_buffer_size);
1395   GNUNET_assert (connection->write_buffer_pos <= connection->write_buffer_size);
1396   GNUNET_assert (connection->write_buffer_pos <= connection->write_buffer_off);
1397   connection->nth.notify_ready = notify;
1398   connection->nth.notify_ready_cls = notify_cls;
1399   connection->nth.connection = connection;
1400   connection->nth.notify_size = size;
1401   connection->nth.transmit_timeout = GNUNET_TIME_relative_to_absolute (timeout);
1402   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == connection->nth.timeout_task);
1403   if ((NULL == connection->sock) &&
1404       (NULL == connection->ap_head) &&
1405       (NULL == connection->dns_active))
1406   {
1407     if (GNUNET_SCHEDULER_NO_TASK != connection->write_task)
1408       GNUNET_SCHEDULER_cancel (connection->write_task);
1409     connection->write_task = GNUNET_SCHEDULER_add_now (&connect_error, connection);
1410     return &connection->nth;
1411   }
1412   if (GNUNET_SCHEDULER_NO_TASK != connection->write_task)
1413     return &connection->nth; /* previous transmission still in progress */
1414   if (NULL != connection->sock)
1415   {
1416     /* connected, try to transmit now */
1417     LOG (GNUNET_ERROR_TYPE_DEBUG, "Scheduling transmission (%p).\n", connection);
1418     connection->write_task =
1419         GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_absolute_get_remaining
1420                                         (connection->nth.transmit_timeout),
1421                                         connection->sock, &transmit_ready, connection);
1422     return &connection->nth;
1423   }
1424   /* not yet connected, wait for connection */
1425   LOG (GNUNET_ERROR_TYPE_DEBUG,
1426        "Need to wait to schedule transmission for connection, adding timeout task (%p).\n", connection);
1427   connection->nth.timeout_task =
1428     GNUNET_SCHEDULER_add_delayed (timeout, &transmit_timeout, connection);
1429   return &connection->nth;
1430 }
1431
1432
1433 /**
1434  * Cancel the specified transmission-ready notification.
1435  *
1436  * @param th notification to cancel
1437  */
1438 void
1439 GNUNET_CONNECTION_notify_transmit_ready_cancel (struct
1440                                                 GNUNET_CONNECTION_TransmitHandle
1441                                                 *th)
1442 {
1443   GNUNET_assert (NULL != th->notify_ready);
1444   th->notify_ready = NULL;
1445   if (GNUNET_SCHEDULER_NO_TASK != th->timeout_task)
1446   {
1447     GNUNET_SCHEDULER_cancel (th->timeout_task);
1448     th->timeout_task = GNUNET_SCHEDULER_NO_TASK;
1449   }
1450   if (GNUNET_SCHEDULER_NO_TASK != th->connection->write_task)
1451   {
1452     GNUNET_SCHEDULER_cancel (th->connection->write_task);
1453     th->connection->write_task = GNUNET_SCHEDULER_NO_TASK;
1454   }
1455 }
1456
1457 /* end of connection.c */