File: ld.c

package info (click to toggle)
cpu 1.4.3-12
  • links: PTS, VCS
  • area: main
  • in suites: buster, sid, stretch
  • size: 2,612 kB
  • sloc: sh: 7,535; ansic: 7,392; makefile: 117
file content (1235 lines) | stat: -rw-r--r-- 29,169 bytes parent folder | download
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
/*
     This file is part of CPU
     (C) 2003 Blake Matheny (and other contributing authors)

     CPU 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, or (at your
     option) any later version.

     CPU 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 CPU; see the file COPYING.  If not, write to the
     Free Software Foundation, Inc., 59 Temple Place - Suite 330,
     Boston, MA 02111-1307, USA.
*/

/**
 * Initialization routines and some helper routines
 * @author Blake Matheny
 * @file ld.c
 **/
#include <stdio.h>
#include <string.h>
#include "plugins/ldap/ldap.h"

gid_t getlGid (LDAP * ld, char *groupn);
char *checkSupGroups (LDAP * ld);
void rmUsrFrmOldSupGrp (LDAP * ld, char *uname);
int checkIsPrimaryGroup (LDAP * ld);
int groupExists (LDAP * ld, int cgid);
void addUserGroup (LDAP * ld, gid_t tg, char *grpnm);

static int list_size = 0;

const char *ldap_hashes[] = {
  "{sha}",
  "{ssha}",
  "{md5}",
  "{smd5}",
  "{crypt}",
  NULL,
};

int
ldapOperation (ldapop_t optype)
{
  LDAP *ld = NULL;
  char *tstr = NULL;

  if (((char *) globalLdap->hostname != NULL || (int) globalLdap->port) &&
      ((char *) globalLdap->uri == NULL))
  {
    ld = ldap_init ((char *) globalLdap->hostname, (int) globalLdap->port);
    if (ld == NULL)
    {
      CPU_ldapPerror (ld, globalLdap, "ldapOperation: ldap_init");
      return -1;
    }
  }
  else
  {
    int rc = LDAP_OPERATIONS_ERROR;
#ifdef HAVE_LDAP_INITIALIZE
    rc = ldap_initialize (&ld, (char *) globalLdap->uri);
#else
    printf("Your version of libldap does not have ldap_initialize()\n");
#endif
    if (rc != LDAP_SUCCESS)
    {
      CPU_ldapPerror (ld, globalLdap, "ldapOperation: ldap_initialize");
      return -1;
    }
  }

  if ((int) globalLdap->usetls)
    {
      globalLdap->version = 3;
    }

  if (ldap_set_option (ld, LDAP_OPT_PROTOCOL_VERSION, &globalLdap->version)
      != LDAP_OPT_SUCCESS)
    {
      CPU_ldapPerror (ld, globalLdap, "ldapOperation: ldap_set_option");
      return -1;
    }

  if ((int) globalLdap->usetls)
  {
#ifdef HAVE_LDAP_START_TLS_S
    if (ldap_start_tls_s (ld, NULL, NULL) != LDAP_SUCCESS)
    {
      CPU_ldapPerror (ld, globalLdap, "ldapOperation: ldap_start_tls");
      return -1;
    }
#else
    printf("Your implementation of libldap does not have ldap_start_tls_s\n");
    return -1;
#endif
  }
  if (ldap_bind_s (ld, globalLdap->bind_dn, globalLdap->bind_password,
		   LDAP_AUTH_SIMPLE) != LDAP_SUCCESS)
    {
      CPU_ldapPerror (ld, globalLdap, "ldapOperation: ldap_bind_s");
      return -1;
    }

  switch (optype)
    {
    case USERADD:
      if ((int) globalLdap->passent->pw_uid < 0)
	{
	  if ((int) (globalLdap->passent->pw_uid = getNextUid (ld)) < 0) {
	    return -1;
	  }
	}
      if (globalLdap->gid != NULL && globalLdap->gid[0] != 0)
	{
	  if ((int)
	      (globalLdap->passent->pw_gid =
	       getlGid (ld, globalLdap->gid)) < 0)
	    {
	      fprintf (stderr, "Unable to find group %s, exiting\n",
		       globalLdap->gid);
	      return -1;
	    }
	}
      else if ( (int)globalLdap->passent->pw_gid >= 0 ) {
	if ( !groupExists(ld, globalLdap->passent->pw_gid) ) {
	      fprintf (stderr,
		  "Group %d does not exist, using anyway.\n",
		  globalLdap->passent->pw_gid);
	}
      }
      tstr = NULL;
      if ((tstr = checkSupGroups (ld)) != NULL)
	{
	  fprintf (stderr, "Unable to find group %s, exiting\n", tstr);
	  return -1;
	}
      if ((int) globalLdap->passent->pw_gid < 0)
      {
	char *ugrp = cfg_get_str ("LDAP", "USERGROUPS");
	int ugid = cfg_get_int ("LDAP", "USERS_GID");
	if (ugrp == NULL || strncmp (ugrp, "no", 2) == 0)
	{
	  if (ugid < 0)
	    globalLdap->passent->pw_gid = 100;
	  else
	  {
	    if (!groupExists (ld, ugid))
	      fprintf (stderr,
		  "Group %d does not exist, using anyway.\n",
		  ugid);
	    globalLdap->passent->pw_gid = ugid;
	  }
	  if (ldapUserAdd (ld) < 0)
	    return -1;
	}
	else
	{
	  gid_t tg = getNextGid (ld, GROUPADD);
	  if ((int) tg < 0)
	  {
	    fprintf (stderr, "Could not find a free gid\n");
	    return -1;
	  }
	  else
	  {
	    globalLdap->passent->pw_gid = tg;
	    if (ldapUserAdd (ld) < 0)
	      return -1;
	    addUserGroup (ld, tg, globalLdap->passent->pw_name);
	  }
	}
      } else {
	  if ( ldapUserAdd (ld) < 0 )
	      return -1;
      }
      break;
    case USERMOD:
      if (globalLdap->gid != NULL && globalLdap->gid[0] != 0)
	{
	  if ((int)
	      (globalLdap->passent->pw_gid =
	       getlGid (ld, globalLdap->gid)) < 0)
	    {
	      fprintf (stderr, "Unable to find group %s, exiting\n",
		       globalLdap->gid);
	      return -1;
	    }
	}
      tstr = NULL;
      if ((tstr = checkSupGroups (ld)) != NULL)
	{
	  fprintf (stderr, "Unable to find group %s, exiting\n", tstr);
	  return -1;
	}
      rmUsrFrmOldSupGrp (ld, globalLdap->passent->pw_name);
      if (ldapUserMod (ld) < 0)
	return -1;
      break;
    case USERDEL:
      rmUsrFrmOldSupGrp (ld, globalLdap->passent->pw_name);
      if (ldapUserDel (ld) < 0)
	return -1;
      break;
    case GROUPADD:
      if ((int) globalLdap->passent->pw_gid < 0)
	{
	  if ((int) (globalLdap->passent->pw_gid = getNextGid (ld, GROUPADD))
	      < 0)
	    return -1;
	}
      if (ldapGroupAdd (ld) < 0)
	return -1;
      break;
    case GROUPMOD:
      if (ldapGroupMod (ld) < 0)
	return -1;
      break;
    case GROUPDEL:
      if (checkIsPrimaryGroup (ld))
	{
	  return -1;
	}
      if (ldapGroupDel (ld) < 0)
	return -1;
      break;
    case CAT:
      if (ldapCat (ld) < 0)
	return -1;
      break;
    default:
      fprintf (stderr, "ldap: ldapOperation: Unknown optype\n");
      return -1;
      break;
    }
  return 0;
}

#define ALLOC_SIZE 1024

LDAPMod **
ldapAddList (LDAPMod ** mods)
{
  LDAPMod **tmod = NULL;
  int lsize = 0;
  int i = 0;
  lsize = list_size + 2;

  tmod = (LDAPMod **) malloc (sizeof (LDAPMod *) * (lsize));
  if (tmod == NULL)
    return NULL;
  bzero (tmod, sizeof (LDAPMod *) * (lsize));

  if (mods != NULL)
    {
      for (i = 0; mods[i] != NULL; i++)
	tmod[i] = mods[i];
      //free(mods);
    }

  tmod[list_size] = (LDAPMod *) malloc (sizeof (LDAPMod));
  bzero (tmod[list_size], sizeof (LDAPMod));

  tmod[list_size + 1] = NULL;

  /*
     mods = (LDAPMod**)realloc(mods, (list_size+ALLOC_SIZE)*sizeof(LDAPMod*));
     mods[list_size] = (LDAPMod*)malloc(sizeof(LDAPMod));
     bzero(mods[list_size], sizeof(LDAPMod));
   */
  return tmod;
}

LDAPMod **
ldapBuildListStr (int mod_op, char *mod_type, char *value, LDAPMod ** mods)
{
  char **temp;

  if (value == NULL)
    return mods;

  mods = ldapAddList (mods);

  temp = (char **) malloc (sizeof (char *) * 2);
  bzero (temp, sizeof (char *) * 2);
  temp[0] = value;
  temp[1] = NULL;

  mods[list_size]->mod_op = mod_op;
  mods[list_size]->mod_type = strdup (mod_type);
  mods[list_size]->mod_values = temp;
  list_size++;
  return mods;
}

LDAPMod **
ldapBuildList (int mod_op, char *mod_type, char **value, LDAPMod ** mods)
{
  mods = ldapAddList (mods);

  if (value == NULL)
    return mods;

  mods[list_size]->mod_op = mod_op;
  mods[list_size]->mod_type = strdup (mod_type);
  mods[list_size]->mod_values = value;
  list_size++;
  return mods;
}

LDAPMod **
ldapBuildListInt (int mod_op, char *mod_type, int value, LDAPMod ** mods)
{
  char **temp;
  size_t len = 1;
  int valtemp = ABS (value);

  mods = ldapAddList (mods);
  temp = (char **) malloc (sizeof (char *) * 2);
  bzero (temp, sizeof (char *) * 2);

  while (valtemp / 10 > 0)
    {
      len++;
      valtemp = valtemp / 10;
    }

  if (value < 0)
    len++;
  len++;
  temp[0] = (char *) malloc (sizeof (char) * len);
  bzero (temp[0], sizeof (char) * len);
  snprintf (temp[0], len, "%d", value);
  temp[1] = NULL;

  mods[list_size]->mod_op = mod_op;
  mods[list_size]->mod_type = strdup (mod_type);
  mods[list_size]->mod_values = temp;
  list_size++;
  return mods;
}

void
addUserGroup (LDAP * ld, gid_t tg, char *grpnm)
{
  LDAPMod **mods;
  char *object_vals = NULL;
  char **tval = NULL;
  int num_tokens, i;
  char *cn;
  char *tn[2];
  char *gn[2];
  char *dn;
  int num_mods = 3;
  num_tokens = 0;

  cn = cfg_get_str ("LDAP", "GROUP_CN_STRING");
  if (cn == NULL)
    cn = strdup ("cn");

  tn[0] = grpnm;
  tn[1] = NULL;

  gn[0] = (char *) malloc (sizeof (char) * 16);
  if (gn[0] == NULL)
    return;
  bzero (gn[0], sizeof (char) * 16);
  snprintf (gn[0], sizeof (char) * 16, "%d", (int)tg);

  gn[1] = NULL;
  if ((object_vals =
       strdup (cfg_get_str ("LDAP", "GROUP_OBJECT_CLASS"))) == NULL)
    {
      fprintf (stderr,
	       "GROUP_OBJECT_CLASS was not found in the configuration "
	       "file and is required\n");
      return;
    }

  while (object_vals != NULL && *object_vals)
    {
      tval =
	(char **) realloc (tval, sizeof (char *) * ((num_tokens + 1) * 4));
      tval[num_tokens] = getToken (&object_vals, ",");
      num_tokens++;
    }
  tval[num_tokens] = NULL;

  mods = (LDAPMod **) malloc ((num_mods + 1) * sizeof (LDAPMod *));

  if (mods == NULL)
    {
      return;
    }

  for (i = 0; i < num_mods; i++)
    {
      if ((mods[i] = (LDAPMod *) malloc (sizeof (LDAPMod))) == NULL)
	{
	  return;
	}
    }

  mods[0]->mod_op = LDAP_MOD_ADD;
  mods[0]->mod_type = "objectclass";
  mods[0]->mod_values = tval;

  mods[1]->mod_op = LDAP_MOD_ADD;
  mods[1]->mod_type = cn;
  mods[1]->mod_values = tn;

  mods[2]->mod_op = LDAP_MOD_ADD;
  mods[2]->mod_type = "gidnumber";
  mods[2]->mod_values = gn;

  mods[num_mods] = NULL;

  dn = buildDn (GROUPADD, grpnm);

  if (ldap_add_s (ld, dn, mods) != LDAP_SUCCESS)
    {
      CPU_ldapPerror (ld, globalLdap, "addUserGroup: ldap_add_s");
      return;
    }
  return;
}

char *
ldapGetCn (void)
{
  size_t slen = 0;
  char *temp;

  if (globalLdap->cn_value)
    {
      temp = globalLdap->cn_value;
    }
  else if (globalLdap->first_name && globalLdap->last_name)
    {
      slen =
	strlen (globalLdap->first_name) + strlen (globalLdap->last_name) + 2;
      temp = (char *) malloc (sizeof (char) * slen);
      if (temp == NULL)
	return NULL;
      bzero (temp, slen * sizeof (char));
      snprintf (temp, slen, "%s %s", globalLdap->first_name,
		globalLdap->last_name);
    }
  else if (globalLdap->first_name)
    temp = globalLdap->first_name;
  else if (globalLdap->last_name)
    temp = globalLdap->last_name;
  else
    temp = globalLdap->passent->pw_name;

  return temp;
}

const char *
ldapGetHashPrefix (hash_t hasht)
{
  switch (hasht)
    {
    case H_SHA1:
      return ldap_hashes[H_SHA1];
      break;
    case H_SSHA1:
      return ldap_hashes[H_SSHA1];
      break;
    case H_MD5:
      return ldap_hashes[H_MD5];
      break;
    case H_SMD5:
      return ldap_hashes[H_SMD5];
      break;
    case H_CRYPT:
      return ldap_hashes[H_CRYPT];
      break;
    case H_MD5CRYPT:
      return ldap_hashes[H_CRYPT]; /* {crypt} too */
      break;
    case H_CLEAR:
      /* FIXME: this should work so that the prefix is returned for the
         correct hash but the password doesn't get encrypted */
      return ldap_hashes[H_CRYPT];
      break;
    default:
      fprintf (stderr, "ldap: ldapGetHashPrefix: Unknown hash type.\n");
      break;
    }
  return NULL;
}

void
rmUsrFrmOldSupGrp (LDAP * ld, char *uname)
{
  LDAPMessage *res[2];
  LDAPMessage *pos;
  LDAPMod **mods;
  int filtsize = 0;
  struct timeval timeout;
  char *filter = NULL;
  char *temp;
  char *attrs[7] = {
    "memberUid",
    NULL
  };
  char *memberuid[2] = { uname, NULL };

  mods = (LDAPMod **) malloc (2 * sizeof (LDAPMod *));
  if (mods == NULL)
    return;
  bzero (mods, 2 * sizeof (LDAPMod *));
  mods[0] = (LDAPMod *) malloc (sizeof (LDAPMod));
  if (mods[0] == NULL)
    return;
  bzero (mods[0], sizeof (LDAPMod));

  mods[0]->mod_op = LDAP_MOD_DELETE;
  mods[0]->mod_type = "memberUid";
  mods[0]->mod_values = memberuid;
  mods[1] = NULL;

  timeout = globalLdap->timeout;
  res[1] = NULL;

  temp = cfg_get_str ("LDAP", "GROUP_FILTER");
  if (temp == NULL)
    temp = strdup ("(objectClass=PosixGroup)");
  filtsize = strlen (temp) + strlen (uname) + 18;
  filter = (char *) malloc (sizeof (char) * filtsize);
  bzero (filter, filtsize);

  snprintf (filter, filtsize, "(&%s (memberUid=%s))", temp, uname);
  if (ldap_search_st (ld, globalLdap->group_base, LDAP_SCOPE_SUBTREE,
		      filter, attrs, 0, &timeout, res) != LDAP_SUCCESS)
    {
      Free (filter);
      CPU_ldapPerror (ld, globalLdap, "rmUsrFrmOldSupGrp: ldap_search_st");
      return;
    }
  free (filter);
  if (ldap_count_entries (ld, res[0]) < 1)
    return;
  for (pos = ldap_first_entry (ld, res[0]); pos != NULL;
       pos = ldap_next_entry (ld, pos))
    {
      if (ldap_modify_s (ld, ldap_get_dn (ld, pos), mods) < 0)
	{
	  CPU_ldapPerror (ld, globalLdap, "rmUsrFrmOldSupGrp: ldap_modify_s");
	  return;
	}
    }
}

int
checkIsPrimaryGroup (LDAP * ld)
{
  /* i <- gidNumberOf(globalLdap->passent->pw_name)
   * s <- usersWith'gidNumber'(i)
   * if s != NULL
   *   return true
   * else
   *  return false
   */
  LDAPMessage *res[2];
  LDAPMessage *pos;
  BerElement *ber;
  char *attrs[2] = {
    "gidNumber",
    NULL
  };

  struct timeval timeout;
  char *filter = NULL;
  char *temp;
  int filtsize = 0;
  char *cn = NULL;
  char *a = NULL;
  char **vals = NULL;

  cn = cfg_get_str ("LDAP", "GROUP_CN_STRING");
  if (cn == NULL)
    cn = strdup ("cn");

  timeout = globalLdap->timeout;
  res[1] = NULL;

  temp = cfg_get_str ("LDAP", "GROUP_FILTER");
  if (temp == NULL)
    temp = strdup ("(objectClass=PosixGroup)");

  filtsize =
    strlen (cn) + strlen (temp) + strlen (globalLdap->passent->pw_name) + 8;
  filter = (char *) malloc (sizeof (char) * filtsize);
  if (filter == NULL)
    {
      fprintf (stderr, "Unable to allocate memory\n");
      return 1;
    }
  bzero (filter, filtsize);
  snprintf (filter, filtsize, "(&%s (%s=%s))", temp, cn,
	    globalLdap->passent->pw_name);
  if (ldap_search_st (ld, globalLdap->group_base, LDAP_SCOPE_SUBTREE,
		      filter, attrs, 0, &timeout, res) != LDAP_SUCCESS)
    {
      Free (filter);
      CPU_ldapPerror (ld, globalLdap, "checkIsPrimaryGroup: ldap_search_st");
      return 1;
    }
  free (filter);
  if (ldap_count_entries (ld, res[0]) < 1)
    return 0;

  pos = ldap_first_entry (ld, res[0]);
  a = ldap_first_attribute (ld, pos, &ber);
  if (a == NULL)
    return 0;

  vals = ldap_get_values (ld, pos, a);
  if (vals == NULL || vals[0] == NULL)
    return 0;

  temp = NULL;
  temp = cfg_get_str ("LDAP", "USER_FILTER");
  if (temp == NULL)
    temp = strdup ("(objectClass=posixAccount)");
  filtsize = strlen (temp) + strlen (vals[0]) + 17;
  filter = NULL;
  filter = (char *) malloc (sizeof (char) * filtsize);
  if (filter == NULL)
    {
      fprintf (stderr, "Unable to allocate memory\n");
      return 1;
    }
  bzero (filter, filtsize);
  snprintf (filter, filtsize, "(&%s (gidNumber=%s))", temp, vals[0]);
  if (ldap_search_st (ld, globalLdap->user_base, LDAP_SCOPE_SUBTREE,
		      filter, attrs, 0, &timeout, res) != LDAP_SUCCESS)
    {
      Free (filter);
      CPU_ldapPerror (ld, globalLdap, "checkIsPrimaryGroup: ldap_search_st");
      return 1;
    }
  if (ldap_count_entries (ld, res[0]) > 0) {
    printf("Can not remove an existing users primary group.\n");
    return 1;
  }
  return 0;
}

char *
checkSupGroups (LDAP * ld)
{
  LDAPMessage *res[2];
  int filtsize = 0;
  struct timeval timeout;
  char *filter = NULL;
  char *temp;
  char *cn = NULL;
  char *attrs[7] = {
    "gidNumber",
    NULL
  };
  int lsize = 0;

  if (globalLdap->memberUid == NULL)
    return NULL;

  cn = cfg_get_str ("LDAP", "GROUP_CN_STRING");
  if (cn == NULL)
    cn = strdup ("cn");

  timeout = globalLdap->timeout;
  res[1] = NULL;

  temp = cfg_get_str ("LDAP", "GROUP_FILTER");
  if (temp == NULL)
    temp = strdup ("(objectClass=PosixGroup)");

  for (lsize = 0; globalLdap->memberUid[lsize] != NULL; lsize++)
    {
      filtsize = strlen (temp) + strlen (globalLdap->memberUid[lsize]) +
	strlen (cn) + 8;
      filter = (char *) malloc (sizeof (char) * filtsize);
      bzero (filter, filtsize);

      snprintf (filter, filtsize, "(&%s (%s=%s))", temp, cn,
		globalLdap->memberUid[lsize]);
      if (ldap_search_st (ld, globalLdap->group_base, LDAP_SCOPE_SUBTREE,
			  filter, attrs, 0, &timeout, res) != LDAP_SUCCESS)
	{
	  Free (filter);
	  CPU_ldapPerror (ld, globalLdap, "checkSupGroups: ldap_search_st");
	  return globalLdap->memberUid[lsize];
	}
      free (filter);
      if (ldap_count_entries (ld, res[0]) < 1)
	return globalLdap->memberUid[lsize];
    }
  return NULL;
}

int
groupExists (LDAP * ld, int cgid)
{
  LDAPMessage *res[2];
  LDAPMessage *pos;
  BerElement *ber;
  int filtsize = 0;
  char * a = NULL;
  char ** vals;
  struct timeval timeout;
  char *filter = NULL;
  char *temp;
  char *cn = NULL;
  char *attrs[2] = {
    "cn",
    NULL
  };

  cn = cfg_get_str ("LDAP", "GROUP_CN_STRING");
  if (cn == NULL)
    cn = strdup ("cn");

  timeout = globalLdap->timeout;
  res[1] = NULL;

  temp = cfg_get_str ("LDAP", "GROUP_FILTER");
  if (temp == NULL)
    temp = strdup ("(objectClass=PosixGroup)");
  filtsize = strlen (temp) + 24;
  filter = (char *) malloc (sizeof (char) * filtsize);
  bzero (filter, filtsize);

  snprintf (filter, filtsize, "(&%s (gidNumber=%d))", temp, cgid);
  if (ldap_search_st (ld, globalLdap->group_base, LDAP_SCOPE_SUBTREE,
		      filter, attrs, 0, &timeout, res) != LDAP_SUCCESS)
    {
      Free (filter);
      CPU_ldapPerror (ld, globalLdap, "getlGid: ldap_search_st");
      return 1;
    }
  free (filter);
  if (ldap_count_entries (ld, res[0]) > 0) {
    pos = ldap_first_entry(ld, res[0]);
    a = ldap_first_attribute(ld, pos, &ber);
    vals = ldap_get_values (ld, pos, a);
    if ( vals != NULL ) {
	globalLdap->gid = strdup(vals[0]);
	return 1;
    } else {
	return 0;
    }
  }
  return 0;
}

gid_t
getlGid (LDAP * ld, char *groupn)
{
  LDAPMessage *res[2];
  LDAPMessage *pos;
  BerElement *ber;
  int filtsize = 0;
  struct timeval timeout;
  char *filter = NULL;
  char *temp;
  char *cn = NULL;
  char *attrs[7] = {
    "gidNumber",
    NULL
  };
  char *gid = NULL;

  cn = cfg_get_str ("LDAP", "GROUP_CN_STRING");
  if (cn == NULL)
    cn = strdup ("cn");

  timeout = globalLdap->timeout;
  res[1] = NULL;

  temp = cfg_get_str ("LDAP", "GROUP_FILTER");
  if (temp == NULL)
    temp = strdup ("(objectClass=PosixGroup)");
  filtsize = strlen (temp) + strlen (groupn) + strlen (cn) + 8;
  filter = (char *) malloc (sizeof (char) * filtsize);
  bzero (filter, filtsize);

  snprintf (filter, filtsize, "(&%s (%s=%s))", temp, cn, groupn);
  if (ldap_search_st (ld, globalLdap->group_base, LDAP_SCOPE_SUBTREE,
		      filter, attrs, 0, &timeout, res) != LDAP_SUCCESS)
    {
      Free (filter);
      CPU_ldapPerror (ld, globalLdap, "getlGid: ldap_search_st");
      return -1;
    }
  if (ldap_count_entries (ld, res[0]) < 1)
    return -10;
  pos = ldap_first_entry (ld, res[0]);
  if (pos != NULL)
    gid = ldap_first_attribute (ld, pos, &ber);
  else
    return -10;
  if (gid != NULL)
    {
      gid = ldap_get_values (ld, pos, gid)[0];
      if (gid != NULL)
	return atoi (gid);
      else
	return -10;
    }
  else
    return -10;
}

uid_t
getNextRandUid (LDAP *ld, uid_t min_uid, uid_t max_uid)
{
  LDAPMessage	  *res;
  uid_t		  next_uid = 0;
  int		  i = 0, id_pass = 0, ldapres = 0, filtsize = 40;
  struct timeval  timeout;
  char		  *filter = NULL;
  char *attrs[2] = {
    "uidNumber",
    NULL
  };

  timeout = globalLdap->timeout;

  filter = (char *) malloc (sizeof (char) * filtsize);
  if (filter == NULL)
    return -1;

  id_pass = cfg_get_int ("LDAP", "ID_MAX_PASSES");
  if (id_pass < 1)
    id_pass = 1000;

  while (i < id_pass)
  {
    next_uid = cRandom (min_uid, max_uid);
    bzero (filter, filtsize);
    snprintf (filter, filtsize, "(uidNumber=%d)", (int)next_uid);
    if (ldap_search_st (ld, globalLdap->user_base, LDAP_SCOPE_SUBTREE,
	  filter, attrs, 0, &timeout,
	  &res) != LDAP_SUCCESS)
    {
      Free (filter);
      CPU_ldapPerror (ld, globalLdap, "getNextRandUid: ldap_search_st");
      return -1;
    }
    ldapres = ldap_count_entries (ld, res);
    if (ldapres == 0)
      break;
    ++i;
  }
  Free (filter);
  if (i == id_pass)
  {
    fprintf (stderr, "ldap: getNextRandUid: Unable to find new uid.\n");
    return -1;
  }
  return next_uid;
}

uid_t
getNextLinearUid ( LDAP * ld, uid_t min_uid, uid_t max_uid )
{
  LDAPMessage *res;
  LDAPMessage *pos;
  BerElement *ber;
  bitvector *bv = bitvector_create((max_uid - min_uid));
  uid_t next_uid = 0;
  char *filter = strdup("(uidNumber=*)");
  char *a;
  char *attrs[2] = {
    "uidNumber",
    NULL
  };
  char **vals;
  struct timeval tv1, tv2;
  int msgid = 0;
  int rc = 0, parse_rc = 0;
  LDAPControl **serverctrls;
  char *matched_msg = NULL, *error_msg = NULL;

  if ( (rc = ldap_search_ext (ld, globalLdap->user_base, LDAP_SCOPE_SUBTREE,
			      filter, attrs, 0, NULL, NULL, NULL,
			      LDAP_NO_LIMIT, &msgid)) != LDAP_SUCCESS )
  {
    Free (filter);
    CPU_ldapPerror (ld, globalLdap, "getNextLinearUid: ldap_search");
    return -1;
  }

  if ( verbose ) {
    gettimeofday (&tv1, NULL);
    printf ("Searching for uid, please wait.");
  }

  while ((rc = ldap_result (ld, msgid, LDAP_MSG_ONE, NULL, &res)) > 0)
  {
    for (pos = ldap_first_message (ld, res);
	pos != NULL; pos = ldap_next_message (ld, pos))
    {
      switch (ldap_msgtype (pos))
      {
	case -1:	/* error */
	  Free (filter);
	  CPU_ldapPerror (ld, globalLdap, "getNextLinearUid: ldap_result");
	  return -1;
	case 0:	/* continue, timeout occurred */
	  printf("Timeout occurred\n");
	  break;
	case LDAP_RES_SEARCH_ENTRY:	/* server returned an entry */
	  a = ldap_first_attribute (ld, pos, &ber);
	  vals = ldap_get_values (ld, pos, a);
	  if (!vals[0])
	    break;
	  if (atoi (vals[0]) < (int) min_uid || atoi (vals[0]) > (int) max_uid)
	    continue;
	  else
	    bitvector_set (bv, atoi (vals[0]) - min_uid);
	  /* This works fine on Linux, barfs on FreeBSD
	  ldap_value_free (vals);
	  ldap_memfree (a);
	  if (ber != NULL)
	  {
	    ber_free (ber, 0);
	  }
	  ldap_msgfree (res);
	  */
	  break;
	case LDAP_RES_SEARCH_REFERENCE:	/* FIXME: Should handle refs */
	  printf("Unable to handle reference\n");
	  break;
	case LDAP_RES_SEARCH_RESULT:	/* last one */
	  parse_rc = ldap_parse_result (ld, res, &rc, &matched_msg,
	      &error_msg, NULL,
	      &serverctrls, 1);
	  if (parse_rc != LDAP_SUCCESS || rc != LDAP_SUCCESS)
	  {
	    Free (filter);
	    CPU_ldapPerror (ld, globalLdap,
		"getLinearNextUid: ldap_parse_result");
	    return -1;
	  }
	  if ( verbose ) {
	    printf ("\n");
	    gettimeofday (&tv1, NULL);
	  }
	  next_uid = -1;
	  if (bitvector_isempty (bv))
	    next_uid = min_uid;
	  else
	  {
	    next_uid = min_uid + bitvector_firstunset (bv);
	    if (next_uid > max_uid)
	    {
	      next_uid = -1;
	    }
	  }
	  return next_uid;
	default:
	  printf("Default was reached, weird. Report me.\n");
	  break;
      }
    }
    ldap_msgfree (res);
    if ( verbose ) {
      gettimeofday(&tv2, NULL);
      if ( (tv1.tv_sec - tv2.tv_sec) > 0 ) {
	printf(".");
	gettimeofday(&tv1, NULL);
      }
    }
  }
  return next_uid;
}

uid_t
getNextUid (LDAP * ld)
{
  uid_t min_uid;
  uid_t max_uid;
  char *temp = NULL;

  if ( (temp = getenv("MIN_UIDNUMBER")) )
    min_uid = atoi(getenv("MIN_UIDNUMBER"));
  else
    min_uid = cfg_get_int ("LDAP", "MIN_UIDNUMBER");
  if (min_uid < 0)
    min_uid = 100;

  temp = NULL;
  if ( (temp = getenv("MAX_UIDNUMBER")) )
    max_uid = atoi(getenv("MAX_UIDNUMBER"));
  else
    max_uid = cfg_get_int ("LDAP", "MAX_UIDNUMBER");
  if (max_uid > 1000000)
    max_uid = 10000;

  temp = NULL;
  if (min_uid > max_uid)
  {
    int swap = min_uid;
    min_uid = max_uid;
    max_uid = swap;
  }

  temp = cfg_get_str ("LDAP", "RANDOM");
  if (temp && (temp[0] == 't' || temp[0] == 'T'))
  {
    return getNextRandUid(ld, min_uid, max_uid);
  }
  else
  {
    return getNextLinearUid(ld, min_uid, max_uid);
  }
}

gid_t
getNextRandGid (LDAP * ld, gid_t min_gid, gid_t max_gid)
{
  LDAPMessage	  *res;
  gid_t		  next_gid = 0;
  int		  i = 0, id_pass = 0, ldapres = 0, filtsize = 40;
  struct timeval  timeout;
  char		  *filter = NULL;
  char *attrs[2] = {
    "gidNumber",
    NULL
  };

  timeout = globalLdap->timeout;

  filter = (char *) malloc (sizeof (char) * filtsize);
  if (filter == NULL)
    return -1;

  id_pass = cfg_get_int ("LDAP", "ID_MAX_PASSES");
  if (id_pass < 1)
    id_pass = 1000;

  while (i < id_pass)
  {
    next_gid = cRandom (min_gid, max_gid);
    bzero (filter, filtsize);
    snprintf (filter, filtsize, "(gidNumber=%d)", (int)next_gid);
    if (ldap_search_st (ld, globalLdap->group_base, LDAP_SCOPE_SUBTREE,
	  filter, attrs, 0, &timeout,
	  &res) != LDAP_SUCCESS)
    {
      Free (filter);
      CPU_ldapPerror (ld, globalLdap, "getNextRandGid: ldap_search_st");
      return -1;
    }
    ldapres = ldap_count_entries (ld, res);
    if (ldapres == 0)
      break;
    ++i;
  }
  Free (filter);
  if (i == id_pass)
  {
    fprintf (stderr, "ldap: getNextRandGid: Unable to find new gid.\n");
    return -1;
  }
  return next_gid;
}

gid_t
getNextLinearGid ( LDAP * ld, gid_t min_gid, gid_t max_gid )
{
  LDAPMessage *res;
  LDAPMessage *pos;
  BerElement *ber;
  bitvector *bv = bitvector_create((max_gid - min_gid));
  gid_t next_gid = 0;
  char *filter = strdup("(gidNumber=*)");
  char *a;
  char *attrs[2] = {
    "gidNumber",
    NULL
  };
  char **vals;
  struct timeval tv1, tv2;
  int msgid = 0;
  int rc = 0, parse_rc = 0;
  LDAPControl **serverctrls;
  char *matched_msg = NULL, *error_msg = NULL;

  if ( (rc = ldap_search_ext (ld, globalLdap->group_base, LDAP_SCOPE_SUBTREE,
			      filter, attrs, 0, NULL, NULL, NULL,
			      LDAP_NO_LIMIT, &msgid)) != LDAP_SUCCESS )
  {
    Free (filter);
    CPU_ldapPerror (ld, globalLdap, "getNextLinearGid: ldap_search");
    return -1;
  }

  if ( verbose ) {
    gettimeofday (&tv1, NULL);
    printf ("Searching for gid, please wait.");
  }

  while ((rc = ldap_result (ld, msgid, LDAP_MSG_ONE, NULL, &res)) > 0)
  {
    for (pos = ldap_first_message (ld, res);
	pos != NULL; pos = ldap_next_message (ld, pos))
    {
      switch (ldap_msgtype (pos))
      {
	case -1:	/* error */
	  Free (filter);
	  CPU_ldapPerror (ld, globalLdap, "getNextLinearGid: ldap_result");
	  return -1;
	case 0:	/* continue, timeout occurred */
	  break;
	case LDAP_RES_SEARCH_ENTRY:	/* server returned an entry */
	  a = ldap_first_attribute (ld, pos, &ber);
	  vals = ldap_get_values (ld, pos, a);
	  if (!vals[0])
	    break;
	  if (atoi (vals[0]) < (int) min_gid || atoi (vals[0]) > (int) max_gid)
	    continue;
	  else
	    bitvector_set (bv, atoi (vals[0]) - min_gid);
	  /* This works fine on Linux, barfs on FreeBSD
	  ldap_value_free (vals);
	  ldap_memfree (a);
	  if (ber != NULL)
	  {
	    ber_free (ber, 0);
	  }
	  ldap_msgfree (res);
	  */
	  break;
	case LDAP_RES_SEARCH_REFERENCE:	/* FIXME: Should handle refs */
	  break;
	case LDAP_RES_SEARCH_RESULT:	/* last one */
	  parse_rc = ldap_parse_result (ld, res, &rc, &matched_msg,
	      &error_msg, NULL,
	      &serverctrls, 1);
	  if (parse_rc != LDAP_SUCCESS || rc != LDAP_SUCCESS)
	  {
	    Free (filter);
	    CPU_ldapPerror (ld, globalLdap,
		"getLinearNextGid: ldap_parse_result");
	    return -1;
	  }
	  if ( verbose ) {
	    printf ("\n");
	    gettimeofday (&tv1, NULL);
	  }
	  next_gid = -1;
	  if (bitvector_isempty (bv))
	    next_gid = min_gid;
	  else
	  {
	    next_gid = min_gid + bitvector_firstunset (bv);
	    if (next_gid > max_gid)
	    {
	      next_gid = -1;
	    }
	  }
	  return next_gid;
	default:
	  break;
      }
    }
    ldap_msgfree (res);
    if ( verbose ) {
      gettimeofday(&tv2, NULL);
      if ( (tv1.tv_sec - tv2.tv_sec) > 0 ) {
	printf(".");
	gettimeofday(&tv1, NULL);
      }
    }
  }
  return next_gid;
}

gid_t
getNextGid (LDAP * ld, ldapop_t op)
{
  gid_t min_gid;
  gid_t max_gid;
  char *temp = NULL;

  if (!(op == USERADD || op == GROUPADD)) {
    return -1;
  }

  if ( (temp = getenv("MIN_GIDNUMBER")) )
    min_gid = atoi(getenv("MIN_GIDNUMBER"));
  else
    min_gid = cfg_get_int ("LDAP", "MIN_GIDNUMBER");
  if (min_gid < 0)
    min_gid = 100;

  temp = NULL;

  if ( (temp = getenv("MAX_GIDNUMBER")) )
    max_gid = atoi(getenv("MAX_GIDNUMBER"));
  else
    max_gid = cfg_get_int ("LDAP", "MAX_GIDNUMBER");
  if (max_gid > 1000000)
    max_gid = 10000;

  temp = NULL;
  if (min_gid > max_gid)
  {
    int swap = min_gid;
    min_gid = max_gid;
    max_gid = swap;
  }

  temp = cfg_get_str ("LDAP", "RANDOM");
  if (temp && (temp[0] == 't' || temp[0] == 'T'))
  {
    return getNextRandGid(ld, min_gid, max_gid);
  }
  else
  {
    return getNextLinearGid(ld, min_gid, max_gid);
  }
}