summaryrefslogtreecommitdiffstats
path: root/dbus/dbus-auth.c
blob: 566abaed11693be3ba9e2beb94deea2387638f85 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
/* -*- mode: C; c-file-style: "gnu" -*- */
/* dbus-auth.c Authentication
 *
 * Copyright (C) 2002  Red Hat Inc.
 *
 * Licensed under the Academic Free License version 1.2
 * 
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 */
#include "dbus-auth.h"
#include "dbus-string.h"
#include "dbus-list.h"
#include "dbus-internals.h"

/* See doc/dbus-sasl-profile.txt */

/**
 * @defgroup DBusAuth Authentication
 * @ingroup  DBusInternals
 * @brief DBusAuth object
 *
 * DBusAuth manages the authentication negotiation when a connection
 * is first established, and also manage any encryption used over a
 * connection.
 *
 * The file doc/dbus-sasl-profile.txt documents the network protocol
 * used for authentication.
 */

/**
 * @defgroup DBusAuthInternals Authentication implementation details
 * @ingroup  DBusInternals
 * @brief DBusAuth implementation details
 *
 * Private details of authentication code.
 *
 * @{
 */

/**
 * Processes a command. Returns whether we had enough memory to
 * complete the operation.
 */
typedef dbus_bool_t (* DBusProcessAuthCommandFunction) (DBusAuth         *auth,
                                                        const DBusString *command,
                                                        const DBusString *args);

typedef struct
{
  const char *command;
  DBusProcessAuthCommandFunction func;
} DBusAuthCommandHandler;

/**
 * This function processes a block of data received from the peer.
 * i.e. handles a DATA command.
 */
typedef dbus_bool_t (* DBusAuthDataFunction)     (DBusAuth         *auth,
                                                  const DBusString *data);

/**
 * This function encodes a block of data from the peer.
 */
typedef dbus_bool_t (* DBusAuthEncodeFunction)   (DBusAuth         *auth,
                                                  const DBusString *data,
                                                  DBusString       *encoded);

/**
 * This function decodes a block of data from the peer.
 */
typedef dbus_bool_t (* DBusAuthDecodeFunction)   (DBusAuth         *auth,
                                                  const DBusString *data,
                                                  DBusString       *decoded);

/**
 * This function is called when the mechanism is abandoned.
 */
typedef void        (* DBusAuthShutdownFunction) (DBusAuth       *auth);

typedef struct
{
  const char *mechanism;
  DBusAuthDataFunction server_data_func;
  DBusAuthEncodeFunction server_encode_func;
  DBusAuthDecodeFunction server_decode_func;
  DBusAuthShutdownFunction server_shutdown_func;
  DBusAuthDataFunction client_data_func;
  DBusAuthEncodeFunction client_encode_func;
  DBusAuthDecodeFunction client_decode_func;
  DBusAuthShutdownFunction client_shutdown_func;
} DBusAuthMechanismHandler;

/**
 * Internal members of DBusAuth.
 */
struct DBusAuth
{
  int refcount;           /**< reference count */

  DBusString incoming;    /**< Incoming data buffer */
  DBusString outgoing;    /**< Outgoing data buffer */
  
  const DBusAuthCommandHandler *handlers; /**< Handlers for commands */

  const DBusAuthMechanismHandler *mech;   /**< Current auth mechanism */
  
  unsigned int needed_memory : 1;   /**< We needed memory to continue since last
                                     * successful getting something done
                                     */
  unsigned int need_disconnect : 1; /**< We've given up, time to disconnect */
  unsigned int authenticated : 1;   /**< We are authenticated */
  unsigned int authenticated_pending_output : 1; /**< Authenticated once we clear outgoing buffer */
  unsigned int authenticated_pending_begin : 1;  /**< Authenticated once we get BEGIN */
  unsigned int already_got_mechanisms : 1;       /**< Client already got mech list */
};

typedef struct
{
  DBusAuth base;

  DBusList *mechs_to_try;
  
} DBusAuthClient;

typedef struct
{
  DBusAuth base;

} DBusAuthServer;

static dbus_bool_t process_auth         (DBusAuth         *auth,
                                         const DBusString *command,
                                         const DBusString *args);
static dbus_bool_t process_cancel       (DBusAuth         *auth,
                                         const DBusString *command,
                                         const DBusString *args);
static dbus_bool_t process_begin        (DBusAuth         *auth,
                                         const DBusString *command,
                                         const DBusString *args);
static dbus_bool_t process_data_server  (DBusAuth         *auth,
                                         const DBusString *command,
                                         const DBusString *args);
static dbus_bool_t process_error_server (DBusAuth         *auth,
                                         const DBusString *command,
                                         const DBusString *args);
static dbus_bool_t process_mechanisms   (DBusAuth         *auth,
                                         const DBusString *command,
                                         const DBusString *args);
static dbus_bool_t process_rejected     (DBusAuth         *auth,
                                         const DBusString *command,
                                         const DBusString *args);
static dbus_bool_t process_ok           (DBusAuth         *auth,
                                         const DBusString *command,
                                         const DBusString *args);
static dbus_bool_t process_data_client  (DBusAuth         *auth,
                                         const DBusString *command,
                                         const DBusString *args);
static dbus_bool_t process_error_client (DBusAuth         *auth,
                                         const DBusString *command,
                                         const DBusString *args);


static DBusAuthCommandHandler
server_handlers[] = {
  { "AUTH", process_auth },
  { "CANCEL", process_cancel },
  { "BEGIN", process_begin },
  { "DATA", process_data_server },
  { "ERROR", process_error_server },
  { NULL, NULL }
};                  

static DBusAuthCommandHandler
client_handlers[] = {
  { "MECHANISMS", process_mechanisms },
  { "REJECTED", process_rejected },
  { "OK", process_ok },
  { "DATA", process_data_client },
  { "ERROR", process_error_client },
  { NULL, NULL }
};

/**
 * @param auth the auth conversation
 * @returns #TRUE if the conversation is the server side
 */
#define DBUS_AUTH_IS_SERVER(auth) ((auth)->handlers == server_handlers)
/**
 * @param auth the auth conversation
 * @returns #TRUE if the conversation is the client side
 */
#define DBUS_AUTH_IS_CLIENT(auth) ((auth)->handlers == client_handlers)
/**
 * @param auth the auth conversation
 * @returns auth cast to DBusAuthClient
 */
#define DBUS_AUTH_CLIENT(auth)    ((DBusAuthClient*)(auth))
/**
 * @param auth the auth conversation
 * @returns auth cast to DBusAuthServer
 */
#define DBUS_AUTH_SERVER(auth)    ((DBusAuthServer*)(auth))

static DBusAuth*
_dbus_auth_new (int size)
{
  DBusAuth *auth;
  
  auth = dbus_malloc0 (size);
  if (auth == NULL)
    return NULL;
  
  auth->refcount = 1;

  /* note that we don't use the max string length feature,
   * because you can't use that feature if you're going to
   * try to recover from out-of-memory (it creates
   * what looks like unrecoverable inability to alloc
   * more space in the string). But we do handle
   * overlong buffers in _dbus_auth_do_work().
   */
  
  if (!_dbus_string_init (&auth->incoming, _DBUS_INT_MAX))
    {
      dbus_free (auth);
      return NULL;
    }

  if (!_dbus_string_init (&auth->outgoing, _DBUS_INT_MAX))
    {
      _dbus_string_free (&auth->outgoing);
      dbus_free (auth);
      return NULL;
    }
  
  return auth;
}

static DBusAuthState
get_state (DBusAuth *auth)
{
  if (auth->need_disconnect)
    return DBUS_AUTH_STATE_NEED_DISCONNECT;
  else if (auth->authenticated)
    {
      if (_dbus_string_get_length (&auth->incoming) > 0)
        return DBUS_AUTH_STATE_AUTHENTICATED_WITH_UNUSED_BYTES;
      else
        return DBUS_AUTH_STATE_AUTHENTICATED;
    }
  else if (auth->needed_memory)
    return DBUS_AUTH_STATE_WAITING_FOR_MEMORY;
  else if (_dbus_string_get_length (&auth->outgoing) > 0)
    return DBUS_AUTH_STATE_HAVE_BYTES_TO_SEND;
  else
    return DBUS_AUTH_STATE_WAITING_FOR_INPUT;
}

static void
shutdown_mech (DBusAuth *auth)
{
  /* Cancel any auth */
  auth->authenticated_pending_begin = FALSE;
  auth->authenticated = FALSE;
  
  if (auth->mech != NULL)
    {
      _dbus_verbose ("Shutting down mechanism %s\n",
                     auth->mech->mechanism);
      
      if (DBUS_AUTH_IS_CLIENT (auth))
        (* auth->mech->client_shutdown_func) (auth);
      else
        (* auth->mech->server_shutdown_func) (auth);
      
      auth->mech = NULL;
    }
}

static dbus_bool_t
handle_server_data_stupid_test_mech (DBusAuth         *auth,
                                     const DBusString *data)
{
  if (!_dbus_string_append (&auth->outgoing,
                            "OK\r\n"))
    return FALSE;

  auth->authenticated_pending_begin = TRUE;
  
  return TRUE;
}

static void
handle_server_shutdown_stupid_test_mech (DBusAuth *auth)
{

}

static dbus_bool_t
handle_client_data_stupid_test_mech (DBusAuth         *auth,
                                     const DBusString *data)
{
  
  return TRUE;
}

static void
handle_client_shutdown_stupid_test_mech (DBusAuth *auth)
{

}

/* the stupid test mech is a base64-encoded string;
 * all the inefficiency, none of the security!
 */
static dbus_bool_t
handle_encode_stupid_test_mech (DBusAuth         *auth,
                                const DBusString *plaintext,
                                DBusString       *encoded)
{
  if (!_dbus_string_base64_encode (plaintext, 0, encoded, 0))
    return FALSE;
  
  return TRUE;
}

static dbus_bool_t
handle_decode_stupid_test_mech (DBusAuth         *auth,
                                const DBusString *encoded,
                                DBusString       *plaintext)
{
  if (!_dbus_string_base64_decode (encoded, 0, plaintext, 0))
    return FALSE;
  
  return TRUE;
}

/* Put mechanisms here in order of preference.
 * What I eventually want to have is:
 *
 *  - a mechanism that checks UNIX domain socket credentials
 *  - a simple magic cookie mechanism like X11 or ICE
 *  - mechanisms that chain to Cyrus SASL, so we can use anything it
 *    offers such as Kerberos, X509, whatever.
 * 
 */
static const DBusAuthMechanismHandler
all_mechanisms[] = {
  { "DBUS_STUPID_TEST_MECH",
    handle_server_data_stupid_test_mech,
    handle_encode_stupid_test_mech,
    handle_decode_stupid_test_mech,
    handle_server_shutdown_stupid_test_mech,
    handle_client_data_stupid_test_mech,
    handle_encode_stupid_test_mech,
    handle_decode_stupid_test_mech,
    handle_client_shutdown_stupid_test_mech },
  { NULL, NULL }
};

static const DBusAuthMechanismHandler*
find_mech (const DBusString *name)
{
  int i;
  
  i = 0;
  while (all_mechanisms[i].mechanism != NULL)
    {
      if (_dbus_string_equal_c_str (name,
                                    all_mechanisms[i].mechanism))

        return &all_mechanisms[i];
      
      ++i;
    }
  
  return NULL;
}

static dbus_bool_t
send_mechanisms (DBusAuth *auth)
{
  DBusString command;
  int i;
  
  if (!_dbus_string_init (&command, _DBUS_INT_MAX))
    return FALSE;
  
  if (!_dbus_string_append (&command,
                            "MECHANISMS"))
    goto nomem;

  i = 0;
  while (all_mechanisms[i].mechanism != NULL)
    {
      if (!_dbus_string_append (&command,
                                " "))
        goto nomem;

      if (!_dbus_string_append (&command,
                                all_mechanisms[i].mechanism))
        goto nomem;
      
      ++i;
    }
  
  if (!_dbus_string_append (&command, "\r\n"))
    goto nomem;

  if (!_dbus_string_copy (&command, 0, &auth->outgoing,
                          _dbus_string_get_length (&auth->outgoing)))
    goto nomem;
  
  return TRUE;

 nomem:
  _dbus_string_free (&command);
  return FALSE;
}

static dbus_bool_t
process_auth (DBusAuth         *auth,
              const DBusString *command,
              const DBusString *args)
{
  if (auth->mech)
    {
      /* We are already using a mechanism, client is on crack */
      if (!_dbus_string_append (&auth->outgoing,
                                "ERROR \"Sent AUTH while another AUTH in progress\"\r\n"))
        return FALSE;

      return TRUE;
    }
  else if (_dbus_string_get_length (args) == 0)
    {
      /* No args to the auth, send mechanisms */
      if (!send_mechanisms (auth))
        return FALSE;

      return TRUE;
    }
  else
    {
      int i;
      DBusString mech;
      DBusString base64_response;
      DBusString decoded_response;
      
      _dbus_string_find_blank (args, 0, &i);

      if (!_dbus_string_init (&mech, _DBUS_INT_MAX))
        return FALSE;

      if (!_dbus_string_init (&base64_response, _DBUS_INT_MAX))
        {
          _dbus_string_free (&mech);
          return FALSE;
        }

      if (!_dbus_string_init (&decoded_response, _DBUS_INT_MAX))
        {
          _dbus_string_free (&mech);
          _dbus_string_free (&base64_response);
          return FALSE;
        }
      
      if (!_dbus_string_copy_len (args, 0, i, &mech, 0))
        goto failed;

      if (!_dbus_string_copy (args, i, &base64_response, 0))
        goto failed;

      if (!_dbus_string_base64_decode (&base64_response, 0,
                                       &decoded_response, 0))
        goto failed;

      auth->mech = find_mech (&mech);
      if (auth->mech != NULL)
        {
          _dbus_verbose ("Trying mechanism %s\n",
                         auth->mech->mechanism);
          
          if (!(* auth->mech->server_data_func) (auth,
                                                 &decoded_response))
            goto failed;
        }
      else
        {
          /* Unsupported mechanism */
          if (!send_mechanisms (auth))
            return FALSE;
        }
      
      return TRUE;
      
    failed:
      auth->mech = NULL;
      _dbus_string_free (&mech);
      _dbus_string_free (&base64_response);
      _dbus_string_free (&decoded_response);
      return FALSE;
    }
}

static dbus_bool_t
process_cancel (DBusAuth         *auth,
                const DBusString *command,
                const DBusString *args)
{
  shutdown_mech (auth);
  
  return TRUE;
}

static dbus_bool_t
process_begin (DBusAuth         *auth,
               const DBusString *command,
               const DBusString *args)
{
  if (auth->authenticated_pending_begin)
    auth->authenticated = TRUE;
  else
    {
      auth->need_disconnect = TRUE; /* client trying to send data before auth,
                                     * kick it
                                     */
      shutdown_mech (auth);
    }
  
  return TRUE;
}

static dbus_bool_t
process_data_server (DBusAuth         *auth,
                     const DBusString *command,
                     const DBusString *args)
{
  if (auth->mech != NULL)
    {
      DBusString decoded;

      if (!_dbus_string_init (&decoded, _DBUS_INT_MAX))
        return FALSE;

      if (!_dbus_string_base64_decode (args, 0, &decoded, 0))
        {
          _dbus_string_free (&decoded);
          return FALSE;
        }
      
      if (!(* auth->mech->server_data_func) (auth, &decoded))
        {
          _dbus_string_free (&decoded);
          return FALSE;
        }

      _dbus_string_free (&decoded);
    }
  else
    {
      if (!_dbus_string_append (&auth->outgoing,
                                "ERROR \"Not currently in an auth conversation\"\r\n"))
        return FALSE;
    }
  
  return TRUE;
}

static dbus_bool_t
process_error_server (DBusAuth         *auth,
                      const DBusString *command,
                      const DBusString *args)
{
  
  return TRUE;
}

/* return FALSE if no memory, TRUE if all OK */
static dbus_bool_t
get_word (const DBusString *str,
          int              *start,
          DBusString       *word)
{
  int i;

  _dbus_string_skip_blank (str, *start, start);
  _dbus_string_find_blank (str, *start, &i);
  
  if (i > *start)
    {
      if (!_dbus_string_copy_len (str, *start, i, word, 0))
        return FALSE;
      
      *start = i;
    }

  return TRUE;
}

static dbus_bool_t
process_mechanisms (DBusAuth         *auth,
                    const DBusString *command,
                    const DBusString *args)
{
  int next;
  int len;

  if (auth->already_got_mechanisms)
    return TRUE;
  
  len = _dbus_string_get_length (args);
  
  next = 0;
  while (next < len)
    {
      DBusString m;
      const DBusAuthMechanismHandler *mech;
      
      if (!_dbus_string_init (&m, _DBUS_INT_MAX))
        goto nomem;
      
      if (!get_word (args, &next, &m))
        goto nomem;

      mech = find_mech (&m);

      if (mech != NULL)
        {
          /* FIXME right now we try mechanisms in the order
           * the server lists them; should we do them in
           * some more deterministic order?
           *
           * Probably in all_mechanisms order, our order of
           * preference. Of course when the server is us,
           * it lists things in that order anyhow.
           */

          _dbus_verbose ("Adding mechanism %s to list we will try\n",
                         mech->mechanism);
          
          if (!_dbus_list_append (& DBUS_AUTH_CLIENT (auth)->mechs_to_try,
                                  (void*) mech))
            goto nomem;
        }
      else
        {
          const char *s;

          _dbus_string_get_const_data (&m, &s);
          _dbus_verbose ("Server offered mechanism \"%s\" that we don't know how to use\n",
                         s);
        }

      _dbus_string_free (&m);
    }
  
  auth->already_got_mechanisms = TRUE;
  
  return TRUE;

 nomem:
  _dbus_list_clear (& DBUS_AUTH_CLIENT (auth)->mechs_to_try);
  
  return FALSE;
}

static dbus_bool_t
process_rejected (DBusAuth         *auth,
                  const DBusString *command,
                  const DBusString *args)
{
  shutdown_mech (auth);
  
  if (!auth->already_got_mechanisms)
    {
      /* Ask for mechanisms */
      if (!_dbus_string_append (&auth->outgoing,
                                "AUTH\r\n"))
        return FALSE;
    }
  else if (DBUS_AUTH_CLIENT (auth)->mechs_to_try != NULL)
    {
      /* Try next mechanism */
      const DBusAuthMechanismHandler *mech;
      DBusString auth_command;

      mech = DBUS_AUTH_CLIENT (auth)->mechs_to_try->data;

      if (!_dbus_string_init (&auth_command, _DBUS_INT_MAX))
        return FALSE;
      
      if (!_dbus_string_append (&auth_command,
                                "AUTH "))
        {
          _dbus_string_free (&auth_command);
          return FALSE;
        }

      if (!_dbus_string_append (&auth->outgoing,
                                mech->mechanism))
        {
          _dbus_string_free (&auth_command);
          return FALSE;
        }
        
      if (!_dbus_string_append (&auth->outgoing,
                                "\r\n"))
        {
          _dbus_string_free (&auth_command);
          return FALSE;
        }

      if (!_dbus_string_copy (&auth_command, 0,
                              &auth->outgoing,
                              _dbus_string_get_length (&auth->outgoing)))
        {
          _dbus_string_free (&auth_command);
          return FALSE;
        }

      auth->mech = mech;      
      _dbus_list_pop_first (& DBUS_AUTH_CLIENT (auth)->mechs_to_try);

      _dbus_verbose ("Trying mechanism %s\n",
                     auth->mech->mechanism);
    }
  else
    {
      /* Give up */
      auth->need_disconnect = TRUE;
    }
  
  return TRUE;
}

static dbus_bool_t
process_ok (DBusAuth         *auth,
            const DBusString *command,
            const DBusString *args)
{
  if (!_dbus_string_append (&auth->outgoing,
                            "BEGIN\r\n"))
    return FALSE;
  
  auth->authenticated_pending_output = TRUE;
  
  return TRUE;
}


static dbus_bool_t
process_data_client (DBusAuth         *auth,
                     const DBusString *command,
                     const DBusString *args)
{
  if (auth->mech != NULL)
    {
      DBusString decoded;

      if (!_dbus_string_init (&decoded, _DBUS_INT_MAX))
        return FALSE;

      if (!_dbus_string_base64_decode (args, 0, &decoded, 0))
        {
          _dbus_string_free (&decoded);
          return FALSE;
        }
      
      if (!(* auth->mech->client_data_func) (auth, &decoded))
        {
          _dbus_string_free (&decoded);
          return FALSE;
        }

      _dbus_string_free (&decoded);
    }
  else
    {
      if (!_dbus_string_append (&auth->outgoing,
                                "ERROR \"Got DATA when not in an auth exchange\"\r\n"))
        return FALSE;
    }
  
  return TRUE;
}

static dbus_bool_t
process_error_client (DBusAuth         *auth,
                      const DBusString *command,
                      const DBusString *args)
{
  return TRUE;
}

static dbus_bool_t
process_unknown (DBusAuth         *auth,
                 const DBusString *command,
                 const DBusString *args)
{
  if (!_dbus_string_append (&auth->outgoing,
                            "ERROR \"Unknown command\"\r\n"))
    return FALSE;

  return TRUE;
}

/* returns whether to call it again right away */
static dbus_bool_t
process_command (DBusAuth *auth)
{
  DBusString command;
  DBusString args;
  int eol;
  int i, j;
  dbus_bool_t retval;

  retval = FALSE;
  
  eol = 0;
  if (!_dbus_string_find (&auth->incoming, 0, "\r\n", &eol))
    return FALSE;
  
  if (!_dbus_string_init (&command, _DBUS_INT_MAX))
    {
      auth->needed_memory = TRUE;
      return FALSE;
    }

  if (!_dbus_string_init (&args, _DBUS_INT_MAX))
    {
      auth->needed_memory = TRUE;
      return FALSE;
    }
  
  if (eol > _DBUS_ONE_MEGABYTE)
    {
      /* This is a giant line, someone is trying to hose us. */
      if (!_dbus_string_append (&auth->outgoing, "ERROR \"Command too long\"\r\n"))
        goto out;
      else
        goto next_command;
    }

  if (!_dbus_string_copy_len (&auth->incoming, 0, eol, &command, 0))
    goto out;

  if (!_dbus_string_validate_ascii (&command, 0,
                                    _dbus_string_get_length (&command)))
    {
      _dbus_verbose ("Command contained non-ASCII chars or embedded nul\n");
      if (!_dbus_string_append (&auth->outgoing, "ERROR \"Command contained non-ASCII\"\r\n"))
        goto out;
      else
        goto next_command;
    }
  
  {
    const char *q;
    _dbus_string_get_const_data (&command, &q);
    _dbus_verbose ("got command \"%s\"\n", q);
  }
  
  _dbus_string_find_blank (&command, 0, &i);
  _dbus_string_skip_blank (&command, i, &j);

  if (j > i)
    _dbus_string_delete (&command, i, j - i);
  
  if (!_dbus_string_move (&command, i, &args, 0))
    goto out;
  
  i = 0;
  while (auth->handlers[i].command != NULL)
    {
      if (_dbus_string_equal_c_str (&command,
                                    auth->handlers[i].command))
        {
          _dbus_verbose ("Processing auth command %s\n",
                         auth->handlers[i].command);
          
          if (!(* auth->handlers[i].func) (auth, &command, &args))
            goto out;

          break;
        }
      ++i;
    }

  if (auth->handlers[i].command == NULL)
    {
      if (!process_unknown (auth, &command, &args))
        goto out;
    }

 next_command:
  
  /* We've succeeded in processing the whole command so drop it out
   * of the incoming buffer and return TRUE to try another command.
   */

  _dbus_string_delete (&auth->incoming, 0, eol);
  
  /* kill the \r\n */
  _dbus_string_delete (&auth->incoming, 0, 2);

  retval = TRUE;
  
 out:
  _dbus_string_free (&args);
  _dbus_string_free (&command);

  if (!retval)
    auth->needed_memory = TRUE;
  else
    auth->needed_memory = FALSE;
  
  return retval;
}


/** @} */

/**
 * @addtogroup DBusAuth
 * @{
 */

/**
 * Creates a new auth conversation object for the server side.
 * See doc/dbus-sasl-profile.txt for full details on what
 * this object does.
 *
 * @returns the new object or #NULL if no memory
 */
DBusAuth*
_dbus_auth_server_new (void)
{
  DBusAuth *auth;

  auth = _dbus_auth_new (sizeof (DBusAuthServer));
  if (auth == NULL)
    return NULL;

  auth->handlers = server_handlers;
  
  return auth;
}

/**
 * Creates a new auth conversation object for the client side.
 * See doc/dbus-sasl-profile.txt for full details on what
 * this object does.
 *
 * @returns the new object or #NULL if no memory
 */
DBusAuth*
_dbus_auth_client_new (void)
{
  DBusAuth *auth;

  auth = _dbus_auth_new (sizeof (DBusAuthClient));
  if (auth == NULL)
    return NULL;

  auth->handlers = client_handlers;

  /* Request an auth */
  if (!_dbus_string_append (&auth->outgoing,
                            "AUTH DBUS_STUPID_TEST_MECH\r\n"))
    {
      _dbus_auth_unref (auth);
      return NULL;
    }
  
  return auth;
}

/**
 * Increments the refcount of an auth object.
 *
 * @param auth the auth conversation
 */
void
_dbus_auth_ref (DBusAuth *auth)
{
  _dbus_assert (auth != NULL);
  
  auth->refcount += 1;
}

/**
 * Decrements the refcount of an auth object.
 *
 * @param auth the auth conversation
 */
void
_dbus_auth_unref (DBusAuth *auth)
{
  _dbus_assert (auth != NULL);
  _dbus_assert (auth->refcount > 0);

  auth->refcount -= 1;
  if (auth->refcount == 0)
    {
      shutdown_mech (auth);

      if (DBUS_AUTH_IS_CLIENT (auth))
        {
          _dbus_list_clear (& DBUS_AUTH_CLIENT (auth)->mechs_to_try);
        }
      
      _dbus_string_free (&auth->incoming);
      _dbus_string_free (&auth->outgoing);
      dbus_free (auth);
    }
}

/**
 * @param auth the auth conversation object
 * @returns #TRUE if we're in a final state
 */
#define DBUS_AUTH_IN_END_STATE(auth) ((auth)->need_disconnect || (auth)->authenticated)

/**
 * Analyzes buffered input and moves the auth conversation forward,
 * returning the new state of the auth conversation.
 *
 * @param auth the auth conversation
 * @returns the new state
 */
DBusAuthState
_dbus_auth_do_work (DBusAuth *auth)
{  
  if (DBUS_AUTH_IN_END_STATE (auth))
    return get_state (auth);

  auth->needed_memory = FALSE;

  /* Max amount we'll buffer up before deciding someone's on crack */
#define MAX_BUFFER (16 * 1024)

  do
    {
      if (_dbus_string_get_length (&auth->incoming) > MAX_BUFFER ||
          _dbus_string_get_length (&auth->outgoing) > MAX_BUFFER)
        {
          auth->need_disconnect = TRUE;
          _dbus_verbose ("Disconnecting due to excessive data buffered in auth phase\n");
          break;
        }

      if (auth->mech == NULL &&
          auth->already_got_mechanisms &&
          DBUS_AUTH_CLIENT (auth)->mechs_to_try == NULL)
        {
          auth->need_disconnect = TRUE;
          _dbus_verbose ("Disconnecting because we are out of mechanisms to try using\n");
          break;
        }
    }
  while (process_command (auth));
  
  return get_state (auth);
}

/**
 * Gets bytes that need to be sent to the peer we're conversing with.
 * After writing some bytes, _dbus_auth_bytes_sent() must be called
 * to notify the auth object that they were written.
 *
 * @param auth the auth conversation
 * @param str return location for a ref to the buffer to send
 * @returns #FALSE if nothing to send
 */
dbus_bool_t
_dbus_auth_get_bytes_to_send (DBusAuth          *auth,
                              const DBusString **str)
{
  _dbus_assert (auth != NULL);
  _dbus_assert (str != NULL);

  *str = NULL;
  
  if (DBUS_AUTH_IN_END_STATE (auth))
    return FALSE;

  if (_dbus_string_get_length (&auth->outgoing) == 0)
    return FALSE;

  *str = &auth->outgoing;

  return TRUE;
}

/**
 * Notifies the auth conversation object that
 * the given number of bytes of the outgoing buffer
 * have been written out.
 *
 * @param auth the auth conversation
 * @param bytes_sent number of bytes written out
 */
void
_dbus_auth_bytes_sent (DBusAuth *auth,
                       int       bytes_sent)
{
  _dbus_string_delete (&auth->outgoing,
                       0, bytes_sent);
  
  if (auth->authenticated_pending_output &&
      _dbus_string_get_length (&auth->outgoing) == 0)
    auth->authenticated = TRUE;
}

/**
 * Stores bytes received from the peer we're conversing with.
 *
 * @param auth the auth conversation
 * @param str the received bytes.
 * @returns #FALSE if not enough memory to store the bytes.
 */
dbus_bool_t
_dbus_auth_bytes_received (DBusAuth   *auth,
                           const DBusString *str)
{
  _dbus_assert (auth != NULL);
  _dbus_assert (str != NULL);
  
  if (DBUS_AUTH_IN_END_STATE (auth))
    return FALSE;

  auth->needed_memory = FALSE;
  
  if (!_dbus_string_copy (str, 0,
                          &auth->incoming,
                          _dbus_string_get_length (&auth->incoming)))
    {
      auth->needed_memory = TRUE;
      return FALSE;
    }

  _dbus_auth_do_work (auth);
  
  return TRUE;
}

/**
 * Returns leftover bytes that were not used as part of the auth
 * conversation.  These bytes will be part of the message stream
 * instead. This function may not be called until authentication has
 * succeeded.
 *
 * @param auth the auth conversation
 * @param str string to append the unused bytes to
 * @returns #FALSE if not enough memory to return the bytes
 */
dbus_bool_t
_dbus_auth_get_unused_bytes (DBusAuth   *auth,
                             DBusString *str)
{
  if (!DBUS_AUTH_IN_END_STATE (auth))
    return FALSE;
  
  if (!_dbus_string_move (&auth->incoming,
                          0, str,
                          _dbus_string_get_length (str)))
    return FALSE;

  return TRUE;
}

/**
 * Called post-authentication, indicates whether we need to encode
 * the message stream with _dbus_auth_encode_data() prior to
 * sending it to the peer.
 *
 * @param auth the auth conversation
 * @returns #TRUE if we need to encode the stream
 */
dbus_bool_t
_dbus_auth_needs_encoding (DBusAuth *auth)
{
  if (!auth->authenticated)
    return FALSE;
  
  if (auth->mech != NULL)
    {
      if (DBUS_AUTH_IS_CLIENT (auth))
        return auth->mech->client_encode_func != NULL;
      else
        return auth->mech->server_encode_func != NULL;
    }
  else
    return FALSE;
}

/**
 * Called post-authentication, encodes a block of bytes for sending to
 * the peer. If no encoding was negotiated, just copies the bytes
 * (you can avoid this by checking _dbus_auth_needs_encoding()).
 *
 * @param auth the auth conversation
 * @param plaintext the plain text data
 * @param encoded initialized string to fill in with encoded data
 * @returns #TRUE if we had enough memory and successfully encoded
 */
dbus_bool_t
_dbus_auth_encode_data (DBusAuth         *auth,
                        const DBusString *plaintext,
                        DBusString       *encoded)
{
  if (!auth->authenticated)
    return FALSE;
  
  if (_dbus_auth_needs_encoding (auth))
    {
      if (DBUS_AUTH_IS_CLIENT (auth))
        return (* auth->mech->client_encode_func) (auth, plaintext, encoded);
      else
        return (* auth->mech->server_encode_func) (auth, plaintext, encoded);
    }
  else
    {
      return _dbus_string_copy (plaintext, 0, encoded, 0);
    }
}

/**
 * Called post-authentication, indicates whether we need to decode
 * the message stream with _dbus_auth_decode_data() after
 * receiving it from the peer.
 *
 * @param auth the auth conversation
 * @returns #TRUE if we need to encode the stream
 */
dbus_bool_t
_dbus_auth_needs_decoding (DBusAuth *auth)
{
  if (!auth->authenticated)
    return FALSE;
    
  if (auth->mech != NULL)
    {
      if (DBUS_AUTH_IS_CLIENT (auth))
        return auth->mech->client_decode_func != NULL;
      else
        return auth->mech->server_decode_func != NULL;
    }
  else
    return FALSE;
}


/**
 * Called post-authentication, decodes a block of bytes received from
 * the peer. If no encoding was negotiated, just copies the bytes (you
 * can avoid this by checking _dbus_auth_needs_decoding()).
 *
 * @param auth the auth conversation
 * @param encoded the encoded data
 * @param plaintext initialized string to fill in with decoded data
 * @returns #TRUE if we had enough memory and successfully decoded
 */
dbus_bool_t
_dbus_auth_decode_data (DBusAuth         *auth,
                        const DBusString *encoded,
                        DBusString       *plaintext)
{
  if (!auth->authenticated)
    return FALSE;
  
  if (_dbus_auth_needs_decoding (auth))
    {
      if (DBUS_AUTH_IS_CLIENT (auth))
        return (* auth->mech->client_decode_func) (auth, encoded, plaintext);
      else
        return (* auth->mech->server_decode_func) (auth, encoded, plaintext);
    }
  else
    {
      return _dbus_string_copy (encoded, 0, plaintext, 0);
    }
}

/** @} */