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