minor changes for address conversion
[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 #ifdef LINUX
836   {
837     int abstract;
838
839     abstract = GNUNET_CONFIGURATION_get_value_yesno (cfg, "TESTING",
840                                                      "USE_ABSTRACT_SOCKETS");
841     if (GNUNET_YES == abstract)
842       un->sun_path[0] = '\0';
843   }
844 #endif
845 #if HAVE_SOCKADDR_IN_SIN_LEN
846   un->sun_len = (u_char) sizeof (struct sockaddr_un);
847 #endif
848   connection = GNUNET_new (struct GNUNET_CONNECTION_Handle);
849   connection->cfg = cfg;
850   connection->write_buffer_size = GNUNET_SERVER_MIN_BUFFER_SIZE;
851   connection->write_buffer = GNUNET_malloc (connection->write_buffer_size);
852   connection->port = 0;
853   connection->hostname = NULL;
854   connection->addr = (struct sockaddr *) un;
855   connection->addrlen = sizeof (struct sockaddr_un);
856   connection->sock = GNUNET_NETWORK_socket_create (AF_UNIX, SOCK_STREAM, 0);
857   if (NULL == connection->sock)
858   {
859     GNUNET_free (connection->addr);
860     GNUNET_free (connection->write_buffer);
861     GNUNET_free (connection);
862     return NULL;
863   }
864   if ( (GNUNET_OK !=
865         GNUNET_NETWORK_socket_connect (connection->sock, connection->addr, connection->addrlen)) &&
866        (EINPROGRESS != errno) )
867   {
868     /* Just return; we expect everything to work eventually so don't fail HARD */
869     GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (connection->sock));
870     connection->sock = NULL;
871     return connection;
872   }
873   connect_success_continuation (connection);
874   return connection;
875 #else
876   return NULL;
877 #endif
878 }
879
880
881 /**
882  * Create a connection handle by (asynchronously) connecting to a host.
883  * This function returns immediately, even if the connection has not
884  * yet been established.  This function only creates TCP connections.
885  *
886  * @param af_family address family to use
887  * @param serv_addr server address
888  * @param addrlen length of server address
889  * @return the connection handle
890  */
891 struct GNUNET_CONNECTION_Handle *
892 GNUNET_CONNECTION_create_from_sockaddr (int af_family,
893                                         const struct sockaddr *serv_addr,
894                                         socklen_t addrlen)
895 {
896   struct GNUNET_NETWORK_Handle *s;
897   struct GNUNET_CONNECTION_Handle *connection;
898
899   s = GNUNET_NETWORK_socket_create (af_family, SOCK_STREAM, 0);
900   if (NULL == s)
901   {
902     LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK, "socket");
903     return NULL;
904   }
905   if ((GNUNET_OK != GNUNET_NETWORK_socket_connect (s, serv_addr, addrlen)) &&
906       (EINPROGRESS != errno))
907   {
908     /* maybe refused / unsupported address, try next */
909     LOG_STRERROR (GNUNET_ERROR_TYPE_INFO, "connect");
910     LOG (GNUNET_ERROR_TYPE_INFO, _("Attempt to connect to `%s' failed\n"),
911          GNUNET_a2s (serv_addr, addrlen));
912     GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (s));
913     return NULL;
914   }
915   connection = GNUNET_CONNECTION_create_from_existing (s);
916   connection->addr = GNUNET_malloc (addrlen);
917   memcpy (connection->addr, serv_addr, addrlen);
918   connection->addrlen = addrlen;
919   LOG (GNUNET_ERROR_TYPE_INFO, _("Trying to connect to `%s' (%p)\n"),
920        GNUNET_a2s (serv_addr, addrlen), connection);
921   return connection;
922 }
923
924
925 /**
926  * Check if connection is valid (no fatal errors have happened so far).
927  * Note that a connection that is still trying to connect is considered
928  * valid.
929  *
930  * @param connection connection to check
931  * @return GNUNET_YES if valid, GNUNET_NO otherwise
932  */
933 int
934 GNUNET_CONNECTION_check (struct GNUNET_CONNECTION_Handle *connection)
935 {
936   if ((NULL != connection->ap_head) || (NULL != connection->dns_active))
937     return GNUNET_YES;          /* still trying to connect */
938   return (NULL == connection->sock) ? GNUNET_NO : GNUNET_YES;
939 }
940
941
942 /**
943  * Close the connection and free associated resources.  There must
944  * not be any pending requests for reading or writing to the
945  * connection at this time.
946  *
947  * @param connection connection to destroy
948  */
949 void
950 GNUNET_CONNECTION_destroy (struct GNUNET_CONNECTION_Handle *connection)
951 {
952   struct AddressProbe *pos;
953
954   if (0 != connection->destroy_later)
955   {
956     connection->destroy_later = -1;
957     return;
958   }
959   LOG (GNUNET_ERROR_TYPE_DEBUG, "Shutting down connection (%p)\n", connection);
960   GNUNET_assert (NULL == connection->nth.notify_ready);
961   GNUNET_assert (NULL == connection->receiver);
962   if (GNUNET_SCHEDULER_NO_TASK != connection->write_task)
963   {
964     GNUNET_SCHEDULER_cancel (connection->write_task);
965     connection->write_task = GNUNET_SCHEDULER_NO_TASK;
966     connection->write_buffer_off = 0;
967   }
968   if (GNUNET_SCHEDULER_NO_TASK != connection->read_task)
969   {
970     GNUNET_SCHEDULER_cancel (connection->read_task);
971     connection->read_task = GNUNET_SCHEDULER_NO_TASK;
972   }
973   if (GNUNET_SCHEDULER_NO_TASK != connection->nth.timeout_task)
974   {
975     GNUNET_SCHEDULER_cancel (connection->nth.timeout_task);
976     connection->nth.timeout_task = GNUNET_SCHEDULER_NO_TASK;
977   }
978   connection->nth.notify_ready = NULL;
979   if (NULL != connection->dns_active)
980   {
981     GNUNET_RESOLVER_request_cancel (connection->dns_active);
982     connection->dns_active = NULL;
983   }
984   while (NULL != (pos = connection->ap_head))
985   {
986     GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (pos->sock));
987     GNUNET_SCHEDULER_cancel (pos->task);
988     GNUNET_CONTAINER_DLL_remove (connection->ap_head, connection->ap_tail, pos);
989     GNUNET_free (pos);
990   }
991   if ( (NULL != connection->sock) &&
992        (GNUNET_YES != connection->persist) )
993   {
994     if ((GNUNET_YES != GNUNET_NETWORK_socket_shutdown (connection->sock, SHUT_RDWR)) &&
995         (ENOTCONN != errno) &&
996         (ECONNRESET != errno) )
997       LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "shutdown");
998   }
999   if (NULL != connection->sock)
1000   {
1001     if (GNUNET_YES != connection->persist)
1002       GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (connection->sock));
1003     else
1004     {
1005       GNUNET_NETWORK_socket_free_memory_only_ (connection->sock); /* at least no memory leak (we deliberately
1006                                                                    * leak the socket in this special case) ... */
1007     }
1008   }
1009   GNUNET_free_non_null (connection->addr);
1010   GNUNET_free_non_null (connection->hostname);
1011   GNUNET_free (connection->write_buffer);
1012   GNUNET_free (connection);
1013 }
1014
1015
1016 /**
1017  * This function is called once we either timeout
1018  * or have data ready to read.
1019  *
1020  * @param cls connection to read from
1021  * @param tc scheduler context
1022  */
1023 static void
1024 receive_ready (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1025 {
1026   struct GNUNET_CONNECTION_Handle *connection = cls;
1027   char buffer[connection->max];
1028   ssize_t ret;
1029   GNUNET_CONNECTION_Receiver receiver;
1030
1031   connection->read_task = GNUNET_SCHEDULER_NO_TASK;
1032   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1033   {
1034     /* ignore shutdown request, go again immediately */
1035     connection->read_task =
1036         GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_absolute_get_remaining
1037                                        (connection->receive_timeout), connection->sock,
1038                                        &receive_ready, connection);
1039     return;
1040   }
1041   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_TIMEOUT))
1042   {
1043     LOG (GNUNET_ERROR_TYPE_DEBUG,
1044          "Receive from `%s' encounters error: timeout (%s, %p)\n",
1045          GNUNET_a2s (connection->addr, connection->addrlen),
1046          GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_duration (connection->receive_timeout), GNUNET_YES),
1047          connection);
1048     signal_receive_timeout (connection);
1049     return;
1050   }
1051   if (NULL == connection->sock)
1052   {
1053     /* connect failed for good */
1054     signal_receive_error (connection, ECONNREFUSED);
1055     return;
1056   }
1057   GNUNET_assert (GNUNET_NETWORK_fdset_isset (tc->read_ready, connection->sock));
1058 RETRY:
1059   ret = GNUNET_NETWORK_socket_recv (connection->sock, buffer, connection->max);
1060   if (-1 == ret)
1061   {
1062     if (EINTR == errno)
1063       goto RETRY;
1064     signal_receive_error (connection, errno);
1065     return;
1066   }
1067   LOG (GNUNET_ERROR_TYPE_DEBUG,
1068        "receive_ready read %u/%u bytes from `%s' (%p)!\n", (unsigned int) ret,
1069        connection->max, GNUNET_a2s (connection->addr, connection->addrlen), connection);
1070   GNUNET_assert (NULL != (receiver = connection->receiver));
1071   connection->receiver = NULL;
1072   receiver (connection->receiver_cls, buffer, ret, connection->addr, connection->addrlen, 0);
1073 }
1074
1075
1076 /**
1077  * Receive data from the given connection.  Note that this function will
1078  * call "receiver" asynchronously using the scheduler.  It will
1079  * "immediately" return.  Note that there MUST only be one active
1080  * receive call per connection at any given point in time (so do not
1081  * call receive again until the receiver callback has been invoked).
1082  *
1083  * @param connection connection handle
1084  * @param max maximum number of bytes to read
1085  * @param timeout maximum amount of time to wait
1086  * @param receiver function to call with received data
1087  * @param receiver_cls closure for receiver
1088  */
1089 void
1090 GNUNET_CONNECTION_receive (struct GNUNET_CONNECTION_Handle *connection, size_t max,
1091                            struct GNUNET_TIME_Relative timeout,
1092                            GNUNET_CONNECTION_Receiver receiver,
1093                            void *receiver_cls)
1094 {
1095   GNUNET_assert ((GNUNET_SCHEDULER_NO_TASK == connection->read_task) &&
1096                  (NULL == connection->receiver));
1097   GNUNET_assert (NULL != receiver);
1098   connection->receiver = receiver;
1099   connection->receiver_cls = receiver_cls;
1100   connection->receive_timeout = GNUNET_TIME_relative_to_absolute (timeout);
1101   connection->max = max;
1102   if (NULL != connection->sock)
1103   {
1104     connection->read_task =
1105       GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_absolute_get_remaining
1106                                      (connection->receive_timeout), connection->sock,
1107                                      &receive_ready, connection);
1108     return;
1109   }
1110   if ((NULL == connection->dns_active) && (NULL == connection->ap_head))
1111   {
1112     connection->receiver = NULL;
1113     receiver (receiver_cls, NULL, 0, NULL, 0, ETIMEDOUT);
1114     return;
1115   }
1116 }
1117
1118
1119 /**
1120  * Cancel receive job on the given connection.  Note that the
1121  * receiver callback must not have been called yet in order
1122  * for the cancellation to be valid.
1123  *
1124  * @param connection connection handle
1125  * @return closure of the original receiver callback closure
1126  */
1127 void *
1128 GNUNET_CONNECTION_receive_cancel (struct GNUNET_CONNECTION_Handle *connection)
1129 {
1130   if (GNUNET_SCHEDULER_NO_TASK != connection->read_task)
1131   {
1132     GNUNET_assert (connection == GNUNET_SCHEDULER_cancel (connection->read_task));
1133     connection->read_task = GNUNET_SCHEDULER_NO_TASK;
1134   }
1135   connection->receiver = NULL;
1136   return connection->receiver_cls;
1137 }
1138
1139
1140 /**
1141  * Try to call the transmit notify method (check if we do
1142  * have enough space available first)!
1143  *
1144  * @param connection connection for which we should do this processing
1145  * @return GNUNET_YES if we were able to call notify
1146  */
1147 static int
1148 process_notify (struct GNUNET_CONNECTION_Handle *connection)
1149 {
1150   size_t used;
1151   size_t avail;
1152   size_t size;
1153   GNUNET_CONNECTION_TransmitReadyNotify notify;
1154
1155   LOG (GNUNET_ERROR_TYPE_DEBUG, "process_notify is running\n");
1156
1157   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == connection->write_task);
1158   if (NULL == (notify = connection->nth.notify_ready))
1159   {
1160     LOG (GNUNET_ERROR_TYPE_DEBUG, "Noone to notify\n");
1161     return GNUNET_NO;
1162   }
1163   used = connection->write_buffer_off - connection->write_buffer_pos;
1164   avail = connection->write_buffer_size - used;
1165   size = connection->nth.notify_size;
1166   if (size > avail)
1167   {
1168     LOG (GNUNET_ERROR_TYPE_DEBUG, "Not enough buffer\n");
1169     return GNUNET_NO;
1170   }
1171   connection->nth.notify_ready = NULL;
1172   if (connection->write_buffer_size - connection->write_buffer_off < size)
1173   {
1174     /* need to compact */
1175     memmove (connection->write_buffer, &connection->write_buffer[connection->write_buffer_pos],
1176              used);
1177     connection->write_buffer_off -= connection->write_buffer_pos;
1178     connection->write_buffer_pos = 0;
1179   }
1180   avail = connection->write_buffer_size - connection->write_buffer_off;
1181   GNUNET_assert (avail >= size);
1182   size =
1183       notify (connection->nth.notify_ready_cls, avail,
1184               &connection->write_buffer[connection->write_buffer_off]);
1185   GNUNET_assert (size <= avail);
1186   if (0 != size)
1187     connection->write_buffer_off += size;
1188   return GNUNET_YES;
1189 }
1190
1191
1192 /**
1193  * Task invoked by the scheduler when a call to transmit
1194  * is timing out (we never got enough buffer space to call
1195  * the callback function before the specified timeout
1196  * expired).
1197  *
1198  * This task notifies the client about the timeout.
1199  *
1200  * @param cls the 'struct GNUNET_CONNECTION_Handle'
1201  * @param tc scheduler context
1202  */
1203 static void
1204 transmit_timeout (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1205 {
1206   struct GNUNET_CONNECTION_Handle *connection = cls;
1207   GNUNET_CONNECTION_TransmitReadyNotify notify;
1208
1209   connection->nth.timeout_task = GNUNET_SCHEDULER_NO_TASK;
1210   LOG (GNUNET_ERROR_TYPE_DEBUG,
1211        "Transmit to `%s:%u/%s' fails, time out reached (%p).\n",
1212        connection->hostname,
1213        connection->port, GNUNET_a2s (connection->addr, connection->addrlen), connection);
1214   notify = connection->nth.notify_ready;
1215   GNUNET_assert (NULL != notify);
1216   connection->nth.notify_ready = NULL;
1217   notify (connection->nth.notify_ready_cls, 0, NULL);
1218 }
1219
1220
1221 /**
1222  * Task invoked by the scheduler when we failed to connect
1223  * at the time of being asked to transmit.
1224  *
1225  * This task notifies the client about the error.
1226  *
1227  * @param cls the 'struct GNUNET_CONNECTION_Handle'
1228  * @param tc scheduler context
1229  */
1230 static void
1231 connect_error (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1232 {
1233   struct GNUNET_CONNECTION_Handle *connection = cls;
1234   GNUNET_CONNECTION_TransmitReadyNotify notify;
1235
1236   LOG (GNUNET_ERROR_TYPE_DEBUG,
1237        "Transmission request of size %u fails (%s/%u), connection failed (%p).\n",
1238        connection->nth.notify_size, connection->hostname, connection->port, connection);
1239   connection->write_task = GNUNET_SCHEDULER_NO_TASK;
1240   notify = connection->nth.notify_ready;
1241   connection->nth.notify_ready = NULL;
1242   notify (connection->nth.notify_ready_cls, 0, NULL);
1243 }
1244
1245
1246 /**
1247  * We are ready to transmit (or got a timeout).
1248  *
1249  * @param cls our connection handle
1250  * @param tc task context describing why we are here
1251  */
1252 static void
1253 transmit_ready (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1254 {
1255   struct GNUNET_CONNECTION_Handle *connection = cls;
1256   GNUNET_CONNECTION_TransmitReadyNotify notify;
1257   ssize_t ret;
1258   size_t have;
1259
1260   LOG (GNUNET_ERROR_TYPE_DEBUG, "transmit_ready running (%p).\n", connection);
1261   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK != connection->write_task);
1262   connection->write_task = GNUNET_SCHEDULER_NO_TASK;
1263   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == connection->nth.timeout_task);
1264   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
1265   {
1266     if (NULL != connection->sock)
1267       goto SCHEDULE_WRITE;      /* ignore shutdown, go again immediately */
1268     LOG (GNUNET_ERROR_TYPE_DEBUG,
1269          "Transmit to `%s' fails, shutdown happened (%p).\n",
1270          GNUNET_a2s (connection->addr, connection->addrlen), connection);
1271     notify = connection->nth.notify_ready;
1272     if (NULL != notify)
1273     {
1274       connection->nth.notify_ready = NULL;
1275       notify (connection->nth.notify_ready_cls, 0, NULL);
1276     }
1277     return;
1278   }
1279   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_TIMEOUT))
1280   {
1281     LOG (GNUNET_ERROR_TYPE_DEBUG,
1282          "Transmit to `%s' fails, time out reached (%p).\n",
1283          GNUNET_a2s (connection->addr, connection->addrlen), connection);
1284     notify = connection->nth.notify_ready;
1285     GNUNET_assert (NULL != notify);
1286     connection->nth.notify_ready = NULL;
1287     notify (connection->nth.notify_ready_cls, 0, NULL);
1288     return;
1289   }
1290   GNUNET_assert (NULL != connection->sock);
1291   if (NULL == tc->write_ready)
1292   {
1293     /* special circumstances (in particular, PREREQ_DONE after
1294      * connect): not yet ready to write, but no "fatal" error either.
1295      * Hence retry.  */
1296     goto SCHEDULE_WRITE;
1297   }
1298   if (!GNUNET_NETWORK_fdset_isset (tc->write_ready, connection->sock))
1299   {
1300     GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == connection->write_task);
1301     /* special circumstances (in particular, shutdown): not yet ready
1302      * to write, but no "fatal" error either.  Hence retry.  */
1303     goto SCHEDULE_WRITE;
1304   }
1305   GNUNET_assert (connection->write_buffer_off >= connection->write_buffer_pos);
1306   if ((NULL != connection->nth.notify_ready) &&
1307       (connection->write_buffer_size < connection->nth.notify_size))
1308   {
1309     connection->write_buffer =
1310         GNUNET_realloc (connection->write_buffer, connection->nth.notify_size);
1311     connection->write_buffer_size = connection->nth.notify_size;
1312   }
1313   process_notify (connection);
1314   have = connection->write_buffer_off - connection->write_buffer_pos;
1315   if (0 == have)
1316   {
1317     /* no data ready for writing, terminate write loop */
1318     return;
1319   }
1320   GNUNET_assert (have <= connection->write_buffer_size);
1321   GNUNET_assert (have + connection->write_buffer_pos <= connection->write_buffer_size);
1322   GNUNET_assert (connection->write_buffer_pos <= connection->write_buffer_size);
1323 RETRY:
1324   ret =
1325       GNUNET_NETWORK_socket_send (connection->sock,
1326                                   &connection->write_buffer[connection->write_buffer_pos],
1327                                   have);
1328   if (-1 == ret)
1329   {
1330     if (EINTR == errno)
1331       goto RETRY;
1332     if (GNUNET_SCHEDULER_NO_TASK != connection->write_task)
1333     {
1334       GNUNET_SCHEDULER_cancel (connection->write_task);
1335       connection->write_task = GNUNET_SCHEDULER_NO_TASK;
1336     }
1337     signal_transmit_error (connection, errno);
1338     return;
1339   }
1340   LOG (GNUNET_ERROR_TYPE_DEBUG,
1341        "Connection transmitted %u/%u bytes to `%s' (%p)\n",
1342        (unsigned int) ret, have, GNUNET_a2s (connection->addr, connection->addrlen), connection);
1343   connection->write_buffer_pos += ret;
1344   if (connection->write_buffer_pos == connection->write_buffer_off)
1345   {
1346     /* transmitted all pending data */
1347     connection->write_buffer_pos = 0;
1348     connection->write_buffer_off = 0;
1349   }
1350   if ((0 == connection->write_buffer_off) && (NULL == connection->nth.notify_ready))
1351     return;                     /* all data sent! */
1352   /* not done writing, schedule more */
1353 SCHEDULE_WRITE:
1354   LOG (GNUNET_ERROR_TYPE_DEBUG,
1355        "Re-scheduling transmit_ready (more to do) (%p).\n", connection);
1356   have = connection->write_buffer_off - connection->write_buffer_pos;
1357   GNUNET_assert ((NULL != connection->nth.notify_ready) || (have > 0));
1358   if (GNUNET_SCHEDULER_NO_TASK == connection->write_task)
1359     connection->write_task =
1360         GNUNET_SCHEDULER_add_write_net ((connection->nth.notify_ready ==
1361                                          NULL) ? GNUNET_TIME_UNIT_FOREVER_REL :
1362                                         GNUNET_TIME_absolute_get_remaining
1363                                         (connection->nth.transmit_timeout),
1364                                         connection->sock, &transmit_ready, connection);
1365 }
1366
1367
1368 /**
1369  * Ask the connection to call us once the specified number of bytes
1370  * are free in the transmission buffer.  May call the notify
1371  * method immediately if enough space is available.
1372  *
1373  * @param connection connection
1374  * @param size number of bytes to send
1375  * @param timeout after how long should we give up (and call
1376  *        notify with buf NULL and size 0)?
1377  * @param notify function to call
1378  * @param notify_cls closure for notify
1379  * @return non-NULL if the notify callback was queued,
1380  *         NULL if we are already going to notify someone else (busy)
1381  */
1382 struct GNUNET_CONNECTION_TransmitHandle *
1383 GNUNET_CONNECTION_notify_transmit_ready (struct GNUNET_CONNECTION_Handle *connection,
1384                                          size_t size,
1385                                          struct GNUNET_TIME_Relative timeout,
1386                                          GNUNET_CONNECTION_TransmitReadyNotify
1387                                          notify, void *notify_cls)
1388 {
1389   if (NULL != connection->nth.notify_ready)
1390   {
1391     GNUNET_assert (0);
1392     return NULL;
1393   }
1394   GNUNET_assert (NULL != notify);
1395   GNUNET_assert (size < GNUNET_SERVER_MAX_MESSAGE_SIZE);
1396   GNUNET_assert (connection->write_buffer_off <= connection->write_buffer_size);
1397   GNUNET_assert (connection->write_buffer_pos <= connection->write_buffer_size);
1398   GNUNET_assert (connection->write_buffer_pos <= connection->write_buffer_off);
1399   connection->nth.notify_ready = notify;
1400   connection->nth.notify_ready_cls = notify_cls;
1401   connection->nth.connection = connection;
1402   connection->nth.notify_size = size;
1403   connection->nth.transmit_timeout = GNUNET_TIME_relative_to_absolute (timeout);
1404   GNUNET_assert (GNUNET_SCHEDULER_NO_TASK == connection->nth.timeout_task);
1405   if ((NULL == connection->sock) &&
1406       (NULL == connection->ap_head) &&
1407       (NULL == connection->dns_active))
1408   {
1409     if (GNUNET_SCHEDULER_NO_TASK != connection->write_task)
1410       GNUNET_SCHEDULER_cancel (connection->write_task);
1411     connection->write_task = GNUNET_SCHEDULER_add_now (&connect_error, connection);
1412     return &connection->nth;
1413   }
1414   if (GNUNET_SCHEDULER_NO_TASK != connection->write_task)
1415     return &connection->nth; /* previous transmission still in progress */
1416   if (NULL != connection->sock)
1417   {
1418     /* connected, try to transmit now */
1419     LOG (GNUNET_ERROR_TYPE_DEBUG, "Scheduling transmission (%p).\n", connection);
1420     connection->write_task =
1421         GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_absolute_get_remaining
1422                                         (connection->nth.transmit_timeout),
1423                                         connection->sock, &transmit_ready, connection);
1424     return &connection->nth;
1425   }
1426   /* not yet connected, wait for connection */
1427   LOG (GNUNET_ERROR_TYPE_DEBUG,
1428        "Need to wait to schedule transmission for connection, adding timeout task (%p).\n", connection);
1429   connection->nth.timeout_task =
1430     GNUNET_SCHEDULER_add_delayed (timeout, &transmit_timeout, connection);
1431   return &connection->nth;
1432 }
1433
1434
1435 /**
1436  * Cancel the specified transmission-ready notification.
1437  *
1438  * @param th notification to cancel
1439  */
1440 void
1441 GNUNET_CONNECTION_notify_transmit_ready_cancel (struct
1442                                                 GNUNET_CONNECTION_TransmitHandle
1443                                                 *th)
1444 {
1445   GNUNET_assert (NULL != th->notify_ready);
1446   th->notify_ready = NULL;
1447   if (GNUNET_SCHEDULER_NO_TASK != th->timeout_task)
1448   {
1449     GNUNET_SCHEDULER_cancel (th->timeout_task);
1450     th->timeout_task = GNUNET_SCHEDULER_NO_TASK;
1451   }
1452   if (GNUNET_SCHEDULER_NO_TASK != th->connection->write_task)
1453   {
1454     GNUNET_SCHEDULER_cancel (th->connection->write_task);
1455     th->connection->write_task = GNUNET_SCHEDULER_NO_TASK;
1456   }
1457 }
1458
1459 /* end of connection.c */