Revert "Rename authorized_identity in authenticated_identity for clarity sake."
[platform/upstream/dbus.git] / dbus / dbus-auth.c
1 /* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */
2 /* dbus-auth.c Authentication
3  *
4  * Copyright (C) 2002, 2003, 2004 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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
21  *
22  */
23
24 #include <config.h>
25 #include "dbus-auth.h"
26 #include "dbus-string.h"
27 #include "dbus-list.h"
28 #include "dbus-internals.h"
29 #include "dbus-keyring.h"
30 #include "dbus-sha.h"
31 #include "dbus-protocol.h"
32 #include "dbus-credentials.h"
33 #include "dbus-authorization.h"
34
35 /**
36  * @defgroup DBusAuth Authentication
37  * @ingroup  DBusInternals
38  * @brief DBusAuth object
39  *
40  * DBusAuth manages the authentication negotiation when a connection
41  * is first established, and also manage any encryption used over a
42  * connection.
43  *
44  * @todo some SASL profiles require sending the empty string as a
45  * challenge/response, but we don't currently allow that in our
46  * protocol.
47  *
48  * @todo right now sometimes both ends will block waiting for input
49  * from the other end, e.g. if there's an error during
50  * DBUS_COOKIE_SHA1.
51  *
52  * @todo the cookie keyring needs to be cached globally not just
53  * per-auth (which raises threadsafety issues too)
54  * 
55  * @todo grep FIXME in dbus-auth.c
56  */
57
58 /**
59  * @defgroup DBusAuthInternals Authentication implementation details
60  * @ingroup  DBusInternals
61  * @brief DBusAuth implementation details
62  *
63  * Private details of authentication code.
64  *
65  * @{
66  */
67
68 /**
69  * This function appends an initial client response to the given string
70  */
71 typedef dbus_bool_t (* DBusInitialResponseFunction)  (DBusAuth         *auth,
72                                                       DBusString       *response);
73
74 /**
75  * This function processes a block of data received from the peer.
76  * i.e. handles a DATA command.
77  */
78 typedef dbus_bool_t (* DBusAuthDataFunction)     (DBusAuth         *auth,
79                                                   const DBusString *data);
80
81 /**
82  * This function encodes a block of data from the peer.
83  */
84 typedef dbus_bool_t (* DBusAuthEncodeFunction)   (DBusAuth         *auth,
85                                                   const DBusString *data,
86                                                   DBusString       *encoded);
87
88 /**
89  * This function decodes a block of data from the peer.
90  */
91 typedef dbus_bool_t (* DBusAuthDecodeFunction)   (DBusAuth         *auth,
92                                                   const DBusString *data,
93                                                   DBusString       *decoded);
94
95 /**
96  * This function is called when the mechanism is abandoned.
97  */
98 typedef void        (* DBusAuthShutdownFunction) (DBusAuth       *auth);
99
100 /**
101  * Virtual table representing a particular auth mechanism.
102  */
103 typedef struct
104 {
105   const char *mechanism; /**< Name of the mechanism */
106   DBusAuthDataFunction server_data_func; /**< Function on server side for DATA */
107   DBusAuthEncodeFunction server_encode_func; /**< Function on server side to encode */
108   DBusAuthDecodeFunction server_decode_func; /**< Function on server side to decode */
109   DBusAuthShutdownFunction server_shutdown_func; /**< Function on server side to shut down */
110   DBusInitialResponseFunction client_initial_response_func; /**< Function on client side to handle initial response */
111   DBusAuthDataFunction client_data_func; /**< Function on client side for DATA */
112   DBusAuthEncodeFunction client_encode_func; /**< Function on client side for encode */
113   DBusAuthDecodeFunction client_decode_func; /**< Function on client side for decode */
114   DBusAuthShutdownFunction client_shutdown_func; /**< Function on client side for shutdown */
115 } DBusAuthMechanismHandler;
116
117 /**
118  * Enumeration for the known authentication commands.
119  */
120 typedef enum {
121   DBUS_AUTH_COMMAND_AUTH,
122   DBUS_AUTH_COMMAND_CANCEL,
123   DBUS_AUTH_COMMAND_DATA,
124   DBUS_AUTH_COMMAND_BEGIN,
125   DBUS_AUTH_COMMAND_REJECTED,
126   DBUS_AUTH_COMMAND_OK,
127   DBUS_AUTH_COMMAND_ERROR,
128   DBUS_AUTH_COMMAND_UNKNOWN,
129   DBUS_AUTH_COMMAND_NEGOTIATE_UNIX_FD,
130   DBUS_AUTH_COMMAND_AGREE_UNIX_FD
131 } DBusAuthCommand;
132
133 /**
134  * Auth state function, determines the reaction to incoming events for
135  * a particular state. Returns whether we had enough memory to
136  * complete the operation.
137  */
138 typedef dbus_bool_t (* DBusAuthStateFunction) (DBusAuth         *auth,
139                                                DBusAuthCommand   command,
140                                                const DBusString *args);
141
142 /**
143  * Information about a auth state.
144  */
145 typedef struct
146 {
147   const char *name;               /**< Name of the state */
148   DBusAuthStateFunction handler;  /**< State function for this state */
149 } DBusAuthStateData;
150
151 /**
152  * Internal members of DBusAuth.
153  */
154 struct DBusAuth
155 {
156   int refcount;           /**< reference count */
157   const char *side;       /**< Client or server */
158
159   DBusString incoming;    /**< Incoming data buffer */
160   DBusString outgoing;    /**< Outgoing data buffer */
161   
162   const DBusAuthStateData *state;         /**< Current protocol state */
163
164   const DBusAuthMechanismHandler *mech;   /**< Current auth mechanism */
165
166   DBusString identity;                   /**< Current identity we're authorizing
167                                           *   as.
168                                           */
169   
170   DBusCredentials *credentials;          /**< Credentials read from socket
171                                           */
172
173   DBusCredentials *authorized_identity; /**< Credentials that are authorized */
174
175   DBusCredentials *desired_identity;    /**< Identity client has requested */
176   
177   DBusString context;               /**< Cookie scope */
178   DBusKeyring *keyring;             /**< Keyring for cookie mechanism. */
179   int cookie_id;                    /**< ID of cookie to use */
180   DBusString challenge;             /**< Challenge sent to client */
181
182   char **allowed_mechs;             /**< Mechanisms we're allowed to use,
183                                      * or #NULL if we can use any
184                                      */
185   
186   unsigned int needed_memory : 1;   /**< We needed memory to continue since last
187                                      * successful getting something done
188                                      */
189   unsigned int already_got_mechanisms : 1;       /**< Client already got mech list */
190   unsigned int already_asked_for_initial_response : 1; /**< Already sent a blank challenge to get an initial response */
191   unsigned int buffer_outstanding : 1; /**< Buffer is "checked out" for reading data into */
192
193   unsigned int unix_fd_possible : 1;  /**< This side could do unix fd passing */
194   unsigned int unix_fd_negotiated : 1; /**< Unix fd was successfully negotiated */
195 };
196
197 /**
198  * "Subclass" of DBusAuth for client side
199  */
200 typedef struct
201 {
202   DBusAuth base;    /**< Parent class */
203
204   DBusList *mechs_to_try; /**< Mechanisms we got from the server that we're going to try using */
205
206   DBusString guid_from_server; /**< GUID received from server */
207   
208 } DBusAuthClient;
209
210 /**
211  * "Subclass" of DBusAuth for server side.
212  */
213 typedef struct
214 {
215   DBusAuth base;    /**< Parent class */
216
217   DBusAuthorization *authorization;             /* DBus Authorization callbacks */
218
219   int failures;     /**< Number of times client has been rejected */
220   int max_failures; /**< Number of times we reject before disconnect */
221
222   DBusString guid;  /**< Our globally unique ID in hex encoding */
223   
224 } DBusAuthServer;
225
226 static void        goto_state                (DBusAuth                       *auth,
227                                               const DBusAuthStateData        *new_state);
228 static dbus_bool_t send_auth                 (DBusAuth *auth,
229                                               const DBusAuthMechanismHandler *mech);
230 static dbus_bool_t send_data                 (DBusAuth *auth,
231                                               DBusString *data);
232 static dbus_bool_t send_rejected             (DBusAuth *auth);
233 static dbus_bool_t send_error                (DBusAuth *auth,
234                                               const char *message);
235 static dbus_bool_t send_ok                   (DBusAuth *auth);
236 static dbus_bool_t send_begin                (DBusAuth *auth);
237 static dbus_bool_t send_cancel               (DBusAuth *auth);
238 static dbus_bool_t send_negotiate_unix_fd    (DBusAuth *auth);
239 static dbus_bool_t send_agree_unix_fd        (DBusAuth *auth);
240
241 /**
242  * Client states
243  */
244  
245 static dbus_bool_t handle_server_state_waiting_for_auth  (DBusAuth         *auth,
246                                                           DBusAuthCommand   command,
247                                                           const DBusString *args);
248 static dbus_bool_t handle_server_state_waiting_for_data  (DBusAuth         *auth,
249                                                           DBusAuthCommand   command,
250                                                           const DBusString *args);
251 static dbus_bool_t handle_server_state_waiting_for_begin (DBusAuth         *auth,
252                                                           DBusAuthCommand   command,
253                                                           const DBusString *args);
254   
255 static const DBusAuthStateData server_state_waiting_for_auth = {
256   "WaitingForAuth", handle_server_state_waiting_for_auth
257 };
258 static const DBusAuthStateData server_state_waiting_for_data = {
259   "WaitingForData", handle_server_state_waiting_for_data
260 };
261 static const DBusAuthStateData server_state_waiting_for_begin = {
262   "WaitingForBegin", handle_server_state_waiting_for_begin
263 };
264   
265 /**
266  * Client states
267  */
268  
269 static dbus_bool_t handle_client_state_waiting_for_data   (DBusAuth         *auth,
270                                                            DBusAuthCommand   command,
271                                                            const DBusString *args);
272 static dbus_bool_t handle_client_state_waiting_for_ok     (DBusAuth         *auth,
273                                                            DBusAuthCommand   command,
274                                                            const DBusString *args);
275 static dbus_bool_t handle_client_state_waiting_for_reject (DBusAuth         *auth,
276                                                            DBusAuthCommand   command,
277                                                            const DBusString *args);
278 static dbus_bool_t handle_client_state_waiting_for_agree_unix_fd (DBusAuth         *auth,
279                                                            DBusAuthCommand   command,
280                                                            const DBusString *args);
281
282 static const DBusAuthStateData client_state_need_send_auth = {
283   "NeedSendAuth", NULL
284 };
285 static const DBusAuthStateData client_state_waiting_for_data = {
286   "WaitingForData", handle_client_state_waiting_for_data
287 };
288 static const DBusAuthStateData client_state_waiting_for_ok = {
289   "WaitingForOK", handle_client_state_waiting_for_ok
290 };
291 static const DBusAuthStateData client_state_waiting_for_reject = {
292   "WaitingForReject", handle_client_state_waiting_for_reject
293 };
294 static const DBusAuthStateData client_state_waiting_for_agree_unix_fd = {
295   "WaitingForAgreeUnixFD", handle_client_state_waiting_for_agree_unix_fd
296 };
297
298 /**
299  * Common terminal states.  Terminal states have handler == NULL.
300  */
301
302 static const DBusAuthStateData common_state_authenticated = {
303   "Authenticated",  NULL
304 };
305
306 static const DBusAuthStateData common_state_need_disconnect = {
307   "NeedDisconnect",  NULL
308 };
309
310 static const char auth_side_client[] = "client";
311 static const char auth_side_server[] = "server";
312 /**
313  * @param auth the auth conversation
314  * @returns #TRUE if the conversation is the server side
315  */
316 #define DBUS_AUTH_IS_SERVER(auth) ((auth)->side == auth_side_server)
317 /**
318  * @param auth the auth conversation
319  * @returns #TRUE if the conversation is the client side
320  */
321 #define DBUS_AUTH_IS_CLIENT(auth) ((auth)->side == auth_side_client)
322 /**
323  * @param auth the auth conversation
324  * @returns auth cast to DBusAuthClient
325  */
326 #define DBUS_AUTH_CLIENT(auth)    ((DBusAuthClient*)(auth))
327 /**
328  * @param auth the auth conversation
329  * @returns auth cast to DBusAuthServer
330  */
331 #define DBUS_AUTH_SERVER(auth)    ((DBusAuthServer*)(auth))
332
333 /**
334  * The name of the auth ("client" or "server")
335  * @param auth the auth conversation
336  * @returns a string
337  */
338 #define DBUS_AUTH_NAME(auth)      ((auth)->side)
339
340 static DBusAuth*
341 _dbus_auth_new (int size)
342 {
343   DBusAuth *auth;
344   
345   auth = dbus_malloc0 (size);
346   if (auth == NULL)
347     return NULL;
348   
349   auth->refcount = 1;
350   
351   auth->keyring = NULL;
352   auth->cookie_id = -1;
353   
354   /* note that we don't use the max string length feature,
355    * because you can't use that feature if you're going to
356    * try to recover from out-of-memory (it creates
357    * what looks like unrecoverable inability to alloc
358    * more space in the string). But we do handle
359    * overlong buffers in _dbus_auth_do_work().
360    */
361   
362   if (!_dbus_string_init (&auth->incoming))
363     goto enomem_0;
364
365   if (!_dbus_string_init (&auth->outgoing))
366     goto enomem_1;
367     
368   if (!_dbus_string_init (&auth->identity))
369     goto enomem_2;
370
371   if (!_dbus_string_init (&auth->context))
372     goto enomem_3;
373
374   if (!_dbus_string_init (&auth->challenge))
375     goto enomem_4;
376
377   /* default context if none is specified */
378   if (!_dbus_string_append (&auth->context, "org_freedesktop_general"))
379     goto enomem_5;
380
381   auth->credentials = _dbus_credentials_new ();
382   if (auth->credentials == NULL)
383     goto enomem_6;
384   
385   auth->authorized_identity = _dbus_credentials_new ();
386   if (auth->authorized_identity == NULL)
387     goto enomem_7;
388
389   auth->desired_identity = _dbus_credentials_new ();
390   if (auth->desired_identity == NULL)
391     goto enomem_8;
392   
393   return auth;
394
395 #if 0
396  enomem_9:
397   _dbus_credentials_unref (auth->desired_identity);
398 #endif
399  enomem_8:
400   _dbus_credentials_unref (auth->authorized_identity);
401  enomem_7:
402   _dbus_credentials_unref (auth->credentials);
403  enomem_6:
404  /* last alloc was an append to context, which is freed already below */ ;
405  enomem_5:
406   _dbus_string_free (&auth->challenge);
407  enomem_4:
408   _dbus_string_free (&auth->context);
409  enomem_3:
410   _dbus_string_free (&auth->identity);
411  enomem_2:
412   _dbus_string_free (&auth->outgoing);
413  enomem_1:
414   _dbus_string_free (&auth->incoming);
415  enomem_0:
416   dbus_free (auth);
417   return NULL;
418 }
419
420 static void
421 shutdown_mech (DBusAuth *auth)
422 {
423   /* Cancel any auth */
424   auth->already_asked_for_initial_response = FALSE;
425   _dbus_string_set_length (&auth->identity, 0);
426
427   _dbus_credentials_clear (auth->authorized_identity);
428   _dbus_credentials_clear (auth->desired_identity);
429   
430   if (auth->mech != NULL)
431     {
432       _dbus_verbose ("%s: Shutting down mechanism %s\n",
433                      DBUS_AUTH_NAME (auth), auth->mech->mechanism);
434       
435       if (DBUS_AUTH_IS_CLIENT (auth))
436         (* auth->mech->client_shutdown_func) (auth);
437       else
438         (* auth->mech->server_shutdown_func) (auth);
439       
440       auth->mech = NULL;
441     }
442 }
443
444 /*
445  * DBUS_COOKIE_SHA1 mechanism
446  */
447
448 /* Returns TRUE but with an empty string hash if the
449  * cookie_id isn't known. As with all this code
450  * TRUE just means we had enough memory.
451  */
452 static dbus_bool_t
453 sha1_compute_hash (DBusAuth         *auth,
454                    int               cookie_id,
455                    const DBusString *server_challenge,
456                    const DBusString *client_challenge,
457                    DBusString       *hash)
458 {
459   DBusString cookie;
460   DBusString to_hash;
461   dbus_bool_t retval;
462   
463   _dbus_assert (auth->keyring != NULL);
464
465   retval = FALSE;
466   
467   if (!_dbus_string_init (&cookie))
468     return FALSE;
469
470   if (!_dbus_keyring_get_hex_key (auth->keyring, cookie_id,
471                                   &cookie))
472     goto out_0;
473
474   if (_dbus_string_get_length (&cookie) == 0)
475     {
476       retval = TRUE;
477       goto out_0;
478     }
479
480   if (!_dbus_string_init (&to_hash))
481     goto out_0;
482   
483   if (!_dbus_string_copy (server_challenge, 0,
484                           &to_hash, _dbus_string_get_length (&to_hash)))
485     goto out_1;
486
487   if (!_dbus_string_append (&to_hash, ":"))
488     goto out_1;
489   
490   if (!_dbus_string_copy (client_challenge, 0,
491                           &to_hash, _dbus_string_get_length (&to_hash)))
492     goto out_1;
493
494   if (!_dbus_string_append (&to_hash, ":"))
495     goto out_1;
496
497   if (!_dbus_string_copy (&cookie, 0,
498                           &to_hash, _dbus_string_get_length (&to_hash)))
499     goto out_1;
500
501   if (!_dbus_sha_compute (&to_hash, hash))
502     goto out_1;
503   
504   retval = TRUE;
505
506  out_1:
507   _dbus_string_zero (&to_hash);
508   _dbus_string_free (&to_hash);
509  out_0:
510   _dbus_string_zero (&cookie);
511   _dbus_string_free (&cookie);
512   return retval;
513 }
514
515 /** http://www.ietf.org/rfc/rfc2831.txt suggests at least 64 bits of
516  * entropy, we use 128. This is the number of bytes in the random
517  * challenge.
518  */
519 #define N_CHALLENGE_BYTES (128/8)
520
521 static dbus_bool_t
522 sha1_handle_first_client_response (DBusAuth         *auth,
523                                    const DBusString *data)
524 {
525   /* We haven't sent a challenge yet, we're expecting a desired
526    * username from the client.
527    */
528   DBusString tmp;
529   DBusString tmp2;
530   dbus_bool_t retval;
531   DBusError error;
532   
533   retval = FALSE;
534
535   _dbus_string_set_length (&auth->challenge, 0);
536   
537   if (_dbus_string_get_length (data) > 0)
538     {
539       if (_dbus_string_get_length (&auth->identity) > 0)
540         {
541           /* Tried to send two auth identities, wtf */
542           _dbus_verbose ("%s: client tried to send auth identity, but we already have one\n",
543                          DBUS_AUTH_NAME (auth));
544           return send_rejected (auth);
545         }
546       else
547         {
548           /* this is our auth identity */
549           if (!_dbus_string_copy (data, 0, &auth->identity, 0))
550             return FALSE;
551         }
552     }
553       
554   if (!_dbus_credentials_add_from_user (auth->desired_identity, data))
555     {
556       _dbus_verbose ("%s: Did not get a valid username from client\n",
557                      DBUS_AUTH_NAME (auth));
558       return send_rejected (auth);
559     }
560       
561   if (!_dbus_string_init (&tmp))
562     return FALSE;
563
564   if (!_dbus_string_init (&tmp2))
565     {
566       _dbus_string_free (&tmp);
567       return FALSE;
568     }
569
570   /* we cache the keyring for speed, so here we drop it if it's the
571    * wrong one. FIXME caching the keyring here is useless since we use
572    * a different DBusAuth for every connection.
573    */
574   if (auth->keyring &&
575       !_dbus_keyring_is_for_credentials (auth->keyring,
576                                          auth->desired_identity))
577     {
578       _dbus_keyring_unref (auth->keyring);
579       auth->keyring = NULL;
580     }
581   
582   if (auth->keyring == NULL)
583     {
584       dbus_error_init (&error);
585       auth->keyring = _dbus_keyring_new_for_credentials (auth->desired_identity,
586                                                          &auth->context,
587                                                          &error);
588
589       if (auth->keyring == NULL)
590         {
591           if (dbus_error_has_name (&error,
592                                    DBUS_ERROR_NO_MEMORY))
593             {
594               dbus_error_free (&error);
595               goto out;
596             }
597           else
598             {
599               _DBUS_ASSERT_ERROR_IS_SET (&error);
600               _dbus_verbose ("%s: Error loading keyring: %s\n",
601                              DBUS_AUTH_NAME (auth), error.message);
602               if (send_rejected (auth))
603                 retval = TRUE; /* retval is only about mem */
604               dbus_error_free (&error);
605               goto out;
606             }
607         }
608       else
609         {
610           _dbus_assert (!dbus_error_is_set (&error));
611         }
612     }
613
614   _dbus_assert (auth->keyring != NULL);
615
616   dbus_error_init (&error);
617   auth->cookie_id = _dbus_keyring_get_best_key (auth->keyring, &error);
618   if (auth->cookie_id < 0)
619     {
620       _DBUS_ASSERT_ERROR_IS_SET (&error);
621       _dbus_verbose ("%s: Could not get a cookie ID to send to client: %s\n",
622                      DBUS_AUTH_NAME (auth), error.message);
623       if (send_rejected (auth))
624         retval = TRUE;
625       dbus_error_free (&error);
626       goto out;
627     }
628   else
629     {
630       _dbus_assert (!dbus_error_is_set (&error));
631     }
632
633   if (!_dbus_string_copy (&auth->context, 0,
634                           &tmp2, _dbus_string_get_length (&tmp2)))
635     goto out;
636
637   if (!_dbus_string_append (&tmp2, " "))
638     goto out;
639
640   if (!_dbus_string_append_int (&tmp2, auth->cookie_id))
641     goto out;
642
643   if (!_dbus_string_append (&tmp2, " "))
644     goto out;  
645   
646   if (!_dbus_generate_random_bytes (&tmp, N_CHALLENGE_BYTES))
647     goto out;
648
649   _dbus_string_set_length (&auth->challenge, 0);
650   if (!_dbus_string_hex_encode (&tmp, 0, &auth->challenge, 0))
651     goto out;
652   
653   if (!_dbus_string_hex_encode (&tmp, 0, &tmp2,
654                                 _dbus_string_get_length (&tmp2)))
655     goto out;
656
657   if (!send_data (auth, &tmp2))
658     goto out;
659       
660   goto_state (auth, &server_state_waiting_for_data);
661   retval = TRUE;
662   
663  out:
664   _dbus_string_zero (&tmp);
665   _dbus_string_free (&tmp);
666   _dbus_string_zero (&tmp2);
667   _dbus_string_free (&tmp2);
668
669   return retval;
670 }
671
672 static dbus_bool_t
673 sha1_handle_second_client_response (DBusAuth         *auth,
674                                     const DBusString *data)
675 {
676   /* We are expecting a response which is the hex-encoded client
677    * challenge, space, then SHA-1 hash of the concatenation of our
678    * challenge, ":", client challenge, ":", secret key, all
679    * hex-encoded.
680    */
681   int i;
682   DBusString client_challenge;
683   DBusString client_hash;
684   dbus_bool_t retval;
685   DBusString correct_hash;
686   
687   retval = FALSE;
688   
689   if (!_dbus_string_find_blank (data, 0, &i))
690     {
691       _dbus_verbose ("%s: no space separator in client response\n",
692                      DBUS_AUTH_NAME (auth));
693       return send_rejected (auth);
694     }
695   
696   if (!_dbus_string_init (&client_challenge))
697     goto out_0;
698
699   if (!_dbus_string_init (&client_hash))
700     goto out_1;  
701
702   if (!_dbus_string_copy_len (data, 0, i, &client_challenge,
703                               0))
704     goto out_2;
705
706   _dbus_string_skip_blank (data, i, &i);
707   
708   if (!_dbus_string_copy_len (data, i,
709                               _dbus_string_get_length (data) - i,
710                               &client_hash,
711                               0))
712     goto out_2;
713
714   if (_dbus_string_get_length (&client_challenge) == 0 ||
715       _dbus_string_get_length (&client_hash) == 0)
716     {
717       _dbus_verbose ("%s: zero-length client challenge or hash\n",
718                      DBUS_AUTH_NAME (auth));
719       if (send_rejected (auth))
720         retval = TRUE;
721       goto out_2;
722     }
723
724   if (!_dbus_string_init (&correct_hash))
725     goto out_2;
726
727   if (!sha1_compute_hash (auth, auth->cookie_id,
728                           &auth->challenge, 
729                           &client_challenge,
730                           &correct_hash))
731     goto out_3;
732
733   /* if cookie_id was invalid, then we get an empty hash */
734   if (_dbus_string_get_length (&correct_hash) == 0)
735     {
736       if (send_rejected (auth))
737         retval = TRUE;
738       goto out_3;
739     }
740   
741   if (!_dbus_string_equal (&client_hash, &correct_hash))
742     {
743       if (send_rejected (auth))
744         retval = TRUE;
745       goto out_3;
746     }
747
748   if (!_dbus_credentials_add_credentials (auth->authorized_identity,
749                                           auth->desired_identity))
750     goto out_3;
751
752   /* Copy process ID from the socket credentials if it's there
753    */
754   if (!_dbus_credentials_add_credential (auth->authorized_identity,
755                                          DBUS_CREDENTIAL_UNIX_PROCESS_ID,
756                                          auth->credentials))
757     goto out_3;
758   
759   if (!send_ok (auth))
760     goto out_3;
761
762   _dbus_verbose ("%s: authenticated client using DBUS_COOKIE_SHA1\n",
763                  DBUS_AUTH_NAME (auth));
764   
765   retval = TRUE;
766   
767  out_3:
768   _dbus_string_zero (&correct_hash);
769   _dbus_string_free (&correct_hash);
770  out_2:
771   _dbus_string_zero (&client_hash);
772   _dbus_string_free (&client_hash);
773  out_1:
774   _dbus_string_free (&client_challenge);
775  out_0:
776   return retval;
777 }
778
779 static dbus_bool_t
780 handle_server_data_cookie_sha1_mech (DBusAuth         *auth,
781                                      const DBusString *data)
782 {
783   if (auth->cookie_id < 0)
784     return sha1_handle_first_client_response (auth, data);
785   else
786     return sha1_handle_second_client_response (auth, data);
787 }
788
789 static void
790 handle_server_shutdown_cookie_sha1_mech (DBusAuth *auth)
791 {
792   auth->cookie_id = -1;  
793   _dbus_string_set_length (&auth->challenge, 0);
794 }
795
796 static dbus_bool_t
797 handle_client_initial_response_cookie_sha1_mech (DBusAuth   *auth,
798                                                  DBusString *response)
799 {
800   DBusString username;
801   dbus_bool_t retval;
802
803   retval = FALSE;
804
805   if (!_dbus_string_init (&username))
806     return FALSE;
807   
808   if (!_dbus_append_user_from_current_process (&username))
809     goto out_0;
810
811   if (!_dbus_string_hex_encode (&username, 0,
812                                 response,
813                                 _dbus_string_get_length (response)))
814     goto out_0;
815
816   retval = TRUE;
817   
818  out_0:
819   _dbus_string_free (&username);
820   
821   return retval;
822 }
823
824 static dbus_bool_t
825 handle_client_data_cookie_sha1_mech (DBusAuth         *auth,
826                                      const DBusString *data)
827 {
828   /* The data we get from the server should be the cookie context
829    * name, the cookie ID, and the server challenge, separated by
830    * spaces. We send back our challenge string and the correct hash.
831    */
832   dbus_bool_t retval;
833   DBusString context;
834   DBusString cookie_id_str;
835   DBusString server_challenge;
836   DBusString client_challenge;
837   DBusString correct_hash;
838   DBusString tmp;
839   int i, j;
840   long val;
841   
842   retval = FALSE;                 
843   
844   if (!_dbus_string_find_blank (data, 0, &i))
845     {
846       if (send_error (auth,
847                       "Server did not send context/ID/challenge properly"))
848         retval = TRUE;
849       goto out_0;
850     }
851
852   if (!_dbus_string_init (&context))
853     goto out_0;
854
855   if (!_dbus_string_copy_len (data, 0, i,
856                               &context, 0))
857     goto out_1;
858   
859   _dbus_string_skip_blank (data, i, &i);
860   if (!_dbus_string_find_blank (data, i, &j))
861     {
862       if (send_error (auth,
863                       "Server did not send context/ID/challenge properly"))
864         retval = TRUE;
865       goto out_1;
866     }
867
868   if (!_dbus_string_init (&cookie_id_str))
869     goto out_1;
870   
871   if (!_dbus_string_copy_len (data, i, j - i,
872                               &cookie_id_str, 0))
873     goto out_2;  
874
875   if (!_dbus_string_init (&server_challenge))
876     goto out_2;
877
878   i = j;
879   _dbus_string_skip_blank (data, i, &i);
880   j = _dbus_string_get_length (data);
881
882   if (!_dbus_string_copy_len (data, i, j - i,
883                               &server_challenge, 0))
884     goto out_3;
885
886   if (!_dbus_keyring_validate_context (&context))
887     {
888       if (send_error (auth, "Server sent invalid cookie context"))
889         retval = TRUE;
890       goto out_3;
891     }
892
893   if (!_dbus_string_parse_int (&cookie_id_str, 0, &val, NULL))
894     {
895       if (send_error (auth, "Could not parse cookie ID as an integer"))
896         retval = TRUE;
897       goto out_3;
898     }
899
900   if (_dbus_string_get_length (&server_challenge) == 0)
901     {
902       if (send_error (auth, "Empty server challenge string"))
903         retval = TRUE;
904       goto out_3;
905     }
906
907   if (auth->keyring == NULL)
908     {
909       DBusError error;
910
911       dbus_error_init (&error);
912       auth->keyring = _dbus_keyring_new_for_credentials (NULL,
913                                                          &context,
914                                                          &error);
915
916       if (auth->keyring == NULL)
917         {
918           if (dbus_error_has_name (&error,
919                                    DBUS_ERROR_NO_MEMORY))
920             {
921               dbus_error_free (&error);
922               goto out_3;
923             }
924           else
925             {
926               _DBUS_ASSERT_ERROR_IS_SET (&error);
927
928               _dbus_verbose ("%s: Error loading keyring: %s\n",
929                              DBUS_AUTH_NAME (auth), error.message);
930               
931               if (send_error (auth, "Could not load cookie file"))
932                 retval = TRUE; /* retval is only about mem */
933               
934               dbus_error_free (&error);
935               goto out_3;
936             }
937         }
938       else
939         {
940           _dbus_assert (!dbus_error_is_set (&error));
941         }
942     }
943   
944   _dbus_assert (auth->keyring != NULL);
945   
946   if (!_dbus_string_init (&tmp))
947     goto out_3;
948   
949   if (!_dbus_generate_random_bytes (&tmp, N_CHALLENGE_BYTES))
950     goto out_4;
951
952   if (!_dbus_string_init (&client_challenge))
953     goto out_4;
954
955   if (!_dbus_string_hex_encode (&tmp, 0, &client_challenge, 0))
956     goto out_5;
957
958   if (!_dbus_string_init (&correct_hash))
959     goto out_5;
960   
961   if (!sha1_compute_hash (auth, val,
962                           &server_challenge,
963                           &client_challenge,
964                           &correct_hash))
965     goto out_6;
966
967   if (_dbus_string_get_length (&correct_hash) == 0)
968     {
969       /* couldn't find the cookie ID or something */
970       if (send_error (auth, "Don't have the requested cookie ID"))
971         retval = TRUE;
972       goto out_6;
973     }
974   
975   _dbus_string_set_length (&tmp, 0);
976   
977   if (!_dbus_string_copy (&client_challenge, 0, &tmp,
978                           _dbus_string_get_length (&tmp)))
979     goto out_6;
980
981   if (!_dbus_string_append (&tmp, " "))
982     goto out_6;
983
984   if (!_dbus_string_copy (&correct_hash, 0, &tmp,
985                           _dbus_string_get_length (&tmp)))
986     goto out_6;
987
988   if (!send_data (auth, &tmp))
989     goto out_6;
990
991   retval = TRUE;
992
993  out_6:
994   _dbus_string_zero (&correct_hash);
995   _dbus_string_free (&correct_hash);
996  out_5:
997   _dbus_string_free (&client_challenge);
998  out_4:
999   _dbus_string_zero (&tmp);
1000   _dbus_string_free (&tmp);
1001  out_3:
1002   _dbus_string_free (&server_challenge);
1003  out_2:
1004   _dbus_string_free (&cookie_id_str);
1005  out_1:
1006   _dbus_string_free (&context);
1007  out_0:
1008   return retval;
1009 }
1010
1011 static void
1012 handle_client_shutdown_cookie_sha1_mech (DBusAuth *auth)
1013 {
1014   auth->cookie_id = -1;  
1015   _dbus_string_set_length (&auth->challenge, 0);
1016 }
1017
1018 /*
1019  * EXTERNAL mechanism
1020  */
1021
1022 static dbus_bool_t
1023 handle_server_data_external_mech (DBusAuth         *auth,
1024                                   const DBusString *data)
1025 {
1026   if (_dbus_credentials_are_anonymous (auth->credentials))
1027     {
1028       _dbus_verbose ("%s: no credentials, mechanism EXTERNAL can't authenticate\n",
1029                      DBUS_AUTH_NAME (auth));
1030       return send_rejected (auth);
1031     }
1032   
1033   if (_dbus_string_get_length (data) > 0)
1034     {
1035       if (_dbus_string_get_length (&auth->identity) > 0)
1036         {
1037           /* Tried to send two auth identities, wtf */
1038           _dbus_verbose ("%s: client tried to send auth identity, but we already have one\n",
1039                          DBUS_AUTH_NAME (auth));
1040           return send_rejected (auth);
1041         }
1042       else
1043         {
1044           /* this is our auth identity */
1045           if (!_dbus_string_copy (data, 0, &auth->identity, 0))
1046             return FALSE;
1047         }
1048     }
1049
1050   /* Poke client for an auth identity, if none given */
1051   if (_dbus_string_get_length (&auth->identity) == 0 &&
1052       !auth->already_asked_for_initial_response)
1053     {
1054       if (send_data (auth, NULL))
1055         {
1056           _dbus_verbose ("%s: sending empty challenge asking client for auth identity\n",
1057                          DBUS_AUTH_NAME (auth));
1058           auth->already_asked_for_initial_response = TRUE;
1059           goto_state (auth, &server_state_waiting_for_data);
1060           return TRUE;
1061         }
1062       else
1063         return FALSE;
1064     }
1065
1066   _dbus_credentials_clear (auth->desired_identity);
1067   
1068   /* If auth->identity is still empty here, then client
1069    * responded with an empty string after we poked it for
1070    * an initial response. This means to try to auth the
1071    * identity provided in the credentials.
1072    */
1073   if (_dbus_string_get_length (&auth->identity) == 0)
1074     {
1075       if (!_dbus_credentials_add_credentials (auth->desired_identity,
1076                                               auth->credentials))
1077         {
1078           return FALSE; /* OOM */
1079         }
1080     }
1081   else
1082     {
1083       if (!_dbus_credentials_add_from_user (auth->desired_identity,
1084                                             &auth->identity))
1085         {
1086           _dbus_verbose ("%s: could not get credentials from uid string\n",
1087                          DBUS_AUTH_NAME (auth));
1088           return send_rejected (auth);
1089         }
1090     }
1091
1092   if (_dbus_credentials_are_anonymous (auth->desired_identity))
1093     {
1094       _dbus_verbose ("%s: desired user %s is no good\n",
1095                      DBUS_AUTH_NAME (auth),
1096                      _dbus_string_get_const_data (&auth->identity));
1097       return send_rejected (auth);
1098     }
1099   
1100   if (_dbus_credentials_are_superset (auth->credentials,
1101                                       auth->desired_identity))
1102     {
1103       /* client has authenticated */
1104       if (!_dbus_credentials_add_credentials (auth->authorized_identity,
1105                                               auth->desired_identity))
1106         return FALSE;
1107
1108       /* also copy process ID from the socket credentials
1109        */
1110       if (!_dbus_credentials_add_credential (auth->authorized_identity,
1111                                              DBUS_CREDENTIAL_UNIX_PROCESS_ID,
1112                                              auth->credentials))
1113         return FALSE;
1114
1115       /* also copy audit data from the socket credentials
1116        */
1117       if (!_dbus_credentials_add_credential (auth->authorized_identity,
1118                                              DBUS_CREDENTIAL_ADT_AUDIT_DATA_ID,
1119                                              auth->credentials))
1120         return FALSE;
1121
1122       /* Do a first authorization of the transport, in order to REJECT
1123        * immediately connection if needed (FDO#39720), transport will
1124        * re-authorize later, but it will close the connection on fail,
1125        * we want to REJECT now if possible */
1126       if (_dbus_authorization_do_authorization (DBUS_AUTH_SERVER (auth)->authorization,
1127             auth->authorized_identity))
1128         {
1129           if (!send_ok (auth))
1130             return FALSE;
1131         }
1132       else
1133         {
1134           _dbus_verbose ("%s: desired identity does not match server identity: "
1135               "not authorized\n", DBUS_AUTH_NAME (auth));
1136           return send_rejected (auth);
1137         }
1138
1139       _dbus_verbose ("%s: authenticated and authorized client based on "
1140           "socket credentials\n", DBUS_AUTH_NAME (auth));
1141
1142       return TRUE;
1143     }
1144   else
1145     {
1146       _dbus_verbose ("%s: desired identity not found in socket credentials\n",
1147                      DBUS_AUTH_NAME (auth));
1148       return send_rejected (auth);
1149     }
1150 }
1151
1152 static void
1153 handle_server_shutdown_external_mech (DBusAuth *auth)
1154 {
1155
1156 }
1157
1158 static dbus_bool_t
1159 handle_client_initial_response_external_mech (DBusAuth         *auth,
1160                                               DBusString       *response)
1161 {
1162   /* We always append our UID as an initial response, so the server
1163    * doesn't have to send back an empty challenge to check whether we
1164    * want to specify an identity. i.e. this avoids a round trip that
1165    * the spec for the EXTERNAL mechanism otherwise requires.
1166    */
1167   DBusString plaintext;
1168
1169   if (!_dbus_string_init (&plaintext))
1170     return FALSE;
1171
1172   if (!_dbus_append_user_from_current_process (&plaintext))
1173     goto failed;
1174
1175   if (!_dbus_string_hex_encode (&plaintext, 0,
1176                                 response,
1177                                 _dbus_string_get_length (response)))
1178     goto failed;
1179
1180   _dbus_string_free (&plaintext);
1181   
1182   return TRUE;
1183
1184  failed:
1185   _dbus_string_free (&plaintext);
1186   return FALSE;  
1187 }
1188
1189 static dbus_bool_t
1190 handle_client_data_external_mech (DBusAuth         *auth,
1191                                   const DBusString *data)
1192 {
1193   
1194   return TRUE;
1195 }
1196
1197 static void
1198 handle_client_shutdown_external_mech (DBusAuth *auth)
1199 {
1200
1201 }
1202
1203 /*
1204  * ANONYMOUS mechanism
1205  */
1206
1207 static dbus_bool_t
1208 handle_server_data_anonymous_mech (DBusAuth         *auth,
1209                                    const DBusString *data)
1210 {  
1211   if (_dbus_string_get_length (data) > 0)
1212     {
1213       /* Client is allowed to send "trace" data, the only defined
1214        * meaning is that if it contains '@' it is an email address,
1215        * and otherwise it is anything else, and it's supposed to be
1216        * UTF-8
1217        */
1218       if (!_dbus_string_validate_utf8 (data, 0, _dbus_string_get_length (data)))
1219         {
1220           _dbus_verbose ("%s: Received invalid UTF-8 trace data from ANONYMOUS client\n",
1221                          DBUS_AUTH_NAME (auth));
1222           return send_rejected (auth);
1223         }
1224       
1225       _dbus_verbose ("%s: ANONYMOUS client sent trace string: '%s'\n",
1226                      DBUS_AUTH_NAME (auth),
1227                      _dbus_string_get_const_data (data));
1228     }
1229
1230   /* We want to be anonymous (clear in case some other protocol got midway through I guess) */
1231   _dbus_credentials_clear (auth->desired_identity);
1232
1233   /* Copy process ID from the socket credentials
1234    */
1235   if (!_dbus_credentials_add_credential (auth->authorized_identity,
1236                                          DBUS_CREDENTIAL_UNIX_PROCESS_ID,
1237                                          auth->credentials))
1238     return FALSE;
1239   
1240   /* Anonymous is always allowed */
1241   if (!send_ok (auth))
1242     return FALSE;
1243
1244   _dbus_verbose ("%s: authenticated client as anonymous\n",
1245                  DBUS_AUTH_NAME (auth));
1246
1247   return TRUE;
1248 }
1249
1250 static void
1251 handle_server_shutdown_anonymous_mech (DBusAuth *auth)
1252 {
1253   
1254 }
1255
1256 static dbus_bool_t
1257 handle_client_initial_response_anonymous_mech (DBusAuth         *auth,
1258                                                DBusString       *response)
1259 {
1260   /* Our initial response is a "trace" string which must be valid UTF-8
1261    * and must be an email address if it contains '@'.
1262    * We just send the dbus implementation info, like a user-agent or
1263    * something, because... why not. There's nothing guaranteed here
1264    * though, we could change it later.
1265    */
1266   DBusString plaintext;
1267
1268   if (!_dbus_string_init (&plaintext))
1269     return FALSE;
1270
1271   if (!_dbus_string_append (&plaintext,
1272                             "libdbus " DBUS_VERSION_STRING))
1273     goto failed;
1274
1275   if (!_dbus_string_hex_encode (&plaintext, 0,
1276                                 response,
1277                                 _dbus_string_get_length (response)))
1278     goto failed;
1279
1280   _dbus_string_free (&plaintext);
1281   
1282   return TRUE;
1283
1284  failed:
1285   _dbus_string_free (&plaintext);
1286   return FALSE;  
1287 }
1288
1289 static dbus_bool_t
1290 handle_client_data_anonymous_mech (DBusAuth         *auth,
1291                                   const DBusString *data)
1292 {
1293   
1294   return TRUE;
1295 }
1296
1297 static void
1298 handle_client_shutdown_anonymous_mech (DBusAuth *auth)
1299 {
1300   
1301 }
1302
1303 /* Put mechanisms here in order of preference.
1304  * Right now we have:
1305  *
1306  * - EXTERNAL checks socket credentials (or in the future, other info from the OS)
1307  * - DBUS_COOKIE_SHA1 uses a cookie in the home directory, like xauth or ICE
1308  * - ANONYMOUS checks nothing but doesn't auth the person as a user
1309  *
1310  * We might ideally add a mechanism to chain to Cyrus SASL so we can
1311  * use its mechanisms as well.
1312  * 
1313  */
1314 static const DBusAuthMechanismHandler
1315 all_mechanisms[] = {
1316   { "EXTERNAL",
1317     handle_server_data_external_mech,
1318     NULL, NULL,
1319     handle_server_shutdown_external_mech,
1320     handle_client_initial_response_external_mech,
1321     handle_client_data_external_mech,
1322     NULL, NULL,
1323     handle_client_shutdown_external_mech },
1324   { "DBUS_COOKIE_SHA1",
1325     handle_server_data_cookie_sha1_mech,
1326     NULL, NULL,
1327     handle_server_shutdown_cookie_sha1_mech,
1328     handle_client_initial_response_cookie_sha1_mech,
1329     handle_client_data_cookie_sha1_mech,
1330     NULL, NULL,
1331     handle_client_shutdown_cookie_sha1_mech },
1332   { "ANONYMOUS",
1333     handle_server_data_anonymous_mech,
1334     NULL, NULL,
1335     handle_server_shutdown_anonymous_mech,
1336     handle_client_initial_response_anonymous_mech,
1337     handle_client_data_anonymous_mech,
1338     NULL, NULL,
1339     handle_client_shutdown_anonymous_mech },  
1340   { NULL, NULL }
1341 };
1342
1343 static const DBusAuthMechanismHandler*
1344 find_mech (const DBusString  *name,
1345            char             **allowed_mechs)
1346 {
1347   int i;
1348   
1349   if (allowed_mechs != NULL &&
1350       !_dbus_string_array_contains ((const char**) allowed_mechs,
1351                                     _dbus_string_get_const_data (name)))
1352     return NULL;
1353   
1354   i = 0;
1355   while (all_mechanisms[i].mechanism != NULL)
1356     {      
1357       if (_dbus_string_equal_c_str (name,
1358                                     all_mechanisms[i].mechanism))
1359
1360         return &all_mechanisms[i];
1361       
1362       ++i;
1363     }
1364   
1365   return NULL;
1366 }
1367
1368 static dbus_bool_t
1369 send_auth (DBusAuth *auth, const DBusAuthMechanismHandler *mech)
1370 {
1371   DBusString auth_command;
1372
1373   if (!_dbus_string_init (&auth_command))
1374     return FALSE;
1375       
1376   if (!_dbus_string_append (&auth_command,
1377                             "AUTH "))
1378     {
1379       _dbus_string_free (&auth_command);
1380       return FALSE;
1381     }  
1382   
1383   if (!_dbus_string_append (&auth_command,
1384                             mech->mechanism))
1385     {
1386       _dbus_string_free (&auth_command);
1387       return FALSE;
1388     }
1389
1390   if (mech->client_initial_response_func != NULL)
1391     {
1392       if (!_dbus_string_append (&auth_command, " "))
1393         {
1394           _dbus_string_free (&auth_command);
1395           return FALSE;
1396         }
1397       
1398       if (!(* mech->client_initial_response_func) (auth, &auth_command))
1399         {
1400           _dbus_string_free (&auth_command);
1401           return FALSE;
1402         }
1403     }
1404   
1405   if (!_dbus_string_append (&auth_command,
1406                             "\r\n"))
1407     {
1408       _dbus_string_free (&auth_command);
1409       return FALSE;
1410     }
1411
1412   if (!_dbus_string_copy (&auth_command, 0,
1413                           &auth->outgoing,
1414                           _dbus_string_get_length (&auth->outgoing)))
1415     {
1416       _dbus_string_free (&auth_command);
1417       return FALSE;
1418     }
1419
1420   _dbus_string_free (&auth_command);
1421   shutdown_mech (auth);
1422   auth->mech = mech;      
1423   goto_state (auth, &client_state_waiting_for_data);
1424
1425   return TRUE;
1426 }
1427
1428 static dbus_bool_t
1429 send_data (DBusAuth *auth, DBusString *data)
1430 {
1431   int old_len;
1432
1433   if (data == NULL || _dbus_string_get_length (data) == 0)
1434     return _dbus_string_append (&auth->outgoing, "DATA\r\n");
1435   else
1436     {
1437       old_len = _dbus_string_get_length (&auth->outgoing);
1438       if (!_dbus_string_append (&auth->outgoing, "DATA "))
1439         goto out;
1440
1441       if (!_dbus_string_hex_encode (data, 0, &auth->outgoing,
1442                                     _dbus_string_get_length (&auth->outgoing)))
1443         goto out;
1444
1445       if (!_dbus_string_append (&auth->outgoing, "\r\n"))
1446         goto out;
1447
1448       return TRUE;
1449
1450     out:
1451       _dbus_string_set_length (&auth->outgoing, old_len);
1452
1453       return FALSE;
1454     }
1455 }
1456
1457 static dbus_bool_t
1458 send_rejected (DBusAuth *auth)
1459 {
1460   DBusString command;
1461   DBusAuthServer *server_auth;
1462   int i;
1463   
1464   if (!_dbus_string_init (&command))
1465     return FALSE;
1466   
1467   if (!_dbus_string_append (&command,
1468                             "REJECTED"))
1469     goto nomem;
1470
1471   i = 0;
1472   while (all_mechanisms[i].mechanism != NULL)
1473     {
1474       if (!_dbus_string_append (&command,
1475                                 " "))
1476         goto nomem;
1477
1478       if (!_dbus_string_append (&command,
1479                                 all_mechanisms[i].mechanism))
1480         goto nomem;
1481       
1482       ++i;
1483     }
1484   
1485   if (!_dbus_string_append (&command, "\r\n"))
1486     goto nomem;
1487
1488   if (!_dbus_string_copy (&command, 0, &auth->outgoing,
1489                           _dbus_string_get_length (&auth->outgoing)))
1490     goto nomem;
1491
1492   shutdown_mech (auth);
1493   
1494   _dbus_assert (DBUS_AUTH_IS_SERVER (auth));
1495   server_auth = DBUS_AUTH_SERVER (auth);
1496   server_auth->failures += 1;
1497
1498   if (server_auth->failures >= server_auth->max_failures)
1499     goto_state (auth, &common_state_need_disconnect);
1500   else
1501     goto_state (auth, &server_state_waiting_for_auth);
1502
1503   _dbus_string_free (&command);
1504   
1505   return TRUE;
1506
1507  nomem:
1508   _dbus_string_free (&command);
1509   return FALSE;
1510 }
1511
1512 static dbus_bool_t
1513 send_error (DBusAuth *auth, const char *message)
1514 {
1515   return _dbus_string_append_printf (&auth->outgoing,
1516                                      "ERROR \"%s\"\r\n", message);
1517 }
1518
1519 static dbus_bool_t
1520 send_ok (DBusAuth *auth)
1521 {
1522   int orig_len;
1523
1524   orig_len = _dbus_string_get_length (&auth->outgoing);
1525   
1526   if (_dbus_string_append (&auth->outgoing, "OK ") &&
1527       _dbus_string_copy (& DBUS_AUTH_SERVER (auth)->guid,
1528                          0,
1529                          &auth->outgoing,
1530                          _dbus_string_get_length (&auth->outgoing)) &&
1531       _dbus_string_append (&auth->outgoing, "\r\n"))
1532     {
1533       goto_state (auth, &server_state_waiting_for_begin);
1534       return TRUE;
1535     }
1536   else
1537     {
1538       _dbus_string_set_length (&auth->outgoing, orig_len);
1539       return FALSE;
1540     }
1541 }
1542
1543 static dbus_bool_t
1544 send_begin (DBusAuth         *auth)
1545 {
1546
1547   if (!_dbus_string_append (&auth->outgoing,
1548                             "BEGIN\r\n"))
1549     return FALSE;
1550
1551   goto_state (auth, &common_state_authenticated);
1552   return TRUE;
1553 }
1554
1555 static dbus_bool_t
1556 process_ok(DBusAuth *auth,
1557           const DBusString *args_from_ok) {
1558
1559   int end_of_hex;
1560   
1561   /* "args_from_ok" should be the GUID, whitespace already pulled off the front */
1562   _dbus_assert (_dbus_string_get_length (& DBUS_AUTH_CLIENT (auth)->guid_from_server) == 0);
1563
1564   /* We decode the hex string to binary, using guid_from_server as scratch... */
1565   
1566   end_of_hex = 0;
1567   if (!_dbus_string_hex_decode (args_from_ok, 0, &end_of_hex,
1568                                 & DBUS_AUTH_CLIENT (auth)->guid_from_server, 0))
1569     return FALSE;
1570
1571   /* now clear out the scratch */
1572   _dbus_string_set_length (& DBUS_AUTH_CLIENT (auth)->guid_from_server, 0);
1573   
1574   if (end_of_hex != _dbus_string_get_length (args_from_ok) ||
1575       end_of_hex == 0)
1576     {
1577       _dbus_verbose ("Bad GUID from server, parsed %d bytes and had %d bytes from server\n",
1578                      end_of_hex, _dbus_string_get_length (args_from_ok));
1579       goto_state (auth, &common_state_need_disconnect);
1580       return TRUE;
1581     }
1582
1583   if (!_dbus_string_copy (args_from_ok, 0, &DBUS_AUTH_CLIENT (auth)->guid_from_server, 0)) {
1584       _dbus_string_set_length (& DBUS_AUTH_CLIENT (auth)->guid_from_server, 0);
1585       return FALSE;
1586   }
1587
1588   _dbus_verbose ("Got GUID '%s' from the server\n",
1589                  _dbus_string_get_const_data (& DBUS_AUTH_CLIENT (auth)->guid_from_server));
1590
1591   if (auth->unix_fd_possible)
1592     return send_negotiate_unix_fd(auth);
1593
1594   _dbus_verbose("Not negotiating unix fd passing, since not possible\n");
1595   return send_begin (auth);
1596 }
1597
1598 static dbus_bool_t
1599 send_cancel (DBusAuth *auth)
1600 {
1601   if (_dbus_string_append (&auth->outgoing, "CANCEL\r\n"))
1602     {
1603       goto_state (auth, &client_state_waiting_for_reject);
1604       return TRUE;
1605     }
1606   else
1607     return FALSE;
1608 }
1609
1610 static dbus_bool_t
1611 process_data (DBusAuth             *auth,
1612               const DBusString     *args,
1613               DBusAuthDataFunction  data_func)
1614 {
1615   int end;
1616   DBusString decoded;
1617
1618   if (!_dbus_string_init (&decoded))
1619     return FALSE;
1620
1621   if (!_dbus_string_hex_decode (args, 0, &end, &decoded, 0))
1622     {
1623       _dbus_string_free (&decoded);
1624       return FALSE;
1625     }
1626
1627   if (_dbus_string_get_length (args) != end)
1628     {
1629       _dbus_string_free (&decoded);
1630       if (!send_error (auth, "Invalid hex encoding"))
1631         return FALSE;
1632
1633       return TRUE;
1634     }
1635
1636 #ifdef DBUS_ENABLE_VERBOSE_MODE
1637   if (_dbus_string_validate_ascii (&decoded, 0,
1638                                    _dbus_string_get_length (&decoded)))
1639     _dbus_verbose ("%s: data: '%s'\n",
1640                    DBUS_AUTH_NAME (auth),
1641                    _dbus_string_get_const_data (&decoded));
1642 #endif
1643       
1644   if (!(* data_func) (auth, &decoded))
1645     {
1646       _dbus_string_free (&decoded);
1647       return FALSE;
1648     }
1649
1650   _dbus_string_free (&decoded);
1651   return TRUE;
1652 }
1653
1654 static dbus_bool_t
1655 send_negotiate_unix_fd (DBusAuth *auth)
1656 {
1657   if (!_dbus_string_append (&auth->outgoing,
1658                             "NEGOTIATE_UNIX_FD\r\n"))
1659     return FALSE;
1660
1661   goto_state (auth, &client_state_waiting_for_agree_unix_fd);
1662   return TRUE;
1663 }
1664
1665 static dbus_bool_t
1666 send_agree_unix_fd (DBusAuth *auth)
1667 {
1668   _dbus_assert(auth->unix_fd_possible);
1669
1670   auth->unix_fd_negotiated = TRUE;
1671   _dbus_verbose("Agreed to UNIX FD passing\n");
1672
1673   if (!_dbus_string_append (&auth->outgoing,
1674                             "AGREE_UNIX_FD\r\n"))
1675     return FALSE;
1676
1677   goto_state (auth, &server_state_waiting_for_begin);
1678   return TRUE;
1679 }
1680
1681 static dbus_bool_t
1682 handle_auth (DBusAuth *auth, const DBusString *args)
1683 {
1684   if (_dbus_string_get_length (args) == 0)
1685     {
1686       /* No args to the auth, send mechanisms */
1687       if (!send_rejected (auth))
1688         return FALSE;
1689
1690       return TRUE;
1691     }
1692   else
1693     {
1694       int i;
1695       DBusString mech;
1696       DBusString hex_response;
1697       
1698       _dbus_string_find_blank (args, 0, &i);
1699
1700       if (!_dbus_string_init (&mech))
1701         return FALSE;
1702
1703       if (!_dbus_string_init (&hex_response))
1704         {
1705           _dbus_string_free (&mech);
1706           return FALSE;
1707         }
1708       
1709       if (!_dbus_string_copy_len (args, 0, i, &mech, 0))
1710         goto failed;
1711
1712       _dbus_string_skip_blank (args, i, &i);
1713       if (!_dbus_string_copy (args, i, &hex_response, 0))
1714         goto failed;
1715      
1716       auth->mech = find_mech (&mech, auth->allowed_mechs);
1717       if (auth->mech != NULL)
1718         {
1719           _dbus_verbose ("%s: Trying mechanism %s\n",
1720                          DBUS_AUTH_NAME (auth),
1721                          auth->mech->mechanism);
1722           
1723           if (!process_data (auth, &hex_response,
1724                              auth->mech->server_data_func))
1725             goto failed;
1726         }
1727       else
1728         {
1729           /* Unsupported mechanism */
1730           _dbus_verbose ("%s: Unsupported mechanism %s\n",
1731                          DBUS_AUTH_NAME (auth),
1732                          _dbus_string_get_const_data (&mech));
1733           
1734           if (!send_rejected (auth))
1735             goto failed;
1736         }
1737
1738       _dbus_string_free (&mech);      
1739       _dbus_string_free (&hex_response);
1740
1741       return TRUE;
1742       
1743     failed:
1744       auth->mech = NULL;
1745       _dbus_string_free (&mech);
1746       _dbus_string_free (&hex_response);
1747       return FALSE;
1748     }
1749 }
1750
1751 static dbus_bool_t
1752 handle_server_state_waiting_for_auth  (DBusAuth         *auth,
1753                                        DBusAuthCommand   command,
1754                                        const DBusString *args)
1755 {
1756   switch (command)
1757     {
1758     case DBUS_AUTH_COMMAND_AUTH:
1759       return handle_auth (auth, args);
1760
1761     case DBUS_AUTH_COMMAND_CANCEL:
1762     case DBUS_AUTH_COMMAND_DATA:
1763       return send_error (auth, "Not currently in an auth conversation");
1764
1765     case DBUS_AUTH_COMMAND_BEGIN:
1766       goto_state (auth, &common_state_need_disconnect);
1767       return TRUE;
1768
1769     case DBUS_AUTH_COMMAND_ERROR:
1770       return send_rejected (auth);
1771
1772     case DBUS_AUTH_COMMAND_NEGOTIATE_UNIX_FD:
1773       return send_error (auth, "Need to authenticate first");
1774
1775     case DBUS_AUTH_COMMAND_REJECTED:
1776     case DBUS_AUTH_COMMAND_OK:
1777     case DBUS_AUTH_COMMAND_UNKNOWN:
1778     case DBUS_AUTH_COMMAND_AGREE_UNIX_FD:
1779     default:
1780       return send_error (auth, "Unknown command");
1781     }
1782 }
1783
1784 static dbus_bool_t
1785 handle_server_state_waiting_for_data  (DBusAuth         *auth,
1786                                        DBusAuthCommand   command,
1787                                        const DBusString *args)
1788 {
1789   switch (command)
1790     {
1791     case DBUS_AUTH_COMMAND_AUTH:
1792       return send_error (auth, "Sent AUTH while another AUTH in progress");
1793
1794     case DBUS_AUTH_COMMAND_CANCEL:
1795     case DBUS_AUTH_COMMAND_ERROR:
1796       return send_rejected (auth);
1797
1798     case DBUS_AUTH_COMMAND_DATA:
1799       return process_data (auth, args, auth->mech->server_data_func);
1800
1801     case DBUS_AUTH_COMMAND_BEGIN:
1802       goto_state (auth, &common_state_need_disconnect);
1803       return TRUE;
1804
1805     case DBUS_AUTH_COMMAND_NEGOTIATE_UNIX_FD:
1806       return send_error (auth, "Need to authenticate first");
1807
1808     case DBUS_AUTH_COMMAND_REJECTED:
1809     case DBUS_AUTH_COMMAND_OK:
1810     case DBUS_AUTH_COMMAND_UNKNOWN:
1811     case DBUS_AUTH_COMMAND_AGREE_UNIX_FD:
1812     default:
1813       return send_error (auth, "Unknown command");
1814     }
1815 }
1816
1817 static dbus_bool_t
1818 handle_server_state_waiting_for_begin (DBusAuth         *auth,
1819                                        DBusAuthCommand   command,
1820                                        const DBusString *args)
1821 {
1822   switch (command)
1823     {
1824     case DBUS_AUTH_COMMAND_AUTH:
1825       return send_error (auth, "Sent AUTH while expecting BEGIN");
1826
1827     case DBUS_AUTH_COMMAND_DATA:
1828       return send_error (auth, "Sent DATA while expecting BEGIN");
1829
1830     case DBUS_AUTH_COMMAND_BEGIN:
1831       goto_state (auth, &common_state_authenticated);
1832       return TRUE;
1833
1834     case DBUS_AUTH_COMMAND_NEGOTIATE_UNIX_FD:
1835       if (auth->unix_fd_possible)
1836         return send_agree_unix_fd(auth);
1837       else
1838         return send_error(auth, "Unix FD passing not supported, not authenticated or otherwise not possible");
1839
1840     case DBUS_AUTH_COMMAND_REJECTED:
1841     case DBUS_AUTH_COMMAND_OK:
1842     case DBUS_AUTH_COMMAND_UNKNOWN:
1843     case DBUS_AUTH_COMMAND_AGREE_UNIX_FD:
1844     default:
1845       return send_error (auth, "Unknown command");
1846
1847     case DBUS_AUTH_COMMAND_CANCEL:
1848     case DBUS_AUTH_COMMAND_ERROR:
1849       return send_rejected (auth);
1850     }
1851 }
1852
1853 /* return FALSE if no memory, TRUE if all OK */
1854 static dbus_bool_t
1855 get_word (const DBusString *str,
1856           int              *start,
1857           DBusString       *word)
1858 {
1859   int i;
1860
1861   _dbus_string_skip_blank (str, *start, start);
1862   _dbus_string_find_blank (str, *start, &i);
1863   
1864   if (i > *start)
1865     {
1866       if (!_dbus_string_copy_len (str, *start, i - *start, word, 0))
1867         return FALSE;
1868       
1869       *start = i;
1870     }
1871
1872   return TRUE;
1873 }
1874
1875 static dbus_bool_t
1876 record_mechanisms (DBusAuth         *auth,
1877                    const DBusString *args)
1878 {
1879   int next;
1880   int len;
1881
1882   if (auth->already_got_mechanisms)
1883     return TRUE;
1884   
1885   len = _dbus_string_get_length (args);
1886   
1887   next = 0;
1888   while (next < len)
1889     {
1890       DBusString m;
1891       const DBusAuthMechanismHandler *mech;
1892       
1893       if (!_dbus_string_init (&m))
1894         goto nomem;
1895       
1896       if (!get_word (args, &next, &m))
1897         {
1898           _dbus_string_free (&m);
1899           goto nomem;
1900         }
1901
1902       mech = find_mech (&m, auth->allowed_mechs);
1903
1904       if (mech != NULL)
1905         {
1906           /* FIXME right now we try mechanisms in the order
1907            * the server lists them; should we do them in
1908            * some more deterministic order?
1909            *
1910            * Probably in all_mechanisms order, our order of
1911            * preference. Of course when the server is us,
1912            * it lists things in that order anyhow.
1913            */
1914
1915           if (mech != &all_mechanisms[0])
1916             {
1917               _dbus_verbose ("%s: Adding mechanism %s to list we will try\n",
1918                              DBUS_AUTH_NAME (auth), mech->mechanism);
1919           
1920               if (!_dbus_list_append (& DBUS_AUTH_CLIENT (auth)->mechs_to_try,
1921                                       (void*) mech))
1922                 {
1923                   _dbus_string_free (&m);
1924                   goto nomem;
1925                 }
1926             }
1927           else
1928             {
1929               _dbus_verbose ("%s: Already tried mechanism %s; not adding to list we will try\n",
1930                              DBUS_AUTH_NAME (auth), mech->mechanism);
1931             }
1932         }
1933       else
1934         {
1935           _dbus_verbose ("%s: Server offered mechanism \"%s\" that we don't know how to use\n",
1936                          DBUS_AUTH_NAME (auth),
1937                          _dbus_string_get_const_data (&m));
1938         }
1939
1940       _dbus_string_free (&m);
1941     }
1942   
1943   auth->already_got_mechanisms = TRUE;
1944   
1945   return TRUE;
1946
1947  nomem:
1948   _dbus_list_clear (& DBUS_AUTH_CLIENT (auth)->mechs_to_try);
1949   
1950   return FALSE;
1951 }
1952
1953 static dbus_bool_t
1954 process_rejected (DBusAuth *auth, const DBusString *args)
1955 {
1956   const DBusAuthMechanismHandler *mech;
1957   DBusAuthClient *client;
1958
1959   client = DBUS_AUTH_CLIENT (auth);
1960
1961   if (!auth->already_got_mechanisms)
1962     {
1963       if (!record_mechanisms (auth, args))
1964         return FALSE;
1965     }
1966   
1967   if (DBUS_AUTH_CLIENT (auth)->mechs_to_try != NULL)
1968     {
1969       mech = client->mechs_to_try->data;
1970
1971       if (!send_auth (auth, mech))
1972         return FALSE;
1973
1974       _dbus_list_pop_first (&client->mechs_to_try);
1975
1976       _dbus_verbose ("%s: Trying mechanism %s\n",
1977                      DBUS_AUTH_NAME (auth),
1978                      mech->mechanism);
1979     }
1980   else
1981     {
1982       /* Give up */
1983       _dbus_verbose ("%s: Disconnecting because we are out of mechanisms to try using\n",
1984                      DBUS_AUTH_NAME (auth));
1985       goto_state (auth, &common_state_need_disconnect);
1986     }
1987   
1988   return TRUE;
1989 }
1990
1991
1992 static dbus_bool_t
1993 handle_client_state_waiting_for_data (DBusAuth         *auth,
1994                                       DBusAuthCommand   command,
1995                                       const DBusString *args)
1996 {
1997   _dbus_assert (auth->mech != NULL);
1998  
1999   switch (command)
2000     {
2001     case DBUS_AUTH_COMMAND_DATA:
2002       return process_data (auth, args, auth->mech->client_data_func);
2003
2004     case DBUS_AUTH_COMMAND_REJECTED:
2005       return process_rejected (auth, args);
2006
2007     case DBUS_AUTH_COMMAND_OK:
2008       return process_ok(auth, args);
2009
2010     case DBUS_AUTH_COMMAND_ERROR:
2011       return send_cancel (auth);
2012
2013     case DBUS_AUTH_COMMAND_AUTH:
2014     case DBUS_AUTH_COMMAND_CANCEL:
2015     case DBUS_AUTH_COMMAND_BEGIN:
2016     case DBUS_AUTH_COMMAND_UNKNOWN:
2017     case DBUS_AUTH_COMMAND_NEGOTIATE_UNIX_FD:
2018     case DBUS_AUTH_COMMAND_AGREE_UNIX_FD:
2019     default:
2020       return send_error (auth, "Unknown command");
2021     }
2022 }
2023
2024 static dbus_bool_t
2025 handle_client_state_waiting_for_ok (DBusAuth         *auth,
2026                                     DBusAuthCommand   command,
2027                                     const DBusString *args)
2028 {
2029   switch (command)
2030     {
2031     case DBUS_AUTH_COMMAND_REJECTED:
2032       return process_rejected (auth, args);
2033
2034     case DBUS_AUTH_COMMAND_OK:
2035       return process_ok(auth, args);
2036
2037     case DBUS_AUTH_COMMAND_DATA:
2038     case DBUS_AUTH_COMMAND_ERROR:
2039       return send_cancel (auth);
2040
2041     case DBUS_AUTH_COMMAND_AUTH:
2042     case DBUS_AUTH_COMMAND_CANCEL:
2043     case DBUS_AUTH_COMMAND_BEGIN:
2044     case DBUS_AUTH_COMMAND_UNKNOWN:
2045     case DBUS_AUTH_COMMAND_NEGOTIATE_UNIX_FD:
2046     case DBUS_AUTH_COMMAND_AGREE_UNIX_FD:
2047     default:
2048       return send_error (auth, "Unknown command");
2049     }
2050 }
2051
2052 static dbus_bool_t
2053 handle_client_state_waiting_for_reject (DBusAuth         *auth,
2054                                         DBusAuthCommand   command,
2055                                         const DBusString *args)
2056 {
2057   switch (command)
2058     {
2059     case DBUS_AUTH_COMMAND_REJECTED:
2060       return process_rejected (auth, args);
2061       
2062     case DBUS_AUTH_COMMAND_AUTH:
2063     case DBUS_AUTH_COMMAND_CANCEL:
2064     case DBUS_AUTH_COMMAND_DATA:
2065     case DBUS_AUTH_COMMAND_BEGIN:
2066     case DBUS_AUTH_COMMAND_OK:
2067     case DBUS_AUTH_COMMAND_ERROR:
2068     case DBUS_AUTH_COMMAND_UNKNOWN:
2069     case DBUS_AUTH_COMMAND_NEGOTIATE_UNIX_FD:
2070     case DBUS_AUTH_COMMAND_AGREE_UNIX_FD:
2071     default:
2072       goto_state (auth, &common_state_need_disconnect);
2073       return TRUE;
2074     }
2075 }
2076
2077 static dbus_bool_t
2078 handle_client_state_waiting_for_agree_unix_fd(DBusAuth         *auth,
2079                                               DBusAuthCommand   command,
2080                                               const DBusString *args)
2081 {
2082   switch (command)
2083     {
2084     case DBUS_AUTH_COMMAND_AGREE_UNIX_FD:
2085       _dbus_assert(auth->unix_fd_possible);
2086       auth->unix_fd_negotiated = TRUE;
2087       _dbus_verbose("Successfully negotiated UNIX FD passing\n");
2088       return send_begin (auth);
2089
2090     case DBUS_AUTH_COMMAND_ERROR:
2091       _dbus_assert(auth->unix_fd_possible);
2092       auth->unix_fd_negotiated = FALSE;
2093       _dbus_verbose("Failed to negotiate UNIX FD passing\n");
2094       return send_begin (auth);
2095
2096     case DBUS_AUTH_COMMAND_OK:
2097     case DBUS_AUTH_COMMAND_DATA:
2098     case DBUS_AUTH_COMMAND_REJECTED:
2099     case DBUS_AUTH_COMMAND_AUTH:
2100     case DBUS_AUTH_COMMAND_CANCEL:
2101     case DBUS_AUTH_COMMAND_BEGIN:
2102     case DBUS_AUTH_COMMAND_UNKNOWN:
2103     case DBUS_AUTH_COMMAND_NEGOTIATE_UNIX_FD:
2104     default:
2105       return send_error (auth, "Unknown command");
2106     }
2107 }
2108
2109 /**
2110  * Mapping from command name to enum
2111  */
2112 typedef struct {
2113   const char *name;        /**< Name of the command */
2114   DBusAuthCommand command; /**< Corresponding enum */
2115 } DBusAuthCommandName;
2116
2117 static const DBusAuthCommandName auth_command_names[] = {
2118   { "AUTH",              DBUS_AUTH_COMMAND_AUTH },
2119   { "CANCEL",            DBUS_AUTH_COMMAND_CANCEL },
2120   { "DATA",              DBUS_AUTH_COMMAND_DATA },
2121   { "BEGIN",             DBUS_AUTH_COMMAND_BEGIN },
2122   { "REJECTED",          DBUS_AUTH_COMMAND_REJECTED },
2123   { "OK",                DBUS_AUTH_COMMAND_OK },
2124   { "ERROR",             DBUS_AUTH_COMMAND_ERROR },
2125   { "NEGOTIATE_UNIX_FD", DBUS_AUTH_COMMAND_NEGOTIATE_UNIX_FD },
2126   { "AGREE_UNIX_FD",     DBUS_AUTH_COMMAND_AGREE_UNIX_FD }
2127 };
2128
2129 static DBusAuthCommand
2130 lookup_command_from_name (DBusString *command)
2131 {
2132   int i;
2133
2134   for (i = 0; i < _DBUS_N_ELEMENTS (auth_command_names); i++)
2135     {
2136       if (_dbus_string_equal_c_str (command,
2137                                     auth_command_names[i].name))
2138         return auth_command_names[i].command;
2139     }
2140
2141   return DBUS_AUTH_COMMAND_UNKNOWN;
2142 }
2143
2144 static void
2145 goto_state (DBusAuth *auth,
2146             const DBusAuthStateData *state)
2147 {
2148   _dbus_verbose ("%s: going from state %s to state %s\n",
2149                  DBUS_AUTH_NAME (auth),
2150                  auth->state->name,
2151                  state->name);
2152
2153   auth->state = state;
2154 }
2155
2156 /* returns whether to call it again right away */
2157 static dbus_bool_t
2158 process_command (DBusAuth *auth)
2159 {
2160   DBusAuthCommand command;
2161   DBusString line;
2162   DBusString args;
2163   int eol;
2164   int i, j;
2165   dbus_bool_t retval;
2166
2167   /* _dbus_verbose ("%s:   trying process_command()\n"); */
2168   
2169   retval = FALSE;
2170   
2171   eol = 0;
2172   if (!_dbus_string_find (&auth->incoming, 0, "\r\n", &eol))
2173     return FALSE;
2174   
2175   if (!_dbus_string_init (&line))
2176     {
2177       auth->needed_memory = TRUE;
2178       return FALSE;
2179     }
2180
2181   if (!_dbus_string_init (&args))
2182     {
2183       _dbus_string_free (&line);
2184       auth->needed_memory = TRUE;
2185       return FALSE;
2186     }
2187   
2188   if (!_dbus_string_copy_len (&auth->incoming, 0, eol, &line, 0))
2189     goto out;
2190
2191   if (!_dbus_string_validate_ascii (&line, 0,
2192                                     _dbus_string_get_length (&line)))
2193     {
2194       _dbus_verbose ("%s: Command contained non-ASCII chars or embedded nul\n",
2195                      DBUS_AUTH_NAME (auth));
2196       if (!send_error (auth, "Command contained non-ASCII"))
2197         goto out;
2198       else
2199         goto next_command;
2200     }
2201   
2202   _dbus_verbose ("%s: got command \"%s\"\n",
2203                  DBUS_AUTH_NAME (auth),
2204                  _dbus_string_get_const_data (&line));
2205   
2206   _dbus_string_find_blank (&line, 0, &i);
2207   _dbus_string_skip_blank (&line, i, &j);
2208
2209   if (j > i)
2210     _dbus_string_delete (&line, i, j - i);
2211   
2212   if (!_dbus_string_move (&line, i, &args, 0))
2213     goto out;
2214
2215   /* FIXME 1.0 we should probably validate that only the allowed
2216    * chars are in the command name
2217    */
2218   
2219   command = lookup_command_from_name (&line);
2220   if (!(* auth->state->handler) (auth, command, &args))
2221     goto out;
2222
2223  next_command:
2224   
2225   /* We've succeeded in processing the whole command so drop it out
2226    * of the incoming buffer and return TRUE to try another command.
2227    */
2228
2229   _dbus_string_delete (&auth->incoming, 0, eol);
2230   
2231   /* kill the \r\n */
2232   _dbus_string_delete (&auth->incoming, 0, 2);
2233
2234   retval = TRUE;
2235   
2236  out:
2237   _dbus_string_free (&args);
2238   _dbus_string_free (&line);
2239
2240   if (!retval)
2241     auth->needed_memory = TRUE;
2242   else
2243     auth->needed_memory = FALSE;
2244   
2245   return retval;
2246 }
2247
2248
2249 /** @} */
2250
2251 /**
2252  * @addtogroup DBusAuth
2253  * @{
2254  */
2255
2256 /**
2257  * Creates a new auth conversation object for the server side.
2258  * See http://dbus.freedesktop.org/doc/dbus-specification.html#auth-protocol
2259  * for full details on what this object does.
2260  *
2261  * @returns the new object or #NULL if no memory
2262  */
2263 DBusAuth*
2264 _dbus_auth_server_new (const DBusString *guid,
2265     DBusAuthorization *authorization)
2266 {
2267   DBusAuth *auth;
2268   DBusAuthServer *server_auth;
2269   DBusString guid_copy;
2270
2271   if (!_dbus_string_init (&guid_copy))
2272     return NULL;
2273
2274   if (!_dbus_string_copy (guid, 0, &guid_copy, 0))
2275     {
2276       _dbus_string_free (&guid_copy);
2277       return NULL;
2278     }
2279
2280   auth = _dbus_auth_new (sizeof (DBusAuthServer));
2281   if (auth == NULL)
2282     {
2283       _dbus_string_free (&guid_copy);
2284       return NULL;
2285     }
2286   
2287   auth->side = auth_side_server;
2288   auth->state = &server_state_waiting_for_auth;
2289
2290   server_auth = DBUS_AUTH_SERVER (auth);
2291
2292   server_auth->guid = guid_copy;
2293   server_auth->authorization = _dbus_authorization_ref (authorization);
2294
2295   /* perhaps this should be per-mechanism with a lower
2296    * max
2297    */
2298   server_auth->failures = 0;
2299   server_auth->max_failures = 6;
2300   
2301   return auth;
2302 }
2303
2304 /**
2305  * Creates a new auth conversation object for the client side.
2306  * See http://dbus.freedesktop.org/doc/dbus-specification.html#auth-protocol
2307  * for full details on what this object does.
2308  *
2309  * @returns the new object or #NULL if no memory
2310  */
2311 DBusAuth*
2312 _dbus_auth_client_new (void)
2313 {
2314   DBusAuth *auth;
2315   DBusString guid_str;
2316
2317   if (!_dbus_string_init (&guid_str))
2318     return NULL;
2319
2320   auth = _dbus_auth_new (sizeof (DBusAuthClient));
2321   if (auth == NULL)
2322     {
2323       _dbus_string_free (&guid_str);
2324       return NULL;
2325     }
2326
2327   DBUS_AUTH_CLIENT (auth)->guid_from_server = guid_str;
2328
2329   auth->side = auth_side_client;
2330   auth->state = &client_state_need_send_auth;
2331
2332   /* Start the auth conversation by sending AUTH for our default
2333    * mechanism */
2334   if (!send_auth (auth, &all_mechanisms[0]))
2335     {
2336       _dbus_auth_unref (auth);
2337       return NULL;
2338     }
2339   
2340   return auth;
2341 }
2342
2343 /**
2344  * Increments the refcount of an auth object.
2345  *
2346  * @param auth the auth conversation
2347  * @returns the auth conversation
2348  */
2349 DBusAuth *
2350 _dbus_auth_ref (DBusAuth *auth)
2351 {
2352   _dbus_assert (auth != NULL);
2353   
2354   auth->refcount += 1;
2355   
2356   return auth;
2357 }
2358
2359 /**
2360  * Decrements the refcount of an auth object.
2361  *
2362  * @param auth the auth conversation
2363  */
2364 void
2365 _dbus_auth_unref (DBusAuth *auth)
2366 {
2367   _dbus_assert (auth != NULL);
2368   _dbus_assert (auth->refcount > 0);
2369
2370   auth->refcount -= 1;
2371   if (auth->refcount == 0)
2372     {
2373       shutdown_mech (auth);
2374
2375       if (DBUS_AUTH_IS_CLIENT (auth))
2376         {
2377           _dbus_string_free (& DBUS_AUTH_CLIENT (auth)->guid_from_server);
2378           _dbus_list_clear (& DBUS_AUTH_CLIENT (auth)->mechs_to_try);
2379         }
2380       else
2381         {
2382           _dbus_assert (DBUS_AUTH_IS_SERVER (auth));
2383
2384           _dbus_string_free (& DBUS_AUTH_SERVER (auth)->guid);
2385           _dbus_authorization_unref (DBUS_AUTH_SERVER (auth)->authorization);
2386         }
2387
2388       if (auth->keyring)
2389         _dbus_keyring_unref (auth->keyring);
2390
2391       _dbus_string_free (&auth->context);
2392       _dbus_string_free (&auth->challenge);
2393       _dbus_string_free (&auth->identity);
2394       _dbus_string_free (&auth->incoming);
2395       _dbus_string_free (&auth->outgoing);
2396
2397       dbus_free_string_array (auth->allowed_mechs);
2398
2399       _dbus_credentials_unref (auth->credentials);
2400       _dbus_credentials_unref (auth->authorized_identity);
2401       _dbus_credentials_unref (auth->desired_identity);
2402       
2403       dbus_free (auth);
2404     }
2405 }
2406
2407 /**
2408  * Sets an array of authentication mechanism names
2409  * that we are willing to use.
2410  *
2411  * @param auth the auth conversation
2412  * @param mechanisms #NULL-terminated array of mechanism names
2413  * @returns #FALSE if no memory
2414  */
2415 dbus_bool_t
2416 _dbus_auth_set_mechanisms (DBusAuth    *auth,
2417                            const char **mechanisms)
2418 {
2419   char **copy;
2420
2421   if (mechanisms != NULL)
2422     {
2423       copy = _dbus_dup_string_array (mechanisms);
2424       if (copy == NULL)
2425         return FALSE;
2426     }
2427   else
2428     copy = NULL;
2429   
2430   dbus_free_string_array (auth->allowed_mechs);
2431
2432   auth->allowed_mechs = copy;
2433
2434   return TRUE;
2435 }
2436
2437 /**
2438  * @param auth the auth conversation object
2439  * @returns #TRUE if we're in a final state
2440  */
2441 #define DBUS_AUTH_IN_END_STATE(auth) ((auth)->state->handler == NULL)
2442
2443 /**
2444  * Analyzes buffered input and moves the auth conversation forward,
2445  * returning the new state of the auth conversation.
2446  *
2447  * @param auth the auth conversation
2448  * @returns the new state
2449  */
2450 DBusAuthState
2451 _dbus_auth_do_work (DBusAuth *auth)
2452 {
2453   auth->needed_memory = FALSE;
2454
2455   /* Max amount we'll buffer up before deciding someone's on crack */
2456 #define MAX_BUFFER (16 * _DBUS_ONE_KILOBYTE)
2457
2458   do
2459     {
2460       if (DBUS_AUTH_IN_END_STATE (auth))
2461         break;
2462       
2463       if (_dbus_string_get_length (&auth->incoming) > MAX_BUFFER ||
2464           _dbus_string_get_length (&auth->outgoing) > MAX_BUFFER)
2465         {
2466           goto_state (auth, &common_state_need_disconnect);
2467           _dbus_verbose ("%s: Disconnecting due to excessive data buffered in auth phase\n",
2468                          DBUS_AUTH_NAME (auth));
2469           break;
2470         }
2471     }
2472   while (process_command (auth));
2473
2474   if (auth->needed_memory)
2475     return DBUS_AUTH_STATE_WAITING_FOR_MEMORY;
2476   else if (_dbus_string_get_length (&auth->outgoing) > 0)
2477     return DBUS_AUTH_STATE_HAVE_BYTES_TO_SEND;
2478   else if (auth->state == &common_state_need_disconnect)
2479     return DBUS_AUTH_STATE_NEED_DISCONNECT;
2480   else if (auth->state == &common_state_authenticated)
2481     return DBUS_AUTH_STATE_AUTHENTICATED;
2482   else return DBUS_AUTH_STATE_WAITING_FOR_INPUT;
2483 }
2484
2485 /**
2486  * Gets bytes that need to be sent to the peer we're conversing with.
2487  * After writing some bytes, _dbus_auth_bytes_sent() must be called
2488  * to notify the auth object that they were written.
2489  *
2490  * @param auth the auth conversation
2491  * @param str return location for a ref to the buffer to send
2492  * @returns #FALSE if nothing to send
2493  */
2494 dbus_bool_t
2495 _dbus_auth_get_bytes_to_send (DBusAuth          *auth,
2496                               const DBusString **str)
2497 {
2498   _dbus_assert (auth != NULL);
2499   _dbus_assert (str != NULL);
2500
2501   *str = NULL;
2502   
2503   if (_dbus_string_get_length (&auth->outgoing) == 0)
2504     return FALSE;
2505
2506   *str = &auth->outgoing;
2507
2508   return TRUE;
2509 }
2510
2511 /**
2512  * Notifies the auth conversation object that
2513  * the given number of bytes of the outgoing buffer
2514  * have been written out.
2515  *
2516  * @param auth the auth conversation
2517  * @param bytes_sent number of bytes written out
2518  */
2519 void
2520 _dbus_auth_bytes_sent (DBusAuth *auth,
2521                        int       bytes_sent)
2522 {
2523   _dbus_verbose ("%s: Sent %d bytes of: %s\n",
2524                  DBUS_AUTH_NAME (auth),
2525                  bytes_sent,
2526                  _dbus_string_get_const_data (&auth->outgoing));
2527   
2528   _dbus_string_delete (&auth->outgoing,
2529                        0, bytes_sent);
2530 }
2531
2532 /**
2533  * Get a buffer to be used for reading bytes from the peer we're conversing
2534  * with. Bytes should be appended to this buffer.
2535  *
2536  * @param auth the auth conversation
2537  * @param buffer return location for buffer to append bytes to
2538  */
2539 void
2540 _dbus_auth_get_buffer (DBusAuth     *auth,
2541                        DBusString **buffer)
2542 {
2543   _dbus_assert (auth != NULL);
2544   _dbus_assert (!auth->buffer_outstanding);
2545   
2546   *buffer = &auth->incoming;
2547
2548   auth->buffer_outstanding = TRUE;
2549 }
2550
2551 /**
2552  * Returns a buffer with new data read into it.
2553  *
2554  * @param auth the auth conversation
2555  * @param buffer the buffer being returned
2556  * @param bytes_read number of new bytes added
2557  */
2558 void
2559 _dbus_auth_return_buffer (DBusAuth               *auth,
2560                           DBusString             *buffer,
2561                           int                     bytes_read)
2562 {
2563   _dbus_assert (buffer == &auth->incoming);
2564   _dbus_assert (auth->buffer_outstanding);
2565
2566   auth->buffer_outstanding = FALSE;
2567 }
2568
2569 /**
2570  * Returns leftover bytes that were not used as part of the auth
2571  * conversation.  These bytes will be part of the message stream
2572  * instead. This function may not be called until authentication has
2573  * succeeded.
2574  *
2575  * @param auth the auth conversation
2576  * @param str return location for pointer to string of unused bytes
2577  */
2578 void
2579 _dbus_auth_get_unused_bytes (DBusAuth           *auth,
2580                              const DBusString **str)
2581 {
2582   if (!DBUS_AUTH_IN_END_STATE (auth))
2583     return;
2584
2585   *str = &auth->incoming;
2586 }
2587
2588
2589 /**
2590  * Gets rid of unused bytes returned by _dbus_auth_get_unused_bytes()
2591  * after we've gotten them and successfully moved them elsewhere.
2592  *
2593  * @param auth the auth conversation
2594  */
2595 void
2596 _dbus_auth_delete_unused_bytes (DBusAuth *auth)
2597 {
2598   if (!DBUS_AUTH_IN_END_STATE (auth))
2599     return;
2600
2601   _dbus_string_set_length (&auth->incoming, 0);
2602 }
2603
2604 /**
2605  * Called post-authentication, indicates whether we need to encode
2606  * the message stream with _dbus_auth_encode_data() prior to
2607  * sending it to the peer.
2608  *
2609  * @param auth the auth conversation
2610  * @returns #TRUE if we need to encode the stream
2611  */
2612 dbus_bool_t
2613 _dbus_auth_needs_encoding (DBusAuth *auth)
2614 {
2615   if (auth->state != &common_state_authenticated)
2616     return FALSE;
2617   
2618   if (auth->mech != NULL)
2619     {
2620       if (DBUS_AUTH_IS_CLIENT (auth))
2621         return auth->mech->client_encode_func != NULL;
2622       else
2623         return auth->mech->server_encode_func != NULL;
2624     }
2625   else
2626     return FALSE;
2627 }
2628
2629 /**
2630  * Called post-authentication, encodes a block of bytes for sending to
2631  * the peer. If no encoding was negotiated, just copies the bytes
2632  * (you can avoid this by checking _dbus_auth_needs_encoding()).
2633  *
2634  * @param auth the auth conversation
2635  * @param plaintext the plain text data
2636  * @param encoded initialized string to where encoded data is appended
2637  * @returns #TRUE if we had enough memory and successfully encoded
2638  */
2639 dbus_bool_t
2640 _dbus_auth_encode_data (DBusAuth         *auth,
2641                         const DBusString *plaintext,
2642                         DBusString       *encoded)
2643 {
2644   _dbus_assert (plaintext != encoded);
2645   
2646   if (auth->state != &common_state_authenticated)
2647     return FALSE;
2648   
2649   if (_dbus_auth_needs_encoding (auth))
2650     {
2651       if (DBUS_AUTH_IS_CLIENT (auth))
2652         return (* auth->mech->client_encode_func) (auth, plaintext, encoded);
2653       else
2654         return (* auth->mech->server_encode_func) (auth, plaintext, encoded);
2655     }
2656   else
2657     {
2658       return _dbus_string_copy (plaintext, 0, encoded,
2659                                 _dbus_string_get_length (encoded));
2660     }
2661 }
2662
2663 /**
2664  * Called post-authentication, indicates whether we need to decode
2665  * the message stream with _dbus_auth_decode_data() after
2666  * receiving it from the peer.
2667  *
2668  * @param auth the auth conversation
2669  * @returns #TRUE if we need to encode the stream
2670  */
2671 dbus_bool_t
2672 _dbus_auth_needs_decoding (DBusAuth *auth)
2673 {
2674   if (auth->state != &common_state_authenticated)
2675     return FALSE;
2676     
2677   if (auth->mech != NULL)
2678     {
2679       if (DBUS_AUTH_IS_CLIENT (auth))
2680         return auth->mech->client_decode_func != NULL;
2681       else
2682         return auth->mech->server_decode_func != NULL;
2683     }
2684   else
2685     return FALSE;
2686 }
2687
2688
2689 /**
2690  * Called post-authentication, decodes a block of bytes received from
2691  * the peer. If no encoding was negotiated, just copies the bytes (you
2692  * can avoid this by checking _dbus_auth_needs_decoding()).
2693  *
2694  * @todo 1.0? We need to be able to distinguish "out of memory" error
2695  * from "the data is hosed" error.
2696  *
2697  * @param auth the auth conversation
2698  * @param encoded the encoded data
2699  * @param plaintext initialized string where decoded data is appended
2700  * @returns #TRUE if we had enough memory and successfully decoded
2701  */
2702 dbus_bool_t
2703 _dbus_auth_decode_data (DBusAuth         *auth,
2704                         const DBusString *encoded,
2705                         DBusString       *plaintext)
2706 {
2707   _dbus_assert (plaintext != encoded);
2708   
2709   if (auth->state != &common_state_authenticated)
2710     return FALSE;
2711   
2712   if (_dbus_auth_needs_decoding (auth))
2713     {
2714       if (DBUS_AUTH_IS_CLIENT (auth))
2715         return (* auth->mech->client_decode_func) (auth, encoded, plaintext);
2716       else
2717         return (* auth->mech->server_decode_func) (auth, encoded, plaintext);
2718     }
2719   else
2720     {
2721       return _dbus_string_copy (encoded, 0, plaintext,
2722                                 _dbus_string_get_length (plaintext));
2723     }
2724 }
2725
2726 /**
2727  * Sets credentials received via reliable means from the operating
2728  * system.
2729  *
2730  * @param auth the auth conversation
2731  * @param credentials the credentials received
2732  * @returns #FALSE on OOM
2733  */
2734 dbus_bool_t
2735 _dbus_auth_set_credentials (DBusAuth               *auth,
2736                             DBusCredentials        *credentials)
2737 {
2738   _dbus_credentials_clear (auth->credentials);
2739   return _dbus_credentials_add_credentials (auth->credentials,
2740                                             credentials);
2741 }
2742
2743 /**
2744  * Gets the identity we authorized the client as.  Apps may have
2745  * different policies as to what identities they allow.
2746  *
2747  * Returned credentials are not a copy and should not be modified
2748  *
2749  * @param auth the auth conversation
2750  * @returns the credentials we've authorized BY REFERENCE do not modify
2751  */
2752 DBusCredentials*
2753 _dbus_auth_get_identity (DBusAuth               *auth)
2754 {
2755   if (auth->state == &common_state_authenticated)
2756     {
2757       return auth->authorized_identity;
2758     }
2759   else
2760     {
2761       /* FIXME instead of this, keep an empty credential around that
2762        * doesn't require allocation or something
2763        */
2764       /* return empty credentials */
2765       _dbus_assert (_dbus_credentials_are_empty (auth->authorized_identity));
2766       return auth->authorized_identity;
2767     }
2768 }
2769
2770 /**
2771  * Gets the GUID from the server if we've authenticated; gets
2772  * #NULL otherwise.
2773  * @param auth the auth object
2774  * @returns the GUID in ASCII hex format
2775  */
2776 const char*
2777 _dbus_auth_get_guid_from_server (DBusAuth *auth)
2778 {
2779   _dbus_assert (DBUS_AUTH_IS_CLIENT (auth));
2780   
2781   if (auth->state == &common_state_authenticated)
2782     return _dbus_string_get_const_data (& DBUS_AUTH_CLIENT (auth)->guid_from_server);
2783   else
2784     return NULL;
2785 }
2786
2787 /**
2788  * Sets the "authentication context" which scopes cookies
2789  * with the DBUS_COOKIE_SHA1 auth mechanism for example.
2790  *
2791  * @param auth the auth conversation
2792  * @param context the context
2793  * @returns #FALSE if no memory
2794  */
2795 dbus_bool_t
2796 _dbus_auth_set_context (DBusAuth               *auth,
2797                         const DBusString       *context)
2798 {
2799   return _dbus_string_replace_len (context, 0, _dbus_string_get_length (context),
2800                                    &auth->context, 0, _dbus_string_get_length (context));
2801 }
2802
2803 /**
2804  * Sets whether unix fd passing is potentially on the transport and
2805  * hence shall be negotiated.
2806  *
2807  * @param auth the auth conversation
2808  * @param b TRUE when unix fd passing shall be negotiated, otherwise FALSE
2809  */
2810 void
2811 _dbus_auth_set_unix_fd_possible(DBusAuth *auth, dbus_bool_t b)
2812 {
2813   auth->unix_fd_possible = b;
2814 }
2815
2816 /**
2817  * Queries whether unix fd passing was successfully negotiated.
2818  *
2819  * @param auth the auth conversion
2820  * @returns #TRUE when unix fd passing was negotiated.
2821  */
2822 dbus_bool_t
2823 _dbus_auth_get_unix_fd_negotiated(DBusAuth *auth)
2824 {
2825   return auth->unix_fd_negotiated;
2826 }
2827
2828 /** @} */
2829
2830 /* tests in dbus-auth-util.c */