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