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