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