]> git.sur5r.net Git - openldap/blob - clients/tools/ldapmodify.c
silence warnings
[openldap] / clients / tools / ldapmodify.c
1 /* ldapmodify.c - generic program to modify or add entries using LDAP */
2 /* $OpenLDAP$ */
3 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
4  *
5  * Copyright 1998-2006 The OpenLDAP Foundation.
6  * Portions Copyright 1998-2003 Kurt D. Zeilenga.
7  * Portions Copyright 1998-2001 Net Boolean Incorporated.
8  * Portions Copyright 2001-2003 IBM Corporation.
9  * All rights reserved.
10  *
11  * Redistribution and use in source and binary forms, with or without
12  * modification, are permitted only as authorized by the OpenLDAP
13  * Public License.
14  *
15  * A copy of this license is available in the file LICENSE in the
16  * top-level directory of the distribution or, alternatively, at
17  * <http://www.OpenLDAP.org/license.html>.
18  */
19 /* Portions Copyright (c) 1992-1996 Regents of the University of Michigan.
20  * All rights reserved.
21  *
22  * Redistribution and use in source and binary forms are permitted
23  * provided that this notice is preserved and that due credit is given
24  * to the University of Michigan at Ann Arbor.  The name of the
25  * University may not be used to endorse or promote products derived
26  * from this software without specific prior written permission.  This
27  * software is provided ``as is'' without express or implied warranty.
28  */
29 /* ACKNOWLEDGEMENTS:
30  * This work was originally developed by the University of Michigan
31  * (as part of U-MICH LDAP).  Additional significant contributors
32  * include:
33  *   Kurt D. Zeilenga
34  *   Norbert Klasen
35  */
36
37 #include "portable.h"
38
39 #include <stdio.h>
40
41 #include <ac/stdlib.h>
42 #include <ac/ctype.h>
43 #include <ac/string.h>
44 #include <ac/unistd.h>
45 #include <ac/time.h>
46
47 #ifdef HAVE_SYS_STAT_H
48 #include <sys/stat.h>
49 #endif
50
51 #ifdef HAVE_SYS_FILE_H
52 #include <sys/file.h>
53 #endif
54 #ifdef HAVE_FCNTL_H
55 #include <fcntl.h>
56 #endif
57
58 #include <ldap.h>
59
60 #include "lutil.h"
61 #include "lutil_ldap.h"
62 #include "ldif.h"
63 #include "ldap_defaults.h"
64 #include "ldap_log.h"
65 #include "ldap_pvt.h"
66
67 #include "common.h"
68
69
70 static int      ldapadd, force = 0;
71 static char *rejfile = NULL;
72 static LDAP     *ld = NULL;
73
74 #define LDAPMOD_MAXLINE         4096
75
76 /* strings found in replog/LDIF entries (mostly lifted from slurpd/slurp.h) */
77 #define T_VERSION_STR           "version"
78 #define T_REPLICA_STR           "replica"
79 #define T_DN_STR                        "dn"
80 #define T_CONTROL_STR           "control"
81 #define T_CHANGETYPESTR         "changetype"
82 #define T_ADDCTSTR                      "add"
83 #define T_MODIFYCTSTR           "modify"
84 #define T_DELETECTSTR           "delete"
85 #define T_MODRDNCTSTR           "modrdn"
86 #define T_MODDNCTSTR            "moddn"
87 #define T_RENAMECTSTR           "rename"
88 #define T_MODOPADDSTR           "add"
89 #define T_MODOPREPLACESTR       "replace"
90 #define T_MODOPDELETESTR        "delete"
91 #define T_MODOPINCREMENTSTR     "increment"
92 #define T_MODSEPSTR                     "-"
93 #define T_NEWRDNSTR                     "newrdn"
94 #define T_DELETEOLDRDNSTR       "deleteoldrdn"
95 #define T_NEWSUPSTR                     "newsuperior"
96
97
98 static int process_ldif_rec LDAP_P(( char *rbuf, int count ));
99 static int parse_ldif_control LDAP_P(( char *line, LDAPControl ***pctrls ));
100 static void addmodifyop LDAP_P((
101         LDAPMod ***pmodsp, int modop,
102         const char *attr,
103         struct berval *value ));
104 static int domodify LDAP_P((
105         const char *dn,
106         LDAPMod **pmods,
107         LDAPControl **pctrls,
108         int newentry ));
109 static int dodelete LDAP_P((
110         const char *dn,
111         LDAPControl **pctrls ));
112 static int dorename LDAP_P((
113         const char *dn,
114         const char *newrdn,
115         const char *newsup,
116         int deleteoldrdn,
117         LDAPControl **pctrls ));
118 static int process_response(
119         LDAP *ld,
120         int msgid,
121         int res,
122         const char *dn );
123 static char *read_one_record LDAP_P(( FILE *fp ));
124
125 #ifdef LDAP_X_TXN
126 static int txn = 0;
127 static int txnabort = 0;
128 struct berval *txn_id = NULL;
129 #endif
130
131 void
132 usage( void )
133 {
134         fprintf( stderr, _("Add or modify entries from an LDAP server\n\n"));
135         fprintf( stderr, _("usage: %s [options]\n"), prog);
136         fprintf( stderr, _("    The list of desired operations are read from stdin"
137                 " or from the file\n"));
138         fprintf( stderr, _("    specified by \"-f file\".\n"));
139         fprintf( stderr, _("Add or modify options:\n"));
140         fprintf( stderr, _("  -a         add values (%s)\n"),
141                 (ldapadd ? _("default") : _("default is to replace")));
142         fprintf( stderr, _("  -E [!]ext=extparam        modify extensions"
143                 " (! indicate s criticality)\n"));
144 #ifdef LDAP_X_TXN
145         fprintf( stderr,
146                 _("             [!]txn=<commit|abort>         (transaction)\n"));
147 #endif
148         fprintf( stderr, _("  -F         force all changes records to be used\n"));
149         fprintf( stderr, _("  -S file    write skipped modifications to `file'\n"));
150
151         tool_common_usage();
152         exit( EXIT_FAILURE );
153 }
154
155
156 const char options[] = "aE:FrS:"
157         "cd:D:e:f:h:H:IkKMnO:p:P:QR:U:vVw:WxX:y:Y:Z";
158
159 int
160 handle_private_option( int i )
161 {
162         char    *control, *cvalue;
163         int             crit;
164
165         switch ( i ) {
166         case 'E': /* modify extensions */
167                 if( protocol == LDAP_VERSION2 ) {
168                         fprintf( stderr, _("%s: -E incompatible with LDAPv%d\n"),
169                                 prog, protocol );
170                         exit( EXIT_FAILURE );
171                 }
172
173                 /* should be extended to support comma separated list of
174                  *      [!]key[=value] parameters, e.g.  -E !foo,bar=567
175                  */
176
177                 crit = 0;
178                 cvalue = NULL;
179                 if( optarg[0] == '!' ) {
180                         crit = 1;
181                         optarg++;
182                 }
183
184                 control = ber_strdup( optarg );
185                 if ( (cvalue = strchr( control, '=' )) != NULL ) {
186                         *cvalue++ = '\0';
187                 }
188
189 #ifdef LDAP_X_TXN
190                 if( strcasecmp( control, "txn" ) == 0 ) {
191                         /* Transaction */
192                         if( txn ) {
193                                 fprintf( stderr,
194                                         _("txn control previously specified\n"));
195                                 exit( EXIT_FAILURE );
196                         }
197                         if( cvalue != NULL ) {
198                                 if( strcasecmp( cvalue, "abort" ) == 0 ) {
199                                         txnabort=1;
200                                 } else if( strcasecmp( cvalue, "commit" ) != 0 ) {
201                                         fprintf( stderr, _("Invalid value for txn control, %s\n"),
202                                                 cvalue );
203                                         exit( EXIT_FAILURE );
204                                 }
205                         }
206
207                         txn = 1 + crit;
208                 } else
209 #endif
210                 {
211                         fprintf( stderr, _("Invalid modify extension name: %s\n"),
212                                 control );
213                         usage();
214                 }
215                 break;
216
217         case 'a':       /* add */
218                 ldapadd = 1;
219                 break;
220
221         case 'F':       /* force all changes records to be used */
222                 force = 1;
223                 break;
224
225         case 'r':       /* replace (obsolete) */
226                 break;
227
228         case 'S':       /* skipped modifications to file */
229                 if( rejfile != NULL ) {
230                         fprintf( stderr, _("%s: -S previously specified\n"), prog );
231                         exit( EXIT_FAILURE );
232                 }
233                 rejfile = ber_strdup( optarg );
234                 break;
235
236         default:
237                 return 0;
238         }
239         return 1;
240 }
241
242
243 int
244 main( int argc, char **argv )
245 {
246         char            *rbuf, *start, *rejbuf = NULL;
247         FILE            *fp, *rejfp;
248         char            *matched_msg, *error_msg;
249         int             rc, retval;
250         int             count, len;
251         int             i = 0;
252         LDAPControl     c[1];
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_X_TXN
301         if( txn ) {
302                 /* start transaction */
303                 rc = ldap_txn_start_s( ld, NULL, NULL, &txn_id );
304                 if( rc != LDAP_SUCCESS ) {
305                         tool_perror( "ldap_txn_start_s", rc, NULL, NULL, NULL, NULL );
306                         if( txn > 1 ) return EXIT_FAILURE;
307                         txn = 0;
308                 }
309         }
310 #endif
311
312         if ( 0
313 #ifdef LDAP_X_TXN
314                 || txn
315 #endif
316                 )
317         {
318 #ifdef LDAP_X_TXN
319                 if( txn ) {
320                         c[i].ldctl_oid = LDAP_CONTROL_X_TXN_SPEC;
321                         c[i].ldctl_value = *txn_id;
322                         c[i].ldctl_iscritical = 1;
323                         i++;
324                 }
325 #endif
326         }
327
328         tool_server_controls( ld, c, i );
329
330         rc = 0;
331         count = 0;
332         retval = 0;
333         while (( rc == 0 || contoper ) &&
334                 ( rbuf = read_one_record( fp )) != NULL )
335         {
336                 count++;
337
338                 start = rbuf;
339
340                 if ( rejfp ) {
341                         len = strlen( rbuf );
342                         if (( rejbuf = (char *)ber_memalloc( len+1 )) == NULL ) {
343                                 perror( "malloc" );
344                                 exit( EXIT_FAILURE );
345                         }
346                         memcpy( rejbuf, rbuf, len+1 );
347                 }
348
349                 rc = process_ldif_rec( start, count );
350
351                 if ( rc ) retval = rc;
352                 if ( rc && rejfp ) {
353                         fprintf(rejfp, _("# Error: %s (%d)"), ldap_err2string(rc), rc);
354
355                         matched_msg = NULL;
356                         ldap_get_option(ld, LDAP_OPT_MATCHED_DN, &matched_msg);
357                         if ( matched_msg != NULL ) {
358                                 if ( *matched_msg != '\0' ) {
359                                         fprintf( rejfp, _(", matched DN: %s"), matched_msg );
360                                 }
361                                 ldap_memfree( matched_msg );
362                         }
363
364                         error_msg = NULL;
365                         ldap_get_option(ld, LDAP_OPT_ERROR_STRING, &error_msg);
366                         if ( error_msg != NULL ) {
367                                 if ( *error_msg != '\0' ) {
368                                         fprintf( rejfp, _(", additional info: %s"), error_msg );
369                                 }
370                                 ldap_memfree( error_msg );
371                         }
372                         fprintf( rejfp, "\n%s\n", rejbuf );
373                 }
374
375                 if (rejfp) free( rejbuf );
376                 free( rbuf );
377         }
378
379 #ifdef LDAP_X_TXN
380         if( retval == 0 && txn ) {
381                 rc = ldap_set_option( ld, LDAP_OPT_SERVER_CONTROLS, NULL );
382                 if ( rc != LDAP_OPT_SUCCESS ) {
383                         fprintf( stderr, "Could not unset controls for ldap_txn_end\n");
384                 }
385
386                 /* create transaction */
387                 rc = ldap_txn_end_s( ld, !txnabort, txn_id, NULL, NULL, NULL );
388                 if( rc != LDAP_SUCCESS ) {
389                         tool_perror( "ldap_txn_end_s", rc, NULL, NULL, NULL, NULL );
390                         retval = rc;
391                 }
392         }
393 #endif
394
395         if ( !dont ) {
396                 tool_unbind( ld );
397         }
398
399         if ( rejfp != NULL ) {
400                 fclose( rejfp );
401         }
402
403         tool_destroy();
404         return( retval );
405 }
406
407
408 static int
409 process_ldif_rec( char *rbuf, int count )
410 {
411         char    *line, *dn, *type, *newrdn, *newsup, *p;
412         int             rc, linenum, modop, replicaport;
413         int             expect_modop, expect_sep, expect_ct, expect_newrdn, expect_newsup;
414         int             expect_deleteoldrdn, deleteoldrdn;
415         int             saw_replica, use_record, new_entry, delete_entry, got_all;
416         LDAPMod **pmods;
417         int version;
418         struct berval val;
419         LDAPControl **pctrls;
420
421         new_entry = ldapadd;
422
423         rc = got_all = saw_replica = delete_entry = modop = expect_modop = 0;
424         expect_deleteoldrdn = expect_newrdn = expect_newsup = 0;
425         expect_sep = expect_ct = 0;
426         linenum = 0;
427         version = 0;
428         deleteoldrdn = 1;
429         use_record = force;
430         pmods = NULL;
431         pctrls = NULL;
432         dn = newrdn = newsup = NULL;
433
434         while ( rc == 0 && ( line = ldif_getline( &rbuf )) != NULL ) {
435                 ++linenum;
436
437                 if ( expect_sep && strcasecmp( line, T_MODSEPSTR ) == 0 ) {
438                         expect_sep = 0;
439                         expect_ct = 1;
440                         continue;
441                 }
442         
443                 if ( ldif_parse_line( line, &type, &val.bv_val, &val.bv_len ) < 0 ) {
444                         fprintf( stderr, _("%s: invalid format (line %d) entry: \"%s\"\n"),
445                                 prog, linenum, dn == NULL ? "" : dn );
446                         rc = LDAP_PARAM_ERROR;
447                         break;
448                 }
449
450                 if ( dn == NULL ) {
451                         if ( !use_record && strcasecmp( type, T_REPLICA_STR ) == 0 ) {
452                                 ++saw_replica;
453                                 if (( p = strchr( val.bv_val, ':' )) == NULL ) {
454                                         replicaport = 0;
455                                 } else {
456                                         *p++ = '\0';
457                                         if ( lutil_atoi( &replicaport, p ) != 0 ) {
458                                                 fprintf( stderr, _("%s: unable to parse replica port \"%s\" (line %d) entry: \"%s\"\n"),
459                                                         prog, p, linenum, dn == NULL ? "" : dn );
460                                                 rc = LDAP_PARAM_ERROR;
461                                                 break;
462                                         }
463                                 }
464                                 if ( ldaphost != NULL &&
465                                         strcasecmp( val.bv_val, ldaphost ) == 0 &&
466                                         replicaport == ldapport )
467                                 {
468                                         use_record = 1;
469                                 }
470                         } else if ( count == 1 && linenum == 1 && 
471                                 strcasecmp( type, T_VERSION_STR ) == 0 )
472                         {
473                                 int     v;
474                                 if( val.bv_len == 0 || lutil_atoi( &v, val.bv_val) != 0 || v != 1 ) {
475                                         fprintf( stderr,
476                                                 _("%s: invalid version %s, line %d (ignored)\n"),
477                                                 prog, val.bv_val, linenum );
478                                 }
479                                 version++;
480
481                         } else if ( strcasecmp( type, T_DN_STR ) == 0 ) {
482                                 if (( dn = ber_strdup( val.bv_val )) == NULL ) {
483                                         perror( "strdup" );
484                                         exit( EXIT_FAILURE );
485                                 }
486                                 expect_ct = 1;
487                         }
488                         goto end_line;  /* skip all lines until we see "dn:" */
489                 }
490
491                 if ( expect_ct ) {
492                         /* Check for "control" tag after dn and before changetype. */
493                         if (strcasecmp(type, T_CONTROL_STR) == 0) {
494                                 /* Parse and add it to the list of controls */
495                                 rc = parse_ldif_control( line, &pctrls );
496                                 if (rc != 0) {
497                                         fprintf( stderr,
498                                                 _("%s: Error processing %s line, line %d: %s\n"),
499                                                 prog, T_CONTROL_STR, linenum, ldap_err2string(rc) );
500                                 }
501                                 goto end_line;
502                         }
503
504                         expect_ct = 0;
505                         if ( !use_record && saw_replica ) {
506                                 printf(_("%s: skipping change record for entry: %s\n"),
507                                         prog, dn);
508                                 printf(_("\t(LDAP host/port does not match replica: lines)\n"));
509                                 free( dn );
510                                 ber_memfree( type );
511                                 ber_memfree( val.bv_val );
512                                 return( 0 );
513                         }
514
515                         if ( strcasecmp( type, T_CHANGETYPESTR ) == 0 ) {
516 #ifdef LIBERAL_CHANGETYPE_MODOP
517                                 /* trim trailing spaces (and log warning ...) */
518                                 int icnt;
519                                 for ( icnt = val.bv_len; --icnt > 0; ) {
520                                         if ( !isspace( (unsigned char) val.bv_val[icnt] ) ) {
521                                                 break;
522                                         }
523                                 }
524
525                                 if ( ++icnt != val.bv_len ) {
526                                         fprintf( stderr, _("%s: illegal trailing space after"
527                                                 " \"%s: %s\" trimmed (line %d of entry \"%s\")\n"),
528                                                 prog, T_CHANGETYPESTR, val.bv_val, linenum, dn );
529                                         val.bv_val[icnt] = '\0';
530                                 }
531 #endif /* LIBERAL_CHANGETYPE_MODOP */
532
533                                 if ( strcasecmp( val.bv_val, T_MODIFYCTSTR ) == 0 ) {
534                                         new_entry = 0;
535                                         expect_modop = 1;
536                                 } else if ( strcasecmp( val.bv_val, T_ADDCTSTR ) == 0 ) {
537                                         new_entry = 1;
538                                 } else if ( strcasecmp( val.bv_val, T_MODRDNCTSTR ) == 0
539                                         || strcasecmp( val.bv_val, T_MODDNCTSTR ) == 0
540                                         || strcasecmp( val.bv_val, T_RENAMECTSTR ) == 0)
541                                 {
542                                         expect_newrdn = 1;
543                                 } else if ( strcasecmp( val.bv_val, T_DELETECTSTR ) == 0 ) {
544                                         got_all = delete_entry = 1;
545                                 } else {
546                                         fprintf( stderr,
547                                                 _("%s:  unknown %s \"%s\" (line %d of entry \"%s\")\n"),
548                                                 prog, T_CHANGETYPESTR, val.bv_val, linenum, dn );
549                                         rc = LDAP_PARAM_ERROR;
550                                 }
551                                 goto end_line;
552                         } else if ( ldapadd ) {         /*  missing changetype => add */
553                                 new_entry = 1;
554                                 modop = LDAP_MOD_ADD;
555                         } else {
556                                 expect_modop = 1;       /* missing changetype => modify */
557                         }
558                 }
559
560                 if ( expect_modop ) {
561 #ifdef LIBERAL_CHANGETYPE_MODOP
562                         /* trim trailing spaces (and log warning ...) */
563                     int icnt;
564                     for ( icnt = val.bv_len; --icnt > 0; ) {
565                                 if ( !isspace( (unsigned char) val.bv_val[icnt] ) ) break;
566                         }
567     
568                         if ( ++icnt != val.bv_len ) {
569                                 fprintf( stderr, _("%s: illegal trailing space after"
570                                         " \"%s: %s\" trimmed (line %d of entry \"%s\")\n"),
571                                         prog, type, val.bv_val, linenum, dn );
572                                 val.bv_val[icnt] = '\0';
573                         }
574 #endif /* LIBERAL_CHANGETYPE_MODOP */
575
576                         expect_modop = 0;
577                         expect_sep = 1;
578                         if ( strcasecmp( type, T_MODOPADDSTR ) == 0 ) {
579                                 modop = LDAP_MOD_ADD;
580                                 goto end_line;
581                         } else if ( strcasecmp( type, T_MODOPREPLACESTR ) == 0 ) {
582                                 modop = LDAP_MOD_REPLACE;
583                                 addmodifyop( &pmods, modop, val.bv_val, NULL );
584                                 goto end_line;
585                         } else if ( strcasecmp( type, T_MODOPDELETESTR ) == 0 ) {
586                                 modop = LDAP_MOD_DELETE;
587                                 addmodifyop( &pmods, modop, val.bv_val, NULL );
588                                 goto end_line;
589                         } else if ( strcasecmp( type, T_MODOPINCREMENTSTR ) == 0 ) {
590                                 modop = LDAP_MOD_INCREMENT;
591                                 addmodifyop( &pmods, modop, val.bv_val, NULL );
592                                 goto end_line;
593                         } else {        /* no modify op:  use default */
594                                 modop = ldapadd ? LDAP_MOD_ADD : LDAP_MOD_REPLACE;
595                         }
596                 }
597
598                 if ( expect_newrdn ) {
599                         if ( strcasecmp( type, T_NEWRDNSTR ) == 0 ) {
600                                 if (( newrdn = ber_strdup( val.bv_val )) == NULL ) {
601                                         perror( "strdup" );
602                                         exit( EXIT_FAILURE );
603                                 }
604                                 expect_deleteoldrdn = 1;
605                                 expect_newrdn = 0;
606                         } else {
607                                 fprintf( stderr, _("%s: expecting \"%s:\" but saw"
608                                         " \"%s:\" (line %d of entry \"%s\")\n"),
609                                         prog, T_NEWRDNSTR, type, linenum, dn );
610                                 rc = LDAP_PARAM_ERROR;
611                         }
612                 } else if ( expect_deleteoldrdn ) {
613                         if ( strcasecmp( type, T_DELETEOLDRDNSTR ) == 0 ) {
614                                 deleteoldrdn = ( *val.bv_val == '0' ) ? 0 : 1;
615                                 expect_deleteoldrdn = 0;
616                                 expect_newsup = 1;
617                                 got_all = 1;
618                         } else {
619                                 fprintf( stderr, _("%s: expecting \"%s:\" but saw"
620                                         " \"%s:\" (line %d of entry \"%s\")\n"),
621                                         prog, T_DELETEOLDRDNSTR, type, linenum, dn );
622                                 rc = LDAP_PARAM_ERROR;
623                         }
624                 } else if ( expect_newsup ) {
625                         if ( strcasecmp( type, T_NEWSUPSTR ) == 0 ) {
626                                 if (( newsup = ber_strdup( val.bv_val )) == NULL ) {
627                                         perror( "strdup" );
628                                         exit( EXIT_FAILURE );
629                                 }
630                                 expect_newsup = 0;
631                         } else {
632                                 fprintf( stderr, _("%s: expecting \"%s:\" but saw"
633                                         " \"%s:\" (line %d of entry \"%s\")\n"),
634                                         prog, T_NEWSUPSTR, type, linenum, dn );
635                                 rc = LDAP_PARAM_ERROR;
636                         }
637                 } else if ( got_all ) {
638                         fprintf( stderr,
639                                 _("%s: extra lines at end (line %d of entry \"%s\")\n"),
640                                 prog, linenum, dn );
641                         rc = LDAP_PARAM_ERROR;
642                 } else {
643                         if ( new_entry && strcasecmp( type, T_DN_STR ) == 0 ) {
644                                 fprintf( stderr, _("%s: attributeDescription \"%s\":"
645                                         " (possible missing newline"
646                                                 " after line %d of entry \"%s\"?)\n"),
647                                         prog, type, linenum - 1, dn );
648                         }
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 ( newsup != NULL ) {
723                 free( newsup );
724         }
725         if ( pmods != NULL ) {
726                 ldap_mods_free( pmods, 1 );
727         }
728     if (pctrls != NULL) {
729         ldap_controls_free( pctrls );
730         }
731
732         return( rc );
733 }
734
735 /* Parse an LDIF control line of the form
736       control:  oid  [true/false]  [: value]              or
737       control:  oid  [true/false]  [:: base64-value]      or
738       control:  oid  [true/false]  [:< url]
739    The control is added to the list of controls in *ppctrls.
740 */      
741 static int
742 parse_ldif_control(
743         char *line, 
744         LDAPControl ***ppctrls )
745 {
746         char *oid = NULL;
747         int criticality = 0;   /* Default is false if not present */
748         char *type=NULL;
749         char *val = NULL;
750         ber_len_t value_len = 0;
751         int i, rc=0;
752         char *s, *oidStart, *pcolon;
753         LDAPControl *newctrl = NULL;
754         LDAPControl **pctrls = NULL;
755
756         if (ppctrls) pctrls = *ppctrls;
757         s = line + strlen(T_CONTROL_STR);  /* Skip over "control" */
758         pcolon = s;                        /* Save this position for later */
759         if (*s++ != ':') {                 /* Make sure colon follows */
760                 return ( LDAP_PARAM_ERROR );
761         }
762         while (*s && isspace((unsigned char)*s)) {
763                 s++;                           /* Skip white space before OID */
764         }
765
766         /* OID should come next. Validate and extract it. */
767         if (*s == 0) return ( LDAP_PARAM_ERROR );
768         oidStart = s;
769         while (isdigit((unsigned char)*s) || *s == '.') {
770                 s++;                           /* OID should be digits or . */
771         }
772         if (s == oidStart) { 
773                 return ( LDAP_PARAM_ERROR );   /* OID was not present */
774         }
775         if (*s) {                          /* End of OID should be space or NULL */
776                 if (!isspace((unsigned char)*s)) {
777                         return ( LDAP_PARAM_ERROR ); /* else OID contained invalid chars */
778                 }
779                 *s++ = 0;                    /* Replace space with null to terminate */
780         }
781
782         oid = ber_strdup(oidStart);
783         if (oid == NULL) return ( LDAP_NO_MEMORY );
784
785         /* Optional Criticality field is next. */
786         while (*s && isspace((unsigned char)*s)) {
787                 s++;                         /* Skip white space before criticality */
788         }
789         if (strncasecmp(s, "true", 4) == 0) {
790                 criticality = 1;
791                 s += 4;
792         } 
793         else if (strncasecmp(s, "false", 5) == 0) {
794                 criticality = 0;
795                 s += 5;
796         }
797
798         /* Optional value field is next */
799         while (*s && isspace((unsigned char)*s)) {
800                 s++;                         /* Skip white space before value */
801         }
802         if (*s) {
803                 if (*s != ':') {           /* If value is present, must start with : */
804                         rc = LDAP_PARAM_ERROR;
805                         goto cleanup;
806                 }
807
808                 /* Shift value down over OID and criticality so it's in the form
809                      control: value
810                      control:: base64-value
811                      control:< url
812                    Then we can use ldif_parse_line to extract and decode the value
813                 */
814                 while ( (*pcolon++ = *s++) != 0) {   /* Shift value */
815                         /* EMPTY */;
816                 }
817                 rc = ldif_parse_line(line, &type, &val, &value_len);
818                 if (type)  ber_memfree(type);   /* Don't need this field*/
819                 if (rc < 0) {
820                         rc = LDAP_PARAM_ERROR;
821                         goto cleanup;
822                 }
823     }
824
825         /* Create a new LDAPControl structure. */
826         newctrl = (LDAPControl *)ber_memalloc(sizeof(LDAPControl));
827         if ( newctrl == NULL ) {
828                 rc = LDAP_NO_MEMORY;
829                 goto cleanup;
830         }
831         newctrl->ldctl_oid = oid;
832         oid = NULL;
833         newctrl->ldctl_iscritical = criticality;
834         newctrl->ldctl_value.bv_len = value_len;
835         newctrl->ldctl_value.bv_val = val;
836         val = NULL;
837
838         /* Add the new control to the passed-in list of controls. */
839         i = 0;
840         if (pctrls) {
841                 while ( pctrls[i] ) {    /* Count the # of controls passed in */
842                         i++;
843                 }
844         }
845         /* Allocate 1 more slot for the new control and 1 for the NULL. */
846         pctrls = (LDAPControl **) ber_memrealloc(pctrls,
847                 (i+2)*(sizeof(LDAPControl *)));
848         if (pctrls == NULL) {
849                 rc = LDAP_NO_MEMORY;
850                 goto cleanup;
851         }
852         pctrls[i] = newctrl;
853         newctrl = NULL;
854         pctrls[i+1] = NULL;
855         *ppctrls = pctrls;
856
857 cleanup:
858         if (newctrl) {
859                 if (newctrl->ldctl_oid) ber_memfree(newctrl->ldctl_oid);
860                 if (newctrl->ldctl_value.bv_val) {
861                         ber_memfree(newctrl->ldctl_value.bv_val);
862                 }
863                 ber_memfree(newctrl);
864         }
865         if (val) ber_memfree(val);
866         if (oid) ber_memfree(oid);
867
868         return( rc );
869 }
870
871
872 static void
873 addmodifyop(
874         LDAPMod ***pmodsp,
875         int modop,
876         const char *attr,
877         struct berval *val )
878 {
879         LDAPMod         **pmods;
880         int                     i, j;
881
882         pmods = *pmodsp;
883         modop |= LDAP_MOD_BVALUES;
884
885         i = 0;
886         if ( pmods != NULL ) {
887                 for ( ; pmods[ i ] != NULL; ++i ) {
888                         if ( strcasecmp( pmods[ i ]->mod_type, attr ) == 0 &&
889                                 pmods[ i ]->mod_op == modop )
890                         {
891                                 break;
892                         }
893                 }
894         }
895
896         if ( pmods == NULL || pmods[ i ] == NULL ) {
897                 if (( pmods = (LDAPMod **)ber_memrealloc( pmods, (i + 2) *
898                         sizeof( LDAPMod * ))) == NULL )
899                 {
900                         perror( "realloc" );
901                         exit( EXIT_FAILURE );
902                 }
903
904                 *pmodsp = pmods;
905                 pmods[ i + 1 ] = NULL;
906
907                 pmods[ i ] = (LDAPMod *)ber_memcalloc( 1, sizeof( LDAPMod ));
908                 if ( pmods[ i ] == NULL ) {
909                         perror( "calloc" );
910                         exit( EXIT_FAILURE );
911                 }
912
913                 pmods[ i ]->mod_op = modop;
914                 pmods[ i ]->mod_type = ber_strdup( attr );
915                 if ( pmods[ i ]->mod_type == NULL ) {
916                         perror( "strdup" );
917                         exit( EXIT_FAILURE );
918                 }
919         }
920
921         if ( val != NULL ) {
922                 j = 0;
923                 if ( pmods[ i ]->mod_bvalues != NULL ) {
924                         for ( ; pmods[ i ]->mod_bvalues[ j ] != NULL; ++j ) {
925                                 /* Empty */;
926                         }
927                 }
928
929                 pmods[ i ]->mod_bvalues = (struct berval **) ber_memrealloc(
930                         pmods[ i ]->mod_bvalues, (j + 2) * sizeof( struct berval * ));
931                 if ( pmods[ i ]->mod_bvalues == NULL ) {
932                         perror( "ber_realloc" );
933                         exit( EXIT_FAILURE );
934                 }
935
936                 pmods[ i ]->mod_bvalues[ j + 1 ] = NULL;
937                 pmods[ i ]->mod_bvalues[ j ] = ber_bvdup( val );
938                 if ( pmods[ i ]->mod_bvalues[ j ] == NULL ) {
939                         perror( "ber_bvdup" );
940                         exit( EXIT_FAILURE );
941                 }
942         }
943 }
944
945
946 static int
947 domodify(
948         const char *dn,
949         LDAPMod **pmods,
950         LDAPControl **pctrls,
951         int newentry )
952 {
953         int                     rc, i, j, k, notascii, op;
954         struct berval   *bvp;
955
956         if ( dn == NULL ) {
957                 fprintf( stderr, _("%s: no DN specified\n"), prog );
958                 return( LDAP_PARAM_ERROR );
959         }
960
961         if ( pmods == NULL ) {
962                 /* implement "touch" (empty sequence)
963                  * modify operation (note that there
964                  * is no symmetry with the UNIX command,
965                  * since \"touch\" on a non-existent entry
966                  * will fail)*/
967                 printf( "warning: no attributes to %sadd (entry=\"%s\")\n",
968                         newentry ? "" : "change or ", dn );
969
970         } else {
971                 for ( i = 0; pmods[ i ] != NULL; ++i ) {
972                         op = pmods[ i ]->mod_op & ~LDAP_MOD_BVALUES;
973                         if( op == LDAP_MOD_ADD && ( pmods[i]->mod_bvalues == NULL )) {
974                                 fprintf( stderr,
975                                         _("%s: attribute \"%s\" has no values (entry=\"%s\")\n"),
976                                         prog, pmods[i]->mod_type, dn );
977                                 return LDAP_PARAM_ERROR;
978                         }
979                 }
980
981                 if ( verbose ) {
982                         for ( i = 0; pmods[ i ] != NULL; ++i ) {
983                                 op = pmods[ i ]->mod_op & ~LDAP_MOD_BVALUES;
984                                 printf( "%s %s:\n",
985                                         op == LDAP_MOD_REPLACE ? _("replace") :
986                                                 op == LDAP_MOD_ADD ?  _("add") :
987                                                         op == LDAP_MOD_INCREMENT ?  _("increment") :
988                                                                 op == LDAP_MOD_DELETE ?  _("delete") :
989                                                                         _("unknown"),
990                                         pmods[ i ]->mod_type );
991         
992                                 if ( pmods[ i ]->mod_bvalues != NULL ) {
993                                         for ( j = 0; pmods[ i ]->mod_bvalues[ j ] != NULL; ++j ) {
994                                                 bvp = pmods[ i ]->mod_bvalues[ j ];
995                                                 notascii = 0;
996                                                 for ( k = 0; (unsigned long) k < bvp->bv_len; ++k ) {
997                                                         if ( !isascii( bvp->bv_val[ k ] )) {
998                                                                 notascii = 1;
999                                                                 break;
1000                                                         }
1001                                                 }
1002                                                 if ( notascii ) {
1003                                                         printf( _("\tNOT ASCII (%ld bytes)\n"), bvp->bv_len );
1004                                                 } else {
1005                                                         printf( "\t%s\n", bvp->bv_val );
1006                                                 }
1007                                         }
1008                                 }
1009                         }
1010                 }
1011         }
1012
1013         if ( newentry ) {
1014                 printf( "%sadding new entry \"%s\"\n", dont ? "!" : "", dn );
1015         } else {
1016                 printf( "%smodifying entry \"%s\"\n", dont ? "!" : "", dn );
1017         }
1018
1019         if ( !dont ) {
1020                 int     msgid;
1021                 if ( newentry ) {
1022                         rc = ldap_add_ext( ld, dn, pmods, pctrls, NULL, &msgid );
1023                 } else {
1024                         rc = ldap_modify_ext( ld, dn, pmods, pctrls, NULL, &msgid );
1025                 }
1026
1027                 if ( rc != LDAP_SUCCESS ) {
1028                         /* print error message about failed update including DN */
1029                         fprintf( stderr, _("%s: update failed: %s\n"), prog, dn );
1030                         tool_perror( newentry ? "ldap_add" : "ldap_modify",
1031                                 rc, NULL, NULL, NULL, NULL );
1032                         goto done;
1033                 } else if ( verbose ) {
1034                         printf( _("modify complete\n") );
1035                 }
1036
1037                 rc = process_response( ld, msgid,
1038                         newentry ? LDAP_RES_ADD : LDAP_RES_MODIFY, dn );
1039
1040         } else {
1041                 rc = LDAP_SUCCESS;
1042         }
1043
1044 done:
1045         putchar( '\n' );
1046         return rc;
1047 }
1048
1049
1050 static int
1051 dodelete(
1052         const char *dn,
1053         LDAPControl **pctrls )
1054 {
1055         int     rc;
1056         int msgid;
1057
1058         printf( _("%sdeleting entry \"%s\"\n"), dont ? "!" : "", dn );
1059         if ( !dont ) {
1060                 rc = ldap_delete_ext( ld, dn, pctrls, NULL, &msgid );
1061                 if ( rc != LDAP_SUCCESS ) {
1062                         fprintf( stderr, _("%s: delete failed: %s\n"), prog, dn );
1063                         tool_perror( "ldap_delete", rc, NULL, NULL, NULL, NULL );
1064                         goto done;
1065                 } else if ( verbose ) {
1066                         printf( _("delete complete") );
1067                 }
1068
1069                 rc = process_response( ld, msgid, LDAP_RES_DELETE, dn );
1070
1071         } else {
1072                 rc = LDAP_SUCCESS;
1073         }
1074
1075 done:
1076         putchar( '\n' );
1077         return( rc );
1078 }
1079
1080
1081 static int
1082 dorename(
1083         const char *dn,
1084         const char *newrdn,
1085         const char* newsup,
1086         int deleteoldrdn,
1087         LDAPControl **pctrls )
1088 {
1089         int     rc;
1090         int msgid;
1091
1092         printf( _("%smodifying rdn of entry \"%s\"\n"), dont ? "!" : "", dn );
1093         if ( verbose ) {
1094                 printf( _("\tnew RDN: \"%s\" (%skeep existing values)\n"),
1095                         newrdn, deleteoldrdn ? _("do not ") : "" );
1096         }
1097         if ( !dont ) {
1098                 rc = ldap_rename( ld, dn, newrdn, newsup, deleteoldrdn,
1099                         pctrls, NULL, &msgid );
1100                 if ( rc != LDAP_SUCCESS ) {
1101                         fprintf( stderr, _("%s: rename failed: %s\n"), prog, dn );
1102                         tool_perror( "ldap_rename", rc, NULL, NULL, NULL, NULL );
1103                         goto done;
1104                 } else {
1105                         printf( _("rename completed\n") );
1106                 }
1107
1108                 rc = process_response( ld, msgid, LDAP_RES_RENAME, dn );
1109
1110         } else {
1111                 rc = LDAP_SUCCESS;
1112         }
1113
1114 done:
1115         putchar( '\n' );
1116         return( rc );
1117 }
1118
1119 static const char *
1120 res2str( int res ) {
1121         switch ( res ) {
1122         case LDAP_RES_ADD:
1123                 return "ldap_add";
1124         case LDAP_RES_DELETE:
1125                 return "ldap_delete";
1126         case LDAP_RES_MODIFY:
1127                 return "ldap_modify";
1128         case LDAP_RES_MODRDN:
1129                 return "ldap_rename";
1130         default:
1131                 assert( 0 );
1132         }
1133
1134         return "ldap_unknown";
1135 }
1136
1137 static int process_response(
1138         LDAP *ld,
1139         int msgid,
1140         int op,
1141         const char *dn )
1142 {
1143         LDAPMessage     *res;
1144         int             rc = LDAP_OTHER, msgtype;
1145         struct timeval  tv = { 0, 0 };
1146         int             err;
1147         char            *text = NULL, *matched = NULL, **refs = NULL;
1148         LDAPControl     **ctrls = NULL;
1149
1150         for ( ; ; ) {
1151                 tv.tv_sec = 0;
1152                 tv.tv_usec = 100000;
1153
1154                 rc = ldap_result( ld, msgid, LDAP_MSG_ALL, &tv, &res );
1155                 if ( tool_check_abandon( ld, msgid ) ) {
1156                         return LDAP_CANCELLED;
1157                 }
1158
1159                 if ( rc == -1 ) {
1160                         ldap_get_option( ld, LDAP_OPT_ERROR_NUMBER, &rc );
1161                         return rc;
1162                 }
1163
1164                 if ( rc != 0 ) {
1165                         break;
1166                 }
1167         }
1168
1169         msgtype = ldap_msgtype( res );
1170
1171         rc = ldap_parse_result( ld, res, &err, &matched, &text, &refs, &ctrls, 1 );
1172         if ( rc == LDAP_SUCCESS ) rc = err;
1173
1174 #ifdef LDAP_X_TXN
1175         if ( rc == LDAP_X_TXN_SPECIFY_OKAY ) {
1176                 rc = LDAP_SUCCESS;
1177         } else
1178 #endif
1179         if ( rc != LDAP_SUCCESS ) {
1180                 tool_perror( res2str( op ), rc, NULL, matched, text, refs );
1181         } else if ( msgtype != op ) {
1182                 fprintf( stderr, "%s: msgtype: expected %d got %d\n",
1183                         res2str( op ), op, msgtype );
1184                 rc = LDAP_OTHER;
1185         }
1186
1187         if ( text ) ldap_memfree( text );
1188         if ( matched ) ldap_memfree( matched );
1189         if ( text ) ber_memvfree( (void **)refs );
1190
1191         if ( ctrls != NULL ) {
1192                 tool_print_ctrls( ld, ctrls );
1193                 ldap_controls_free( ctrls );
1194         }
1195
1196         return rc;
1197 }
1198
1199 static char *
1200 read_one_record( FILE *fp )
1201 {
1202         char        *buf, line[ LDAPMOD_MAXLINE ];
1203         int             lcur, lmax;
1204
1205         lcur = lmax = 0;
1206         buf = NULL;
1207
1208         while ( fgets( line, sizeof(line), fp ) != NULL ) {
1209                 int len = strlen( line );
1210
1211                 if( len < 2 || ( len == 2 && *line == '\r' )) {
1212                         if( buf == NULL ) {
1213                                 continue;
1214                         } else {
1215                                 break;
1216                         }
1217                 }
1218
1219                 if ( lcur + len + 1 > lmax ) {
1220                         lmax = LDAPMOD_MAXLINE
1221                                 * (( lcur + len + 1 ) / LDAPMOD_MAXLINE + 1 );
1222
1223                         if (( buf = (char *)ber_memrealloc( buf, lmax )) == NULL ) {
1224                                 perror( "realloc" );
1225                                 exit( EXIT_FAILURE );
1226                         }
1227                 }
1228
1229                 strcpy( buf + lcur, line );
1230                 lcur += len;
1231         }
1232
1233         return( buf );
1234 }
1235
1236