]> git.sur5r.net Git - openldap/blob - clients/tools/ldapmodify.c
7765201fe4060486b1a4b3528e10d1f474dc6078
[openldap] / clients / tools / ldapmodify.c
1 /* ldapmodify.c - generic program to modify or add entries using LDAP */
2 /* $OpenLDAP$ */
3 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
4  *
5  * Copyright 1998-2006 The OpenLDAP Foundation.
6  * Portions Copyright 1998-2003 Kurt D. Zeilenga.
7  * Portions Copyright 1998-2001 Net Boolean Incorporated.
8  * Portions Copyright 2001-2003 IBM Corporation.
9  * All rights reserved.
10  *
11  * Redistribution and use in source and binary forms, with or without
12  * modification, are permitted only as authorized by the OpenLDAP
13  * Public License.
14  *
15  * A copy of this license is available in the file LICENSE in the
16  * top-level directory of the distribution or, alternatively, at
17  * <http://www.OpenLDAP.org/license.html>.
18  */
19 /* Portions Copyright (c) 1992-1996 Regents of the University of Michigan.
20  * All rights reserved.
21  *
22  * Redistribution and use in source and binary forms are permitted
23  * provided that this notice is preserved and that due credit is given
24  * to the University of Michigan at Ann Arbor.  The name of the
25  * University may not be used to endorse or promote products derived
26  * from this software without specific prior written permission.  This
27  * software is provided ``as is'' without express or implied warranty.
28  */
29 /* ACKNOWLEDGEMENTS:
30  * This work was originally developed by the University of Michigan
31  * (as part of U-MICH LDAP).  Additional significant contributors
32  * include:
33  *   Kurt D. Zeilenga
34  *   Norbert Klasen
35  */
36
37 #include "portable.h"
38
39 #include <stdio.h>
40
41 #include <ac/stdlib.h>
42 #include <ac/ctype.h>
43 #include <ac/string.h>
44 #include <ac/unistd.h>
45 #include <ac/time.h>
46
47 #ifdef HAVE_SYS_STAT_H
48 #include <sys/stat.h>
49 #endif
50
51 #ifdef HAVE_SYS_FILE_H
52 #include <sys/file.h>
53 #endif
54 #ifdef HAVE_FCNTL_H
55 #include <fcntl.h>
56 #endif
57
58 #include <ldap.h>
59
60 #include "lutil.h"
61 #include "lutil_ldap.h"
62 #include "ldif.h"
63 #include "ldap_defaults.h"
64 #include "ldap_log.h"
65 #include "ldap_pvt.h"
66
67 #include "common.h"
68
69
70 static int      ldapadd, force = 0;
71 static char *rejfile = NULL;
72 static LDAP     *ld = NULL;
73
74 #define LDAPMOD_MAXLINE         4096
75
76 /* strings found in replog/LDIF entries (mostly lifted from slurpd/slurp.h) */
77 #define T_VERSION_STR           "version"
78 #define T_REPLICA_STR           "replica"
79 #define T_DN_STR                        "dn"
80 #define T_CONTROL_STR           "control"
81 #define T_CHANGETYPESTR         "changetype"
82 #define T_ADDCTSTR                      "add"
83 #define T_MODIFYCTSTR           "modify"
84 #define T_DELETECTSTR           "delete"
85 #define T_MODRDNCTSTR           "modrdn"
86 #define T_MODDNCTSTR            "moddn"
87 #define T_RENAMECTSTR           "rename"
88 #define T_MODOPADDSTR           "add"
89 #define T_MODOPREPLACESTR       "replace"
90 #define T_MODOPDELETESTR        "delete"
91 #define T_MODOPINCREMENTSTR     "increment"
92 #define T_MODSEPSTR                     "-"
93 #define T_NEWRDNSTR                     "newrdn"
94 #define T_DELETEOLDRDNSTR       "deleteoldrdn"
95 #define T_NEWSUPSTR                     "newsuperior"
96
97
98 static int process_ldif_rec LDAP_P(( char *rbuf, int count ));
99 static int parse_ldif_control LDAP_P(( char *line, LDAPControl ***pctrls ));
100 static void addmodifyop LDAP_P((
101         LDAPMod ***pmodsp, int modop,
102         const char *attr,
103         struct berval *value ));
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 static char *read_one_record LDAP_P(( FILE *fp ));
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: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
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, *start, *rejbuf = NULL;
246         FILE            *fp, *rejfp;
247         char            *matched_msg, *error_msg;
248         int             rc, retval;
249         int             count, len;
250         int             i = 0;
251         LDAPControl     c[1];
252
253         prog = lutil_progname( "ldapmodify", argc, argv );
254
255         /* strncmp instead of strcmp since NT binaries carry .exe extension */
256         ldapadd = ( strncasecmp( prog, "ldapadd", sizeof("ldapadd")-1 ) == 0 );
257
258         tool_init( ldapadd ? TOOL_ADD : TOOL_MODIFY );
259
260         tool_args( argc, argv );
261
262         if ( argc != optind ) usage();
263
264         if ( rejfile != NULL ) {
265                 if (( rejfp = fopen( rejfile, "w" )) == NULL ) {
266                         perror( rejfile );
267                         return( EXIT_FAILURE );
268                 }
269         } else {
270                 rejfp = NULL;
271         }
272
273         if ( infile != NULL ) {
274                 if (( fp = fopen( infile, "r" )) == NULL ) {
275                         perror( infile );
276                         return( EXIT_FAILURE );
277                 }
278         } else {
279                 fp = stdin;
280         }
281
282         if ( debug ) ldif_debug = debug;
283
284         ld = tool_conn_setup( dont, 0 );
285
286         if ( !dont ) {
287                 if ( pw_file || want_bindpw ) {
288                         if ( pw_file ) {
289                                 rc = lutil_get_filed_password( pw_file, &passwd );
290                                 if( rc ) return EXIT_FAILURE;
291                         } else {
292                                 passwd.bv_val = getpassphrase( _("Enter LDAP Password: ") );
293                                 passwd.bv_len = passwd.bv_val ? strlen( passwd.bv_val ) : 0;
294                         }
295                 }
296                 tool_bind( ld );
297         }
298
299 #ifdef LDAP_X_TXN
300         if( txn ) {
301                 /* start transaction */
302                 rc = ldap_txn_start_s( ld, NULL, NULL, &txn_id );
303                 if( rc != LDAP_SUCCESS ) {
304                         tool_perror( "ldap_txn_start_s", rc, NULL, NULL, NULL, NULL );
305                         if( txn > 1 ) return EXIT_FAILURE;
306                         txn = 0;
307                 }
308         }
309 #endif
310
311         if ( 0
312 #ifdef LDAP_X_TXN
313                 || txn
314 #endif
315                 )
316         {
317 #ifdef LDAP_X_TXN
318                 if( txn ) {
319                         c[i].ldctl_oid = LDAP_CONTROL_X_TXN_SPEC;
320                         c[i].ldctl_value = *txn_id;
321                         c[i].ldctl_iscritical = 1;
322                         i++;
323                 }
324 #endif
325         }
326
327         tool_server_controls( ld, c, i );
328
329         rc = 0;
330         count = 0;
331         retval = 0;
332         while (( rc == 0 || contoper ) &&
333                 ( rbuf = read_one_record( fp )) != NULL )
334         {
335                 count++;
336
337                 start = rbuf;
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( start, count );
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_ERROR_STRING, &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) free( rejbuf );
375                 free( rbuf );
376         }
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 count )
409 {
410         char    *line, *dn, *type, *newrdn, *newsup, *p;
411         int             rc, linenum, modop, replicaport;
412         int             expect_modop, expect_sep, expect_ct, expect_newrdn, expect_newsup;
413         int             expect_deleteoldrdn, deleteoldrdn;
414         int             saw_replica, use_record, new_entry, delete_entry, got_all;
415         LDAPMod **pmods;
416         int version;
417         struct berval val;
418         LDAPControl **pctrls;
419
420         new_entry = ldapadd;
421
422         rc = got_all = saw_replica = delete_entry = modop = expect_modop = 0;
423         expect_deleteoldrdn = expect_newrdn = expect_newsup = 0;
424         expect_sep = expect_ct = 0;
425         linenum = 0;
426         version = 0;
427         deleteoldrdn = 1;
428         use_record = force;
429         pmods = NULL;
430         pctrls = NULL;
431         dn = newrdn = newsup = NULL;
432
433         while ( rc == 0 && ( line = ldif_getline( &rbuf )) != NULL ) {
434                 ++linenum;
435
436                 if ( expect_sep && strcasecmp( line, T_MODSEPSTR ) == 0 ) {
437                         expect_sep = 0;
438                         expect_ct = 1;
439                         continue;
440                 }
441         
442                 if ( ldif_parse_line( line, &type, &val.bv_val, &val.bv_len ) < 0 ) {
443                         fprintf( stderr, _("%s: invalid format (line %d) entry: \"%s\"\n"),
444                                 prog, linenum, dn == NULL ? "" : dn );
445                         rc = LDAP_PARAM_ERROR;
446                         break;
447                 }
448
449                 if ( dn == NULL ) {
450                         if ( !use_record && strcasecmp( type, T_REPLICA_STR ) == 0 ) {
451                                 ++saw_replica;
452                                 if (( p = strchr( val.bv_val, ':' )) == NULL ) {
453                                         replicaport = 0;
454                                 } else {
455                                         *p++ = '\0';
456                                         if ( lutil_atoi( &replicaport, p ) != 0 ) {
457                                                 fprintf( stderr, _("%s: unable to parse replica port \"%s\" (line %d) entry: \"%s\"\n"),
458                                                         prog, p, linenum, dn == NULL ? "" : dn );
459                                                 rc = LDAP_PARAM_ERROR;
460                                                 break;
461                                         }
462                                 }
463                                 if ( ldaphost != NULL &&
464                                         strcasecmp( val.bv_val, ldaphost ) == 0 &&
465                                         replicaport == ldapport )
466                                 {
467                                         use_record = 1;
468                                 }
469                         } else if ( count == 1 && linenum == 1 && 
470                                 strcasecmp( type, T_VERSION_STR ) == 0 )
471                         {
472                                 int     v;
473                                 if( val.bv_len == 0 || lutil_atoi( &v, val.bv_val) != 0 || v != 1 ) {
474                                         fprintf( stderr,
475                                                 _("%s: invalid version %s, line %d (ignored)\n"),
476                                                 prog, val.bv_val, linenum );
477                                 }
478                                 version++;
479
480                         } else if ( strcasecmp( type, T_DN_STR ) == 0 ) {
481                                 if (( dn = ber_strdup( val.bv_val )) == NULL ) {
482                                         perror( "strdup" );
483                                         exit( EXIT_FAILURE );
484                                 }
485                                 expect_ct = 1;
486                         }
487                         goto end_line;  /* skip all lines until we see "dn:" */
488                 }
489
490                 if ( expect_ct ) {
491                         /* Check for "control" tag after dn and before changetype. */
492                         if (strcasecmp(type, T_CONTROL_STR) == 0) {
493                                 /* Parse and add it to the list of controls */
494                                 rc = parse_ldif_control( line, &pctrls );
495                                 if (rc != 0) {
496                                         fprintf( stderr,
497                                                 _("%s: Error processing %s line, line %d: %s\n"),
498                                                 prog, T_CONTROL_STR, linenum, ldap_err2string(rc) );
499                                 }
500                                 goto end_line;
501                         }
502
503                         expect_ct = 0;
504                         if ( !use_record && saw_replica ) {
505                                 printf(_("%s: skipping change record for entry: %s\n"),
506                                         prog, dn);
507                                 printf(_("\t(LDAP host/port does not match replica: lines)\n"));
508                                 free( dn );
509                                 ber_memfree( type );
510                                 ber_memfree( val.bv_val );
511                                 return( 0 );
512                         }
513
514                         if ( strcasecmp( type, T_CHANGETYPESTR ) == 0 ) {
515 #ifdef LIBERAL_CHANGETYPE_MODOP
516                                 /* trim trailing spaces (and log warning ...) */
517                                 int icnt;
518                                 for ( icnt = val.bv_len; --icnt > 0; ) {
519                                         if ( !isspace( (unsigned char) val.bv_val[icnt] ) ) {
520                                                 break;
521                                         }
522                                 }
523
524                                 if ( ++icnt != val.bv_len ) {
525                                         fprintf( stderr, _("%s: illegal trailing space after"
526                                                 " \"%s: %s\" trimmed (line %d of entry \"%s\")\n"),
527                                                 prog, T_CHANGETYPESTR, val.bv_val, linenum, dn );
528                                         val.bv_val[icnt] = '\0';
529                                 }
530 #endif /* LIBERAL_CHANGETYPE_MODOP */
531
532                                 if ( strcasecmp( val.bv_val, T_MODIFYCTSTR ) == 0 ) {
533                                         new_entry = 0;
534                                         expect_modop = 1;
535                                 } else if ( strcasecmp( val.bv_val, T_ADDCTSTR ) == 0 ) {
536                                         new_entry = 1;
537                                 } else if ( strcasecmp( val.bv_val, T_MODRDNCTSTR ) == 0
538                                         || strcasecmp( val.bv_val, T_MODDNCTSTR ) == 0
539                                         || strcasecmp( val.bv_val, T_RENAMECTSTR ) == 0)
540                                 {
541                                         expect_newrdn = 1;
542                                 } else if ( strcasecmp( val.bv_val, T_DELETECTSTR ) == 0 ) {
543                                         got_all = delete_entry = 1;
544                                 } else {
545                                         fprintf( stderr,
546                                                 _("%s:  unknown %s \"%s\" (line %d of entry \"%s\")\n"),
547                                                 prog, T_CHANGETYPESTR, val.bv_val, linenum, dn );
548                                         rc = LDAP_PARAM_ERROR;
549                                 }
550                                 goto end_line;
551                         } else if ( ldapadd ) {         /*  missing changetype => add */
552                                 new_entry = 1;
553                                 modop = LDAP_MOD_ADD;
554                         } else {
555                                 expect_modop = 1;       /* missing changetype => modify */
556                         }
557                 }
558
559                 if ( expect_modop ) {
560 #ifdef LIBERAL_CHANGETYPE_MODOP
561                         /* trim trailing spaces (and log warning ...) */
562                     int icnt;
563                     for ( icnt = val.bv_len; --icnt > 0; ) {
564                                 if ( !isspace( (unsigned char) val.bv_val[icnt] ) ) break;
565                         }
566     
567                         if ( ++icnt != val.bv_len ) {
568                                 fprintf( stderr, _("%s: illegal trailing space after"
569                                         " \"%s: %s\" trimmed (line %d of entry \"%s\")\n"),
570                                         prog, type, val.bv_val, linenum, dn );
571                                 val.bv_val[icnt] = '\0';
572                         }
573 #endif /* LIBERAL_CHANGETYPE_MODOP */
574
575                         expect_modop = 0;
576                         expect_sep = 1;
577                         if ( strcasecmp( type, T_MODOPADDSTR ) == 0 ) {
578                                 modop = LDAP_MOD_ADD;
579                                 goto end_line;
580                         } else if ( strcasecmp( type, T_MODOPREPLACESTR ) == 0 ) {
581                                 modop = LDAP_MOD_REPLACE;
582                                 addmodifyop( &pmods, modop, val.bv_val, NULL );
583                                 goto end_line;
584                         } else if ( strcasecmp( type, T_MODOPDELETESTR ) == 0 ) {
585                                 modop = LDAP_MOD_DELETE;
586                                 addmodifyop( &pmods, modop, val.bv_val, NULL );
587                                 goto end_line;
588                         } else if ( strcasecmp( type, T_MODOPINCREMENTSTR ) == 0 ) {
589                                 modop = LDAP_MOD_INCREMENT;
590                                 addmodifyop( &pmods, modop, val.bv_val, NULL );
591                                 goto end_line;
592                         } else {        /* no modify op:  use default */
593                                 modop = ldapadd ? LDAP_MOD_ADD : LDAP_MOD_REPLACE;
594                         }
595                 }
596
597                 if ( expect_newrdn ) {
598                         if ( strcasecmp( type, T_NEWRDNSTR ) == 0 ) {
599                                 if (( newrdn = ber_strdup( val.bv_val )) == NULL ) {
600                                         perror( "strdup" );
601                                         exit( EXIT_FAILURE );
602                                 }
603                                 expect_deleteoldrdn = 1;
604                                 expect_newrdn = 0;
605                         } else {
606                                 fprintf( stderr, _("%s: expecting \"%s:\" but saw"
607                                         " \"%s:\" (line %d of entry \"%s\")\n"),
608                                         prog, T_NEWRDNSTR, type, linenum, dn );
609                                 rc = LDAP_PARAM_ERROR;
610                         }
611                 } else if ( expect_deleteoldrdn ) {
612                         if ( strcasecmp( type, T_DELETEOLDRDNSTR ) == 0 ) {
613                                 deleteoldrdn = ( *val.bv_val == '0' ) ? 0 : 1;
614                                 expect_deleteoldrdn = 0;
615                                 expect_newsup = 1;
616                                 got_all = 1;
617                         } else {
618                                 fprintf( stderr, _("%s: expecting \"%s:\" but saw"
619                                         " \"%s:\" (line %d of entry \"%s\")\n"),
620                                         prog, T_DELETEOLDRDNSTR, type, linenum, dn );
621                                 rc = LDAP_PARAM_ERROR;
622                         }
623                 } else if ( expect_newsup ) {
624                         if ( strcasecmp( type, T_NEWSUPSTR ) == 0 ) {
625                                 if (( newsup = ber_strdup( val.bv_val )) == NULL ) {
626                                         perror( "strdup" );
627                                         exit( EXIT_FAILURE );
628                                 }
629                                 expect_newsup = 0;
630                         } else {
631                                 fprintf( stderr, _("%s: expecting \"%s:\" but saw"
632                                         " \"%s:\" (line %d of entry \"%s\")\n"),
633                                         prog, T_NEWSUPSTR, type, linenum, dn );
634                                 rc = LDAP_PARAM_ERROR;
635                         }
636                 } else if ( got_all ) {
637                         fprintf( stderr,
638                                 _("%s: extra lines at end (line %d of entry \"%s\")\n"),
639                                 prog, linenum, dn );
640                         rc = LDAP_PARAM_ERROR;
641                 } else {
642                         if ( new_entry && strcasecmp( type, T_DN_STR ) == 0 ) {
643                                 fprintf( stderr, _("%s: attributeDescription \"%s\":"
644                                         " (possible missing newline"
645                                                 " after line %d of entry \"%s\"?)\n"),
646                                         prog, type, linenum - 1, dn );
647                         }
648                         addmodifyop( &pmods, modop, type, &val );
649                 }
650
651 end_line:
652                 ber_memfree( type );
653                 ber_memfree( val.bv_val );
654         }
655
656         if( linenum == 0 ) {
657                 return 0;
658         }
659
660         if( version && linenum == 1 ) {
661                 return 0;
662         }
663
664         /* If default controls are set (as with -M option) and controls are
665            specified in the LDIF file, we must add the default controls to
666            the list of controls sent with the ldap operation.
667         */
668         if ( rc == 0 ) {
669                 if (pctrls) {
670                         LDAPControl **defctrls = NULL;   /* Default server controls */
671                         LDAPControl **newctrls = NULL;
672                         ldap_get_option(ld, LDAP_OPT_SERVER_CONTROLS, &defctrls);
673                         if (defctrls) {
674                                 int npc=0;                       /* Num of LDIF controls */
675                                 int ndefc=0;                     /* Num of default controls */
676                                 while (pctrls[npc]) npc++;       /* Count LDIF controls */
677                                 while (defctrls[ndefc]) ndefc++; /* Count default controls */
678                                 newctrls = ber_memrealloc(pctrls,
679                                         (npc+ndefc+1)*sizeof(LDAPControl*));
680
681                                 if (newctrls == NULL) {
682                                         rc = LDAP_NO_MEMORY;
683                                 } else {
684                                         int i;
685                                         pctrls = newctrls;
686                                         for (i=npc; i<npc+ndefc; i++) {
687                                                 pctrls[i] = ldap_control_dup(defctrls[i-npc]);
688                                                 if (pctrls[i] == NULL) {
689                                                         rc = LDAP_NO_MEMORY;
690                                                         break;
691                                                 }
692                                         }
693                                         pctrls[npc+ndefc] = NULL;
694                                 }
695                                 ldap_controls_free(defctrls);  /* Must be freed by library */
696                         }
697                 }
698         }
699
700
701         if ( rc == 0 ) {
702                 if ( delete_entry ) {
703                         rc = dodelete( dn, pctrls );
704                 } else if ( newrdn != NULL ) {
705                         rc = dorename( dn, newrdn, newsup, deleteoldrdn, pctrls );
706                 } else {
707                         rc = domodify( dn, pmods, pctrls, new_entry );
708                 }
709
710                 if ( rc == LDAP_SUCCESS ) {
711                         rc = 0;
712                 }
713         }
714
715         if ( dn != NULL ) {
716                 free( dn );
717         }
718         if ( newrdn != NULL ) {
719                 free( newrdn );
720         }
721         if ( newsup != NULL ) {
722                 free( newsup );
723         }
724         if ( pmods != NULL ) {
725                 ldap_mods_free( pmods, 1 );
726         }
727     if (pctrls != NULL) {
728         ldap_controls_free( pctrls );
729         }
730
731         return( rc );
732 }
733
734 /* Parse an LDIF control line of the form
735       control:  oid  [true/false]  [: value]              or
736       control:  oid  [true/false]  [:: base64-value]      or
737       control:  oid  [true/false]  [:< url]
738    The control is added to the list of controls in *ppctrls.
739 */      
740 static int
741 parse_ldif_control(
742         char *line, 
743         LDAPControl ***ppctrls )
744 {
745         char *oid = NULL;
746         int criticality = 0;   /* Default is false if not present */
747         char *type=NULL;
748         char *val = NULL;
749         ber_len_t value_len = 0;
750         int i, rc=0;
751         char *s, *oidStart, *pcolon;
752         LDAPControl *newctrl = NULL;
753         LDAPControl **pctrls = NULL;
754
755         if (ppctrls) pctrls = *ppctrls;
756         s = line + strlen(T_CONTROL_STR);  /* Skip over "control" */
757         pcolon = s;                        /* Save this position for later */
758         if (*s++ != ':') {                 /* Make sure colon follows */
759                 return ( LDAP_PARAM_ERROR );
760         }
761         while (*s && isspace((unsigned char)*s)) {
762                 s++;                           /* Skip white space before OID */
763         }
764
765         /* OID should come next. Validate and extract it. */
766         if (*s == 0) return ( LDAP_PARAM_ERROR );
767         oidStart = s;
768         while (isdigit((unsigned char)*s) || *s == '.') {
769                 s++;                           /* OID should be digits or . */
770         }
771         if (s == oidStart) { 
772                 return ( LDAP_PARAM_ERROR );   /* OID was not present */
773         }
774         if (*s) {                          /* End of OID should be space or NULL */
775                 if (!isspace((unsigned char)*s)) {
776                         return ( LDAP_PARAM_ERROR ); /* else OID contained invalid chars */
777                 }
778                 *s++ = 0;                    /* Replace space with null to terminate */
779         }
780
781         oid = ber_strdup(oidStart);
782         if (oid == NULL) return ( LDAP_NO_MEMORY );
783
784         /* Optional Criticality field is next. */
785         while (*s && isspace((unsigned char)*s)) {
786                 s++;                         /* Skip white space before criticality */
787         }
788         if (strncasecmp(s, "true", 4) == 0) {
789                 criticality = 1;
790                 s += 4;
791         } 
792         else if (strncasecmp(s, "false", 5) == 0) {
793                 criticality = 0;
794                 s += 5;
795         }
796
797         /* Optional value field is next */
798         while (*s && isspace((unsigned char)*s)) {
799                 s++;                         /* Skip white space before value */
800         }
801         if (*s) {
802                 if (*s != ':') {           /* If value is present, must start with : */
803                         rc = LDAP_PARAM_ERROR;
804                         goto cleanup;
805                 }
806
807                 /* Shift value down over OID and criticality so it's in the form
808                      control: value
809                      control:: base64-value
810                      control:< url
811                    Then we can use ldif_parse_line to extract and decode the value
812                 */
813                 while ( (*pcolon++ = *s++) != 0) {   /* Shift value */
814                         /* EMPTY */;
815                 }
816                 rc = ldif_parse_line(line, &type, &val, &value_len);
817                 if (type)  ber_memfree(type);   /* Don't need this field*/
818                 if (rc < 0) {
819                         rc = LDAP_PARAM_ERROR;
820                         goto cleanup;
821                 }
822     }
823
824         /* Create a new LDAPControl structure. */
825         newctrl = (LDAPControl *)ber_memalloc(sizeof(LDAPControl));
826         if ( newctrl == NULL ) {
827                 rc = LDAP_NO_MEMORY;
828                 goto cleanup;
829         }
830         newctrl->ldctl_oid = oid;
831         oid = NULL;
832         newctrl->ldctl_iscritical = criticality;
833         newctrl->ldctl_value.bv_len = value_len;
834         newctrl->ldctl_value.bv_val = val;
835         val = NULL;
836
837         /* Add the new control to the passed-in list of controls. */
838         i = 0;
839         if (pctrls) {
840                 while ( pctrls[i] ) {    /* Count the # of controls passed in */
841                         i++;
842                 }
843         }
844         /* Allocate 1 more slot for the new control and 1 for the NULL. */
845         pctrls = (LDAPControl **) ber_memrealloc(pctrls,
846                 (i+2)*(sizeof(LDAPControl *)));
847         if (pctrls == NULL) {
848                 rc = LDAP_NO_MEMORY;
849                 goto cleanup;
850         }
851         pctrls[i] = newctrl;
852         newctrl = NULL;
853         pctrls[i+1] = NULL;
854         *ppctrls = pctrls;
855
856 cleanup:
857         if (newctrl) {
858                 if (newctrl->ldctl_oid) ber_memfree(newctrl->ldctl_oid);
859                 if (newctrl->ldctl_value.bv_val) {
860                         ber_memfree(newctrl->ldctl_value.bv_val);
861                 }
862                 ber_memfree(newctrl);
863         }
864         if (val) ber_memfree(val);
865         if (oid) ber_memfree(oid);
866
867         return( rc );
868 }
869
870
871 static void
872 addmodifyop(
873         LDAPMod ***pmodsp,
874         int modop,
875         const char *attr,
876         struct berval *val )
877 {
878         LDAPMod         **pmods;
879         int                     i, j;
880
881         pmods = *pmodsp;
882         modop |= LDAP_MOD_BVALUES;
883
884         i = 0;
885         if ( pmods != NULL ) {
886                 for ( ; pmods[ i ] != NULL; ++i ) {
887                         if ( strcasecmp( pmods[ i ]->mod_type, attr ) == 0 &&
888                                 pmods[ i ]->mod_op == modop )
889                         {
890                                 break;
891                         }
892                 }
893         }
894
895         if ( pmods == NULL || pmods[ i ] == NULL ) {
896                 if (( pmods = (LDAPMod **)ber_memrealloc( pmods, (i + 2) *
897                         sizeof( LDAPMod * ))) == NULL )
898                 {
899                         perror( "realloc" );
900                         exit( EXIT_FAILURE );
901                 }
902
903                 *pmodsp = pmods;
904                 pmods[ i + 1 ] = NULL;
905
906                 pmods[ i ] = (LDAPMod *)ber_memcalloc( 1, sizeof( LDAPMod ));
907                 if ( pmods[ i ] == NULL ) {
908                         perror( "calloc" );
909                         exit( EXIT_FAILURE );
910                 }
911
912                 pmods[ i ]->mod_op = modop;
913                 pmods[ i ]->mod_type = ber_strdup( attr );
914                 if ( pmods[ i ]->mod_type == NULL ) {
915                         perror( "strdup" );
916                         exit( EXIT_FAILURE );
917                 }
918         }
919
920         if ( val != NULL ) {
921                 j = 0;
922                 if ( pmods[ i ]->mod_bvalues != NULL ) {
923                         for ( ; pmods[ i ]->mod_bvalues[ j ] != NULL; ++j ) {
924                                 /* Empty */;
925                         }
926                 }
927
928                 pmods[ i ]->mod_bvalues = (struct berval **) ber_memrealloc(
929                         pmods[ i ]->mod_bvalues, (j + 2) * sizeof( struct berval * ));
930                 if ( pmods[ i ]->mod_bvalues == NULL ) {
931                         perror( "ber_realloc" );
932                         exit( EXIT_FAILURE );
933                 }
934
935                 pmods[ i ]->mod_bvalues[ j + 1 ] = NULL;
936                 pmods[ i ]->mod_bvalues[ j ] = ber_bvdup( val );
937                 if ( pmods[ i ]->mod_bvalues[ j ] == NULL ) {
938                         perror( "ber_bvdup" );
939                         exit( EXIT_FAILURE );
940                 }
941         }
942 }
943
944
945 static int
946 domodify(
947         const char *dn,
948         LDAPMod **pmods,
949         LDAPControl **pctrls,
950         int newentry )
951 {
952         int                     rc, i, j, k, notascii, op;
953         struct berval   *bvp;
954
955         if ( dn == NULL ) {
956                 fprintf( stderr, _("%s: no DN specified\n"), prog );
957                 return( LDAP_PARAM_ERROR );
958         }
959
960         if ( pmods == NULL ) {
961                 /* implement "touch" (empty sequence)
962                  * modify operation (note that there
963                  * is no symmetry with the UNIX command,
964                  * since \"touch\" on a non-existent entry
965                  * will fail)*/
966                 printf( "warning: no attributes to %sadd (entry=\"%s\")\n",
967                         newentry ? "" : "change or ", dn );
968
969         } else {
970                 for ( i = 0; pmods[ i ] != NULL; ++i ) {
971                         op = pmods[ i ]->mod_op & ~LDAP_MOD_BVALUES;
972                         if( op == LDAP_MOD_ADD && ( pmods[i]->mod_bvalues == NULL )) {
973                                 fprintf( stderr,
974                                         _("%s: attribute \"%s\" has no values (entry=\"%s\")\n"),
975                                         prog, pmods[i]->mod_type, dn );
976                                 return LDAP_PARAM_ERROR;
977                         }
978                 }
979
980                 if ( verbose ) {
981                         for ( i = 0; pmods[ i ] != NULL; ++i ) {
982                                 op = pmods[ i ]->mod_op & ~LDAP_MOD_BVALUES;
983                                 printf( "%s %s:\n",
984                                         op == LDAP_MOD_REPLACE ? _("replace") :
985                                                 op == LDAP_MOD_ADD ?  _("add") :
986                                                         op == LDAP_MOD_INCREMENT ?  _("increment") :
987                                                                 op == LDAP_MOD_DELETE ?  _("delete") :
988                                                                         _("unknown"),
989                                         pmods[ i ]->mod_type );
990         
991                                 if ( pmods[ i ]->mod_bvalues != NULL ) {
992                                         for ( j = 0; pmods[ i ]->mod_bvalues[ j ] != NULL; ++j ) {
993                                                 bvp = pmods[ i ]->mod_bvalues[ j ];
994                                                 notascii = 0;
995                                                 for ( k = 0; (unsigned long) k < bvp->bv_len; ++k ) {
996                                                         if ( !isascii( bvp->bv_val[ k ] )) {
997                                                                 notascii = 1;
998                                                                 break;
999                                                         }
1000                                                 }
1001                                                 if ( notascii ) {
1002                                                         printf( _("\tNOT ASCII (%ld bytes)\n"), bvp->bv_len );
1003                                                 } else {
1004                                                         printf( "\t%s\n", bvp->bv_val );
1005                                                 }
1006                                         }
1007                                 }
1008                         }
1009                 }
1010         }
1011
1012         if ( newentry ) {
1013                 printf( "%sadding new entry \"%s\"\n", dont ? "!" : "", dn );
1014         } else {
1015                 printf( "%smodifying entry \"%s\"\n", dont ? "!" : "", dn );
1016         }
1017
1018         if ( !dont ) {
1019                 int     msgid;
1020                 if ( newentry ) {
1021                         rc = ldap_add_ext( ld, dn, pmods, pctrls, NULL, &msgid );
1022                 } else {
1023                         rc = ldap_modify_ext( ld, dn, pmods, pctrls, NULL, &msgid );
1024                 }
1025
1026                 if ( rc != LDAP_SUCCESS ) {
1027                         /* print error message about failed update including DN */
1028                         fprintf( stderr, _("%s: update failed: %s\n"), prog, dn );
1029                         tool_perror( newentry ? "ldap_add" : "ldap_modify", rc, NULL, NULL, NULL, NULL );
1030                         goto done;
1031                 } else if ( verbose ) {
1032                         printf( _("modify complete\n") );
1033                 }
1034
1035                 rc = process_response( ld, msgid,
1036                         newentry ? LDAP_RES_ADD : LDAP_RES_MODIFY, dn );
1037
1038         } else {
1039                 rc = LDAP_SUCCESS;
1040         }
1041
1042 done:
1043         putchar( '\n' );
1044         return rc;
1045 }
1046
1047
1048 static int
1049 dodelete(
1050         const char *dn,
1051         LDAPControl **pctrls )
1052 {
1053         int     rc;
1054         int msgid;
1055
1056         printf( _("%sdeleting entry \"%s\"\n"), dont ? "!" : "", dn );
1057         if ( !dont ) {
1058                 rc = ldap_delete_ext( ld, dn, pctrls, NULL, &msgid );
1059                 if ( rc != LDAP_SUCCESS ) {
1060                         fprintf( stderr, _("%s: delete failed: %s\n"), prog, dn );
1061                         tool_perror( "ldap_delete", rc, NULL, NULL, NULL, NULL );
1062                         goto done;
1063                 } else if ( verbose ) {
1064                         printf( _("delete complete") );
1065                 }
1066
1067                 rc = process_response( ld, msgid, LDAP_RES_DELETE, dn );
1068
1069         } else {
1070                 rc = LDAP_SUCCESS;
1071         }
1072
1073 done:
1074         putchar( '\n' );
1075         return( rc );
1076 }
1077
1078
1079 static int
1080 dorename(
1081         const char *dn,
1082         const char *newrdn,
1083         const char* newsup,
1084         int deleteoldrdn,
1085         LDAPControl **pctrls )
1086 {
1087         int     rc;
1088         int msgid;
1089
1090         printf( _("%smodifying rdn of entry \"%s\"\n"), dont ? "!" : "", dn );
1091         if ( verbose ) {
1092                 printf( _("\tnew RDN: \"%s\" (%skeep existing values)\n"),
1093                         newrdn, deleteoldrdn ? _("do not ") : "" );
1094         }
1095         if ( !dont ) {
1096                 rc = ldap_rename( ld, dn, newrdn, newsup, deleteoldrdn,
1097                         pctrls, NULL, &msgid );
1098                 if ( rc != LDAP_SUCCESS ) {
1099                         fprintf( stderr, _("%s: rename failed: %s\n"), prog, dn );
1100                         tool_perror( "ldap_modrdn", rc, NULL, NULL, NULL, NULL );
1101                         goto done;
1102                 } else {
1103                         printf( _("modrdn completed\n") );
1104                 }
1105
1106                 rc = process_response( ld, msgid, LDAP_RES_RENAME, dn );
1107
1108         } else {
1109                 rc = LDAP_SUCCESS;
1110         }
1111
1112 done:
1113         putchar( '\n' );
1114         return( rc );
1115 }
1116
1117 static const char *
1118 res2str( int res ) {
1119         switch ( res ) {
1120         case LDAP_RES_ADD:
1121                 return "ldap_add";
1122         case LDAP_RES_DELETE:
1123                 return "ldap_delete";
1124         case LDAP_RES_MODIFY:
1125                 return "ldap_modify";
1126         case LDAP_RES_MODRDN:
1127                 return "ldap_modrdn";
1128         default:
1129                 assert( 0 );
1130         }
1131
1132         return "ldap_unknown";
1133 }
1134
1135 static int process_response(
1136         LDAP *ld,
1137         int msgid,
1138         int op,
1139         const char *dn )
1140 {
1141         LDAPMessage     *res;
1142         int             rc = LDAP_OTHER, msgtype;
1143         struct timeval  tv = { 0, 0 };
1144         int             err;
1145         char            *text = NULL, *matched = NULL, **refs = NULL;
1146         LDAPControl     **ctrls = NULL;
1147
1148         for ( ; ; ) {
1149                 tv.tv_sec = 0;
1150                 tv.tv_usec = 100000;
1151
1152                 rc = ldap_result( ld, msgid, LDAP_MSG_ALL, &tv, &res );
1153                 if ( tool_check_abandon( ld, msgid ) ) {
1154                         return LDAP_CANCELLED;
1155                 }
1156
1157                 if ( rc == -1 ) {
1158                         ldap_get_option( ld, LDAP_OPT_ERROR_NUMBER, &rc );
1159                         return rc;
1160                 }
1161
1162                 if ( rc != 0 ) {
1163                         break;
1164                 }
1165         }
1166
1167         msgtype = ldap_msgtype( res );
1168
1169         rc = ldap_parse_result( ld, res, &err, &matched, &text, &refs, &ctrls, 1 );
1170         if ( rc == LDAP_SUCCESS ) rc = err;
1171
1172         if ( rc != LDAP_SUCCESS ) {
1173                 tool_perror( res2str( op ), rc, NULL, matched, text, refs );
1174         } else if ( msgtype != op ) {
1175                 fprintf( stderr, "%s: msgtype: expected %d got %d\n",
1176                         res2str( op ), op, msgtype );
1177                 rc = LDAP_OTHER;
1178         }
1179
1180         if ( text ) ldap_memfree( text );
1181         if ( matched ) ldap_memfree( matched );
1182         if ( text ) ber_memvfree( (void **)refs );
1183
1184         if ( ctrls != NULL ) {
1185                 tool_print_ctrls( ld, ctrls );
1186                 ldap_controls_free( ctrls );
1187         }
1188
1189         return rc;
1190 }
1191
1192 static char *
1193 read_one_record( FILE *fp )
1194 {
1195         char        *buf, line[ LDAPMOD_MAXLINE ];
1196         int             lcur, lmax;
1197
1198         lcur = lmax = 0;
1199         buf = NULL;
1200
1201         while ( fgets( line, sizeof(line), fp ) != NULL ) {
1202                 int len = strlen( line );
1203
1204                 if( len < 2 || ( len == 2 && *line == '\r' )) {
1205                         if( buf == NULL ) {
1206                                 continue;
1207                         } else {
1208                                 break;
1209                         }
1210                 }
1211
1212                 if ( lcur + len + 1 > lmax ) {
1213                         lmax = LDAPMOD_MAXLINE
1214                                 * (( lcur + len + 1 ) / LDAPMOD_MAXLINE + 1 );
1215
1216                         if (( buf = (char *)ber_memrealloc( buf, lmax )) == NULL ) {
1217                                 perror( "realloc" );
1218                                 exit( EXIT_FAILURE );
1219                         }
1220                 }
1221
1222                 strcpy( buf + lcur, line );
1223                 lcur += len;
1224         }
1225
1226         return( buf );
1227 }
1228
1229