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