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