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