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