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