]> git.sur5r.net Git - openldap/blob - clients/tools/ldapmodify.c
ITS#6428
[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-2009 The OpenLDAP Foundation.
6  * Portions Copyright 2006 Howard Chu.
7  * Portions Copyright 1998-2003 Kurt D. Zeilenga.
8  * Portions Copyright 1998-2001 Net Boolean Incorporated.
9  * Portions Copyright 2001-2003 IBM Corporation.
10  * All rights reserved.
11  *
12  * Redistribution and use in source and binary forms, with or without
13  * modification, are permitted only as authorized by the OpenLDAP
14  * Public License.
15  *
16  * A copy of this license is available in the file LICENSE in the
17  * top-level directory of the distribution or, alternatively, at
18  * <http://www.OpenLDAP.org/license.html>.
19  */
20 /* Portions Copyright (c) 1992-1996 Regents of the University of Michigan.
21  * All rights reserved.
22  *
23  * Redistribution and use in source and binary forms are permitted
24  * provided that this notice is preserved and that due credit is given
25  * to the University of Michigan at Ann Arbor.  The name of the
26  * University may not be used to endorse or promote products derived
27  * from this software without specific prior written permission.  This
28  * software is provided ``as is'' without express or implied warranty.
29  */
30 /* ACKNOWLEDGEMENTS:
31  * This work was originally developed by the University of Michigan
32  * (as part of U-MICH LDAP).  Additional significant contributors
33  * include:
34  *   Kurt D. Zeilenga
35  *   Norbert Klasen
36  *   Howard Chu
37  */
38
39 #include "portable.h"
40
41 #include <stdio.h>
42
43 #include <ac/stdlib.h>
44 #include <ac/ctype.h>
45 #include <ac/string.h>
46 #include <ac/unistd.h>
47 #include <ac/socket.h>
48 #include <ac/time.h>
49
50 #ifdef HAVE_SYS_STAT_H
51 #include <sys/stat.h>
52 #endif
53
54 #ifdef HAVE_SYS_FILE_H
55 #include <sys/file.h>
56 #endif
57 #ifdef HAVE_FCNTL_H
58 #include <fcntl.h>
59 #endif
60
61 #include <ldap.h>
62
63 #include "lutil.h"
64 #include "lutil_ldap.h"
65 #include "ldif.h"
66 #include "ldap_defaults.h"
67 #include "ldap_log.h"
68 #include "ldap_pvt.h"
69 #include "lber_pvt.h"
70
71 #include "common.h"
72
73 static int      ldapadd;
74 static char *rejfile = NULL;
75 static LDAP     *ld = NULL;
76
77 #define M_SEP   0x7f
78
79 /* strings found in LDIF entries */
80 static struct berval BV_VERSION = BER_BVC("version");
81 static struct berval BV_DN = BER_BVC("dn");
82 static struct berval BV_CONTROL = BER_BVC("control");
83 static struct berval BV_CHANGETYPE = BER_BVC("changetype");
84 static struct berval BV_ADDCT = BER_BVC("add");
85 static struct berval BV_MODIFYCT = BER_BVC("modify");
86 static struct berval BV_DELETECT = BER_BVC("delete");
87 static struct berval BV_MODRDNCT = BER_BVC("modrdn");
88 static struct berval BV_MODDNCT = BER_BVC("moddn");
89 static struct berval BV_RENAMECT = BER_BVC("rename");
90 static struct berval BV_MODOPADD = BER_BVC("add");
91 static struct berval BV_MODOPREPLACE = BER_BVC("replace");
92 static struct berval BV_MODOPDELETE = BER_BVC("delete");
93 static struct berval BV_MODOPINCREMENT = BER_BVC("increment");
94 static struct berval BV_NEWRDN = BER_BVC("newrdn");
95 static struct berval BV_DELETEOLDRDN = BER_BVC("deleteoldrdn");
96 static struct berval BV_NEWSUP = BER_BVC("newsuperior");
97
98 #define BV_CASEMATCH(a, b) \
99         ((a)->bv_len == (b)->bv_len && 0 == strcasecmp((a)->bv_val, (b)->bv_val))
100
101 static int process_ldif_rec LDAP_P(( char *rbuf, int lineno ));
102 static int parse_ldif_control LDAP_P(( struct berval *val, LDAPControl ***pctrls ));
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         int res,
121         const char *dn );
122
123 #ifdef LDAP_X_TXN
124 static int txn = 0;
125 static int txnabort = 0;
126 struct berval *txn_id = NULL;
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, _("  -c         continuous operation mode (do not stop on errors)\n"));
141         fprintf( stderr, _("  -E [!]ext=extparam        modify extensions"
142                 " (! indicate s criticality)\n"));
143         fprintf( stderr, _("  -f file    read operations from `file'\n"));
144         fprintf( stderr, _("  -M         enable Manage DSA IT control (-MM to make critical)\n"));
145         fprintf( stderr, _("  -P version protocol version (default: 3)\n"));
146 #ifdef LDAP_X_TXN
147         fprintf( stderr,
148                 _("             [!]txn=<commit|abort>         (transaction)\n"));
149 #endif
150         fprintf( stderr, _("  -S file    write skipped modifications to `file'\n"));
151
152         tool_common_usage();
153         exit( EXIT_FAILURE );
154 }
155
156
157 const char options[] = "aE:rS:"
158         "cd:D:e:f:h:H:IMnNO:o:p:P:QR:U:vVw:WxX:y:Y:Z";
159
160 int
161 handle_private_option( int i )
162 {
163         char    *control, *cvalue;
164         int             crit;
165
166         switch ( i ) {
167         case 'E': /* modify extensions */
168                 if( protocol == LDAP_VERSION2 ) {
169                         fprintf( stderr, _("%s: -E incompatible with LDAPv%d\n"),
170                                 prog, protocol );
171                         exit( EXIT_FAILURE );
172                 }
173
174                 /* should be extended to support comma separated list of
175                  *      [!]key[=value] parameters, e.g.  -E !foo,bar=567
176                  */
177
178                 crit = 0;
179                 cvalue = NULL;
180                 if( optarg[0] == '!' ) {
181                         crit = 1;
182                         optarg++;
183                 }
184
185                 control = ber_strdup( optarg );
186                 if ( (cvalue = strchr( control, '=' )) != NULL ) {
187                         *cvalue++ = '\0';
188                 }
189
190 #ifdef LDAP_X_TXN
191                 if( strcasecmp( control, "txn" ) == 0 ) {
192                         /* Transaction */
193                         if( txn ) {
194                                 fprintf( stderr,
195                                         _("txn control previously specified\n"));
196                                 exit( EXIT_FAILURE );
197                         }
198                         if( cvalue != NULL ) {
199                                 if( strcasecmp( cvalue, "abort" ) == 0 ) {
200                                         txnabort=1;
201                                 } else if( strcasecmp( cvalue, "commit" ) != 0 ) {
202                                         fprintf( stderr, _("Invalid value for txn control, %s\n"),
203                                                 cvalue );
204                                         exit( EXIT_FAILURE );
205                                 }
206                         }
207
208                         txn = 1 + crit;
209                 } else
210 #endif
211                 {
212                         fprintf( stderr, _("Invalid modify extension name: %s\n"),
213                                 control );
214                         usage();
215                 }
216                 break;
217
218         case 'a':       /* add */
219                 ldapadd = 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         char            *rbuf = NULL, *rejbuf = NULL;
244         FILE            *rejfp;
245         struct LDIFFP *ldiffp, ldifdummy = {0};
246         char            *matched_msg, *error_msg;
247         int             rc, retval, ldifrc;
248         int             len;
249         int             i = 0;
250         int             lineno, nextline = 0, lmax = 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 (( ldiffp = ldif_open( infile, "r" )) == NULL ) {
275                         perror( infile );
276                         return( EXIT_FAILURE );
277                 }
278         } else {
279                 ldifdummy.fp = stdin;
280                 ldiffp = &ldifdummy;
281         }
282
283         if ( debug ) ldif_debug = debug;
284
285         ld = tool_conn_setup( dont, 0 );
286
287         if ( !dont ) {
288                 if ( pw_file || want_bindpw ) {
289                         if ( pw_file ) {
290                                 rc = lutil_get_filed_password( pw_file, &passwd );
291                                 if( rc ) return EXIT_FAILURE;
292                         } else {
293                                 passwd.bv_val = getpassphrase( _("Enter LDAP Password: ") );
294                                 passwd.bv_len = passwd.bv_val ? strlen( passwd.bv_val ) : 0;
295                         }
296                 }
297                 tool_bind( ld );
298         }
299
300 #ifdef LDAP_X_TXN
301         if( txn ) {
302                 /* start transaction */
303                 rc = ldap_txn_start_s( ld, NULL, NULL, &txn_id );
304                 if( rc != LDAP_SUCCESS ) {
305                         tool_perror( "ldap_txn_start_s", rc, NULL, NULL, NULL, NULL );
306                         if( txn > 1 ) return EXIT_FAILURE;
307                         txn = 0;
308                 }
309         }
310 #endif
311
312         if ( 0
313 #ifdef LDAP_X_TXN
314                 || txn
315 #endif
316                 )
317         {
318 #ifdef LDAP_X_TXN
319                 if( txn ) {
320                         c[i].ldctl_oid = LDAP_CONTROL_X_TXN_SPEC;
321                         c[i].ldctl_value = *txn_id;
322                         c[i].ldctl_iscritical = 1;
323                         i++;
324                 }
325 #endif
326         }
327
328         tool_server_controls( ld, c, i );
329
330         rc = 0;
331         retval = 0;
332         lineno = 1;
333         while (( rc == 0 || contoper ) && ( ldifrc = ldif_read_record( ldiffp, &nextline,
334                 &rbuf, &lmax )) > 0 )
335         {
336                 if ( rejfp ) {
337                         len = strlen( rbuf );
338                         if (( rejbuf = (char *)ber_memalloc( len+1 )) == NULL ) {
339                                 perror( "malloc" );
340                                 exit( EXIT_FAILURE );
341                         }
342                         memcpy( rejbuf, rbuf, len+1 );
343                 }
344
345                 rc = process_ldif_rec( rbuf, lineno );
346                 lineno = nextline+1;
347
348                 if ( rc ) retval = rc;
349                 if ( rc && rejfp ) {
350                         fprintf(rejfp, _("# Error: %s (%d)"), ldap_err2string(rc), rc);
351
352                         matched_msg = NULL;
353                         ldap_get_option(ld, LDAP_OPT_MATCHED_DN, &matched_msg);
354                         if ( matched_msg != NULL ) {
355                                 if ( *matched_msg != '\0' ) {
356                                         fprintf( rejfp, _(", matched DN: %s"), matched_msg );
357                                 }
358                                 ldap_memfree( matched_msg );
359                         }
360
361                         error_msg = NULL;
362                         ldap_get_option(ld, LDAP_OPT_DIAGNOSTIC_MESSAGE, &error_msg);
363                         if ( error_msg != NULL ) {
364                                 if ( *error_msg != '\0' ) {
365                                         fprintf( rejfp, _(", additional info: %s"), error_msg );
366                                 }
367                                 ldap_memfree( error_msg );
368                         }
369                         fprintf( rejfp, "\n%s\n", rejbuf );
370                 }
371
372                 if (rejfp) ber_memfree( rejbuf );
373         }
374         ber_memfree( rbuf );
375
376         if ( ldifrc < 0 )
377                 retval = LDAP_OTHER;
378
379 #ifdef LDAP_X_TXN
380         if( retval == 0 && txn ) {
381                 rc = ldap_set_option( ld, LDAP_OPT_SERVER_CONTROLS, NULL );
382                 if ( rc != LDAP_OPT_SUCCESS ) {
383                         fprintf( stderr, "Could not unset controls for ldap_txn_end\n");
384                 }
385
386                 /* create transaction */
387                 rc = ldap_txn_end_s( ld, !txnabort, txn_id, NULL, NULL, NULL );
388                 if( rc != LDAP_SUCCESS ) {
389                         tool_perror( "ldap_txn_end_s", rc, NULL, NULL, NULL, NULL );
390                         retval = rc;
391                 }
392         }
393 #endif
394
395         if ( !dont ) {
396                 tool_unbind( ld );
397         }
398
399         if ( rejfp != NULL ) {
400                 fclose( rejfp );
401         }
402
403         tool_destroy();
404         return( retval );
405 }
406
407
408 static int
409 process_ldif_rec( char *rbuf, int linenum )
410 {
411         char    *line, *dn, *newrdn, *newsup;
412         int             rc, modop;
413         int             expect_modop, expect_sep;
414         int             deleteoldrdn;
415         int             new_entry, delete_entry, got_all;
416         LDAPMod **pmods, *lm = NULL;
417         int version;
418         LDAPControl **pctrls;
419         int i, j, k, lines, idn, nmods;
420         struct berval *btype, *vals, **bvl, bv;
421         char *freeval;
422         unsigned char *mops = NULL;
423
424         new_entry = ldapadd;
425
426         rc = got_all = delete_entry = modop = expect_modop = 0;
427         expect_sep = 0;
428         version = 0;
429         deleteoldrdn = 1;
430         pmods = NULL;
431         pctrls = NULL;
432         dn = newrdn = newsup = NULL;
433
434         lines = ldif_countlines( rbuf );
435         btype = ber_memcalloc( 1, (lines+1)*2*sizeof(struct berval)+lines );
436         if ( !btype )
437                 return LDAP_NO_MEMORY;
438
439         vals = btype+lines+1;
440         freeval = (char *)(vals+lines+1);
441         i = -1;
442
443         while ( rc == 0 && ( line = ldif_getline( &rbuf )) != NULL ) {
444                 int freev;
445
446                 if ( *line == '\n' || *line == '\0' ) {
447                         break;
448                 }
449
450                 ++i;
451
452                 if ( line[0] == '-' && !line[1] ) {
453                         BER_BVZERO( btype+i );
454                         freeval[i] = 0;
455                         continue;
456                 }
457         
458                 if ( ( rc = ldif_parse_line2( line, btype+i, vals+i, &freev ) ) < 0 ) {
459                         fprintf( stderr, _("%s: invalid format (line %d) entry: \"%s\"\n"),
460                                 prog, linenum+i, dn == NULL ? "" : dn );
461                         rc = LDAP_PARAM_ERROR;
462                         break;
463                 }
464                 freeval[i] = freev;
465
466                 if ( dn == NULL ) {
467                         if ( linenum+i == 1 && BV_CASEMATCH( btype+i, &BV_VERSION )) {
468                                 int     v;
469                                 if( vals[i].bv_len == 0 || lutil_atoi( &v, vals[i].bv_val) != 0 || v != 1 ) {
470                                         fprintf( stderr,
471                                                 _("%s: invalid version %s, line %d (ignored)\n"),
472                                                 prog, vals[i].bv_val, linenum );
473                                 }
474                                 version++;
475
476                         } else if ( BV_CASEMATCH( btype+i, &BV_DN )) {
477                                 dn = vals[i].bv_val;
478                                 idn = i;
479                         }
480                         /* skip all lines until we see "dn:" */
481                 }
482         }
483
484         /* check to make sure there was a dn: line */
485         if ( !dn ) {
486                 rc = 0;
487                 goto leave;
488         }
489
490         lines = i+1;
491
492         if( lines == 0 ) {
493                 rc = 0;
494                 goto leave;
495         }
496
497         if( version && lines == 1 ) {
498                 rc = 0;
499                 goto leave;
500         }
501
502         i = idn+1;
503         /* Check for "control" tag after dn and before changetype. */
504         if ( BV_CASEMATCH( btype+i, &BV_CONTROL )) {
505                 /* Parse and add it to the list of controls */
506                 rc = parse_ldif_control( vals+i, &pctrls );
507                 if (rc != 0) {
508                         fprintf( stderr,
509                                 _("%s: Error processing %s line, line %d: %s\n"),
510                                 prog, BV_CONTROL.bv_val, linenum+i, ldap_err2string(rc) );
511                 }
512                 i++;
513                 if ( i>= lines ) {
514 short_input:
515                         fprintf( stderr,
516                                 _("%s: Expecting more input after %s line, line %d\n"),
517                                 prog, btype[i-1].bv_val, linenum+i );
518                         
519                         rc = LDAP_PARAM_ERROR;
520                         goto leave;
521                 }
522         }
523
524         /* Check for changetype */
525         if ( BV_CASEMATCH( btype+i, &BV_CHANGETYPE )) {
526 #ifdef LIBERAL_CHANGETYPE_MODOP
527                 /* trim trailing spaces (and log warning ...) */
528                 int icnt;
529                 for ( icnt = vals[i].bv_len; --icnt > 0; ) {
530                         if ( !isspace( (unsigned char) vals[i].bv_val[icnt] ) ) {
531                                 break;
532                         }
533                 }
534
535                 if ( ++icnt != vals[i].bv_len ) {
536                         fprintf( stderr, _("%s: illegal trailing space after"
537                                 " \"%s: %s\" trimmed (line %d, entry \"%s\")\n"),
538                                 prog, BV_CHANGETYPE.bv_val, vals[i].bv_val, linenum+i, dn );
539                         vals[i].bv_val[icnt] = '\0';
540                 }
541 #endif /* LIBERAL_CHANGETYPE_MODOP */
542
543                 if ( BV_CASEMATCH( vals+i, &BV_MODIFYCT )) {
544                         new_entry = 0;
545                         expect_modop = 1;
546                 } else if ( BV_CASEMATCH( vals+i, &BV_ADDCT )) {
547                         new_entry = 1;
548                         modop = LDAP_MOD_ADD;
549                 } else if ( BV_CASEMATCH( vals+i, &BV_MODRDNCT )
550                         || BV_CASEMATCH( vals+i, &BV_MODDNCT )
551                         || BV_CASEMATCH( vals+i, &BV_RENAMECT ))
552                 {
553                         i++;
554                         if ( i >= lines )
555                                 goto short_input;
556                         if ( !BV_CASEMATCH( btype+i, &BV_NEWRDN )) {
557                                 fprintf( stderr, _("%s: expecting \"%s:\" but saw"
558                                         " \"%s:\" (line %d, entry \"%s\")\n"),
559                                         prog, BV_NEWRDN.bv_val, btype[i].bv_val, linenum+i, dn );
560                                 rc = LDAP_PARAM_ERROR;
561                                 goto leave;
562                         }
563                         newrdn = vals[i].bv_val;
564                         i++;
565                         if ( i >= lines )
566                                 goto short_input;
567                         if ( !BV_CASEMATCH( btype+i, &BV_DELETEOLDRDN )) {
568                                 fprintf( stderr, _("%s: expecting \"%s:\" but saw"
569                                         " \"%s:\" (line %d, entry \"%s\")\n"),
570                                         prog, BV_DELETEOLDRDN.bv_val, btype[i].bv_val, linenum+i, dn );
571                                 rc = LDAP_PARAM_ERROR;
572                                 goto leave;
573                         }
574                         deleteoldrdn = ( vals[i].bv_val[0] == '0' ) ? 0 : 1;
575                         i++;
576                         if ( i < lines ) {
577                                 if ( !BV_CASEMATCH( btype+i, &BV_NEWSUP )) {
578                                         fprintf( stderr, _("%s: expecting \"%s:\" but saw"
579                                                 " \"%s:\" (line %d, entry \"%s\")\n"),
580                                                 prog, BV_NEWSUP.bv_val, btype[i].bv_val, linenum+i, dn );
581                                         rc = LDAP_PARAM_ERROR;
582                                         goto leave;
583                                 }
584                                 newsup = vals[i].bv_val;
585                                 i++;
586                         }
587                         got_all = 1;
588                 } else if ( BV_CASEMATCH( vals+i, &BV_DELETECT )) {
589                         got_all = delete_entry = 1;
590                 } else {
591                         fprintf( stderr,
592                                 _("%s:  unknown %s \"%s\" (line %d, entry \"%s\")\n"),
593                                 prog, BV_CHANGETYPE.bv_val, vals[i].bv_val, linenum+i, dn );
594                         rc = LDAP_PARAM_ERROR;
595                         goto leave;
596                 }
597                 i++;
598         } else if ( ldapadd ) {         /*  missing changetype => add */
599                 new_entry = 1;
600                 modop = LDAP_MOD_ADD;
601         } else {
602                 expect_modop = 1;       /* missing changetype => modify */
603         }
604
605         if ( got_all ) {
606                 if ( i < lines ) {
607                         fprintf( stderr,
608                                 _("%s: extra lines at end (line %d, entry \"%s\")\n"),
609                                 prog, linenum+i, dn );
610                         rc = LDAP_PARAM_ERROR;
611                         goto leave;
612                 }
613                 goto doit;
614         }
615
616         nmods = lines - i;
617         idn = i;
618
619         if ( new_entry ) {
620                 int fv;
621
622                 /* Make sure all attributes with multiple values are contiguous */
623                 for (; i<lines; i++) {
624                         for (j=i+1; j<lines; j++) {
625                                 if ( BV_CASEMATCH( btype+i, btype+j )) {
626                                         nmods--;
627                                         /* out of order, move intervening attributes down */
628                                         if ( j != i+1 ) {
629                                                 bv = vals[j];
630                                                 fv = freeval[j];
631                                                 for (k=j; k>i; k--) {
632                                                         btype[k] = btype[k-1];
633                                                         vals[k] = vals[k-1];
634                                                         freeval[k] = freeval[k-1];
635                                                 }
636                                                 k++;
637                                                 btype[k] = btype[i];
638                                                 vals[k] = bv;
639                                                 freeval[k] = fv;
640                                         }
641                                         i++;
642                                 }
643                         }
644                 }
645                 /* Allocate space for array of mods, array of pointers to mods,
646                  * and array of pointers to values, allowing for NULL terminators
647                  * for the pointer arrays...
648                  */
649                 lm = ber_memalloc( nmods * sizeof(LDAPMod) +
650                         (nmods+1) * sizeof(LDAPMod*) +
651                         (lines + nmods - idn) * sizeof(struct berval *));
652                 pmods = (LDAPMod **)(lm+nmods);
653                 bvl = (struct berval **)(pmods+nmods+1);
654
655                 j = 0;
656                 k = -1;
657                 BER_BVZERO(&bv);
658                 for (i=idn; i<lines; i++) {
659                         if ( BV_CASEMATCH( btype+i, &BV_DN )) {
660                                 fprintf( stderr, _("%s: attributeDescription \"%s\":"
661                                         " (possible missing newline"
662                                                 " after line %d, entry \"%s\"?)\n"),
663                                         prog, btype[i].bv_val, linenum+i - 1, dn );
664                         }
665                         if ( !BV_CASEMATCH( btype+i, &bv )) {
666                                 bvl[k++] = NULL;
667                                 bv = btype[i];
668                                 lm[j].mod_op = LDAP_MOD_ADD | LDAP_MOD_BVALUES;
669                                 lm[j].mod_type = bv.bv_val;
670                                 lm[j].mod_bvalues = bvl+k;
671                                 pmods[j] = lm+j;
672                                 j++;
673                         }
674                         bvl[k++] = vals+i;
675                 }
676                 bvl[k] = NULL;
677                 pmods[j] = NULL;
678                 goto doit;
679         }
680
681         mops = ber_memalloc( lines+1 );
682         mops[lines] = M_SEP;
683         mops[i-1] = M_SEP;
684
685         for ( ; i<lines; i++ ) {
686                 if ( expect_modop ) {
687 #ifdef LIBERAL_CHANGETYPE_MODOP
688                         /* trim trailing spaces (and log warning ...) */
689                     int icnt;
690                     for ( icnt = vals[i].bv_len; --icnt > 0; ) {
691                                 if ( !isspace( (unsigned char) vals[i].bv_val[icnt] ) ) break;
692                         }
693     
694                         if ( ++icnt != vals[i].bv_len ) {
695                                 fprintf( stderr, _("%s: illegal trailing space after"
696                                         " \"%s: %s\" trimmed (line %d, entry \"%s\")\n"),
697                                         prog, type, vals[i].bv_val, linenum+i, dn );
698                                 vals[i].bv_val[icnt] = '\0';
699                         }
700 #endif /* LIBERAL_CHANGETYPE_MODOP */
701
702                         expect_modop = 0;
703                         expect_sep = 1;
704                         if ( BV_CASEMATCH( btype+i, &BV_MODOPADD )) {
705                                 modop = LDAP_MOD_ADD;
706                                 mops[i] = M_SEP;
707                                 nmods--;
708                         } else if ( BV_CASEMATCH( btype+i, &BV_MODOPREPLACE )) {
709                         /* defer handling these since they might have no values.
710                          * Use the BVALUES flag to signal that these were
711                          * deferred. If values are provided later, this
712                          * flag will be switched off.
713                          */
714                                 modop = LDAP_MOD_REPLACE;
715                                 mops[i] = modop | LDAP_MOD_BVALUES;
716                                 btype[i] = vals[i];
717                         } else if ( BV_CASEMATCH( btype+i, &BV_MODOPDELETE )) {
718                                 modop = LDAP_MOD_DELETE;
719                                 mops[i] = modop | LDAP_MOD_BVALUES;
720                                 btype[i] = vals[i];
721                         } else if ( BV_CASEMATCH( btype+i, &BV_MODOPINCREMENT )) {
722                                 modop = LDAP_MOD_INCREMENT;
723                                 mops[i] = M_SEP;
724                                 nmods--;
725                         } else {        /* no modify op: invalid LDIF */
726                                 fprintf( stderr, _("%s: modify operation type is missing at"
727                                         " line %d, entry \"%s\"\n"),
728                                         prog, linenum+i, dn );
729                                 rc = LDAP_PARAM_ERROR;
730                                 goto leave;
731                         }
732                         bv = vals[i];
733                 } else if ( expect_sep && BER_BVISEMPTY( btype+i )) {
734                         mops[i] = M_SEP;
735                         expect_sep = 0;
736                         expect_modop = 1;
737                         nmods--;
738                 } else {
739                         if ( !BV_CASEMATCH( btype+i, &bv )) {
740                                 fprintf( stderr, _("%s: wrong attributeType at"
741                                         " line %d, entry \"%s\"\n"),
742                                         prog, linenum+i, dn );
743                                 rc = LDAP_PARAM_ERROR;
744                                 goto leave;
745                         }
746                         mops[i] = modop;
747                         /* If prev op was deferred and matches this type,
748                          * clear the flag
749                          */
750                         if ( (mops[i-1] & LDAP_MOD_BVALUES)
751                                 && BV_CASEMATCH( btype+i, btype+i-1 ))
752                         {
753                                 mops[i-1] = M_SEP;
754                                 nmods--;
755                         }
756                 }
757         }
758
759 #if 0   /* we should faithfully encode the LDIF, not combine */
760         /* Make sure all modops with multiple values are contiguous */
761         for (i=idn; i<lines; i++) {
762                 if ( mops[i] == M_SEP )
763                         continue;
764                 for (j=i+1; j<lines; j++) {
765                         if ( mops[j] == M_SEP || mops[i] != mops[j] )
766                                 continue;
767                         if ( BV_CASEMATCH( btype+i, btype+j )) {
768                                 nmods--;
769                                 /* out of order, move intervening attributes down */
770                                 if ( j != i+1 ) {
771                                         int c;
772                                         struct berval bv;
773                                         char fv;
774
775                                         c = mops[j];
776                                         bv = vals[j];
777                                         fv = freeval[j];
778                                         for (k=j; k>i; k--) {
779                                                 btype[k] = btype[k-1];
780                                                 vals[k] = vals[k-1];
781                                                 freeval[k] = freeval[k-1];
782                                                 mops[k] = mops[k-1];
783                                         }
784                                         k++;
785                                         btype[k] = btype[i];
786                                         vals[k] = bv;
787                                         freeval[k] = fv;
788                                         mops[k] = c;
789                                 }
790                                 i++;
791                         }
792                 }
793         }
794 #endif
795
796         /* Allocate space for array of mods, array of pointers to mods,
797          * and array of pointers to values, allowing for NULL terminators
798          * for the pointer arrays...
799          */
800         lm = ber_memalloc( nmods * sizeof(LDAPMod) +
801                 (nmods+1) * sizeof(LDAPMod*) +
802                 (lines + nmods - idn) * sizeof(struct berval *));
803         pmods = (LDAPMod **)(lm+nmods);
804         bvl = (struct berval **)(pmods+nmods+1);
805
806         j = 0;
807         k = -1;
808         BER_BVZERO(&bv);
809         mops[idn-1] = M_SEP;
810         for (i=idn; i<lines; i++) {
811                 if ( mops[i] == M_SEP )
812                         continue;
813                 if ( mops[i] != mops[i-1] || !BV_CASEMATCH( btype+i, &bv )) {
814                         bvl[k++] = NULL;
815                         bv = btype[i];
816                         lm[j].mod_op = mops[i] | LDAP_MOD_BVALUES;
817                         lm[j].mod_type = bv.bv_val;
818                         if ( mops[i] & LDAP_MOD_BVALUES ) {
819                                 lm[j].mod_bvalues = NULL;
820                         } else {
821                                 lm[j].mod_bvalues = bvl+k;
822                         }
823                         pmods[j] = lm+j;
824                         j++;
825                 }
826                 bvl[k++] = vals+i;
827         }
828         bvl[k] = NULL;
829         pmods[j] = NULL;
830
831 doit:
832         /* If default controls are set (as with -M option) and controls are
833            specified in the LDIF file, we must add the default controls to
834            the list of controls sent with the ldap operation.
835         */
836         if ( rc == 0 ) {
837                 if (pctrls) {
838                         LDAPControl **defctrls = NULL;   /* Default server controls */
839                         LDAPControl **newctrls = NULL;
840                         ldap_get_option(ld, LDAP_OPT_SERVER_CONTROLS, &defctrls);
841                         if (defctrls) {
842                                 int npc=0;                       /* Num of LDIF controls */
843                                 int ndefc=0;                     /* Num of default controls */
844                                 while (pctrls[npc]) npc++;       /* Count LDIF controls */
845                                 while (defctrls[ndefc]) ndefc++; /* Count default controls */
846                                 newctrls = ber_memrealloc(pctrls,
847                                         (npc+ndefc+1)*sizeof(LDAPControl*));
848
849                                 if (newctrls == NULL) {
850                                         rc = LDAP_NO_MEMORY;
851                                 } else {
852                                         int i;
853                                         pctrls = newctrls;
854                                         for (i=npc; i<npc+ndefc; i++) {
855                                                 pctrls[i] = ldap_control_dup(defctrls[i-npc]);
856                                                 if (pctrls[i] == NULL) {
857                                                         rc = LDAP_NO_MEMORY;
858                                                         break;
859                                                 }
860                                         }
861                                         pctrls[npc+ndefc] = NULL;
862                                 }
863                                 ldap_controls_free(defctrls);  /* Must be freed by library */
864                         }
865                 }
866         }
867
868         if ( rc == 0 ) {
869                 if ( delete_entry ) {
870                         rc = dodelete( dn, pctrls );
871                 } else if ( newrdn != NULL ) {
872                         rc = dorename( dn, newrdn, newsup, deleteoldrdn, pctrls );
873                 } else {
874                         rc = domodify( dn, pmods, pctrls, new_entry );
875                 }
876
877                 if ( rc == LDAP_SUCCESS ) {
878                         rc = 0;
879                 }
880         }
881
882 leave:
883     if (pctrls != NULL) {
884         ldap_controls_free( pctrls );
885         }
886         if ( lm != NULL ) {
887                 ber_memfree( lm );
888         }
889         if ( mops != NULL ) {
890                 ber_memfree( mops );
891         }
892         for (i=lines-1; i>=0; i--)
893                 if ( freeval[i] ) ber_memfree( vals[i].bv_val );
894         ber_memfree( btype );
895
896         return( rc );
897 }
898
899 /* Parse an LDIF control line of the form
900       control:  oid  [true/false]  [: value]              or
901       control:  oid  [true/false]  [:: base64-value]      or
902       control:  oid  [true/false]  [:< url]
903    The control is added to the list of controls in *ppctrls.
904 */      
905 static int
906 parse_ldif_control(
907         struct berval *bval,
908         LDAPControl ***ppctrls )
909 {
910         char *oid = NULL;
911         int criticality = 0;   /* Default is false if not present */
912         int i, rc=0;
913         char *s, *oidStart;
914         LDAPControl *newctrl = NULL;
915         LDAPControl **pctrls = NULL;
916         struct berval type, bv;
917         int freeval;
918
919         if (ppctrls) pctrls = *ppctrls;
920         /* OID should come first. Validate and extract it. */
921         s = bval->bv_val;
922         if (*s == 0) return ( LDAP_PARAM_ERROR );
923         oidStart = s;
924         while (isdigit((unsigned char)*s) || *s == '.') {
925                 s++;                           /* OID should be digits or . */
926         }
927         if (s == oidStart) { 
928                 return ( LDAP_PARAM_ERROR );   /* OID was not present */
929         }
930         if (*s) {                          /* End of OID should be space or NULL */
931                 if (!isspace((unsigned char)*s)) {
932                         return ( LDAP_PARAM_ERROR ); /* else OID contained invalid chars */
933                 }
934                 *s++ = 0;                    /* Replace space with null to terminate */
935         }
936
937         oid = ber_strdup(oidStart);
938         if (oid == NULL) return ( LDAP_NO_MEMORY );
939
940         /* Optional Criticality field is next. */
941         while (*s && isspace((unsigned char)*s)) {
942                 s++;                         /* Skip white space before criticality */
943         }
944         if (strncasecmp(s, "true", 4) == 0) {
945                 criticality = 1;
946                 s += 4;
947         } 
948         else if (strncasecmp(s, "false", 5) == 0) {
949                 criticality = 0;
950                 s += 5;
951         }
952
953         /* Optional value field is next */
954         while (*s && isspace((unsigned char)*s)) {
955                 s++;                         /* Skip white space before value */
956         }
957         if (*s) {
958                 if (*s != ':') {           /* If value is present, must start with : */
959                         rc = LDAP_PARAM_ERROR;
960                         goto cleanup;
961                 }
962
963                 /* Back up so value is in the form
964                      a: value
965                      a:: base64-value
966                      a:< url
967                    Then we can use ldif_parse_line2 to extract and decode the value
968                 */
969                 s--;
970                 *s = 'a';
971
972                 rc = ldif_parse_line2(s, &type, &bv, &freeval);
973                 if (rc < 0) {
974                         rc = LDAP_PARAM_ERROR;
975                         goto cleanup;
976                 }
977     }
978
979         /* Create a new LDAPControl structure. */
980         newctrl = (LDAPControl *)ber_memalloc(sizeof(LDAPControl));
981         if ( newctrl == NULL ) {
982                 rc = LDAP_NO_MEMORY;
983                 goto cleanup;
984         }
985         newctrl->ldctl_oid = oid;
986         oid = NULL;
987         newctrl->ldctl_iscritical = criticality;
988         if ( freeval )
989                 newctrl->ldctl_value = bv;
990         else
991                 ber_dupbv( &newctrl->ldctl_value, &bv );
992
993         /* Add the new control to the passed-in list of controls. */
994         i = 0;
995         if (pctrls) {
996                 while ( pctrls[i] ) {    /* Count the # of controls passed in */
997                         i++;
998                 }
999         }
1000         /* Allocate 1 more slot for the new control and 1 for the NULL. */
1001         pctrls = (LDAPControl **) ber_memrealloc(pctrls,
1002                 (i+2)*(sizeof(LDAPControl *)));
1003         if (pctrls == NULL) {
1004                 rc = LDAP_NO_MEMORY;
1005                 goto cleanup;
1006         }
1007         pctrls[i] = newctrl;
1008         newctrl = NULL;
1009         pctrls[i+1] = NULL;
1010         *ppctrls = pctrls;
1011
1012 cleanup:
1013         if (newctrl) {
1014                 if (newctrl->ldctl_oid) ber_memfree(newctrl->ldctl_oid);
1015                 if (newctrl->ldctl_value.bv_val) {
1016                         ber_memfree(newctrl->ldctl_value.bv_val);
1017                 }
1018                 ber_memfree(newctrl);
1019         }
1020         if (oid) ber_memfree(oid);
1021
1022         return( rc );
1023 }
1024
1025
1026 static int
1027 domodify(
1028         const char *dn,
1029         LDAPMod **pmods,
1030         LDAPControl **pctrls,
1031         int newentry )
1032 {
1033         int                     rc, i, j, k, notascii, op;
1034         struct berval   *bvp;
1035
1036         if ( dn == NULL ) {
1037                 fprintf( stderr, _("%s: no DN specified\n"), prog );
1038                 return( LDAP_PARAM_ERROR );
1039         }
1040
1041         if ( pmods == NULL ) {
1042                 /* implement "touch" (empty sequence)
1043                  * modify operation (note that there
1044                  * is no symmetry with the UNIX command,
1045                  * since \"touch\" on a non-existent entry
1046                  * will fail)*/
1047                 printf( "warning: no attributes to %sadd (entry=\"%s\")\n",
1048                         newentry ? "" : "change or ", dn );
1049
1050         } else {
1051                 for ( i = 0; pmods[ i ] != NULL; ++i ) {
1052                         op = pmods[ i ]->mod_op & ~LDAP_MOD_BVALUES;
1053                         if( op == LDAP_MOD_ADD && ( pmods[i]->mod_bvalues == NULL )) {
1054                                 fprintf( stderr,
1055                                         _("%s: attribute \"%s\" has no values (entry=\"%s\")\n"),
1056                                         prog, pmods[i]->mod_type, dn );
1057                                 return LDAP_PARAM_ERROR;
1058                         }
1059                 }
1060
1061                 if ( verbose ) {
1062                         for ( i = 0; pmods[ i ] != NULL; ++i ) {
1063                                 op = pmods[ i ]->mod_op & ~LDAP_MOD_BVALUES;
1064                                 printf( "%s %s:\n",
1065                                         op == LDAP_MOD_REPLACE ? _("replace") :
1066                                                 op == LDAP_MOD_ADD ?  _("add") :
1067                                                         op == LDAP_MOD_INCREMENT ?  _("increment") :
1068                                                                 op == LDAP_MOD_DELETE ?  _("delete") :
1069                                                                         _("unknown"),
1070                                         pmods[ i ]->mod_type );
1071         
1072                                 if ( pmods[ i ]->mod_bvalues != NULL ) {
1073                                         for ( j = 0; pmods[ i ]->mod_bvalues[ j ] != NULL; ++j ) {
1074                                                 bvp = pmods[ i ]->mod_bvalues[ j ];
1075                                                 notascii = 0;
1076                                                 for ( k = 0; (unsigned long) k < bvp->bv_len; ++k ) {
1077                                                         if ( !isascii( bvp->bv_val[ k ] )) {
1078                                                                 notascii = 1;
1079                                                                 break;
1080                                                         }
1081                                                 }
1082                                                 if ( notascii ) {
1083                                                         printf( _("\tNOT ASCII (%ld bytes)\n"), bvp->bv_len );
1084                                                 } else {
1085                                                         printf( "\t%s\n", bvp->bv_val );
1086                                                 }
1087                                         }
1088                                 }
1089                         }
1090                 }
1091         }
1092
1093         if ( newentry ) {
1094                 printf( "%sadding new entry \"%s\"\n", dont ? "!" : "", dn );
1095         } else {
1096                 printf( "%smodifying entry \"%s\"\n", dont ? "!" : "", dn );
1097         }
1098
1099         if ( !dont ) {
1100                 int     msgid;
1101                 if ( newentry ) {
1102                         rc = ldap_add_ext( ld, dn, pmods, pctrls, NULL, &msgid );
1103                 } else {
1104                         rc = ldap_modify_ext( ld, dn, pmods, pctrls, NULL, &msgid );
1105                 }
1106
1107                 if ( rc != LDAP_SUCCESS ) {
1108                         /* print error message about failed update including DN */
1109                         fprintf( stderr, _("%s: update failed: %s\n"), prog, dn );
1110                         tool_perror( newentry ? "ldap_add" : "ldap_modify",
1111                                 rc, NULL, NULL, NULL, NULL );
1112                         goto done;
1113                 }
1114                 rc = process_response( ld, msgid,
1115                         newentry ? LDAP_RES_ADD : LDAP_RES_MODIFY, dn );
1116
1117                 if ( verbose && rc == LDAP_SUCCESS ) {
1118                         printf( _("modify complete\n") );
1119                 }
1120
1121         } else {
1122                 rc = LDAP_SUCCESS;
1123         }
1124
1125 done:
1126         putchar( '\n' );
1127         return rc;
1128 }
1129
1130
1131 static int
1132 dodelete(
1133         const char *dn,
1134         LDAPControl **pctrls )
1135 {
1136         int     rc;
1137         int msgid;
1138
1139         printf( _("%sdeleting entry \"%s\"\n"), dont ? "!" : "", dn );
1140         if ( !dont ) {
1141                 rc = ldap_delete_ext( ld, dn, pctrls, NULL, &msgid );
1142                 if ( rc != LDAP_SUCCESS ) {
1143                         fprintf( stderr, _("%s: delete failed: %s\n"), prog, dn );
1144                         tool_perror( "ldap_delete", rc, NULL, NULL, NULL, NULL );
1145                         goto done;
1146                 }
1147                 rc = process_response( ld, msgid, LDAP_RES_DELETE, dn );
1148
1149                 if ( verbose && rc == LDAP_SUCCESS ) {
1150                         printf( _("delete complete\n") );
1151                 }
1152         } else {
1153                 rc = LDAP_SUCCESS;
1154         }
1155
1156 done:
1157         putchar( '\n' );
1158         return( rc );
1159 }
1160
1161
1162 static int
1163 dorename(
1164         const char *dn,
1165         const char *newrdn,
1166         const char* newsup,
1167         int deleteoldrdn,
1168         LDAPControl **pctrls )
1169 {
1170         int     rc;
1171         int msgid;
1172
1173         printf( _("%smodifying rdn of entry \"%s\"\n"), dont ? "!" : "", dn );
1174         if ( verbose ) {
1175                 printf( _("\tnew RDN: \"%s\" (%skeep existing values)\n"),
1176                         newrdn, deleteoldrdn ? _("do not ") : "" );
1177         }
1178         if ( !dont ) {
1179                 rc = ldap_rename( ld, dn, newrdn, newsup, deleteoldrdn,
1180                         pctrls, NULL, &msgid );
1181                 if ( rc != LDAP_SUCCESS ) {
1182                         fprintf( stderr, _("%s: rename failed: %s\n"), prog, dn );
1183                         tool_perror( "ldap_rename", rc, NULL, NULL, NULL, NULL );
1184                         goto done;
1185                 }
1186                 rc = process_response( ld, msgid, LDAP_RES_RENAME, dn );
1187
1188                 if ( verbose && rc == LDAP_SUCCESS ) {
1189                         printf( _("rename complete\n") );
1190                 }
1191         } else {
1192                 rc = LDAP_SUCCESS;
1193         }
1194
1195 done:
1196         putchar( '\n' );
1197         return( rc );
1198 }
1199
1200 static const char *
1201 res2str( int res ) {
1202         switch ( res ) {
1203         case LDAP_RES_ADD:
1204                 return "ldap_add";
1205         case LDAP_RES_DELETE:
1206                 return "ldap_delete";
1207         case LDAP_RES_MODIFY:
1208                 return "ldap_modify";
1209         case LDAP_RES_MODRDN:
1210                 return "ldap_rename";
1211         default:
1212                 assert( 0 );
1213         }
1214
1215         return "ldap_unknown";
1216 }
1217
1218 static int process_response(
1219         LDAP *ld,
1220         int msgid,
1221         int op,
1222         const char *dn )
1223 {
1224         LDAPMessage     *res;
1225         int             rc = LDAP_OTHER, msgtype;
1226         struct timeval  tv = { 0, 0 };
1227         int             err;
1228         char            *text = NULL, *matched = NULL, **refs = NULL;
1229         LDAPControl     **ctrls = NULL;
1230
1231         for ( ; ; ) {
1232                 tv.tv_sec = 0;
1233                 tv.tv_usec = 100000;
1234
1235                 rc = ldap_result( ld, msgid, LDAP_MSG_ALL, &tv, &res );
1236                 if ( tool_check_abandon( ld, msgid ) ) {
1237                         return LDAP_CANCELLED;
1238                 }
1239
1240                 if ( rc == -1 ) {
1241                         ldap_get_option( ld, LDAP_OPT_RESULT_CODE, &rc );
1242                         tool_perror( "ldap_result", rc, NULL, NULL, NULL, NULL );
1243                         return rc;
1244                 }
1245
1246                 if ( rc != 0 ) {
1247                         break;
1248                 }
1249         }
1250
1251         msgtype = ldap_msgtype( res );
1252
1253         rc = ldap_parse_result( ld, res, &err, &matched, &text, &refs, &ctrls, 1 );
1254         if ( rc == LDAP_SUCCESS ) rc = err;
1255
1256 #ifdef LDAP_X_TXN
1257         if ( rc == LDAP_X_TXN_SPECIFY_OKAY ) {
1258                 rc = LDAP_SUCCESS;
1259         } else
1260 #endif
1261         if ( rc != LDAP_SUCCESS ) {
1262                 tool_perror( res2str( op ), rc, NULL, matched, text, refs );
1263         } else if ( msgtype != op ) {
1264                 fprintf( stderr, "%s: msgtype: expected %d got %d\n",
1265                         res2str( op ), op, msgtype );
1266                 rc = LDAP_OTHER;
1267         }
1268
1269         if ( text ) ldap_memfree( text );
1270         if ( matched ) ldap_memfree( matched );
1271         if ( text ) ber_memvfree( (void **)refs );
1272
1273         if ( ctrls ) {
1274                 tool_print_ctrls( ld, ctrls );
1275                 ldap_controls_free( ctrls );
1276         }
1277
1278         return rc;
1279 }