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