Update.
[jlayton/glibc.git] / nss / makedb.c
1 /* Create simple DB database from textual input.
2    Copyright (C) 1996, 1997, 1998, 1999, 2000 Free Software Foundation, Inc.
3    This file is part of the GNU C Library.
4    Contributed by Ulrich Drepper <drepper@cygnus.com>, 1996.
5
6    The GNU C Library is free software; you can redistribute it and/or
7    modify it under the terms of the GNU Library General Public License as
8    published by the Free Software Foundation; either version 2 of the
9    License, or (at your option) any later version.
10
11    The GNU C Library is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14    Library General Public License for more details.
15
16    You should have received a copy of the GNU Library General Public
17    License along with the GNU C Library; see the file COPYING.LIB.  If not,
18    write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
19    Boston, MA 02111-1307, USA.  */
20
21 #include <argp.h>
22 #include <ctype.h>
23 #include <dlfcn.h>
24 #include <errno.h>
25 #include <error.h>
26 #include <fcntl.h>
27 #include <libintl.h>
28 #include <locale.h>
29 #include <stdio.h>
30 #include <stdint.h>
31 #include <stdlib.h>
32 #include <string.h>
33 #include <sys/stat.h>
34 #include "nss_db/dummy-db.h"
35
36 /* Get libc version number.  */
37 #include "../version.h"
38
39 #define PACKAGE _libc_intl_domainname
40
41 /* If non-zero convert key to lower case.  */
42 static int to_lowercase;
43
44 /* If non-zero print content of input file, one entry per line.  */
45 static int do_undo;
46
47 /* If non-zero do not print informational messages.  */
48 static int be_quiet;
49
50 /* Name of output file.  */
51 static const char *output_name;
52
53 /* Various definitions for the libdb handling.  */
54 enum {
55   nodb,
56   db24,
57   db27
58 } libdb_version;
59 static int (*db_open) (const char *, int,
60                        uint32_t, int, void *, void *, void **);
61
62 /* Constants which vary from version to version are actually variables
63    here.  */
64 static int db_first;
65 static int db_next;
66 static int db_nooverwrite;
67 static int db_truncate;
68
69
70 /* Name and version of program.  */
71 static void print_version (FILE *stream, struct argp_state *state);
72 void (*argp_program_version_hook) (FILE *, struct argp_state *) = print_version;
73
74 /* Definitions of arguments for argp functions.  */
75 static const struct argp_option options[] =
76 {
77   { "fold-case", 'f', NULL, 0, N_("Convert key to lower case") },
78   { "output", 'o', N_("NAME"), 0, N_("Write output to file NAME") },
79   { "quiet", 'q', NULL, 0,
80     N_("Do not print messages while building database") },
81   { "undo", 'u', NULL, 0,
82     N_("Print content of database file, one entry a line") },
83   { NULL, 0, NULL, 0, NULL }
84 };
85
86 /* Short description of program.  */
87 static const char doc[] = N_("Create simple DB database from textual input.");
88
89 /* Strings for arguments in help texts.  */
90 static const char args_doc[] = N_("\
91 INPUT-FILE OUTPUT-FILE\n-o OUTPUT-FILE INPUT-FILE\n-u INPUT-FILE");
92
93 /* Prototype for option handler.  */
94 static error_t parse_opt (int key, char *arg, struct argp_state *state);
95
96 /* Function to print some extra text in the help message.  */
97 static char *more_help (int key, const char *text, void *input);
98
99 /* Data structure to communicate with argp functions.  */
100 static struct argp argp =
101 {
102   options, parse_opt, args_doc, doc, NULL, more_help
103 };
104
105
106 /* Prototypes for local functions.  */
107 static int process_input (FILE *input, const char *inname, NSS_DB *output,
108                           int to_lowercase, int be_quiet);
109 static int print_database (NSS_DB *db);
110 static NSS_DB *dbopen (const char *fname, int oper, int mode);
111
112
113 int
114 main (int argc, char *argv[])
115 {
116   const char *input_name;
117   FILE *input_file;
118   NSS_DB *db_file;
119   int status;
120   int remaining;
121   int mode = 0666;
122
123   /* Set locale via LC_ALL.  */
124   setlocale (LC_ALL, "");
125
126   /* Set the text message domain.  */
127   textdomain (_libc_intl_domainname);
128
129   /* Initialize local variables.  */
130   input_name = NULL;
131
132   /* Parse and process arguments.  */
133   argp_parse (&argp, argc, argv, 0, &remaining, NULL);
134
135   /* Determine file names.  */
136   if (do_undo || output_name != NULL)
137     {
138       if (remaining + 1 != argc)
139         {
140         wrong_arguments:
141           error (0, 0, gettext ("wrong number of arguments"));
142           argp_help (&argp, stdout, ARGP_HELP_SEE,
143                      program_invocation_short_name);
144           exit (1);
145         }
146       input_name = argv[remaining];
147     }
148   else
149     {
150       if (remaining + 2 != argc)
151         goto wrong_arguments;
152
153       input_name = argv[remaining++];
154       output_name = argv[remaining];
155     }
156
157   /* Special handling if we are asked to print the database.  */
158   if (do_undo)
159     {
160       db_file = dbopen (input_name, DB_RDONLY, 0666);
161       if (db_file == NULL)
162         error (EXIT_FAILURE, 0, gettext ("cannot open database file `%s': %s"),
163                input_name,
164                (errno == EINVAL ? gettext ("incorrectly formatted file")
165                 : strerror (errno)));
166
167       status = print_database (db_file);
168
169       db_file->close (db_file->db, 0);
170
171       return status;
172     }
173
174   /* Open input file.  */
175   if (strcmp (input_name, "-") == 0 || strcmp (input_name, "/dev/stdin") == 0)
176     input_file = stdin;
177   else
178     {
179       struct stat st;
180
181       input_file = fopen (input_name, "r");
182       if (input_file == NULL)
183         error (EXIT_FAILURE, errno, gettext ("cannot open input file `%s'"),
184                input_name);
185
186       /* Get the access rights from the source file.  The output file should
187          have the same.  */
188       if (fstat (fileno (input_file), &st) >= 0)
189         mode = st.st_mode & ACCESSPERMS;
190     }
191
192   /* Open output file.  This must not be standard output so we don't
193      handle "-" and "/dev/stdout" special.  */
194   db_file = dbopen (output_name, DB_CREATE | db_truncate, mode);
195   if (db_file == NULL)
196     error (EXIT_FAILURE, errno, gettext ("cannot open output file `%s'"),
197            output_name);
198
199   /* Start the real work.  */
200   status = process_input (input_file, input_name, db_file, to_lowercase,
201                           be_quiet);
202
203   /* Close files.  */
204   if (input_file != stdin)
205     fclose (input_file);
206   db_file->close (db_file->db, 0);
207
208   return status;
209 }
210
211
212 /* Handle program arguments.  */
213 static error_t
214 parse_opt (int key, char *arg, struct argp_state *state)
215 {
216   switch (key)
217     {
218     case 'f':
219       to_lowercase = 1;
220       break;
221     case 'o':
222       output_name = arg;
223       break;
224     case 'q':
225       be_quiet = 1;
226       break;
227     case 'u':
228       do_undo = 1;
229       break;
230     default:
231       return ARGP_ERR_UNKNOWN;
232     }
233   return 0;
234 }
235
236
237 static char *
238 more_help (int key, const char *text, void *input)
239 {
240   switch (key)
241     {
242     case ARGP_KEY_HELP_EXTRA:
243       /* We print some extra information.  */
244       return strdup (gettext ("\
245 Report bugs using the `glibcbug' script to <bugs@gnu.org>.\n"));
246     default:
247       break;
248     }
249   return (char *) text;
250 }
251
252 /* Print the version information.  */
253 static void
254 print_version (FILE *stream, struct argp_state *state)
255 {
256   fprintf (stream, "makedb (GNU %s) %s\n", PACKAGE, VERSION);
257   fprintf (stream, gettext ("\
258 Copyright (C) %s Free Software Foundation, Inc.\n\
259 This is free software; see the source for copying conditions.  There is NO\n\
260 warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n\
261 "), "2000");
262   fprintf (stream, gettext ("Written by %s.\n"), "Ulrich Drepper");
263 }
264
265
266 static int
267 process_input (input, inname, output, to_lowercase, be_quiet)
268      FILE *input;
269      const char *inname;
270      NSS_DB *output;
271      int to_lowercase;
272      int be_quiet;
273 {
274   char *line;
275   size_t linelen;
276   int status;
277   size_t linenr;
278
279   line = NULL;
280   linelen = 0;
281   status = EXIT_SUCCESS;
282   linenr = 0;
283
284   while (!feof (input))
285     {
286       DBT key;
287       DBT val;
288       char *cp;
289       int n;
290
291       n = getline (&line, &linelen, input);
292       if (n < 0)
293         /* This means end of file or some bug.  */
294         break;
295       if (n == 0)
296         /* Short read.  Probably interrupted system call. */
297         continue;
298
299       ++linenr;
300
301       if (line[n - 1] == '\n')
302         /* Remove trailing newline.  */
303         line[--n] = '\0';
304
305       cp = line;
306       while (isspace (*cp))
307         ++cp;
308
309       if (*cp == '#')
310         /* First non-space character in line '#': it's a comment.  */
311         continue;
312
313       key.data = cp;
314       while (*cp != '\0' && !isspace (*cp))
315         {
316           if (to_lowercase)
317             *cp = tolower (*cp);
318           ++cp;
319         }
320
321       if (key.data == cp)
322         /* It's an empty line.  */
323         continue;
324
325       key.size = cp - (char *) key.data;
326       key.flags = 0;
327
328       while (isspace (*cp))
329         ++cp;
330
331       val.data = cp;
332       val.size = (&line[n] - cp) + 1;
333       val.flags = 0;
334
335       /* Store the value.  */
336       status = output->put (output->db, NULL, &key, &val, db_nooverwrite);
337       if (status != 0)
338         {
339           if (status == DB_KEYEXIST)
340             {
341               if (!be_quiet)
342                 error_at_line (0, 0, inname, linenr,
343                                gettext ("duplicate key"));
344               /* This is no real error.  Just give a warning.  */
345               status = 0;
346               continue;
347             }
348           else
349             error (0, status, gettext ("while writing database file"));
350
351           status = EXIT_FAILURE;
352
353           clearerr (input);
354           break;
355         }
356     }
357
358   if (ferror (input))
359     {
360       error (0, 0, gettext ("problems while reading `%s'"), inname);
361       status = EXIT_FAILURE;
362     }
363
364   return status;
365 }
366
367
368 static int
369 print_database (db)
370      NSS_DB *db;
371 {
372   DBT key;
373   DBT val;
374   NSS_DBC *cursor;
375   int status;
376
377   status = db->cursor (db->db, NULL, &cursor);
378   if (status != 0)
379     {
380       error (0, status, gettext ("while reading database"));
381       return EXIT_FAILURE;
382     }
383
384   key.flags = 0;
385   val.flags = 0;
386   status = cursor->c_get (cursor->cursor, &key, &val, db_first);
387   while (status == 0)
388     {
389       printf ("%.*s %s\n", (int) key.size, (char *) key.data,
390               (char *) val.data);
391
392       status = cursor->c_get (cursor->cursor, &key, &val, db_next);
393     }
394
395   if (status != DB_NOTFOUND)
396     {
397       error (0, status, gettext ("while reading database"));
398       return EXIT_FAILURE;
399     }
400
401   return EXIT_SUCCESS;
402 }
403
404
405 static int
406 load_db (void)
407 {
408   static const char *libnames[] = { "libdb.so.3" };
409   int x;
410   void *handle;
411
412   for(x = 0; x < sizeof (libnames) / sizeof (libnames[0]); ++x)
413     {
414       handle = dlopen (libnames[x], RTLD_LAZY);
415       if (handle == NULL)
416         continue;
417
418       db_open = dlsym (handle, "db_open");
419       if (db_open != NULL)
420         {
421           /* Alright, we got a library.  Now find out which version it is.  */
422           const char *(*db_version) (int *, int *, int *);
423
424           db_version = dlsym (handle, "db_version");
425           if (db_version != NULL)
426             {
427               /* Call the function and get the information.  */
428               int major, minor, subminor;
429
430               DL_CALL_FCT (db_version, (&major, &minor, &subminor));
431               if (major == 2)
432                 {
433                   /* We currently cannot handle other versions than the
434                      2.x series.  */
435                   if (minor < 6 || (minor == 6 && subminor < 4))
436                     {
437                       libdb_version = db24;
438                       db_first = DB24_FIRST;
439                       db_next = DB24_NEXT;
440                       db_nooverwrite = DB24_NOOVERWRITE;
441                       db_truncate = DB24_TRUNCATE;
442                     }
443                   else
444                     {
445                       libdb_version = db27;
446                       db_first = DB27_FIRST;
447                       db_next = DB27_NEXT;
448                       db_nooverwrite = DB27_NOOVERWRITE;
449                       db_truncate = DB27_TRUNCATE;
450                     }
451                 }
452             }
453
454           if (libdb_version != nodb)
455             return 0;
456         }
457
458       dlclose (handle);
459     }
460
461   (void) dlerror ();
462   return 1;
463 }
464
465
466 static int
467 db_cursor (void *db, void *txn, NSS_DBC **dbcp)
468 {
469   void *ptr;
470   NSS_DBC *dbc = NULL;
471   int ret;
472
473   switch (libdb_version)
474     {
475     case db24:
476       ret = ((struct db24 *) db)->cursor (db, txn, &ptr);
477       break;
478     case db27:
479       ret = ((struct db27 *) db)->cursor (db, txn, &ptr, 0);
480       break;
481     default:
482       abort ();
483     }
484
485   if (ret == 0)
486     {
487       dbc = (NSS_DBC *) malloc (sizeof (NSS_DBC));
488       if (dbc == NULL)
489         error (EXIT_FAILURE, errno, gettext ("while reading database"));
490       dbc->cursor = ptr;
491
492       switch (libdb_version)
493         {
494         case db24:
495           dbc->c_get =
496             (int (*) (void *, void *, void *, uint32_t))
497             ((struct dbc24 *) ptr)->c_get;
498           break;
499         case db27:
500           dbc->c_get =
501             (int (*) (void *, void *, void *, uint32_t))
502             ((struct dbc27 *) ptr)->c_get;
503           break;
504         default:
505           abort ();
506         }
507     }
508
509   *dbcp = dbc;
510
511   return ret;
512 }
513
514
515 static NSS_DB *
516 dbopen (const char *fname, int oper, int mode)
517 {
518   int err;
519   void *odb;
520   NSS_DB *db;
521
522   /* First load the shared object.  */
523   load_db ();
524
525   if (db_open == NULL)
526     return NULL;
527
528   /* Actually open the database.  */
529   err = DL_CALL_FCT (db_open, (fname, DB_BTREE, oper, mode, NULL, NULL, &odb));
530   if (err != 0)
531     {
532       errno = err;
533       return NULL;
534     }
535
536   /* Construct the object we pass up.  */
537   db = (NSS_DB *) malloc (sizeof (NSS_DB));
538   if (db != NULL)
539     {
540       db->db = odb;
541
542       /* The functions are at different positions for the different
543          versions.  Sigh.  */
544       switch (libdb_version)
545         {
546         case db24:
547           db->close =
548             (int (*) (void *, uint32_t)) ((struct db24 *) odb)->close;
549           db->fd =
550             (int (*) (void *, int *)) ((struct db24 *) odb)->fd;
551           db->get =
552             (int (*) (void *, void *, void *, void *, uint32_t))
553             ((struct db24 *) odb)->get;
554           db->put =
555             (int (*) (void *, void *, void *, void *, uint32_t))
556             ((struct db24 *) odb)->put;
557           break;
558         case db27:
559           db->close =
560             (int (*) (void *, uint32_t)) ((struct db27 *) odb)->close;
561           db->fd =
562             (int (*) (void *, int *)) ((struct db27 *) odb)->fd;
563           db->get =
564             (int (*) (void *, void *, void *, void *, uint32_t))
565             ((struct db27 *) odb)->get;
566           db->put =
567             (int (*) (void *, void *, void *, void *, uint32_t))
568             ((struct db27 *) odb)->put;
569           break;
570         default:
571           abort ();
572         }
573       db->cursor = db_cursor;
574     }
575
576   return db;
577 }