2003-02-16 Anders Carlsson <andersca@codefactory.se>
[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
28 /* See doc/dbus-sasl-profile.txt */
29
30 /**
31  * @defgroup DBusAuth Authentication
32  * @ingroup  DBusInternals
33  * @brief DBusAuth object
34  *
35  * DBusAuth manages the authentication negotiation when a connection
36  * is first established, and also manage any encryption used over a
37  * connection.
38  *
39  * The file doc/dbus-sasl-profile.txt documents the network protocol
40  * used for authentication.
41  *
42  * @todo some SASL profiles require sending the empty string as a
43  * challenge/response, but we don't currently allow that in our
44  * protocol.
45  */
46
47 /**
48  * @defgroup DBusAuthInternals Authentication implementation details
49  * @ingroup  DBusInternals
50  * @brief DBusAuth implementation details
51  *
52  * Private details of authentication code.
53  *
54  * @{
55  */
56
57 /**
58  * Processes a command. Returns whether we had enough memory to
59  * complete the operation.
60  */
61 typedef dbus_bool_t (* DBusProcessAuthCommandFunction) (DBusAuth         *auth,
62                                                         const DBusString *command,
63                                                         const DBusString *args);
64
65 typedef struct
66 {
67   const char *command;
68   DBusProcessAuthCommandFunction func;
69 } DBusAuthCommandHandler;
70
71 /**
72  * This function appends an initial client response to the given string
73  */
74 typedef dbus_bool_t (* DBusInitialResponseFunction)  (DBusAuth         *auth,
75                                                       DBusString       *response);
76
77 /**
78  * This function processes a block of data received from the peer.
79  * i.e. handles a DATA command.
80  */
81 typedef dbus_bool_t (* DBusAuthDataFunction)     (DBusAuth         *auth,
82                                                   const DBusString *data);
83
84 /**
85  * This function encodes a block of data from the peer.
86  */
87 typedef dbus_bool_t (* DBusAuthEncodeFunction)   (DBusAuth         *auth,
88                                                   const DBusString *data,
89                                                   DBusString       *encoded);
90
91 /**
92  * This function decodes a block of data from the peer.
93  */
94 typedef dbus_bool_t (* DBusAuthDecodeFunction)   (DBusAuth         *auth,
95                                                   const DBusString *data,
96                                                   DBusString       *decoded);
97
98 /**
99  * This function is called when the mechanism is abandoned.
100  */
101 typedef void        (* DBusAuthShutdownFunction) (DBusAuth       *auth);
102
103 typedef struct
104 {
105   const char *mechanism;
106   DBusAuthDataFunction server_data_func;
107   DBusAuthEncodeFunction server_encode_func;
108   DBusAuthDecodeFunction server_decode_func;
109   DBusAuthShutdownFunction server_shutdown_func;
110   DBusInitialResponseFunction client_initial_response_func;
111   DBusAuthDataFunction client_data_func;
112   DBusAuthEncodeFunction client_encode_func;
113   DBusAuthDecodeFunction client_decode_func;
114   DBusAuthShutdownFunction client_shutdown_func;
115 } DBusAuthMechanismHandler;
116
117 /**
118  * Internal members of DBusAuth.
119  */
120 struct DBusAuth
121 {
122   int refcount;           /**< reference count */
123
124   DBusString incoming;    /**< Incoming data buffer */
125   DBusString outgoing;    /**< Outgoing data buffer */
126   
127   const DBusAuthCommandHandler *handlers; /**< Handlers for commands */
128
129   const DBusAuthMechanismHandler *mech;   /**< Current auth mechanism */
130
131   DBusString identity;                   /**< Current identity we're authorizing
132                                           *   as.
133                                           */
134   
135   DBusCredentials credentials;      /**< Credentials, fields may be -1 */
136
137   DBusCredentials authorized_identity; /**< Credentials that are authorized */
138   
139   unsigned int needed_memory : 1;   /**< We needed memory to continue since last
140                                      * successful getting something done
141                                      */
142   unsigned int need_disconnect : 1; /**< We've given up, time to disconnect */
143   unsigned int authenticated : 1;   /**< We are authenticated */
144   unsigned int authenticated_pending_output : 1; /**< Authenticated once we clear outgoing buffer */
145   unsigned int authenticated_pending_begin : 1;  /**< Authenticated once we get BEGIN */
146   unsigned int already_got_mechanisms : 1;       /**< Client already got mech list */
147   unsigned int already_asked_for_initial_response : 1; /**< Already sent a blank challenge to get an initial response */
148 };
149
150 typedef struct
151 {
152   DBusAuth base;
153
154   DBusList *mechs_to_try; /**< Mechanisms we got from the server that we're going to try using */
155   
156 } DBusAuthClient;
157
158 typedef struct
159 {
160   DBusAuth base;
161
162   int failures;     /**< Number of times client has been rejected */
163   int max_failures; /**< Number of times we reject before disconnect */
164   
165 } DBusAuthServer;
166
167 static dbus_bool_t process_auth         (DBusAuth         *auth,
168                                          const DBusString *command,
169                                          const DBusString *args);
170 static dbus_bool_t process_cancel       (DBusAuth         *auth,
171                                          const DBusString *command,
172                                          const DBusString *args);
173 static dbus_bool_t process_begin        (DBusAuth         *auth,
174                                          const DBusString *command,
175                                          const DBusString *args);
176 static dbus_bool_t process_data_server  (DBusAuth         *auth,
177                                          const DBusString *command,
178                                          const DBusString *args);
179 static dbus_bool_t process_error_server (DBusAuth         *auth,
180                                          const DBusString *command,
181                                          const DBusString *args);
182 static dbus_bool_t process_rejected     (DBusAuth         *auth,
183                                          const DBusString *command,
184                                          const DBusString *args);
185 static dbus_bool_t process_ok           (DBusAuth         *auth,
186                                          const DBusString *command,
187                                          const DBusString *args);
188 static dbus_bool_t process_data_client  (DBusAuth         *auth,
189                                          const DBusString *command,
190                                          const DBusString *args);
191 static dbus_bool_t process_error_client (DBusAuth         *auth,
192                                          const DBusString *command,
193                                          const DBusString *args);
194
195
196 static dbus_bool_t client_try_next_mechanism (DBusAuth *auth);
197 static dbus_bool_t send_rejected             (DBusAuth *auth);
198
199 static DBusAuthCommandHandler
200 server_handlers[] = {
201   { "AUTH", process_auth },
202   { "CANCEL", process_cancel },
203   { "BEGIN", process_begin },
204   { "DATA", process_data_server },
205   { "ERROR", process_error_server },
206   { NULL, NULL }
207 };
208
209 static DBusAuthCommandHandler
210 client_handlers[] = {
211   { "REJECTED", process_rejected },
212   { "OK", process_ok },
213   { "DATA", process_data_client },
214   { "ERROR", process_error_client },
215   { NULL, NULL }
216 };
217
218 /**
219  * @param auth the auth conversation
220  * @returns #TRUE if the conversation is the server side
221  */
222 #define DBUS_AUTH_IS_SERVER(auth) ((auth)->handlers == server_handlers)
223 /**
224  * @param auth the auth conversation
225  * @returns #TRUE if the conversation is the client side
226  */
227 #define DBUS_AUTH_IS_CLIENT(auth) ((auth)->handlers == client_handlers)
228 /**
229  * @param auth the auth conversation
230  * @returns auth cast to DBusAuthClient
231  */
232 #define DBUS_AUTH_CLIENT(auth)    ((DBusAuthClient*)(auth))
233 /**
234  * @param auth the auth conversation
235  * @returns auth cast to DBusAuthServer
236  */
237 #define DBUS_AUTH_SERVER(auth)    ((DBusAuthServer*)(auth))
238
239 static DBusAuth*
240 _dbus_auth_new (int size)
241 {
242   DBusAuth *auth;
243   
244   auth = dbus_malloc0 (size);
245   if (auth == NULL)
246     return NULL;
247   
248   auth->refcount = 1;
249
250   auth->credentials.pid = -1;
251   auth->credentials.uid = -1;
252   auth->credentials.gid = -1;
253
254   auth->authorized_identity.pid = -1;
255   auth->authorized_identity.uid = -1;
256   auth->authorized_identity.gid = -1;
257   
258   /* note that we don't use the max string length feature,
259    * because you can't use that feature if you're going to
260    * try to recover from out-of-memory (it creates
261    * what looks like unrecoverable inability to alloc
262    * more space in the string). But we do handle
263    * overlong buffers in _dbus_auth_do_work().
264    */
265   
266   if (!_dbus_string_init (&auth->incoming, _DBUS_INT_MAX))
267     {
268       dbus_free (auth);
269       return NULL;
270     }
271
272   if (!_dbus_string_init (&auth->outgoing, _DBUS_INT_MAX))
273     {
274       _dbus_string_free (&auth->incoming);
275       dbus_free (auth);
276       return NULL;
277     }
278   
279   if (!_dbus_string_init (&auth->identity, _DBUS_INT_MAX))
280     {
281       _dbus_string_free (&auth->incoming);
282       _dbus_string_free (&auth->outgoing);
283       dbus_free (auth);
284       return NULL;
285     }
286   
287   return auth;
288 }
289
290 static void
291 shutdown_mech (DBusAuth *auth)
292 {
293   /* Cancel any auth */
294   auth->authenticated_pending_begin = FALSE;
295   auth->authenticated = FALSE;
296   auth->already_asked_for_initial_response = FALSE;
297   _dbus_string_set_length (&auth->identity, 0);
298   auth->authorized_identity.pid = -1;
299   auth->authorized_identity.uid = -1;
300   auth->authorized_identity.gid = -1;
301   
302   if (auth->mech != NULL)
303     {
304       _dbus_verbose ("Shutting down mechanism %s\n",
305                      auth->mech->mechanism);
306       
307       if (DBUS_AUTH_IS_CLIENT (auth))
308         (* auth->mech->client_shutdown_func) (auth);
309       else
310         (* auth->mech->server_shutdown_func) (auth);
311       
312       auth->mech = NULL;
313     }
314 }
315
316 static dbus_bool_t
317 handle_server_data_stupid_test_mech (DBusAuth         *auth,
318                                      const DBusString *data)
319 {
320   if (!_dbus_string_append (&auth->outgoing,
321                             "OK\r\n"))
322     return FALSE;
323
324   auth->authenticated_pending_begin = TRUE;
325   
326   return TRUE;
327 }
328
329 static void
330 handle_server_shutdown_stupid_test_mech (DBusAuth *auth)
331 {
332
333 }
334
335 static dbus_bool_t
336 handle_client_data_stupid_test_mech (DBusAuth         *auth,
337                                      const DBusString *data)
338 {
339   
340   return TRUE;
341 }
342
343 static void
344 handle_client_shutdown_stupid_test_mech (DBusAuth *auth)
345 {
346
347 }
348
349 /* the stupid test mech is a base64-encoded string;
350  * all the inefficiency, none of the security!
351  */
352 static dbus_bool_t
353 handle_encode_stupid_test_mech (DBusAuth         *auth,
354                                 const DBusString *plaintext,
355                                 DBusString       *encoded)
356 {
357   if (!_dbus_string_base64_encode (plaintext, 0, encoded,
358                                    _dbus_string_get_length (encoded)))
359     return FALSE;
360   
361   return TRUE;
362 }
363
364 static dbus_bool_t
365 handle_decode_stupid_test_mech (DBusAuth         *auth,
366                                 const DBusString *encoded,
367                                 DBusString       *plaintext)
368 {
369   if (!_dbus_string_base64_decode (encoded, 0, plaintext,
370                                    _dbus_string_get_length (plaintext)))
371     return FALSE;
372   
373   return TRUE;
374 }
375
376 static dbus_bool_t
377 handle_server_data_external_mech (DBusAuth         *auth,
378                                   const DBusString *data)
379 {
380   DBusCredentials desired_identity;
381
382   if (auth->credentials.uid < 0)
383     {
384       _dbus_verbose ("no credentials, mechanism EXTERNAL can't authenticate\n");
385       return send_rejected (auth);
386     }
387   
388   if (_dbus_string_get_length (data) > 0)
389     {
390       if (_dbus_string_get_length (&auth->identity) > 0)
391         {
392           /* Tried to send two auth identities, wtf */
393           _dbus_verbose ("client tried to send auth identity, but we already have one\n");
394           return send_rejected (auth);
395         }
396       else
397         {
398           /* this is our auth identity */
399           if (!_dbus_string_copy (data, 0, &auth->identity, 0))
400             return FALSE;
401         }
402     }
403
404   /* Poke client for an auth identity, if none given */
405   if (_dbus_string_get_length (&auth->identity) == 0 &&
406       !auth->already_asked_for_initial_response)
407     {
408       if (_dbus_string_append (&auth->outgoing,
409                                "DATA\r\n"))
410         {
411           _dbus_verbose ("sending empty challenge asking client for auth identity\n");
412           auth->already_asked_for_initial_response = TRUE;
413           return TRUE;
414         }
415       else
416         return FALSE;
417     }
418
419   desired_identity.pid = -1;
420   desired_identity.uid = -1;
421   desired_identity.gid = -1;
422   
423   /* If auth->identity is still empty here, then client
424    * responded with an empty string after we poked it for
425    * an initial response. This means to try to auth the
426    * identity provided in the credentials.
427    */
428   if (_dbus_string_get_length (&auth->identity) == 0)
429     {
430       desired_identity.uid = auth->credentials.uid;
431     }
432   else
433     {
434       if (!_dbus_credentials_from_uid_string (&auth->identity,
435                                               &desired_identity))
436         {
437           _dbus_verbose ("could not get credentials from uid string\n");
438           return send_rejected (auth);
439         }
440     }
441
442   if (desired_identity.uid < 0)
443     {
444       _dbus_verbose ("desired UID %d is no good\n", desired_identity.uid);
445       return send_rejected (auth);
446     }
447   
448   if (_dbus_credentials_match (&desired_identity,
449                                &auth->credentials))
450     {
451       /* client has authenticated */
452       _dbus_verbose ("authenticated client with UID %d matching socket credentials UID %d\n",
453                      desired_identity.uid,
454                      auth->credentials.uid);
455       
456       if (!_dbus_string_append (&auth->outgoing,
457                                 "OK\r\n"))
458         return FALSE;
459
460       auth->authorized_identity.uid = desired_identity.uid;
461       
462       auth->authenticated_pending_begin = TRUE;
463       
464       return TRUE;
465     }
466   else
467     {
468       _dbus_verbose ("credentials uid=%d gid=%d do not allow uid=%d gid=%d\n",
469                      auth->credentials.uid, auth->credentials.gid,
470                      desired_identity.uid, desired_identity.gid);
471       return send_rejected (auth);
472     }
473 }
474
475 static void
476 handle_server_shutdown_external_mech (DBusAuth *auth)
477 {
478
479 }
480
481 static dbus_bool_t
482 handle_client_initial_response_external_mech (DBusAuth         *auth,
483                                               DBusString       *response)
484 {
485   /* We always append our UID as an initial response, so the server
486    * doesn't have to send back an empty challenge to check whether we
487    * want to specify an identity. i.e. this avoids a round trip that
488    * the spec for the EXTERNAL mechanism otherwise requires.
489    */
490   DBusString plaintext;
491
492   if (!_dbus_string_init (&plaintext, _DBUS_INT_MAX))
493     return FALSE;
494   
495   if (!_dbus_string_append_our_uid (&plaintext))
496     goto failed;
497
498   if (!_dbus_string_base64_encode (&plaintext, 0,
499                                    response,
500                                    _dbus_string_get_length (response)))
501     goto failed;
502
503   _dbus_string_free (&plaintext);
504   
505   return TRUE;
506
507  failed:
508   _dbus_string_free (&plaintext);
509   return FALSE;  
510 }
511
512 static dbus_bool_t
513 handle_client_data_external_mech (DBusAuth         *auth,
514                                   const DBusString *data)
515 {
516   
517   return TRUE;
518 }
519
520 static void
521 handle_client_shutdown_external_mech (DBusAuth *auth)
522 {
523
524 }
525
526 /* Put mechanisms here in order of preference.
527  * What I eventually want to have is:
528  *
529  *  - a mechanism that checks UNIX domain socket credentials
530  *  - a simple magic cookie mechanism like X11 or ICE
531  *  - mechanisms that chain to Cyrus SASL, so we can use anything it
532  *    offers such as Kerberos, X509, whatever.
533  * 
534  */
535 static const DBusAuthMechanismHandler
536 all_mechanisms[] = {
537   { "EXTERNAL",
538     handle_server_data_external_mech,
539     NULL, NULL,
540     handle_server_shutdown_external_mech,
541     handle_client_initial_response_external_mech,
542     handle_client_data_external_mech,
543     NULL, NULL,
544     handle_client_shutdown_external_mech },
545   /* Obviously this has to die for production use */
546   { "DBUS_STUPID_TEST_MECH",
547     handle_server_data_stupid_test_mech,
548     handle_encode_stupid_test_mech,
549     handle_decode_stupid_test_mech,
550     handle_server_shutdown_stupid_test_mech,
551     NULL,
552     handle_client_data_stupid_test_mech,
553     handle_encode_stupid_test_mech,
554     handle_decode_stupid_test_mech,
555     handle_client_shutdown_stupid_test_mech },
556   { NULL, NULL }
557 };
558
559 static const DBusAuthMechanismHandler*
560 find_mech (const DBusString *name)
561 {
562   int i;
563   
564   i = 0;
565   while (all_mechanisms[i].mechanism != NULL)
566     {
567       if (_dbus_string_equal_c_str (name,
568                                     all_mechanisms[i].mechanism))
569
570         return &all_mechanisms[i];
571       
572       ++i;
573     }
574   
575   return NULL;
576 }
577
578 static dbus_bool_t
579 send_rejected (DBusAuth *auth)
580 {
581   DBusString command;
582   DBusAuthServer *server_auth;
583   int i;
584   
585   if (!_dbus_string_init (&command, _DBUS_INT_MAX))
586     return FALSE;
587   
588   if (!_dbus_string_append (&command,
589                             "REJECTED"))
590     goto nomem;
591
592   i = 0;
593   while (all_mechanisms[i].mechanism != NULL)
594     {
595       if (!_dbus_string_append (&command,
596                                 " "))
597         goto nomem;
598
599       if (!_dbus_string_append (&command,
600                                 all_mechanisms[i].mechanism))
601         goto nomem;
602       
603       ++i;
604     }
605   
606   if (!_dbus_string_append (&command, "\r\n"))
607     goto nomem;
608
609   if (!_dbus_string_copy (&command, 0, &auth->outgoing,
610                           _dbus_string_get_length (&auth->outgoing)))
611     goto nomem;
612
613   shutdown_mech (auth);
614   
615   _dbus_assert (DBUS_AUTH_IS_SERVER (auth));
616   server_auth = DBUS_AUTH_SERVER (auth);
617   server_auth->failures += 1;
618   
619   return TRUE;
620
621  nomem:
622   _dbus_string_free (&command);
623   return FALSE;
624 }
625
626 static dbus_bool_t
627 process_auth (DBusAuth         *auth,
628               const DBusString *command,
629               const DBusString *args)
630 {
631   if (auth->mech)
632     {
633       /* We are already using a mechanism, client is on crack */
634       if (!_dbus_string_append (&auth->outgoing,
635                                 "ERROR \"Sent AUTH while another AUTH in progress\"\r\n"))
636         return FALSE;
637
638       return TRUE;
639     }
640   else if (_dbus_string_get_length (args) == 0)
641     {
642       /* No args to the auth, send mechanisms */
643       if (!send_rejected (auth))
644         return FALSE;
645
646       return TRUE;
647     }
648   else
649     {
650       int i;
651       DBusString mech;
652       DBusString base64_response;
653       DBusString decoded_response;
654       
655       _dbus_string_find_blank (args, 0, &i);
656
657       if (!_dbus_string_init (&mech, _DBUS_INT_MAX))
658         return FALSE;
659
660       if (!_dbus_string_init (&base64_response, _DBUS_INT_MAX))
661         {
662           _dbus_string_free (&mech);
663           return FALSE;
664         }
665
666       if (!_dbus_string_init (&decoded_response, _DBUS_INT_MAX))
667         {
668           _dbus_string_free (&mech);
669           _dbus_string_free (&base64_response);
670           return FALSE;
671         }
672       
673       if (!_dbus_string_copy_len (args, 0, i, &mech, 0))
674         goto failed;
675
676       if (!_dbus_string_copy (args, i, &base64_response, 0))
677         goto failed;
678
679       if (!_dbus_string_base64_decode (&base64_response, 0,
680                                        &decoded_response, 0))
681         goto failed;
682
683       auth->mech = find_mech (&mech);
684       if (auth->mech != NULL)
685         {
686           _dbus_verbose ("Trying mechanism %s with initial response of %d bytes\n",
687                          auth->mech->mechanism,
688                          _dbus_string_get_length (&decoded_response));
689           
690           if (!(* auth->mech->server_data_func) (auth,
691                                                  &decoded_response))
692             goto failed;
693         }
694       else
695         {
696           /* Unsupported mechanism */
697           if (!send_rejected (auth))
698             return FALSE;
699         }
700
701       _dbus_string_free (&mech);      
702       _dbus_string_free (&base64_response);
703       _dbus_string_free (&decoded_response);
704
705       return TRUE;
706       
707     failed:
708       auth->mech = NULL;
709       _dbus_string_free (&mech);
710       _dbus_string_free (&base64_response);
711       _dbus_string_free (&decoded_response);
712       return FALSE;
713     }
714 }
715
716 static dbus_bool_t
717 process_cancel (DBusAuth         *auth,
718                 const DBusString *command,
719                 const DBusString *args)
720 {
721   shutdown_mech (auth);
722   
723   return TRUE;
724 }
725
726 static dbus_bool_t
727 process_begin (DBusAuth         *auth,
728                const DBusString *command,
729                const DBusString *args)
730 {
731   if (auth->authenticated_pending_begin)
732     auth->authenticated = TRUE;
733   else
734     {
735       auth->need_disconnect = TRUE; /* client trying to send data before auth,
736                                      * kick it
737                                      */
738       shutdown_mech (auth);
739     }
740   
741   return TRUE;
742 }
743
744 static dbus_bool_t
745 process_data_server (DBusAuth         *auth,
746                      const DBusString *command,
747                      const DBusString *args)
748 {
749   if (auth->mech != NULL)
750     {
751       DBusString decoded;
752
753       if (!_dbus_string_init (&decoded, _DBUS_INT_MAX))
754         return FALSE;
755
756       if (!_dbus_string_base64_decode (args, 0, &decoded, 0))
757         {
758           _dbus_string_free (&decoded);
759           return FALSE;
760         }
761       
762       if (!(* auth->mech->server_data_func) (auth, &decoded))
763         {
764           _dbus_string_free (&decoded);
765           return FALSE;
766         }
767
768       _dbus_string_free (&decoded);
769     }
770   else
771     {
772       if (!_dbus_string_append (&auth->outgoing,
773                                 "ERROR \"Not currently in an auth conversation\"\r\n"))
774         return FALSE;
775     }
776   
777   return TRUE;
778 }
779
780 static dbus_bool_t
781 process_error_server (DBusAuth         *auth,
782                       const DBusString *command,
783                       const DBusString *args)
784 {
785   
786   return TRUE;
787 }
788
789 /* return FALSE if no memory, TRUE if all OK */
790 static dbus_bool_t
791 get_word (const DBusString *str,
792           int              *start,
793           DBusString       *word)
794 {
795   int i;
796
797   _dbus_string_skip_blank (str, *start, start);
798   _dbus_string_find_blank (str, *start, &i);
799   
800   if (i > *start)
801     {
802       if (!_dbus_string_copy_len (str, *start, i, word, 0))
803         return FALSE;
804       
805       *start = i;
806     }
807
808   return TRUE;
809 }
810
811 static dbus_bool_t
812 record_mechanisms (DBusAuth         *auth,
813                    const DBusString *command,
814                    const DBusString *args)
815 {
816   int next;
817   int len;
818
819   if (auth->already_got_mechanisms)
820     return TRUE;
821   
822   len = _dbus_string_get_length (args);
823   
824   next = 0;
825   while (next < len)
826     {
827       DBusString m;
828       const DBusAuthMechanismHandler *mech;
829       
830       if (!_dbus_string_init (&m, _DBUS_INT_MAX))
831         goto nomem;
832       
833       if (!get_word (args, &next, &m))
834         goto nomem;
835
836       mech = find_mech (&m);
837
838       if (mech != NULL)
839         {
840           /* FIXME right now we try mechanisms in the order
841            * the server lists them; should we do them in
842            * some more deterministic order?
843            *
844            * Probably in all_mechanisms order, our order of
845            * preference. Of course when the server is us,
846            * it lists things in that order anyhow.
847            */
848
849           _dbus_verbose ("Adding mechanism %s to list we will try\n",
850                          mech->mechanism);
851           
852           if (!_dbus_list_append (& DBUS_AUTH_CLIENT (auth)->mechs_to_try,
853                                   (void*) mech))
854             goto nomem;
855         }
856       else
857         {
858           const char *s;
859
860           _dbus_string_get_const_data (&m, &s);
861           _dbus_verbose ("Server offered mechanism \"%s\" that we don't know how to use\n",
862                          s);
863         }
864
865       _dbus_string_free (&m);
866     }
867   
868   auth->already_got_mechanisms = TRUE;
869   
870   return TRUE;
871
872  nomem:
873   _dbus_list_clear (& DBUS_AUTH_CLIENT (auth)->mechs_to_try);
874   
875   return FALSE;
876 }
877
878 static dbus_bool_t
879 client_try_next_mechanism (DBusAuth *auth)
880 {
881   const DBusAuthMechanismHandler *mech;
882   DBusString auth_command;
883
884   if (DBUS_AUTH_CLIENT (auth)->mechs_to_try == NULL)
885     return FALSE;
886
887   mech = DBUS_AUTH_CLIENT (auth)->mechs_to_try->data;
888
889   if (!_dbus_string_init (&auth_command, _DBUS_INT_MAX))
890     return FALSE;
891       
892   if (!_dbus_string_append (&auth_command,
893                             "AUTH "))
894     {
895       _dbus_string_free (&auth_command);
896       return FALSE;
897     }  
898   
899   if (!_dbus_string_append (&auth_command,
900                             mech->mechanism))
901     {
902       _dbus_string_free (&auth_command);
903       return FALSE;
904     }
905
906   if (mech->client_initial_response_func != NULL)
907     {
908       if (!_dbus_string_append (&auth_command, " "))
909         {
910           _dbus_string_free (&auth_command);
911           return FALSE;
912         }
913       
914       if (!(* mech->client_initial_response_func) (auth, &auth_command))
915         {
916           _dbus_string_free (&auth_command);
917           return FALSE;
918         }
919     }
920   
921   if (!_dbus_string_append (&auth_command,
922                             "\r\n"))
923     {
924       _dbus_string_free (&auth_command);
925       return FALSE;
926     }
927
928   if (!_dbus_string_copy (&auth_command, 0,
929                           &auth->outgoing,
930                           _dbus_string_get_length (&auth->outgoing)))
931     {
932       _dbus_string_free (&auth_command);
933       return FALSE;
934     }
935
936   auth->mech = mech;      
937   _dbus_list_pop_first (& DBUS_AUTH_CLIENT (auth)->mechs_to_try);
938
939   _dbus_verbose ("Trying mechanism %s\n",
940                  auth->mech->mechanism);
941
942   _dbus_string_free (&auth_command);
943   
944   return TRUE;
945 }
946
947 static dbus_bool_t
948 process_rejected (DBusAuth         *auth,
949                   const DBusString *command,
950                   const DBusString *args)
951 {
952   shutdown_mech (auth);
953   
954   if (!auth->already_got_mechanisms)
955     {
956       if (!record_mechanisms (auth, command, args))
957         return FALSE;
958     }
959   
960   if (DBUS_AUTH_CLIENT (auth)->mechs_to_try != NULL)
961     {
962       client_try_next_mechanism (auth);
963     }
964   else
965     {
966       /* Give up */
967       auth->need_disconnect = TRUE;
968     }
969   
970   return TRUE;
971 }
972
973 static dbus_bool_t
974 process_ok (DBusAuth         *auth,
975             const DBusString *command,
976             const DBusString *args)
977 {
978   if (!_dbus_string_append (&auth->outgoing,
979                             "BEGIN\r\n"))
980     return FALSE;
981   
982   auth->authenticated_pending_output = TRUE;
983   
984   return TRUE;
985 }
986
987
988 static dbus_bool_t
989 process_data_client (DBusAuth         *auth,
990                      const DBusString *command,
991                      const DBusString *args)
992 {
993   if (auth->mech != NULL)
994     {
995       DBusString decoded;
996
997       if (!_dbus_string_init (&decoded, _DBUS_INT_MAX))
998         return FALSE;
999
1000       if (!_dbus_string_base64_decode (args, 0, &decoded, 0))
1001         {
1002           _dbus_string_free (&decoded);
1003           return FALSE;
1004         }
1005       
1006       if (!(* auth->mech->client_data_func) (auth, &decoded))
1007         {
1008           _dbus_string_free (&decoded);
1009           return FALSE;
1010         }
1011
1012       _dbus_string_free (&decoded);
1013     }
1014   else
1015     {
1016       if (!_dbus_string_append (&auth->outgoing,
1017                                 "ERROR \"Got DATA when not in an auth exchange\"\r\n"))
1018         return FALSE;
1019     }
1020   
1021   return TRUE;
1022 }
1023
1024 static dbus_bool_t
1025 process_error_client (DBusAuth         *auth,
1026                       const DBusString *command,
1027                       const DBusString *args)
1028 {
1029   return TRUE;
1030 }
1031
1032 static dbus_bool_t
1033 process_unknown (DBusAuth         *auth,
1034                  const DBusString *command,
1035                  const DBusString *args)
1036 {
1037   if (!_dbus_string_append (&auth->outgoing,
1038                             "ERROR \"Unknown command\"\r\n"))
1039     return FALSE;
1040
1041   return TRUE;
1042 }
1043
1044 /* returns whether to call it again right away */
1045 static dbus_bool_t
1046 process_command (DBusAuth *auth)
1047 {
1048   DBusString command;
1049   DBusString args;
1050   int eol;
1051   int i, j;
1052   dbus_bool_t retval;
1053
1054   /* _dbus_verbose ("  trying process_command()\n"); */
1055   
1056   retval = FALSE;
1057   
1058   eol = 0;
1059   if (!_dbus_string_find (&auth->incoming, 0, "\r\n", &eol))
1060     return FALSE;
1061   
1062   if (!_dbus_string_init (&command, _DBUS_INT_MAX))
1063     {
1064       auth->needed_memory = TRUE;
1065       return FALSE;
1066     }
1067
1068   if (!_dbus_string_init (&args, _DBUS_INT_MAX))
1069     {
1070       auth->needed_memory = TRUE;
1071       return FALSE;
1072     }
1073   
1074   if (eol > _DBUS_ONE_MEGABYTE)
1075     {
1076       /* This is a giant line, someone is trying to hose us. */
1077       if (!_dbus_string_append (&auth->outgoing, "ERROR \"Command too long\"\r\n"))
1078         goto out;
1079       else
1080         goto next_command;
1081     }
1082
1083   if (!_dbus_string_copy_len (&auth->incoming, 0, eol, &command, 0))
1084     goto out;
1085
1086   if (!_dbus_string_validate_ascii (&command, 0,
1087                                     _dbus_string_get_length (&command)))
1088     {
1089       _dbus_verbose ("Command contained non-ASCII chars or embedded nul\n");
1090       if (!_dbus_string_append (&auth->outgoing, "ERROR \"Command contained non-ASCII\"\r\n"))
1091         goto out;
1092       else
1093         goto next_command;
1094     }
1095   
1096   {
1097     const char *q;
1098     _dbus_string_get_const_data (&command, &q);
1099     _dbus_verbose ("got command \"%s\"\n", q);
1100   }
1101   
1102   _dbus_string_find_blank (&command, 0, &i);
1103   _dbus_string_skip_blank (&command, i, &j);
1104
1105   if (j > i)
1106     _dbus_string_delete (&command, i, j - i);
1107   
1108   if (!_dbus_string_move (&command, i, &args, 0))
1109     goto out;
1110   
1111   i = 0;
1112   while (auth->handlers[i].command != NULL)
1113     {
1114       if (_dbus_string_equal_c_str (&command,
1115                                     auth->handlers[i].command))
1116         {
1117           _dbus_verbose ("Processing auth command %s\n",
1118                          auth->handlers[i].command);
1119           
1120           if (!(* auth->handlers[i].func) (auth, &command, &args))
1121             goto out;
1122
1123           break;
1124         }
1125       ++i;
1126     }
1127
1128   if (auth->handlers[i].command == NULL)
1129     {
1130       if (!process_unknown (auth, &command, &args))
1131         goto out;
1132     }
1133
1134  next_command:
1135   
1136   /* We've succeeded in processing the whole command so drop it out
1137    * of the incoming buffer and return TRUE to try another command.
1138    */
1139
1140   _dbus_string_delete (&auth->incoming, 0, eol);
1141   
1142   /* kill the \r\n */
1143   _dbus_string_delete (&auth->incoming, 0, 2);
1144
1145   retval = TRUE;
1146   
1147  out:
1148   _dbus_string_free (&args);
1149   _dbus_string_free (&command);
1150
1151   if (!retval)
1152     auth->needed_memory = TRUE;
1153   else
1154     auth->needed_memory = FALSE;
1155   
1156   return retval;
1157 }
1158
1159
1160 /** @} */
1161
1162 /**
1163  * @addtogroup DBusAuth
1164  * @{
1165  */
1166
1167 /**
1168  * Creates a new auth conversation object for the server side.
1169  * See doc/dbus-sasl-profile.txt for full details on what
1170  * this object does.
1171  *
1172  * @returns the new object or #NULL if no memory
1173  */
1174 DBusAuth*
1175 _dbus_auth_server_new (void)
1176 {
1177   DBusAuth *auth;
1178   DBusAuthServer *server_auth;
1179
1180   auth = _dbus_auth_new (sizeof (DBusAuthServer));
1181   if (auth == NULL)
1182     return NULL;
1183
1184   auth->handlers = server_handlers;
1185
1186   server_auth = DBUS_AUTH_SERVER (auth);
1187
1188   /* perhaps this should be per-mechanism with a lower
1189    * max
1190    */
1191   server_auth->failures = 0;
1192   server_auth->max_failures = 6;
1193   
1194   return auth;
1195 }
1196
1197 /**
1198  * Creates a new auth conversation object for the client side.
1199  * See doc/dbus-sasl-profile.txt for full details on what
1200  * this object does.
1201  *
1202  * @returns the new object or #NULL if no memory
1203  */
1204 DBusAuth*
1205 _dbus_auth_client_new (void)
1206 {
1207   DBusAuth *auth;
1208
1209   auth = _dbus_auth_new (sizeof (DBusAuthClient));
1210   if (auth == NULL)
1211     return NULL;
1212
1213   auth->handlers = client_handlers;
1214
1215   /* Add a default mechanism to try */
1216   if (!_dbus_list_append (& DBUS_AUTH_CLIENT (auth)->mechs_to_try,
1217                           (void*) &all_mechanisms[0]))
1218     {
1219       _dbus_auth_unref (auth);
1220       return NULL;
1221     }
1222
1223   /* Now try the mechanism we just added */
1224   if (!client_try_next_mechanism (auth))
1225     {
1226       _dbus_auth_unref (auth);
1227       return NULL;
1228     }
1229   
1230   return auth;
1231 }
1232
1233 /**
1234  * Increments the refcount of an auth object.
1235  *
1236  * @param auth the auth conversation
1237  */
1238 void
1239 _dbus_auth_ref (DBusAuth *auth)
1240 {
1241   _dbus_assert (auth != NULL);
1242   
1243   auth->refcount += 1;
1244 }
1245
1246 /**
1247  * Decrements the refcount of an auth object.
1248  *
1249  * @param auth the auth conversation
1250  */
1251 void
1252 _dbus_auth_unref (DBusAuth *auth)
1253 {
1254   _dbus_assert (auth != NULL);
1255   _dbus_assert (auth->refcount > 0);
1256
1257   auth->refcount -= 1;
1258   if (auth->refcount == 0)
1259     {
1260       shutdown_mech (auth);
1261
1262       if (DBUS_AUTH_IS_CLIENT (auth))
1263         {
1264           _dbus_list_clear (& DBUS_AUTH_CLIENT (auth)->mechs_to_try);
1265         }
1266
1267       _dbus_string_free (&auth->identity);
1268       _dbus_string_free (&auth->incoming);
1269       _dbus_string_free (&auth->outgoing);
1270       dbus_free (auth);
1271     }
1272 }
1273
1274 /**
1275  * @param auth the auth conversation object
1276  * @returns #TRUE if we're in a final state
1277  */
1278 #define DBUS_AUTH_IN_END_STATE(auth) ((auth)->need_disconnect || (auth)->authenticated)
1279
1280 /**
1281  * Analyzes buffered input and moves the auth conversation forward,
1282  * returning the new state of the auth conversation.
1283  *
1284  * @param auth the auth conversation
1285  * @returns the new state
1286  */
1287 DBusAuthState
1288 _dbus_auth_do_work (DBusAuth *auth)
1289 {
1290   auth->needed_memory = FALSE;
1291
1292   /* Max amount we'll buffer up before deciding someone's on crack */
1293 #define MAX_BUFFER (16 * _DBUS_ONE_KILOBYTE)
1294
1295   do
1296     {
1297       if (DBUS_AUTH_IN_END_STATE (auth))
1298         break;
1299       
1300       if (_dbus_string_get_length (&auth->incoming) > MAX_BUFFER ||
1301           _dbus_string_get_length (&auth->outgoing) > MAX_BUFFER)
1302         {
1303           auth->need_disconnect = TRUE;
1304           _dbus_verbose ("Disconnecting due to excessive data buffered in auth phase\n");
1305           break;
1306         }
1307
1308       if (auth->mech == NULL &&
1309           auth->already_got_mechanisms &&
1310           DBUS_AUTH_CLIENT (auth)->mechs_to_try == NULL)
1311         {
1312           auth->need_disconnect = TRUE;
1313           _dbus_verbose ("Disconnecting because we are out of mechanisms to try using\n");
1314           break;
1315         }
1316     }
1317   while (process_command (auth));
1318
1319   if (DBUS_AUTH_IS_SERVER (auth) &&
1320       DBUS_AUTH_SERVER (auth)->failures >=
1321       DBUS_AUTH_SERVER (auth)->max_failures)
1322     auth->need_disconnect = TRUE;
1323
1324   if (auth->need_disconnect)
1325     return DBUS_AUTH_STATE_NEED_DISCONNECT;
1326   else if (auth->authenticated)
1327     {
1328       if (_dbus_string_get_length (&auth->incoming) > 0)
1329         return DBUS_AUTH_STATE_AUTHENTICATED_WITH_UNUSED_BYTES;
1330       else
1331         return DBUS_AUTH_STATE_AUTHENTICATED;
1332     }
1333   else if (auth->needed_memory)
1334     return DBUS_AUTH_STATE_WAITING_FOR_MEMORY;
1335   else if (_dbus_string_get_length (&auth->outgoing) > 0)
1336     return DBUS_AUTH_STATE_HAVE_BYTES_TO_SEND;
1337   else
1338     return DBUS_AUTH_STATE_WAITING_FOR_INPUT;
1339 }
1340
1341 /**
1342  * Gets bytes that need to be sent to the peer we're conversing with.
1343  * After writing some bytes, _dbus_auth_bytes_sent() must be called
1344  * to notify the auth object that they were written.
1345  *
1346  * @param auth the auth conversation
1347  * @param str return location for a ref to the buffer to send
1348  * @returns #FALSE if nothing to send
1349  */
1350 dbus_bool_t
1351 _dbus_auth_get_bytes_to_send (DBusAuth          *auth,
1352                               const DBusString **str)
1353 {
1354   _dbus_assert (auth != NULL);
1355   _dbus_assert (str != NULL);
1356
1357   *str = NULL;
1358   
1359   if (DBUS_AUTH_IN_END_STATE (auth))
1360     return FALSE;
1361
1362   if (_dbus_string_get_length (&auth->outgoing) == 0)
1363     return FALSE;
1364
1365   *str = &auth->outgoing;
1366
1367   return TRUE;
1368 }
1369
1370 /**
1371  * Notifies the auth conversation object that
1372  * the given number of bytes of the outgoing buffer
1373  * have been written out.
1374  *
1375  * @param auth the auth conversation
1376  * @param bytes_sent number of bytes written out
1377  */
1378 void
1379 _dbus_auth_bytes_sent (DBusAuth *auth,
1380                        int       bytes_sent)
1381 {
1382   _dbus_string_delete (&auth->outgoing,
1383                        0, bytes_sent);
1384   
1385   if (auth->authenticated_pending_output &&
1386       _dbus_string_get_length (&auth->outgoing) == 0)
1387     auth->authenticated = TRUE;
1388 }
1389
1390 /**
1391  * Stores bytes received from the peer we're conversing with.
1392  *
1393  * @param auth the auth conversation
1394  * @param str the received bytes.
1395  * @returns #FALSE if not enough memory to store the bytes or we were already authenticated.
1396  */
1397 dbus_bool_t
1398 _dbus_auth_bytes_received (DBusAuth   *auth,
1399                            const DBusString *str)
1400 {
1401   _dbus_assert (auth != NULL);
1402   _dbus_assert (str != NULL);
1403   
1404   if (DBUS_AUTH_IN_END_STATE (auth))
1405     return FALSE;
1406
1407   auth->needed_memory = FALSE;
1408   
1409   if (!_dbus_string_copy (str, 0,
1410                           &auth->incoming,
1411                           _dbus_string_get_length (&auth->incoming)))
1412     {
1413       auth->needed_memory = TRUE;
1414       return FALSE;
1415     }
1416
1417   _dbus_auth_do_work (auth);
1418   
1419   return TRUE;
1420 }
1421
1422 /**
1423  * Returns leftover bytes that were not used as part of the auth
1424  * conversation.  These bytes will be part of the message stream
1425  * instead. This function may not be called until authentication has
1426  * succeeded.
1427  *
1428  * @param auth the auth conversation
1429  * @param str string to append the unused bytes to
1430  * @returns #FALSE if not enough memory to return the bytes
1431  */
1432 dbus_bool_t
1433 _dbus_auth_get_unused_bytes (DBusAuth   *auth,
1434                              DBusString *str)
1435 {
1436   if (!DBUS_AUTH_IN_END_STATE (auth))
1437     return FALSE;
1438   
1439   if (!_dbus_string_move (&auth->incoming,
1440                           0, str,
1441                           _dbus_string_get_length (str)))
1442     return FALSE;
1443
1444   return TRUE;
1445 }
1446
1447 /**
1448  * Called post-authentication, indicates whether we need to encode
1449  * the message stream with _dbus_auth_encode_data() prior to
1450  * sending it to the peer.
1451  *
1452  * @param auth the auth conversation
1453  * @returns #TRUE if we need to encode the stream
1454  */
1455 dbus_bool_t
1456 _dbus_auth_needs_encoding (DBusAuth *auth)
1457 {
1458   if (!auth->authenticated)
1459     return FALSE;
1460   
1461   if (auth->mech != NULL)
1462     {
1463       if (DBUS_AUTH_IS_CLIENT (auth))
1464         return auth->mech->client_encode_func != NULL;
1465       else
1466         return auth->mech->server_encode_func != NULL;
1467     }
1468   else
1469     return FALSE;
1470 }
1471
1472 /**
1473  * Called post-authentication, encodes a block of bytes for sending to
1474  * the peer. If no encoding was negotiated, just copies the bytes
1475  * (you can avoid this by checking _dbus_auth_needs_encoding()).
1476  *
1477  * @param auth the auth conversation
1478  * @param plaintext the plain text data
1479  * @param encoded initialized string to where encoded data is appended
1480  * @returns #TRUE if we had enough memory and successfully encoded
1481  */
1482 dbus_bool_t
1483 _dbus_auth_encode_data (DBusAuth         *auth,
1484                         const DBusString *plaintext,
1485                         DBusString       *encoded)
1486 {
1487   _dbus_assert (plaintext != encoded);
1488   
1489   if (!auth->authenticated)
1490     return FALSE;
1491   
1492   if (_dbus_auth_needs_encoding (auth))
1493     {
1494       if (DBUS_AUTH_IS_CLIENT (auth))
1495         return (* auth->mech->client_encode_func) (auth, plaintext, encoded);
1496       else
1497         return (* auth->mech->server_encode_func) (auth, plaintext, encoded);
1498     }
1499   else
1500     {
1501       return _dbus_string_copy (plaintext, 0, encoded,
1502                                 _dbus_string_get_length (encoded));
1503     }
1504 }
1505
1506 /**
1507  * Called post-authentication, indicates whether we need to decode
1508  * the message stream with _dbus_auth_decode_data() after
1509  * receiving it from the peer.
1510  *
1511  * @param auth the auth conversation
1512  * @returns #TRUE if we need to encode the stream
1513  */
1514 dbus_bool_t
1515 _dbus_auth_needs_decoding (DBusAuth *auth)
1516 {
1517   if (!auth->authenticated)
1518     return FALSE;
1519     
1520   if (auth->mech != NULL)
1521     {
1522       if (DBUS_AUTH_IS_CLIENT (auth))
1523         return auth->mech->client_decode_func != NULL;
1524       else
1525         return auth->mech->server_decode_func != NULL;
1526     }
1527   else
1528     return FALSE;
1529 }
1530
1531
1532 /**
1533  * Called post-authentication, decodes a block of bytes received from
1534  * the peer. If no encoding was negotiated, just copies the bytes (you
1535  * can avoid this by checking _dbus_auth_needs_decoding()).
1536  *
1537  * @todo We need to be able to distinguish "out of memory" error
1538  * from "the data is hosed" error.
1539  *
1540  * @param auth the auth conversation
1541  * @param encoded the encoded data
1542  * @param plaintext initialized string where decoded data is appended
1543  * @returns #TRUE if we had enough memory and successfully decoded
1544  */
1545 dbus_bool_t
1546 _dbus_auth_decode_data (DBusAuth         *auth,
1547                         const DBusString *encoded,
1548                         DBusString       *plaintext)
1549 {
1550   _dbus_assert (plaintext != encoded);
1551   
1552   if (!auth->authenticated)
1553     return FALSE;
1554   
1555   if (_dbus_auth_needs_decoding (auth))
1556     {
1557       if (DBUS_AUTH_IS_CLIENT (auth))
1558         return (* auth->mech->client_decode_func) (auth, encoded, plaintext);
1559       else
1560         return (* auth->mech->server_decode_func) (auth, encoded, plaintext);
1561     }
1562   else
1563     {
1564       return _dbus_string_copy (encoded, 0, plaintext,
1565                                 _dbus_string_get_length (plaintext));
1566     }
1567 }
1568
1569 /**
1570  * Sets credentials received via reliable means from the operating
1571  * system.
1572  *
1573  * @param auth the auth conversation
1574  * @param credentials the credentials received
1575  */
1576 void
1577 _dbus_auth_set_credentials (DBusAuth               *auth,
1578                             const DBusCredentials  *credentials)
1579 {
1580   auth->credentials = *credentials;
1581 }
1582
1583 /**
1584  * Gets the identity we authorized the client as.  Apps may have
1585  * different policies as to what identities they allow.
1586  *
1587  * @param auth the auth conversation
1588  * @param credentials the credentials we've authorized
1589  */
1590 void
1591 _dbus_auth_get_identity (DBusAuth               *auth,
1592                          DBusCredentials        *credentials)
1593 {
1594   if (auth->authenticated)
1595     {
1596       *credentials = auth->authorized_identity;
1597     }
1598   else
1599     {
1600       credentials->pid = -1;
1601       credentials->uid = -1;
1602       credentials->gid = -1;
1603     }
1604 }
1605
1606 /** @} */
1607
1608 #ifdef DBUS_BUILD_TESTS
1609 #include "dbus-test.h"
1610 #include "dbus-auth-script.h"
1611 #include <stdio.h>
1612
1613 static dbus_bool_t
1614 process_test_subdir (const DBusString          *test_base_dir,
1615                      const char                *subdir)
1616 {
1617   DBusString test_directory;
1618   DBusString filename;
1619   DBusDirIter *dir;
1620   dbus_bool_t retval;
1621   DBusResultCode result;
1622
1623   retval = FALSE;
1624   dir = NULL;
1625   
1626   if (!_dbus_string_init (&test_directory, _DBUS_INT_MAX))
1627     _dbus_assert_not_reached ("didn't allocate test_directory\n");
1628
1629   _dbus_string_init_const (&filename, subdir);
1630   
1631   if (!_dbus_string_copy (test_base_dir, 0,
1632                           &test_directory, 0))
1633     _dbus_assert_not_reached ("couldn't copy test_base_dir to test_directory");
1634   
1635   if (!_dbus_concat_dir_and_file (&test_directory, &filename))    
1636     _dbus_assert_not_reached ("couldn't allocate full path");
1637
1638   _dbus_string_free (&filename);
1639   if (!_dbus_string_init (&filename, _DBUS_INT_MAX))
1640     _dbus_assert_not_reached ("didn't allocate filename string\n");
1641   
1642   dir = _dbus_directory_open (&test_directory, &result);
1643   if (dir == NULL)
1644     {
1645       const char *s;
1646       _dbus_string_get_const_data (&test_directory, &s);
1647       _dbus_warn ("Could not open %s: %s\n", s,
1648                   dbus_result_to_string (result));
1649       goto failed;
1650     }
1651
1652   printf ("Testing:\n");
1653   
1654   result = DBUS_RESULT_SUCCESS;
1655  next:
1656   while (_dbus_directory_get_next_file (dir, &filename, &result))
1657     {
1658       DBusString full_path;
1659       
1660       if (!_dbus_string_init (&full_path, _DBUS_INT_MAX))
1661         _dbus_assert_not_reached ("couldn't init string");
1662
1663       if (!_dbus_string_copy (&test_directory, 0, &full_path, 0))
1664         _dbus_assert_not_reached ("couldn't copy dir to full_path");
1665
1666       if (!_dbus_concat_dir_and_file (&full_path, &filename))
1667         _dbus_assert_not_reached ("couldn't concat file to dir");
1668
1669       if (!_dbus_string_ends_with_c_str (&filename, ".auth-script"))
1670         {
1671           const char *filename_c;
1672           _dbus_string_get_const_data (&filename, &filename_c);
1673           _dbus_verbose ("Skipping non-.auth-script file %s\n",
1674                          filename_c);
1675           goto next;
1676         }
1677
1678       {
1679         const char *s;
1680         _dbus_string_get_const_data (&filename, &s);
1681         printf ("    %s\n", s);
1682       }
1683       
1684       if (!_dbus_auth_script_run (&full_path))
1685         {
1686           _dbus_string_free (&full_path);
1687           goto failed;
1688         }
1689       else
1690         _dbus_string_free (&full_path);
1691     }
1692
1693   if (result != DBUS_RESULT_SUCCESS)
1694     {
1695       const char *s;
1696       _dbus_string_get_const_data (&test_directory, &s);
1697       _dbus_warn ("Could not get next file in %s: %s\n",
1698                   s, dbus_result_to_string (result));
1699       goto failed;
1700     }
1701     
1702   retval = TRUE;
1703   
1704  failed:
1705
1706   if (dir)
1707     _dbus_directory_close (dir);
1708   _dbus_string_free (&test_directory);
1709   _dbus_string_free (&filename);
1710
1711   return retval;
1712 }
1713
1714 static dbus_bool_t
1715 process_test_dirs (const char *test_data_dir)
1716 {
1717   DBusString test_directory;
1718   dbus_bool_t retval;
1719
1720   retval = FALSE;
1721   
1722   _dbus_string_init_const (&test_directory, test_data_dir);
1723
1724   if (!process_test_subdir (&test_directory, "auth"))
1725     goto failed;
1726
1727   retval = TRUE;
1728   
1729  failed:
1730
1731   _dbus_string_free (&test_directory);
1732   
1733   return retval;
1734 }
1735
1736 dbus_bool_t
1737 _dbus_auth_test (const char *test_data_dir)
1738 {
1739   
1740   if (test_data_dir == NULL)
1741     return TRUE;
1742   
1743   if (!process_test_dirs (test_data_dir))
1744     return FALSE;
1745
1746   return TRUE;
1747 }
1748
1749 #endif /* DBUS_BUILD_TESTS */