2004-07-24 Havoc Pennington <hp@redhat.com>
[platform/upstream/dbus.git] / dbus / dbus-transport-unix.c
index dfaeb1a..3447ae1 100644 (file)
@@ -3,7 +3,7 @@
  *
  * Copyright (C) 2002, 2003  Red Hat Inc.
  *
- * Licensed under the Academic Free License version 1.2
+ * Licensed under the Academic Free License version 2.0
  * 
  * This program is free software; you can redistribute it and/or modify
  * it under the terms of the GNU General Public License as published by
@@ -26,9 +26,6 @@
 #include "dbus-transport-unix.h"
 #include "dbus-transport-protected.h"
 #include "dbus-watch.h"
-#include <sys/types.h>
-#include <sys/time.h>
-#include <unistd.h>
 
 
 /**
@@ -61,9 +58,12 @@ struct DBusTransportUnix
                                          *   outgoing message that have
                                          *   been written.
                                          */
-  DBusString encoded_message;           /**< Encoded version of current
+  DBusString encoded_outgoing;          /**< Encoded version of current
                                          *   outgoing message.
                                          */
+  DBusString encoded_incoming;          /**< Encoded version of current
+                                         *   incoming data.
+                                         */
 };
 
 static void
@@ -99,7 +99,8 @@ unix_finalize (DBusTransport *transport)
   
   free_watches (transport);
 
-  _dbus_string_free (&unix_transport->encoded_message);
+  _dbus_string_free (&unix_transport->encoded_outgoing);
+  _dbus_string_free (&unix_transport->encoded_incoming);
   
   _dbus_transport_finalize_base (transport);
 
@@ -117,6 +118,12 @@ check_write_watch (DBusTransport *transport)
 
   if (transport->connection == NULL)
     return;
+
+  if (transport->disconnected)
+    {
+      _dbus_assert (unix_transport->write_watch == NULL);
+      return;
+    }
   
   _dbus_transport_ref (transport);
 
@@ -126,49 +133,10 @@ check_write_watch (DBusTransport *transport)
     need_write_watch = transport->send_credentials_pending ||
       _dbus_auth_do_work (transport->auth) == DBUS_AUTH_STATE_HAVE_BYTES_TO_SEND;
 
-  if (transport->disconnected)
-    need_write_watch = FALSE;
-  
-  if (need_write_watch &&
-      unix_transport->write_watch == NULL)
-    {
-      unix_transport->write_watch =
-        _dbus_watch_new (unix_transport->fd,
-                         DBUS_WATCH_WRITABLE);
-
-      /* FIXME this is total crack. The proper fix is probably to
-       * allocate the write watch on transport creation, keep it
-       * allocated. But that doesn't solve needing memory to add the
-       * watch.  messages_pending is going to have to handle OOM
-       * somehow (probably being part of PreallocatedSend)
-       */
-      if (unix_transport->write_watch == NULL)
-        goto out;
+  _dbus_connection_toggle_watch (transport->connection,
+                                 unix_transport->write_watch,
+                                 need_write_watch);
 
-      if (!_dbus_connection_add_watch (transport->connection,
-                                       unix_transport->write_watch))
-        {
-          _dbus_watch_invalidate (unix_transport->write_watch);
-          _dbus_watch_unref (unix_transport->write_watch);
-          unix_transport->write_watch = NULL;
-        }
-    }
-  else if (!need_write_watch &&
-           unix_transport->write_watch != NULL)
-    {
-      _dbus_connection_remove_watch (transport->connection,
-                                     unix_transport->write_watch);
-      _dbus_watch_invalidate (unix_transport->write_watch);
-      _dbus_watch_unref (unix_transport->write_watch);
-      unix_transport->write_watch = NULL;
-    }
-  else
-    {
-      _dbus_verbose ("Write watch is unchanged from %p on fd %d\n",
-                     unix_transport->write_watch, unix_transport->fd);
-    }
-  
- out:
   _dbus_transport_unref (transport);
 }
 
@@ -180,6 +148,12 @@ check_read_watch (DBusTransport *transport)
 
   if (transport->connection == NULL)
     return;
+
+  if (transport->disconnected)
+    {
+      _dbus_assert (unix_transport->read_watch == NULL);
+      return;
+    }
   
   _dbus_transport_ref (transport);
 
@@ -190,53 +164,10 @@ check_read_watch (DBusTransport *transport)
     need_read_watch = transport->receive_credentials_pending ||
       _dbus_auth_do_work (transport->auth) == DBUS_AUTH_STATE_WAITING_FOR_INPUT;
 
-  _dbus_verbose ("need_read_watch = %d authenticated = %d\n",
-                 need_read_watch, _dbus_transport_get_is_authenticated (transport));
-  
-  if (transport->disconnected)
-    need_read_watch = FALSE;
-  
-  if (need_read_watch &&
-      unix_transport->read_watch == NULL)
-    {
-      _dbus_verbose ("Adding read watch to unix fd %d\n",
-                     unix_transport->fd);
-      
-      unix_transport->read_watch =
-        _dbus_watch_new (unix_transport->fd,
-                         DBUS_WATCH_READABLE);
+  _dbus_connection_toggle_watch (transport->connection,
+                                 unix_transport->read_watch,
+                                 need_read_watch);
 
-      /* we can maybe add it some other time, just silently bomb */
-      if (unix_transport->read_watch == NULL)
-        goto out;
-
-      if (!_dbus_connection_add_watch (transport->connection,
-                                       unix_transport->read_watch))
-        {
-          _dbus_watch_invalidate (unix_transport->read_watch);
-          _dbus_watch_unref (unix_transport->read_watch);
-          unix_transport->read_watch = NULL;
-        }
-    }
-  else if (!need_read_watch &&
-           unix_transport->read_watch != NULL)
-    {
-      _dbus_verbose ("Removing read watch from unix fd %d\n",
-                     unix_transport->fd);
-      
-      _dbus_connection_remove_watch (transport->connection,
-                                     unix_transport->read_watch);
-      _dbus_watch_invalidate (unix_transport->read_watch);
-      _dbus_watch_unref (unix_transport->read_watch);
-      unix_transport->read_watch = NULL;
-    }
-  else
-    {
-      _dbus_verbose ("Read watch is unchanged from %p on fd %d\n",
-                     unix_transport->read_watch, unix_transport->fd);
-    }
-  
- out:
   _dbus_transport_unref (transport);
 }
 
@@ -248,79 +179,41 @@ do_io_error (DBusTransport *transport)
   _dbus_transport_unref (transport);
 }
 
-static void
-queue_messages (DBusTransport *transport)
-{
-  DBusMessage *message;
-  
-  /* Queue any messages */
-  while ((message = _dbus_message_loader_pop_message (transport->loader)))
-    {
-      _dbus_verbose ("queueing received message %p\n", message);
-
-      _dbus_message_add_size_counter (message, transport->live_messages_size);
-      _dbus_connection_queue_received_message (transport->connection,
-                                               message);
-      dbus_message_unref (message);
-    }
-
-  if (_dbus_message_loader_get_is_corrupted (transport->loader))
-    {
-      _dbus_verbose ("Corrupted message stream, disconnecting\n");
-      do_io_error (transport);
-    }
-
-  /* check read watch in case we've now exceeded max outstanding messages */
-  check_read_watch (transport);
-}
-
 /* return value is whether we successfully read any new data. */
 static dbus_bool_t
-read_data_into_auth (DBusTransport *transport)
+read_data_into_auth (DBusTransport *transport,
+                     dbus_bool_t   *oom)
 {
   DBusTransportUnix *unix_transport = (DBusTransportUnix*) transport;
-  DBusString buffer;
+  DBusString *buffer;
   int bytes_read;
   
-  if (!_dbus_string_init (&buffer, _DBUS_INT_MAX))
-    {
-      /* just disconnect if we don't have memory
-       * to do an authentication
-       */
-      _dbus_verbose ("No memory for authentication\n");
-      do_io_error (transport);
-      return FALSE;
-    }
+  *oom = FALSE;
+
+  _dbus_auth_get_buffer (transport->auth, &buffer);
   
   bytes_read = _dbus_read (unix_transport->fd,
-                           &buffer, unix_transport->max_bytes_read_per_iteration);
+                           buffer, unix_transport->max_bytes_read_per_iteration);
+
+  _dbus_auth_return_buffer (transport->auth, buffer,
+                            bytes_read > 0 ? bytes_read : 0);
 
   if (bytes_read > 0)
     {
       _dbus_verbose (" read %d bytes in auth phase\n", bytes_read);
-      
-      if (_dbus_auth_bytes_received (transport->auth,
-                                     &buffer))
-        {
-          _dbus_string_free (&buffer);
-          return TRUE; /* We did read some data! woo! */
-        }
-      else
-        {
-          /* just disconnect if we don't have memory to do an
-           * authentication, don't fool with trying to save the buffer
-           * and who knows what.
-           */
-          _dbus_verbose ("No memory for authentication\n");
-          do_io_error (transport);
-        }
+
+      return TRUE;
     }
   else if (bytes_read < 0)
     {
       /* EINTR already handled for us */
-      
-      if (errno == EAGAIN ||
-          errno == EWOULDBLOCK)
+
+      if (errno == ENOMEM)
+        {
+          *oom = TRUE;
+        }
+      else if (errno == EAGAIN ||
+               errno == EWOULDBLOCK)
         ; /* do nothing, just return FALSE below */
       else
         {
@@ -328,15 +221,18 @@ read_data_into_auth (DBusTransport *transport)
                          _dbus_strerror (errno));
           do_io_error (transport);
         }
+
+      return FALSE;
     }
-  else if (bytes_read == 0)
+  else
     {
+      _dbus_assert (bytes_read == 0);
+      
       _dbus_verbose ("Disconnected from remote app\n");
-      do_io_error (transport);      
+      do_io_error (transport);
+
+      return FALSE;
     }
-  
-  _dbus_string_free (&buffer);
-  return FALSE;
 }
 
 /* Return value is whether we successfully wrote any bytes */
@@ -379,100 +275,6 @@ write_data_from_auth (DBusTransport *transport)
 }
 
 static void
-recover_unused_bytes (DBusTransport *transport)
-{
-  
-  if (_dbus_auth_needs_decoding (transport->auth))
-    {
-      DBusString plaintext;
-      DBusString encoded;
-      DBusString *buffer;
-      int orig_len;
-      
-      if (!_dbus_string_init (&plaintext, _DBUS_INT_MAX))
-        goto nomem;
-
-      if (!_dbus_string_init (&encoded, _DBUS_INT_MAX))
-        {
-          _dbus_string_free (&plaintext);
-          goto nomem;
-        }
-      
-      if (!_dbus_auth_get_unused_bytes (transport->auth,
-                                        &encoded))
-        {
-          _dbus_string_free (&plaintext);
-          _dbus_string_free (&encoded);
-          goto nomem;
-        }
-      
-      if (!_dbus_auth_decode_data (transport->auth,
-                                   &encoded, &plaintext))
-        {
-          _dbus_string_free (&plaintext);
-          _dbus_string_free (&encoded);
-          goto nomem;
-        }
-      
-      _dbus_message_loader_get_buffer (transport->loader,
-                                       &buffer);
-      
-      orig_len = _dbus_string_get_length (buffer);
-
-      if (!_dbus_string_move (&plaintext, 0, buffer,
-                              orig_len))
-        {
-          _dbus_string_free (&plaintext);
-          _dbus_string_free (&encoded);
-          goto nomem;
-        }
-      
-      _dbus_verbose (" %d unused bytes sent to message loader\n", 
-                     _dbus_string_get_length (buffer) -
-                     orig_len);
-      
-      _dbus_message_loader_return_buffer (transport->loader,
-                                          buffer,
-                                          _dbus_string_get_length (buffer) -
-                                          orig_len);
-
-      _dbus_string_free (&plaintext);
-      _dbus_string_free (&encoded);
-    }
-  else
-    {
-      DBusString *buffer;
-      int orig_len;
-
-      _dbus_message_loader_get_buffer (transport->loader,
-                                       &buffer);
-                
-      orig_len = _dbus_string_get_length (buffer);
-                
-      if (!_dbus_auth_get_unused_bytes (transport->auth,
-                                        buffer))
-        goto nomem;
-                
-      _dbus_verbose (" %d unused bytes sent to message loader\n", 
-                     _dbus_string_get_length (buffer) -
-                     orig_len);
-      
-      _dbus_message_loader_return_buffer (transport->loader,
-                                          buffer,
-                                          _dbus_string_get_length (buffer) -
-                                          orig_len);
-    }
-  
-  queue_messages (transport);
-
-  return;
-
- nomem:
-  _dbus_verbose ("Not enough memory to transfer unused bytes from auth conversation\n");
-  do_io_error (transport);
-}
-
-static void
 exchange_credentials (DBusTransport *transport,
                       dbus_bool_t    do_reading,
                       dbus_bool_t    do_writing)
@@ -516,16 +318,20 @@ exchange_credentials (DBusTransport *transport,
     }
 }
 
-static void
+static dbus_bool_t
 do_authentication (DBusTransport *transport,
                    dbus_bool_t    do_reading,
                    dbus_bool_t    do_writing)
-{  
+{
+  dbus_bool_t oom;
+  
   _dbus_transport_ref (transport);
+
+  oom = FALSE;
   
   while (!_dbus_transport_get_is_authenticated (transport) &&
          _dbus_transport_get_is_connected (transport))
-    {
+    {      
       exchange_credentials (transport, do_reading, do_writing);
       
       if (transport->send_credentials_pending ||
@@ -536,62 +342,82 @@ do_authentication (DBusTransport *transport,
                          transport->receive_credentials_pending);
           goto out;
         }
-      
+
+#define TRANSPORT_SIDE(t) ((t)->is_server ? "server" : "client")
       switch (_dbus_auth_do_work (transport->auth))
         {
         case DBUS_AUTH_STATE_WAITING_FOR_INPUT:
-          _dbus_verbose (" auth state: waiting for input\n");
-          if (!do_reading || !read_data_into_auth (transport))
+          _dbus_verbose (" %s auth state: waiting for input\n",
+                         TRANSPORT_SIDE (transport));
+          if (!do_reading || !read_data_into_auth (transport, &oom))
             goto out;
           break;
       
         case DBUS_AUTH_STATE_WAITING_FOR_MEMORY:
-          /* Screw it, just disconnect */
-          _dbus_verbose (" auth state: waiting for memory\n");
-          do_io_error (transport);
+          _dbus_verbose (" %s auth state: waiting for memory\n",
+                         TRANSPORT_SIDE (transport));
+          oom = TRUE;
+          goto out;
           break;
       
         case DBUS_AUTH_STATE_HAVE_BYTES_TO_SEND:
-          _dbus_verbose (" auth state: bytes to send\n");
+          _dbus_verbose (" %s auth state: bytes to send\n",
+                         TRANSPORT_SIDE (transport));
           if (!do_writing || !write_data_from_auth (transport))
             goto out;
           break;
       
         case DBUS_AUTH_STATE_NEED_DISCONNECT:
-          _dbus_verbose (" auth state: need to disconnect\n");
+          _dbus_verbose (" %s auth state: need to disconnect\n",
+                         TRANSPORT_SIDE (transport));
           do_io_error (transport);
           break;
       
-        case DBUS_AUTH_STATE_AUTHENTICATED_WITH_UNUSED_BYTES:
-          _dbus_verbose (" auth state: auth with unused bytes\n");
-          recover_unused_bytes (transport);
-          break;
-          
         case DBUS_AUTH_STATE_AUTHENTICATED:
-          _dbus_verbose (" auth state: authenticated\n");
+          _dbus_verbose (" %s auth state: authenticated\n",
+                         TRANSPORT_SIDE (transport));
           break;
         }
     }
-
+  
  out:
   check_read_watch (transport);
   check_write_watch (transport);
   _dbus_transport_unref (transport);
+
+  if (oom)
+    return FALSE;
+  else
+    return TRUE;
 }
 
-static void
+/* returns false on oom */
+static dbus_bool_t
 do_writing (DBusTransport *transport)
 {
   int total;
   DBusTransportUnix *unix_transport = (DBusTransportUnix*) transport;
-
+  dbus_bool_t oom;
+  
   /* No messages without authentication! */
   if (!_dbus_transport_get_is_authenticated (transport))
-    return;
+    {
+      _dbus_verbose ("Not authenticated, not writing anything\n");
+      return TRUE;
+    }
 
   if (transport->disconnected)
-    return;
+    {
+      _dbus_verbose ("Not connected, not writing anything\n");
+      return TRUE;
+    }
+
+#if 0
+  _dbus_verbose ("do_writing(), have_messages = %d\n",
+                 _dbus_connection_have_messages_to_send (transport->connection));
+#endif
   
+  oom = FALSE;
   total = 0;
 
   while (!transport->disconnected &&
@@ -611,9 +437,9 @@ do_writing (DBusTransport *transport)
           goto out;
         }
 
-      if (unix_transport->write_watch == NULL)
+      if (!dbus_watch_get_enabled (unix_transport->write_watch))
         {
-          _dbus_verbose ("write watch removed, not writing more stuff\n");
+          _dbus_verbose ("write watch disabled, not writing more stuff\n");
           goto out;
         }
       
@@ -621,7 +447,9 @@ do_writing (DBusTransport *transport)
       _dbus_assert (message != NULL);
       _dbus_message_lock (message);
 
+#if 0
       _dbus_verbose ("writing message %p\n", message);
+#endif
       
       _dbus_message_get_network_data (message,
                                       &header, &body);
@@ -631,28 +459,34 @@ do_writing (DBusTransport *transport)
 
       if (_dbus_auth_needs_encoding (transport->auth))
         {
-          if (_dbus_string_get_length (&unix_transport->encoded_message) == 0)
+          if (_dbus_string_get_length (&unix_transport->encoded_outgoing) == 0)
             {
               if (!_dbus_auth_encode_data (transport->auth,
-                                           header, &unix_transport->encoded_message))
-                goto out;
+                                           header, &unix_transport->encoded_outgoing))
+                {
+                  oom = TRUE;
+                  goto out;
+                }
               
               if (!_dbus_auth_encode_data (transport->auth,
-                                           body, &unix_transport->encoded_message))
+                                           body, &unix_transport->encoded_outgoing))
                 {
-                  _dbus_string_set_length (&unix_transport->encoded_message, 0);
+                  _dbus_string_set_length (&unix_transport->encoded_outgoing, 0);
+                  oom = TRUE;
                   goto out;
                 }
             }
           
-          total_bytes_to_write = _dbus_string_get_length (&unix_transport->encoded_message);
+          total_bytes_to_write = _dbus_string_get_length (&unix_transport->encoded_outgoing);
 
+#if 0
           _dbus_verbose ("encoded message is %d bytes\n",
                          total_bytes_to_write);
+#endif
           
           bytes_written =
             _dbus_write (unix_transport->fd,
-                         &unix_transport->encoded_message,
+                         &unix_transport->encoded_outgoing,
                          unix_transport->message_bytes_written,
                          total_bytes_to_write - unix_transport->message_bytes_written);
         }
@@ -660,8 +494,10 @@ do_writing (DBusTransport *transport)
         {
           total_bytes_to_write = header_len + body_len;
 
+#if 0
           _dbus_verbose ("message is %d bytes\n",
                          total_bytes_to_write);          
+#endif
           
           if (unix_transport->message_bytes_written < header_len)
             {
@@ -700,7 +536,7 @@ do_writing (DBusTransport *transport)
             }
         }
       else
-        {          
+        {
           _dbus_verbose (" wrote %d bytes of %d\n", bytes_written,
                          total_bytes_to_write);
           
@@ -713,7 +549,7 @@ do_writing (DBusTransport *transport)
           if (unix_transport->message_bytes_written == total_bytes_to_write)
             {
               unix_transport->message_bytes_written = 0;
-              _dbus_string_set_length (&unix_transport->encoded_message, 0);
+              _dbus_string_set_length (&unix_transport->encoded_outgoing, 0);
 
               _dbus_connection_message_sent (transport->connection,
                                              message);
@@ -722,29 +558,34 @@ do_writing (DBusTransport *transport)
     }
 
  out:
-  return; /* I think some C compilers require a statement after a label */
+  if (oom)
+    return FALSE;
+  else
+    return TRUE;
 }
 
-static void
+/* returns false on out-of-memory */
+static dbus_bool_t
 do_reading (DBusTransport *transport)
 {
   DBusTransportUnix *unix_transport = (DBusTransportUnix*) transport;
   DBusString *buffer;
   int bytes_read;
   int total;
+  dbus_bool_t oom;
 
   /* No messages without authentication! */
   if (!_dbus_transport_get_is_authenticated (transport))
-    return;
+    return TRUE;
+
+  oom = FALSE;
   
   total = 0;
 
  again:
-
+  
   /* See if we've exceeded max messages and need to disable reading */
   check_read_watch (transport);
-  if (unix_transport->read_watch == NULL)
-    return;
   
   if (total > unix_transport->max_bytes_read_per_iteration)
     {
@@ -753,20 +594,27 @@ do_reading (DBusTransport *transport)
       goto out;
     }
 
+  _dbus_assert (unix_transport->read_watch != NULL ||
+                transport->disconnected);
+  
   if (transport->disconnected)
     goto out;
 
+  if (!dbus_watch_get_enabled (unix_transport->read_watch))
+    return TRUE;
+  
   if (_dbus_auth_needs_decoding (transport->auth))
     {
-      DBusString encoded;
-
-      if (!_dbus_string_init (&encoded, _DBUS_INT_MAX))
-        goto out; /* not enough memory for the moment */
-
-      bytes_read = _dbus_read (unix_transport->fd,
-                               &encoded,
-                               unix_transport->max_bytes_read_per_iteration);
+      if (_dbus_string_get_length (&unix_transport->encoded_incoming) > 0)
+        bytes_read = _dbus_string_get_length (&unix_transport->encoded_incoming);
+      else
+        bytes_read = _dbus_read (unix_transport->fd,
+                                 &unix_transport->encoded_incoming,
+                                 unix_transport->max_bytes_read_per_iteration);
 
+      _dbus_assert (_dbus_string_get_length (&unix_transport->encoded_incoming) ==
+                    bytes_read);
+      
       if (bytes_read > 0)
         {
           int orig_len;
@@ -777,24 +625,20 @@ do_reading (DBusTransport *transport)
           orig_len = _dbus_string_get_length (buffer);
           
           if (!_dbus_auth_decode_data (transport->auth,
-                                       &encoded, buffer))
+                                       &unix_transport->encoded_incoming,
+                                       buffer))
             {
-              /* FIXME argh, we are really fucked here - nowhere to
-               * put "encoded" while we wait for more memory.  Just
-               * screw it for now and disconnect.  The failure may be
-               * due to badly-encoded data instead of lack of memory
-               * anyhow.
-               */
-              _dbus_verbose ("Disconnected from remote app due to failure decoding data\n");
-              do_io_error (transport);
+              _dbus_verbose ("Out of memory decoding incoming data\n");
+              oom = TRUE;
+              goto out;
             }
 
           _dbus_message_loader_return_buffer (transport->loader,
                                               buffer,
                                               _dbus_string_get_length (buffer) - orig_len);
-        }
 
-      _dbus_string_free (&encoded);
+          _dbus_string_set_length (&unix_transport->encoded_incoming, 0);
+        }
     }
   else
     {
@@ -812,9 +656,15 @@ do_reading (DBusTransport *transport)
   if (bytes_read < 0)
     {
       /* EINTR already handled for us */
-      
-      if (errno == EAGAIN ||
-          errno == EWOULDBLOCK)
+
+      if (errno == ENOMEM)
+        {
+          _dbus_verbose ("Out of memory in read()/do_reading()\n");
+          oom = TRUE;
+          goto out;
+        }
+      else if (errno == EAGAIN ||
+               errno == EWOULDBLOCK)
         goto out;
       else
         {
@@ -836,7 +686,12 @@ do_reading (DBusTransport *transport)
       
       total += bytes_read;      
 
-      queue_messages (transport);
+      if (!_dbus_transport_queue_messages (transport))
+        {
+          oom = TRUE;
+          _dbus_verbose (" out of memory when queueing messages we just read in the transport\n");
+          goto out;
+        }
       
       /* Try reading more data until we get EAGAIN and return, or
        * exceed max bytes per iteration.  If in blocking mode of
@@ -846,10 +701,13 @@ do_reading (DBusTransport *transport)
     }
 
  out:
-  return; /* I think some C compilers require a statement after a label */
+  if (oom)
+    return FALSE;
+  else
+    return TRUE;
 }
 
-static void
+static dbus_bool_t
 unix_handle_watch (DBusTransport *transport,
                    DBusWatch     *watch,
                    unsigned int   flags)
@@ -859,26 +717,67 @@ unix_handle_watch (DBusTransport *transport,
   _dbus_assert (watch == unix_transport->read_watch ||
                 watch == unix_transport->write_watch);
   
-  if (flags & (DBUS_WATCH_HANGUP | DBUS_WATCH_ERROR))
+  /* Disconnect in case of an error.  In case of hangup do not
+   * disconnect the transport because data can still be in the buffer
+   * and do_reading may need several iteration to read it all (because
+   * of its max_bytes_read_per_iteration limit).  The condition where
+   * flags == HANGUP (without READABLE) probably never happen in fact.
+   */
+  if ((flags & DBUS_WATCH_ERROR) ||
+      ((flags & DBUS_WATCH_HANGUP) && !(flags & DBUS_WATCH_READABLE)))
     {
+      _dbus_verbose ("Hang up or error on watch\n");
       _dbus_transport_disconnect (transport);
-      return;
+      return TRUE;
     }
   
   if (watch == unix_transport->read_watch &&
       (flags & DBUS_WATCH_READABLE))
     {
-      _dbus_verbose ("handling read watch\n");
-      do_authentication (transport, TRUE, FALSE);
-      do_reading (transport);
+#if 0
+      _dbus_verbose ("handling read watch (%x)\n", flags);
+#endif
+      if (!do_authentication (transport, TRUE, FALSE))
+        return FALSE;
+      
+      if (!do_reading (transport))
+        {
+          _dbus_verbose ("no memory to read\n");
+          return FALSE;
+        }
     }
   else if (watch == unix_transport->write_watch &&
            (flags & DBUS_WATCH_WRITABLE))
     {
-      _dbus_verbose ("handling write watch\n");
-      do_authentication (transport, FALSE, TRUE);
-      do_writing (transport);
+#if 0
+      _dbus_verbose ("handling write watch, messages_need_sending = %d\n",
+                     transport->messages_need_sending);
+#endif
+      if (!do_authentication (transport, FALSE, TRUE))
+        return FALSE;
+      
+      if (!do_writing (transport))
+        {
+          _dbus_verbose ("no memory to write\n");
+          return FALSE;
+        }
+    }
+#ifdef DBUS_ENABLE_VERBOSE_MODE
+  else
+    {
+      if (watch == unix_transport->read_watch)
+        _dbus_verbose ("asked to handle read watch with non-read condition 0x%x\n",
+                       flags);
+      else if (watch == unix_transport->write_watch)
+        _dbus_verbose ("asked to handle write watch with non-write condition 0x%x\n",
+                       flags);
+      else
+        _dbus_verbose ("asked to handle watch %p on fd %d that we don't recognize\n",
+                       watch, dbus_watch_get_fd (watch));
     }
+#endif /* DBUS_ENABLE_VERBOSE_MODE */
+
+  return TRUE;
 }
 
 static void
@@ -892,11 +791,35 @@ unix_disconnect (DBusTransport *transport)
   unix_transport->fd = -1;
 }
 
-static void
+static dbus_bool_t
 unix_connection_set (DBusTransport *transport)
 {
+  DBusTransportUnix *unix_transport = (DBusTransportUnix*) transport;
+
+  _dbus_watch_set_handler (unix_transport->write_watch,
+                           _dbus_connection_handle_watch,
+                           transport->connection, NULL);
+
+  _dbus_watch_set_handler (unix_transport->read_watch,
+                           _dbus_connection_handle_watch,
+                           transport->connection, NULL);
+  
+  if (!_dbus_connection_add_watch (transport->connection,
+                                   unix_transport->write_watch))
+    return FALSE;
+
+  if (!_dbus_connection_add_watch (transport->connection,
+                                   unix_transport->read_watch))
+    {
+      _dbus_connection_remove_watch (transport->connection,
+                                     unix_transport->write_watch);
+      return FALSE;
+    }
+
   check_read_watch (transport);
   check_write_watch (transport);
+
+  return TRUE;
 }
 
 static void
@@ -906,7 +829,6 @@ unix_messages_pending (DBusTransport *transport,
   check_write_watch (transport);
 }
 
-/* FIXME use _dbus_poll(), not select() */
 /**
  * @todo We need to have a way to wake up the select sleep if
  * a new iteration request comes in with a flag (read/write) that
@@ -920,10 +842,9 @@ unix_do_iteration (DBusTransport *transport,
                    int            timeout_milliseconds)
 {
   DBusTransportUnix *unix_transport = (DBusTransportUnix*) transport;
-  fd_set read_set;
-  fd_set write_set;
-  dbus_bool_t do_select;
-  int select_res;
+  DBusPollFD poll_fd;
+  int poll_res;
+  int poll_timeout;
 
   _dbus_verbose (" iteration flags = %s%s timeout = %d read_watch = %p write_watch = %p\n",
                  flags & DBUS_ITERATION_DO_READING ? "read" : "",
@@ -932,13 +853,6 @@ unix_do_iteration (DBusTransport *transport,
                  unix_transport->read_watch,
                  unix_transport->write_watch);
   
-  /* "again" has to be up here because on EINTR the fd sets become
-   * undefined
-   */
- again:
-  
-  do_select = FALSE;
-
   /* the passed in DO_READING/DO_WRITING flags indicate whether to
    * read/write messages, but regardless of those we may need to block
    * for reading/writing to do auth.  But if we do reading for auth,
@@ -948,24 +862,18 @@ unix_do_iteration (DBusTransport *transport,
    * want to read/write so don't.
    */
 
-  FD_ZERO (&read_set);
-  FD_ZERO (&write_set);
+  poll_fd.fd = unix_transport->fd;
+  poll_fd.events = 0;
   
   if (_dbus_transport_get_is_authenticated (transport))
     {
       if (unix_transport->read_watch &&
           (flags & DBUS_ITERATION_DO_READING))
-        {
-          FD_SET (unix_transport->fd, &read_set);
-          do_select = TRUE;
-        }
+       poll_fd.events |= _DBUS_POLLIN;
       
       if (unix_transport->write_watch &&
           (flags & DBUS_ITERATION_DO_WRITING))
-        {
-          FD_SET (unix_transport->fd, &write_set);
-          do_select = TRUE;
-        }
+       poll_fd.events |= _DBUS_POLLOUT;
     }
   else
     {
@@ -975,50 +883,19 @@ unix_do_iteration (DBusTransport *transport,
 
       if (transport->receive_credentials_pending ||
           auth_state == DBUS_AUTH_STATE_WAITING_FOR_INPUT)
-        {
-          FD_SET (unix_transport->fd, &read_set);
-          do_select = TRUE;
-        }
+       poll_fd.events |= _DBUS_POLLIN;
 
       if (transport->send_credentials_pending ||
           auth_state == DBUS_AUTH_STATE_HAVE_BYTES_TO_SEND)
-        {
-          FD_SET (unix_transport->fd, &write_set);
-          do_select = TRUE;
-        }
+       poll_fd.events |= _DBUS_POLLOUT;
     } 
 
-  if (do_select)
+  if (poll_fd.events)
     {
-      fd_set err_set;
-      struct timeval timeout;
-      dbus_bool_t use_timeout;
-      
-      FD_ZERO (&err_set);
-      FD_SET (unix_transport->fd, &err_set);
-  
       if (flags & DBUS_ITERATION_BLOCK)
-        {
-          if (timeout_milliseconds >= 0)
-            {
-              timeout.tv_sec = timeout_milliseconds / 1000;
-              timeout.tv_usec = (timeout_milliseconds % 1000) * 1000;
-              
-              /* Always use timeout if one is passed in. */
-              use_timeout = TRUE;
-            }
-          else
-            {
-              use_timeout = FALSE; /* NULL timeout to block forever */
-            }
-        }
+       poll_timeout = timeout_milliseconds;
       else
-        {
-          /* 0 timeout to not block */
-          timeout.tv_sec = 0;
-          timeout.tv_usec = 0;
-          use_timeout = TRUE;
-        }
+       poll_timeout = 0;
 
       /* For blocking selects we drop the connection lock here
        * to avoid blocking out connection access during a potentially
@@ -1028,22 +905,23 @@ unix_do_iteration (DBusTransport *transport,
       if (flags & DBUS_ITERATION_BLOCK)
        _dbus_connection_unlock (transport->connection);
       
-      select_res = select (unix_transport->fd + 1,
-                          &read_set, &write_set, &err_set,
-                          use_timeout ? &timeout : NULL);
+    again:
+      poll_res = _dbus_poll (&poll_fd, 1, poll_timeout);
+
+      if (poll_res < 0 && errno == EINTR)
+       goto again;
 
       if (flags & DBUS_ITERATION_BLOCK)
        _dbus_connection_lock (transport->connection);
       
-      
-      if (select_res >= 0)
+      if (poll_res >= 0)
         {
-          if (FD_ISSET (unix_transport->fd, &err_set))
+          if (poll_fd.revents & _DBUS_POLLERR)
             do_io_error (transport);
           else
             {
-              dbus_bool_t need_read = FD_ISSET (unix_transport->fd, &read_set);
-              dbus_bool_t need_write = FD_ISSET (unix_transport->fd, &write_set);
+              dbus_bool_t need_read = (poll_fd.revents & _DBUS_POLLIN) > 0;
+              dbus_bool_t need_write = (poll_fd.revents & _DBUS_POLLOUT) > 0;
 
               _dbus_verbose ("in iteration, need_read=%d need_write=%d\n",
                              need_read, need_write);
@@ -1055,11 +933,9 @@ unix_do_iteration (DBusTransport *transport,
                 do_writing (transport);
             }
         }
-      else if (errno == EINTR)
-        goto again;
       else
         {
-          _dbus_verbose ("Error from select(): %s\n",
+          _dbus_verbose ("Error from _dbus_poll(): %s\n",
                          _dbus_strerror (errno));
         }
     }
@@ -1072,6 +948,18 @@ unix_live_messages_changed (DBusTransport *transport)
   check_read_watch (transport);
 }
 
+
+static dbus_bool_t
+unix_get_unix_fd (DBusTransport *transport,
+                  int           *fd_p)
+{
+  DBusTransportUnix *unix_transport = (DBusTransportUnix*) transport;
+  
+  *fd_p = unix_transport->fd;
+
+  return TRUE;
+}
+
 static DBusTransportVTable unix_vtable = {
   unix_finalize,
   unix_handle_watch,
@@ -1079,7 +967,8 @@ static DBusTransportVTable unix_vtable = {
   unix_connection_set,
   unix_messages_pending,
   unix_do_iteration,
-  unix_live_messages_changed
+  unix_live_messages_changed,
+  unix_get_unix_fd
 };
 
 /**
@@ -1090,11 +979,13 @@ static DBusTransportVTable unix_vtable = {
  *
  * @param fd the file descriptor.
  * @param server #TRUE if this transport is on the server side of a connection
+ * @param address the transport's address
  * @returns the new transport, or #NULL if no memory.
  */
 DBusTransport*
-_dbus_transport_new_for_fd (int         fd,
-                            dbus_bool_t server)
+_dbus_transport_new_for_fd (int               fd,
+                            dbus_bool_t       server,
+                            const DBusString *address)
 {
   DBusTransportUnix *unix_transport;
   
@@ -1102,21 +993,30 @@ _dbus_transport_new_for_fd (int         fd,
   if (unix_transport == NULL)
     return NULL;
 
-  if (!_dbus_string_init (&unix_transport->encoded_message,
-                          _DBUS_INT_MAX))
-    {
-      dbus_free (unix_transport);
-      return NULL;
-    }
+  if (!_dbus_string_init (&unix_transport->encoded_outgoing))
+    goto failed_0;
+
+  if (!_dbus_string_init (&unix_transport->encoded_incoming))
+    goto failed_1;
+  
+  unix_transport->write_watch = _dbus_watch_new (fd,
+                                                 DBUS_WATCH_WRITABLE,
+                                                 FALSE,
+                                                 NULL, NULL, NULL);
+  if (unix_transport->write_watch == NULL)
+    goto failed_2;
+  
+  unix_transport->read_watch = _dbus_watch_new (fd,
+                                                DBUS_WATCH_READABLE,
+                                                FALSE,
+                                                NULL, NULL, NULL);
+  if (unix_transport->read_watch == NULL)
+    goto failed_3;
   
   if (!_dbus_transport_init_base (&unix_transport->base,
                                   &unix_vtable,
-                                  server))
-    {
-      _dbus_string_free (&unix_transport->encoded_message);
-      dbus_free (unix_transport);
-      return NULL;
-    }
+                                  server, address))
+    goto failed_4;
   
   unix_transport->fd = fd;
   unix_transport->message_bytes_written = 0;
@@ -1124,48 +1024,91 @@ _dbus_transport_new_for_fd (int         fd,
   /* These values should probably be tunable or something. */     
   unix_transport->max_bytes_read_per_iteration = 2048;
   unix_transport->max_bytes_written_per_iteration = 2048;
-
-  check_read_watch ((DBusTransport*) unix_transport);
-  check_write_watch ((DBusTransport*) unix_transport);
   
   return (DBusTransport*) unix_transport;
+
+ failed_4:
+  _dbus_watch_unref (unix_transport->read_watch);
+ failed_3:
+  _dbus_watch_unref (unix_transport->write_watch);
+ failed_2:
+  _dbus_string_free (&unix_transport->encoded_incoming);
+ failed_1:
+  _dbus_string_free (&unix_transport->encoded_outgoing);
+ failed_0:
+  dbus_free (unix_transport);
+  return NULL;
 }
 
 /**
  * Creates a new transport for the given Unix domain socket
- * path.
+ * path. This creates a client-side of a transport.
+ *
+ * @todo once we add a way to escape paths in a dbus
+ * address, this function needs to do escaping.
  *
  * @param path the path to the domain socket.
- * @param server #TRUE if this transport is on the server side of a connection
- * @param result location to store reason for failure.
+ * @param abstract #TRUE to use abstract socket namespace
+ * @param error address where an error can be returned.
  * @returns a new transport, or #NULL on failure.
  */
 DBusTransport*
 _dbus_transport_new_for_domain_socket (const char     *path,
-                                       dbus_bool_t     server,
-                                       DBusResultCode *result)
+                                       dbus_bool_t     abstract,
+                                       DBusError      *error)
 {
   int fd;
   DBusTransport *transport;
+  DBusString address;
+  
+  _DBUS_ASSERT_ERROR_IS_CLEAR (error);
+
+  if (!_dbus_string_init (&address))
+    {
+      dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
+      return NULL;
+    }
+
+  fd = -1;
 
-  fd = _dbus_connect_unix_socket (path, result);
+  if ((abstract &&
+       !_dbus_string_append (&address, "unix:abstract=")) ||
+      (!abstract &&
+       !_dbus_string_append (&address, "unix:path=")) ||
+      !_dbus_string_append (&address, path))
+    {
+      dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
+      goto failed_0;
+    }
+  
+  fd = _dbus_connect_unix_socket (path, abstract, error);
   if (fd < 0)
-    return NULL;
+    {
+      _DBUS_ASSERT_ERROR_IS_SET (error);
+      goto failed_0;
+    }
 
   _dbus_fd_set_close_on_exec (fd);
   
   _dbus_verbose ("Successfully connected to unix socket %s\n",
                  path);
-  
-  transport = _dbus_transport_new_for_fd (fd, server);
+
+  transport = _dbus_transport_new_for_fd (fd, FALSE, &address);
   if (transport == NULL)
     {
-      dbus_set_result (result, DBUS_RESULT_NO_MEMORY);
-      _dbus_close (fd, NULL);
-      fd = -1;
+      dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
+      goto failed_1;
     }
   
+  _dbus_string_free (&address);
+  
   return transport;
+
+ failed_1:
+  _dbus_close (fd, NULL);
+ failed_0:
+  _dbus_string_free (&address);
+  return NULL;
 }
 
 /**
@@ -1173,36 +1116,60 @@ _dbus_transport_new_for_domain_socket (const char     *path,
  *
  * @param host the host to connect to
  * @param port the port to connect to
- * @param server #TRUE if this transport is on the server side of a connection
- * @param result location to store reason for failure.
+ * @param error location to store reason for failure.
  * @returns a new transport, or #NULL on failure.
  */
 DBusTransport*
 _dbus_transport_new_for_tcp_socket (const char     *host,
                                     dbus_int32_t    port,
-                                    dbus_bool_t     server,
-                                    DBusResultCode *result)
+                                    DBusError      *error)
 {
   int fd;
   DBusTransport *transport;
+  DBusString address;
+  
+  _DBUS_ASSERT_ERROR_IS_CLEAR (error);
+
+  if (!_dbus_string_init (&address))
+    {
+      dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
+      return NULL;
+    }
+  
+  if (!_dbus_string_append (&address, "tcp:host=") ||
+      !_dbus_string_append (&address, host) ||
+      !_dbus_string_append (&address, ",port=") ||
+      !_dbus_string_append_int (&address, port))
+    {
+      _dbus_string_free (&address);
+      dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
+      return NULL;
+    }
   
-  fd = _dbus_connect_tcp_socket (host, port, result);
+  fd = _dbus_connect_tcp_socket (host, port, error);
   if (fd < 0)
-    return NULL;
+    {
+      _DBUS_ASSERT_ERROR_IS_SET (error);
+      _dbus_string_free (&address);
+      return NULL;
+    }
 
   _dbus_fd_set_close_on_exec (fd);
   
   _dbus_verbose ("Successfully connected to tcp socket %s:%d\n",
                  host, port);
   
-  transport = _dbus_transport_new_for_fd (fd, server);
+  transport = _dbus_transport_new_for_fd (fd, FALSE, &address);
   if (transport == NULL)
     {
-      dbus_set_result (result, DBUS_RESULT_NO_MEMORY);
+      dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
       _dbus_close (fd, NULL);
+      _dbus_string_free (&address);
       fd = -1;
     }
 
+  _dbus_string_free (&address);
+  
   return transport;
 }