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