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