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