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