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