Bug 896 - Avoid race conditions reading message from exited process
[platform/upstream/dbus.git] / dbus / dbus-transport-socket.c
1 /* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */
2 /* dbus-transport-socket.c  Socket subclasses of DBusTransport
3  *
4  * Copyright (C) 2002, 2003, 2004, 2006  Red Hat Inc.
5  *
6  * Licensed under the Academic Free License version 2.1
7  * 
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  * 
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
21  *
22  */
23
24 #include "dbus-internals.h"
25 #include "dbus-connection-internal.h"
26 #include "dbus-transport-socket.h"
27 #include "dbus-transport-protected.h"
28 #include "dbus-watch.h"
29 #include "dbus-credentials.h"
30
31
32 /**
33  * @defgroup DBusTransportSocket DBusTransport implementations for sockets
34  * @ingroup  DBusInternals
35  * @brief Implementation details of DBusTransport on sockets
36  *
37  * @{
38  */
39
40 /**
41  * Opaque object representing a socket file descriptor transport.
42  */
43 typedef struct DBusTransportSocket DBusTransportSocket;
44
45 /**
46  * Implementation details of DBusTransportSocket. All members are private.
47  */
48 struct DBusTransportSocket
49 {
50   DBusTransport base;                   /**< Parent instance */
51   int fd;                               /**< File descriptor. */
52   DBusWatch *read_watch;                /**< Watch for readability. */
53   DBusWatch *write_watch;               /**< Watch for writability. */
54
55   int max_bytes_read_per_iteration;     /**< To avoid blocking too long. */
56   int max_bytes_written_per_iteration;  /**< To avoid blocking too long. */
57
58   int message_bytes_written;            /**< Number of bytes of current
59                                          *   outgoing message that have
60                                          *   been written.
61                                          */
62   DBusString encoded_outgoing;          /**< Encoded version of current
63                                          *   outgoing message.
64                                          */
65   DBusString encoded_incoming;          /**< Encoded version of current
66                                          *   incoming data.
67                                          */
68 };
69
70 static void
71 free_watches (DBusTransport *transport)
72 {
73   DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
74
75   _dbus_verbose ("%s start\n", _DBUS_FUNCTION_NAME);
76   
77   if (socket_transport->read_watch)
78     {
79       if (transport->connection)
80         _dbus_connection_remove_watch_unlocked (transport->connection,
81                                                 socket_transport->read_watch);
82       _dbus_watch_invalidate (socket_transport->read_watch);
83       _dbus_watch_unref (socket_transport->read_watch);
84       socket_transport->read_watch = NULL;
85     }
86
87   if (socket_transport->write_watch)
88     {
89       if (transport->connection)
90         _dbus_connection_remove_watch_unlocked (transport->connection,
91                                                 socket_transport->write_watch);
92       _dbus_watch_invalidate (socket_transport->write_watch);
93       _dbus_watch_unref (socket_transport->write_watch);
94       socket_transport->write_watch = NULL;
95     }
96
97   _dbus_verbose ("%s end\n", _DBUS_FUNCTION_NAME);
98 }
99
100 static void
101 socket_finalize (DBusTransport *transport)
102 {
103   DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
104
105   _dbus_verbose ("%s\n", _DBUS_FUNCTION_NAME);
106   
107   free_watches (transport);
108
109   _dbus_string_free (&socket_transport->encoded_outgoing);
110   _dbus_string_free (&socket_transport->encoded_incoming);
111   
112   _dbus_transport_finalize_base (transport);
113
114   _dbus_assert (socket_transport->read_watch == NULL);
115   _dbus_assert (socket_transport->write_watch == NULL);
116   
117   dbus_free (transport);
118 }
119
120 static void
121 check_write_watch (DBusTransport *transport)
122 {
123   DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
124   dbus_bool_t needed;
125
126   if (transport->connection == NULL)
127     return;
128
129   if (transport->disconnected)
130     {
131       _dbus_assert (socket_transport->write_watch == NULL);
132       return;
133     }
134   
135   _dbus_transport_ref (transport);
136
137   if (_dbus_transport_get_is_authenticated (transport))
138     needed = _dbus_connection_has_messages_to_send_unlocked (transport->connection);
139   else
140     {
141       if (transport->send_credentials_pending)
142         needed = TRUE;
143       else
144         {
145           DBusAuthState auth_state;
146           
147           auth_state = _dbus_auth_do_work (transport->auth);
148           
149           /* If we need memory we install the write watch just in case,
150            * if there's no need for it, it will get de-installed
151            * next time we try reading.
152            */
153           if (auth_state == DBUS_AUTH_STATE_HAVE_BYTES_TO_SEND ||
154               auth_state == DBUS_AUTH_STATE_WAITING_FOR_MEMORY)
155             needed = TRUE;
156           else
157             needed = FALSE;
158         }
159     }
160
161   _dbus_verbose ("check_write_watch(): needed = %d on connection %p watch %p fd = %d outgoing messages exist %d\n",
162                  needed, transport->connection, socket_transport->write_watch,
163                  socket_transport->fd,
164                  _dbus_connection_has_messages_to_send_unlocked (transport->connection));
165
166   _dbus_connection_toggle_watch_unlocked (transport->connection,
167                                           socket_transport->write_watch,
168                                           needed);
169
170   _dbus_transport_unref (transport);
171 }
172
173 static void
174 check_read_watch (DBusTransport *transport)
175 {
176   DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
177   dbus_bool_t need_read_watch;
178
179   _dbus_verbose ("%s: fd = %d\n",
180                  _DBUS_FUNCTION_NAME, socket_transport->fd);
181   
182   if (transport->connection == NULL)
183     return;
184
185   if (transport->disconnected)
186     {
187       _dbus_assert (socket_transport->read_watch == NULL);
188       return;
189     }
190   
191   _dbus_transport_ref (transport);
192
193   if (_dbus_transport_get_is_authenticated (transport))
194     need_read_watch =
195       _dbus_counter_get_value (transport->live_messages_size) < transport->max_live_messages_size;
196   else
197     {
198       if (transport->receive_credentials_pending)
199         need_read_watch = TRUE;
200       else
201         {
202           /* The reason to disable need_read_watch when not WAITING_FOR_INPUT
203            * is to avoid spinning on the file descriptor when we're waiting
204            * to write or for some other part of the auth process
205            */
206           DBusAuthState auth_state;
207           
208           auth_state = _dbus_auth_do_work (transport->auth);
209
210           /* If we need memory we install the read watch just in case,
211            * if there's no need for it, it will get de-installed
212            * next time we try reading. If we're authenticated we
213            * install it since we normally have it installed while
214            * authenticated.
215            */
216           if (auth_state == DBUS_AUTH_STATE_WAITING_FOR_INPUT ||
217               auth_state == DBUS_AUTH_STATE_WAITING_FOR_MEMORY ||
218               auth_state == DBUS_AUTH_STATE_AUTHENTICATED)
219             need_read_watch = TRUE;
220           else
221             need_read_watch = FALSE;
222         }
223     }
224
225   _dbus_verbose ("  setting read watch enabled = %d\n", need_read_watch);
226   _dbus_connection_toggle_watch_unlocked (transport->connection,
227                                           socket_transport->read_watch,
228                                           need_read_watch);
229
230   _dbus_transport_unref (transport);
231 }
232
233 static void
234 do_io_error (DBusTransport *transport)
235 {
236   _dbus_transport_ref (transport);
237   _dbus_transport_disconnect (transport);
238   _dbus_transport_unref (transport);
239 }
240
241 /* return value is whether we successfully read any new data. */
242 static dbus_bool_t
243 read_data_into_auth (DBusTransport *transport,
244                      dbus_bool_t   *oom)
245 {
246   DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
247   DBusString *buffer;
248   int bytes_read;
249   
250   *oom = FALSE;
251
252   _dbus_auth_get_buffer (transport->auth, &buffer);
253   
254   bytes_read = _dbus_read_socket (socket_transport->fd,
255                                   buffer, socket_transport->max_bytes_read_per_iteration);
256
257   _dbus_auth_return_buffer (transport->auth, buffer,
258                             bytes_read > 0 ? bytes_read : 0);
259
260   if (bytes_read > 0)
261     {
262       _dbus_verbose (" read %d bytes in auth phase\n", bytes_read);
263
264       return TRUE;
265     }
266   else if (bytes_read < 0)
267     {
268       /* EINTR already handled for us */
269
270       if (_dbus_get_is_errno_enomem ())
271         {
272           *oom = TRUE;
273         }
274       else if (_dbus_get_is_errno_eagain_or_ewouldblock ())
275         ; /* do nothing, just return FALSE below */
276       else
277         {
278           _dbus_verbose ("Error reading from remote app: %s\n",
279                          _dbus_strerror_from_errno ());
280           do_io_error (transport);
281         }
282
283       return FALSE;
284     }
285   else
286     {
287       _dbus_assert (bytes_read == 0);
288       
289       _dbus_verbose ("Disconnected from remote app\n");
290       do_io_error (transport);
291
292       return FALSE;
293     }
294 }
295
296 /* Return value is whether we successfully wrote any bytes */
297 static dbus_bool_t
298 write_data_from_auth (DBusTransport *transport)
299 {
300   DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
301   int bytes_written;
302   const DBusString *buffer;
303
304   if (!_dbus_auth_get_bytes_to_send (transport->auth,
305                                      &buffer))
306     return FALSE;
307   
308   bytes_written = _dbus_write_socket (socket_transport->fd,
309                                       buffer,
310                                       0, _dbus_string_get_length (buffer));
311
312   if (bytes_written > 0)
313     {
314       _dbus_auth_bytes_sent (transport->auth, bytes_written);
315       return TRUE;
316     }
317   else if (bytes_written < 0)
318     {
319       /* EINTR already handled for us */
320       
321       if (_dbus_get_is_errno_eagain_or_ewouldblock ())
322         ;
323       else
324         {
325           _dbus_verbose ("Error writing to remote app: %s\n",
326                          _dbus_strerror_from_errno ());
327           do_io_error (transport);
328         }
329     }
330
331   return FALSE;
332 }
333
334 /* FALSE on OOM */
335 static dbus_bool_t
336 exchange_credentials (DBusTransport *transport,
337                       dbus_bool_t    do_reading,
338                       dbus_bool_t    do_writing)
339 {
340   DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
341   DBusError error = DBUS_ERROR_INIT;
342
343   _dbus_verbose ("exchange_credentials: do_reading = %d, do_writing = %d\n",
344                   do_reading, do_writing);
345
346   if (do_writing && transport->send_credentials_pending)
347     {
348       if (_dbus_send_credentials_socket (socket_transport->fd,
349                                          &error))
350         {
351           transport->send_credentials_pending = FALSE;
352         }
353       else
354         {
355           _dbus_verbose ("Failed to write credentials: %s\n", error.message);
356           dbus_error_free (&error);
357           do_io_error (transport);
358         }
359     }
360   
361   if (do_reading && transport->receive_credentials_pending)
362     {
363       /* FIXME this can fail due to IO error _or_ OOM, broken
364        * (somewhat tricky to fix since the OOM error can be set after
365        * we already read the credentials byte, so basically we need to
366        * separate reading the byte and storing it in the
367        * transport->credentials). Does not really matter for now
368        * because storing in credentials never actually fails on unix.
369        */      
370       if (_dbus_read_credentials_socket (socket_transport->fd,
371                                          transport->credentials,
372                                          &error))
373         {
374           transport->receive_credentials_pending = FALSE;
375         }
376       else
377         {
378           _dbus_verbose ("Failed to read credentials %s\n", error.message);
379           dbus_error_free (&error);
380           do_io_error (transport);
381         }
382     }
383
384   if (!(transport->send_credentials_pending ||
385         transport->receive_credentials_pending))
386     {
387       if (!_dbus_auth_set_credentials (transport->auth,
388                                        transport->credentials))
389         return FALSE;
390     }
391
392   return TRUE;
393 }
394
395 static dbus_bool_t
396 do_authentication (DBusTransport *transport,
397                    dbus_bool_t    do_reading,
398                    dbus_bool_t    do_writing,
399                    dbus_bool_t   *auth_completed)
400 {
401   dbus_bool_t oom;
402   dbus_bool_t orig_auth_state;
403
404   oom = FALSE;
405   
406   orig_auth_state = _dbus_transport_get_is_authenticated (transport);
407
408   /* This is essential to avoid the check_write_watch() at the end,
409    * we don't want to add a write watch in do_iteration before
410    * we try writing and get EAGAIN
411    */
412   if (orig_auth_state)
413     {
414       if (auth_completed)
415         *auth_completed = FALSE;
416       return TRUE;
417     }
418   
419   _dbus_transport_ref (transport);
420   
421   while (!_dbus_transport_get_is_authenticated (transport) &&
422          _dbus_transport_get_is_connected (transport))
423     {      
424       if (!exchange_credentials (transport, do_reading, do_writing))
425         {
426           /* OOM */
427           oom = TRUE;
428           goto out;
429         }
430       
431       if (transport->send_credentials_pending ||
432           transport->receive_credentials_pending)
433         {
434           _dbus_verbose ("send_credentials_pending = %d receive_credentials_pending = %d\n",
435                          transport->send_credentials_pending,
436                          transport->receive_credentials_pending);
437           goto out;
438         }
439
440 #define TRANSPORT_SIDE(t) ((t)->is_server ? "server" : "client")
441       switch (_dbus_auth_do_work (transport->auth))
442         {
443         case DBUS_AUTH_STATE_WAITING_FOR_INPUT:
444           _dbus_verbose (" %s auth state: waiting for input\n",
445                          TRANSPORT_SIDE (transport));
446           if (!do_reading || !read_data_into_auth (transport, &oom))
447             goto out;
448           break;
449       
450         case DBUS_AUTH_STATE_WAITING_FOR_MEMORY:
451           _dbus_verbose (" %s auth state: waiting for memory\n",
452                          TRANSPORT_SIDE (transport));
453           oom = TRUE;
454           goto out;
455           break;
456       
457         case DBUS_AUTH_STATE_HAVE_BYTES_TO_SEND:
458           _dbus_verbose (" %s auth state: bytes to send\n",
459                          TRANSPORT_SIDE (transport));
460           if (!do_writing || !write_data_from_auth (transport))
461             goto out;
462           break;
463       
464         case DBUS_AUTH_STATE_NEED_DISCONNECT:
465           _dbus_verbose (" %s auth state: need to disconnect\n",
466                          TRANSPORT_SIDE (transport));
467           do_io_error (transport);
468           break;
469       
470         case DBUS_AUTH_STATE_AUTHENTICATED:
471           _dbus_verbose (" %s auth state: authenticated\n",
472                          TRANSPORT_SIDE (transport));
473           break;
474         }
475     }
476
477  out:
478   if (auth_completed)
479     *auth_completed = (orig_auth_state != _dbus_transport_get_is_authenticated (transport));
480   
481   check_read_watch (transport);
482   check_write_watch (transport);
483   _dbus_transport_unref (transport);
484
485   if (oom)
486     return FALSE;
487   else
488     return TRUE;
489 }
490
491 /* returns false on oom */
492 static dbus_bool_t
493 do_writing (DBusTransport *transport)
494 {
495   int total;
496   DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
497   dbus_bool_t oom;
498   
499   /* No messages without authentication! */
500   if (!_dbus_transport_get_is_authenticated (transport))
501     {
502       _dbus_verbose ("Not authenticated, not writing anything\n");
503       return TRUE;
504     }
505
506   if (transport->disconnected)
507     {
508       _dbus_verbose ("Not connected, not writing anything\n");
509       return TRUE;
510     }
511
512 #if 1
513   _dbus_verbose ("do_writing(), have_messages = %d, fd = %d\n",
514                  _dbus_connection_has_messages_to_send_unlocked (transport->connection),
515                  socket_transport->fd);
516 #endif
517   
518   oom = FALSE;
519   total = 0;
520
521   while (!transport->disconnected &&
522          _dbus_connection_has_messages_to_send_unlocked (transport->connection))
523     {
524       int bytes_written;
525       DBusMessage *message;
526       const DBusString *header;
527       const DBusString *body;
528       int header_len, body_len;
529       int total_bytes_to_write;
530       
531       if (total > socket_transport->max_bytes_written_per_iteration)
532         {
533           _dbus_verbose ("%d bytes exceeds %d bytes written per iteration, returning\n",
534                          total, socket_transport->max_bytes_written_per_iteration);
535           goto out;
536         }
537       
538       message = _dbus_connection_get_message_to_send (transport->connection);
539       _dbus_assert (message != NULL);
540       dbus_message_lock (message);
541
542 #if 0
543       _dbus_verbose ("writing message %p\n", message);
544 #endif
545       
546       _dbus_message_get_network_data (message,
547                                       &header, &body);
548
549       header_len = _dbus_string_get_length (header);
550       body_len = _dbus_string_get_length (body);
551
552       if (_dbus_auth_needs_encoding (transport->auth))
553         {
554           if (_dbus_string_get_length (&socket_transport->encoded_outgoing) == 0)
555             {
556               if (!_dbus_auth_encode_data (transport->auth,
557                                            header, &socket_transport->encoded_outgoing))
558                 {
559                   oom = TRUE;
560                   goto out;
561                 }
562               
563               if (!_dbus_auth_encode_data (transport->auth,
564                                            body, &socket_transport->encoded_outgoing))
565                 {
566                   _dbus_string_set_length (&socket_transport->encoded_outgoing, 0);
567                   oom = TRUE;
568                   goto out;
569                 }
570             }
571           
572           total_bytes_to_write = _dbus_string_get_length (&socket_transport->encoded_outgoing);
573
574 #if 0
575           _dbus_verbose ("encoded message is %d bytes\n",
576                          total_bytes_to_write);
577 #endif
578           
579           bytes_written =
580             _dbus_write_socket (socket_transport->fd,
581                                 &socket_transport->encoded_outgoing,
582                                 socket_transport->message_bytes_written,
583                                 total_bytes_to_write - socket_transport->message_bytes_written);
584         }
585       else
586         {
587           total_bytes_to_write = header_len + body_len;
588
589 #if 0
590           _dbus_verbose ("message is %d bytes\n",
591                          total_bytes_to_write);          
592 #endif
593           
594           if (socket_transport->message_bytes_written < header_len)
595             {
596               bytes_written =
597                 _dbus_write_socket_two (socket_transport->fd,
598                                         header,
599                                         socket_transport->message_bytes_written,
600                                         header_len - socket_transport->message_bytes_written,
601                                         body,
602                                         0, body_len);
603             }
604           else
605             {
606               bytes_written =
607                 _dbus_write_socket (socket_transport->fd,
608                                     body,
609                                     (socket_transport->message_bytes_written - header_len),
610                                     body_len -
611                                     (socket_transport->message_bytes_written - header_len));
612             }
613         }
614
615       if (bytes_written < 0)
616         {
617           /* EINTR already handled for us */
618           
619           /* For some discussion of why we also ignore EPIPE here, see
620            * http://lists.freedesktop.org/archives/dbus/2008-March/009526.html
621            */
622           
623           if (_dbus_get_is_errno_eagain_or_ewouldblock () || _dbus_get_is_errno_epipe ())
624             goto out;
625           else
626             {
627               _dbus_verbose ("Error writing to remote app: %s\n",
628                              _dbus_strerror_from_errno ());
629               do_io_error (transport);
630               goto out;
631             }
632         }
633       else
634         {
635           _dbus_verbose (" wrote %d bytes of %d\n", bytes_written,
636                          total_bytes_to_write);
637           
638           total += bytes_written;
639           socket_transport->message_bytes_written += bytes_written;
640
641           _dbus_assert (socket_transport->message_bytes_written <=
642                         total_bytes_to_write);
643           
644           if (socket_transport->message_bytes_written == total_bytes_to_write)
645             {
646               socket_transport->message_bytes_written = 0;
647               _dbus_string_set_length (&socket_transport->encoded_outgoing, 0);
648               _dbus_string_compact (&socket_transport->encoded_outgoing, 2048);
649
650               _dbus_connection_message_sent (transport->connection,
651                                              message);
652             }
653         }
654     }
655
656  out:
657   if (oom)
658     return FALSE;
659   else
660     return TRUE;
661 }
662
663 /* returns false on out-of-memory */
664 static dbus_bool_t
665 do_reading (DBusTransport *transport)
666 {
667   DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
668   DBusString *buffer;
669   int bytes_read;
670   int total;
671   dbus_bool_t oom;
672
673   _dbus_verbose ("%s: fd = %d\n", _DBUS_FUNCTION_NAME,
674                  socket_transport->fd);
675   
676   /* No messages without authentication! */
677   if (!_dbus_transport_get_is_authenticated (transport))
678     return TRUE;
679
680   oom = FALSE;
681   
682   total = 0;
683
684  again:
685   
686   /* See if we've exceeded max messages and need to disable reading */
687   check_read_watch (transport);
688   
689   if (total > socket_transport->max_bytes_read_per_iteration)
690     {
691       _dbus_verbose ("%d bytes exceeds %d bytes read per iteration, returning\n",
692                      total, socket_transport->max_bytes_read_per_iteration);
693       goto out;
694     }
695
696   _dbus_assert (socket_transport->read_watch != NULL ||
697                 transport->disconnected);
698   
699   if (transport->disconnected)
700     goto out;
701
702   if (!dbus_watch_get_enabled (socket_transport->read_watch))
703     return TRUE;
704   
705   if (_dbus_auth_needs_decoding (transport->auth))
706     {
707       if (_dbus_string_get_length (&socket_transport->encoded_incoming) > 0)
708         bytes_read = _dbus_string_get_length (&socket_transport->encoded_incoming);
709       else
710         bytes_read = _dbus_read_socket (socket_transport->fd,
711                                         &socket_transport->encoded_incoming,
712                                         socket_transport->max_bytes_read_per_iteration);
713
714       _dbus_assert (_dbus_string_get_length (&socket_transport->encoded_incoming) ==
715                     bytes_read);
716       
717       if (bytes_read > 0)
718         {
719           int orig_len;
720           
721           _dbus_message_loader_get_buffer (transport->loader,
722                                            &buffer);
723
724           orig_len = _dbus_string_get_length (buffer);
725           
726           if (!_dbus_auth_decode_data (transport->auth,
727                                        &socket_transport->encoded_incoming,
728                                        buffer))
729             {
730               _dbus_verbose ("Out of memory decoding incoming data\n");
731               _dbus_message_loader_return_buffer (transport->loader,
732                                               buffer,
733                                               _dbus_string_get_length (buffer) - orig_len);
734
735               oom = TRUE;
736               goto out;
737             }
738
739           _dbus_message_loader_return_buffer (transport->loader,
740                                               buffer,
741                                               _dbus_string_get_length (buffer) - orig_len);
742
743           _dbus_string_set_length (&socket_transport->encoded_incoming, 0);
744           _dbus_string_compact (&socket_transport->encoded_incoming, 2048);
745         }
746     }
747   else
748     {
749       _dbus_message_loader_get_buffer (transport->loader,
750                                        &buffer);
751       
752       bytes_read = _dbus_read_socket (socket_transport->fd,
753                                       buffer, socket_transport->max_bytes_read_per_iteration);
754       
755       _dbus_message_loader_return_buffer (transport->loader,
756                                           buffer,
757                                           bytes_read < 0 ? 0 : bytes_read);
758     }
759   
760   if (bytes_read < 0)
761     {
762       /* EINTR already handled for us */
763
764       if (_dbus_get_is_errno_enomem ())
765         {
766           _dbus_verbose ("Out of memory in read()/do_reading()\n");
767           oom = TRUE;
768           goto out;
769         }
770       else if (_dbus_get_is_errno_eagain_or_ewouldblock ())
771         goto out;
772       else
773         {
774           _dbus_verbose ("Error reading from remote app: %s\n",
775                          _dbus_strerror_from_errno ());
776           do_io_error (transport);
777           goto out;
778         }
779     }
780   else if (bytes_read == 0)
781     {
782       _dbus_verbose ("Disconnected from remote app\n");
783       do_io_error (transport);
784       goto out;
785     }
786   else
787     {
788       _dbus_verbose (" read %d bytes\n", bytes_read);
789       
790       total += bytes_read;      
791
792       if (!_dbus_transport_queue_messages (transport))
793         {
794           oom = TRUE;
795           _dbus_verbose (" out of memory when queueing messages we just read in the transport\n");
796           goto out;
797         }
798       
799       /* Try reading more data until we get EAGAIN and return, or
800        * exceed max bytes per iteration.  If in blocking mode of
801        * course we'll block instead of returning.
802        */
803       goto again;
804     }
805
806  out:
807   if (oom)
808     return FALSE;
809   else
810     return TRUE;
811 }
812
813 static dbus_bool_t
814 unix_error_with_read_to_come (DBusTransport *itransport,
815                               DBusWatch     *watch,
816                               unsigned int   flags)
817 {
818   DBusTransportSocket *transport = (DBusTransportSocket *) itransport;
819
820   if (!(flags & DBUS_WATCH_HANGUP || flags & DBUS_WATCH_ERROR))
821     return FALSE;
822    
823   /* If we have a read watch enabled ...
824      we -might have data incoming ... => handle the HANGUP there */
825   if (watch != transport->read_watch &&
826       _dbus_watch_get_enabled (transport->read_watch))
827     return FALSE;
828       
829   return TRUE; 
830 }
831
832 static dbus_bool_t
833 socket_handle_watch (DBusTransport *transport,
834                    DBusWatch     *watch,
835                    unsigned int   flags)
836 {
837   DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
838
839   _dbus_assert (watch == socket_transport->read_watch ||
840                 watch == socket_transport->write_watch);
841   _dbus_assert (watch != NULL);
842   
843   /* If we hit an error here on a write watch, don't disconnect the transport yet because data can
844    * still be in the buffer and do_reading may need several iteration to read
845    * it all (because of its max_bytes_read_per_iteration limit). 
846    */
847   if (!(flags & DBUS_WATCH_READABLE) && unix_error_with_read_to_come (transport, watch, flags))
848     {
849       _dbus_verbose ("Hang up or error on watch\n");
850       _dbus_transport_disconnect (transport);
851       return TRUE;
852     }
853   
854   if (watch == socket_transport->read_watch &&
855       (flags & DBUS_WATCH_READABLE))
856     {
857       dbus_bool_t auth_finished;
858 #if 1
859       _dbus_verbose ("handling read watch %p flags = %x\n",
860                      watch, flags);
861 #endif
862       if (!do_authentication (transport, TRUE, FALSE, &auth_finished))
863         return FALSE;
864
865       /* We don't want to do a read immediately following
866        * a successful authentication.  This is so we
867        * have a chance to propagate the authentication
868        * state further up.  Specifically, we need to
869        * process any pending data from the auth object.
870        */
871       if (!auth_finished)
872         {
873           if (!do_reading (transport))
874             {
875               _dbus_verbose ("no memory to read\n");
876               return FALSE;
877             }
878         }
879       else
880         {
881           _dbus_verbose ("Not reading anything since we just completed the authentication\n");
882         }
883     }
884   else if (watch == socket_transport->write_watch &&
885            (flags & DBUS_WATCH_WRITABLE))
886     {
887 #if 1
888       _dbus_verbose ("handling write watch, have_outgoing_messages = %d\n",
889                      _dbus_connection_has_messages_to_send_unlocked (transport->connection));
890 #endif
891       if (!do_authentication (transport, FALSE, TRUE, NULL))
892         return FALSE;
893       
894       if (!do_writing (transport))
895         {
896           _dbus_verbose ("no memory to write\n");
897           return FALSE;
898         }
899
900       /* See if we still need the write watch */
901       check_write_watch (transport);
902     }
903 #ifdef DBUS_ENABLE_VERBOSE_MODE
904   else
905     {
906       if (watch == socket_transport->read_watch)
907         _dbus_verbose ("asked to handle read watch with non-read condition 0x%x\n",
908                        flags);
909       else if (watch == socket_transport->write_watch)
910         _dbus_verbose ("asked to handle write watch with non-write condition 0x%x\n",
911                        flags);
912       else
913         _dbus_verbose ("asked to handle watch %p on fd %d that we don't recognize\n",
914                        watch, dbus_watch_get_socket (watch));
915     }
916 #endif /* DBUS_ENABLE_VERBOSE_MODE */
917
918   return TRUE;
919 }
920
921 static void
922 socket_disconnect (DBusTransport *transport)
923 {
924   DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
925
926   _dbus_verbose ("%s\n", _DBUS_FUNCTION_NAME);
927   
928   free_watches (transport);
929   
930   _dbus_close_socket (socket_transport->fd, NULL);
931   socket_transport->fd = -1;
932 }
933
934 static dbus_bool_t
935 socket_connection_set (DBusTransport *transport)
936 {
937   DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
938
939   _dbus_watch_set_handler (socket_transport->write_watch,
940                            _dbus_connection_handle_watch,
941                            transport->connection, NULL);
942
943   _dbus_watch_set_handler (socket_transport->read_watch,
944                            _dbus_connection_handle_watch,
945                            transport->connection, NULL);
946   
947   if (!_dbus_connection_add_watch_unlocked (transport->connection,
948                                             socket_transport->write_watch))
949     return FALSE;
950
951   if (!_dbus_connection_add_watch_unlocked (transport->connection,
952                                             socket_transport->read_watch))
953     {
954       _dbus_connection_remove_watch_unlocked (transport->connection,
955                                               socket_transport->write_watch);
956       return FALSE;
957     }
958
959   check_read_watch (transport);
960   check_write_watch (transport);
961
962   return TRUE;
963 }
964
965 /**
966  * @todo We need to have a way to wake up the select sleep if
967  * a new iteration request comes in with a flag (read/write) that
968  * we're not currently serving. Otherwise a call that just reads
969  * could block a write call forever (if there are no incoming
970  * messages).
971  */
972 static  void
973 socket_do_iteration (DBusTransport *transport,
974                    unsigned int   flags,
975                    int            timeout_milliseconds)
976 {
977   DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
978   DBusPollFD poll_fd;
979   int poll_res;
980   int poll_timeout;
981
982   _dbus_verbose (" iteration flags = %s%s timeout = %d read_watch = %p write_watch = %p fd = %d\n",
983                  flags & DBUS_ITERATION_DO_READING ? "read" : "",
984                  flags & DBUS_ITERATION_DO_WRITING ? "write" : "",
985                  timeout_milliseconds,
986                  socket_transport->read_watch,
987                  socket_transport->write_watch,
988                  socket_transport->fd);
989   
990   /* the passed in DO_READING/DO_WRITING flags indicate whether to
991    * read/write messages, but regardless of those we may need to block
992    * for reading/writing to do auth.  But if we do reading for auth,
993    * we don't want to read any messages yet if not given DO_READING.
994    */
995
996   poll_fd.fd = socket_transport->fd;
997   poll_fd.events = 0;
998   
999   if (_dbus_transport_get_is_authenticated (transport))
1000     {
1001       /* This is kind of a hack; if we have stuff to write, then try
1002        * to avoid the poll. This is probably about a 5% speedup on an
1003        * echo client/server.
1004        *
1005        * If both reading and writing were requested, we want to avoid this
1006        * since it could have funky effects:
1007        *   - both ends spinning waiting for the other one to read
1008        *     data so they can finish writing
1009        *   - prioritizing all writing ahead of reading
1010        */
1011       if ((flags & DBUS_ITERATION_DO_WRITING) &&
1012           !(flags & (DBUS_ITERATION_DO_READING | DBUS_ITERATION_BLOCK)) &&
1013           !transport->disconnected &&
1014           _dbus_connection_has_messages_to_send_unlocked (transport->connection))
1015         {
1016           do_writing (transport);
1017
1018           if (transport->disconnected ||
1019               !_dbus_connection_has_messages_to_send_unlocked (transport->connection))
1020             goto out;
1021         }
1022
1023       /* If we get here, we decided to do the poll() after all */
1024       _dbus_assert (socket_transport->read_watch);
1025       if (flags & DBUS_ITERATION_DO_READING)
1026         poll_fd.events |= _DBUS_POLLIN;
1027
1028       _dbus_assert (socket_transport->write_watch);
1029       if (flags & DBUS_ITERATION_DO_WRITING)
1030         poll_fd.events |= _DBUS_POLLOUT;
1031     }
1032   else
1033     {
1034       DBusAuthState auth_state;
1035       
1036       auth_state = _dbus_auth_do_work (transport->auth);
1037
1038       if (transport->receive_credentials_pending ||
1039           auth_state == DBUS_AUTH_STATE_WAITING_FOR_INPUT)
1040         poll_fd.events |= _DBUS_POLLIN;
1041
1042       if (transport->send_credentials_pending ||
1043           auth_state == DBUS_AUTH_STATE_HAVE_BYTES_TO_SEND)
1044         poll_fd.events |= _DBUS_POLLOUT;
1045     }
1046
1047   if (poll_fd.events)
1048     {
1049       if (flags & DBUS_ITERATION_BLOCK)
1050         poll_timeout = timeout_milliseconds;
1051       else
1052         poll_timeout = 0;
1053
1054       /* For blocking selects we drop the connection lock here
1055        * to avoid blocking out connection access during a potentially
1056        * indefinite blocking call. The io path is still protected
1057        * by the io_path_cond condvar, so we won't reenter this.
1058        */
1059       if (flags & DBUS_ITERATION_BLOCK)
1060         {
1061           _dbus_verbose ("unlock %s pre poll\n", _DBUS_FUNCTION_NAME);
1062           _dbus_connection_unlock (transport->connection);
1063         }
1064       
1065     again:
1066       poll_res = _dbus_poll (&poll_fd, 1, poll_timeout);
1067
1068       if (poll_res < 0 && _dbus_get_is_errno_eintr ())
1069         goto again;
1070
1071       if (flags & DBUS_ITERATION_BLOCK)
1072         {
1073           _dbus_verbose ("lock %s post poll\n", _DBUS_FUNCTION_NAME);
1074           _dbus_connection_lock (transport->connection);
1075         }
1076       
1077       if (poll_res >= 0)
1078         {
1079           if (poll_res == 0)
1080             poll_fd.revents = 0; /* some concern that posix does not guarantee this;
1081                                   * valgrind flags it as an error. though it probably
1082                                   * is guaranteed on linux at least.
1083                                   */
1084           
1085           if (poll_fd.revents & _DBUS_POLLERR)
1086             do_io_error (transport);
1087           else
1088             {
1089               dbus_bool_t need_read = (poll_fd.revents & _DBUS_POLLIN) > 0;
1090               dbus_bool_t need_write = (poll_fd.revents & _DBUS_POLLOUT) > 0;
1091               dbus_bool_t authentication_completed;
1092
1093               _dbus_verbose ("in iteration, need_read=%d need_write=%d\n",
1094                              need_read, need_write);
1095               do_authentication (transport, need_read, need_write,
1096                                  &authentication_completed);
1097
1098               /* See comment in socket_handle_watch. */
1099               if (authentication_completed)
1100                 goto out;
1101                                  
1102               if (need_read && (flags & DBUS_ITERATION_DO_READING))
1103                 do_reading (transport);
1104               if (need_write && (flags & DBUS_ITERATION_DO_WRITING))
1105                 do_writing (transport);
1106             }
1107         }
1108       else
1109         {
1110           _dbus_verbose ("Error from _dbus_poll(): %s\n",
1111                          _dbus_strerror_from_errno ());
1112         }
1113     }
1114
1115
1116  out:
1117   /* We need to install the write watch only if we did not
1118    * successfully write everything. Note we need to be careful that we
1119    * don't call check_write_watch *before* do_writing, since it's
1120    * inefficient to add the write watch, and we can avoid it most of
1121    * the time since we can write immediately.
1122    * 
1123    * However, we MUST always call check_write_watch(); DBusConnection code
1124    * relies on the fact that running an iteration will notice that
1125    * messages are pending.
1126    */
1127   check_write_watch (transport);
1128
1129   _dbus_verbose (" ... leaving do_iteration()\n");
1130 }
1131
1132 static void
1133 socket_live_messages_changed (DBusTransport *transport)
1134 {
1135   /* See if we should look for incoming messages again */
1136   check_read_watch (transport);
1137 }
1138
1139
1140 static dbus_bool_t
1141 socket_get_socket_fd (DBusTransport *transport,
1142                       int           *fd_p)
1143 {
1144   DBusTransportSocket *socket_transport = (DBusTransportSocket*) transport;
1145   
1146   *fd_p = socket_transport->fd;
1147   
1148   return TRUE;
1149 }
1150
1151 static const DBusTransportVTable socket_vtable = {
1152   socket_finalize,
1153   socket_handle_watch,
1154   socket_disconnect,
1155   socket_connection_set,
1156   socket_do_iteration,
1157   socket_live_messages_changed,
1158   socket_get_socket_fd
1159 };
1160
1161 /**
1162  * Creates a new transport for the given socket file descriptor.  The file
1163  * descriptor must be nonblocking (use _dbus_set_fd_nonblocking() to
1164  * make it so). This function is shared by various transports that
1165  * boil down to a full duplex file descriptor.
1166  *
1167  * @param fd the file descriptor.
1168  * @param server_guid non-#NULL if this transport is on the server side of a connection
1169  * @param address the transport's address
1170  * @returns the new transport, or #NULL if no memory.
1171  */
1172 DBusTransport*
1173 _dbus_transport_new_for_socket (int               fd,
1174                                 const DBusString *server_guid,
1175                                 const DBusString *address)
1176 {
1177   DBusTransportSocket *socket_transport;
1178   
1179   socket_transport = dbus_new0 (DBusTransportSocket, 1);
1180   if (socket_transport == NULL)
1181     return NULL;
1182
1183   if (!_dbus_string_init (&socket_transport->encoded_outgoing))
1184     goto failed_0;
1185
1186   if (!_dbus_string_init (&socket_transport->encoded_incoming))
1187     goto failed_1;
1188   
1189   socket_transport->write_watch = _dbus_watch_new (fd,
1190                                                  DBUS_WATCH_WRITABLE,
1191                                                  FALSE,
1192                                                  NULL, NULL, NULL);
1193   if (socket_transport->write_watch == NULL)
1194     goto failed_2;
1195   
1196   socket_transport->read_watch = _dbus_watch_new (fd,
1197                                                 DBUS_WATCH_READABLE,
1198                                                 FALSE,
1199                                                 NULL, NULL, NULL);
1200   if (socket_transport->read_watch == NULL)
1201     goto failed_3;
1202
1203   if (!_dbus_transport_init_base (&socket_transport->base,
1204                                   &socket_vtable,
1205                                   server_guid, address))
1206     goto failed_4;
1207   
1208   socket_transport->fd = fd;
1209   socket_transport->message_bytes_written = 0;
1210   
1211   /* These values should probably be tunable or something. */     
1212   socket_transport->max_bytes_read_per_iteration = 2048;
1213   socket_transport->max_bytes_written_per_iteration = 2048;
1214   
1215   return (DBusTransport*) socket_transport;
1216
1217  failed_4:
1218   _dbus_watch_unref (socket_transport->read_watch);
1219  failed_3:
1220   _dbus_watch_unref (socket_transport->write_watch);
1221  failed_2:
1222   _dbus_string_free (&socket_transport->encoded_incoming);
1223  failed_1:
1224   _dbus_string_free (&socket_transport->encoded_outgoing);
1225  failed_0:
1226   dbus_free (socket_transport);
1227   return NULL;
1228 }
1229
1230 /**
1231  * Creates a new transport for the given hostname and port.
1232  * If host is NULL, it will default to localhost
1233  *
1234  * @param host the host to connect to
1235  * @param port the port to connect to
1236  * @param family the address family to connect to
1237  * @param error location to store reason for failure.
1238  * @returns a new transport, or #NULL on failure.
1239  */
1240 DBusTransport*
1241 _dbus_transport_new_for_tcp_socket (const char     *host,
1242                                     const char     *port,
1243                                     const char     *family,
1244                                     DBusError      *error)
1245 {
1246   int fd;
1247   DBusTransport *transport;
1248   DBusString address;
1249   
1250   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1251
1252   if (!_dbus_string_init (&address))
1253     {
1254       dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1255       return NULL;
1256     }
1257
1258   if (host == NULL)
1259     host = "localhost";
1260
1261   if (!_dbus_string_append (&address, "tcp:"))
1262     goto error;
1263
1264   if (!_dbus_string_append (&address, "host=") ||
1265       !_dbus_string_append (&address, host))
1266     goto error;
1267
1268   if (!_dbus_string_append (&address, ",port=") ||
1269       !_dbus_string_append (&address, port))
1270     goto error;
1271
1272   if (family != NULL &&
1273       (!_dbus_string_append (&address, "family=") ||
1274        !_dbus_string_append (&address, family)))
1275     goto error;
1276
1277   fd = _dbus_connect_tcp_socket (host, port, family, error);
1278   if (fd < 0)
1279     {
1280       _DBUS_ASSERT_ERROR_IS_SET (error);
1281       _dbus_string_free (&address);
1282       return NULL;
1283     }
1284
1285   _dbus_fd_set_close_on_exec (fd);
1286   
1287   _dbus_verbose ("Successfully connected to tcp socket %s:%s\n",
1288                  host, port);
1289   
1290   transport = _dbus_transport_new_for_socket (fd, NULL, &address);
1291   if (transport == NULL)
1292     {
1293       dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1294       _dbus_close_socket (fd, NULL);
1295       _dbus_string_free (&address);
1296       fd = -1;
1297     }
1298
1299   _dbus_string_free (&address);
1300   
1301   return transport;
1302
1303 error:
1304   _dbus_string_free (&address);
1305   dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1306   return NULL;
1307 }
1308
1309 /**
1310  * Opens a TCP socket transport.
1311  * 
1312  * @param entry the address entry to try opening as a tcp transport.
1313  * @param transport_p return location for the opened transport
1314  * @param error error to be set
1315  * @returns result of the attempt
1316  */
1317 DBusTransportOpenResult
1318 _dbus_transport_open_socket(DBusAddressEntry  *entry,
1319                             DBusTransport    **transport_p,                            
1320                             DBusError         *error)
1321 {
1322   const char *method;
1323   
1324   method = dbus_address_entry_get_method (entry);
1325   _dbus_assert (method != NULL);
1326
1327   if (strcmp (method, "tcp") == 0)
1328     {
1329       const char *host = dbus_address_entry_get_value (entry, "host");
1330       const char *port = dbus_address_entry_get_value (entry, "port");
1331       const char *family = dbus_address_entry_get_value (entry, "family");
1332
1333       if (port == NULL)
1334         {
1335           _dbus_set_bad_address (error, "tcp", "port", NULL);
1336           return DBUS_TRANSPORT_OPEN_BAD_ADDRESS;
1337         }
1338
1339       *transport_p = _dbus_transport_new_for_tcp_socket (host, port, family, error);
1340       if (*transport_p == NULL)
1341         {
1342           _DBUS_ASSERT_ERROR_IS_SET (error);
1343           return DBUS_TRANSPORT_OPEN_DID_NOT_CONNECT;
1344         }
1345       else
1346         {
1347           _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1348           return DBUS_TRANSPORT_OPEN_OK;
1349         }
1350     }
1351   else
1352     {
1353       _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1354       return DBUS_TRANSPORT_OPEN_NOT_HANDLED;
1355     }
1356 }
1357
1358 /** @} */
1359