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