82b28e0d7dc9a4a00501f78e194941150283ba76
[platform/upstream/dbus.git] / dbus / dbus-transport-unix.c
1 /* -*- mode: C; c-file-style: "gnu" -*- */
2 /* dbus-transport-unix.c UNIX socket subclasses of DBusTransport
3  *
4  * Copyright (C) 2002, 2003  Red Hat Inc.
5  *
6  * Licensed under the Academic Free License version 1.2
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-unix.h"
27 #include "dbus-transport-protected.h"
28 #include "dbus-watch.h"
29 #include <sys/types.h>
30 #include <sys/time.h>
31 #include <unistd.h>
32
33
34 /**
35  * @defgroup DBusTransportUnix DBusTransport implementations for UNIX
36  * @ingroup  DBusInternals
37  * @brief Implementation details of DBusTransport on UNIX
38  *
39  * @{
40  */
41
42 /**
43  * Opaque object representing a Unix file descriptor transport.
44  */
45 typedef struct DBusTransportUnix DBusTransportUnix;
46
47 /**
48  * Implementation details of DBusTransportUnix. All members are private.
49  */
50 struct DBusTransportUnix
51 {
52   DBusTransport base;                   /**< Parent instance */
53   int fd;                               /**< File descriptor. */
54   DBusWatch *read_watch;                /**< Watch for readability. */
55   DBusWatch *write_watch;               /**< Watch for writability. */
56
57   int max_bytes_read_per_iteration;     /**< To avoid blocking too long. */
58   int max_bytes_written_per_iteration;  /**< To avoid blocking too long. */
59
60   int message_bytes_written;            /**< Number of bytes of current
61                                          *   outgoing message that have
62                                          *   been written.
63                                          */
64   DBusString encoded_outgoing;          /**< Encoded version of current
65                                          *   outgoing message.
66                                          */
67   DBusString encoded_incoming;          /**< Encoded version of current
68                                          *   incoming data.
69                                          */
70 };
71
72 static void
73 free_watches (DBusTransport *transport)
74 {
75   DBusTransportUnix *unix_transport = (DBusTransportUnix*) transport;
76   
77   if (unix_transport->read_watch)
78     {
79       if (transport->connection)
80         _dbus_connection_remove_watch (transport->connection,
81                                        unix_transport->read_watch);
82       _dbus_watch_invalidate (unix_transport->read_watch);
83       _dbus_watch_unref (unix_transport->read_watch);
84       unix_transport->read_watch = NULL;
85     }
86
87   if (unix_transport->write_watch)
88     {
89       if (transport->connection)
90         _dbus_connection_remove_watch (transport->connection,
91                                        unix_transport->write_watch);
92       _dbus_watch_invalidate (unix_transport->write_watch);
93       _dbus_watch_unref (unix_transport->write_watch);
94       unix_transport->write_watch = NULL;
95     }
96 }
97
98 static void
99 unix_finalize (DBusTransport *transport)
100 {
101   DBusTransportUnix *unix_transport = (DBusTransportUnix*) transport;
102   
103   free_watches (transport);
104
105   _dbus_string_free (&unix_transport->encoded_outgoing);
106   _dbus_string_free (&unix_transport->encoded_incoming);
107   
108   _dbus_transport_finalize_base (transport);
109
110   _dbus_assert (unix_transport->read_watch == NULL);
111   _dbus_assert (unix_transport->write_watch == NULL);
112   
113   dbus_free (transport);
114 }
115
116 static void
117 check_write_watch (DBusTransport *transport)
118 {
119   DBusTransportUnix *unix_transport = (DBusTransportUnix*) transport;
120   dbus_bool_t need_write_watch;
121
122   if (transport->connection == NULL)
123     return;
124
125   if (transport->disconnected)
126     {
127       _dbus_assert (unix_transport->write_watch == NULL);
128       return;
129     }
130   
131   _dbus_transport_ref (transport);
132
133   if (_dbus_transport_get_is_authenticated (transport))
134     need_write_watch = transport->messages_need_sending;
135   else
136     need_write_watch = transport->send_credentials_pending ||
137       _dbus_auth_do_work (transport->auth) == DBUS_AUTH_STATE_HAVE_BYTES_TO_SEND;
138
139   _dbus_connection_toggle_watch (transport->connection,
140                                  unix_transport->write_watch,
141                                  need_write_watch);
142
143   _dbus_transport_unref (transport);
144 }
145
146 static void
147 check_read_watch (DBusTransport *transport)
148 {
149   DBusTransportUnix *unix_transport = (DBusTransportUnix*) transport;
150   dbus_bool_t need_read_watch;
151
152   if (transport->connection == NULL)
153     return;
154
155   if (transport->disconnected)
156     {
157       _dbus_assert (unix_transport->read_watch == NULL);
158       return;
159     }
160   
161   _dbus_transport_ref (transport);
162
163   if (_dbus_transport_get_is_authenticated (transport))
164     need_read_watch =
165       _dbus_counter_get_value (transport->live_messages_size) < transport->max_live_messages_size;
166   else
167     need_read_watch = transport->receive_credentials_pending ||
168       _dbus_auth_do_work (transport->auth) == DBUS_AUTH_STATE_WAITING_FOR_INPUT;
169
170   _dbus_connection_toggle_watch (transport->connection,
171                                  unix_transport->read_watch,
172                                  need_read_watch);
173
174   _dbus_transport_unref (transport);
175 }
176
177 static void
178 do_io_error (DBusTransport *transport)
179 {
180   _dbus_transport_ref (transport);
181   _dbus_transport_disconnect (transport);
182   _dbus_transport_unref (transport);
183 }
184
185 /* return value is whether we successfully read any new data. */
186 static dbus_bool_t
187 read_data_into_auth (DBusTransport *transport,
188                      dbus_bool_t   *oom)
189 {
190   DBusTransportUnix *unix_transport = (DBusTransportUnix*) transport;
191   DBusString *buffer;
192   int bytes_read;
193   
194   *oom = FALSE;
195
196   _dbus_auth_get_buffer (transport->auth, &buffer);
197   
198   bytes_read = _dbus_read (unix_transport->fd,
199                            buffer, unix_transport->max_bytes_read_per_iteration);
200
201   _dbus_auth_return_buffer (transport->auth, buffer,
202                             bytes_read > 0 ? bytes_read : 0);
203
204   if (bytes_read > 0)
205     {
206       _dbus_verbose (" read %d bytes in auth phase\n", bytes_read);
207
208       return TRUE;
209     }
210   else if (bytes_read < 0)
211     {
212       /* EINTR already handled for us */
213
214       if (errno == ENOMEM)
215         {
216           *oom = TRUE;
217         }
218       else if (errno == EAGAIN ||
219                errno == EWOULDBLOCK)
220         ; /* do nothing, just return FALSE below */
221       else
222         {
223           _dbus_verbose ("Error reading from remote app: %s\n",
224                          _dbus_strerror (errno));
225           do_io_error (transport);
226         }
227
228       return FALSE;
229     }
230   else
231     {
232       _dbus_assert (bytes_read == 0);
233       
234       _dbus_verbose ("Disconnected from remote app\n");
235       do_io_error (transport);
236
237       return FALSE;
238     }
239 }
240
241 /* Return value is whether we successfully wrote any bytes */
242 static dbus_bool_t
243 write_data_from_auth (DBusTransport *transport)
244 {
245   DBusTransportUnix *unix_transport = (DBusTransportUnix*) transport;
246   int bytes_written;
247   const DBusString *buffer;
248
249   if (!_dbus_auth_get_bytes_to_send (transport->auth,
250                                      &buffer))
251     return FALSE;
252   
253   bytes_written = _dbus_write (unix_transport->fd,
254                                buffer,
255                                0, _dbus_string_get_length (buffer));
256
257   if (bytes_written > 0)
258     {
259       _dbus_auth_bytes_sent (transport->auth, bytes_written);
260       return TRUE;
261     }
262   else if (bytes_written < 0)
263     {
264       /* EINTR already handled for us */
265       
266       if (errno == EAGAIN ||
267           errno == EWOULDBLOCK)
268         ;
269       else
270         {
271           _dbus_verbose ("Error writing to remote app: %s\n",
272                          _dbus_strerror (errno));
273           do_io_error (transport);
274         }
275     }
276
277   return FALSE;
278 }
279
280 static void
281 exchange_credentials (DBusTransport *transport,
282                       dbus_bool_t    do_reading,
283                       dbus_bool_t    do_writing)
284 {
285   DBusTransportUnix *unix_transport = (DBusTransportUnix*) transport;
286
287   if (do_writing && transport->send_credentials_pending)
288     {
289       if (_dbus_send_credentials_unix_socket (unix_transport->fd,
290                                               NULL))
291         {
292           transport->send_credentials_pending = FALSE;
293         }
294       else
295         {
296           _dbus_verbose ("Failed to write credentials\n");
297           do_io_error (transport);
298         }
299     }
300   
301   if (do_reading && transport->receive_credentials_pending)
302     {
303       if (_dbus_read_credentials_unix_socket (unix_transport->fd,
304                                                &transport->credentials,
305                                                NULL))
306         {
307           transport->receive_credentials_pending = FALSE;
308         }
309       else
310         {
311           _dbus_verbose ("Failed to read credentials\n");
312           do_io_error (transport);
313         }
314     }
315
316   if (!(transport->send_credentials_pending ||
317         transport->receive_credentials_pending))
318     {
319       _dbus_auth_set_credentials (transport->auth,
320                                   &transport->credentials);
321     }
322 }
323
324 static dbus_bool_t
325 do_authentication (DBusTransport *transport,
326                    dbus_bool_t    do_reading,
327                    dbus_bool_t    do_writing)
328 {
329   dbus_bool_t oom;
330   
331   _dbus_transport_ref (transport);
332
333   oom = FALSE;
334   
335   while (!_dbus_transport_get_is_authenticated (transport) &&
336          _dbus_transport_get_is_connected (transport))
337     {      
338       exchange_credentials (transport, do_reading, do_writing);
339       
340       if (transport->send_credentials_pending ||
341           transport->receive_credentials_pending)
342         {
343           _dbus_verbose ("send_credentials_pending = %d receive_credentials_pending = %d\n",
344                          transport->send_credentials_pending,
345                          transport->receive_credentials_pending);
346           goto out;
347         }
348       
349       switch (_dbus_auth_do_work (transport->auth))
350         {
351         case DBUS_AUTH_STATE_WAITING_FOR_INPUT:
352           _dbus_verbose (" auth state: waiting for input\n");
353           if (!do_reading || !read_data_into_auth (transport, &oom))
354             goto out;
355           break;
356       
357         case DBUS_AUTH_STATE_WAITING_FOR_MEMORY:
358           _dbus_verbose (" auth state: waiting for memory\n");
359           oom = TRUE;
360           goto out;
361           break;
362       
363         case DBUS_AUTH_STATE_HAVE_BYTES_TO_SEND:
364           _dbus_verbose (" auth state: bytes to send\n");
365           if (!do_writing || !write_data_from_auth (transport))
366             goto out;
367           break;
368       
369         case DBUS_AUTH_STATE_NEED_DISCONNECT:
370           _dbus_verbose (" auth state: need to disconnect\n");
371           do_io_error (transport);
372           break;
373       
374         case DBUS_AUTH_STATE_AUTHENTICATED_WITH_UNUSED_BYTES:
375           _dbus_verbose (" auth state: auth with unused bytes\n");
376           /* We'll recover the unused bytes in dbus-transport.c */
377           goto out;
378           break;
379           
380         case DBUS_AUTH_STATE_AUTHENTICATED:
381           _dbus_verbose (" auth state: authenticated\n");
382           break;
383         }
384     }
385   
386  out:
387   check_read_watch (transport);
388   check_write_watch (transport);
389   _dbus_transport_unref (transport);
390
391   if (oom)
392     return FALSE;
393   else
394     return TRUE;
395 }
396
397 /* returns false on oom */
398 static dbus_bool_t
399 do_writing (DBusTransport *transport)
400 {
401   int total;
402   DBusTransportUnix *unix_transport = (DBusTransportUnix*) transport;
403   dbus_bool_t oom;
404   
405   /* No messages without authentication! */
406   if (!_dbus_transport_get_is_authenticated (transport))
407     {
408       _dbus_verbose ("Not authenticated, not writing anything\n");
409       return TRUE;
410     }
411
412   if (transport->disconnected)
413     {
414       _dbus_verbose ("Not connected, not writing anything\n");
415       return TRUE;
416     }
417
418 #if 0
419   _dbus_verbose ("do_writing(), have_messages = %d\n",
420                  _dbus_connection_have_messages_to_send (transport->connection));
421 #endif
422   
423   oom = FALSE;
424   total = 0;
425
426   while (!transport->disconnected &&
427          _dbus_connection_have_messages_to_send (transport->connection))
428     {
429       int bytes_written;
430       DBusMessage *message;
431       const DBusString *header;
432       const DBusString *body;
433       int header_len, body_len;
434       int total_bytes_to_write;
435       
436       if (total > unix_transport->max_bytes_written_per_iteration)
437         {
438           _dbus_verbose ("%d bytes exceeds %d bytes written per iteration, returning\n",
439                          total, unix_transport->max_bytes_written_per_iteration);
440           goto out;
441         }
442
443       if (!dbus_watch_get_enabled (unix_transport->write_watch))
444         {
445           _dbus_verbose ("write watch disabled, not writing more stuff\n");
446           goto out;
447         }
448       
449       message = _dbus_connection_get_message_to_send (transport->connection);
450       _dbus_assert (message != NULL);
451       _dbus_message_lock (message);
452
453 #if 0
454       _dbus_verbose ("writing message %p\n", message);
455 #endif
456       
457       _dbus_message_get_network_data (message,
458                                       &header, &body);
459
460       header_len = _dbus_string_get_length (header);
461       body_len = _dbus_string_get_length (body);
462
463       if (_dbus_auth_needs_encoding (transport->auth))
464         {
465           if (_dbus_string_get_length (&unix_transport->encoded_outgoing) == 0)
466             {
467               if (!_dbus_auth_encode_data (transport->auth,
468                                            header, &unix_transport->encoded_outgoing))
469                 {
470                   oom = TRUE;
471                   goto out;
472                 }
473               
474               if (!_dbus_auth_encode_data (transport->auth,
475                                            body, &unix_transport->encoded_outgoing))
476                 {
477                   _dbus_string_set_length (&unix_transport->encoded_outgoing, 0);
478                   oom = TRUE;
479                   goto out;
480                 }
481             }
482           
483           total_bytes_to_write = _dbus_string_get_length (&unix_transport->encoded_outgoing);
484
485 #if 0
486           _dbus_verbose ("encoded message is %d bytes\n",
487                          total_bytes_to_write);
488 #endif
489           
490           bytes_written =
491             _dbus_write (unix_transport->fd,
492                          &unix_transport->encoded_outgoing,
493                          unix_transport->message_bytes_written,
494                          total_bytes_to_write - unix_transport->message_bytes_written);
495         }
496       else
497         {
498           total_bytes_to_write = header_len + body_len;
499
500 #if 0
501           _dbus_verbose ("message is %d bytes\n",
502                          total_bytes_to_write);          
503 #endif
504           
505           if (unix_transport->message_bytes_written < header_len)
506             {
507               bytes_written =
508                 _dbus_write_two (unix_transport->fd,
509                                  header,
510                                  unix_transport->message_bytes_written,
511                                  header_len - unix_transport->message_bytes_written,
512                                  body,
513                                  0, body_len);
514             }
515           else
516             {
517               bytes_written =
518                 _dbus_write (unix_transport->fd,
519                              body,
520                              (unix_transport->message_bytes_written - header_len),
521                              body_len -
522                              (unix_transport->message_bytes_written - header_len));
523             }
524         }
525
526       if (bytes_written < 0)
527         {
528           /* EINTR already handled for us */
529           
530           if (errno == EAGAIN ||
531               errno == EWOULDBLOCK)
532             goto out;
533           else
534             {
535               _dbus_verbose ("Error writing to remote app: %s\n",
536                              _dbus_strerror (errno));
537               do_io_error (transport);
538               goto out;
539             }
540         }
541       else
542         {
543           _dbus_verbose (" wrote %d bytes of %d\n", bytes_written,
544                          total_bytes_to_write);
545           
546           total += bytes_written;
547           unix_transport->message_bytes_written += bytes_written;
548
549           _dbus_assert (unix_transport->message_bytes_written <=
550                         total_bytes_to_write);
551           
552           if (unix_transport->message_bytes_written == total_bytes_to_write)
553             {
554               unix_transport->message_bytes_written = 0;
555               _dbus_string_set_length (&unix_transport->encoded_outgoing, 0);
556
557               _dbus_connection_message_sent (transport->connection,
558                                              message);
559             }
560         }
561     }
562
563  out:
564   if (oom)
565     return FALSE;
566   else
567     return TRUE;
568 }
569
570 /* returns false on out-of-memory */
571 static dbus_bool_t
572 do_reading (DBusTransport *transport)
573 {
574   DBusTransportUnix *unix_transport = (DBusTransportUnix*) transport;
575   DBusString *buffer;
576   int bytes_read;
577   int total;
578   dbus_bool_t oom;
579
580   /* No messages without authentication! */
581   if (!_dbus_transport_get_is_authenticated (transport))
582     return TRUE;
583
584   oom = FALSE;
585   
586   total = 0;
587
588  again:
589
590   /* See if we've exceeded max messages and need to disable reading */
591   check_read_watch (transport);
592   if (!dbus_watch_get_enabled (unix_transport->read_watch))
593     return TRUE;
594   
595   if (total > unix_transport->max_bytes_read_per_iteration)
596     {
597       _dbus_verbose ("%d bytes exceeds %d bytes read per iteration, returning\n",
598                      total, unix_transport->max_bytes_read_per_iteration);
599       goto out;
600     }
601
602   if (transport->disconnected)
603     goto out;
604
605   if (_dbus_auth_needs_decoding (transport->auth))
606     {
607       if (_dbus_string_get_length (&unix_transport->encoded_incoming) > 0)
608         bytes_read = _dbus_string_get_length (&unix_transport->encoded_incoming);
609       else
610         bytes_read = _dbus_read (unix_transport->fd,
611                                  &unix_transport->encoded_incoming,
612                                  unix_transport->max_bytes_read_per_iteration);
613
614       _dbus_assert (_dbus_string_get_length (&unix_transport->encoded_incoming) ==
615                     bytes_read);
616       
617       if (bytes_read > 0)
618         {
619           int orig_len;
620           
621           _dbus_message_loader_get_buffer (transport->loader,
622                                            &buffer);
623
624           orig_len = _dbus_string_get_length (buffer);
625           
626           if (!_dbus_auth_decode_data (transport->auth,
627                                        &unix_transport->encoded_incoming,
628                                        buffer))
629             {
630               _dbus_verbose ("Out of memory decoding incoming data\n");
631               oom = TRUE;
632               goto out;
633             }
634
635           _dbus_message_loader_return_buffer (transport->loader,
636                                               buffer,
637                                               _dbus_string_get_length (buffer) - orig_len);
638
639           _dbus_string_set_length (&unix_transport->encoded_incoming, 0);
640         }
641     }
642   else
643     {
644       _dbus_message_loader_get_buffer (transport->loader,
645                                        &buffer);
646       
647       bytes_read = _dbus_read (unix_transport->fd,
648                                buffer, unix_transport->max_bytes_read_per_iteration);
649       
650       _dbus_message_loader_return_buffer (transport->loader,
651                                           buffer,
652                                           bytes_read < 0 ? 0 : bytes_read);
653     }
654   
655   if (bytes_read < 0)
656     {
657       /* EINTR already handled for us */
658
659       if (errno == ENOMEM)
660         {
661           _dbus_verbose ("Out of memory in read()/do_reading()\n");
662           oom = TRUE;
663           goto out;
664         }
665       else if (errno == EAGAIN ||
666                errno == EWOULDBLOCK)
667         goto out;
668       else
669         {
670           _dbus_verbose ("Error reading from remote app: %s\n",
671                          _dbus_strerror (errno));
672           do_io_error (transport);
673           goto out;
674         }
675     }
676   else if (bytes_read == 0)
677     {
678       _dbus_verbose ("Disconnected from remote app\n");
679       do_io_error (transport);
680       goto out;
681     }
682   else
683     {
684       _dbus_verbose (" read %d bytes\n", bytes_read);
685       
686       total += bytes_read;      
687
688       if (_dbus_transport_queue_messages (transport) == DBUS_DISPATCH_NEED_MEMORY)
689         {
690           oom = TRUE;
691           _dbus_verbose (" out of memory when queueing messages we just read in the transport\n");
692           goto out;
693         }
694       
695       /* Try reading more data until we get EAGAIN and return, or
696        * exceed max bytes per iteration.  If in blocking mode of
697        * course we'll block instead of returning.
698        */
699       goto again;
700     }
701
702  out:
703   if (oom)
704     return FALSE;
705   else
706     return TRUE;
707 }
708
709 static dbus_bool_t
710 unix_handle_watch (DBusTransport *transport,
711                    DBusWatch     *watch,
712                    unsigned int   flags)
713 {
714   DBusTransportUnix *unix_transport = (DBusTransportUnix*) transport;
715
716   _dbus_assert (watch == unix_transport->read_watch ||
717                 watch == unix_transport->write_watch);
718   
719   if (flags & (DBUS_WATCH_HANGUP | DBUS_WATCH_ERROR))
720     {
721       _dbus_transport_disconnect (transport);
722       return TRUE;
723     }
724   
725   if (watch == unix_transport->read_watch &&
726       (flags & DBUS_WATCH_READABLE))
727     {
728 #if 1
729       _dbus_verbose ("handling read watch\n");
730 #endif
731       if (!do_authentication (transport, TRUE, FALSE))
732         return FALSE;
733       
734       if (!do_reading (transport))
735         {
736           _dbus_verbose ("no memory to read\n");
737           return FALSE;
738         }
739     }
740   else if (watch == unix_transport->write_watch &&
741            (flags & DBUS_WATCH_WRITABLE))
742     {
743 #if 0
744       _dbus_verbose ("handling write watch, messages_need_sending = %d\n",
745                      transport->messages_need_sending);
746 #endif
747       if (!do_authentication (transport, FALSE, TRUE))
748         return FALSE;
749       
750       if (!do_writing (transport))
751         {
752           _dbus_verbose ("no memory to write\n");
753           return FALSE;
754         }
755     }
756 #ifdef DBUS_ENABLE_VERBOSE_MODE
757   else
758     {
759       if (watch == unix_transport->read_watch)
760         _dbus_verbose ("asked to handle read watch with non-read condition 0x%x\n",
761                        flags);
762       else if (watch == unix_transport->write_watch)
763         _dbus_verbose ("asked to handle write watch with non-write condition 0x%x\n",
764                        flags);
765       else
766         _dbus_verbose ("asked to handle watch %p on fd %d that we don't recognize\n",
767                        watch, dbus_watch_get_fd (watch));
768     }
769 #endif /* DBUS_ENABLE_VERBOSE_MODE */
770
771   return TRUE;
772 }
773
774 static void
775 unix_disconnect (DBusTransport *transport)
776 {
777   DBusTransportUnix *unix_transport = (DBusTransportUnix*) transport;
778   
779   free_watches (transport);
780   
781   _dbus_close (unix_transport->fd, NULL);
782   unix_transport->fd = -1;
783 }
784
785 static dbus_bool_t
786 unix_connection_set (DBusTransport *transport)
787 {
788   DBusTransportUnix *unix_transport = (DBusTransportUnix*) transport;
789   
790   if (!_dbus_connection_add_watch (transport->connection,
791                                    unix_transport->write_watch))
792     return FALSE;
793
794   if (!_dbus_connection_add_watch (transport->connection,
795                                    unix_transport->read_watch))
796     {
797       _dbus_connection_remove_watch (transport->connection,
798                                      unix_transport->write_watch);
799       return FALSE;
800     }
801
802   check_read_watch (transport);
803   check_write_watch (transport);
804
805   return TRUE;
806 }
807
808 static void
809 unix_messages_pending (DBusTransport *transport,
810                        int            messages_pending)
811 {
812   check_write_watch (transport);
813 }
814
815 /* FIXME use _dbus_poll(), not select() */
816 /**
817  * @todo We need to have a way to wake up the select sleep if
818  * a new iteration request comes in with a flag (read/write) that
819  * we're not currently serving. Otherwise a call that just reads
820  * could block a write call forever (if there are no incoming
821  * messages).
822  */
823 static  void
824 unix_do_iteration (DBusTransport *transport,
825                    unsigned int   flags,
826                    int            timeout_milliseconds)
827 {
828   DBusTransportUnix *unix_transport = (DBusTransportUnix*) transport;
829   fd_set read_set;
830   fd_set write_set;
831   dbus_bool_t do_select;
832   int select_res;
833
834   _dbus_verbose (" iteration flags = %s%s timeout = %d read_watch = %p write_watch = %p\n",
835                  flags & DBUS_ITERATION_DO_READING ? "read" : "",
836                  flags & DBUS_ITERATION_DO_WRITING ? "write" : "",
837                  timeout_milliseconds,
838                  unix_transport->read_watch,
839                  unix_transport->write_watch);
840   
841   /* "again" has to be up here because on EINTR the fd sets become
842    * undefined
843    */
844  again:
845   
846   do_select = FALSE;
847
848   /* the passed in DO_READING/DO_WRITING flags indicate whether to
849    * read/write messages, but regardless of those we may need to block
850    * for reading/writing to do auth.  But if we do reading for auth,
851    * we don't want to read any messages yet if not given DO_READING.
852    *
853    * Also, if read_watch == NULL or write_watch == NULL, we don't
854    * want to read/write so don't.
855    */
856
857   FD_ZERO (&read_set);
858   FD_ZERO (&write_set);
859   
860   if (_dbus_transport_get_is_authenticated (transport))
861     {
862       if (unix_transport->read_watch &&
863           (flags & DBUS_ITERATION_DO_READING))
864         {
865           FD_SET (unix_transport->fd, &read_set);
866           do_select = TRUE;
867         }
868       
869       if (unix_transport->write_watch &&
870           (flags & DBUS_ITERATION_DO_WRITING))
871         {
872           FD_SET (unix_transport->fd, &write_set);
873           do_select = TRUE;
874         }
875     }
876   else
877     {
878       DBusAuthState auth_state;
879       
880       auth_state = _dbus_auth_do_work (transport->auth);
881
882       if (transport->receive_credentials_pending ||
883           auth_state == DBUS_AUTH_STATE_WAITING_FOR_INPUT)
884         {
885           FD_SET (unix_transport->fd, &read_set);
886           do_select = TRUE;
887         }
888
889       if (transport->send_credentials_pending ||
890           auth_state == DBUS_AUTH_STATE_HAVE_BYTES_TO_SEND)
891         {
892           FD_SET (unix_transport->fd, &write_set);
893           do_select = TRUE;
894         }
895     } 
896
897   if (do_select)
898     {
899       fd_set err_set;
900       struct timeval timeout;
901       dbus_bool_t use_timeout;
902       
903       FD_ZERO (&err_set);
904       FD_SET (unix_transport->fd, &err_set);
905   
906       if (flags & DBUS_ITERATION_BLOCK)
907         {
908           if (timeout_milliseconds >= 0)
909             {
910               timeout.tv_sec = timeout_milliseconds / 1000;
911               timeout.tv_usec = (timeout_milliseconds % 1000) * 1000;
912               
913               /* Always use timeout if one is passed in. */
914               use_timeout = TRUE;
915             }
916           else
917             {
918               use_timeout = FALSE; /* NULL timeout to block forever */
919             }
920         }
921       else
922         {
923           /* 0 timeout to not block */
924           timeout.tv_sec = 0;
925           timeout.tv_usec = 0;
926           use_timeout = TRUE;
927         }
928
929       /* For blocking selects we drop the connection lock here
930        * to avoid blocking out connection access during a potentially
931        * indefinite blocking call. The io path is still protected
932        * by the io_path_cond condvar, so we won't reenter this.
933        */
934       if (flags & DBUS_ITERATION_BLOCK)
935         _dbus_connection_unlock (transport->connection);
936       
937       select_res = select (unix_transport->fd + 1,
938                            &read_set, &write_set, &err_set,
939                            use_timeout ? &timeout : NULL);
940
941       if (flags & DBUS_ITERATION_BLOCK)
942         _dbus_connection_lock (transport->connection);
943       
944       
945       if (select_res >= 0)
946         {
947           if (FD_ISSET (unix_transport->fd, &err_set))
948             do_io_error (transport);
949           else
950             {
951               dbus_bool_t need_read = FD_ISSET (unix_transport->fd, &read_set);
952               dbus_bool_t need_write = FD_ISSET (unix_transport->fd, &write_set);
953
954               _dbus_verbose ("in iteration, need_read=%d need_write=%d\n",
955                              need_read, need_write);
956               do_authentication (transport, need_read, need_write);
957                                  
958               if (need_read && (flags & DBUS_ITERATION_DO_READING))
959                 do_reading (transport);
960               if (need_write && (flags & DBUS_ITERATION_DO_WRITING))
961                 do_writing (transport);
962             }
963         }
964       else if (errno == EINTR)
965         goto again;
966       else
967         {
968           _dbus_verbose ("Error from select(): %s\n",
969                          _dbus_strerror (errno));
970         }
971     }
972 }
973
974 static void
975 unix_live_messages_changed (DBusTransport *transport)
976 {
977   /* See if we should look for incoming messages again */
978   check_read_watch (transport);
979 }
980
981 static DBusTransportVTable unix_vtable = {
982   unix_finalize,
983   unix_handle_watch,
984   unix_disconnect,
985   unix_connection_set,
986   unix_messages_pending,
987   unix_do_iteration,
988   unix_live_messages_changed
989 };
990
991 /**
992  * Creates a new transport for the given file descriptor.  The file
993  * descriptor must be nonblocking (use _dbus_set_fd_nonblocking() to
994  * make it so). This function is shared by various transports that
995  * boil down to a full duplex file descriptor.
996  *
997  * @param fd the file descriptor.
998  * @param server #TRUE if this transport is on the server side of a connection
999  * @param address the transport's address
1000  * @returns the new transport, or #NULL if no memory.
1001  */
1002 DBusTransport*
1003 _dbus_transport_new_for_fd (int               fd,
1004                             dbus_bool_t       server,
1005                             const DBusString *address)
1006 {
1007   DBusTransportUnix *unix_transport;
1008   
1009   unix_transport = dbus_new0 (DBusTransportUnix, 1);
1010   if (unix_transport == NULL)
1011     return NULL;
1012
1013   if (!_dbus_string_init (&unix_transport->encoded_outgoing))
1014     goto failed_0;
1015
1016   if (!_dbus_string_init (&unix_transport->encoded_incoming))
1017     goto failed_1;
1018   
1019   unix_transport->write_watch = _dbus_watch_new (fd,
1020                                                  DBUS_WATCH_WRITABLE,
1021                                                  FALSE);
1022   if (unix_transport->write_watch == NULL)
1023     goto failed_2;
1024   
1025   unix_transport->read_watch = _dbus_watch_new (fd,
1026                                                 DBUS_WATCH_READABLE,
1027                                                 FALSE);
1028   if (unix_transport->read_watch == NULL)
1029     goto failed_3;
1030   
1031   if (!_dbus_transport_init_base (&unix_transport->base,
1032                                   &unix_vtable,
1033                                   server, address))
1034     goto failed_4;
1035   
1036   unix_transport->fd = fd;
1037   unix_transport->message_bytes_written = 0;
1038   
1039   /* These values should probably be tunable or something. */     
1040   unix_transport->max_bytes_read_per_iteration = 2048;
1041   unix_transport->max_bytes_written_per_iteration = 2048;
1042   
1043   return (DBusTransport*) unix_transport;
1044
1045  failed_4:
1046   _dbus_watch_unref (unix_transport->read_watch);
1047  failed_3:
1048   _dbus_watch_unref (unix_transport->write_watch);
1049  failed_2:
1050   _dbus_string_free (&unix_transport->encoded_incoming);
1051  failed_1:
1052   _dbus_string_free (&unix_transport->encoded_outgoing);
1053  failed_0:
1054   dbus_free (unix_transport);
1055   return NULL;
1056 }
1057
1058 /**
1059  * Creates a new transport for the given Unix domain socket
1060  * path. This creates a client-side of a transport.
1061  *
1062  * @param path the path to the domain socket.
1063  * @param error address where an error can be returned.
1064  * @returns a new transport, or #NULL on failure.
1065  */
1066 DBusTransport*
1067 _dbus_transport_new_for_domain_socket (const char     *path,
1068                                        DBusError      *error)
1069 {
1070   int fd;
1071   DBusTransport *transport;
1072   DBusString address;
1073   
1074   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1075
1076   if (!_dbus_string_init (&address))
1077     {
1078       dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1079       return NULL;
1080     }
1081
1082   fd = -1;
1083   
1084   if (!_dbus_string_append (&address, "unix:path=") ||
1085       !_dbus_string_append (&address, path))
1086     {
1087       dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1088       goto failed_0;
1089     }
1090   
1091   fd = _dbus_connect_unix_socket (path, error);
1092   if (fd < 0)
1093     {
1094       _DBUS_ASSERT_ERROR_IS_SET (error);
1095       goto failed_0;
1096     }
1097
1098   _dbus_fd_set_close_on_exec (fd);
1099   
1100   _dbus_verbose ("Successfully connected to unix socket %s\n",
1101                  path);
1102
1103   transport = _dbus_transport_new_for_fd (fd, FALSE, &address);
1104   if (transport == NULL)
1105     {
1106       dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1107       goto failed_1;
1108     }
1109   
1110   _dbus_string_free (&address);
1111   
1112   return transport;
1113
1114  failed_1:
1115   _dbus_close (fd, NULL);
1116  failed_0:
1117   _dbus_string_free (&address);
1118   return NULL;
1119 }
1120
1121 /**
1122  * Creates a new transport for the given hostname and port.
1123  *
1124  * @param host the host to connect to
1125  * @param port the port to connect to
1126  * @param error location to store reason for failure.
1127  * @returns a new transport, or #NULL on failure.
1128  */
1129 DBusTransport*
1130 _dbus_transport_new_for_tcp_socket (const char     *host,
1131                                     dbus_int32_t    port,
1132                                     DBusError      *error)
1133 {
1134   int fd;
1135   DBusTransport *transport;
1136   DBusString address;
1137   
1138   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
1139
1140   if (!_dbus_string_init (&address))
1141     {
1142       dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1143       return NULL;
1144     }
1145   
1146   if (!_dbus_string_append (&address, "tcp:host=") ||
1147       !_dbus_string_append (&address, host) ||
1148       !_dbus_string_append (&address, ",port=") ||
1149       !_dbus_string_append_int (&address, port))
1150     {
1151       _dbus_string_free (&address);
1152       dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1153       return NULL;
1154     }
1155   
1156   fd = _dbus_connect_tcp_socket (host, port, error);
1157   if (fd < 0)
1158     {
1159       _DBUS_ASSERT_ERROR_IS_SET (error);
1160       _dbus_string_free (&address);
1161       return NULL;
1162     }
1163
1164   _dbus_fd_set_close_on_exec (fd);
1165   
1166   _dbus_verbose ("Successfully connected to tcp socket %s:%d\n",
1167                  host, port);
1168   
1169   transport = _dbus_transport_new_for_fd (fd, FALSE, &address);
1170   if (transport == NULL)
1171     {
1172       dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
1173       _dbus_close (fd, NULL);
1174       _dbus_string_free (&address);
1175       fd = -1;
1176     }
1177
1178   _dbus_string_free (&address);
1179   
1180   return transport;
1181 }
1182
1183 /** @} */
1184