- add user feedback
[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,
423            _("Access denied to `%s'\n"),
424            GNUNET_a2s (uaddr, addrlen));
425     GNUNET_break (GNUNET_OK ==
426                   GNUNET_NETWORK_socket_shutdown (sock, SHUT_RDWR));
427     GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (sock));
428     GNUNET_free (uaddr);
429     return NULL;
430   }
431   connection = GNUNET_new (struct GNUNET_CONNECTION_Handle);
432   connection->write_buffer_size = GNUNET_SERVER_MIN_BUFFER_SIZE;
433   connection->write_buffer = GNUNET_malloc (connection->write_buffer_size);
434   connection->addr = uaddr;
435   connection->addrlen = addrlen;
436   connection->sock = sock;
437   LOG (GNUNET_ERROR_TYPE_INFO,
438        _("Accepting connection from `%s': %p\n"),
439        GNUNET_a2s (uaddr, addrlen), connection);
440   return connection;
441 }
442
443
444 /**
445  * Obtain the network address of the other party.
446  *
447  * @param connection the client to get the address for
448  * @param addr where to store the address
449  * @param addrlen where to store the length of the address
450  * @return GNUNET_OK on success
451  */
452 int
453 GNUNET_CONNECTION_get_address (struct GNUNET_CONNECTION_Handle *connection,
454                                void **addr, size_t * addrlen)
455 {
456   if ((NULL == connection->addr) || (0 == connection->addrlen))
457     return GNUNET_NO;
458   *addr = GNUNET_malloc (connection->addrlen);
459   memcpy (*addr, connection->addr, connection->addrlen);
460   *addrlen = connection->addrlen;
461   return GNUNET_OK;
462 }
463
464
465 /**
466  * Tell the receiver callback that we had an IO error.
467  *
468  * @param connection connection to signal error
469  * @param errcode error code to send
470  */
471 static void
472 signal_receive_error (struct GNUNET_CONNECTION_Handle *connection, int errcode)
473 {
474   GNUNET_CONNECTION_Receiver receiver;
475
476   LOG (GNUNET_ERROR_TYPE_DEBUG,
477        "Receive encounters error (%s), connection closed (%p)\n",
478        STRERROR (errcode),
479        connection);
480   GNUNET_assert (NULL != (receiver = connection->receiver));
481   connection->receiver = NULL;
482   receiver (connection->receiver_cls, NULL, 0, connection->addr, connection->addrlen, errcode);
483 }
484
485
486 /**
487  * Tell the receiver callback that a timeout was reached.
488  *
489  * @param connection connection to signal for
490  */
491 static void
492 signal_receive_timeout (struct GNUNET_CONNECTION_Handle *connection)
493 {
494   GNUNET_CONNECTION_Receiver receiver;
495
496   LOG (GNUNET_ERROR_TYPE_DEBUG, "Connection signals timeout to receiver (%p)!\n",
497        connection);
498   GNUNET_assert (NULL != (receiver = connection->receiver));
499   connection->receiver = NULL;
500   receiver (connection->receiver_cls, NULL, 0, NULL, 0, 0);
501 }
502
503
504 /**
505  * We failed to transmit data to the service, signal the error.
506  *
507  * @param connection handle that had trouble
508  * @param ecode error code (errno)
509  */
510 static void
511 signal_transmit_error (struct GNUNET_CONNECTION_Handle *connection,
512                        int ecode)
513 {
514   GNUNET_CONNECTION_TransmitReadyNotify notify;
515
516   LOG (GNUNET_ERROR_TYPE_DEBUG,
517        "Transmission encounterd error (%s), connection closed (%p)\n",
518        STRERROR (ecode),
519        connection);
520   if (NULL != connection->sock)
521   {
522     GNUNET_NETWORK_socket_shutdown (connection->sock, SHUT_RDWR);
523     GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (connection->sock));
524     connection->sock = NULL;
525     GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == connection->write_task);
526   }
527   if (GNUNET_SCHEDULER_NO_TASK != connection->read_task)
528   {
529     /* send errors trigger read errors... */
530     GNUNET_SCHEDULER_cancel (connection->read_task);
531     connection->read_task = GNUNET_SCHEDULER_NO_TASK;
532     signal_receive_timeout (connection);
533     return;
534   }
535   if (NULL == connection->nth.notify_ready)
536     return;                     /* nobody to tell about it */
537   notify = connection->nth.notify_ready;
538   connection->nth.notify_ready = NULL;
539   notify (connection->nth.notify_ready_cls, 0, NULL);
540 }
541
542
543 /**
544  * We've failed for good to establish a connection (timeout or
545  * no more addresses to try).
546  *
547  * @param connection the connection we tried to establish
548  */
549 static void
550 connect_fail_continuation (struct GNUNET_CONNECTION_Handle *connection)
551 {
552   LOG (GNUNET_ERROR_TYPE_INFO,
553        _("Failed to establish TCP connection to `%s:%u', no further addresses to try.\n"),
554        connection->hostname, connection->port);
555   GNUNET_break (NULL == connection->ap_head);
556   GNUNET_break (NULL == connection->ap_tail);
557   GNUNET_break (GNUNET_NO == connection->dns_active);
558   GNUNET_break (NULL == connection->sock);
559   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == connection->write_task);
560
561   /* signal errors for jobs that used to wait on the connection */
562   connection->destroy_later = 1;
563   if (NULL != connection->receiver)
564     signal_receive_error (connection, ECONNREFUSED);
565   if (NULL != connection->nth.notify_ready)
566   {
567     GNUNET_assert (connection->nth.timeout_task != GNUNET_SCHEDULER_NO_TASK);
568     GNUNET_SCHEDULER_cancel (connection->nth.timeout_task);
569     connection->nth.timeout_task = GNUNET_SCHEDULER_NO_TASK;
570     signal_transmit_error (connection, ECONNREFUSED);
571   }
572   if (-1 == connection->destroy_later)
573   {
574     /* do it now */
575     connection->destroy_later = 0;
576     GNUNET_CONNECTION_destroy (connection);
577     return;
578   }
579   connection->destroy_later = 0;
580 }
581
582
583 /**
584  * We are ready to transmit (or got a timeout).
585  *
586  * @param cls our connection handle
587  * @param tc task context describing why we are here
588  */
589 static void
590 transmit_ready (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
591
592
593 /**
594  * This function is called once we either timeout or have data ready
595  * to read.
596  *
597  * @param cls connection to read from
598  * @param tc scheduler context
599  */
600 static void
601 receive_ready (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
602
603
604 /**
605  * We've succeeded in establishing a connection.
606  *
607  * @param connection the connection we tried to establish
608  */
609 static void
610 connect_success_continuation (struct GNUNET_CONNECTION_Handle *connection)
611 {
612   LOG (GNUNET_ERROR_TYPE_DEBUG,
613        "Connection to `%s' succeeded! (%p)\n",
614        GNUNET_a2s (connection->addr, connection->addrlen), connection);
615   /* trigger jobs that waited for the connection */
616   if (NULL != connection->receiver)
617   {
618     LOG (GNUNET_ERROR_TYPE_DEBUG,
619          "Connection succeeded, starting with receiving data (%p)\n",
620          connection);
621     GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == connection->read_task);
622     connection->read_task =
623       GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_absolute_get_remaining
624                                      (connection->receive_timeout), connection->sock,
625                                      &receive_ready, connection);
626   }
627   if (NULL != connection->nth.notify_ready)
628   {
629     LOG (GNUNET_ERROR_TYPE_DEBUG,
630          "Connection succeeded, starting with sending data (%p)\n",
631          connection);
632     GNUNET_assert (connection->nth.timeout_task != GNUNET_SCHEDULER_NO_TASK);
633     GNUNET_SCHEDULER_cancel (connection->nth.timeout_task);
634     connection->nth.timeout_task = GNUNET_SCHEDULER_NO_TASK;
635     GNUNET_assert (connection->write_task == GNUNET_SCHEDULER_NO_TASK);
636     connection->write_task =
637         GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_absolute_get_remaining
638                                         (connection->nth.transmit_timeout), connection->sock,
639                                         &transmit_ready, connection);
640   }
641 }
642
643
644 /**
645  * Scheduler let us know that we're either ready to write on the
646  * socket OR connect timed out.  Do the right thing.
647  *
648  * @param cls the "struct AddressProbe*" with the address that we are probing
649  * @param tc success or failure info about the connect attempt.
650  */
651 static void
652 connect_probe_continuation (void *cls,
653                             const struct GNUNET_SCHEDULER_TaskContext *tc)
654 {
655   struct AddressProbe *ap = cls;
656   struct GNUNET_CONNECTION_Handle *connection = ap->connection;
657   struct AddressProbe *pos;
658   int error;
659   socklen_t len;
660
661   GNUNET_assert (NULL != ap->sock);
662   GNUNET_CONTAINER_DLL_remove (connection->ap_head, connection->ap_tail, ap);
663   len = sizeof (error);
664   errno = 0;
665   error = 0;
666   if ((0 == (tc->reason & GNUNET_SCHEDULER_REASON_WRITE_READY)) ||
667       (GNUNET_OK !=
668        GNUNET_NETWORK_socket_getsockopt (ap->sock, SOL_SOCKET, SO_ERROR, &error,
669                                          &len)) || (0 != error))
670   {
671     GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (ap->sock));
672     GNUNET_free (ap);
673     if ((NULL == connection->ap_head) && (GNUNET_NO == connection->dns_active))
674       connect_fail_continuation (connection);
675     return;
676   }
677   GNUNET_assert (NULL == connection->sock);
678   connection->sock = ap->sock;
679   GNUNET_assert (NULL == connection->addr);
680   connection->addr = GNUNET_malloc (ap->addrlen);
681   memcpy (connection->addr, ap->addr, ap->addrlen);
682   connection->addrlen = ap->addrlen;
683   GNUNET_free (ap);
684   /* cancel all other attempts */
685   while (NULL != (pos = connection->ap_head))
686   {
687     GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (pos->sock));
688     GNUNET_SCHEDULER_cancel (pos->task);
689     GNUNET_CONTAINER_DLL_remove (connection->ap_head, connection->ap_tail, pos);
690     GNUNET_free (pos);
691   }
692   connect_success_continuation (connection);
693 }
694
695
696 /**
697  * Try to establish a connection given the specified address.
698  * This function is called by the resolver once we have a DNS reply.
699  *
700  * @param cls our "struct GNUNET_CONNECTION_Handle *"
701  * @param addr address to try, NULL for "last call"
702  * @param addrlen length of addr
703  */
704 static void
705 try_connect_using_address (void *cls, const struct sockaddr *addr,
706                            socklen_t addrlen)
707 {
708   struct GNUNET_CONNECTION_Handle *connection = cls;
709   struct AddressProbe *ap;
710   struct GNUNET_TIME_Relative delay;
711
712   if (NULL == addr)
713   {
714     connection->dns_active = NULL;
715     if ((NULL == connection->ap_head) && (NULL == connection->sock))
716       connect_fail_continuation (connection);
717     return;
718   }
719   if (NULL != connection->sock)
720     return;                     /* already connected */
721   GNUNET_assert (NULL == connection->addr);
722   /* try to connect */
723   LOG (GNUNET_ERROR_TYPE_DEBUG,
724        "Trying to connect using address `%s:%u/%s:%u'\n", connection->hostname, connection->port,
725        GNUNET_a2s (addr, addrlen), connection->port);
726   ap = GNUNET_malloc (sizeof (struct AddressProbe) + addrlen);
727   ap->addr = (const struct sockaddr *) &ap[1];
728   memcpy (&ap[1], addr, addrlen);
729   ap->addrlen = addrlen;
730   ap->connection = connection;
731
732   switch (ap->addr->sa_family)
733   {
734   case AF_INET:
735     ((struct sockaddr_in *) ap->addr)->sin_port = htons (connection->port);
736     break;
737   case AF_INET6:
738     ((struct sockaddr_in6 *) ap->addr)->sin6_port = htons (connection->port);
739     break;
740   default:
741     GNUNET_break (0);
742     GNUNET_free (ap);
743     return;                     /* not supported by us */
744   }
745   ap->sock = GNUNET_NETWORK_socket_create (ap->addr->sa_family, SOCK_STREAM, 0);
746   if (NULL == ap->sock)
747   {
748     GNUNET_free (ap);
749     return;                     /* not supported by OS */
750   }
751   LOG (GNUNET_ERROR_TYPE_INFO, _("Trying to connect to `%s' (%p)\n"),
752        GNUNET_a2s (ap->addr, ap->addrlen), connection);
753   if ((GNUNET_OK !=
754        GNUNET_NETWORK_socket_connect (ap->sock, ap->addr, ap->addrlen)) &&
755       (EINPROGRESS != errno))
756   {
757     /* maybe refused / unsupported address, try next */
758     LOG_STRERROR (GNUNET_ERROR_TYPE_INFO, "connect");
759     GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (ap->sock));
760     GNUNET_free (ap);
761     return;
762   }
763   GNUNET_CONTAINER_DLL_insert (connection->ap_head, connection->ap_tail, ap);
764   delay = GNUNET_CONNECTION_CONNECT_RETRY_TIMEOUT;
765   if (NULL != connection->nth.notify_ready)
766     delay =
767         GNUNET_TIME_relative_min (delay,
768                                   GNUNET_TIME_absolute_get_remaining (connection->
769                                                                       nth.transmit_timeout));
770   if (NULL != connection->receiver)
771     delay =
772         GNUNET_TIME_relative_min (delay,
773                                   GNUNET_TIME_absolute_get_remaining
774                                   (connection->receive_timeout));
775   ap->task =
776       GNUNET_SCHEDULER_add_write_net (delay, ap->sock,
777                                       &connect_probe_continuation, ap);
778 }
779
780
781 /**
782  * Create a connection handle by (asynchronously) connecting to a host.
783  * This function returns immediately, even if the connection has not
784  * yet been established.  This function only creates TCP connections.
785  *
786  * @param cfg configuration to use
787  * @param hostname name of the host to connect to
788  * @param port port to connect to
789  * @return the connection handle
790  */
791 struct GNUNET_CONNECTION_Handle *
792 GNUNET_CONNECTION_create_from_connect (const struct GNUNET_CONFIGURATION_Handle
793                                        *cfg, const char *hostname,
794                                        uint16_t port)
795 {
796   struct GNUNET_CONNECTION_Handle *connection;
797
798   GNUNET_assert (0 < strlen (hostname));        /* sanity check */
799   connection = GNUNET_new (struct GNUNET_CONNECTION_Handle);
800   connection->cfg = cfg;
801   connection->write_buffer_size = GNUNET_SERVER_MIN_BUFFER_SIZE;
802   connection->write_buffer = GNUNET_malloc (connection->write_buffer_size);
803   connection->port = port;
804   connection->hostname = GNUNET_strdup (hostname);
805   connection->dns_active =
806       GNUNET_RESOLVER_ip_get (connection->hostname, AF_UNSPEC,
807                               GNUNET_CONNECTION_CONNECT_RETRY_TIMEOUT,
808                               &try_connect_using_address, connection);
809   return connection;
810 }
811
812
813 /**
814  * Create a connection handle by connecting to a UNIX domain service.
815  * This function returns immediately, even if the connection has not
816  * yet been established.  This function only creates UNIX connections.
817  *
818  * @param cfg configuration to use
819  * @param unixpath path to connect to
820  * @return the connection handle, NULL on systems without UNIX support
821  */
822 struct GNUNET_CONNECTION_Handle *
823 GNUNET_CONNECTION_create_from_connect_to_unixpath (const struct
824                                                    GNUNET_CONFIGURATION_Handle
825                                                    *cfg, const char *unixpath)
826 {
827 #ifdef AF_UNIX
828   struct GNUNET_CONNECTION_Handle *connection;
829   struct sockaddr_un *un;
830
831   GNUNET_assert (0 < strlen (unixpath));        /* sanity check */
832   un = GNUNET_new (struct sockaddr_un);
833   un->sun_family = AF_UNIX;
834   strncpy (un->sun_path, unixpath, sizeof (un->sun_path) - 1);
835 #if HAVE_SOCKADDR_IN_SIN_LEN
836   un->sun_len = (u_char) sizeof (struct sockaddr_un);
837 #endif
838   connection = GNUNET_new (struct GNUNET_CONNECTION_Handle);
839   connection->cfg = cfg;
840   connection->write_buffer_size = GNUNET_SERVER_MIN_BUFFER_SIZE;
841   connection->write_buffer = GNUNET_malloc (connection->write_buffer_size);
842   connection->port = 0;
843   connection->hostname = NULL;
844   connection->addr = (struct sockaddr *) un;
845   connection->addrlen = sizeof (struct sockaddr_un);
846   connection->sock = GNUNET_NETWORK_socket_create (AF_UNIX, SOCK_STREAM, 0);
847   if (NULL == connection->sock)
848   {
849     GNUNET_free (connection->addr);
850     GNUNET_free (connection->write_buffer);
851     GNUNET_free (connection);
852     return NULL;
853   }
854   if ( (GNUNET_OK !=
855         GNUNET_NETWORK_socket_connect (connection->sock, connection->addr, connection->addrlen)) &&
856        (EINPROGRESS != errno) )
857   {
858     /* Just return; we expect everything to work eventually so don't fail HARD */
859     GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (connection->sock));
860     connection->sock = NULL;
861     return connection;
862   }
863   connect_success_continuation (connection);
864   return connection;
865 #else
866   return NULL;
867 #endif
868 }
869
870
871 /**
872  * Create a connection handle by (asynchronously) connecting to a host.
873  * This function returns immediately, even if the connection has not
874  * yet been established.  This function only creates TCP connections.
875  *
876  * @param af_family address family to use
877  * @param serv_addr server address
878  * @param addrlen length of server address
879  * @return the connection handle
880  */
881 struct GNUNET_CONNECTION_Handle *
882 GNUNET_CONNECTION_create_from_sockaddr (int af_family,
883                                         const struct sockaddr *serv_addr,
884                                         socklen_t addrlen)
885 {
886   struct GNUNET_NETWORK_Handle *s;
887   struct GNUNET_CONNECTION_Handle *connection;
888
889   s = GNUNET_NETWORK_socket_create (af_family, SOCK_STREAM, 0);
890   if (NULL == s)
891   {
892     LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK, "socket");
893     return NULL;
894   }
895   if ((GNUNET_OK != GNUNET_NETWORK_socket_connect (s, serv_addr, addrlen)) &&
896       (EINPROGRESS != errno))
897   {
898     /* maybe refused / unsupported address, try next */
899     LOG_STRERROR (GNUNET_ERROR_TYPE_INFO, "connect");
900     LOG (GNUNET_ERROR_TYPE_INFO, _("Attempt to connect to `%s' failed\n"),
901          GNUNET_a2s (serv_addr, addrlen));
902     GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (s));
903     return NULL;
904   }
905   connection = GNUNET_CONNECTION_create_from_existing (s);
906   connection->addr = GNUNET_malloc (addrlen);
907   memcpy (connection->addr, serv_addr, addrlen);
908   connection->addrlen = addrlen;
909   LOG (GNUNET_ERROR_TYPE_INFO, _("Trying to connect to `%s' (%p)\n"),
910        GNUNET_a2s (serv_addr, addrlen), connection);
911   return connection;
912 }
913
914
915 /**
916  * Check if connection is valid (no fatal errors have happened so far).
917  * Note that a connection that is still trying to connect is considered
918  * valid.
919  *
920  * @param connection connection to check
921  * @return GNUNET_YES if valid, GNUNET_NO otherwise
922  */
923 int
924 GNUNET_CONNECTION_check (struct GNUNET_CONNECTION_Handle *connection)
925 {
926   if ((NULL != connection->ap_head) || (NULL != connection->dns_active))
927     return GNUNET_YES;          /* still trying to connect */
928   return (NULL == connection->sock) ? GNUNET_NO : GNUNET_YES;
929 }
930
931
932 /**
933  * Close the connection and free associated resources.  There must
934  * not be any pending requests for reading or writing to the
935  * connection at this time.
936  *
937  * @param connection connection to destroy
938  */
939 void
940 GNUNET_CONNECTION_destroy (struct GNUNET_CONNECTION_Handle *connection)
941 {
942   struct AddressProbe *pos;
943
944   if (0 != connection->destroy_later)
945   {
946     connection->destroy_later = -1;
947     return;
948   }
949   LOG (GNUNET_ERROR_TYPE_DEBUG, "Shutting down connection (%p)\n", connection);
950   GNUNET_assert (NULL == connection->nth.notify_ready);
951   GNUNET_assert (NULL == connection->receiver);
952   if (GNUNET_SCHEDULER_NO_TASK != connection->write_task)
953   {
954     GNUNET_SCHEDULER_cancel (connection->write_task);
955     connection->write_task = GNUNET_SCHEDULER_NO_TASK;
956     connection->write_buffer_off = 0;
957   }
958   if (GNUNET_SCHEDULER_NO_TASK != connection->read_task)
959   {
960     GNUNET_SCHEDULER_cancel (connection->read_task);
961     connection->read_task = GNUNET_SCHEDULER_NO_TASK;
962   }
963   if (GNUNET_SCHEDULER_NO_TASK != connection->nth.timeout_task)
964   {
965     GNUNET_SCHEDULER_cancel (connection->nth.timeout_task);
966     connection->nth.timeout_task = GNUNET_SCHEDULER_NO_TASK;
967   }
968   connection->nth.notify_ready = NULL;
969   if (NULL != connection->dns_active)
970   {
971     GNUNET_RESOLVER_request_cancel (connection->dns_active);
972     connection->dns_active = NULL;
973   }
974   while (NULL != (pos = connection->ap_head))
975   {
976     GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (pos->sock));
977     GNUNET_SCHEDULER_cancel (pos->task);
978     GNUNET_CONTAINER_DLL_remove (connection->ap_head, connection->ap_tail, pos);
979     GNUNET_free (pos);
980   }
981   if ( (NULL != connection->sock) &&
982        (GNUNET_YES != connection->persist) )
983   {
984     if ((GNUNET_YES != GNUNET_NETWORK_socket_shutdown (connection->sock, SHUT_RDWR)) &&
985         (ENOTCONN != errno) &&
986         (ECONNRESET != errno) )
987       LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "shutdown");
988   }
989   if (NULL != connection->sock)
990   {
991     if (GNUNET_YES != connection->persist)
992       GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (connection->sock));
993     else
994     {
995       GNUNET_NETWORK_socket_free_memory_only_ (connection->sock); /* at least no memory leak (we deliberately
996                                                                    * leak the socket in this special case) ... */
997     }
998   }
999   GNUNET_free_non_null (connection->addr);
1000   GNUNET_free_non_null (connection->hostname);
1001   GNUNET_free (connection->write_buffer);
1002   GNUNET_free (connection);
1003 }
1004
1005
1006 /**
1007  * This function is called once we either timeout
1008  * or have data ready to read.
1009  *
1010  * @param cls connection to read from
1011  * @param tc scheduler context
1012  */
1013 static void
1014 receive_ready (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1015 {
1016   struct GNUNET_CONNECTION_Handle *connection = cls;
1017   char buffer[connection->max];
1018   ssize_t ret;
1019   GNUNET_CONNECTION_Receiver receiver;
1020
1021   connection->read_task = GNUNET_SCHEDULER_NO_TASK;
1022   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1023   {
1024     /* ignore shutdown request, go again immediately */
1025     connection->read_task =
1026         GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_absolute_get_remaining
1027                                        (connection->receive_timeout), connection->sock,
1028                                        &receive_ready, connection);
1029     return;
1030   }
1031   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_TIMEOUT))
1032   {
1033     LOG (GNUNET_ERROR_TYPE_DEBUG,
1034          "Receive from `%s' encounters error: timeout (%s, %p)\n",
1035          GNUNET_a2s (connection->addr, connection->addrlen),
1036          GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_duration (connection->receive_timeout), GNUNET_YES),
1037          connection);
1038     signal_receive_timeout (connection);
1039     return;
1040   }
1041   if (NULL == connection->sock)
1042   {
1043     /* connect failed for good */
1044     signal_receive_error (connection, ECONNREFUSED);
1045     return;
1046   }
1047   GNUNET_assert (GNUNET_NETWORK_fdset_isset (tc->read_ready, connection->sock));
1048 RETRY:
1049   ret = GNUNET_NETWORK_socket_recv (connection->sock, buffer, connection->max);
1050   if (-1 == ret)
1051   {
1052     if (EINTR == errno)
1053       goto RETRY;
1054     signal_receive_error (connection, errno);
1055     return;
1056   }
1057   LOG (GNUNET_ERROR_TYPE_DEBUG,
1058        "receive_ready read %u/%u bytes from `%s' (%p)!\n", (unsigned int) ret,
1059        connection->max, GNUNET_a2s (connection->addr, connection->addrlen), connection);
1060   GNUNET_assert (NULL != (receiver = connection->receiver));
1061   connection->receiver = NULL;
1062   receiver (connection->receiver_cls, buffer, ret, connection->addr, connection->addrlen, 0);
1063 }
1064
1065
1066 /**
1067  * Receive data from the given connection.  Note that this function will
1068  * call "receiver" asynchronously using the scheduler.  It will
1069  * "immediately" return.  Note that there MUST only be one active
1070  * receive call per connection at any given point in time (so do not
1071  * call receive again until the receiver callback has been invoked).
1072  *
1073  * @param connection connection handle
1074  * @param max maximum number of bytes to read
1075  * @param timeout maximum amount of time to wait
1076  * @param receiver function to call with received data
1077  * @param receiver_cls closure for receiver
1078  */
1079 void
1080 GNUNET_CONNECTION_receive (struct GNUNET_CONNECTION_Handle *connection, size_t max,
1081                            struct GNUNET_TIME_Relative timeout,
1082                            GNUNET_CONNECTION_Receiver receiver,
1083                            void *receiver_cls)
1084 {
1085   GNUNET_assert ((GNUNET_SCHEDULER_NO_TASK == connection->read_task) &&
1086                  (NULL == connection->receiver));
1087   GNUNET_assert (NULL != receiver);
1088   connection->receiver = receiver;
1089   connection->receiver_cls = receiver_cls;
1090   connection->receive_timeout = GNUNET_TIME_relative_to_absolute (timeout);
1091   connection->max = max;
1092   if (NULL != connection->sock)
1093   {
1094     connection->read_task =
1095       GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_absolute_get_remaining
1096                                      (connection->receive_timeout), connection->sock,
1097                                      &receive_ready, connection);
1098     return;
1099   }
1100   if ((NULL == connection->dns_active) && (NULL == connection->ap_head))
1101   {
1102     connection->receiver = NULL;
1103     receiver (receiver_cls, NULL, 0, NULL, 0, ETIMEDOUT);
1104     return;
1105   }
1106 }
1107
1108
1109 /**
1110  * Cancel receive job on the given connection.  Note that the
1111  * receiver callback must not have been called yet in order
1112  * for the cancellation to be valid.
1113  *
1114  * @param connection connection handle
1115  * @return closure of the original receiver callback closure
1116  */
1117 void *
1118 GNUNET_CONNECTION_receive_cancel (struct GNUNET_CONNECTION_Handle *connection)
1119 {
1120   if (GNUNET_SCHEDULER_NO_TASK != connection->read_task)
1121   {
1122     GNUNET_assert (connection == GNUNET_SCHEDULER_cancel (connection->read_task));
1123     connection->read_task = GNUNET_SCHEDULER_NO_TASK;
1124   }
1125   connection->receiver = NULL;
1126   return connection->receiver_cls;
1127 }
1128
1129
1130 /**
1131  * Try to call the transmit notify method (check if we do
1132  * have enough space available first)!
1133  *
1134  * @param connection connection for which we should do this processing
1135  * @return GNUNET_YES if we were able to call notify
1136  */
1137 static int
1138 process_notify (struct GNUNET_CONNECTION_Handle *connection)
1139 {
1140   size_t used;
1141   size_t avail;
1142   size_t size;
1143   GNUNET_CONNECTION_TransmitReadyNotify notify;
1144
1145   LOG (GNUNET_ERROR_TYPE_DEBUG, "process_notify is running\n");
1146
1147   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == connection->write_task);
1148   if (NULL == (notify = connection->nth.notify_ready))
1149   {
1150     LOG (GNUNET_ERROR_TYPE_DEBUG, "Noone to notify\n");
1151     return GNUNET_NO;
1152   }
1153   used = connection->write_buffer_off - connection->write_buffer_pos;
1154   avail = connection->write_buffer_size - used;
1155   size = connection->nth.notify_size;
1156   if (size > avail)
1157   {
1158     LOG (GNUNET_ERROR_TYPE_DEBUG, "Not enough buffer\n");
1159     return GNUNET_NO;
1160   }
1161   connection->nth.notify_ready = NULL;
1162   if (connection->write_buffer_size - connection->write_buffer_off < size)
1163   {
1164     /* need to compact */
1165     memmove (connection->write_buffer, &connection->write_buffer[connection->write_buffer_pos],
1166              used);
1167     connection->write_buffer_off -= connection->write_buffer_pos;
1168     connection->write_buffer_pos = 0;
1169   }
1170   avail = connection->write_buffer_size - connection->write_buffer_off;
1171   GNUNET_assert (avail >= size);
1172   size =
1173       notify (connection->nth.notify_ready_cls, avail,
1174               &connection->write_buffer[connection->write_buffer_off]);
1175   GNUNET_assert (size <= avail);
1176   if (0 != size)
1177     connection->write_buffer_off += size;
1178   return GNUNET_YES;
1179 }
1180
1181
1182 /**
1183  * Task invoked by the scheduler when a call to transmit
1184  * is timing out (we never got enough buffer space to call
1185  * the callback function before the specified timeout
1186  * expired).
1187  *
1188  * This task notifies the client about the timeout.
1189  *
1190  * @param cls the 'struct GNUNET_CONNECTION_Handle'
1191  * @param tc scheduler context
1192  */
1193 static void
1194 transmit_timeout (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1195 {
1196   struct GNUNET_CONNECTION_Handle *connection = cls;
1197   GNUNET_CONNECTION_TransmitReadyNotify notify;
1198
1199   connection->nth.timeout_task = GNUNET_SCHEDULER_NO_TASK;
1200   LOG (GNUNET_ERROR_TYPE_DEBUG,
1201        "Transmit to `%s:%u/%s' fails, time out reached (%p).\n",
1202        connection->hostname,
1203        connection->port, GNUNET_a2s (connection->addr, connection->addrlen), connection);
1204   notify = connection->nth.notify_ready;
1205   GNUNET_assert (NULL != notify);
1206   connection->nth.notify_ready = NULL;
1207   notify (connection->nth.notify_ready_cls, 0, NULL);
1208 }
1209
1210
1211 /**
1212  * Task invoked by the scheduler when we failed to connect
1213  * at the time of being asked to transmit.
1214  *
1215  * This task notifies the client about the error.
1216  *
1217  * @param cls the 'struct GNUNET_CONNECTION_Handle'
1218  * @param tc scheduler context
1219  */
1220 static void
1221 connect_error (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1222 {
1223   struct GNUNET_CONNECTION_Handle *connection = cls;
1224   GNUNET_CONNECTION_TransmitReadyNotify notify;
1225
1226   LOG (GNUNET_ERROR_TYPE_DEBUG,
1227        "Transmission request of size %u fails (%s/%u), connection failed (%p).\n",
1228        connection->nth.notify_size, connection->hostname, connection->port, connection);
1229   connection->write_task = GNUNET_SCHEDULER_NO_TASK;
1230   notify = connection->nth.notify_ready;
1231   connection->nth.notify_ready = NULL;
1232   notify (connection->nth.notify_ready_cls, 0, NULL);
1233 }
1234
1235
1236 /**
1237  * We are ready to transmit (or got a timeout).
1238  *
1239  * @param cls our connection handle
1240  * @param tc task context describing why we are here
1241  */
1242 static void
1243 transmit_ready (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1244 {
1245   struct GNUNET_CONNECTION_Handle *connection = cls;
1246   GNUNET_CONNECTION_TransmitReadyNotify notify;
1247   ssize_t ret;
1248   size_t have;
1249
1250   LOG (GNUNET_ERROR_TYPE_DEBUG, "transmit_ready running (%p).\n", connection);
1251   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK != connection->write_task);
1252   connection->write_task = GNUNET_SCHEDULER_NO_TASK;
1253   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == connection->nth.timeout_task);
1254   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1255   {
1256     if (NULL != connection->sock)
1257       goto SCHEDULE_WRITE;      /* ignore shutdown, go again immediately */
1258     LOG (GNUNET_ERROR_TYPE_DEBUG,
1259          "Transmit to `%s' fails, shutdown happened (%p).\n",
1260          GNUNET_a2s (connection->addr, connection->addrlen), connection);
1261     notify = connection->nth.notify_ready;
1262     if (NULL != notify)
1263     {
1264       connection->nth.notify_ready = NULL;
1265       notify (connection->nth.notify_ready_cls, 0, NULL);
1266     }
1267     return;
1268   }
1269   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_TIMEOUT))
1270   {
1271     LOG (GNUNET_ERROR_TYPE_DEBUG,
1272          "Transmit to `%s' fails, time out reached (%p).\n",
1273          GNUNET_a2s (connection->addr, connection->addrlen), connection);
1274     notify = connection->nth.notify_ready;
1275     GNUNET_assert (NULL != notify);
1276     connection->nth.notify_ready = NULL;
1277     notify (connection->nth.notify_ready_cls, 0, NULL);
1278     return;
1279   }
1280   GNUNET_assert (NULL != connection->sock);
1281   if (NULL == tc->write_ready)
1282   {
1283     /* special circumstances (in particular, PREREQ_DONE after
1284      * connect): not yet ready to write, but no "fatal" error either.
1285      * Hence retry.  */
1286     goto SCHEDULE_WRITE;
1287   }
1288   if (!GNUNET_NETWORK_fdset_isset (tc->write_ready, connection->sock))
1289   {
1290     GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == connection->write_task);
1291     /* special circumstances (in particular, shutdown): not yet ready
1292      * to write, but no "fatal" error either.  Hence retry.  */
1293     goto SCHEDULE_WRITE;
1294   }
1295   GNUNET_assert (connection->write_buffer_off >= connection->write_buffer_pos);
1296   if ((NULL != connection->nth.notify_ready) &&
1297       (connection->write_buffer_size < connection->nth.notify_size))
1298   {
1299     connection->write_buffer =
1300         GNUNET_realloc (connection->write_buffer, connection->nth.notify_size);
1301     connection->write_buffer_size = connection->nth.notify_size;
1302   }
1303   process_notify (connection);
1304   have = connection->write_buffer_off - connection->write_buffer_pos;
1305   if (0 == have)
1306   {
1307     /* no data ready for writing, terminate write loop */
1308     return;
1309   }
1310   GNUNET_assert (have <= connection->write_buffer_size);
1311   GNUNET_assert (have + connection->write_buffer_pos <= connection->write_buffer_size);
1312   GNUNET_assert (connection->write_buffer_pos <= connection->write_buffer_size);
1313 RETRY:
1314   ret =
1315       GNUNET_NETWORK_socket_send (connection->sock,
1316                                   &connection->write_buffer[connection->write_buffer_pos],
1317                                   have);
1318   if (-1 == ret)
1319   {
1320     if (EINTR == errno)
1321       goto RETRY;
1322     if (GNUNET_SCHEDULER_NO_TASK != connection->write_task)
1323     {
1324       GNUNET_SCHEDULER_cancel (connection->write_task);
1325       connection->write_task = GNUNET_SCHEDULER_NO_TASK;
1326     }
1327     signal_transmit_error (connection, errno);
1328     return;
1329   }
1330   LOG (GNUNET_ERROR_TYPE_DEBUG,
1331        "Connection transmitted %u/%u bytes to `%s' (%p)\n",
1332        (unsigned int) ret, have, GNUNET_a2s (connection->addr, connection->addrlen), connection);
1333   connection->write_buffer_pos += ret;
1334   if (connection->write_buffer_pos == connection->write_buffer_off)
1335   {
1336     /* transmitted all pending data */
1337     connection->write_buffer_pos = 0;
1338     connection->write_buffer_off = 0;
1339   }
1340   if ((0 == connection->write_buffer_off) && (NULL == connection->nth.notify_ready))
1341     return;                     /* all data sent! */
1342   /* not done writing, schedule more */
1343 SCHEDULE_WRITE:
1344   LOG (GNUNET_ERROR_TYPE_DEBUG,
1345        "Re-scheduling transmit_ready (more to do) (%p).\n", connection);
1346   have = connection->write_buffer_off - connection->write_buffer_pos;
1347   GNUNET_assert ((NULL != connection->nth.notify_ready) || (have > 0));
1348   if (GNUNET_SCHEDULER_NO_TASK == connection->write_task)
1349     connection->write_task =
1350         GNUNET_SCHEDULER_add_write_net ((connection->nth.notify_ready ==
1351                                          NULL) ? GNUNET_TIME_UNIT_FOREVER_REL :
1352                                         GNUNET_TIME_absolute_get_remaining
1353                                         (connection->nth.transmit_timeout),
1354                                         connection->sock, &transmit_ready, connection);
1355 }
1356
1357
1358 /**
1359  * Ask the connection to call us once the specified number of bytes
1360  * are free in the transmission buffer.  May call the notify
1361  * method immediately if enough space is available.
1362  *
1363  * @param connection connection
1364  * @param size number of bytes to send
1365  * @param timeout after how long should we give up (and call
1366  *        notify with buf NULL and size 0)?
1367  * @param notify function to call
1368  * @param notify_cls closure for notify
1369  * @return non-NULL if the notify callback was queued,
1370  *         NULL if we are already going to notify someone else (busy)
1371  */
1372 struct GNUNET_CONNECTION_TransmitHandle *
1373 GNUNET_CONNECTION_notify_transmit_ready (struct GNUNET_CONNECTION_Handle *connection,
1374                                          size_t size,
1375                                          struct GNUNET_TIME_Relative timeout,
1376                                          GNUNET_CONNECTION_TransmitReadyNotify
1377                                          notify, void *notify_cls)
1378 {
1379   if (NULL != connection->nth.notify_ready)
1380   {
1381     GNUNET_assert (0);
1382     return NULL;
1383   }
1384   GNUNET_assert (NULL != notify);
1385   GNUNET_assert (size < GNUNET_SERVER_MAX_MESSAGE_SIZE);
1386   GNUNET_assert (connection->write_buffer_off <= connection->write_buffer_size);
1387   GNUNET_assert (connection->write_buffer_pos <= connection->write_buffer_size);
1388   GNUNET_assert (connection->write_buffer_pos <= connection->write_buffer_off);
1389   connection->nth.notify_ready = notify;
1390   connection->nth.notify_ready_cls = notify_cls;
1391   connection->nth.connection = connection;
1392   connection->nth.notify_size = size;
1393   connection->nth.transmit_timeout = GNUNET_TIME_relative_to_absolute (timeout);
1394   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == connection->nth.timeout_task);
1395   if ((NULL == connection->sock) &&
1396       (NULL == connection->ap_head) &&
1397       (NULL == connection->dns_active))
1398   {
1399     if (GNUNET_SCHEDULER_NO_TASK != connection->write_task)
1400       GNUNET_SCHEDULER_cancel (connection->write_task);
1401     connection->write_task = GNUNET_SCHEDULER_add_now (&connect_error, connection);
1402     return &connection->nth;
1403   }
1404   if (GNUNET_SCHEDULER_NO_TASK != connection->write_task)
1405     return &connection->nth; /* previous transmission still in progress */
1406   if (NULL != connection->sock)
1407   {
1408     /* connected, try to transmit now */
1409     LOG (GNUNET_ERROR_TYPE_DEBUG, "Scheduling transmission (%p).\n", connection);
1410     connection->write_task =
1411         GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_absolute_get_remaining
1412                                         (connection->nth.transmit_timeout),
1413                                         connection->sock, &transmit_ready, connection);
1414     return &connection->nth;
1415   }
1416   /* not yet connected, wait for connection */
1417   LOG (GNUNET_ERROR_TYPE_DEBUG,
1418        "Need to wait to schedule transmission for connection, adding timeout task (%p).\n", connection);
1419   connection->nth.timeout_task =
1420     GNUNET_SCHEDULER_add_delayed (timeout, &transmit_timeout, connection);
1421   return &connection->nth;
1422 }
1423
1424
1425 /**
1426  * Cancel the specified transmission-ready notification.
1427  *
1428  * @param th notification to cancel
1429  */
1430 void
1431 GNUNET_CONNECTION_notify_transmit_ready_cancel (struct
1432                                                 GNUNET_CONNECTION_TransmitHandle
1433                                                 *th)
1434 {
1435   GNUNET_assert (NULL != th->notify_ready);
1436   th->notify_ready = NULL;
1437   if (GNUNET_SCHEDULER_NO_TASK != th->timeout_task)
1438   {
1439     GNUNET_SCHEDULER_cancel (th->timeout_task);
1440     th->timeout_task = GNUNET_SCHEDULER_NO_TASK;
1441   }
1442   if (GNUNET_SCHEDULER_NO_TASK != th->connection->write_task)
1443   {
1444     GNUNET_SCHEDULER_cancel (th->connection->write_task);
1445     th->connection->write_task = GNUNET_SCHEDULER_NO_TASK;
1446   }
1447 }
1448
1449 /* end of connection.c */