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