1 /* Create simple DB database from textual input.
2 Copyright (C) 1996-2000, 2011, 2012 Free Software Foundation, Inc.
3 This file is part of the GNU C Library.
4 Contributed by Ulrich Drepper <drepper@cygnus.com>, 1996.
6 The GNU C Library is free software; you can redistribute it and/or
7 modify it under the terms of the GNU Lesser General Public
8 License as published by the Free Software Foundation; either
9 version 2.1 of the License, or (at your option) any later version.
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 Lesser General Public License for more details.
16 You should have received a copy of the GNU Lesser General Public
17 License along with the GNU C Library; if not, write to the Free
18 Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
37 #include "nss_db/nss_db.h"
39 /* Get libc version number. */
40 #include "../version.h"
42 /* The hashing function we use. */
43 #include "../intl/hash-string.h"
45 /* SELinux support. */
47 # include <selinux/selinux.h>
50 #define PACKAGE _libc_intl_domainname
52 /* List of data bases. */
57 struct database
*next
;
66 static size_t ndatabases
;
67 static size_t nhashentries_total
;
68 static size_t valstrlen
;
69 static void *valstrtree
;
70 static char *valstrtab
;
71 static size_t extrastrlen
;
81 /* Stored string entry. */
90 /* True if any entry has been added. */
91 static bool any_dbentry
;
93 /* If non-zero convert key to lower case. */
94 static int to_lowercase
;
96 /* If non-zero print content of input file, one entry per line. */
99 /* If non-zero do not print informational messages. */
102 /* Name of output file. */
103 static const char *output_name
;
105 /* Name and version of program. */
106 static void print_version (FILE *stream
, struct argp_state
*state
);
107 void (*argp_program_version_hook
) (FILE *, struct argp_state
*) = print_version
;
109 /* Definitions of arguments for argp functions. */
110 static const struct argp_option options
[] =
112 { "fold-case", 'f', NULL
, 0, N_("Convert key to lower case") },
113 { "output", 'o', N_("NAME"), 0, N_("Write output to file NAME") },
114 { "quiet", 'q', NULL
, 0,
115 N_("Do not print messages while building database") },
116 { "undo", 'u', NULL
, 0,
117 N_("Print content of database file, one entry a line") },
118 { "generated", 'g', N_("CHAR"), 0,
119 N_("Generated line not part of iteration") },
120 { NULL
, 0, NULL
, 0, NULL
}
123 /* Short description of program. */
124 static const char doc
[] = N_("Create simple database from textual input.");
126 /* Strings for arguments in help texts. */
127 static const char args_doc
[] = N_("\
128 INPUT-FILE OUTPUT-FILE\n-o OUTPUT-FILE INPUT-FILE\n-u INPUT-FILE");
130 /* Prototype for option handler. */
131 static error_t
parse_opt (int key
, char *arg
, struct argp_state
*state
);
133 /* Function to print some extra text in the help message. */
134 static char *more_help (int key
, const char *text
, void *input
);
136 /* Data structure to communicate with argp functions. */
137 static struct argp argp
=
139 options
, parse_opt
, args_doc
, doc
, NULL
, more_help
143 /* List of databases which are not part of the iteration table. */
144 static struct db_option
147 struct db_option
*next
;
151 /* Prototypes for local functions. */
152 static int process_input (FILE *input
, const char *inname
,
153 int to_lowercase
, int be_quiet
);
154 static int print_database (int fd
);
155 static void compute_tables (void);
156 static int write_output (int fd
);
158 /* SELinux support. */
160 /* Set the SELinux file creation context for the given file. */
161 static void set_file_creation_context (const char *outname
, mode_t mode
);
162 static void reset_file_creation_context (void);
164 # define set_file_creation_context(_outname,_mode)
165 # define reset_file_creation_context()
169 /* External functions. */
170 extern void *xmalloc (size_t n
)
171 __attribute_malloc__
__attribute_alloc_size (1);
172 extern void *xcalloc (size_t n
, size_t s
)
173 __attribute_malloc__
__attribute_alloc_size (1, 2);
177 main (int argc
, char *argv
[])
179 const char *input_name
;
184 /* Set locale via LC_ALL. */
185 setlocale (LC_ALL
, "");
187 /* Set the text message domain. */
188 textdomain (_libc_intl_domainname
);
190 /* Initialize local variables. */
193 /* Parse and process arguments. */
194 argp_parse (&argp
, argc
, argv
, 0, &remaining
, NULL
);
196 /* Determine file names. */
197 if (do_undo
|| output_name
!= NULL
)
199 if (remaining
+ 1 != argc
)
202 error (0, 0, gettext ("wrong number of arguments"));
203 argp_help (&argp
, stdout
, ARGP_HELP_SEE
,
204 program_invocation_short_name
);
207 input_name
= argv
[remaining
];
211 if (remaining
+ 2 != argc
)
212 goto wrong_arguments
;
214 input_name
= argv
[remaining
++];
215 output_name
= argv
[remaining
];
218 /* Special handling if we are asked to print the database. */
221 int fd
= open (input_name
, O_RDONLY
);
223 error (EXIT_FAILURE
, errno
, gettext ("cannot open database file `%s'"),
226 int status
= print_database (fd
);
233 /* Open input file. */
234 if (strcmp (input_name
, "-") == 0 || strcmp (input_name
, "/dev/stdin") == 0)
240 input_file
= fopen64 (input_name
, "r");
241 if (input_file
== NULL
)
242 error (EXIT_FAILURE
, errno
, gettext ("cannot open input file `%s'"),
245 /* Get the access rights from the source file. The output file should
247 if (fstat64 (fileno (input_file
), &st
) >= 0)
248 mode
= st
.st_mode
& ACCESSPERMS
;
251 /* Start the real work. */
252 int status
= process_input (input_file
, input_name
, to_lowercase
, be_quiet
);
255 if (input_file
!= stdin
)
258 /* No need to continue when we did not read the file successfully. */
259 if (status
!= EXIT_SUCCESS
)
262 /* Bail out if nothing is to be done. */
268 error (EXIT_SUCCESS
, 0, gettext ("no entries to be processed"));
271 /* Compute hash and string tables. */
274 /* Open output file. This must not be standard output so we don't
275 handle "-" and "/dev/stdout" special. */
276 char *tmp_output_name
;
277 if (asprintf (&tmp_output_name
, "%s.XXXXXX", output_name
) == -1)
278 error (EXIT_FAILURE
, errno
, gettext ("cannot create temporary file name"));
280 set_file_creation_context (output_name
, mode
);
281 int fd
= mkstemp (tmp_output_name
);
282 reset_file_creation_context ();
284 error (EXIT_FAILURE
, errno
, gettext ("cannot create temporary file"));
286 status
= write_output (fd
);
288 if (status
== EXIT_SUCCESS
)
292 if (fstat64 (fd
, &st
) == 0)
294 if ((st
.st_mode
& ACCESSPERMS
) != mode
)
295 /* We ignore problems with changing the mode. */
300 error (0, errno
, gettext ("cannot stat newly created file"));
301 status
= EXIT_FAILURE
;
307 if (status
== EXIT_SUCCESS
)
309 if (rename (tmp_output_name
, output_name
) != 0)
311 error (0, errno
, gettext ("cannot rename temporary file"));
312 status
= EXIT_FAILURE
;
318 unlink (tmp_output_name
);
324 /* Handle program arguments. */
326 parse_opt (int key
, char *arg
, struct argp_state
*state
)
328 struct db_option
*newp
;
345 newp
= xmalloc (sizeof (*newp
));
347 newp
->next
= db_options
;
351 return ARGP_ERR_UNKNOWN
;
358 more_help (int key
, const char *text
, void *input
)
362 case ARGP_KEY_HELP_EXTRA
:
363 /* We print some extra information. */
364 return strdup (gettext ("\
365 For bug reporting instructions, please see:\n\
366 <http://www.gnu.org/software/libc/bugs.html>.\n"));
370 return (char *) text
;
373 /* Print the version information. */
375 print_version (FILE *stream
, struct argp_state
*state
)
377 fprintf (stream
, "makedb (GNU %s) %s\n", PACKAGE
, VERSION
);
378 fprintf (stream
, gettext ("\
379 Copyright (C) %s Free Software Foundation, Inc.\n\
380 This is free software; see the source for copying conditions. There is NO\n\
381 warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n\
383 fprintf (stream
, gettext ("Written by %s.\n"), "Ulrich Drepper");
388 dbentry_compare (const void *p1
, const void *p2
)
390 const struct dbentry
*d1
= (const struct dbentry
*) p1
;
391 const struct dbentry
*d2
= (const struct dbentry
*) p2
;
393 if (d1
->hashval
!= d2
->hashval
)
394 return d1
->hashval
< d2
->hashval
? -1 : 1;
396 return strcmp (d1
->str
, d2
->str
);
401 valstr_compare (const void *p1
, const void *p2
)
403 const struct valstrentry
*d1
= (const struct valstrentry
*) p1
;
404 const struct valstrentry
*d2
= (const struct valstrentry
*) p2
;
406 return strcmp (d1
->str
, d2
->str
);
411 process_input (input
, inname
, to_lowercase
, be_quiet
)
424 status
= EXIT_SUCCESS
;
427 struct database
*last_database
= NULL
;
429 while (!feof_unlocked (input
))
431 ssize_t n
= getline (&line
, &linelen
, input
);
433 /* This means end of file or some bug. */
436 /* Short read. Probably interrupted system call. */
441 if (line
[n
- 1] == '\n')
442 /* Remove trailing newline. */
446 while (isspace (*cp
))
449 if (*cp
== '#' || *cp
== '\0')
450 /* First non-space character in line '#': it's a comment.
451 Also go to the next line if it is empty except for whitespaces. */
454 /* Skip over the character indicating the database so that it is not
455 affected by TO_LOWERCASE. */
457 while (*cp
!= '\0' && !isspace (*cp
))
465 /* It's a line without a value field. */
469 size_t keylen
= cp
- key
;
471 while (isspace (*cp
))
475 size_t datalen
= (&line
[n
] - cp
) + 1;
477 /* Find the database. */
478 if (last_database
== NULL
|| last_database
->dbid
!= key
[0])
480 last_database
= databases
;
481 while (last_database
!= NULL
&& last_database
->dbid
!= key
[0])
482 last_database
= last_database
->next
;
484 if (last_database
== NULL
)
486 last_database
= xmalloc (sizeof (*last_database
));
487 last_database
->dbid
= key
[0];
488 last_database
->extra_string
= false;
489 last_database
->next
= databases
;
490 last_database
->entries
= NULL
;
491 last_database
->nentries
= 0;
492 last_database
->keystrlen
= 0;
493 databases
= last_database
;
495 struct db_option
*runp
= db_options
;
497 if (runp
->dbid
== key
[0])
499 last_database
->extra_string
= true;
507 /* Skip the database selector. */
511 /* Store the data. */
512 struct valstrentry
*nentry
= xmalloc (sizeof (struct valstrentry
)
514 if (last_database
->extra_string
)
515 nentry
->idx
= extrastrlen
;
517 nentry
->idx
= valstrlen
;
518 nentry
->extra_string
= last_database
->extra_string
;
519 memcpy (nentry
->str
, data
, datalen
);
521 struct valstrentry
**fdata
= tsearch (nentry
, &valstrtree
,
524 error (EXIT_FAILURE
, errno
, gettext ("cannot create search tree"));
526 if (*fdata
!= nentry
)
528 /* We can reuse a string. */
533 if (last_database
->extra_string
)
534 extrastrlen
+= datalen
;
536 valstrlen
+= datalen
;
539 struct dbentry
*newp
= xmalloc (sizeof (struct dbentry
) + keylen
);
540 newp
->validx
= nentry
->idx
;
541 newp
->hashval
= __hash_string (key
);
542 memcpy (newp
->str
, key
, keylen
);
544 struct dbentry
**found
= tsearch (newp
, &last_database
->entries
,
547 error (EXIT_FAILURE
, errno
, gettext ("cannot create search tree"));
553 error_at_line (0, 0, inname
, linenr
, gettext ("duplicate key"));
557 ++last_database
->nentries
;
558 last_database
->keystrlen
+= keylen
;
563 if (ferror_unlocked (input
))
565 error (0, 0, gettext ("problems while reading `%s'"), inname
);
566 status
= EXIT_FAILURE
;
574 copy_valstr (const void *nodep
, const VISIT which
, const int depth
)
576 if (which
!= leaf
&& which
!= postorder
)
579 const struct valstrentry
*p
= *(const struct valstrentry
**) nodep
;
581 strcpy (valstrtab
+ (p
->extra_string
? valstrlen
: 0) + p
->idx
, p
->str
);
586 is_prime (size_t candidate
)
588 /* No even number and none less than 10 will be passed here. */
590 size_t sq
= divn
* divn
;
592 while (sq
< candidate
&& candidate
% divn
!= 0)
599 return candidate
% divn
!= 0;
604 next_prime (size_t seed
)
606 /* Make it definitely odd. */
609 while (!is_prime (seed
))
617 compute_tables (void)
619 valstrtab
= xmalloc (roundup (valstrlen
+ extrastrlen
, sizeof (stridx_t
)));
620 while ((valstrlen
+ extrastrlen
) % sizeof (stridx_t
) != 0)
621 valstrtab
[valstrlen
++] = '\0';
622 twalk (valstrtree
, copy_valstr
);
624 static struct database
*db
;
625 for (db
= databases
; db
!= NULL
; db
= db
->next
)
626 if (db
->nentries
!= 0)
630 /* We simply use an odd number large than twice the number of
631 elements to store in the hash table for the size. This gives
632 enough efficiency. */
633 #define TEST_RANGE 30
634 size_t nhashentries_min
= next_prime (db
->nentries
< TEST_RANGE
636 : db
->nentries
* 2 - TEST_RANGE
);
637 size_t nhashentries_max
= MAX (nhashentries_min
, db
->nentries
* 4);
638 size_t nhashentries_best
= nhashentries_min
;
639 size_t chainlength_best
= db
->nentries
;
641 db
->hashtable
= xmalloc (2 * nhashentries_max
* sizeof (stridx_t
)
643 db
->keyidxtab
= db
->hashtable
+ nhashentries_max
;
644 db
->keystrtab
= (char *) (db
->keyidxtab
+ nhashentries_max
);
646 static size_t max_chainlength
;
648 static size_t nhashentries
;
649 static bool copy_string
;
651 void add_key(const void *nodep
, const VISIT which
, const int depth
)
653 if (which
!= leaf
&& which
!= postorder
)
656 const struct dbentry
*dbe
= *(const struct dbentry
**) nodep
;
661 stridx
= wp
- db
->keystrtab
;
662 wp
= stpcpy (wp
, dbe
->str
) + 1;
667 size_t hidx
= dbe
->hashval
% nhashentries
;
668 size_t hval2
= 1 + dbe
->hashval
% (nhashentries
- 2);
669 size_t chainlength
= 0;
671 while (db
->hashtable
[hidx
] != ~((stridx_t
) 0))
674 if ((hidx
+= hval2
) >= nhashentries
)
675 hidx
-= nhashentries
;
678 db
->hashtable
[hidx
] = ((db
->extra_string
? valstrlen
: 0)
680 db
->keyidxtab
[hidx
] = stridx
;
682 max_chainlength
= MAX (max_chainlength
, chainlength
);
686 nhashentries
= nhashentries_min
;
687 for (size_t cnt
= 0; cnt
< TEST_RANGE
; ++cnt
)
689 memset (db
->hashtable
, '\xff', nhashentries
* sizeof (stridx_t
));
694 twalk (db
->entries
, add_key
);
696 if (max_chainlength
== 0)
698 /* No need to look further, this is as good as it gets. */
699 nhashentries_best
= nhashentries
;
703 if (max_chainlength
< chainlength_best
)
705 chainlength_best
= max_chainlength
;
706 nhashentries_best
= nhashentries
;
709 nhashentries
= next_prime (nhashentries
+ 1);
710 if (nhashentries
> nhashentries_max
)
714 /* Recompute the best table again, this time fill in the strings. */
715 nhashentries
= nhashentries_best
;
716 memset (db
->hashtable
, '\xff',
717 2 * nhashentries_max
* sizeof (stridx_t
));
721 twalk (db
->entries
, add_key
);
723 db
->nhashentries
= nhashentries_best
;
724 nhashentries_total
+= nhashentries_best
;
730 write_output (int fd
)
732 struct nss_db_header
*header
;
733 uint64_t file_offset
= (sizeof (struct nss_db_header
)
734 + (ndatabases
* sizeof (header
->dbs
[0])));
735 header
= alloca (file_offset
);
737 header
->magic
= NSS_DB_MAGIC
;
738 header
->ndbs
= ndatabases
;
739 header
->valstroffset
= file_offset
;
740 header
->valstrlen
= valstrlen
;
742 size_t filled_dbs
= 0;
743 struct iovec iov
[2 + ndatabases
* 3];
744 iov
[0].iov_base
= header
;
745 iov
[0].iov_len
= file_offset
;
747 iov
[1].iov_base
= valstrtab
;
748 iov
[1].iov_len
= valstrlen
+ extrastrlen
;
749 file_offset
+= iov
[1].iov_len
;
751 size_t keydataoffset
= file_offset
+ nhashentries_total
* sizeof (stridx_t
);
752 for (struct database
*db
= databases
; db
!= NULL
; db
= db
->next
)
753 if (db
->entries
!= NULL
)
755 assert (file_offset
% sizeof (stridx_t
) == 0);
756 assert (filled_dbs
< ndatabases
);
758 header
->dbs
[filled_dbs
].id
= db
->dbid
;
759 memset (header
->dbs
[filled_dbs
].pad
, '\0',
760 sizeof (header
->dbs
[0].pad
));
761 header
->dbs
[filled_dbs
].hashsize
= db
->nhashentries
;
763 iov
[2 + filled_dbs
].iov_base
= db
->hashtable
;
764 iov
[2 + filled_dbs
].iov_len
= db
->nhashentries
* sizeof (stridx_t
);
765 header
->dbs
[filled_dbs
].hashoffset
= file_offset
;
766 file_offset
+= iov
[2 + filled_dbs
].iov_len
;
768 iov
[2 + ndatabases
+ filled_dbs
* 2].iov_base
= db
->keyidxtab
;
769 iov
[2 + ndatabases
+ filled_dbs
* 2].iov_len
770 = db
->nhashentries
* sizeof (stridx_t
);
771 header
->dbs
[filled_dbs
].keyidxoffset
= keydataoffset
;
772 keydataoffset
+= iov
[2 + ndatabases
+ filled_dbs
* 2].iov_len
;
774 iov
[3 + ndatabases
+ filled_dbs
* 2].iov_base
= db
->keystrtab
;
775 iov
[3 + ndatabases
+ filled_dbs
* 2].iov_len
= db
->keystrlen
;
776 header
->dbs
[filled_dbs
].keystroffset
= keydataoffset
;
777 keydataoffset
+= iov
[3 + ndatabases
+ filled_dbs
* 2].iov_len
;
782 assert (filled_dbs
== ndatabases
);
783 assert (file_offset
== (iov
[0].iov_len
+ iov
[1].iov_len
784 + nhashentries_total
* sizeof (stridx_t
)));
785 header
->allocate
= file_offset
;
787 if (writev (fd
, iov
, 2 + ndatabases
* 3) != keydataoffset
)
789 error (0, errno
, gettext ("failed to write new database file"));
798 print_database (int fd
)
801 if (fstat64 (fd
, &st
) != 0)
802 error (EXIT_FAILURE
, errno
, gettext ("cannot stat database file"));
804 const struct nss_db_header
*header
= mmap (NULL
, st
.st_size
, PROT_READ
,
805 MAP_PRIVATE
|MAP_POPULATE
, fd
, 0);
806 if (header
== MAP_FAILED
)
807 error (EXIT_FAILURE
, errno
, gettext ("cannot map database file"));
809 if (header
->magic
!= NSS_DB_MAGIC
)
810 error (EXIT_FAILURE
, 0, gettext ("file not a database file"));
812 const char *valstrtab
= (const char *) header
+ header
->valstroffset
;
814 for (unsigned int dbidx
= 0; dbidx
< header
->ndbs
; ++dbidx
)
816 const stridx_t
*stridxtab
817 = ((const stridx_t
*) ((const char *) header
818 + header
->dbs
[dbidx
].keyidxoffset
));
819 const char *keystrtab
820 = (const char *) header
+ header
->dbs
[dbidx
].keystroffset
;
821 const stridx_t
*hashtab
822 = (const stridx_t
*) ((const char *) header
823 + header
->dbs
[dbidx
].hashoffset
);
825 for (uint32_t hidx
= 0; hidx
< header
->dbs
[dbidx
].hashsize
; ++hidx
)
826 if (hashtab
[hidx
] != ~((stridx_t
) 0))
828 header
->dbs
[dbidx
].id
,
829 keystrtab
+ stridxtab
[hidx
],
830 valstrtab
+ hashtab
[hidx
]);
839 set_file_creation_context (const char *outname
, mode_t mode
)
842 static int enforcing
;
843 security_context_t ctx
;
845 /* Check if SELinux is enabled, and remember. */
847 enabled
= is_selinux_enabled () ? 1 : -1;
851 /* Check if SELinux is enforcing, and remember. */
853 enforcing
= security_getenforce () ? 1 : -1;
855 /* Determine the context which the file should have. */
857 if (matchpathcon (outname
, S_IFREG
| mode
, &ctx
) == 0 && ctx
!= NULL
)
859 if (setfscreatecon (ctx
) != 0)
860 error (enforcing
> 0 ? EXIT_FAILURE
: 0, 0,
861 gettext ("cannot set file creation context for `%s'"),
869 reset_file_creation_context (void)
871 setfscreatecon (NULL
);