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