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