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