]> git.sur5r.net Git - openldap/blob - clients/tools/ldapmodify.c
c2c52aeb880c4819da31502badcc35b0f811debb
[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-2003 The OpenLDAP Foundation.
6  * Portions Copyright 1998-2003 Kurt D. Zeilenga.
7  * Portions Copyright 1998-2001 Net Boolean Incorporated.
8  * Portions Copyright 2001-2003 IBM Corporation.
9  * All rights reserved.
10  *
11  * Redistribution and use in source and binary forms, with or without
12  * modification, are permitted only as authorized by the OpenLDAP
13  * Public License.
14  *
15  * A copy of this license is available in the file LICENSE in the
16  * top-level directory of the distribution or, alternatively, at
17  * <http://www.OpenLDAP.org/license.html>.
18  */
19 /* Portions Copyright (c) 1992-1996 Regents of the University of Michigan.
20  * All rights reserved.
21  *
22  * Redistribution and use in source and binary forms are permitted
23  * provided that this notice is preserved and that due credit is given
24  * to the University of Michigan at Ann Arbor.  The name of the
25  * University may not be used to endorse or promote products derived
26  * from this software without specific prior written permission.  This
27  * software is provided ``as is'' without express or implied warranty.
28  */
29 /* ACKNOWLEDGEMENTS:
30  * This work was originally developed by the University of Michigan
31  * (as part of U-MICH LDAP).  Additional significant contributors
32  * include:
33  *   Kurt D. Zeilenga
34  *   Norbert Klasen
35  */
36
37 #include "portable.h"
38
39 #include <stdio.h>
40
41 #include <ac/stdlib.h>
42 #include <ac/ctype.h>
43 #include <ac/string.h>
44 #include <ac/unistd.h>
45
46 #ifdef HAVE_SYS_STAT_H
47 #include <sys/stat.h>
48 #endif
49
50 #ifdef HAVE_SYS_FILE_H
51 #include <sys/file.h>
52 #endif
53 #ifdef HAVE_FCNTL_H
54 #include <fcntl.h>
55 #endif
56
57 #include <ldap.h>
58
59 #include "lutil.h"
60 #include "lutil_ldap.h"
61 #include "ldif.h"
62 #include "ldap_defaults.h"
63 #include "ldap_log.h"
64 #include "ldap_pvt.h"
65
66 #include "common.h"
67
68
69 static int      ldapadd, force = 0;
70 static char *rejfile = NULL;
71 static LDAP     *ld = NULL;
72
73 #define LDAPMOD_MAXLINE         4096
74
75 /* strings found in replog/LDIF entries (mostly lifted from slurpd/slurp.h) */
76 #define T_VERSION_STR           "version"
77 #define T_REPLICA_STR           "replica"
78 #define T_DN_STR                "dn"
79 #define T_CONTROL_STR           "control"
80 #define T_CHANGETYPESTR         "changetype"
81 #define T_ADDCTSTR              "add"
82 #define T_MODIFYCTSTR           "modify"
83 #define T_DELETECTSTR           "delete"
84 #define T_MODRDNCTSTR           "modrdn"
85 #define T_MODDNCTSTR            "moddn"
86 #define T_RENAMECTSTR           "rename"
87 #define T_MODOPADDSTR           "add"
88 #define T_MODOPREPLACESTR       "replace"
89 #define T_MODOPDELETESTR        "delete"
90 #define T_MODOPINCREMENTSTR     "increment"
91 #define T_MODSEPSTR             "-"
92 #define T_NEWRDNSTR             "newrdn"
93 #define T_DELETEOLDRDNSTR       "deleteoldrdn"
94 #define T_NEWSUPSTR             "newsuperior"
95
96
97 static int process_ldif_rec LDAP_P(( char *rbuf, int count ));
98 static int parse_ldif_control LDAP_P(( char *line, LDAPControl ***pctrls ));
99 static void addmodifyop LDAP_P((
100         LDAPMod ***pmodsp, int modop,
101         const char *attr,
102         struct berval *value ));
103 static int domodify LDAP_P((
104         const char *dn,
105         LDAPMod **pmods,
106     LDAPControl **pctrls,
107         int newentry ));
108 static int dodelete LDAP_P((
109         const char *dn,
110     LDAPControl **pctrls ));
111 static int dorename LDAP_P((
112         const char *dn,
113         const char *newrdn,
114         const char *newsup,
115         int deleteoldrdn,
116     LDAPControl **pctrls ));
117 static char *read_one_record LDAP_P(( FILE *fp ));
118
119 void
120 usage( void )
121 {
122     fprintf( stderr, _("Add or modify entries from an LDAP server\n\n"));
123     fprintf( stderr, _("usage: %s [options]\n"), prog);
124     fprintf( stderr, _("        The list of desired operations are read from stdin or from the file\n"));
125     fprintf( stderr, _("        specified by \"-f file\".\n"));
126     fprintf( stderr, _("Add or modify options:\n"));
127     fprintf( stderr, _("  -a         add values (%s)\n"),
128                 (ldapadd ? _("default") : _("default is to replace")));
129     fprintf( stderr, _("  -F         force all changes records to be used\n"));
130     fprintf( stderr, _("  -S file    write skipped modifications to `file'\n"));
131     tool_common_usage();
132     exit( EXIT_FAILURE );
133 }
134
135
136 const char options[] = "aFrS:"
137         "cCd:D:e:f:h:H:IkKMnO:p:P:QR:U:vVw:WxX:y:Y:Z";
138
139 int
140 handle_private_option( int i )
141 {
142         switch ( i ) {
143 #if 0
144                 char    *control, *cvalue;
145                 int             crit;
146         case 'E': /* modify controls */
147                 if( protocol == LDAP_VERSION2 ) {
148                         fprintf( stderr, _("%s: -E incompatible with LDAPv%d\n"),
149                                 prog, protocol );
150                         exit( EXIT_FAILURE );
151                 }
152
153                 /* should be extended to support comma separated list of
154                  *      [!]key[=value] parameters, e.g.  -E !foo,bar=567
155                  */
156
157                 crit = 0;
158                 cvalue = NULL;
159                 if( optarg[0] == '!' ) {
160                         crit = 1;
161                         optarg++;
162                 }
163
164                 control = ber_strdup( optarg );
165                 if ( (cvalue = strchr( control, '=' )) != NULL ) {
166                         *cvalue++ = '\0';
167                 }
168                 fprintf( stderr, _("Invalid modify control name: %s\n"), control );
169                 usage();
170 #endif
171
172         case 'a':       /* add */
173             ldapadd = 1;
174             break;
175
176         case 'F':       /* force all changes records to be used */
177             force = 1;
178             break;
179
180         case 'r':       /* replace (obsolete) */
181                 break;
182
183         case 'S':       /* skipped modifications to file */
184                 if( rejfile != NULL ) {
185                         fprintf( stderr, _("%s: -S previously specified\n"), prog );
186                         exit( EXIT_FAILURE );
187                 }
188                 rejfile = ber_strdup( optarg );
189                 break;
190
191         default:
192                 return 0;
193         }
194         return 1;
195 }
196
197
198 int
199 main( int argc, char **argv )
200 {
201         char            *rbuf, *start, *rejbuf = NULL;
202         FILE            *fp, *rejfp;
203         char            *matched_msg, *error_msg;
204         int             rc, retval;
205         int count, len;
206
207         tool_init();
208         prog = lutil_progname( "ldapmodify", argc, argv );
209
210         /* strncmp instead of strcmp since NT binaries carry .exe extension */
211         ldapadd = ( strncasecmp( prog, "ldapadd", sizeof("ldapadd")-1 ) == 0 );
212
213         /* Print usage when no parameters */
214         if( argc < 2 ) usage();
215
216         tool_args( argc, argv );
217
218         if ( argc != optind ) usage();
219
220         if ( rejfile != NULL ) {
221                 if (( rejfp = fopen( rejfile, "w" )) == NULL ) {
222                         perror( rejfile );
223                         return( EXIT_FAILURE );
224                 }
225         } else {
226                 rejfp = NULL;
227         }
228
229         if ( infile != NULL ) {
230                 if (( fp = fopen( infile, "r" )) == NULL ) {
231                         perror( infile );
232                         return( EXIT_FAILURE );
233                 }
234         } else {
235                 fp = stdin;
236         }
237
238         if ( debug ) ldif_debug = debug;
239
240         ld = tool_conn_setup( not, 0 );
241
242         if ( !not ) {
243                 if ( pw_file || want_bindpw ) {
244                         if ( pw_file ) {
245                                 rc = lutil_get_filed_password( pw_file, &passwd );
246                                 if( rc ) return EXIT_FAILURE;
247                         } else {
248                                 passwd.bv_val = getpassphrase( _("Enter LDAP Password: ") );
249                                 passwd.bv_len = passwd.bv_val ? strlen( passwd.bv_val ) : 0;
250                         }
251                 }
252                 tool_bind( ld );
253         }
254
255     rc = 0;
256
257         if ( assertion || authzid || manageDSAit || noop || preread || postread ) {
258                 tool_server_controls( ld, NULL, 0 );
259         }
260
261         count = 0;
262         retval = 0;
263         while (( rc == 0 || contoper ) &&
264                 ( rbuf = read_one_record( fp )) != NULL )
265         {
266                 count++;
267
268                 start = rbuf;
269
270                 if ( rejfp ) {
271                         len = strlen( rbuf );
272                         if (( rejbuf = (char *)ber_memalloc( len+1 )) == NULL ) {
273                                 perror( "malloc" );
274                                 exit( EXIT_FAILURE );
275                         }
276                         memcpy( rejbuf, rbuf, len+1 );
277                 }
278
279                 rc = process_ldif_rec( start, count );
280
281                 if ( rc ) retval = rc;
282                 if ( rc && rejfp ) {
283                         fprintf(rejfp, _("# Error: %s (%d)"), ldap_err2string(rc), rc);
284
285                         matched_msg = NULL;
286                         ldap_get_option(ld, LDAP_OPT_MATCHED_DN, &matched_msg);
287                         if ( matched_msg != NULL ) {
288                                 if ( *matched_msg != '\0' ) {
289                                         fprintf( rejfp, _(", matched DN: %s"), matched_msg );
290                                 }
291                                 ldap_memfree( matched_msg );
292                         }
293
294                         error_msg = NULL;
295                         ldap_get_option(ld, LDAP_OPT_ERROR_STRING, &error_msg);
296                         if ( error_msg != NULL ) {
297                                 if ( *error_msg != '\0' ) {
298                                         fprintf( rejfp, _(", additional info: %s"), error_msg );
299                                 }
300                                 ldap_memfree( error_msg );
301                         }
302                         fprintf( rejfp, "\n%s\n", rejbuf );
303                 }
304
305                 if (rejfp) free( rejbuf );
306                 free( rbuf );
307         }
308
309         if ( !not ) {
310                 ldap_unbind( ld );
311         }
312
313         if ( rejfp != NULL ) {
314                 fclose( rejfp );
315         }
316
317         return( retval );
318 }
319
320
321 static int
322 process_ldif_rec( char *rbuf, int count )
323 {
324     char        *line, *dn, *type, *newrdn, *newsup, *p;
325     int         rc, linenum, modop, replicaport;
326     int         expect_modop, expect_sep, expect_ct, expect_newrdn, expect_newsup;
327     int         expect_deleteoldrdn, deleteoldrdn;
328     int         saw_replica, use_record, new_entry, delete_entry, got_all;
329     LDAPMod     **pmods;
330         int version;
331         struct berval val;
332     LDAPControl **pctrls;
333
334     new_entry = ldapadd;
335
336     rc = got_all = saw_replica = delete_entry = modop = expect_modop = 0;
337     expect_deleteoldrdn = expect_newrdn = expect_newsup = 0;
338         expect_sep = expect_ct = 0;
339     linenum = 0;
340         version = 0;
341     deleteoldrdn = 1;
342     use_record = force;
343     pmods = NULL;
344     pctrls = NULL;
345     dn = newrdn = newsup = NULL;
346
347     while ( rc == 0 && ( line = ldif_getline( &rbuf )) != NULL ) {
348         ++linenum;
349
350         if ( expect_sep && strcasecmp( line, T_MODSEPSTR ) == 0 ) {
351             expect_sep = 0;
352             expect_ct = 1;
353             continue;
354         }
355         
356         if ( ldif_parse_line( line, &type, &val.bv_val, &val.bv_len ) < 0 ) {
357             fprintf( stderr, _("%s: invalid format (line %d) entry: \"%s\"\n"),
358                     prog, linenum, dn == NULL ? "" : dn );
359             rc = LDAP_PARAM_ERROR;
360             break;
361         }
362
363         if ( dn == NULL ) {
364             if ( !use_record && strcasecmp( type, T_REPLICA_STR ) == 0 ) {
365                 ++saw_replica;
366                 if (( p = strchr( val.bv_val, ':' )) == NULL ) {
367                     replicaport = 0;
368                 } else {
369                     *p++ = '\0';
370                     replicaport = atoi( p );
371                 }
372                 if ( ldaphost != NULL && strcasecmp( val.bv_val, ldaphost ) == 0 &&
373                         replicaport == ldapport ) {
374                     use_record = 1;
375                 }
376             } else if ( count == 1 && linenum == 1 && 
377                         strcasecmp( type, T_VERSION_STR ) == 0 )
378                 {
379                         if( val.bv_len == 0 || atoi(val.bv_val) != 1 ) {
380                         fprintf( stderr, _("%s: invalid version %s, line %d (ignored)\n"),
381                                 prog, val.bv_val, linenum );
382                         }
383                         version++;
384
385             } else if ( strcasecmp( type, T_DN_STR ) == 0 ) {
386                 if (( dn = ber_strdup( val.bv_val )) == NULL ) {
387                     perror( "strdup" );
388                     exit( EXIT_FAILURE );
389                 }
390                 expect_ct = 1;
391             }
392             goto end_line;      /* skip all lines until we see "dn:" */
393         }
394
395         if ( expect_ct ) {
396         
397         /* Check for "control" tag after dn and before changetype. */
398         if (strcasecmp(type, T_CONTROL_STR) == 0) {
399             /* Parse and add it to the list of controls */
400             rc = parse_ldif_control( line, &pctrls );
401             if (rc != 0) {
402                         fprintf( stderr, _("%s: Error processing %s line, line %d: %s\n"),
403                                 prog, T_CONTROL_STR, linenum, ldap_err2string(rc) );
404             }
405             goto end_line;
406         }
407         
408             expect_ct = 0;
409             if ( !use_record && saw_replica ) {
410                 printf(_("%s: skipping change record for entry: %s\n"), prog, dn);
411                 printf(_("\t(LDAP host/port does not match replica: lines)\n"));
412                 free( dn );
413                 ber_memfree( type );
414                 ber_memfree( val.bv_val );
415                 return( 0 );
416             }
417
418             if ( strcasecmp( type, T_CHANGETYPESTR ) == 0 ) {
419 #ifdef LIBERAL_CHANGETYPE_MODOP
420                 /* trim trailing spaces (and log warning ...) */
421
422                 int icnt;
423                 for ( icnt = val.bv_len; --icnt > 0; ) {
424                     if ( !isspace( (unsigned char) val.bv_val[icnt] ) ) {
425                         break;
426                     }
427                 }
428
429                 if ( ++icnt != val.bv_len ) {
430                     fprintf( stderr, _("%s: illegal trailing space after \"%s: %s\" trimmed (line %d of entry \"%s\")\n"),
431                             prog, T_CHANGETYPESTR, val.bv_val, linenum, dn );
432                     val.bv_val[icnt] = '\0';
433                 }
434 #endif /* LIBERAL_CHANGETYPE_MODOP */
435
436                 if ( strcasecmp( val.bv_val, T_MODIFYCTSTR ) == 0 ) {
437                         new_entry = 0;
438                         expect_modop = 1;
439                 } else if ( strcasecmp( val.bv_val, T_ADDCTSTR ) == 0 ) {
440                         new_entry = 1;
441                 } else if ( strcasecmp( val.bv_val, T_MODRDNCTSTR ) == 0
442                         || strcasecmp( val.bv_val, T_MODDNCTSTR ) == 0
443                         || strcasecmp( val.bv_val, T_RENAMECTSTR ) == 0)
444                 {
445                     expect_newrdn = 1;
446                 } else if ( strcasecmp( val.bv_val, T_DELETECTSTR ) == 0 ) {
447                     got_all = delete_entry = 1;
448                 } else {
449                     fprintf( stderr,
450                             _("%s:  unknown %s \"%s\" (line %d of entry \"%s\")\n"),
451                             prog, T_CHANGETYPESTR, val.bv_val, linenum, dn );
452                     rc = LDAP_PARAM_ERROR;
453                 }
454                 goto end_line;
455             } else if ( ldapadd ) {             /*  missing changetype => add */
456                 new_entry = 1;
457                 modop = LDAP_MOD_ADD;
458             } else {
459                 expect_modop = 1;       /* missing changetype => modify */
460             }
461         }
462
463         if ( expect_modop ) {
464 #ifdef LIBERAL_CHANGETYPE_MODOP
465             /* trim trailing spaces (and log warning ...) */
466             
467             int icnt;
468             for ( icnt = val.bv_len; --icnt > 0; ) {
469                 if ( !isspace( (unsigned char) val.bv_val[icnt] ) ) {
470                     break;
471                 }
472             }
473             
474             if ( ++icnt != val.bv_len ) {
475                 fprintf( stderr, _("%s: illegal trailing space after \"%s: %s\" trimmed (line %d of entry \"%s\")\n"),
476                         prog, type, val.bv_val, linenum, dn );
477                 val.bv_val[icnt] = '\0';
478             }
479 #endif /* LIBERAL_CHANGETYPE_MODOP */
480
481             expect_modop = 0;
482             expect_sep = 1;
483             if ( strcasecmp( type, T_MODOPADDSTR ) == 0 ) {
484                 modop = LDAP_MOD_ADD;
485                 goto end_line;
486             } else if ( strcasecmp( type, T_MODOPREPLACESTR ) == 0 ) {
487                 modop = LDAP_MOD_REPLACE;
488                 addmodifyop( &pmods, modop, val.bv_val, NULL );
489                 goto end_line;
490             } else if ( strcasecmp( type, T_MODOPDELETESTR ) == 0 ) {
491                 modop = LDAP_MOD_DELETE;
492                 addmodifyop( &pmods, modop, val.bv_val, NULL );
493                 goto end_line;
494             } else if ( strcasecmp( type, T_MODOPINCREMENTSTR ) == 0 ) {
495                 modop = LDAP_MOD_INCREMENT;
496                 addmodifyop( &pmods, modop, val.bv_val, NULL );
497                 goto end_line;
498             } else {    /* no modify op:  use default */
499                 modop = ldapadd ? LDAP_MOD_ADD : LDAP_MOD_REPLACE;
500             }
501         }
502
503         if ( expect_newrdn ) {
504             if ( strcasecmp( type, T_NEWRDNSTR ) == 0 ) {
505                         if (( newrdn = ber_strdup( val.bv_val )) == NULL ) {
506                     perror( "strdup" );
507                     exit( EXIT_FAILURE );
508                 }
509                 expect_deleteoldrdn = 1;
510                 expect_newrdn = 0;
511             } else {
512                 fprintf( stderr, _("%s: expecting \"%s:\" but saw \"%s:\" (line %d of entry \"%s\")\n"),
513                         prog, T_NEWRDNSTR, type, linenum, dn );
514                 rc = LDAP_PARAM_ERROR;
515             }
516         } else if ( expect_deleteoldrdn ) {
517             if ( strcasecmp( type, T_DELETEOLDRDNSTR ) == 0 ) {
518                 deleteoldrdn = ( *val.bv_val == '0' ) ? 0 : 1;
519                 expect_deleteoldrdn = 0;
520                 expect_newsup = 1;
521                 got_all = 1;
522             } else {
523                 fprintf( stderr, _("%s: expecting \"%s:\" but saw \"%s:\" (line %d of entry \"%s\")\n"),
524                         prog, T_DELETEOLDRDNSTR, type, linenum, dn );
525                 rc = LDAP_PARAM_ERROR;
526             }
527         } else if ( expect_newsup ) {
528             if ( strcasecmp( type, T_NEWSUPSTR ) == 0 ) {
529                 if (( newsup = ber_strdup( val.bv_val )) == NULL ) {
530                     perror( "strdup" );
531                     exit( EXIT_FAILURE );
532                 }
533                 expect_newsup = 0;
534             } else {
535                 fprintf( stderr, _("%s: expecting \"%s:\" but saw \"%s:\" (line %d of entry \"%s\")\n"),
536                         prog, T_NEWSUPSTR, type, linenum, dn );
537                 rc = LDAP_PARAM_ERROR;
538             }
539         } else if ( got_all ) {
540             fprintf( stderr,
541                     _("%s: extra lines at end (line %d of entry \"%s\")\n"),
542                     prog, linenum, dn );
543             rc = LDAP_PARAM_ERROR;
544         } else {
545                 addmodifyop( &pmods, modop, type, &val );
546         }
547
548 end_line:
549         ber_memfree( type );
550         ber_memfree( val.bv_val );
551     }
552
553         if( linenum == 0 ) {
554                 return 0;
555         }
556
557         if( version && linenum == 1 ) {
558                 return 0;
559         }
560
561     /* If default controls are set (as with -M option) and controls are
562        specified in the LDIF file, we must add the default controls to
563        the list of controls sent with the ldap operation.
564     */
565     if ( rc == 0 ) {
566         if (pctrls) {
567             LDAPControl **defctrls = NULL;   /* Default server controls */
568             LDAPControl **newctrls = NULL;
569             ldap_get_option(ld, LDAP_OPT_SERVER_CONTROLS, &defctrls);
570             if (defctrls) {
571                 int npc=0;                  /* Number of LDIF controls */
572                 int ndefc=0;                /* Number of default controls */
573                 while (pctrls[npc])         /* Count LDIF controls */
574                     npc++; 
575                 while (defctrls[ndefc])     /* Count default controls */
576                     ndefc++;
577                 newctrls = ber_memrealloc(pctrls, (npc+ndefc+1)*sizeof(LDAPControl*));
578                 if (newctrls == NULL)
579                     rc = LDAP_NO_MEMORY;
580                 else {
581                     int i;
582                     pctrls = newctrls;
583                     for (i=npc; i<npc+ndefc; i++) {
584                         pctrls[i] = ldap_control_dup(defctrls[i-npc]);
585                         if (pctrls[i] == NULL) {
586                             rc = LDAP_NO_MEMORY;
587                             break;
588                         }
589                     }
590                     pctrls[npc+ndefc] = NULL;
591                 }
592                 ldap_controls_free(defctrls);  /* Must be freed by library */
593             }
594         }
595     }
596
597
598     if ( rc == 0 ) {
599         if ( delete_entry ) {
600             rc = dodelete( dn, pctrls );
601         } else if ( newrdn != NULL ) {
602             rc = dorename( dn, newrdn, newsup, deleteoldrdn, pctrls );
603         } else {
604             rc = domodify( dn, pmods, pctrls, new_entry );
605         }
606
607         if ( rc == LDAP_SUCCESS ) {
608             rc = 0;
609         }
610     }
611
612     if ( dn != NULL ) {
613         free( dn );
614     }
615     if ( newrdn != NULL ) {
616         free( newrdn );
617     }
618     if ( pmods != NULL ) {
619         ldap_mods_free( pmods, 1 );
620     }
621
622     if (pctrls != NULL) {
623         ldap_controls_free( pctrls );
624     }
625
626     return( rc );
627 }
628
629 /* Parse an LDIF control line of the form
630       control:  oid  [true/false]  [: value]              or
631       control:  oid  [true/false]  [:: base64-value]      or
632       control:  oid  [true/false]  [:< url]
633    The control is added to the list of controls in *ppctrls.
634 */      
635 static int
636 parse_ldif_control( char *line, 
637                     LDAPControl ***ppctrls )
638 {
639     char *oid = NULL;
640     int criticality = 0;   /* Default is false if not present */
641     char *type=NULL;
642     char *val = NULL;
643     ber_len_t value_len = 0;
644     int i, rc=0;
645     char *s, *oidStart, *pcolon;
646     LDAPControl *newctrl = NULL;
647     LDAPControl **pctrls = NULL;
648
649     if (ppctrls) {
650         pctrls = *ppctrls;
651     }
652     s = line + strlen(T_CONTROL_STR);  /* Skip over "control" */
653     pcolon = s;                        /* Save this position for later */
654     if (*s++ != ':')                   /* Make sure colon follows */
655         return ( LDAP_PARAM_ERROR );
656     while (*s && isspace((unsigned char)*s))
657                 s++;                           /* Skip white space before OID */
658
659     /* OID should come next. Validate and extract it. */
660     if (*s == 0)
661         return ( LDAP_PARAM_ERROR );
662     oidStart = s;
663     while (isdigit((unsigned char)*s) || *s == '.')
664                 s++;                           /* OID should be digits or . */
665     if (s == oidStart) 
666         return ( LDAP_PARAM_ERROR );   /* OID was not present */
667     if (*s) {                          /* End of OID should be space or NULL */
668         if (!isspace((unsigned char)*s))
669             return ( LDAP_PARAM_ERROR ); /* else OID contained invalid chars */
670         *s++ = 0;                    /* Replace space with null to terminate */
671     }
672
673     
674     oid = ber_strdup(oidStart);
675     if (oid == NULL)
676         return ( LDAP_NO_MEMORY );
677
678     /* Optional Criticality field is next. */
679     while (*s && isspace((unsigned char)*s))
680                 s++;                         /* Skip white space before criticality */
681     if (strncasecmp(s, "true", 4) == 0) {
682         criticality = 1;
683         s += 4;
684     } 
685     else if (strncasecmp(s, "false", 5) == 0) {
686         criticality = 0;
687         s += 5;
688     }
689
690     /* Optional value field is next */
691     while (*s && isspace((unsigned char)*s))
692                 s++;                         /* Skip white space before value */
693     if (*s) {
694         if (*s != ':') {           /* If value is present, must start with : */
695             rc = LDAP_PARAM_ERROR;
696             goto cleanup;
697         }
698
699         /* Shift value down over OID and criticality so it's in the form
700              control: value
701              control:: base64-value
702              control:< url
703            Then we can use ldif_parse_line to extract and decode the value
704         */
705         while ( (*pcolon++ = *s++) != 0)     /* Shift value */
706             ;
707         rc = ldif_parse_line(line, &type, &val, &value_len);
708         if (type)  ber_memfree(type);   /* Don't need this field*/
709         if (rc < 0) {
710             rc = LDAP_PARAM_ERROR;
711             goto cleanup;
712         }
713     }
714
715     /* Create a new LDAPControl structure. */
716     newctrl = (LDAPControl *)ber_memalloc(sizeof(LDAPControl));
717     if ( newctrl == NULL ) {
718         rc = LDAP_NO_MEMORY;
719         goto cleanup;
720     }
721     newctrl->ldctl_oid = oid;
722     oid = NULL;
723     newctrl->ldctl_iscritical = criticality;
724     newctrl->ldctl_value.bv_len = value_len;
725     newctrl->ldctl_value.bv_val = val;
726     val = NULL;
727
728     /* Add the new control to the passed-in list of controls. */
729     i = 0;
730     if (pctrls) {
731         while ( pctrls[i] )      /* Count the # of controls passed in */
732             i++;
733     }
734     /* Allocate 1 more slot for the new control and 1 for the NULL. */
735     pctrls = (LDAPControl **)ber_memrealloc(pctrls, (i+2)*(sizeof(LDAPControl *)));
736     if (pctrls == NULL) {
737         rc = LDAP_NO_MEMORY;
738         goto cleanup;
739     }
740     pctrls[i] = newctrl;
741     newctrl = NULL;
742     pctrls[i+1] = NULL;
743     *ppctrls = pctrls;
744
745 cleanup:
746     if (newctrl) {
747         if (newctrl->ldctl_oid)
748             ber_memfree(newctrl->ldctl_oid);
749         if (newctrl->ldctl_value.bv_val)
750             ber_memfree(newctrl->ldctl_value.bv_val);
751         ber_memfree(newctrl);
752     }
753     if (val)
754         ber_memfree(val);
755     if (oid)
756         ber_memfree(oid);
757
758     return( rc );
759 }
760
761
762 static void
763 addmodifyop(
764         LDAPMod ***pmodsp,
765         int modop,
766         const char *attr,
767         struct berval *val )
768 {
769         LDAPMod         **pmods;
770         int                     i, j;
771
772         pmods = *pmodsp;
773         modop |= LDAP_MOD_BVALUES;
774
775         i = 0;
776         if ( pmods != NULL ) {
777                 for ( ; pmods[ i ] != NULL; ++i ) {
778                         if ( strcasecmp( pmods[ i ]->mod_type, attr ) == 0 &&
779                                 pmods[ i ]->mod_op == modop )
780                         {
781                                 break;
782                         }
783                 }
784         }
785
786         if ( pmods == NULL || pmods[ i ] == NULL ) {
787                 if (( pmods = (LDAPMod **)ber_memrealloc( pmods, (i + 2) *
788                         sizeof( LDAPMod * ))) == NULL )
789                 {
790                         perror( "realloc" );
791                         exit( EXIT_FAILURE );
792                 }
793
794                 *pmodsp = pmods;
795                 pmods[ i + 1 ] = NULL;
796
797                 pmods[ i ] = (LDAPMod *)ber_memcalloc( 1, sizeof( LDAPMod ));
798                 if ( pmods[ i ] == NULL ) {
799                         perror( "calloc" );
800                         exit( EXIT_FAILURE );
801                 }
802
803                 pmods[ i ]->mod_op = modop;
804                 pmods[ i ]->mod_type = ber_strdup( attr );
805                 if ( pmods[ i ]->mod_type == NULL ) {
806                         perror( "strdup" );
807                         exit( EXIT_FAILURE );
808                 }
809         }
810
811         if ( val != NULL ) {
812                 j = 0;
813                 if ( pmods[ i ]->mod_bvalues != NULL ) {
814                         for ( ; pmods[ i ]->mod_bvalues[ j ] != NULL; ++j ) {
815                                 /* Empty */;
816                         }
817                 }
818
819                 pmods[ i ]->mod_bvalues = (struct berval **) ber_memrealloc(
820                         pmods[ i ]->mod_bvalues, (j + 2) * sizeof( struct berval * ));
821                 if ( pmods[ i ]->mod_bvalues == NULL ) {
822                         perror( "ber_realloc" );
823                         exit( EXIT_FAILURE );
824                 }
825
826                 pmods[ i ]->mod_bvalues[ j + 1 ] = NULL;
827                 pmods[ i ]->mod_bvalues[ j ] = ber_bvdup( val );
828                 if ( pmods[ i ]->mod_bvalues[ j ] == NULL ) {
829                         perror( "ber_bvdup" );
830                         exit( EXIT_FAILURE );
831                 }
832         }
833 }
834
835
836 static int
837 domodify(
838         const char *dn,
839         LDAPMod **pmods,
840     LDAPControl **pctrls,
841         int newentry )
842 {
843     int                 i, j, k, notascii, op;
844     struct berval       *bvp;
845
846         if ( dn == NULL ) {
847         fprintf( stderr, _("%s: no DN specified\n"), prog );
848         return( LDAP_PARAM_ERROR );
849         }
850
851     if ( pmods == NULL ) {
852         fprintf( stderr, _("%s: no attributes to change or add (entry=\"%s\")\n"),
853                 prog, dn );
854         return( LDAP_PARAM_ERROR );
855     } 
856
857     for ( i = 0; pmods[ i ] != NULL; ++i ) {
858         op = pmods[ i ]->mod_op & ~LDAP_MOD_BVALUES;
859         if( op == LDAP_MOD_ADD && ( pmods[i]->mod_bvalues == NULL )) {
860                 fprintf( stderr,
861                         _("%s: attribute \"%s\" has no values (entry=\"%s\")\n"),
862                         prog, pmods[i]->mod_type, dn );
863                 return LDAP_PARAM_ERROR;
864         }
865     }
866
867     if ( verbose ) {
868         for ( i = 0; pmods[ i ] != NULL; ++i ) {
869             op = pmods[ i ]->mod_op & ~LDAP_MOD_BVALUES;
870             printf( "%s %s:\n",
871                         op == LDAP_MOD_REPLACE ? _("replace") :
872                                 op == LDAP_MOD_ADD ?  _("add") :
873                                         op == LDAP_MOD_INCREMENT ?  _("increment") :
874                                                 op == LDAP_MOD_DELETE ?  _("delete") :
875                                                         _("unknown"),
876                         pmods[ i ]->mod_type );
877             if ( pmods[ i ]->mod_bvalues != NULL ) {
878                 for ( j = 0; pmods[ i ]->mod_bvalues[ j ] != NULL; ++j ) {
879                     bvp = pmods[ i ]->mod_bvalues[ j ];
880                     notascii = 0;
881                     for ( k = 0; (unsigned long) k < bvp->bv_len; ++k ) {
882                         if ( !isascii( bvp->bv_val[ k ] )) {
883                             notascii = 1;
884                             break;
885                         }
886                     }
887                     if ( notascii ) {
888                         printf( _("\tNOT ASCII (%ld bytes)\n"), bvp->bv_len );
889                     } else {
890                         printf( "\t%s\n", bvp->bv_val );
891                     }
892                 }
893             }
894         }
895     }
896
897     if ( newentry ) {
898         printf( "%sadding new entry \"%s\"\n", not ? "!" : "", dn );
899     } else {
900         printf( "%smodifying entry \"%s\"\n", not ? "!" : "", dn );
901     }
902
903     if ( !not ) {
904         if ( newentry ) {
905             i = ldap_add_ext_s( ld, dn, pmods, pctrls, NULL );
906         } else {
907             i = ldap_modify_ext_s( ld, dn, pmods, pctrls, NULL );
908         }
909         if ( i != LDAP_SUCCESS ) {
910                 /* print error message about failed update including DN */
911                 fprintf( stderr, _("%s: update failed: %s\n"), prog, dn );
912                 ldap_perror( ld, newentry ? "ldap_add" : "ldap_modify" );
913         } else if ( verbose ) {
914             printf( _("modify complete\n") );
915         }
916     } else {
917         i = LDAP_SUCCESS;
918     }
919
920     putchar( '\n' );
921
922     return( i );
923 }
924
925
926 static int
927 dodelete(
928         const char *dn,
929     LDAPControl **pctrls )
930 {
931     int rc;
932
933     printf( _("%sdeleting entry \"%s\"\n"), not ? "!" : "", dn );
934     if ( !not ) {
935         if (( rc = ldap_delete_ext_s( ld, dn, pctrls, NULL )) != LDAP_SUCCESS ) {
936                 fprintf( stderr, _("%s: delete failed: %s\n"), prog, dn );
937                 ldap_perror( ld, "ldap_delete" );
938         } else if ( verbose ) {
939             printf( _("delete complete") );
940         }
941     } else {
942         rc = LDAP_SUCCESS;
943     }
944
945     putchar( '\n' );
946
947     return( rc );
948 }
949
950
951 static int
952 dorename(
953         const char *dn,
954         const char *newrdn,
955         const char* newsup,
956         int deleteoldrdn,
957     LDAPControl **pctrls )
958 {
959     int rc;
960
961
962     printf( _("%smodifying rdn of entry \"%s\"\n"), not ? "!" : "", dn );
963     if ( verbose ) {
964         printf( _("\tnew RDN: \"%s\" (%skeep existing values)\n"),
965                 newrdn, deleteoldrdn ? _("do not ") : "" );
966     }
967     if ( !not ) {
968         if (( rc = ldap_rename_s( ld, dn, newrdn, newsup, deleteoldrdn, pctrls, NULL ))
969                 != LDAP_SUCCESS ) {
970                 fprintf( stderr, _("%s: rename failed: %s\n"), prog, dn );
971                 ldap_perror( ld, "ldap_modrdn" );
972         } else {
973             printf( _("modrdn completed\n") );
974         }
975     } else {
976         rc = LDAP_SUCCESS;
977     }
978
979     putchar( '\n' );
980
981     return( rc );
982 }
983
984
985 static char *
986 read_one_record( FILE *fp )
987 {
988     char        *buf, line[ LDAPMOD_MAXLINE ];
989     int         lcur, lmax;
990
991     lcur = lmax = 0;
992     buf = NULL;
993
994     while ( fgets( line, sizeof(line), fp ) != NULL ) {
995         int len = strlen( line );
996
997                 if( len < 2 || ( len == 2 && *line == '\r' )) {
998                         if( buf == NULL ) {
999                                 continue;
1000                         } else {
1001                                 break;
1002                         }
1003                 }
1004
1005                 if ( lcur + len + 1 > lmax ) {
1006                         lmax = LDAPMOD_MAXLINE
1007                                 * (( lcur + len + 1 ) / LDAPMOD_MAXLINE + 1 );
1008
1009                         if (( buf = (char *)ber_memrealloc( buf, lmax )) == NULL ) {
1010                                 perror( "realloc" );
1011                                 exit( EXIT_FAILURE );
1012                         }
1013                 }
1014
1015                 strcpy( buf + lcur, line );
1016                 lcur += len;
1017     }
1018
1019     return( buf );
1020 }
1021
1022