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