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