]> git.sur5r.net Git - openldap/blob - clients/tools/ldapmodify.c
Sync with HEAD
[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-2005 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 int process_response(
118         LDAP *ld,
119         int msgid,
120         const char *opstr,
121         const char *dn );
122 static char *read_one_record LDAP_P(( FILE *fp ));
123
124 #ifdef LDAP_GROUP_TRANSACTION
125 static int txn = 0;
126 static int txnabort = 0;
127 #endif
128
129 void
130 usage( void )
131 {
132         fprintf( stderr, _("Add or modify entries from an LDAP server\n\n"));
133         fprintf( stderr, _("usage: %s [options]\n"), prog);
134         fprintf( stderr, _("    The list of desired operations are read from stdin"
135                 " or from the file\n"));
136         fprintf( stderr, _("    specified by \"-f file\".\n"));
137         fprintf( stderr, _("Add or modify options:\n"));
138         fprintf( stderr, _("  -a         add values (%s)\n"),
139                 (ldapadd ? _("default") : _("default is to replace")));
140         fprintf( stderr, _("  -E [!]ext=extparam        modify extensions"
141                 " (! indicate s criticality)\n"));
142 #ifdef LDAP_GROUP_TRANSACTION
143         fprintf( stderr,
144                 _("             [!]txn                      (transaction)\n"));
145 #endif
146         fprintf( stderr, _("  -F         force all changes records to be used\n"));
147         fprintf( stderr, _("  -S file    write skipped modifications to `file'\n"));
148
149         tool_common_usage();
150         exit( EXIT_FAILURE );
151 }
152
153
154 const char options[] = "aE:FrS:"
155         "cd:D:e:f:h:H:IkKMnO:p:P:QR:U:vVw:WxX:y:Y:Z";
156
157 int
158 handle_private_option( int i )
159 {
160         char    *control, *cvalue;
161         int             crit;
162
163         switch ( i ) {
164         case 'E': /* modify extensions */
165                 if( protocol == LDAP_VERSION2 ) {
166                         fprintf( stderr, _("%s: -E incompatible with LDAPv%d\n"),
167                                 prog, protocol );
168                         exit( EXIT_FAILURE );
169                 }
170
171                 /* should be extended to support comma separated list of
172                  *      [!]key[=value] parameters, e.g.  -E !foo,bar=567
173                  */
174
175                 crit = 0;
176                 cvalue = NULL;
177                 if( optarg[0] == '!' ) {
178                         crit = 1;
179                         optarg++;
180                 }
181
182                 control = ber_strdup( optarg );
183                 if ( (cvalue = strchr( control, '=' )) != NULL ) {
184                         *cvalue++ = '\0';
185                 }
186
187 #ifdef LDAP_GROUP_TRANSACTION
188                 if( strcasecmp( control, "txn" ) == 0 ) {
189                         /* Transaction */
190                         if( txn ) {
191                                 fprintf( stderr,
192                                         _("txn control previously specified\n"));
193                                 exit( EXIT_FAILURE );
194                         }
195                         if( cvalue != NULL ) {
196                                 if( strcasecmp( cvalue, "abort" ) == 0 ) {
197                                         txnabort=1;
198                                 } else if( strcasecmp( cvalue, "commit" ) != 0 ) {
199                                         fprintf( stderr, _("Invalid value for txn control, %s\n"),
200                                                 cvalue );
201                                         exit( EXIT_FAILURE );
202                                 }
203                         }
204
205                         txn = 1 + crit;
206                 } else
207 #endif
208                 {
209                         fprintf( stderr, _("Invalid modify extension name: %s\n"),
210                                 control );
211                         usage();
212                 }
213
214         case 'a':       /* add */
215                 ldapadd = 1;
216                 break;
217
218         case 'F':       /* force all changes records to be used */
219                 force = 1;
220                 break;
221
222         case 'r':       /* replace (obsolete) */
223                 break;
224
225         case 'S':       /* skipped modifications to file */
226                 if( rejfile != NULL ) {
227                         fprintf( stderr, _("%s: -S previously specified\n"), prog );
228                         exit( EXIT_FAILURE );
229                 }
230                 rejfile = ber_strdup( optarg );
231                 break;
232
233         default:
234                 return 0;
235         }
236         return 1;
237 }
238
239
240 int
241 main( int argc, char **argv )
242 {
243 #ifdef LDAP_GROUP_TRANSACTION
244         BerElement *txnber;
245         struct berval txnCookie = { 0, NULL };
246 #endif
247         char            *rbuf, *start, *rejbuf = NULL;
248         FILE            *fp, *rejfp;
249         char            *matched_msg, *error_msg;
250         int             rc, retval;
251         int count, len;
252
253         tool_init();
254         prog = lutil_progname( "ldapmodify", argc, argv );
255
256         /* strncmp instead of strcmp since NT binaries carry .exe extension */
257         ldapadd = ( strncasecmp( prog, "ldapadd", sizeof("ldapadd")-1 ) == 0 );
258
259         tool_args( argc, argv );
260
261         if ( argc != optind ) usage();
262
263         if ( rejfile != NULL ) {
264                 if (( rejfp = fopen( rejfile, "w" )) == NULL ) {
265                         perror( rejfile );
266                         return( EXIT_FAILURE );
267                 }
268         } else {
269                 rejfp = NULL;
270         }
271
272         if ( infile != NULL ) {
273                 if (( fp = fopen( infile, "r" )) == NULL ) {
274                         perror( infile );
275                         return( EXIT_FAILURE );
276                 }
277         } else {
278                 fp = stdin;
279         }
280
281         if ( debug ) ldif_debug = debug;
282
283         ld = tool_conn_setup( not, 0 );
284
285         if ( !not ) {
286                 if ( pw_file || want_bindpw ) {
287                         if ( pw_file ) {
288                                 rc = lutil_get_filed_password( pw_file, &passwd );
289                                 if( rc ) return EXIT_FAILURE;
290                         } else {
291                                 passwd.bv_val = getpassphrase( _("Enter LDAP Password: ") );
292                                 passwd.bv_len = passwd.bv_val ? strlen( passwd.bv_val ) : 0;
293                         }
294                 }
295                 tool_bind( ld );
296         }
297
298 #ifdef LDAP_GROUP_TRANSACTION
299         if( txn ) {
300                 struct berval *txnCookiep = &txnCookie;
301
302                 /* create transaction */
303                 rc = ldap_txn_create_s( ld, &txnCookiep, NULL, NULL );
304                 if( rc != LDAP_SUCCESS ) {
305                         ldap_perror( ld, "ldap_txn_create_s" );
306                         if( txn > 2 ) return EXIT_FAILURE;
307                         txn = 0;
308                 }
309         }
310 #endif
311
312         if ( assertion || authzid || manageDSAit || noop || preread || postread
313 #ifdef LDAP_GROUP_TRANSACTION
314                 || txn
315 #endif
316                 )
317         {
318                 int err;
319                 int i = 0;
320                 LDAPControl c[1];
321
322 #ifdef LDAP_GROUP_TRANSACTION
323                 if( txn ) {
324                         txnber = ber_alloc_t( LBER_USE_DER );
325                         if( txnber == NULL ) return EXIT_FAILURE;
326
327                         err = ber_printf( txnber, "{o}", &txnCookie );
328                         if( err == -1 ) {
329                                 ber_free( txnber, 1 );
330                                 fprintf( stderr, _("txn grouping control encoding error!\n") );
331                                 return EXIT_FAILURE;
332                         }
333
334                         err = ber_flatten2( txnber, &c[i].ldctl_value, 0 );
335                         if( err == -1 ) return EXIT_FAILURE;
336
337                         c[i].ldctl_oid = LDAP_CONTROL_GROUPING;
338                         c[i].ldctl_iscritical = 1;
339                         i++;
340                 }
341 #endif
342
343                 tool_server_controls( ld, c, i );
344         }
345
346         rc = 0;
347         count = 0;
348         retval = 0;
349         while (( rc == 0 || contoper ) &&
350                 ( rbuf = read_one_record( fp )) != NULL )
351         {
352                 count++;
353
354                 start = rbuf;
355
356                 if ( rejfp ) {
357                         len = strlen( rbuf );
358                         if (( rejbuf = (char *)ber_memalloc( len+1 )) == NULL ) {
359                                 perror( "malloc" );
360                                 exit( EXIT_FAILURE );
361                         }
362                         memcpy( rejbuf, rbuf, len+1 );
363                 }
364
365                 rc = process_ldif_rec( start, count );
366
367                 if ( rc ) retval = rc;
368                 if ( rc && rejfp ) {
369                         fprintf(rejfp, _("# Error: %s (%d)"), ldap_err2string(rc), rc);
370
371                         matched_msg = NULL;
372                         ldap_get_option(ld, LDAP_OPT_MATCHED_DN, &matched_msg);
373                         if ( matched_msg != NULL ) {
374                                 if ( *matched_msg != '\0' ) {
375                                         fprintf( rejfp, _(", matched DN: %s"), matched_msg );
376                                 }
377                                 ldap_memfree( matched_msg );
378                         }
379
380                         error_msg = NULL;
381                         ldap_get_option(ld, LDAP_OPT_ERROR_STRING, &error_msg);
382                         if ( error_msg != NULL ) {
383                                 if ( *error_msg != '\0' ) {
384                                         fprintf( rejfp, _(", additional info: %s"), error_msg );
385                                 }
386                                 ldap_memfree( error_msg );
387                         }
388                         fprintf( rejfp, "\n%s\n", rejbuf );
389                 }
390
391                 if (rejfp) free( rejbuf );
392                 free( rbuf );
393         }
394
395 #ifdef LDAP_GROUP_TRANSACTION
396         if( txn ) {
397                 /* create transaction */
398                 rc = ldap_txn_end_s( ld, &txnCookie, !txnabort, NULL, NULL );
399                 if( rc != LDAP_SUCCESS ) {
400                         ldap_perror( ld, "ldap_txn_create_s" );
401                         if( txn > 2 ) return EXIT_FAILURE;
402                         txn = 0;
403                 }
404         }
405 #endif
406
407         if ( !not ) {
408                 ldap_unbind_ext( ld, NULL, NULL );
409         }
410
411         if ( rejfp != NULL ) {
412                 fclose( rejfp );
413         }
414
415         return( retval );
416 }
417
418
419 static int
420 process_ldif_rec( char *rbuf, int count )
421 {
422         char    *line, *dn, *type, *newrdn, *newsup, *p;
423         int             rc, linenum, modop, replicaport;
424         int             expect_modop, expect_sep, expect_ct, expect_newrdn, expect_newsup;
425         int             expect_deleteoldrdn, deleteoldrdn;
426         int             saw_replica, use_record, new_entry, delete_entry, got_all;
427         LDAPMod **pmods;
428         int version;
429         struct berval val;
430         LDAPControl **pctrls;
431
432         new_entry = ldapadd;
433
434         rc = got_all = saw_replica = delete_entry = modop = expect_modop = 0;
435         expect_deleteoldrdn = expect_newrdn = expect_newsup = 0;
436         expect_sep = expect_ct = 0;
437         linenum = 0;
438         version = 0;
439         deleteoldrdn = 1;
440         use_record = force;
441         pmods = NULL;
442         pctrls = NULL;
443         dn = newrdn = newsup = NULL;
444
445         while ( rc == 0 && ( line = ldif_getline( &rbuf )) != NULL ) {
446                 ++linenum;
447
448                 if ( expect_sep && strcasecmp( line, T_MODSEPSTR ) == 0 ) {
449                         expect_sep = 0;
450                         expect_ct = 1;
451                         continue;
452                 }
453         
454                 if ( ldif_parse_line( line, &type, &val.bv_val, &val.bv_len ) < 0 ) {
455                         fprintf( stderr, _("%s: invalid format (line %d) entry: \"%s\"\n"),
456                                 prog, linenum, dn == NULL ? "" : dn );
457                         rc = LDAP_PARAM_ERROR;
458                         break;
459                 }
460
461                 if ( dn == NULL ) {
462                         if ( !use_record && strcasecmp( type, T_REPLICA_STR ) == 0 ) {
463                                 ++saw_replica;
464                                 if (( p = strchr( val.bv_val, ':' )) == NULL ) {
465                                         replicaport = 0;
466                                 } else {
467                                         *p++ = '\0';
468                                         replicaport = atoi( p );
469                                 }
470                                 if ( ldaphost != NULL &&
471                                         strcasecmp( val.bv_val, ldaphost ) == 0 &&
472                                         replicaport == ldapport )
473                                 {
474                                         use_record = 1;
475                                 }
476                 } else if ( count == 1 && linenum == 1 && 
477                                 strcasecmp( type, T_VERSION_STR ) == 0 )
478                         {
479                                 if( val.bv_len == 0 || atoi(val.bv_val) != 1 ) {
480                                         fprintf( stderr,
481                                                 _("%s: invalid version %s, line %d (ignored)\n"),
482                                                 prog, val.bv_val, linenum );
483                                 }
484                                 version++;
485
486                         } else if ( strcasecmp( type, T_DN_STR ) == 0 ) {
487                                 if (( dn = ber_strdup( val.bv_val )) == NULL ) {
488                                         perror( "strdup" );
489                                         exit( EXIT_FAILURE );
490                                 }
491                                 expect_ct = 1;
492                         }
493                         goto end_line;  /* skip all lines until we see "dn:" */
494                 }
495
496                 if ( expect_ct ) {
497                         /* Check for "control" tag after dn and before changetype. */
498                         if (strcasecmp(type, T_CONTROL_STR) == 0) {
499                                 /* Parse and add it to the list of controls */
500                                 rc = parse_ldif_control( line, &pctrls );
501                                 if (rc != 0) {
502                                         fprintf( stderr,
503                                                 _("%s: Error processing %s line, line %d: %s\n"),
504                                                 prog, T_CONTROL_STR, linenum, ldap_err2string(rc) );
505                                 }
506                                 goto end_line;
507                         }
508
509                         expect_ct = 0;
510                         if ( !use_record && saw_replica ) {
511                                 printf(_("%s: skipping change record for entry: %s\n"),
512                                         prog, dn);
513                                 printf(_("\t(LDAP host/port does not match replica: lines)\n"));
514                                 free( dn );
515                                 ber_memfree( type );
516                                 ber_memfree( val.bv_val );
517                                 return( 0 );
518                         }
519
520                         if ( strcasecmp( type, T_CHANGETYPESTR ) == 0 ) {
521 #ifdef LIBERAL_CHANGETYPE_MODOP
522                                 /* trim trailing spaces (and log warning ...) */
523                                 int icnt;
524                                 for ( icnt = val.bv_len; --icnt > 0; ) {
525                                         if ( !isspace( (unsigned char) val.bv_val[icnt] ) ) {
526                                                 break;
527                                         }
528                                 }
529
530                                 if ( ++icnt != val.bv_len ) {
531                                         fprintf( stderr, _("%s: illegal trailing space after"
532                                                 " \"%s: %s\" trimmed (line %d of entry \"%s\")\n"),
533                                                 prog, T_CHANGETYPESTR, val.bv_val, linenum, dn );
534                                         val.bv_val[icnt] = '\0';
535                                 }
536 #endif /* LIBERAL_CHANGETYPE_MODOP */
537
538                                 if ( strcasecmp( val.bv_val, T_MODIFYCTSTR ) == 0 ) {
539                                         new_entry = 0;
540                                         expect_modop = 1;
541                                 } else if ( strcasecmp( val.bv_val, T_ADDCTSTR ) == 0 ) {
542                                         new_entry = 1;
543                                 } else if ( strcasecmp( val.bv_val, T_MODRDNCTSTR ) == 0
544                                         || strcasecmp( val.bv_val, T_MODDNCTSTR ) == 0
545                                         || strcasecmp( val.bv_val, T_RENAMECTSTR ) == 0)
546                                 {
547                                         expect_newrdn = 1;
548                                 } else if ( strcasecmp( val.bv_val, T_DELETECTSTR ) == 0 ) {
549                                         got_all = delete_entry = 1;
550                                 } else {
551                                         fprintf( stderr,
552                                                 _("%s:  unknown %s \"%s\" (line %d of entry \"%s\")\n"),
553                                                 prog, T_CHANGETYPESTR, val.bv_val, linenum, dn );
554                                         rc = LDAP_PARAM_ERROR;
555                                 }
556                                 goto end_line;
557                         } else if ( ldapadd ) {         /*  missing changetype => add */
558                                 new_entry = 1;
559                                 modop = LDAP_MOD_ADD;
560                         } else {
561                                 expect_modop = 1;       /* missing changetype => modify */
562                         }
563                 }
564
565                 if ( expect_modop ) {
566 #ifdef LIBERAL_CHANGETYPE_MODOP
567                         /* trim trailing spaces (and log warning ...) */
568                     int icnt;
569                     for ( icnt = val.bv_len; --icnt > 0; ) {
570                                 if ( !isspace( (unsigned char) val.bv_val[icnt] ) ) break;
571                         }
572     
573                         if ( ++icnt != val.bv_len ) {
574                                 fprintf( stderr, _("%s: illegal trailing space after"
575                                         " \"%s: %s\" trimmed (line %d of entry \"%s\")\n"),
576                                         prog, type, val.bv_val, linenum, dn );
577                                 val.bv_val[icnt] = '\0';
578                         }
579 #endif /* LIBERAL_CHANGETYPE_MODOP */
580
581                         expect_modop = 0;
582                         expect_sep = 1;
583                         if ( strcasecmp( type, T_MODOPADDSTR ) == 0 ) {
584                                 modop = LDAP_MOD_ADD;
585                                 goto end_line;
586                         } else if ( strcasecmp( type, T_MODOPREPLACESTR ) == 0 ) {
587                                 modop = LDAP_MOD_REPLACE;
588                                 addmodifyop( &pmods, modop, val.bv_val, NULL );
589                                 goto end_line;
590                         } else if ( strcasecmp( type, T_MODOPDELETESTR ) == 0 ) {
591                                 modop = LDAP_MOD_DELETE;
592                                 addmodifyop( &pmods, modop, val.bv_val, NULL );
593                                 goto end_line;
594                         } else if ( strcasecmp( type, T_MODOPINCREMENTSTR ) == 0 ) {
595                                 modop = LDAP_MOD_INCREMENT;
596                                 addmodifyop( &pmods, modop, val.bv_val, NULL );
597                                 goto end_line;
598                         } else {        /* no modify op:  use default */
599                                 modop = ldapadd ? LDAP_MOD_ADD : LDAP_MOD_REPLACE;
600                         }
601                 }
602
603                 if ( expect_newrdn ) {
604                         if ( strcasecmp( type, T_NEWRDNSTR ) == 0 ) {
605                                 if (( newrdn = ber_strdup( val.bv_val )) == NULL ) {
606                                         perror( "strdup" );
607                                         exit( EXIT_FAILURE );
608                                 }
609                                 expect_deleteoldrdn = 1;
610                                 expect_newrdn = 0;
611                         } else {
612                                 fprintf( stderr, _("%s: expecting \"%s:\" but saw"
613                                         " \"%s:\" (line %d of entry \"%s\")\n"),
614                                         prog, T_NEWRDNSTR, type, linenum, dn );
615                                 rc = LDAP_PARAM_ERROR;
616                         }
617                 } else if ( expect_deleteoldrdn ) {
618                         if ( strcasecmp( type, T_DELETEOLDRDNSTR ) == 0 ) {
619                                 deleteoldrdn = ( *val.bv_val == '0' ) ? 0 : 1;
620                                 expect_deleteoldrdn = 0;
621                                 expect_newsup = 1;
622                                 got_all = 1;
623                         } else {
624                                 fprintf( stderr, _("%s: expecting \"%s:\" but saw"
625                                         " \"%s:\" (line %d of entry \"%s\")\n"),
626                                         prog, T_DELETEOLDRDNSTR, type, linenum, dn );
627                                 rc = LDAP_PARAM_ERROR;
628                         }
629                 } else if ( expect_newsup ) {
630                         if ( strcasecmp( type, T_NEWSUPSTR ) == 0 ) {
631                                 if (( newsup = ber_strdup( val.bv_val )) == NULL ) {
632                                         perror( "strdup" );
633                                         exit( EXIT_FAILURE );
634                                 }
635                                 expect_newsup = 0;
636                         } else {
637                                 fprintf( stderr, _("%s: expecting \"%s:\" but saw"
638                                         " \"%s:\" (line %d of entry \"%s\")\n"),
639                                         prog, T_NEWSUPSTR, type, linenum, dn );
640                                 rc = LDAP_PARAM_ERROR;
641                         }
642                 } else if ( got_all ) {
643                         fprintf( stderr,
644                                 _("%s: extra lines at end (line %d of entry \"%s\")\n"),
645                                 prog, linenum, dn );
646                         rc = LDAP_PARAM_ERROR;
647                 } else {
648                         addmodifyop( &pmods, modop, type, &val );
649                 }
650
651 end_line:
652                 ber_memfree( type );
653                 ber_memfree( val.bv_val );
654         }
655
656         if( linenum == 0 ) {
657                 return 0;
658         }
659
660         if( version && linenum == 1 ) {
661                 return 0;
662         }
663
664         /* If default controls are set (as with -M option) and controls are
665            specified in the LDIF file, we must add the default controls to
666            the list of controls sent with the ldap operation.
667         */
668         if ( rc == 0 ) {
669                 if (pctrls) {
670                         LDAPControl **defctrls = NULL;   /* Default server controls */
671                         LDAPControl **newctrls = NULL;
672                         ldap_get_option(ld, LDAP_OPT_SERVER_CONTROLS, &defctrls);
673                         if (defctrls) {
674                                 int npc=0;                       /* Num of LDIF controls */
675                                 int ndefc=0;                     /* Num of default controls */
676                                 while (pctrls[npc]) npc++;       /* Count LDIF controls */
677                                 while (defctrls[ndefc]) ndefc++; /* Count default controls */
678                                 newctrls = ber_memrealloc(pctrls,
679                                         (npc+ndefc+1)*sizeof(LDAPControl*));
680
681                                 if (newctrls == NULL) {
682                                         rc = LDAP_NO_MEMORY;
683                                 } else {
684                                         int i;
685                                         pctrls = newctrls;
686                                         for (i=npc; i<npc+ndefc; i++) {
687                                                 pctrls[i] = ldap_control_dup(defctrls[i-npc]);
688                                                 if (pctrls[i] == NULL) {
689                                                         rc = LDAP_NO_MEMORY;
690                                                         break;
691                                                 }
692                                         }
693                                         pctrls[npc+ndefc] = NULL;
694                                 }
695                                 ldap_controls_free(defctrls);  /* Must be freed by library */
696                         }
697                 }
698         }
699
700
701         if ( rc == 0 ) {
702                 if ( delete_entry ) {
703                         rc = dodelete( dn, pctrls );
704                 } else if ( newrdn != NULL ) {
705                         rc = dorename( dn, newrdn, newsup, deleteoldrdn, pctrls );
706                 } else {
707                         rc = domodify( dn, pmods, pctrls, new_entry );
708                 }
709
710                 if ( rc == LDAP_SUCCESS ) {
711                         rc = 0;
712                 }
713         }
714
715         if ( dn != NULL ) {
716                 free( dn );
717         }
718         if ( newrdn != NULL ) {
719                 free( newrdn );
720         }
721         if ( pmods != NULL ) {
722                 ldap_mods_free( pmods, 1 );
723         }
724     if (pctrls != NULL) {
725         ldap_controls_free( pctrls );
726         }
727
728         return( rc );
729 }
730
731 /* Parse an LDIF control line of the form
732       control:  oid  [true/false]  [: value]              or
733       control:  oid  [true/false]  [:: base64-value]      or
734       control:  oid  [true/false]  [:< url]
735    The control is added to the list of controls in *ppctrls.
736 */      
737 static int
738 parse_ldif_control(
739         char *line, 
740         LDAPControl ***ppctrls )
741 {
742         char *oid = NULL;
743         int criticality = 0;   /* Default is false if not present */
744         char *type=NULL;
745         char *val = NULL;
746         ber_len_t value_len = 0;
747         int i, rc=0;
748         char *s, *oidStart, *pcolon;
749         LDAPControl *newctrl = NULL;
750         LDAPControl **pctrls = NULL;
751
752         if (ppctrls) pctrls = *ppctrls;
753         s = line + strlen(T_CONTROL_STR);  /* Skip over "control" */
754         pcolon = s;                        /* Save this position for later */
755         if (*s++ != ':') {                 /* Make sure colon follows */
756                 return ( LDAP_PARAM_ERROR );
757         }
758         while (*s && isspace((unsigned char)*s)) {
759                 s++;                           /* Skip white space before OID */
760         }
761
762         /* OID should come next. Validate and extract it. */
763         if (*s == 0) return ( LDAP_PARAM_ERROR );
764         oidStart = s;
765         while (isdigit((unsigned char)*s) || *s == '.') {
766                 s++;                           /* OID should be digits or . */
767         }
768         if (s == oidStart) { 
769                 return ( LDAP_PARAM_ERROR );   /* OID was not present */
770         }
771         if (*s) {                          /* End of OID should be space or NULL */
772                 if (!isspace((unsigned char)*s)) {
773                         return ( LDAP_PARAM_ERROR ); /* else OID contained invalid chars */
774                 }
775                 *s++ = 0;                    /* Replace space with null to terminate */
776         }
777
778         oid = ber_strdup(oidStart);
779         if (oid == NULL) return ( LDAP_NO_MEMORY );
780
781         /* Optional Criticality field is next. */
782         while (*s && isspace((unsigned char)*s)) {
783                 s++;                         /* Skip white space before criticality */
784         }
785         if (strncasecmp(s, "true", 4) == 0) {
786                 criticality = 1;
787                 s += 4;
788         } 
789         else if (strncasecmp(s, "false", 5) == 0) {
790                 criticality = 0;
791                 s += 5;
792         }
793
794         /* Optional value field is next */
795         while (*s && isspace((unsigned char)*s)) {
796                 s++;                         /* Skip white space before value */
797         }
798         if (*s) {
799                 if (*s != ':') {           /* If value is present, must start with : */
800                         rc = LDAP_PARAM_ERROR;
801                         goto cleanup;
802                 }
803
804                 /* Shift value down over OID and criticality so it's in the form
805                      control: value
806                      control:: base64-value
807                      control:< url
808                    Then we can use ldif_parse_line to extract and decode the value
809                 */
810                 while ( (*pcolon++ = *s++) != 0) {   /* Shift value */
811                         /* EMPTY */;
812                 }
813                 rc = ldif_parse_line(line, &type, &val, &value_len);
814                 if (type)  ber_memfree(type);   /* Don't need this field*/
815                 if (rc < 0) {
816                         rc = LDAP_PARAM_ERROR;
817                         goto cleanup;
818                 }
819     }
820
821         /* Create a new LDAPControl structure. */
822         newctrl = (LDAPControl *)ber_memalloc(sizeof(LDAPControl));
823         if ( newctrl == NULL ) {
824                 rc = LDAP_NO_MEMORY;
825                 goto cleanup;
826         }
827         newctrl->ldctl_oid = oid;
828         oid = NULL;
829         newctrl->ldctl_iscritical = criticality;
830         newctrl->ldctl_value.bv_len = value_len;
831         newctrl->ldctl_value.bv_val = val;
832         val = NULL;
833
834         /* Add the new control to the passed-in list of controls. */
835         i = 0;
836         if (pctrls) {
837                 while ( pctrls[i] ) {    /* Count the # of controls passed in */
838                         i++;
839                 }
840         }
841         /* Allocate 1 more slot for the new control and 1 for the NULL. */
842         pctrls = (LDAPControl **) ber_memrealloc(pctrls,
843                 (i+2)*(sizeof(LDAPControl *)));
844         if (pctrls == NULL) {
845                 rc = LDAP_NO_MEMORY;
846                 goto cleanup;
847         }
848         pctrls[i] = newctrl;
849         newctrl = NULL;
850         pctrls[i+1] = NULL;
851         *ppctrls = pctrls;
852
853 cleanup:
854         if (newctrl) {
855                 if (newctrl->ldctl_oid) ber_memfree(newctrl->ldctl_oid);
856                 if (newctrl->ldctl_value.bv_val) {
857                         ber_memfree(newctrl->ldctl_value.bv_val);
858                 }
859                 ber_memfree(newctrl);
860         }
861         if (val) ber_memfree(val);
862         if (oid) ber_memfree(oid);
863
864         return( rc );
865 }
866
867
868 static void
869 addmodifyop(
870         LDAPMod ***pmodsp,
871         int modop,
872         const char *attr,
873         struct berval *val )
874 {
875         LDAPMod         **pmods;
876         int                     i, j;
877
878         pmods = *pmodsp;
879         modop |= LDAP_MOD_BVALUES;
880
881         i = 0;
882         if ( pmods != NULL ) {
883                 for ( ; pmods[ i ] != NULL; ++i ) {
884                         if ( strcasecmp( pmods[ i ]->mod_type, attr ) == 0 &&
885                                 pmods[ i ]->mod_op == modop )
886                         {
887                                 break;
888                         }
889                 }
890         }
891
892         if ( pmods == NULL || pmods[ i ] == NULL ) {
893                 if (( pmods = (LDAPMod **)ber_memrealloc( pmods, (i + 2) *
894                         sizeof( LDAPMod * ))) == NULL )
895                 {
896                         perror( "realloc" );
897                         exit( EXIT_FAILURE );
898                 }
899
900                 *pmodsp = pmods;
901                 pmods[ i + 1 ] = NULL;
902
903                 pmods[ i ] = (LDAPMod *)ber_memcalloc( 1, sizeof( LDAPMod ));
904                 if ( pmods[ i ] == NULL ) {
905                         perror( "calloc" );
906                         exit( EXIT_FAILURE );
907                 }
908
909                 pmods[ i ]->mod_op = modop;
910                 pmods[ i ]->mod_type = ber_strdup( attr );
911                 if ( pmods[ i ]->mod_type == NULL ) {
912                         perror( "strdup" );
913                         exit( EXIT_FAILURE );
914                 }
915         }
916
917         if ( val != NULL ) {
918                 j = 0;
919                 if ( pmods[ i ]->mod_bvalues != NULL ) {
920                         for ( ; pmods[ i ]->mod_bvalues[ j ] != NULL; ++j ) {
921                                 /* Empty */;
922                         }
923                 }
924
925                 pmods[ i ]->mod_bvalues = (struct berval **) ber_memrealloc(
926                         pmods[ i ]->mod_bvalues, (j + 2) * sizeof( struct berval * ));
927                 if ( pmods[ i ]->mod_bvalues == NULL ) {
928                         perror( "ber_realloc" );
929                         exit( EXIT_FAILURE );
930                 }
931
932                 pmods[ i ]->mod_bvalues[ j + 1 ] = NULL;
933                 pmods[ i ]->mod_bvalues[ j ] = ber_bvdup( val );
934                 if ( pmods[ i ]->mod_bvalues[ j ] == NULL ) {
935                         perror( "ber_bvdup" );
936                         exit( EXIT_FAILURE );
937                 }
938         }
939 }
940
941
942 static int
943 domodify(
944         const char *dn,
945         LDAPMod **pmods,
946         LDAPControl **pctrls,
947         int newentry )
948 {
949         int                     rc, i, j, k, notascii, op;
950         struct berval   *bvp;
951
952         if ( dn == NULL ) {
953                 fprintf( stderr, _("%s: no DN specified\n"), prog );
954                 return( LDAP_PARAM_ERROR );
955         }
956
957         if ( pmods == NULL ) {
958                 fprintf( stderr,
959                         _("%s: no attributes to change or add (entry=\"%s\")\n"),
960                         prog, dn );
961                 return( LDAP_PARAM_ERROR );
962         } 
963
964         for ( i = 0; pmods[ i ] != NULL; ++i ) {
965                 op = pmods[ i ]->mod_op & ~LDAP_MOD_BVALUES;
966                 if( op == LDAP_MOD_ADD && ( pmods[i]->mod_bvalues == NULL )) {
967                         fprintf( stderr,
968                                 _("%s: attribute \"%s\" has no values (entry=\"%s\")\n"),
969                                 prog, pmods[i]->mod_type, dn );
970                         return LDAP_PARAM_ERROR;
971                 }
972         }
973
974         if ( verbose ) {
975                 for ( i = 0; pmods[ i ] != NULL; ++i ) {
976                         op = pmods[ i ]->mod_op & ~LDAP_MOD_BVALUES;
977                         printf( "%s %s:\n",
978                                 op == LDAP_MOD_REPLACE ? _("replace") :
979                                         op == LDAP_MOD_ADD ?  _("add") :
980                                                 op == LDAP_MOD_INCREMENT ?  _("increment") :
981                                                         op == LDAP_MOD_DELETE ?  _("delete") :
982                                                                 _("unknown"),
983                                 pmods[ i ]->mod_type );
984
985                         if ( pmods[ i ]->mod_bvalues != NULL ) {
986                                 for ( j = 0; pmods[ i ]->mod_bvalues[ j ] != NULL; ++j ) {
987                                         bvp = pmods[ i ]->mod_bvalues[ j ];
988                                         notascii = 0;
989                                         for ( k = 0; (unsigned long) k < bvp->bv_len; ++k ) {
990                                                 if ( !isascii( bvp->bv_val[ k ] )) {
991                                                         notascii = 1;
992                                                         break;
993                                                 }
994                                         }
995                                         if ( notascii ) {
996                                                 printf( _("\tNOT ASCII (%ld bytes)\n"), bvp->bv_len );
997                                         } else {
998                                                 printf( "\t%s\n", bvp->bv_val );
999                                         }
1000                                 }
1001                         }
1002                 }
1003         }
1004
1005         if ( newentry ) {
1006                 printf( "%sadding new entry \"%s\"\n", not ? "!" : "", dn );
1007         } else {
1008                 printf( "%smodifying entry \"%s\"\n", not ? "!" : "", dn );
1009         }
1010
1011         if ( !not ) {
1012                 int msgid;
1013                 if ( newentry ) {
1014                         rc = ldap_add_ext( ld, dn, pmods, pctrls, NULL, &msgid );
1015                 } else {
1016                         rc = ldap_modify_ext( ld, dn, pmods, pctrls, NULL, &msgid );
1017                 }
1018
1019                 if ( rc != LDAP_SUCCESS ) {
1020                         /* print error message about failed update including DN */
1021                         fprintf( stderr, _("%s: update failed: %s\n"), prog, dn );
1022                         ldap_perror( ld, newentry ? "ldap_add" : "ldap_modify" );
1023                         goto done;
1024                 } else if ( verbose ) {
1025                         printf( _("modify complete\n") );
1026                 }
1027
1028                 rc = process_response( ld, msgid,
1029                         newentry ? "ldap_add" : "ldap_modify", dn );
1030
1031         } else {
1032                 rc = LDAP_SUCCESS;
1033         }
1034
1035 done:
1036         putchar( '\n' );
1037         return rc;
1038 }
1039
1040
1041 static int
1042 dodelete(
1043         const char *dn,
1044         LDAPControl **pctrls )
1045 {
1046         int     rc;
1047         int msgid;
1048
1049         printf( _("%sdeleting entry \"%s\"\n"), not ? "!" : "", dn );
1050         if ( !not ) {
1051                 rc = ldap_delete_ext( ld, dn, pctrls, NULL, &msgid );
1052                 if ( rc != LDAP_SUCCESS ) {
1053                         fprintf( stderr, _("%s: delete failed: %s\n"), prog, dn );
1054                         ldap_perror( ld, "ldap_delete" );
1055                         goto done;
1056                 } else if ( verbose ) {
1057                         printf( _("delete complete") );
1058                 }
1059
1060                 rc = process_response( ld, msgid, "ldap_delete", dn );
1061
1062         } else {
1063                 rc = LDAP_SUCCESS;
1064         }
1065
1066 done:
1067         putchar( '\n' );
1068         return( rc );
1069 }
1070
1071
1072 static int
1073 dorename(
1074         const char *dn,
1075         const char *newrdn,
1076         const char* newsup,
1077         int deleteoldrdn,
1078         LDAPControl **pctrls )
1079 {
1080         int     rc;
1081         int msgid;
1082
1083         printf( _("%smodifying rdn of entry \"%s\"\n"), not ? "!" : "", dn );
1084         if ( verbose ) {
1085                 printf( _("\tnew RDN: \"%s\" (%skeep existing values)\n"),
1086                         newrdn, deleteoldrdn ? _("do not ") : "" );
1087         }
1088         if ( !not ) {
1089                 rc = ldap_rename( ld, dn, newrdn, newsup, deleteoldrdn,
1090                         pctrls, NULL, &msgid );
1091                 if ( rc != LDAP_SUCCESS ) {
1092                         fprintf( stderr, _("%s: rename failed: %s\n"), prog, dn );
1093                         ldap_perror( ld, "ldap_modrdn" );
1094                         goto done;
1095                 } else {
1096                         printf( _("modrdn completed\n") );
1097                 }
1098
1099                 rc = process_response( ld, msgid, "ldap_rename", dn );
1100
1101         } else {
1102                 rc = LDAP_SUCCESS;
1103         }
1104
1105 done:
1106         putchar( '\n' );
1107         return( rc );
1108 }
1109
1110 static int process_response(
1111         LDAP *ld,
1112         int msgid,
1113         const char *opstr,
1114         const char *dn )
1115 {
1116         LDAPMessage *res;
1117         int rc = LDAP_OTHER;
1118
1119         if( ldap_result( ld, msgid,
1120 #ifdef LDAP_GROUP_TRANSACTION
1121                 txn ? 0 : 1,
1122 #else
1123                 1,
1124 #endif
1125                 NULL, &res ) == -1 ) {
1126                 ldap_get_option( ld, LDAP_OPT_ERROR_NUMBER, &rc );
1127                 return rc;
1128         }
1129
1130         if( ldap_msgtype( res ) != LDAP_RES_INTERMEDIATE ) {
1131                 rc = ldap_result2error( ld, res, 1 );
1132                 if( rc != LDAP_SUCCESS ) ldap_perror( ld, opstr );
1133                 return rc;
1134         }
1135
1136 #ifdef LDAP_GROUP_TRANSACTION
1137         /* assume (successful) transaction intermediate response */
1138         return LDAP_SUCCESS;
1139
1140 #else
1141         /* intermediate response? */
1142         return LDAP_DECODING_ERROR;
1143 #endif
1144 }
1145
1146 static char *
1147 read_one_record( FILE *fp )
1148 {
1149         char        *buf, line[ LDAPMOD_MAXLINE ];
1150         int             lcur, lmax;
1151
1152         lcur = lmax = 0;
1153         buf = NULL;
1154
1155         while ( fgets( line, sizeof(line), fp ) != NULL ) {
1156                 int len = strlen( line );
1157
1158                 if( len < 2 || ( len == 2 && *line == '\r' )) {
1159                         if( buf == NULL ) {
1160                                 continue;
1161                         } else {
1162                                 break;
1163                         }
1164                 }
1165
1166                 if ( lcur + len + 1 > lmax ) {
1167                         lmax = LDAPMOD_MAXLINE
1168                                 * (( lcur + len + 1 ) / LDAPMOD_MAXLINE + 1 );
1169
1170                         if (( buf = (char *)ber_memrealloc( buf, lmax )) == NULL ) {
1171                                 perror( "realloc" );
1172                                 exit( EXIT_FAILURE );
1173                         }
1174                 }
1175
1176                 strcpy( buf + lcur, line );
1177                 lcur += len;
1178         }
1179
1180         return( buf );
1181 }
1182
1183