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