]> git.sur5r.net Git - openldap/blob - clients/tools/ldapmodify.c
Plug memory leaks from ldap_get_option().
[openldap] / clients / tools / ldapmodify.c
1 /* $OpenLDAP$ */
2 /*
3  * Copyright 1998-2002 The OpenLDAP Foundation, All Rights Reserved.
4  * COPYING RESTRICTIONS APPLY, see COPYRIGHT file
5  */
6 /* ldapmodify.c - generic program to modify or add entries using LDAP */
7
8 #include "portable.h"
9
10 #include <stdio.h>
11
12 #include <ac/stdlib.h>
13 #include <ac/ctype.h>
14 #include <ac/string.h>
15 #include <ac/unistd.h>
16
17 #ifdef HAVE_SYS_STAT_H
18 #include <sys/stat.h>
19 #endif
20
21 #ifdef HAVE_SYS_FILE_H
22 #include <sys/file.h>
23 #endif
24 #ifdef HAVE_FCNTL_H
25 #include <fcntl.h>
26 #endif
27
28 #include <ldap.h>
29
30 #include "lutil.h"
31 #include "lutil_ldap.h"
32 #include "ldif.h"
33 #include "ldap_defaults.h"
34 #include "ldap_log.h"
35 #include "ldap_pvt.h"
36
37 #include "common.h"
38
39
40 static int      ldapadd, force = 0;
41 static char *rejfile = NULL;
42 static LDAP     *ld = NULL;
43
44 #define LDAPMOD_MAXLINE         4096
45
46 /* strings found in replog/LDIF entries (mostly lifted from slurpd/slurp.h) */
47 #define T_VERSION_STR           "version"
48 #define T_REPLICA_STR           "replica"
49 #define T_DN_STR                "dn"
50 #define T_CONTROL_STR           "control"
51 #define T_CHANGETYPESTR         "changetype"
52 #define T_ADDCTSTR              "add"
53 #define T_MODIFYCTSTR           "modify"
54 #define T_DELETECTSTR           "delete"
55 #define T_MODRDNCTSTR           "modrdn"
56 #define T_MODDNCTSTR            "moddn"
57 #define T_RENAMECTSTR           "rename"
58 #define T_MODOPADDSTR           "add"
59 #define T_MODOPREPLACESTR       "replace"
60 #define T_MODOPDELETESTR        "delete"
61 #define T_MODSEPSTR             "-"
62 #define T_NEWRDNSTR             "newrdn"
63 #define T_DELETEOLDRDNSTR       "deleteoldrdn"
64 #define T_NEWSUPSTR             "newsuperior"
65
66
67 static int process_ldif_rec LDAP_P(( char *rbuf, int count ));
68 static int parse_ldif_control LDAP_P(( char *line, LDAPControl ***pctrls ));
69 static void addmodifyop LDAP_P((
70         LDAPMod ***pmodsp, int modop,
71         const char *attr,
72         struct berval *value ));
73 static int domodify LDAP_P((
74         const char *dn,
75         LDAPMod **pmods,
76     LDAPControl **pctrls,
77         int newentry ));
78 static int dodelete LDAP_P((
79         const char *dn,
80     LDAPControl **pctrls ));
81 static int dorename LDAP_P((
82         const char *dn,
83         const char *newrdn,
84         const char *newsup,
85         int deleteoldrdn,
86     LDAPControl **pctrls ));
87 static char *read_one_record LDAP_P(( FILE *fp ));
88
89 void
90 usage( void )
91 {
92     fprintf( stderr,
93 "Add or modify entries from an LDAP server\n\n"
94 "usage: %s [options]\n"
95 "       The list of desired operations are read from stdin or from the file\n"
96 "       specified by \"-f file\".\n"
97 "Add or modify options:\n"
98 "  -a         add values (default%s)\n"
99 "  -F         force all changes records to be used\n"
100 "  -S file    write skipped modifications to `file'\n"
101                  , prog, (ldapadd ? "" : " is to replace") );
102         tool_common_usage();
103     exit( EXIT_FAILURE );
104 }
105
106
107 const char options[] = "aFrS:" "cCd:D:e:f:h:H:IkKMnO:p:P:QR:U:vw:WxX:y:Y:Z";
108
109 int
110 handle_private_option( int i )
111 {
112         switch ( i ) {
113 #if 0
114                 char    *control, *cvalue;
115                 int             crit;
116         case 'E': /* modify controls */
117                 if( version == LDAP_VERSION2 ) {
118                         fprintf( stderr, "%s: -E incompatible with LDAPv%d\n",
119                                 prog, version );
120                         exit( EXIT_FAILURE );
121                 }
122
123                 /* should be extended to support comma separated list of
124                  *      [!]key[=value] parameters, e.g.  -E !foo,bar=567
125                  */
126
127                 crit = 0;
128                 cvalue = NULL;
129                 if( optarg[0] == '!' ) {
130                         crit = 1;
131                         optarg++;
132                 }
133
134                 control = ber_strdup( optarg );
135                 if ( (cvalue = strchr( control, '=' )) != NULL ) {
136                         *cvalue++ = '\0';
137                 }
138                 fprintf( stderr, "Invalid modify control name: %s\n", control );
139                 usage();
140 #endif
141
142         case 'a':       /* add */
143             ldapadd = 1;
144             break;
145
146         case 'F':       /* force all changes records to be used */
147             force = 1;
148             break;
149
150         case 'r':       /* replace (obsolete) */
151                 break;
152
153         case 'S':       /* skipped modifications to file */
154                 if( rejfile != NULL ) {
155                         fprintf( stderr, "%s: -S previously specified\n", prog );
156                         exit( EXIT_FAILURE );
157                 }
158                 rejfile = ber_strdup( optarg );
159                 break;
160
161         default:
162                 return 0;
163         }
164         return 1;
165 }
166
167
168 int
169 main( int argc, char **argv )
170 {
171     char                *rbuf, *start, *rejbuf = NULL;
172     FILE                *fp, *rejfp;
173         char            *matched_msg, *error_msg;
174         int             rc, retval;
175         int count, len;
176
177     prog = lutil_progname( "ldapmodify", argc, argv );
178
179         /* strncmp instead of strcmp since NT binaries carry .exe extension */
180     ldapadd = ( strncasecmp( prog, "ldapadd", sizeof("ldapadd")-1 ) == 0 );
181
182     /* Print usage when no parameters */
183     if( argc < 2 ) usage();
184
185         tool_args( argc, argv );
186
187         if ( argc != optind )
188         usage();
189
190     if ( rejfile != NULL ) {
191         if (( rejfp = fopen( rejfile, "w" )) == NULL ) {
192             perror( rejfile );
193             return( EXIT_FAILURE );
194         }
195     } else {
196         rejfp = NULL;
197     }
198
199     if ( infile != NULL ) {
200         if (( fp = fopen( infile, "r" )) == NULL ) {
201             perror( infile );
202             return( EXIT_FAILURE );
203         }
204     } else {
205         fp = stdin;
206     }
207
208         if ( debug )
209                 ldif_debug = debug;
210
211         ld = tool_conn_setup( not, 0 );
212
213     if ( !not ) {
214         if ( pw_file || want_bindpw ) {
215                 if ( pw_file ) {
216                         rc = lutil_get_filed_password( pw_file, &passwd );
217                         if( rc ) return EXIT_FAILURE;
218                 } else {
219                         passwd.bv_val = getpassphrase( "Enter LDAP Password: " );
220                         passwd.bv_len = passwd.bv_val ? strlen( passwd.bv_val ) : 0;
221                 }
222         }
223
224         tool_bind( ld );
225     }
226
227     rc = 0;
228
229         if ( authzid || manageDSAit || noop )
230                 tool_server_controls( ld, NULL, 0 );
231
232         count = 0;
233         retval = 0;
234     while (( rc == 0 || contoper ) &&
235                 ( rbuf = read_one_record( fp )) != NULL ) {
236         count++;
237
238         start = rbuf;
239
240         if ( rejfp ) {
241                 len = strlen( rbuf );
242                 if (( rejbuf = (char *)ber_memalloc( len+1 )) == NULL ) {
243                         perror( "malloc" );
244                         exit( EXIT_FAILURE );
245                 }
246                 memcpy( rejbuf, rbuf, len+1 );
247         }
248
249     rc = process_ldif_rec( start, count );
250
251         if ( rc )
252                 retval = rc;
253         if ( rc && rejfp ) {
254                 fprintf(rejfp, "# Error: %s (%d)", ldap_err2string(rc), rc);
255
256                 matched_msg = NULL;
257                 ldap_get_option(ld, LDAP_OPT_MATCHED_DN, &matched_msg);
258                 if ( matched_msg != NULL ) {
259                         if ( *matched_msg != '\0' )
260                                 fprintf( rejfp, ", matched DN: %s", matched_msg );
261                         ldap_memfree( matched_msg );
262                 }
263
264                 error_msg = NULL;
265                 ldap_get_option(ld, LDAP_OPT_ERROR_STRING, &error_msg);
266                 if ( error_msg != NULL ) {
267                         if ( *error_msg != '\0' )
268                                 fprintf( rejfp, ", additional info: %s", error_msg );
269                         ldap_memfree( error_msg );
270                 }
271                 fprintf( rejfp, "\n%s\n", rejbuf );
272         }
273                 if (rejfp) 
274                         free( rejbuf );
275                 free( rbuf );
276     }
277
278     if ( !not ) {
279                 ldap_unbind( ld );
280     }
281
282     if ( rejfp != NULL ) {
283             fclose( rejfp );
284     }
285
286     return( retval );
287 }
288
289
290 static int
291 process_ldif_rec( char *rbuf, int count )
292 {
293     char        *line, *dn, *type, *newrdn, *newsup, *p;
294     int         rc, linenum, modop, replicaport;
295     int         expect_modop, expect_sep, expect_ct, expect_newrdn, expect_newsup;
296     int         expect_deleteoldrdn, deleteoldrdn;
297     int         saw_replica, use_record, new_entry, delete_entry, got_all;
298     LDAPMod     **pmods;
299         int version;
300         struct berval val;
301     LDAPControl **pctrls;
302
303     new_entry = ldapadd;
304
305     rc = got_all = saw_replica = delete_entry = modop = expect_modop = 0;
306     expect_deleteoldrdn = expect_newrdn = expect_newsup = 0;
307         expect_sep = expect_ct = 0;
308     linenum = 0;
309         version = 0;
310     deleteoldrdn = 1;
311     use_record = force;
312     pmods = NULL;
313     pctrls = NULL;
314     dn = newrdn = newsup = NULL;
315
316     while ( rc == 0 && ( line = ldif_getline( &rbuf )) != NULL ) {
317         ++linenum;
318
319         if ( expect_sep && strcasecmp( line, T_MODSEPSTR ) == 0 ) {
320             expect_sep = 0;
321             expect_ct = 1;
322             continue;
323         }
324         
325         if ( ldif_parse_line( line, &type, &val.bv_val, &val.bv_len ) < 0 ) {
326             fprintf( stderr, "%s: invalid format (line %d) entry: \"%s\"\n",
327                     prog, linenum, dn == NULL ? "" : dn );
328             rc = LDAP_PARAM_ERROR;
329             break;
330         }
331
332         if ( dn == NULL ) {
333             if ( !use_record && strcasecmp( type, T_REPLICA_STR ) == 0 ) {
334                 ++saw_replica;
335                 if (( p = strchr( val.bv_val, ':' )) == NULL ) {
336                     replicaport = 0;
337                 } else {
338                     *p++ = '\0';
339                     replicaport = atoi( p );
340                 }
341                 if ( ldaphost != NULL && strcasecmp( val.bv_val, ldaphost ) == 0 &&
342                         replicaport == ldapport ) {
343                     use_record = 1;
344                 }
345             } else if ( count == 1 && linenum == 1 && 
346                         strcasecmp( type, T_VERSION_STR ) == 0 )
347                 {
348                         if( val.bv_len == 0 || atoi(val.bv_val) != 1 ) {
349                         fprintf( stderr, "%s: invalid version %s, line %d (ignored)\n",
350                                 prog, val.bv_val, linenum );
351                         }
352                         version++;
353
354             } else if ( strcasecmp( type, T_DN_STR ) == 0 ) {
355                 if (( dn = ber_strdup( val.bv_val )) == NULL ) {
356                     perror( "strdup" );
357                     exit( EXIT_FAILURE );
358                 }
359                 expect_ct = 1;
360             }
361             goto end_line;      /* skip all lines until we see "dn:" */
362         }
363
364         if ( expect_ct ) {
365         
366         /* Check for "control" tag after dn and before changetype. */
367         if (strcasecmp(type, T_CONTROL_STR) == 0) {
368             /* Parse and add it to the list of controls */
369             rc = parse_ldif_control( line, &pctrls );
370             if (rc != 0) {
371                         fprintf( stderr, "%s: Error processing %s line, line %d: %s\n",
372                                 prog, T_CONTROL_STR, linenum, ldap_err2string(rc) );
373             }
374             goto end_line;
375         }
376         
377             expect_ct = 0;
378             if ( !use_record && saw_replica ) {
379                 printf( "%s: skipping change record for entry: %s\n"
380                         "\t(LDAP host/port does not match replica: lines)\n",
381                         prog, dn );
382                 free( dn );
383                 ber_memfree( type );
384                 ber_memfree( val.bv_val );
385                 return( 0 );
386             }
387
388             if ( strcasecmp( type, T_CHANGETYPESTR ) == 0 ) {
389 #ifdef LIBERAL_CHANGETYPE_MODOP
390                 /* trim trailing spaces (and log warning ...) */
391
392                 int icnt;
393                 for ( icnt = val.bv_len; --icnt > 0; ) {
394                     if ( !isspace( (unsigned char) val.bv_val[icnt] ) ) {
395                         break;
396                     }
397                 }
398
399                 if ( ++icnt != val.bv_len ) {
400                     fprintf( stderr, "%s: illegal trailing space after \"%s: %s\" trimmed (line %d of entry \"%s\")\n",
401                             prog, T_CHANGETYPESTR, val.bv_val, linenum, dn );
402                     val.bv_val[icnt] = '\0';
403                 }
404 #endif /* LIBERAL_CHANGETYPE_MODOP */
405
406                 if ( strcasecmp( val.bv_val, T_MODIFYCTSTR ) == 0 ) {
407                         new_entry = 0;
408                         expect_modop = 1;
409                 } else if ( strcasecmp( val.bv_val, T_ADDCTSTR ) == 0 ) {
410                         new_entry = 1;
411                 } else if ( strcasecmp( val.bv_val, T_MODRDNCTSTR ) == 0
412                         || strcasecmp( val.bv_val, T_MODDNCTSTR ) == 0
413                         || strcasecmp( val.bv_val, T_RENAMECTSTR ) == 0)
414                 {
415                     expect_newrdn = 1;
416                 } else if ( strcasecmp( val.bv_val, T_DELETECTSTR ) == 0 ) {
417                     got_all = delete_entry = 1;
418                 } else {
419                     fprintf( stderr,
420                             "%s:  unknown %s \"%s\" (line %d of entry \"%s\")\n",
421                             prog, T_CHANGETYPESTR, val.bv_val, linenum, dn );
422                     rc = LDAP_PARAM_ERROR;
423                 }
424                 goto end_line;
425             } else if ( ldapadd ) {             /*  missing changetype => add */
426                 new_entry = 1;
427                 modop = LDAP_MOD_ADD;
428             } else {
429                 expect_modop = 1;       /* missing changetype => modify */
430             }
431         }
432
433         if ( expect_modop ) {
434 #ifdef LIBERAL_CHANGETYPE_MODOP
435             /* trim trailing spaces (and log warning ...) */
436             
437             int icnt;
438             for ( icnt = val.bv_len; --icnt > 0; ) {
439                 if ( !isspace( (unsigned char) val.bv_val[icnt] ) ) {
440                     break;
441                 }
442             }
443             
444             if ( ++icnt != val.bv_len ) {
445                 fprintf( stderr, "%s: illegal trailing space after \"%s: %s\" trimmed (line %d of entry \"%s\")\n",
446                         prog, type, val.bv_val, linenum, dn );
447                 val.bv_val[icnt] = '\0';
448             }
449 #endif /* LIBERAL_CHANGETYPE_MODOP */
450
451             expect_modop = 0;
452             expect_sep = 1;
453             if ( strcasecmp( type, T_MODOPADDSTR ) == 0 ) {
454                 modop = LDAP_MOD_ADD;
455                 goto end_line;
456             } else if ( strcasecmp( type, T_MODOPREPLACESTR ) == 0 ) {
457                 modop = LDAP_MOD_REPLACE;
458                 addmodifyop( &pmods, modop, val.bv_val, NULL );
459                 goto end_line;
460             } else if ( strcasecmp( type, T_MODOPDELETESTR ) == 0 ) {
461                 modop = LDAP_MOD_DELETE;
462                 addmodifyop( &pmods, modop, val.bv_val, NULL );
463                 goto end_line;
464             } else {    /* no modify op:  use default */
465                 modop = ldapadd ? LDAP_MOD_ADD : LDAP_MOD_REPLACE;
466             }
467         }
468
469         if ( expect_newrdn ) {
470             if ( strcasecmp( type, T_NEWRDNSTR ) == 0 ) {
471                         if (( newrdn = ber_strdup( val.bv_val )) == NULL ) {
472                     perror( "strdup" );
473                     exit( EXIT_FAILURE );
474                 }
475                 expect_deleteoldrdn = 1;
476                 expect_newrdn = 0;
477             } else {
478                 fprintf( stderr, "%s: expecting \"%s:\" but saw \"%s:\" (line %d of entry \"%s\")\n",
479                         prog, T_NEWRDNSTR, type, linenum, dn );
480                 rc = LDAP_PARAM_ERROR;
481             }
482         } else if ( expect_deleteoldrdn ) {
483             if ( strcasecmp( type, T_DELETEOLDRDNSTR ) == 0 ) {
484                 deleteoldrdn = ( *val.bv_val == '0' ) ? 0 : 1;
485                 expect_deleteoldrdn = 0;
486                 expect_newsup = 1;
487                 got_all = 1;
488             } else {
489                 fprintf( stderr, "%s: expecting \"%s:\" but saw \"%s:\" (line %d of entry \"%s\")\n",
490                         prog, T_DELETEOLDRDNSTR, type, linenum, dn );
491                 rc = LDAP_PARAM_ERROR;
492             }
493         } else if ( expect_newsup ) {
494             if ( strcasecmp( type, T_NEWSUPSTR ) == 0 ) {
495                 if (( newsup = ber_strdup( val.bv_val )) == NULL ) {
496                     perror( "strdup" );
497                     exit( EXIT_FAILURE );
498                 }
499                 expect_newsup = 0;
500             } else {
501                 fprintf( stderr, "%s: expecting \"%s:\" but saw \"%s:\" (line %d of entry \"%s\")\n",
502                         prog, T_NEWSUPSTR, type, linenum, dn );
503                 rc = LDAP_PARAM_ERROR;
504             }
505         } else if ( got_all ) {
506             fprintf( stderr,
507                     "%s: extra lines at end (line %d of entry \"%s\")\n",
508                     prog, linenum, dn );
509             rc = LDAP_PARAM_ERROR;
510         } else {
511                 addmodifyop( &pmods, modop, type, &val );
512         }
513
514 end_line:
515         ber_memfree( type );
516         ber_memfree( val.bv_val );
517     }
518
519         if( linenum == 0 ) {
520                 return 0;
521         }
522
523         if( version && linenum == 1 ) {
524                 return 0;
525         }
526
527     /* If default controls are set (as with -M option) and controls are
528        specified in the LDIF file, we must add the default controls to
529        the list of controls sent with the ldap operation.
530     */
531     if ( rc == 0 ) {
532         if (pctrls) {
533             LDAPControl **defctrls = NULL;   /* Default server controls */
534             LDAPControl **newctrls = NULL;
535             ldap_get_option(ld, LDAP_OPT_SERVER_CONTROLS, &defctrls);
536             if (defctrls) {
537                 int npc=0;                  /* Number of LDIF controls */
538                 int ndefc=0;                /* Number of default controls */
539                 while (pctrls[npc])         /* Count LDIF controls */
540                     npc++; 
541                 while (defctrls[ndefc])     /* Count default controls */
542                     ndefc++;
543                 newctrls = ber_memrealloc(pctrls, (npc+ndefc+1)*sizeof(LDAPControl*));
544                 if (newctrls == NULL)
545                     rc = LDAP_NO_MEMORY;
546                 else {
547                     int i;
548                     pctrls = newctrls;
549                     for (i=npc; i<npc+ndefc; i++) {
550                         pctrls[i] = ldap_control_dup(defctrls[i-npc]);
551                         if (pctrls[i] == NULL) {
552                             rc = LDAP_NO_MEMORY;
553                             break;
554                         }
555                     }
556                     pctrls[npc+ndefc] = NULL;
557                 }
558                 ldap_controls_free(defctrls);  /* Must be freed by library */
559             }
560         }
561     }
562
563
564     if ( rc == 0 ) {
565         if ( delete_entry ) {
566             rc = dodelete( dn, pctrls );
567         } else if ( newrdn != NULL ) {
568             rc = dorename( dn, newrdn, newsup, deleteoldrdn, pctrls );
569         } else {
570             rc = domodify( dn, pmods, pctrls, new_entry );
571         }
572
573         if ( rc == LDAP_SUCCESS ) {
574             rc = 0;
575         }
576     }
577
578     if ( dn != NULL ) {
579         free( dn );
580     }
581     if ( newrdn != NULL ) {
582         free( newrdn );
583     }
584     if ( pmods != NULL ) {
585         ldap_mods_free( pmods, 1 );
586     }
587
588     if (pctrls != NULL) {
589         ldap_controls_free( pctrls );
590     }
591
592     return( rc );
593 }
594
595 /* Parse an LDIF control line of the form
596       control:  oid  [true/false]  [: value]              or
597       control:  oid  [true/false]  [:: base64-value]      or
598       control:  oid  [true/false]  [:< url]
599    The control is added to the list of controls in *ppctrls.
600 */      
601 static int
602 parse_ldif_control( char *line, 
603                     LDAPControl ***ppctrls )
604 {
605     char *oid = NULL;
606     int criticality = 0;   /* Default is false if not present */
607     char *type=NULL;
608     char *val = NULL;
609     ber_len_t value_len = 0;
610     int i, rc=0;
611     char *s, *oidStart, *pcolon;
612     LDAPControl *newctrl = NULL;
613     LDAPControl **pctrls = NULL;
614
615     if (ppctrls) {
616         pctrls = *ppctrls;
617     }
618     s = line + strlen(T_CONTROL_STR);  /* Skip over "control" */
619     pcolon = s;                        /* Save this position for later */
620     if (*s++ != ':')                   /* Make sure colon follows */
621         return ( LDAP_PARAM_ERROR );
622     while (*s && isspace(*s))  s++;    /* Skip white space before OID */
623
624     /* OID should come next. Validate and extract it. */
625     if (*s == 0)
626         return ( LDAP_PARAM_ERROR );
627     oidStart = s;
628     while (isdigit(*s) || *s == '.')  s++;    /* OID should be digits or . */
629     if (s == oidStart) 
630         return ( LDAP_PARAM_ERROR );   /* OID was not present */
631     if (*s) {                          /* End of OID should be space or NULL */
632         if (!isspace(*s))
633             return ( LDAP_PARAM_ERROR ); /* else OID contained invalid chars */
634         *s++ = 0;                    /* Replace space with null to terminate */
635     }
636
637     
638     oid = ber_strdup(oidStart);
639     if (oid == NULL)
640         return ( LDAP_NO_MEMORY );
641
642     /* Optional Criticality field is next. */
643     while (*s && isspace(*s))  s++;   /* Skip white space before criticality */
644     if (strncasecmp(s, "true", 4) == 0) {
645         criticality = 1;
646         s += 4;
647     } 
648     else if (strncasecmp(s, "false", 5) == 0) {
649         criticality = 0;
650         s += 5;
651     }
652
653     /* Optional value field is next */
654     while (*s && isspace(*s))  s++;    /* Skip white space before value */
655     if (*s) {
656         if (*s != ':') {           /* If value is present, must start with : */
657             rc = LDAP_PARAM_ERROR;
658             goto cleanup;
659         }
660
661         /* Shift value down over OID and criticality so it's in the form
662              control: value
663              control:: base64-value
664              control:< url
665            Then we can use ldif_parse_line to extract and decode the value
666         */
667         while ( (*pcolon++ = *s++) != 0)     /* Shift value */
668             ;
669         rc = ldif_parse_line(line, &type, &val, &value_len);
670         if (type)  ber_memfree(type);   /* Don't need this field*/
671         if (rc < 0) {
672             rc = LDAP_PARAM_ERROR;
673             goto cleanup;
674         }
675     }
676
677     /* Create a new LDAPControl structure. */
678     newctrl = (LDAPControl *)ber_memalloc(sizeof(LDAPControl));
679     if ( newctrl == NULL ) {
680         rc = LDAP_NO_MEMORY;
681         goto cleanup;
682     }
683     newctrl->ldctl_oid = oid;
684     oid = NULL;
685     newctrl->ldctl_iscritical = criticality;
686     newctrl->ldctl_value.bv_len = value_len;
687     newctrl->ldctl_value.bv_val = val;
688     val = NULL;
689
690     /* Add the new control to the passed-in list of controls. */
691     i = 0;
692     if (pctrls) {
693         while ( pctrls[i] )      /* Count the # of controls passed in */
694             i++;
695     }
696     /* Allocate 1 more slot for the new control and 1 for the NULL. */
697     pctrls = (LDAPControl **)ber_memrealloc(pctrls, (i+2)*(sizeof(LDAPControl *)));
698     if (pctrls == NULL) {
699         rc = LDAP_NO_MEMORY;
700         goto cleanup;
701     }
702     pctrls[i] = newctrl;
703     newctrl = NULL;
704     pctrls[i+1] = NULL;
705     *ppctrls = pctrls;
706
707 cleanup:
708     if (newctrl) {
709         if (newctrl->ldctl_oid)
710             ber_memfree(newctrl->ldctl_oid);
711         if (newctrl->ldctl_value.bv_val)
712             ber_memfree(newctrl->ldctl_value.bv_val);
713         ber_memfree(newctrl);
714     }
715     if (val)
716         ber_memfree(val);
717     if (oid)
718         ber_memfree(oid);
719
720     return( rc );
721 }
722
723
724 static void
725 addmodifyop(
726         LDAPMod ***pmodsp,
727         int modop,
728         const char *attr,
729         struct berval *val )
730 {
731         LDAPMod         **pmods;
732         int                     i, j;
733
734         pmods = *pmodsp;
735         modop |= LDAP_MOD_BVALUES;
736
737         i = 0;
738         if ( pmods != NULL ) {
739                 for ( ; pmods[ i ] != NULL; ++i ) {
740                         if ( strcasecmp( pmods[ i ]->mod_type, attr ) == 0 &&
741                                 pmods[ i ]->mod_op == modop )
742                         {
743                                 break;
744                         }
745                 }
746         }
747
748         if ( pmods == NULL || pmods[ i ] == NULL ) {
749                 if (( pmods = (LDAPMod **)ber_memrealloc( pmods, (i + 2) *
750                         sizeof( LDAPMod * ))) == NULL )
751                 {
752                         perror( "realloc" );
753                         exit( EXIT_FAILURE );
754                 }
755
756                 *pmodsp = pmods;
757                 pmods[ i + 1 ] = NULL;
758
759                 pmods[ i ] = (LDAPMod *)ber_memcalloc( 1, sizeof( LDAPMod ));
760                 if ( pmods[ i ] == NULL ) {
761                         perror( "calloc" );
762                         exit( EXIT_FAILURE );
763                 }
764
765                 pmods[ i ]->mod_op = modop;
766                 pmods[ i ]->mod_type = ber_strdup( attr );
767                 if ( pmods[ i ]->mod_type == NULL ) {
768                         perror( "strdup" );
769                         exit( EXIT_FAILURE );
770                 }
771         }
772
773         if ( val != NULL ) {
774                 j = 0;
775                 if ( pmods[ i ]->mod_bvalues != NULL ) {
776                         for ( ; pmods[ i ]->mod_bvalues[ j ] != NULL; ++j ) {
777                                 /* Empty */;
778                         }
779                 }
780
781                 pmods[ i ]->mod_bvalues = (struct berval **) ber_memrealloc(
782                         pmods[ i ]->mod_bvalues, (j + 2) * sizeof( struct berval * ));
783                 if ( pmods[ i ]->mod_bvalues == NULL ) {
784                         perror( "ber_realloc" );
785                         exit( EXIT_FAILURE );
786                 }
787
788                 pmods[ i ]->mod_bvalues[ j + 1 ] = NULL;
789                 pmods[ i ]->mod_bvalues[ j ] = ber_bvdup( val );
790                 if ( pmods[ i ]->mod_bvalues[ j ] == NULL ) {
791                         perror( "ber_bvdup" );
792                         exit( EXIT_FAILURE );
793                 }
794         }
795 }
796
797
798 static int
799 domodify(
800         const char *dn,
801         LDAPMod **pmods,
802     LDAPControl **pctrls,
803         int newentry )
804 {
805     int                 i, j, k, notascii, op;
806     struct berval       *bvp;
807
808     if ( pmods == NULL ) {
809         fprintf( stderr, "%s: no attributes to change or add (entry=\"%s\")\n",
810                 prog, dn );
811         return( LDAP_PARAM_ERROR );
812     } 
813
814     for ( i = 0; pmods[ i ] != NULL; ++i ) {
815         op = pmods[ i ]->mod_op & ~LDAP_MOD_BVALUES;
816         if( op == LDAP_MOD_ADD && ( pmods[i]->mod_bvalues == NULL )) {
817                 fprintf( stderr,
818                         "%s: attribute \"%s\" has no values (entry=\"%s\")\n",
819                         prog, pmods[i]->mod_type, dn );
820                 return LDAP_PARAM_ERROR;
821         }
822     }
823
824     if ( verbose ) {
825         for ( i = 0; pmods[ i ] != NULL; ++i ) {
826             op = pmods[ i ]->mod_op & ~LDAP_MOD_BVALUES;
827             printf( "%s %s:\n", op == LDAP_MOD_REPLACE ?
828                     "replace" : op == LDAP_MOD_ADD ?
829                     "add" : "delete", pmods[ i ]->mod_type );
830             if ( pmods[ i ]->mod_bvalues != NULL ) {
831                 for ( j = 0; pmods[ i ]->mod_bvalues[ j ] != NULL; ++j ) {
832                     bvp = pmods[ i ]->mod_bvalues[ j ];
833                     notascii = 0;
834                     for ( k = 0; (unsigned long) k < bvp->bv_len; ++k ) {
835                         if ( !isascii( bvp->bv_val[ k ] )) {
836                             notascii = 1;
837                             break;
838                         }
839                     }
840                     if ( notascii ) {
841                         printf( "\tNOT ASCII (%ld bytes)\n", bvp->bv_len );
842                     } else {
843                         printf( "\t%s\n", bvp->bv_val );
844                     }
845                 }
846             }
847         }
848     }
849
850     if ( newentry ) {
851         printf( "%sadding new entry \"%s\"\n", not ? "!" : "", dn );
852     } else {
853         printf( "%smodifying entry \"%s\"\n", not ? "!" : "", dn );
854     }
855
856     if ( !not ) {
857         if ( newentry ) {
858             i = ldap_add_ext_s( ld, dn, pmods, pctrls, NULL );
859         } else {
860             i = ldap_modify_ext_s( ld, dn, pmods, pctrls, NULL );
861         }
862         if ( i != LDAP_SUCCESS ) {
863                 /* print error message about failed update including DN */
864                 fprintf( stderr, "%s: update failed: %s\n", prog, dn );
865                 ldap_perror( ld, newentry ? "ldap_add" : "ldap_modify" );
866         } else if ( verbose ) {
867             printf( "modify complete\n" );
868         }
869     } else {
870         i = LDAP_SUCCESS;
871     }
872
873     putchar( '\n' );
874
875     return( i );
876 }
877
878
879 static int
880 dodelete(
881         const char *dn,
882     LDAPControl **pctrls )
883 {
884     int rc;
885
886     printf( "%sdeleting entry \"%s\"\n", not ? "!" : "", dn );
887     if ( !not ) {
888         if (( rc = ldap_delete_ext_s( ld, dn, pctrls, NULL )) != LDAP_SUCCESS ) {
889                 fprintf( stderr, "%s: delete failed: %s\n", prog, dn );
890                 ldap_perror( ld, "ldap_delete" );
891         } else if ( verbose ) {
892             printf( "delete complete" );
893         }
894     } else {
895         rc = LDAP_SUCCESS;
896     }
897
898     putchar( '\n' );
899
900     return( rc );
901 }
902
903
904 static int
905 dorename(
906         const char *dn,
907         const char *newrdn,
908         const char* newsup,
909         int deleteoldrdn,
910     LDAPControl **pctrls )
911 {
912     int rc;
913
914
915     printf( "%smodifying rdn of entry \"%s\"\n", not ? "!" : "", dn );
916     if ( verbose ) {
917         printf( "\tnew RDN: \"%s\" (%skeep existing values)\n",
918                 newrdn, deleteoldrdn ? "do not " : "" );
919     }
920     if ( !not ) {
921         if (( rc = ldap_rename_s( ld, dn, newrdn, newsup, deleteoldrdn, pctrls, NULL ))
922                 != LDAP_SUCCESS ) {
923                 fprintf( stderr, "%s: rename failed: %s\n", prog, dn );
924                 ldap_perror( ld, "ldap_modrdn" );
925         } else {
926             printf( "modrdn completed\n" );
927         }
928     } else {
929         rc = LDAP_SUCCESS;
930     }
931
932     putchar( '\n' );
933
934     return( rc );
935 }
936
937
938 static char *
939 read_one_record( FILE *fp )
940 {
941     char        *buf, line[ LDAPMOD_MAXLINE ];
942     int         lcur, lmax;
943
944     lcur = lmax = 0;
945     buf = NULL;
946
947     while ( fgets( line, sizeof(line), fp ) != NULL ) {
948         int len = strlen( line );
949
950                 if( len < 2 || ( len == 2 && *line == '\r' )) {
951                         if( buf == NULL ) {
952                                 continue;
953                         } else {
954                                 break;
955                         }
956                 }
957
958                 if ( lcur + len + 1 > lmax ) {
959                         lmax = LDAPMOD_MAXLINE
960                                 * (( lcur + len + 1 ) / LDAPMOD_MAXLINE + 1 );
961
962                         if (( buf = (char *)ber_memrealloc( buf, lmax )) == NULL ) {
963                                 perror( "realloc" );
964                                 exit( EXIT_FAILURE );
965                         }
966                 }
967
968                 strcpy( buf + lcur, line );
969                 lcur += len;
970     }
971
972     return( buf );
973 }
974
975