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