]> git.sur5r.net Git - openldap/blob - clients/tools/ldapmodify.c
partial sync
[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-2005 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) free( rejbuf );
393                 free( 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                                         replicaport = atoi( p );
471                                 }
472                                 if ( ldaphost != NULL &&
473                                         strcasecmp( val.bv_val, ldaphost ) == 0 &&
474                                         replicaport == ldapport )
475                                 {
476                                         use_record = 1;
477                                 }
478                         } else if ( count == 1 && linenum == 1 && 
479                                 strcasecmp( type, T_VERSION_STR ) == 0 )
480                         {
481                                 if( val.bv_len == 0 || atoi(val.bv_val) != 1 ) {
482                                         fprintf( stderr,
483                                                 _("%s: invalid version %s, line %d (ignored)\n"),
484                                                 prog, val.bv_val, linenum );
485                                 }
486                                 version++;
487
488                         } else if ( strcasecmp( type, T_DN_STR ) == 0 ) {
489                                 if (( dn = ber_strdup( val.bv_val )) == NULL ) {
490                                         perror( "strdup" );
491                                         exit( EXIT_FAILURE );
492                                 }
493                                 expect_ct = 1;
494                         }
495                         goto end_line;  /* skip all lines until we see "dn:" */
496                 }
497
498                 if ( expect_ct ) {
499                         /* Check for "control" tag after dn and before changetype. */
500                         if (strcasecmp(type, T_CONTROL_STR) == 0) {
501                                 /* Parse and add it to the list of controls */
502                                 rc = parse_ldif_control( line, &pctrls );
503                                 if (rc != 0) {
504                                         fprintf( stderr,
505                                                 _("%s: Error processing %s line, line %d: %s\n"),
506                                                 prog, T_CONTROL_STR, linenum, ldap_err2string(rc) );
507                                 }
508                                 goto end_line;
509                         }
510
511                         expect_ct = 0;
512                         if ( !use_record && saw_replica ) {
513                                 printf(_("%s: skipping change record for entry: %s\n"),
514                                         prog, dn);
515                                 printf(_("\t(LDAP host/port does not match replica: lines)\n"));
516                                 free( dn );
517                                 ber_memfree( type );
518                                 ber_memfree( val.bv_val );
519                                 return( 0 );
520                         }
521
522                         if ( strcasecmp( type, T_CHANGETYPESTR ) == 0 ) {
523 #ifdef LIBERAL_CHANGETYPE_MODOP
524                                 /* trim trailing spaces (and log warning ...) */
525                                 int icnt;
526                                 for ( icnt = val.bv_len; --icnt > 0; ) {
527                                         if ( !isspace( (unsigned char) val.bv_val[icnt] ) ) {
528                                                 break;
529                                         }
530                                 }
531
532                                 if ( ++icnt != val.bv_len ) {
533                                         fprintf( stderr, _("%s: illegal trailing space after"
534                                                 " \"%s: %s\" trimmed (line %d of entry \"%s\")\n"),
535                                                 prog, T_CHANGETYPESTR, val.bv_val, linenum, dn );
536                                         val.bv_val[icnt] = '\0';
537                                 }
538 #endif /* LIBERAL_CHANGETYPE_MODOP */
539
540                                 if ( strcasecmp( val.bv_val, T_MODIFYCTSTR ) == 0 ) {
541                                         new_entry = 0;
542                                         expect_modop = 1;
543                                 } else if ( strcasecmp( val.bv_val, T_ADDCTSTR ) == 0 ) {
544                                         new_entry = 1;
545                                 } else if ( strcasecmp( val.bv_val, T_MODRDNCTSTR ) == 0
546                                         || strcasecmp( val.bv_val, T_MODDNCTSTR ) == 0
547                                         || strcasecmp( val.bv_val, T_RENAMECTSTR ) == 0)
548                                 {
549                                         expect_newrdn = 1;
550                                 } else if ( strcasecmp( val.bv_val, T_DELETECTSTR ) == 0 ) {
551                                         got_all = delete_entry = 1;
552                                 } else {
553                                         fprintf( stderr,
554                                                 _("%s:  unknown %s \"%s\" (line %d of entry \"%s\")\n"),
555                                                 prog, T_CHANGETYPESTR, val.bv_val, linenum, dn );
556                                         rc = LDAP_PARAM_ERROR;
557                                 }
558                                 goto end_line;
559                         } else if ( ldapadd ) {         /*  missing changetype => add */
560                                 new_entry = 1;
561                                 modop = LDAP_MOD_ADD;
562                         } else {
563                                 expect_modop = 1;       /* missing changetype => modify */
564                         }
565                 }
566
567                 if ( expect_modop ) {
568 #ifdef LIBERAL_CHANGETYPE_MODOP
569                         /* trim trailing spaces (and log warning ...) */
570                     int icnt;
571                     for ( icnt = val.bv_len; --icnt > 0; ) {
572                                 if ( !isspace( (unsigned char) val.bv_val[icnt] ) ) break;
573                         }
574     
575                         if ( ++icnt != val.bv_len ) {
576                                 fprintf( stderr, _("%s: illegal trailing space after"
577                                         " \"%s: %s\" trimmed (line %d of entry \"%s\")\n"),
578                                         prog, type, val.bv_val, linenum, dn );
579                                 val.bv_val[icnt] = '\0';
580                         }
581 #endif /* LIBERAL_CHANGETYPE_MODOP */
582
583                         expect_modop = 0;
584                         expect_sep = 1;
585                         if ( strcasecmp( type, T_MODOPADDSTR ) == 0 ) {
586                                 modop = LDAP_MOD_ADD;
587                                 goto end_line;
588                         } else if ( strcasecmp( type, T_MODOPREPLACESTR ) == 0 ) {
589                                 modop = LDAP_MOD_REPLACE;
590                                 addmodifyop( &pmods, modop, val.bv_val, NULL );
591                                 goto end_line;
592                         } else if ( strcasecmp( type, T_MODOPDELETESTR ) == 0 ) {
593                                 modop = LDAP_MOD_DELETE;
594                                 addmodifyop( &pmods, modop, val.bv_val, NULL );
595                                 goto end_line;
596                         } else if ( strcasecmp( type, T_MODOPINCREMENTSTR ) == 0 ) {
597                                 modop = LDAP_MOD_INCREMENT;
598                                 addmodifyop( &pmods, modop, val.bv_val, NULL );
599                                 goto end_line;
600                         } else {        /* no modify op:  use default */
601                                 modop = ldapadd ? LDAP_MOD_ADD : LDAP_MOD_REPLACE;
602                         }
603                 }
604
605                 if ( expect_newrdn ) {
606                         if ( strcasecmp( type, T_NEWRDNSTR ) == 0 ) {
607                                 if (( newrdn = ber_strdup( val.bv_val )) == NULL ) {
608                                         perror( "strdup" );
609                                         exit( EXIT_FAILURE );
610                                 }
611                                 expect_deleteoldrdn = 1;
612                                 expect_newrdn = 0;
613                         } else {
614                                 fprintf( stderr, _("%s: expecting \"%s:\" but saw"
615                                         " \"%s:\" (line %d of entry \"%s\")\n"),
616                                         prog, T_NEWRDNSTR, type, linenum, dn );
617                                 rc = LDAP_PARAM_ERROR;
618                         }
619                 } else if ( expect_deleteoldrdn ) {
620                         if ( strcasecmp( type, T_DELETEOLDRDNSTR ) == 0 ) {
621                                 deleteoldrdn = ( *val.bv_val == '0' ) ? 0 : 1;
622                                 expect_deleteoldrdn = 0;
623                                 expect_newsup = 1;
624                                 got_all = 1;
625                         } else {
626                                 fprintf( stderr, _("%s: expecting \"%s:\" but saw"
627                                         " \"%s:\" (line %d of entry \"%s\")\n"),
628                                         prog, T_DELETEOLDRDNSTR, type, linenum, dn );
629                                 rc = LDAP_PARAM_ERROR;
630                         }
631                 } else if ( expect_newsup ) {
632                         if ( strcasecmp( type, T_NEWSUPSTR ) == 0 ) {
633                                 if (( newsup = ber_strdup( val.bv_val )) == NULL ) {
634                                         perror( "strdup" );
635                                         exit( EXIT_FAILURE );
636                                 }
637                                 expect_newsup = 0;
638                         } else {
639                                 fprintf( stderr, _("%s: expecting \"%s:\" but saw"
640                                         " \"%s:\" (line %d of entry \"%s\")\n"),
641                                         prog, T_NEWSUPSTR, type, linenum, dn );
642                                 rc = LDAP_PARAM_ERROR;
643                         }
644                 } else if ( got_all ) {
645                         fprintf( stderr,
646                                 _("%s: extra lines at end (line %d of entry \"%s\")\n"),
647                                 prog, linenum, dn );
648                         rc = LDAP_PARAM_ERROR;
649                 } else {
650                         if ( new_entry && strcasecmp( type, T_DN_STR ) == 0 ) {
651                                 fprintf( stderr, _("%s: attributeDescription \"%s\":"
652                                         " (possible missing newline"
653                                                 " after line %d of entry \"%s\"?)\n"),
654                                         prog, type, linenum - 1, dn );
655                         }
656                         addmodifyop( &pmods, modop, type, &val );
657                 }
658
659 end_line:
660                 ber_memfree( type );
661                 ber_memfree( val.bv_val );
662         }
663
664         if( linenum == 0 ) {
665                 return 0;
666         }
667
668         if( version && linenum == 1 ) {
669                 return 0;
670         }
671
672         /* If default controls are set (as with -M option) and controls are
673            specified in the LDIF file, we must add the default controls to
674            the list of controls sent with the ldap operation.
675         */
676         if ( rc == 0 ) {
677                 if (pctrls) {
678                         LDAPControl **defctrls = NULL;   /* Default server controls */
679                         LDAPControl **newctrls = NULL;
680                         ldap_get_option(ld, LDAP_OPT_SERVER_CONTROLS, &defctrls);
681                         if (defctrls) {
682                                 int npc=0;                       /* Num of LDIF controls */
683                                 int ndefc=0;                     /* Num of default controls */
684                                 while (pctrls[npc]) npc++;       /* Count LDIF controls */
685                                 while (defctrls[ndefc]) ndefc++; /* Count default controls */
686                                 newctrls = ber_memrealloc(pctrls,
687                                         (npc+ndefc+1)*sizeof(LDAPControl*));
688
689                                 if (newctrls == NULL) {
690                                         rc = LDAP_NO_MEMORY;
691                                 } else {
692                                         int i;
693                                         pctrls = newctrls;
694                                         for (i=npc; i<npc+ndefc; i++) {
695                                                 pctrls[i] = ldap_control_dup(defctrls[i-npc]);
696                                                 if (pctrls[i] == NULL) {
697                                                         rc = LDAP_NO_MEMORY;
698                                                         break;
699                                                 }
700                                         }
701                                         pctrls[npc+ndefc] = NULL;
702                                 }
703                                 ldap_controls_free(defctrls);  /* Must be freed by library */
704                         }
705                 }
706         }
707
708
709         if ( rc == 0 ) {
710                 if ( delete_entry ) {
711                         rc = dodelete( dn, pctrls );
712                 } else if ( newrdn != NULL ) {
713                         rc = dorename( dn, newrdn, newsup, deleteoldrdn, pctrls );
714                 } else {
715                         rc = domodify( dn, pmods, pctrls, new_entry );
716                 }
717
718                 if ( rc == LDAP_SUCCESS ) {
719                         rc = 0;
720                 }
721         }
722
723         if ( dn != NULL ) {
724                 free( dn );
725         }
726         if ( newrdn != NULL ) {
727                 free( newrdn );
728         }
729         if ( newsup != NULL ) {
730                 free( newsup );
731         }
732         if ( pmods != NULL ) {
733                 ldap_mods_free( pmods, 1 );
734         }
735     if (pctrls != NULL) {
736         ldap_controls_free( pctrls );
737         }
738
739         return( rc );
740 }
741
742 /* Parse an LDIF control line of the form
743       control:  oid  [true/false]  [: value]              or
744       control:  oid  [true/false]  [:: base64-value]      or
745       control:  oid  [true/false]  [:< url]
746    The control is added to the list of controls in *ppctrls.
747 */      
748 static int
749 parse_ldif_control(
750         char *line, 
751         LDAPControl ***ppctrls )
752 {
753         char *oid = NULL;
754         int criticality = 0;   /* Default is false if not present */
755         char *type=NULL;
756         char *val = NULL;
757         ber_len_t value_len = 0;
758         int i, rc=0;
759         char *s, *oidStart, *pcolon;
760         LDAPControl *newctrl = NULL;
761         LDAPControl **pctrls = NULL;
762
763         if (ppctrls) pctrls = *ppctrls;
764         s = line + strlen(T_CONTROL_STR);  /* Skip over "control" */
765         pcolon = s;                        /* Save this position for later */
766         if (*s++ != ':') {                 /* Make sure colon follows */
767                 return ( LDAP_PARAM_ERROR );
768         }
769         while (*s && isspace((unsigned char)*s)) {
770                 s++;                           /* Skip white space before OID */
771         }
772
773         /* OID should come next. Validate and extract it. */
774         if (*s == 0) return ( LDAP_PARAM_ERROR );
775         oidStart = s;
776         while (isdigit((unsigned char)*s) || *s == '.') {
777                 s++;                           /* OID should be digits or . */
778         }
779         if (s == oidStart) { 
780                 return ( LDAP_PARAM_ERROR );   /* OID was not present */
781         }
782         if (*s) {                          /* End of OID should be space or NULL */
783                 if (!isspace((unsigned char)*s)) {
784                         return ( LDAP_PARAM_ERROR ); /* else OID contained invalid chars */
785                 }
786                 *s++ = 0;                    /* Replace space with null to terminate */
787         }
788
789         oid = ber_strdup(oidStart);
790         if (oid == NULL) return ( LDAP_NO_MEMORY );
791
792         /* Optional Criticality field is next. */
793         while (*s && isspace((unsigned char)*s)) {
794                 s++;                         /* Skip white space before criticality */
795         }
796         if (strncasecmp(s, "true", 4) == 0) {
797                 criticality = 1;
798                 s += 4;
799         } 
800         else if (strncasecmp(s, "false", 5) == 0) {
801                 criticality = 0;
802                 s += 5;
803         }
804
805         /* Optional value field is next */
806         while (*s && isspace((unsigned char)*s)) {
807                 s++;                         /* Skip white space before value */
808         }
809         if (*s) {
810                 if (*s != ':') {           /* If value is present, must start with : */
811                         rc = LDAP_PARAM_ERROR;
812                         goto cleanup;
813                 }
814
815                 /* Shift value down over OID and criticality so it's in the form
816                      control: value
817                      control:: base64-value
818                      control:< url
819                    Then we can use ldif_parse_line to extract and decode the value
820                 */
821                 while ( (*pcolon++ = *s++) != 0) {   /* Shift value */
822                         /* EMPTY */;
823                 }
824                 rc = ldif_parse_line(line, &type, &val, &value_len);
825                 if (type)  ber_memfree(type);   /* Don't need this field*/
826                 if (rc < 0) {
827                         rc = LDAP_PARAM_ERROR;
828                         goto cleanup;
829                 }
830     }
831
832         /* Create a new LDAPControl structure. */
833         newctrl = (LDAPControl *)ber_memalloc(sizeof(LDAPControl));
834         if ( newctrl == NULL ) {
835                 rc = LDAP_NO_MEMORY;
836                 goto cleanup;
837         }
838         newctrl->ldctl_oid = oid;
839         oid = NULL;
840         newctrl->ldctl_iscritical = criticality;
841         newctrl->ldctl_value.bv_len = value_len;
842         newctrl->ldctl_value.bv_val = val;
843         val = NULL;
844
845         /* Add the new control to the passed-in list of controls. */
846         i = 0;
847         if (pctrls) {
848                 while ( pctrls[i] ) {    /* Count the # of controls passed in */
849                         i++;
850                 }
851         }
852         /* Allocate 1 more slot for the new control and 1 for the NULL. */
853         pctrls = (LDAPControl **) ber_memrealloc(pctrls,
854                 (i+2)*(sizeof(LDAPControl *)));
855         if (pctrls == NULL) {
856                 rc = LDAP_NO_MEMORY;
857                 goto cleanup;
858         }
859         pctrls[i] = newctrl;
860         newctrl = NULL;
861         pctrls[i+1] = NULL;
862         *ppctrls = pctrls;
863
864 cleanup:
865         if (newctrl) {
866                 if (newctrl->ldctl_oid) ber_memfree(newctrl->ldctl_oid);
867                 if (newctrl->ldctl_value.bv_val) {
868                         ber_memfree(newctrl->ldctl_value.bv_val);
869                 }
870                 ber_memfree(newctrl);
871         }
872         if (val) ber_memfree(val);
873         if (oid) ber_memfree(oid);
874
875         return( rc );
876 }
877
878
879 static void
880 addmodifyop(
881         LDAPMod ***pmodsp,
882         int modop,
883         const char *attr,
884         struct berval *val )
885 {
886         LDAPMod         **pmods;
887         int                     i, j;
888
889         pmods = *pmodsp;
890         modop |= LDAP_MOD_BVALUES;
891
892         i = 0;
893         if ( pmods != NULL ) {
894                 for ( ; pmods[ i ] != NULL; ++i ) {
895                         if ( strcasecmp( pmods[ i ]->mod_type, attr ) == 0 &&
896                                 pmods[ i ]->mod_op == modop )
897                         {
898                                 break;
899                         }
900                 }
901         }
902
903         if ( pmods == NULL || pmods[ i ] == NULL ) {
904                 if (( pmods = (LDAPMod **)ber_memrealloc( pmods, (i + 2) *
905                         sizeof( LDAPMod * ))) == NULL )
906                 {
907                         perror( "realloc" );
908                         exit( EXIT_FAILURE );
909                 }
910
911                 *pmodsp = pmods;
912                 pmods[ i + 1 ] = NULL;
913
914                 pmods[ i ] = (LDAPMod *)ber_memcalloc( 1, sizeof( LDAPMod ));
915                 if ( pmods[ i ] == NULL ) {
916                         perror( "calloc" );
917                         exit( EXIT_FAILURE );
918                 }
919
920                 pmods[ i ]->mod_op = modop;
921                 pmods[ i ]->mod_type = ber_strdup( attr );
922                 if ( pmods[ i ]->mod_type == NULL ) {
923                         perror( "strdup" );
924                         exit( EXIT_FAILURE );
925                 }
926         }
927
928         if ( val != NULL ) {
929                 j = 0;
930                 if ( pmods[ i ]->mod_bvalues != NULL ) {
931                         for ( ; pmods[ i ]->mod_bvalues[ j ] != NULL; ++j ) {
932                                 /* Empty */;
933                         }
934                 }
935
936                 pmods[ i ]->mod_bvalues = (struct berval **) ber_memrealloc(
937                         pmods[ i ]->mod_bvalues, (j + 2) * sizeof( struct berval * ));
938                 if ( pmods[ i ]->mod_bvalues == NULL ) {
939                         perror( "ber_realloc" );
940                         exit( EXIT_FAILURE );
941                 }
942
943                 pmods[ i ]->mod_bvalues[ j + 1 ] = NULL;
944                 pmods[ i ]->mod_bvalues[ j ] = ber_bvdup( val );
945                 if ( pmods[ i ]->mod_bvalues[ j ] == NULL ) {
946                         perror( "ber_bvdup" );
947                         exit( EXIT_FAILURE );
948                 }
949         }
950 }
951
952
953 static int
954 domodify(
955         const char *dn,
956         LDAPMod **pmods,
957         LDAPControl **pctrls,
958         int newentry )
959 {
960         int                     rc, i, j, k, notascii, op;
961         struct berval   *bvp;
962
963         if ( dn == NULL ) {
964                 fprintf( stderr, _("%s: no DN specified\n"), prog );
965                 return( LDAP_PARAM_ERROR );
966         }
967
968         if ( pmods == NULL ) {
969                 /* implement "touch" (empty sequence)
970                  * modify operation (note that there
971                  * is no symmetry with the UNIX command,
972                  * since \"touch\" on a non-existent entry
973                  * will fail)*/
974                 printf( "warning: no attributes to %sadd (entry=\"%s\")\n",
975                         newentry ? "" : "change or ", dn );
976
977         } else {
978                 for ( i = 0; pmods[ i ] != NULL; ++i ) {
979                         op = pmods[ i ]->mod_op & ~LDAP_MOD_BVALUES;
980                         if( op == LDAP_MOD_ADD && ( pmods[i]->mod_bvalues == NULL )) {
981                                 fprintf( stderr,
982                                         _("%s: attribute \"%s\" has no values (entry=\"%s\")\n"),
983                                         prog, pmods[i]->mod_type, dn );
984                                 return LDAP_PARAM_ERROR;
985                         }
986                 }
987
988                 if ( verbose ) {
989                         for ( i = 0; pmods[ i ] != NULL; ++i ) {
990                                 op = pmods[ i ]->mod_op & ~LDAP_MOD_BVALUES;
991                                 printf( "%s %s:\n",
992                                         op == LDAP_MOD_REPLACE ? _("replace") :
993                                                 op == LDAP_MOD_ADD ?  _("add") :
994                                                         op == LDAP_MOD_INCREMENT ?  _("increment") :
995                                                                 op == LDAP_MOD_DELETE ?  _("delete") :
996                                                                         _("unknown"),
997                                         pmods[ i ]->mod_type );
998         
999                                 if ( pmods[ i ]->mod_bvalues != NULL ) {
1000                                         for ( j = 0; pmods[ i ]->mod_bvalues[ j ] != NULL; ++j ) {
1001                                                 bvp = pmods[ i ]->mod_bvalues[ j ];
1002                                                 notascii = 0;
1003                                                 for ( k = 0; (unsigned long) k < bvp->bv_len; ++k ) {
1004                                                         if ( !isascii( bvp->bv_val[ k ] )) {
1005                                                                 notascii = 1;
1006                                                                 break;
1007                                                         }
1008                                                 }
1009                                                 if ( notascii ) {
1010                                                         printf( _("\tNOT ASCII (%ld bytes)\n"), bvp->bv_len );
1011                                                 } else {
1012                                                         printf( "\t%s\n", bvp->bv_val );
1013                                                 }
1014                                         }
1015                                 }
1016                         }
1017                 }
1018         }
1019
1020         if ( newentry ) {
1021                 printf( "%sadding new entry \"%s\"\n", not ? "!" : "", dn );
1022         } else {
1023                 printf( "%smodifying entry \"%s\"\n", not ? "!" : "", dn );
1024         }
1025
1026         if ( !not ) {
1027                 int     msgid;
1028                 if ( newentry ) {
1029                         rc = ldap_add_ext( ld, dn, pmods, pctrls, NULL, &msgid );
1030                 } else {
1031                         rc = ldap_modify_ext( ld, dn, pmods, pctrls, NULL, &msgid );
1032                 }
1033
1034                 if ( rc != LDAP_SUCCESS ) {
1035                         /* print error message about failed update including DN */
1036                         fprintf( stderr, _("%s: update failed: %s\n"), prog, dn );
1037                         ldap_perror( ld, newentry ? "ldap_add" : "ldap_modify" );
1038                         goto done;
1039                 } else if ( verbose ) {
1040                         printf( _("modify complete\n") );
1041                 }
1042
1043                 rc = process_response( ld, msgid,
1044                         newentry ? "ldap_add" : "ldap_modify", dn );
1045
1046         } else {
1047                 rc = LDAP_SUCCESS;
1048         }
1049
1050 done:
1051         putchar( '\n' );
1052         return rc;
1053 }
1054
1055
1056 static int
1057 dodelete(
1058         const char *dn,
1059         LDAPControl **pctrls )
1060 {
1061         int     rc;
1062         int msgid;
1063
1064         printf( _("%sdeleting entry \"%s\"\n"), not ? "!" : "", dn );
1065         if ( !not ) {
1066                 rc = ldap_delete_ext( ld, dn, pctrls, NULL, &msgid );
1067                 if ( rc != LDAP_SUCCESS ) {
1068                         fprintf( stderr, _("%s: delete failed: %s\n"), prog, dn );
1069                         ldap_perror( ld, "ldap_delete" );
1070                         goto done;
1071                 } else if ( verbose ) {
1072                         printf( _("delete complete") );
1073                 }
1074
1075                 rc = process_response( ld, msgid, "ldap_delete", dn );
1076
1077         } else {
1078                 rc = LDAP_SUCCESS;
1079         }
1080
1081 done:
1082         putchar( '\n' );
1083         return( rc );
1084 }
1085
1086
1087 static int
1088 dorename(
1089         const char *dn,
1090         const char *newrdn,
1091         const char* newsup,
1092         int deleteoldrdn,
1093         LDAPControl **pctrls )
1094 {
1095         int     rc;
1096         int msgid;
1097
1098         printf( _("%smodifying rdn of entry \"%s\"\n"), not ? "!" : "", dn );
1099         if ( verbose ) {
1100                 printf( _("\tnew RDN: \"%s\" (%skeep existing values)\n"),
1101                         newrdn, deleteoldrdn ? _("do not ") : "" );
1102         }
1103         if ( !not ) {
1104                 rc = ldap_rename( ld, dn, newrdn, newsup, deleteoldrdn,
1105                         pctrls, NULL, &msgid );
1106                 if ( rc != LDAP_SUCCESS ) {
1107                         fprintf( stderr, _("%s: rename failed: %s\n"), prog, dn );
1108                         ldap_perror( ld, "ldap_modrdn" );
1109                         goto done;
1110                 } else {
1111                         printf( _("modrdn completed\n") );
1112                 }
1113
1114                 rc = process_response( ld, msgid, "ldap_rename", dn );
1115
1116         } else {
1117                 rc = LDAP_SUCCESS;
1118         }
1119
1120 done:
1121         putchar( '\n' );
1122         return( rc );
1123 }
1124
1125 static int process_response(
1126         LDAP *ld,
1127         int msgid,
1128         const char *opstr,
1129         const char *dn )
1130 {
1131         LDAPMessage     *res;
1132         int             rc = LDAP_OTHER;
1133         struct timeval  tv = { 0, 0 };
1134
1135         for ( ; ; ) {
1136                 tv.tv_sec = 0;
1137                 tv.tv_usec = 100000;
1138
1139                 rc = ldap_result( ld, msgid,
1140 #ifdef LDAP_GROUP_TRANSACTION
1141                         txn ? 0 : 1,
1142 #else
1143                         1,
1144 #endif
1145                         &tv, &res );
1146                 if ( tool_check_abandon( ld, msgid ) ) {
1147                         return LDAP_CANCELLED;
1148                 }
1149
1150                 if ( rc == -1 ) {
1151                         ldap_get_option( ld, LDAP_OPT_ERROR_NUMBER, &rc );
1152                         return rc;
1153                 }
1154
1155                 if ( rc != 0 ) {
1156                         break;
1157                 }
1158         }
1159
1160         if ( ldap_msgtype( res ) != LDAP_RES_INTERMEDIATE ) {
1161                 rc = ldap_result2error( ld, res, 1 );
1162                 if( rc != LDAP_SUCCESS ) ldap_perror( ld, opstr );
1163                 return rc;
1164         }
1165
1166 #ifdef LDAP_GROUP_TRANSACTION
1167         /* assume (successful) transaction intermediate response */
1168         return LDAP_SUCCESS;
1169
1170 #else
1171         /* intermediate response? */
1172         return LDAP_DECODING_ERROR;
1173 #endif
1174 }
1175
1176 static char *
1177 read_one_record( FILE *fp )
1178 {
1179         char        *buf, line[ LDAPMOD_MAXLINE ];
1180         int             lcur, lmax;
1181
1182         lcur = lmax = 0;
1183         buf = NULL;
1184
1185         while ( fgets( line, sizeof(line), fp ) != NULL ) {
1186                 int len = strlen( line );
1187
1188                 if( len < 2 || ( len == 2 && *line == '\r' )) {
1189                         if( buf == NULL ) {
1190                                 continue;
1191                         } else {
1192                                 break;
1193                         }
1194                 }
1195
1196                 if ( lcur + len + 1 > lmax ) {
1197                         lmax = LDAPMOD_MAXLINE
1198                                 * (( lcur + len + 1 ) / LDAPMOD_MAXLINE + 1 );
1199
1200                         if (( buf = (char *)ber_memrealloc( buf, lmax )) == NULL ) {
1201                                 perror( "realloc" );
1202                                 exit( EXIT_FAILURE );
1203                         }
1204                 }
1205
1206                 strcpy( buf + lcur, line );
1207                 lcur += len;
1208         }
1209
1210         return( buf );
1211 }
1212
1213