aboutsummaryrefslogtreecommitdiffstats
path: root/packet-ldap.c
blob: 9510a08248e794291400bdbfe62a8676e23f3034 (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
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
/* packet-ldap.c
 * Routines for ldap packet dissection
 *
 * $Id: packet-ldap.c,v 1.41 2002/03/31 22:17:37 guy Exp $
 *
 * Ethereal - Network traffic analyzer
 * By Gerald Combs <gerald@ethereal.com>
 * Copyright 1998 Gerald Combs
 *
 * 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.
 */

/*
 * This is not a complete implementation. It doesn't handle the full version 3, more specifically,
 * it handles only the commands of version 2, but any additional characteristics of the ver3 command are supported.
 * It's also missing extensible search filters.
 * 
 * There should probably be alot more error checking, I simply assume that if we have a full packet, it will be a complete
 * and correct packet.
 * 
 * AFAIK, it will handle all messages used by the OpenLDAP 1.2.9 server and libraries which was my goal. I do plan to add
 * the remaining commands as time permits but this is not a priority to me. Send me an email if you need it and I'll see what
 * I can do.
 * 
 * Doug Nazar
 * nazard@dragoninc.on.ca
 */

#ifdef HAVE_CONFIG_H
# include "config.h"
#endif

#include <stdio.h>

#ifdef HAVE_SYS_TYPES_H
# include <sys/types.h>
#endif

#ifdef HAVE_NETINET_IN_H
# include <netinet/in.h>
#endif

#include <string.h>
#include <glib.h>

#ifdef NEED_SNPRINTF_H
# include "snprintf.h"
#endif

#include <epan/packet.h>

#include "packet-ldap.h"
#include "asn1.h"
#include "prefs.h"

static int proto_ldap = -1;
static int hf_ldap_length = -1;
static int hf_ldap_message_id = -1;
static int hf_ldap_message_type = -1;
static int hf_ldap_message_length = -1;

static int hf_ldap_message_result = -1;
static int hf_ldap_message_result_matcheddn = -1;
static int hf_ldap_message_result_errormsg = -1;
static int hf_ldap_message_result_referral = -1;

static int hf_ldap_message_bind_version = -1;
static int hf_ldap_message_bind_dn = -1;
static int hf_ldap_message_bind_auth = -1;
static int hf_ldap_message_bind_auth_password = -1;

static int hf_ldap_message_search_base = -1;
static int hf_ldap_message_search_scope = -1;
static int hf_ldap_message_search_deref = -1;
static int hf_ldap_message_search_sizeLimit = -1;
static int hf_ldap_message_search_timeLimit = -1;
static int hf_ldap_message_search_typesOnly = -1;
static int hf_ldap_message_search_filter = -1;

static int hf_ldap_message_dn = -1;
static int hf_ldap_message_attribute = -1;
static int hf_ldap_message_value = -1;

static int hf_ldap_message_modrdn_name = -1;
static int hf_ldap_message_modrdn_delete = -1;
static int hf_ldap_message_modrdn_superior = -1;

static int hf_ldap_message_compare = -1;

static int hf_ldap_message_modify_add = -1;
static int hf_ldap_message_modify_replace = -1;
static int hf_ldap_message_modify_delete = -1;

static int hf_ldap_message_abandon_msgid = -1;

static gint ett_ldap = -1;
static gint ett_ldap_message = -1;
static gint ett_ldap_referrals = -1;
static gint ett_ldap_attribute = -1;

/* desegmentation of LDAP */
static gboolean ldap_desegment = TRUE;

#define TCP_PORT_LDAP			389

static value_string msgTypes [] = {
  {LDAP_REQ_BIND, "Bind Request"},
  {LDAP_REQ_UNBIND, "Unbind Request"},
  {LDAP_REQ_SEARCH, "Search Request"},
  {LDAP_REQ_MODIFY, "Modify Request"},
  {LDAP_REQ_ADD, "Add Request"},
  {LDAP_REQ_DELETE, "Delete Request"},
  {LDAP_REQ_MODRDN, "Modify RDN Request"},
  {LDAP_REQ_COMPARE, "Compare Request"},
  {LDAP_REQ_ABANDON, "Abandon Request"},
  {LDAP_REQ_EXTENDED, "Extended Request"},
    
  {LDAP_RES_BIND, "Bind Result"},
  {LDAP_RES_SEARCH_ENTRY, "Search Entry"},
  {LDAP_RES_SEARCH_RESULT, "Search Result"},
  {LDAP_RES_SEARCH_REF, "Search Result Reference"},
  {LDAP_RES_MODIFY, "Modify Result"},
  {LDAP_RES_ADD, "Add Result"},
  {LDAP_RES_DELETE, "Delete Result"},
  {LDAP_RES_MODRDN, "Modify RDN Result"},
  {LDAP_RES_COMPARE, "Compare Result"},
  {LDAP_REQ_EXTENDED, "Extended Response"},
  {0, NULL},
};

static int read_length(ASN1_SCK *a, proto_tree *tree, int hf_id, guint *len)
{
  guint length = 0;
  gboolean def = FALSE;
  int start = a->offset;
  int ret;
  
  ret = asn1_length_decode(a, &def, &length);
  if (ret != ASN1_ERR_NOERROR) {
    if (tree) {
      proto_tree_add_text(tree, a->tvb, start, 0,
        "%s: ERROR: Couldn't parse length: %s",
        proto_registrar_get_name(hf_id), asn1_err_to_str(ret));
    }
    return ret;
  }

  if (len)
    *len = length;

  if (tree)
    proto_tree_add_uint(tree, hf_id, a->tvb, start, a->offset-start, length);

  return ASN1_ERR_NOERROR;
}

static int read_sequence(ASN1_SCK *a, guint *len)
{
  guint cls, con, tag;
  gboolean def;
  guint length;
  int ret;
  
  ret = asn1_header_decode(a, &cls, &con, &tag, &def, &length);
  if (ret != ASN1_ERR_NOERROR)
    return ret;
  if (cls != ASN1_UNI || con != ASN1_CON || tag != ASN1_SEQ)
    return ASN1_ERR_WRONG_TYPE;

  if (len)
    *len = length;
  
  return ASN1_ERR_NOERROR;
}

static int read_set(ASN1_SCK *a, guint *len)
{
  guint cls, con, tag;
  gboolean def;
  guint length;
  int ret;
  
  ret = asn1_header_decode(a, &cls, &con, &tag, &def, &length);
  if (ret != ASN1_ERR_NOERROR)
    return ret;
  if (cls != ASN1_UNI || con != ASN1_CON || tag != ASN1_SET)
    return ASN1_ERR_WRONG_TYPE;
  
  if (len)
    *len = length;
  
  return ASN1_ERR_NOERROR;
}

static int read_integer_value(ASN1_SCK *a, proto_tree *tree, int hf_id,
	proto_item **new_item, guint *i, int start, guint length)
{
  guint integer = 0;
  proto_item *temp_item = NULL;
  int ret;

  ret = asn1_uint32_value_decode(a, length, &integer);
  if (ret != ASN1_ERR_NOERROR) {
    if (tree) {
      proto_tree_add_text(tree, a->tvb, start, 0,
       "%s: ERROR: Couldn't parse value: %s",
        proto_registrar_get_name(hf_id), asn1_err_to_str(ret));
    }
    return ret;
  }

  if (i)
    *i = integer;

  if (tree)
    temp_item = proto_tree_add_uint(tree, hf_id, a->tvb, start, a->offset-start, integer);

  if (new_item)
    *new_item = temp_item;

  return ASN1_ERR_NOERROR;
}

static int read_integer(ASN1_SCK *a, proto_tree *tree, int hf_id,
	proto_item **new_item, guint *i, guint expected_tag)
{
  guint cls, con, tag;
  gboolean def;
  guint length;
  int start = a->offset;
  int ret;
  
  ret = asn1_header_decode(a, &cls, &con, &tag, &def, &length);
  if (ret == ASN1_ERR_NOERROR) {
    if (cls != ASN1_UNI || con != ASN1_PRI || tag != expected_tag)
      ret = ASN1_ERR_WRONG_TYPE;
  }
  if (ret != ASN1_ERR_NOERROR) {
    if (tree) {
      proto_tree_add_text(tree, a->tvb, start, 0,
        "%s: ERROR: Couldn't parse header: %s",
        (hf_id != -1) ? proto_registrar_get_name(hf_id) : "LDAP message",
        asn1_err_to_str(ret));
    }
    return ret;
  }

  return read_integer_value(a, tree, hf_id, new_item, i, start, length);
}

static int read_boolean_value(ASN1_SCK *a, proto_tree *tree, int hf_id,
	proto_item **new_item, guint *i, int start, guint length)
{
  guint integer = 0;
  proto_item *temp_item = NULL;
  int ret;

  ret = asn1_uint32_value_decode(a, length, &integer);
  if (ret != ASN1_ERR_NOERROR) {
    if (tree) {
      proto_tree_add_text(tree, a->tvb, start, 0,
        "%s: ERROR: Couldn't parse value: %s",
        proto_registrar_get_name(hf_id), asn1_err_to_str(ret));
    }
    return ret;
  }

  if (i)
    *i = integer;

  if (tree)
    temp_item = proto_tree_add_boolean(tree, hf_id, a->tvb, start, a->offset-start, integer);
  if (new_item)
    *new_item = temp_item;

  return ASN1_ERR_NOERROR;
}

static int read_boolean(ASN1_SCK *a, proto_tree *tree, int hf_id,
	proto_item **new_item, guint *i)
{
  guint cls, con, tag;
  gboolean def;
  guint length;
  int start = a->offset;
  int ret;
  
  ret = asn1_header_decode(a, &cls, &con, &tag, &def, &length);
  if (ret == ASN1_ERR_NOERROR) {
    if (cls != ASN1_UNI || con != ASN1_PRI || tag != ASN1_BOL)
      ret = ASN1_ERR_WRONG_TYPE;
  }
  if (ret != ASN1_ERR_NOERROR) {
    if (tree) {
      proto_tree_add_text(tree, a->tvb, start, 0,
        "%s: ERROR: Couldn't parse header: %s",
        proto_registrar_get_name(hf_id), asn1_err_to_str(ret));
    }
    return ret;
  }

  return read_boolean_value(a, tree, hf_id, new_item, i, start, length);
}

static int read_string_value(ASN1_SCK *a, proto_tree *tree, int hf_id,
	proto_item **new_item, char **s, int start, guint length)
{
  guchar *string;
  proto_item *temp_item = NULL;
  int ret;
  
  if (length)
  {
    ret = asn1_string_value_decode(a, length, &string);
    if (ret != ASN1_ERR_NOERROR) {
      if (tree) {
        proto_tree_add_text(tree, a->tvb, start, 0,
          "%s: ERROR: Couldn't parse value: %s",
          proto_registrar_get_name(hf_id), asn1_err_to_str(ret));
      }
      return ret;
    }
    string = g_realloc(string, length + 1);
    string[length] = '\0';
  }
  else
    string = "(null)";
    
  if (tree)
    temp_item = proto_tree_add_string(tree, hf_id, a->tvb, start, a->offset - start, string);
  if (new_item)
    *new_item = temp_item;

  if (s && length)
    *s = string;
  else if (length)
    g_free(string);

  return ASN1_ERR_NOERROR;
}

static int read_string(ASN1_SCK *a, proto_tree *tree, int hf_id,
	proto_item **new_item, char **s, guint expected_cls, guint expected_tag)
{
  guint cls, con, tag;
  gboolean def;
  guint length;
  int start = a->offset;
  int ret;
  
  ret = asn1_header_decode(a, &cls, &con, &tag, &def, &length);
  if (ret == ASN1_ERR_NOERROR) {
    if (cls != expected_cls || con != ASN1_PRI || tag != expected_tag)
      ret = ASN1_ERR_WRONG_TYPE;
  }
  if (ret != ASN1_ERR_NOERROR) {
    if (tree) {
      proto_tree_add_text(tree, a->tvb, start, 0,
        "%s: ERROR: Couldn't parse header: %s",
        proto_registrar_get_name(hf_id), asn1_err_to_str(ret));
    }
    return ret;
  }

  return read_string_value(a, tree, hf_id, new_item, s, start, length);
}

static int parse_filter_strings(ASN1_SCK *a, char **filter, guint *filter_length, const guchar *operation)
{
  guchar *string;
  guchar *string2;
  guint string_length;
  guint string2_length;
  guint string_bytes;
  char *filterp;
  int ret;

  ret = asn1_octet_string_decode(a, &string, &string_length, &string_bytes);
  if (ret != ASN1_ERR_NOERROR)
    return ret;
  ret = asn1_octet_string_decode(a, &string2, &string2_length, &string_bytes);
  if (ret != ASN1_ERR_NOERROR)
    return ret;
  *filter_length += 2 + strlen(operation) + string_length + string2_length;
  *filter = g_realloc(*filter, *filter_length);
  filterp = *filter + strlen(*filter);
  *filterp++ = '(';
  if (string_length != 0) {
  	memcpy(filterp, string, string_length);
  	filterp += string_length;
  }
  strcpy(filterp, operation);
  filterp += strlen(operation);
  if (string2_length != 0) {
  	memcpy(filterp, string2, string2_length);
  	filterp += string2_length;
  }
  *filterp++ = ')';
  *filterp = '\0';
  g_free(string);
  g_free(string2);
  return ASN1_ERR_NOERROR;
}

/* Richard Dawe: To parse substring filters, I added this function. */
static int parse_filter_substrings(ASN1_SCK *a, char **filter, guint *filter_length)
{
  int end;
  guchar *string;
  char *filterp;
  guint string_length;
  guint string_bytes;
  guint seq_len;
  guint header_bytes;  
  int ret, any_valued;

  /* For ASN.1 parsing of octet strings */
  guint        cls;
  guint        con;
  guint        tag;
  gboolean     def;

  ret = asn1_octet_string_decode(a, &string, &string_length, &string_bytes);
  if (ret != ASN1_ERR_NOERROR)
    return ret;

  ret = asn1_sequence_decode(a, &seq_len, &header_bytes);
  if (ret != ASN1_ERR_NOERROR)
    return ret;

  *filter_length += 2 + 1 + string_length;
  *filter = g_realloc(*filter, *filter_length);
  
  filterp = *filter + strlen(*filter);
  *filterp++ = '(';
  if (string_length != 0) {
    memcpy(filterp, string, string_length);
    filterp += string_length;
  }
  *filterp++ = '=';
  *filterp = '\0';
  g_free(string);

  /* Now decode seq_len's worth of octet strings. */
  any_valued = 0;
  end = a->offset + seq_len;

  while (a->offset < end) {
    /* Octet strings here are context-specific, which
     * asn1_octet_string_decode() barfs on. Emulate it, but don't barf. */
    ret = asn1_header_decode (a, &cls, &con, &tag, &def, &string_length);
    if (ret != ASN1_ERR_NOERROR)
      return ret;

    /* XXX - check the tag? */
    if (cls != ASN1_CTX || con != ASN1_PRI) {
    	/* XXX - handle the constructed encoding? */
	return ASN1_ERR_WRONG_TYPE;
    }
    if (!def)
    	return ASN1_ERR_LENGTH_NOT_DEFINITE;

    ret = asn1_string_value_decode(a, (int) string_length, &string);
    if (ret != ASN1_ERR_NOERROR)
      return ret;

    /* If we have an 'any' component with a string value, we need to append
     * an extra asterisk before final component. */
    if ((tag == 1) && (string_length != 0))
      any_valued = 1;

    if ( (tag == 1) || ((tag == 2) && any_valued) )
      (*filter_length)++;
    *filter_length += string_length;
    *filter = g_realloc(*filter, *filter_length);

    filterp = *filter + strlen(*filter);
    if ( (tag == 1) || ((tag == 2) && any_valued) )
      *filterp++ = '*';
    if (tag == 2)
      any_valued = 0;
    if (string_length != 0) {
      memcpy(filterp, string, string_length);
      filterp += string_length;
    }
    *filterp = '\0';
    g_free(string);
  }

  if (any_valued)
  {
    (*filter_length)++;
    *filter = g_realloc(*filter, *filter_length);
    filterp = *filter + strlen(*filter);
    *filterp++ = '*';
  }
  
  /* NB: Allocated byte for this earlier */
  *filterp++ = ')';
  *filterp = '\0';

  return ASN1_ERR_NOERROR;
}

/* Returns -1 if we're at the end, returns an ASN1_ERR value otherwise. */
static int parse_filter(ASN1_SCK *a, char **filter, guint *filter_length,
			int *end)
{
  guint cls, con, tag;
  guint length;
  gboolean def;
  int ret;

  ret = asn1_header_decode(a, &cls, &con, &tag, &def, &length);
  if (ret != ASN1_ERR_NOERROR)
    return ret;
  
  if (*end == 0)
  {
    *end = a->offset + length;
    *filter_length = 1;
    *filter = g_malloc0(*filter_length);
  }

  if (cls == ASN1_CTX)	/* XXX - handle other types as errors? */
  {
    switch (tag)
    {
     case LDAP_FILTER_AND:
      {
        int add_end;

        if (con != ASN1_CON)
          return ASN1_ERR_WRONG_TYPE;
        add_end = a->offset + length;
        *filter_length += 3;
        *filter = g_realloc(*filter, *filter_length);
        strcat(*filter, "(&");
        while ((ret = parse_filter(a, filter, filter_length, &add_end))
 		== ASN1_ERR_NOERROR)
	  continue;
	if (ret != -1)
	  return ret;
        strcat(*filter, ")");
      }
      break;
     case LDAP_FILTER_OR:
      {
        int or_end;

        if (con != ASN1_CON)
          return ASN1_ERR_WRONG_TYPE;
        or_end = a->offset + length;
        *filter_length += 3;
        *filter = g_realloc(*filter, *filter_length);
        strcat(*filter, "(|");
        while ((ret = parse_filter(a, filter, filter_length, &or_end))
 		== ASN1_ERR_NOERROR)
	  continue;
	if (ret != -1)
	  return ret;
        strcat(*filter, ")");
      }
      break;
     case LDAP_FILTER_NOT:
      {
        int not_end;

        if (con != ASN1_CON)
          return ASN1_ERR_WRONG_TYPE;
        not_end = a->offset + length;
        *filter_length += 3;
        *filter = g_realloc(*filter, *filter_length);
        strcat(*filter, "(!");
        ret = parse_filter(a, filter, filter_length, &not_end);
        if (ret != -1 && ret != ASN1_ERR_NOERROR)
          return ret;
        strcat(*filter, ")");
      }
      break;
     case LDAP_FILTER_EQUALITY:
      if (con != ASN1_CON)
        return ASN1_ERR_WRONG_TYPE;
      ret = parse_filter_strings(a, filter, filter_length, "=");
      if (ret != ASN1_ERR_NOERROR)
        return ret;
      break;
     case LDAP_FILTER_GE:
      if (con != ASN1_CON)
        return ASN1_ERR_WRONG_TYPE;
      ret = parse_filter_strings(a, filter, filter_length, ">=");
      if (ret != ASN1_ERR_NOERROR)
        return ret;
      break;
     case LDAP_FILTER_LE:
      if (con != ASN1_CON)
        return ASN1_ERR_WRONG_TYPE;
      ret = parse_filter_strings(a, filter, filter_length, "<=");
      if (ret != -1 && ret != ASN1_ERR_NOERROR)
        return ret;
      break;
     case LDAP_FILTER_APPROX:
      if (con != ASN1_CON)
        return ASN1_ERR_WRONG_TYPE;
      ret = parse_filter_strings(a, filter, filter_length, "~=");
      if (ret != ASN1_ERR_NOERROR)
        return ret;
      break;
     case LDAP_FILTER_PRESENT:
      {
        guchar *string;
        char *filterp;
    
        if (con != ASN1_PRI)
          return ASN1_ERR_WRONG_TYPE;
        ret = asn1_string_value_decode(a, length, &string);
        if (ret != ASN1_ERR_NOERROR)
          return ret;
        *filter_length += 4 + length;
        *filter = g_realloc(*filter, *filter_length);
        filterp = *filter + strlen(*filter);
        *filterp++ = '(';
        if (length != 0) {
          memcpy(filterp, string, length);
          filterp += length;
        }
        *filterp++ = '=';
        *filterp++ = '*';
        *filterp++ = ')';
        *filterp = '\0';
        g_free(string);
      }
      break;
     case LDAP_FILTER_SUBSTRINGS:
      if (con != ASN1_CON)
        return ASN1_ERR_WRONG_TYPE;
      /* Richard Dawe: Handle substrings */
      ret = parse_filter_substrings(a, filter, filter_length);
      if (ret != ASN1_ERR_NOERROR)
        return ret;
      break;
     default:
      return ASN1_ERR_WRONG_TYPE;
    }
  }
  
  if (a->offset == *end)
    return -1;
  else
    return ret;
}

static gboolean read_filter(ASN1_SCK *a, proto_tree *tree, int hf_id)
{
  int start = a->offset;
  char *filter = 0;
  guint filter_length = 0;
  int end = 0;
  int ret;
     
  while ((ret = parse_filter(a, &filter, &filter_length, &end))
	== ASN1_ERR_NOERROR)
    continue;

  if (tree) {
    if (ret != -1) {
      proto_tree_add_text(tree, a->tvb, start, 0,
        "%s: ERROR: Can't parse filter: %s",
        proto_registrar_get_name(hf_id), asn1_err_to_str(ret));
    } else
      proto_tree_add_string(tree, hf_id, a->tvb, start, a->offset-start, filter);
  }

  g_free(filter);

  return (ret == -1) ? TRUE : FALSE;
}

/********************************************************************************************/

static void dissect_ldap_result(ASN1_SCK *a, proto_tree *tree)
{
  guint resultCode = 0;
  int ret;
  
  if (read_integer(a, tree, hf_ldap_message_result, 0, &resultCode, ASN1_ENUM) != ASN1_ERR_NOERROR)
    return;
  if (read_string(a, tree, hf_ldap_message_result_matcheddn, 0, 0, ASN1_UNI, ASN1_OTS) != ASN1_ERR_NOERROR)
    return;
  if (read_string(a, tree, hf_ldap_message_result_errormsg, 0, 0, ASN1_UNI, ASN1_OTS) != ASN1_ERR_NOERROR)
    return;

  if (resultCode == 10)		/* Referral */
  {
    int start = a->offset;
    int end;
    guint length;
    proto_item *ti;
    proto_tree *referralTree;
    
    ret = read_sequence(a, &length);
    if (ret != ASN1_ERR_NOERROR) {
      if (tree) {
        proto_tree_add_text(tree, a->tvb, start, 0,
            "ERROR: Couldn't parse referral URL sequence header: %s",
            asn1_err_to_str(ret));
      }
      return;
    }
    ti = proto_tree_add_text(tree, a->tvb, start, length, "Referral URLs");
    referralTree = proto_item_add_subtree(ti, ett_ldap_referrals);

    end = a->offset + length;
    while (a->offset < end) {
      if (read_string(a, referralTree, hf_ldap_message_result_referral, 0, 0, ASN1_UNI, ASN1_OTS) != ASN1_ERR_NOERROR)
        return;
    }
  }
}

static void dissect_ldap_request_bind(ASN1_SCK *a, proto_tree *tree)
{
  guint cls, con, tag;
  guint def, length;
  int start;
  int ret;

  if (read_integer(a, tree, hf_ldap_message_bind_version, 0, 0, ASN1_INT) != ASN1_ERR_NOERROR)
    return;
  if (read_string(a, tree, hf_ldap_message_bind_dn, 0, 0, ASN1_UNI, ASN1_OTS) != ASN1_ERR_NOERROR)
    return;

  start = a->offset;
  ret = asn1_header_decode(a, &cls, &con, &tag, &def, &length);
  if (ret == ASN1_ERR_NOERROR) {
    if (cls != ASN1_CTX) {
      /* RFCs 1777 and 2251 say these are context-specific types */
      ret = ASN1_ERR_WRONG_TYPE;
    }
  }
  if (ret != ASN1_ERR_NOERROR) {
    proto_tree_add_text(tree, a->tvb, start, 0,
      "%s: ERROR: Couldn't parse header: %s",
      proto_registrar_get_name(hf_ldap_message_bind_auth),
      asn1_err_to_str(ret));
    return;
  }
  proto_tree_add_uint(tree, hf_ldap_message_bind_auth, a->tvb, start,
			a->offset - start, tag);
  switch (tag)
  {
   case LDAP_AUTH_SIMPLE:
    if (read_string_value(a, tree, hf_ldap_message_bind_auth_password, NULL,
                          NULL, start, length) != ASN1_ERR_NOERROR)
      return;
    break;

    /* For Kerberos V4, dissect it as a ticket. */
    /* For SASL, dissect it as SaslCredentials. */
  }
}

static void dissect_ldap_response_bind(ASN1_SCK *a, proto_tree *tree)
{
  /* FIXME: handle SASL data */
  dissect_ldap_result(a, tree);
}

static void dissect_ldap_request_search(ASN1_SCK *a, proto_tree *tree)
{
  guint seq_length;
  int end;
  int ret;
  
  if (read_string(a, tree, hf_ldap_message_search_base, 0, 0, ASN1_UNI, ASN1_OTS) != ASN1_ERR_NOERROR)
    return;
  if (read_integer(a, tree, hf_ldap_message_search_scope, 0, 0, ASN1_ENUM) != ASN1_ERR_NOERROR)
    return;
  if (read_integer(a, tree, hf_ldap_message_search_deref, 0, 0, ASN1_ENUM) != ASN1_ERR_NOERROR)
    return;
  if (read_integer(a, tree, hf_ldap_message_search_sizeLimit, 0, 0, ASN1_INT) != ASN1_ERR_NOERROR)
    return;
  if (read_integer(a, tree, hf_ldap_message_search_timeLimit, 0, 0, ASN1_INT) != ASN1_ERR_NOERROR)
    return;
  if (read_boolean(a, tree, hf_ldap_message_search_typesOnly, 0, 0) != ASN1_ERR_NOERROR)
    return;
  if (!read_filter(a, tree, hf_ldap_message_search_filter))
    return;
  ret = read_sequence(a, &seq_length);
  if (ret != ASN1_ERR_NOERROR) {
    if (tree) {
      proto_tree_add_text(tree, a->tvb, a->offset, 0,
          "ERROR: Couldn't parse LDAP attribute sequence header: %s",
          asn1_err_to_str(ret));
    }
    return;
  }
  end = a->offset + seq_length;
  while (a->offset < end) {
    if (read_string(a, tree, hf_ldap_message_attribute, 0, 0, ASN1_UNI,
                    ASN1_OTS) != ASN1_ERR_NOERROR)
      return;
  }
}

static void dissect_ldap_response_search_entry(ASN1_SCK *a, proto_tree *tree)
{
  guint seq_length;
  int end_of_sequence;
  int ret;
 
  if (read_string(a, tree, hf_ldap_message_dn, 0, 0, ASN1_UNI, ASN1_OTS) != ASN1_ERR_NOERROR)
    return;
  ret = read_sequence(a, &seq_length);
  if (ret != ASN1_ERR_NOERROR) {
    if (tree) {
      proto_tree_add_text(tree, a->tvb, a->offset, 0,
          "ERROR: Couldn't parse search entry response sequence header: %s",
          asn1_err_to_str(ret));
    }
    return;
  }

  end_of_sequence = a->offset + seq_length;
  while (a->offset < end_of_sequence)
  {
    proto_item *ti;
    proto_tree *attr_tree;
    guint set_length;
    int end_of_set;

    ret = read_sequence(a, 0);
    if (ret != ASN1_ERR_NOERROR) {
      if (tree) {
        proto_tree_add_text(tree, a->tvb, a->offset, 0,
            "ERROR: Couldn't parse LDAP attribute sequence header: %s",
            asn1_err_to_str(ret));
      }
      return;
    }
    if (read_string(a, tree, hf_ldap_message_attribute, &ti, 0, ASN1_UNI, ASN1_OTS) != ASN1_ERR_NOERROR)
      return;
    attr_tree = proto_item_add_subtree(ti, ett_ldap_attribute);

    ret = read_set(a, &set_length);
    if (ret != ASN1_ERR_NOERROR) {
      if (tree) {
        proto_tree_add_text(attr_tree, a->tvb, a->offset, 0,
            "ERROR: Couldn't parse LDAP value set header: %s",
            asn1_err_to_str(ret));
      }
      return;
    }
    end_of_set = a->offset + set_length;
    while (a->offset < end_of_set) {
      if (read_string(a, attr_tree, hf_ldap_message_value, 0, 0, ASN1_UNI,
                      ASN1_OTS) != ASN1_ERR_NOERROR)
        return;
    }
  }
}

static void dissect_ldap_request_add(ASN1_SCK *a, proto_tree *tree)
{
  guint seq_length;
  int end_of_sequence;
  int ret;
  
  if (read_string(a, tree, hf_ldap_message_dn, 0, 0, ASN1_UNI, ASN1_OTS) != ASN1_ERR_NOERROR)
    return;

  ret = read_sequence(a, &seq_length);
  if (ret != ASN1_ERR_NOERROR) {
    if (tree) {
      proto_tree_add_text(tree, a->tvb, a->offset, 0,
          "ERROR: Couldn't parse add request sequence header: %s",
          asn1_err_to_str(ret));
    }
    return;
  }

  end_of_sequence = a->offset + seq_length;
  while (a->offset < end_of_sequence)
  {
    proto_item *ti;
    proto_tree *attr_tree;
    guint set_length;
    int end_of_set;

    ret = read_sequence(a, 0);
    if (ret != ASN1_ERR_NOERROR) {
      if (tree) {
        proto_tree_add_text(tree, a->tvb, a->offset, 0,
            "ERROR: Couldn't parse LDAP attribute sequence header: %s",
            asn1_err_to_str(ret));
      }
      return;
    }
    if (read_string(a, tree, hf_ldap_message_attribute, &ti, 0, ASN1_UNI,
                    ASN1_OTS) != ASN1_ERR_NOERROR)
      return;
    attr_tree = proto_item_add_subtree(ti, ett_ldap_attribute);

    ret = read_set(a, &set_length);
    if (ret != ASN1_ERR_NOERROR) {
      if (tree) {
        proto_tree_add_text(attr_tree, a->tvb, a->offset, 0,
            "ERROR: Couldn't parse LDAP value set header: %s",
            asn1_err_to_str(ret));
      }
      return;
    }
    end_of_set = a->offset + set_length;
    while (a->offset < end_of_set) {
      if (read_string(a, attr_tree, hf_ldap_message_value, 0, 0, ASN1_UNI, ASN1_OTS) != ASN1_ERR_NOERROR)
        return;
    }
  }
}

static void dissect_ldap_request_delete(ASN1_SCK *a, proto_tree *tree,
		int start, guint length)
{
  read_string_value(a, tree, hf_ldap_message_dn, NULL, NULL, start, length);
}

static void dissect_ldap_request_modifyrdn(ASN1_SCK *a, proto_tree *tree,
		guint length)
{
  int start = a->offset;

  if (read_string(a, tree, hf_ldap_message_dn, 0, 0, ASN1_UNI, ASN1_OTS) != ASN1_ERR_NOERROR)
    return;
  if (read_string(a, tree, hf_ldap_message_modrdn_name, 0, 0, ASN1_UNI, ASN1_OTS) != ASN1_ERR_NOERROR)
    return;
  if (read_boolean(a, tree, hf_ldap_message_modrdn_delete, 0, 0) != ASN1_ERR_NOERROR)
    return;
  
  if (a->offset < (int) (start + length)) {
    /* LDAP V3 Modify DN operation, with newSuperior */
    if (read_string(a, tree, hf_ldap_message_modrdn_superior, 0, 0, ASN1_UNI, ASN1_OTS) != ASN1_ERR_NOERROR)
      return;
  }
}

static void dissect_ldap_request_compare(ASN1_SCK *a, proto_tree *tree)
{
  int start;
  int length;
  char *string1 = 0;
  char *string2 = 0;
  char *compare;
  int ret;
  
  if (read_string(a, tree, hf_ldap_message_dn, 0, 0, ASN1_UNI, ASN1_OTS) != ASN1_ERR_NOERROR)
    return;
  ret = read_sequence(a, 0);
  if (ret != ASN1_ERR_NOERROR) {
    if (tree) {
      proto_tree_add_text(tree, a->tvb, a->offset, 0,
          "ERROR: Couldn't parse compare request sequence header: %s",
          asn1_err_to_str(ret));
    }
    return;
  }

  start = a->offset;
  ret = read_string(a, 0, -1, 0, &string1, ASN1_UNI, ASN1_OTS);
  if (ret != ASN1_ERR_NOERROR) {
    if (tree) {
      proto_tree_add_text(tree, a->tvb, start, 0,
        "ERROR: Couldn't parse compare type: %s", asn1_err_to_str(ret));
    }
    return;
  }
  ret = read_string(a, 0, -1, 0, &string2, ASN1_UNI, ASN1_OTS);
  if (ret != ASN1_ERR_NOERROR) {
    if (tree) {
      proto_tree_add_text(tree, a->tvb, start, 0,
        "ERROR: Couldn't parse compare value: %s", asn1_err_to_str(ret));
    }
    return;
  }

  length = 2 + strlen(string1) + strlen(string2);
  compare = g_malloc0(length);
  snprintf(compare, length, "%s=%s", string1, string2);
  proto_tree_add_string(tree, hf_ldap_message_compare, a->tvb, start,
      a->offset-start, compare);
  
  g_free(string1);
  g_free(string2);
  g_free(compare);
  
  return;
}

static void dissect_ldap_request_modify(ASN1_SCK *a, proto_tree *tree)
{
  guint seq_length;
  int end_of_sequence;
  int ret;
  
  if (read_string(a, tree, hf_ldap_message_dn, 0, 0, ASN1_UNI, ASN1_OTS) != ASN1_ERR_NOERROR)
    return;
  ret = read_sequence(a, &seq_length);
  if (ret != ASN1_ERR_NOERROR) {
    if (tree) {
      proto_tree_add_text(tree, a->tvb, a->offset, 0,
          "ERROR: Couldn't parse modify request sequence header: %s",
          asn1_err_to_str(ret));
    }
    return;
  }
  end_of_sequence = a->offset + seq_length;
  while (a->offset < end_of_sequence)
  {
    proto_item *ti;
    proto_tree *attr_tree;
    guint set_length;
    int end_of_set;
    guint operation;

    ret = read_sequence(a, 0);
    if (ret != ASN1_ERR_NOERROR) {
      if (tree) {
        proto_tree_add_text(tree, a->tvb, a->offset, 0,
            "ERROR: Couldn't parse modify request item sequence header: %s",
            asn1_err_to_str(ret));
      }
      return;
    }
    ret = read_integer(a, 0, -1, 0, &operation, ASN1_ENUM);
    if (ret != ASN1_ERR_NOERROR) {
      if (tree) {
        proto_tree_add_text(tree, a->tvb, a->offset, 0,
          "ERROR: Couldn't parse modify operation: %s",
          asn1_err_to_str(ret));
        return;
      }
    }
    ret = read_sequence(a, 0);
    if (ret != ASN1_ERR_NOERROR) {
      if (tree) {
        proto_tree_add_text(tree, a->tvb, a->offset, 0,
            "ERROR: Couldn't parse modify request operation sequence header: %s",
            asn1_err_to_str(ret));
      }
      return;
    }

    switch (operation)
    {
     case LDAP_MOD_ADD:
      if (read_string(a, tree, hf_ldap_message_modify_add, &ti, 0, ASN1_UNI,
                      ASN1_OTS) != ASN1_ERR_NOERROR)
        return;
      break;

     case LDAP_MOD_REPLACE:
      if (read_string(a, tree, hf_ldap_message_modify_replace, &ti, 0,
                      ASN1_UNI, ASN1_OTS) != ASN1_ERR_NOERROR)
        return;
      break;

     case LDAP_MOD_DELETE:
      if (read_string(a, tree, hf_ldap_message_modify_delete, &ti, 0,
                      ASN1_UNI, ASN1_OTS) != ASN1_ERR_NOERROR)
        return;
      break;

     default:
       proto_tree_add_text(tree, a->tvb, a->offset, 0,
            "Unknown LDAP modify operation (%u)", operation);
       return;
    }
    attr_tree = proto_item_add_subtree(ti, ett_ldap_attribute);

    ret = read_set(a, &set_length);
    if (ret != ASN1_ERR_NOERROR) {
      if (tree) {
        proto_tree_add_text(attr_tree, a->tvb, a->offset, 0,
            "ERROR: Couldn't parse LDAP value set header: %s",
            asn1_err_to_str(ret));
      }
      return;
    }
    end_of_set = a->offset + set_length;
    while (a->offset < end_of_set) {
      if (read_string(a, attr_tree, hf_ldap_message_value, 0, 0, ASN1_UNI,
                      ASN1_OTS) != ASN1_ERR_NOERROR)
        return;
    }
  }
}

static void dissect_ldap_request_abandon(ASN1_SCK *a, proto_tree *tree,
		int start, guint length)
{
  read_integer_value(a, tree, hf_ldap_message_abandon_msgid, NULL, NULL,
			    start, length); 
}

static void
dissect_ldap(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree)
{
  proto_tree *ldap_tree = 0, *ti, *msg_tree;
  guint messageLength;
  guint messageId;
  int next_offset;
  guint protocolOpCls, protocolOpCon, protocolOpTag;
  gchar *typestr;
  guint opLen;
  ASN1_SCK a;
  int start;
  gboolean first_time = TRUE;
  int ret;

  asn1_open(&a, tvb, 0);

  while (tvb_reported_length_remaining(tvb, a.offset) > 0)
  {
    int message_id_start;
    int message_id_length;
    int message_start;
    
    /*
     * XXX - should handle the initial sequence specifier split across
     * segment boundaries.
     */
    message_start = a.offset;
    ret = read_sequence(&a, &messageLength);
    if (ret != ASN1_ERR_NOERROR)
    {
      if (first_time)
      {
        if (check_col(pinfo->cinfo, COL_PROTOCOL))
          col_set_str(pinfo->cinfo, COL_PROTOCOL, "LDAP");
        if (check_col(pinfo->cinfo, COL_INFO))
        {
          col_add_fstr(pinfo->cinfo, COL_INFO,
                      "Invalid LDAP message (Can't parse sequence header: %s)",
                      asn1_err_to_str(ret));
        }
      }
      if (tree)
      {
        ti = proto_tree_add_item(tree, proto_ldap, tvb, message_start, -1,
			         FALSE);
        ldap_tree = proto_item_add_subtree(ti, ett_ldap);
        proto_tree_add_text(ldap_tree, tvb, message_start, -1,
			    "Invalid LDAP message (Can't parse sequence header: %s)",
			    asn1_err_to_str(ret));
      }
      break;
    }

    /*
     * Desegmentation check.
     */
    if (ldap_desegment) {
	if (pinfo->can_desegment
	    && messageLength > (guint)tvb_length_remaining(tvb, a.offset)) {
	    /*
	     * This frame doesn't have all of the data for this message,
	     * but we can do reassembly on it.
	     *
	     * Tell the TCP dissector where the data for this message
	     * starts in the data it handed us, and how many more bytes
	     * we need, and return.
	     */
	    pinfo->desegment_offset = message_start;
	    pinfo->desegment_len = messageLength -
	        tvb_length_remaining(tvb, a.offset);
	    return;
	}
    }
    next_offset = a.offset + messageLength;

    if (first_time)
    {
      if (check_col(pinfo->cinfo, COL_PROTOCOL))
        col_set_str(pinfo->cinfo, COL_PROTOCOL, "LDAP");
      if (check_col(pinfo->cinfo, COL_INFO))
        col_clear(pinfo->cinfo, COL_INFO);
    }

    if (tree) 
    {
      ti = proto_tree_add_item(tree, proto_ldap, tvb, message_start,
			       next_offset - message_start, FALSE);
      ldap_tree = proto_item_add_subtree(ti, ett_ldap);
    }

    message_id_start = a.offset;
    ret = read_integer(&a, 0, hf_ldap_message_id, 0, &messageId, ASN1_INT);
    if (ret != ASN1_ERR_NOERROR)
    {
      if (first_time && check_col(pinfo->cinfo, COL_INFO))
        col_add_fstr(pinfo->cinfo, COL_INFO, "Invalid LDAP packet (Can't parse Message ID: %s)",
                    asn1_err_to_str(ret));
      if (ldap_tree)
        proto_tree_add_text(ldap_tree, tvb, message_id_start, 1,
                            "Invalid LDAP packet (Can't parse Message ID: %s)",
                            asn1_err_to_str(ret));
      break;
    }
    message_id_length = a.offset - message_id_start;

    start = a.offset;
    asn1_id_decode(&a, &protocolOpCls, &protocolOpCon, &protocolOpTag);
    if (protocolOpCls != ASN1_APL)
      typestr = "Bad message type (not Application)";
    else
      typestr = val_to_str(protocolOpTag, msgTypes, "Unknown message type (%u)");

    if (first_time)
    {
      if (check_col(pinfo->cinfo, COL_INFO))
        col_add_fstr(pinfo->cinfo, COL_INFO, "MsgId=%u MsgType=%s",
		     messageId, typestr);
      first_time = FALSE;
    }

    if (ldap_tree) 
    {
      proto_tree_add_uint_hidden(ldap_tree, hf_ldap_message_id, tvb, message_id_start, message_id_length, messageId);
      proto_tree_add_uint_hidden(ldap_tree, hf_ldap_message_type, tvb,
			         start, a.offset - start, protocolOpTag);
      ti = proto_tree_add_text(ldap_tree, tvb, message_id_start, messageLength, "Message: Id=%u  %s", messageId, typestr);
      msg_tree = proto_item_add_subtree(ti, ett_ldap_message);
      start = a.offset;
      if (read_length(&a, msg_tree, hf_ldap_message_length, &opLen) != ASN1_ERR_NOERROR)
        return;

      if (protocolOpCls != ASN1_APL)
      {
        proto_tree_add_text(msg_tree, a.tvb, a.offset, opLen,
			    "%s", typestr);
      }
      else
      {
        switch (protocolOpTag)
        {
         case LDAP_REQ_BIND:
          dissect_ldap_request_bind(&a, msg_tree);
          break;
         case LDAP_REQ_UNBIND:
          /* Nothing to dissect */
          break;
         case LDAP_REQ_SEARCH:
          dissect_ldap_request_search(&a, msg_tree);
          break;
         case LDAP_REQ_MODIFY:
          dissect_ldap_request_modify(&a, msg_tree);
          break;
         case LDAP_REQ_ADD:
          dissect_ldap_request_add(&a, msg_tree);
          break;
         case LDAP_REQ_DELETE:
          dissect_ldap_request_delete(&a, msg_tree, start, opLen);
          break;
         case LDAP_REQ_MODRDN:
          dissect_ldap_request_modifyrdn(&a, msg_tree, opLen);
          break;
         case LDAP_REQ_COMPARE:
          dissect_ldap_request_compare(&a, msg_tree);
          break;
         case LDAP_REQ_ABANDON:
          dissect_ldap_request_abandon(&a, msg_tree, start, opLen);
          break;
         case LDAP_RES_BIND:
          dissect_ldap_response_bind(&a, msg_tree);
          break;
         case LDAP_RES_SEARCH_ENTRY:
          dissect_ldap_response_search_entry(&a, msg_tree);
          break;
         case LDAP_RES_SEARCH_RESULT:
         case LDAP_RES_MODIFY:
         case LDAP_RES_ADD:
         case LDAP_RES_DELETE:
         case LDAP_RES_MODRDN:
         case LDAP_RES_COMPARE:
          dissect_ldap_result(&a, msg_tree);
          break;
         default:
          proto_tree_add_text(msg_tree, a.tvb, a.offset, opLen,
			      "Unknown LDAP operation (%u)", protocolOpTag);
          break;
        }
      }
    }

    /*
     * XXX - what if "a.offset" is past the offset of the next top-level
     * sequence?  Show that as an error?
     */
    a.offset = next_offset;
  }
}

void
proto_register_ldap(void)
{
  static value_string result_codes[] = {
    {0, "Success"},
    {1, "Operations error"},
    {2, "Protocol error"},
    {3, "Time limit exceeded"},
    {4, "Size limit exceeded"},
    {5, "Compare false"},
    {6, "Compare true"},
    {7, "Authentication method not supported"},
    {8, "Strong authentication required"},
    {10, "Referral"},
    {11, "Administrative limit exceeded"},
    {12, "Unavailable critical extension"},
    {13, "Confidentiality required"},
    {14, "SASL bind in progress"},
    {16, "No such attribute"},
    {17, "Undefined attribute type"},
    {18, "Inappropriate matching"},
    {19, "Constraint violation"},
    {20, "Attribute or value exists"},
    {21, "Invalid attribute syntax"},
    {32, "No such object"},
    {33, "Alias problem"},
    {34, "Invalid DN syntax"},
    {36, "Alias derefetencing problem"},
    {48, "Inappropriate authentication"},
    {49, "Invalid credentials"},
    {50, "Insufficient access rights"},
    {51, "Busy"},
    {52, "Unavailable"},
    {53, "Unwilling to perform"},
    {54, "Loop detected"},
    {64, "Naming violation"},
    {65, "Objectclass violation"},
    {66, "Not allowed on non-leaf"},
    {67, "Not allowed on RDN"},
    {68, "Entry already exists"},
    {69, "Objectclass modification prohibited"},
    {71, "Affects multiple DSAs"},
    {80, "Other"},
    {0,  NULL},
  };

  static value_string auth_types[] = {
    {LDAP_AUTH_SIMPLE,    "Simple"},
    {LDAP_AUTH_KRBV4LDAP, "Kerberos V4 to the LDAP server"},
    {LDAP_AUTH_KRBV4DSA,  "Kerberos V4 to the DSA"},
    {LDAP_AUTH_SASL,      "SASL"},
    {0, NULL},
  };
  
  static value_string search_scope[] = {
    {0x00, "Base"},
    {0x01, "Single"},
    {0x02, "Subtree"},
    {0x00, NULL},
  };
    
  static value_string search_dereference[] = {
    {0x00, "Never"},
    {0x01, "Searching"},
    {0x02, "Base Object"},
    {0x03, "Always"},
    {0x00, NULL},
  };
  
  static hf_register_info hf[] = {
    { &hf_ldap_length,
      { "Length",		"ldap.length",
	FT_UINT32, BASE_DEC, NULL, 0x0,
	"LDAP Length", HFILL }},
	  
    { &hf_ldap_message_id,
      { "Message Id",		"ldap.message_id",
	FT_UINT32, BASE_DEC, NULL, 0x0,
	"LDAP Message Id", HFILL }},
    { &hf_ldap_message_type,
      { "Message Type",		"ldap.message_type",
	FT_UINT8, BASE_HEX, &msgTypes, 0x0,
	"LDAP Message Type", HFILL }},
    { &hf_ldap_message_length,
      { "Message Length",		"ldap.message_length",
	FT_UINT32, BASE_DEC, NULL, 0x0,
	"LDAP Message Length", HFILL }},

    { &hf_ldap_message_result,
      { "Result Code",		"ldap.result.code",
	FT_UINT8, BASE_HEX, result_codes, 0x0,
	"LDAP Result Code", HFILL }},
    { &hf_ldap_message_result_matcheddn,
      { "Matched DN",		"ldap.result.matcheddn",
	FT_STRING, BASE_NONE, NULL, 0x0,
	"LDAP Result Matched DN", HFILL }},
    { &hf_ldap_message_result_errormsg,
      { "Error Message",		"ldap.result.errormsg",
	FT_STRING, BASE_NONE, NULL, 0x0,
	"LDAP Result Error Message", HFILL }},
    { &hf_ldap_message_result_referral,
      { "Referral",		"ldap.result.referral",
	FT_STRING, BASE_NONE, NULL, 0x0,
	"LDAP Result Referral URL", HFILL }},

    { &hf_ldap_message_bind_version,
      { "Version",		"ldap.bind.version",
	FT_UINT32, BASE_DEC, NULL, 0x0,
	"LDAP Bind Version", HFILL }},
    { &hf_ldap_message_bind_dn,
      { "DN",			"ldap.bind.dn",
	FT_STRING, BASE_NONE, NULL, 0x0,
	"LDAP Bind Distinguished Name", HFILL }},
    { &hf_ldap_message_bind_auth,
      { "Auth Type",		"ldap.bind.auth_type",
	FT_UINT8, BASE_HEX, auth_types, 0x0,
	"LDAP Bind Auth Type", HFILL }},
    { &hf_ldap_message_bind_auth_password,
      { "Password",		"ldap.bind.password",
	FT_STRING, BASE_NONE, NULL, 0x0,
	"LDAP Bind Password", HFILL }},

    { &hf_ldap_message_search_base,
      { "Base DN",		"ldap.search.basedn",
	FT_STRING, BASE_NONE, NULL, 0x0,
	"LDAP Search Base Distinguished Name", HFILL }},
    { &hf_ldap_message_search_scope,
      { "Scope",			"ldap.search.scope",
	FT_UINT8, BASE_HEX, search_scope, 0x0,
	"LDAP Search Scope", HFILL }},
    { &hf_ldap_message_search_deref,
      { "Dereference",		"ldap.search.dereference",
	FT_UINT8, BASE_HEX, search_dereference, 0x0,
	"LDAP Search Dereference", HFILL }},
    { &hf_ldap_message_search_sizeLimit,
      { "Size Limit",		"ldap.search.sizelimit",
	FT_UINT32, BASE_DEC, NULL, 0x0,
	"LDAP Search Size Limit", HFILL }},
    { &hf_ldap_message_search_timeLimit,
      { "Time Limit",		"ldap.search.timelimit",
	FT_UINT32, BASE_DEC, NULL, 0x0,
	"LDAP Search Time Limit", HFILL }},
    { &hf_ldap_message_search_typesOnly,
      { "Attributes Only",	"ldap.search.typesonly",
	FT_BOOLEAN, BASE_NONE, NULL, 0x0,
	"LDAP Search Attributes Only", HFILL }},
    { &hf_ldap_message_search_filter,
      { "Filter",		"ldap.search.filter",
	FT_STRING, BASE_NONE, NULL, 0x0,
	"LDAP Search Filter", HFILL }},
    { &hf_ldap_message_dn,
      { "Distinguished Name",	"ldap.dn",
	FT_STRING, BASE_NONE, NULL, 0x0,
	"LDAP Distinguished Name", HFILL }},
    { &hf_ldap_message_attribute,
      { "Attribute",		"ldap.attribute",
	FT_STRING, BASE_NONE, NULL, 0x0,
	"LDAP Attribute", HFILL }},
    { &hf_ldap_message_value,
      { "Value",		"ldap.value",
	FT_STRING, BASE_NONE, NULL, 0x0,
	"LDAP Value", HFILL }},

    { &hf_ldap_message_modrdn_name,
      { "New Name",		"ldap.modrdn.name",
	FT_STRING, BASE_NONE, NULL, 0x0,
	"LDAP New Name", HFILL }},
    { &hf_ldap_message_modrdn_delete,
      { "Delete Values",	"ldap.modrdn.delete",
	FT_BOOLEAN, BASE_NONE, NULL, 0x0,
	"LDAP Modify RDN - Delete original values", HFILL }},
    { &hf_ldap_message_modrdn_superior,
      { "New Location",		"ldap.modrdn.superior",
	FT_STRING, BASE_NONE, NULL, 0x0,
	"LDAP Modify RDN - New Location", HFILL }},

    { &hf_ldap_message_compare,
      { "Test",		"ldap.compare.test",
	FT_STRING, BASE_NONE, NULL, 0x0,
	"LDAP Compare Test", HFILL }},

    { &hf_ldap_message_modify_add,
      { "Add",			"ldap.modify.add",
	FT_STRING, BASE_NONE, NULL, 0x0,
	"LDAP Add", HFILL }},
    { &hf_ldap_message_modify_replace,
      { "Replace",		"ldap.modify.replace",
	FT_STRING, BASE_NONE, NULL, 0x0,
	"LDAP Replace", HFILL }},
    { &hf_ldap_message_modify_delete,
      { "Delete",		"ldap.modify.delete",
	FT_STRING, BASE_NONE, NULL, 0x0,
	"LDAP Delete", HFILL }},

    { &hf_ldap_message_abandon_msgid,
      { "Abandon Msg Id",	"ldap.abandon.msgid",
	FT_UINT32, BASE_DEC, NULL, 0x0,
	"LDAP Abandon Msg Id", HFILL }},
  };

  static gint *ett[] = {
    &ett_ldap,
    &ett_ldap_message,
    &ett_ldap_referrals,
    &ett_ldap_attribute
  };
  module_t *ldap_module;

  proto_ldap = proto_register_protocol("Lightweight Directory Access Protocol",
				       "LDAP", "ldap");
  proto_register_field_array(proto_ldap, hf, array_length(hf));
  proto_register_subtree_array(ett, array_length(ett));

  ldap_module = prefs_register_protocol(proto_ldap, NULL);
  prefs_register_bool_preference(ldap_module, "desegment_ldap_messages",
    "Desegment all LDAP messages spanning multiple TCP segments",
    "Whether the LDAP dissector should desegment all messages spanning multiple TCP segments",
    &ldap_desegment);
}

void
proto_reg_handoff_ldap(void)
{
  dissector_handle_t ldap_handle;

  ldap_handle = create_dissector_handle(dissect_ldap, proto_ldap);
  dissector_add("tcp.port", TCP_PORT_LDAP, ldap_handle);
}