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