xref: /onnv-gate/usr/src/cmd/svc/configd/backend.c (revision 11996:91b62f7b8186)
10Sstevel@tonic-gate /*
20Sstevel@tonic-gate  * CDDL HEADER START
30Sstevel@tonic-gate  *
40Sstevel@tonic-gate  * The contents of this file are subject to the terms of the
54520Snw141292  * Common Development and Distribution License (the "License").
64520Snw141292  * You may not use this file except in compliance with the License.
70Sstevel@tonic-gate  *
80Sstevel@tonic-gate  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
90Sstevel@tonic-gate  * or http://www.opensolaris.org/os/licensing.
100Sstevel@tonic-gate  * See the License for the specific language governing permissions
110Sstevel@tonic-gate  * and limitations under the License.
120Sstevel@tonic-gate  *
130Sstevel@tonic-gate  * When distributing Covered Code, include this CDDL HEADER in each
140Sstevel@tonic-gate  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
150Sstevel@tonic-gate  * If applicable, add the following below this CDDL HEADER, with the
160Sstevel@tonic-gate  * fields enclosed by brackets "[]" replaced with your own identifying
170Sstevel@tonic-gate  * information: Portions Copyright [yyyy] [name of copyright owner]
180Sstevel@tonic-gate  *
190Sstevel@tonic-gate  * CDDL HEADER END
200Sstevel@tonic-gate  */
215777Stw21770 
220Sstevel@tonic-gate /*
23*11996SThomas.Whitten@Sun.COM  * Copyright 2010 Sun Microsystems, Inc.  All rights reserved.
240Sstevel@tonic-gate  * Use is subject to license terms.
250Sstevel@tonic-gate  */
260Sstevel@tonic-gate 
27407Sjwadams /*
28407Sjwadams  * sqlite is not compatible with _FILE_OFFSET_BITS=64, but we need to
29407Sjwadams  * be able to statvfs(2) possibly large systems.  This define gives us
30407Sjwadams  * access to the transitional interfaces.  See lfcompile64(5) for how
31407Sjwadams  * _LARGEFILE64_SOURCE works.
32407Sjwadams  */
33407Sjwadams #define	_LARGEFILE64_SOURCE
34407Sjwadams 
350Sstevel@tonic-gate #include <assert.h>
36*11996SThomas.Whitten@Sun.COM #include <atomic.h>
370Sstevel@tonic-gate #include <door.h>
380Sstevel@tonic-gate #include <dirent.h>
390Sstevel@tonic-gate #include <errno.h>
400Sstevel@tonic-gate #include <fcntl.h>
410Sstevel@tonic-gate #include <limits.h>
420Sstevel@tonic-gate #include <pthread.h>
430Sstevel@tonic-gate #include <stdarg.h>
440Sstevel@tonic-gate #include <stdio.h>
450Sstevel@tonic-gate #include <stdlib.h>
460Sstevel@tonic-gate #include <string.h>
47*11996SThomas.Whitten@Sun.COM #include <strings.h>
48407Sjwadams #include <sys/stat.h>
49407Sjwadams #include <sys/statvfs.h>
50*11996SThomas.Whitten@Sun.COM #include <time.h>
510Sstevel@tonic-gate #include <unistd.h>
520Sstevel@tonic-gate #include <zone.h>
536035Sstevep #include <libscf_priv.h>
540Sstevel@tonic-gate 
550Sstevel@tonic-gate #include "configd.h"
560Sstevel@tonic-gate #include "repcache_protocol.h"
570Sstevel@tonic-gate 
584520Snw141292 #include <sqlite.h>
594520Snw141292 #include <sqlite-misc.h>
600Sstevel@tonic-gate 
610Sstevel@tonic-gate /*
620Sstevel@tonic-gate  * This file has two purposes:
630Sstevel@tonic-gate  *
640Sstevel@tonic-gate  * 1. It contains the database schema, and the code for setting up our backend
650Sstevel@tonic-gate  *    databases, including installing said schema.
660Sstevel@tonic-gate  *
670Sstevel@tonic-gate  * 2. It provides a simplified interface to the SQL database library, and
680Sstevel@tonic-gate  *    synchronizes MT access to the database.
690Sstevel@tonic-gate  */
700Sstevel@tonic-gate 
71*11996SThomas.Whitten@Sun.COM #define	IS_VOLATILE(be)		((be)->be_ppath != NULL)
72*11996SThomas.Whitten@Sun.COM #define	MAX_FLIGHT_RECORDER_EVENTS	100
73*11996SThomas.Whitten@Sun.COM 
74*11996SThomas.Whitten@Sun.COM typedef enum backend_switch_results {
75*11996SThomas.Whitten@Sun.COM 	BACKEND_SWITCH_FATAL =	-1,
76*11996SThomas.Whitten@Sun.COM 	BACKEND_SWITCH_OK =	0,
77*11996SThomas.Whitten@Sun.COM 	BACKEND_SWITCH_RO
78*11996SThomas.Whitten@Sun.COM } backend_switch_results_t;
79*11996SThomas.Whitten@Sun.COM 
800Sstevel@tonic-gate typedef struct backend_spent {
810Sstevel@tonic-gate 	uint64_t bs_count;
820Sstevel@tonic-gate 	hrtime_t bs_time;
830Sstevel@tonic-gate 	hrtime_t bs_vtime;
840Sstevel@tonic-gate } backend_spent_t;
850Sstevel@tonic-gate 
860Sstevel@tonic-gate typedef struct backend_totals {
870Sstevel@tonic-gate 	backend_spent_t	bt_lock;	/* waiting for lock */
880Sstevel@tonic-gate 	backend_spent_t	bt_exec;	/* time spent executing SQL */
890Sstevel@tonic-gate } backend_totals_t;
900Sstevel@tonic-gate 
91*11996SThomas.Whitten@Sun.COM /*
92*11996SThomas.Whitten@Sun.COM  * There are times when svcadm asks configd to move the BACKEND_TYPE_NORMAL
93*11996SThomas.Whitten@Sun.COM  * repository to volatile storage.  See backend_switch().  When the
94*11996SThomas.Whitten@Sun.COM  * repository is on volatile storage, we save the location of the permanent
95*11996SThomas.Whitten@Sun.COM  * repository in be_ppath.  We use the saved path when the time comes to
96*11996SThomas.Whitten@Sun.COM  * move the repository back.  When the repository is on permanent storage,
97*11996SThomas.Whitten@Sun.COM  * be_ppath is set to NULL.  Also see the definition of IS_VOLATILE() above
98*11996SThomas.Whitten@Sun.COM  * for testing if the repository is on volatile storage.
99*11996SThomas.Whitten@Sun.COM  */
1000Sstevel@tonic-gate typedef struct sqlite_backend {
1010Sstevel@tonic-gate 	pthread_mutex_t	be_lock;
1020Sstevel@tonic-gate 	pthread_t	be_thread;	/* thread holding lock */
1030Sstevel@tonic-gate 	struct sqlite	*be_db;
1040Sstevel@tonic-gate 	const char	*be_path;	/* path to db */
105*11996SThomas.Whitten@Sun.COM 	const char	*be_ppath;	/* saved path to persistent db when */
106*11996SThomas.Whitten@Sun.COM 					/* backend is volatile */
107*11996SThomas.Whitten@Sun.COM 	const char	*be_checkpoint;	/* path to repository checkpoint */
108407Sjwadams 	int		be_readonly;	/* readonly at start, and still is */
1090Sstevel@tonic-gate 	int		be_writing;	/* held for writing */
1100Sstevel@tonic-gate 	backend_type_t	be_type;	/* type of db */
111407Sjwadams 	hrtime_t	be_lastcheck;	/* time of last read-only check */
1120Sstevel@tonic-gate 	backend_totals_t be_totals[2];	/* one for reading, one for writing */
1130Sstevel@tonic-gate } sqlite_backend_t;
1140Sstevel@tonic-gate 
1150Sstevel@tonic-gate struct backend_tx {
1160Sstevel@tonic-gate 	sqlite_backend_t	*bt_be;
1170Sstevel@tonic-gate 	int			bt_readonly;
1180Sstevel@tonic-gate 	int			bt_type;
1190Sstevel@tonic-gate 	int			bt_full;	/* SQLITE_FULL during tx */
1200Sstevel@tonic-gate };
1210Sstevel@tonic-gate 
1220Sstevel@tonic-gate #define	UPDATE_TOTALS_WR(sb, writing, field, ts, vts) { \
1230Sstevel@tonic-gate 	backend_spent_t *__bsp = &(sb)->be_totals[!!(writing)].field; \
1240Sstevel@tonic-gate 	__bsp->bs_count++;						\
1250Sstevel@tonic-gate 	__bsp->bs_time += (gethrtime() - ts);				\
1260Sstevel@tonic-gate 	__bsp->bs_vtime += (gethrvtime() - vts);			\
1270Sstevel@tonic-gate }
1280Sstevel@tonic-gate 
1290Sstevel@tonic-gate #define	UPDATE_TOTALS(sb, field, ts, vts) \
1300Sstevel@tonic-gate 	UPDATE_TOTALS_WR(sb, (sb)->be_writing, field, ts, vts)
1310Sstevel@tonic-gate 
1320Sstevel@tonic-gate struct backend_query {
1330Sstevel@tonic-gate 	char	*bq_buf;
1340Sstevel@tonic-gate 	size_t	bq_size;
1350Sstevel@tonic-gate };
1360Sstevel@tonic-gate 
1370Sstevel@tonic-gate struct backend_tbl_info {
1380Sstevel@tonic-gate 	const char *bti_name;
1390Sstevel@tonic-gate 	const char *bti_cols;
1400Sstevel@tonic-gate };
1410Sstevel@tonic-gate 
1420Sstevel@tonic-gate struct backend_idx_info {
1430Sstevel@tonic-gate 	const char *bxi_tbl;
1440Sstevel@tonic-gate 	const char *bxi_idx;
1450Sstevel@tonic-gate 	const char *bxi_cols;
1460Sstevel@tonic-gate };
1470Sstevel@tonic-gate 
148*11996SThomas.Whitten@Sun.COM /* Definitions for the flight recorder: */
149*11996SThomas.Whitten@Sun.COM 
150*11996SThomas.Whitten@Sun.COM typedef enum be_flight_type {
151*11996SThomas.Whitten@Sun.COM 	BE_FLIGHT_EV_NOEVENT = 0,	/* No event yet recorded. */
152*11996SThomas.Whitten@Sun.COM 	BE_FLIGHT_EV_BACKUP,		/* Information about repo. backup */
153*11996SThomas.Whitten@Sun.COM 	BE_FLIGHT_EV_BACKUP_ENTER,	/* Enter */
154*11996SThomas.Whitten@Sun.COM 					/* backend_create_backup_locked() */
155*11996SThomas.Whitten@Sun.COM 	BE_FLIGHT_EV_CHECKPOINT,	/* Request to checkpoint repository */
156*11996SThomas.Whitten@Sun.COM 					/* for boot time backup */
157*11996SThomas.Whitten@Sun.COM 	BE_FLIGHT_EV_CHECKPOINT_EXISTS,	/* Existing checkpoint detected on */
158*11996SThomas.Whitten@Sun.COM 					/* restart */
159*11996SThomas.Whitten@Sun.COM 	BE_FLIGHT_EV_LINGERING_FAST,	/* Use lingering fast repository */
160*11996SThomas.Whitten@Sun.COM 	BE_FLIGHT_EV_NO_BACKUP,		/* Requested backup not made */
161*11996SThomas.Whitten@Sun.COM 	BE_FLIGHT_EV_REPO_CREATE,	/* Main repository created */
162*11996SThomas.Whitten@Sun.COM 	BE_FLIGHT_EV_RESTART,		/* This is a restart of configd */
163*11996SThomas.Whitten@Sun.COM 	BE_FLIGHT_EV_SWITCH,		/* Switch repositories */
164*11996SThomas.Whitten@Sun.COM 	BE_FLIGHT_EV_TRANS_RW		/* Root transitioned to read/write */
165*11996SThomas.Whitten@Sun.COM } be_flight_type_t;
166*11996SThomas.Whitten@Sun.COM 
167*11996SThomas.Whitten@Sun.COM typedef enum be_flight_status {
168*11996SThomas.Whitten@Sun.COM 	BE_FLIGHT_ST_INFO = 0,		/* No status.  Event is informative */
169*11996SThomas.Whitten@Sun.COM 	BE_FLIGHT_ST_BOOT_BACKUP,	/* Boot time backup */
170*11996SThomas.Whitten@Sun.COM 	BE_FLIGHT_ST_CHECKPOINT_BACKUP,	/* Backup from checkpoint */
171*11996SThomas.Whitten@Sun.COM 	BE_FLIGHT_ST_CLIENT,		/* Request form client as opposed to */
172*11996SThomas.Whitten@Sun.COM 					/* internal call */
173*11996SThomas.Whitten@Sun.COM 	BE_FLIGHT_ST_DUPLICATE,		/* Backup duplicates existing one */
174*11996SThomas.Whitten@Sun.COM 	BE_FLIGHT_ST_FAIL,		/* Operation failed. */
175*11996SThomas.Whitten@Sun.COM 	BE_FLIGHT_ST_FAST,		/* Fast repository (tmpfs) */
176*11996SThomas.Whitten@Sun.COM 	BE_FLIGHT_ST_MI_BACKUP,		/* Manifest-import backup */
177*11996SThomas.Whitten@Sun.COM 	BE_FLIGHT_ST_NO_SWITCH,		/* Don't switch repositories */
178*11996SThomas.Whitten@Sun.COM 	BE_FLIGHT_ST_OTHER_BACKUP,	/* Other type of backup */
179*11996SThomas.Whitten@Sun.COM 	BE_FLIGHT_ST_PERMANENT,		/* Repository on permanet storage */
180*11996SThomas.Whitten@Sun.COM 	BE_FLIGHT_ST_REPO_BACKUP,	/* Backup from repository */
181*11996SThomas.Whitten@Sun.COM 	BE_FLIGHT_ST_RO,		/* Main repository is read-only */
182*11996SThomas.Whitten@Sun.COM 	BE_FLIGHT_ST_RW,		/* Main repository is read/write */
183*11996SThomas.Whitten@Sun.COM 	BE_FLIGHT_ST_SUCCESS,		/* Operation was successful */
184*11996SThomas.Whitten@Sun.COM 	BE_FLIGHT_ST_SWITCH		/* Switch repository */
185*11996SThomas.Whitten@Sun.COM } be_flight_status_t;
186*11996SThomas.Whitten@Sun.COM 
187*11996SThomas.Whitten@Sun.COM typedef struct be_flight_event {
188*11996SThomas.Whitten@Sun.COM 	be_flight_type_t	bfe_type;	/* Type of event. */
189*11996SThomas.Whitten@Sun.COM 	be_flight_status_t	bfe_status;	/* Result of the event. */
190*11996SThomas.Whitten@Sun.COM 	time_t			bfe_time;	/* Time of the event. */
191*11996SThomas.Whitten@Sun.COM 	uint_t			bfe_sequence;	/* Sequence number. */
192*11996SThomas.Whitten@Sun.COM } be_flight_event_t;
193*11996SThomas.Whitten@Sun.COM 
1940Sstevel@tonic-gate static pthread_mutex_t backend_panic_lock = PTHREAD_MUTEX_INITIALIZER;
1950Sstevel@tonic-gate static pthread_cond_t backend_panic_cv = PTHREAD_COND_INITIALIZER;
1960Sstevel@tonic-gate pthread_t backend_panic_thread = 0;
1970Sstevel@tonic-gate 
1980Sstevel@tonic-gate int backend_do_trace = 0;		/* invoke tracing callback */
1990Sstevel@tonic-gate int backend_print_trace = 0;		/* tracing callback prints SQL */
2000Sstevel@tonic-gate int backend_panic_abort = 0;		/* abort when panicking */
2010Sstevel@tonic-gate 
202*11996SThomas.Whitten@Sun.COM /* Data for the flight_recorder. */
203*11996SThomas.Whitten@Sun.COM 
204*11996SThomas.Whitten@Sun.COM static pthread_mutex_t backend_flight_recorder_lock = PTHREAD_MUTEX_INITIALIZER;
205*11996SThomas.Whitten@Sun.COM static be_flight_event_t flight_recorder[MAX_FLIGHT_RECORDER_EVENTS];
206*11996SThomas.Whitten@Sun.COM static uint_t flight_recorder_next = 0;
207*11996SThomas.Whitten@Sun.COM static uint_t flight_recorder_missed = 0;
208*11996SThomas.Whitten@Sun.COM static uint_t flight_recorder_sequence = 0;
209*11996SThomas.Whitten@Sun.COM 
210407Sjwadams /* interval between read-only checks while starting up */
211407Sjwadams #define	BACKEND_READONLY_CHECK_INTERVAL	(2 * (hrtime_t)NANOSEC)
212407Sjwadams 
2130Sstevel@tonic-gate /*
2147128Samaguire  * Any incompatible change to the below schema should bump the version number.
2157128Samaguire  * The schema has been changed to support value ordering,  but this change
2167128Samaguire  * is backwards-compatible - i.e. a previous svc.configd can use a
2177128Samaguire  * repository database with the new schema perfectly well.  As a result,
2187128Samaguire  * the schema version has not been updated,  allowing downgrade of systems
2197128Samaguire  * without losing repository data.
2200Sstevel@tonic-gate  */
2210Sstevel@tonic-gate #define	BACKEND_SCHEMA_VERSION		5
2220Sstevel@tonic-gate 
2230Sstevel@tonic-gate static struct backend_tbl_info tbls_normal[] = { /* BACKEND_TYPE_NORMAL */
2240Sstevel@tonic-gate 	/*
2250Sstevel@tonic-gate 	 * service_tbl holds all services.  svc_id is the identifier of the
2260Sstevel@tonic-gate 	 * service.
2270Sstevel@tonic-gate 	 */
2280Sstevel@tonic-gate 	{
2290Sstevel@tonic-gate 		"service_tbl",
2300Sstevel@tonic-gate 		"svc_id          INTEGER PRIMARY KEY,"
2310Sstevel@tonic-gate 		"svc_name        CHAR(256) NOT NULL"
2320Sstevel@tonic-gate 	},
2330Sstevel@tonic-gate 
2340Sstevel@tonic-gate 	/*
2350Sstevel@tonic-gate 	 * instance_tbl holds all of the instances.  The parent service id
2360Sstevel@tonic-gate 	 * is instance_svc.
2370Sstevel@tonic-gate 	 */
2380Sstevel@tonic-gate 	{
2390Sstevel@tonic-gate 		"instance_tbl",
2400Sstevel@tonic-gate 		"instance_id     INTEGER PRIMARY KEY,"
2410Sstevel@tonic-gate 		"instance_name   CHAR(256) NOT NULL,"
2420Sstevel@tonic-gate 		"instance_svc    INTEGER NOT NULL"
2430Sstevel@tonic-gate 	},
2440Sstevel@tonic-gate 
2450Sstevel@tonic-gate 	/*
2460Sstevel@tonic-gate 	 * snapshot_lnk_tbl links (instance, snapshot name) with snapshots.
2470Sstevel@tonic-gate 	 */
2480Sstevel@tonic-gate 	{
2490Sstevel@tonic-gate 		"snapshot_lnk_tbl",
2500Sstevel@tonic-gate 		"lnk_id          INTEGER PRIMARY KEY,"
2510Sstevel@tonic-gate 		"lnk_inst_id     INTEGER NOT NULL,"
2520Sstevel@tonic-gate 		"lnk_snap_name   CHAR(256) NOT NULL,"
2530Sstevel@tonic-gate 		"lnk_snap_id     INTEGER NOT NULL"
2540Sstevel@tonic-gate 	},
2550Sstevel@tonic-gate 
2560Sstevel@tonic-gate 	/*
2570Sstevel@tonic-gate 	 * snaplevel_tbl maps a snapshot id to a set of named, ordered
2580Sstevel@tonic-gate 	 * snaplevels.
2590Sstevel@tonic-gate 	 */
2600Sstevel@tonic-gate 	{
2610Sstevel@tonic-gate 		"snaplevel_tbl",
2620Sstevel@tonic-gate 		"snap_id                 INTEGER NOT NULL,"
2630Sstevel@tonic-gate 		"snap_level_num          INTEGER NOT NULL,"
2640Sstevel@tonic-gate 		"snap_level_id           INTEGER NOT NULL,"
2650Sstevel@tonic-gate 		"snap_level_service_id   INTEGER NOT NULL,"
2660Sstevel@tonic-gate 		"snap_level_service      CHAR(256) NOT NULL,"
2670Sstevel@tonic-gate 		"snap_level_instance_id  INTEGER NULL,"
2680Sstevel@tonic-gate 		"snap_level_instance     CHAR(256) NULL"
2690Sstevel@tonic-gate 	},
2700Sstevel@tonic-gate 
2710Sstevel@tonic-gate 	/*
2720Sstevel@tonic-gate 	 * snaplevel_lnk_tbl links snaplevels to property groups.
2730Sstevel@tonic-gate 	 * snaplvl_pg_* is identical to the original property group,
2740Sstevel@tonic-gate 	 * and snaplvl_gen_id overrides the generation number.
2750Sstevel@tonic-gate 	 * The service/instance ids are as in the snaplevel.
2760Sstevel@tonic-gate 	 */
2770Sstevel@tonic-gate 	{
2780Sstevel@tonic-gate 		"snaplevel_lnk_tbl",
2790Sstevel@tonic-gate 		"snaplvl_level_id INTEGER NOT NULL,"
2800Sstevel@tonic-gate 		"snaplvl_pg_id    INTEGER NOT NULL,"
2810Sstevel@tonic-gate 		"snaplvl_pg_name  CHAR(256) NOT NULL,"
2820Sstevel@tonic-gate 		"snaplvl_pg_type  CHAR(256) NOT NULL,"
2830Sstevel@tonic-gate 		"snaplvl_pg_flags INTEGER NOT NULL,"
2840Sstevel@tonic-gate 		"snaplvl_gen_id   INTEGER NOT NULL"
2850Sstevel@tonic-gate 	},
2860Sstevel@tonic-gate 
2870Sstevel@tonic-gate 	{ NULL, NULL }
2880Sstevel@tonic-gate };
2890Sstevel@tonic-gate 
2900Sstevel@tonic-gate static struct backend_idx_info idxs_normal[] = { /* BACKEND_TYPE_NORMAL */
2910Sstevel@tonic-gate 	{ "service_tbl",	"name",	"svc_name" },
2920Sstevel@tonic-gate 	{ "instance_tbl",	"name",	"instance_svc, instance_name" },
2930Sstevel@tonic-gate 	{ "snapshot_lnk_tbl",	"name",	"lnk_inst_id, lnk_snap_name" },
2940Sstevel@tonic-gate 	{ "snapshot_lnk_tbl",	"snapid", "lnk_snap_id" },
2950Sstevel@tonic-gate 	{ "snaplevel_tbl",	"id",	"snap_id" },
2960Sstevel@tonic-gate 	{ "snaplevel_lnk_tbl",	"id",	"snaplvl_pg_id" },
2970Sstevel@tonic-gate 	{ "snaplevel_lnk_tbl",	"level", "snaplvl_level_id" },
2980Sstevel@tonic-gate 	{ NULL, NULL, NULL }
2990Sstevel@tonic-gate };
3000Sstevel@tonic-gate 
3010Sstevel@tonic-gate static struct backend_tbl_info tbls_np[] = { /* BACKEND_TYPE_NONPERSIST */
3020Sstevel@tonic-gate 	{ NULL, NULL }
3030Sstevel@tonic-gate };
3040Sstevel@tonic-gate 
3050Sstevel@tonic-gate static struct backend_idx_info idxs_np[] = {	/* BACKEND_TYPE_NONPERSIST */
3060Sstevel@tonic-gate 	{ NULL, NULL, NULL }
3070Sstevel@tonic-gate };
3080Sstevel@tonic-gate 
3090Sstevel@tonic-gate static struct backend_tbl_info tbls_common[] = { /* all backend types */
3100Sstevel@tonic-gate 	/*
3110Sstevel@tonic-gate 	 * pg_tbl defines property groups.  They are associated with a single
3120Sstevel@tonic-gate 	 * service or instance.  The pg_gen_id links them with the latest
3130Sstevel@tonic-gate 	 * "edited" version of its properties.
3140Sstevel@tonic-gate 	 */
3150Sstevel@tonic-gate 	{
3160Sstevel@tonic-gate 		"pg_tbl",
3170Sstevel@tonic-gate 		"pg_id           INTEGER PRIMARY KEY,"
3180Sstevel@tonic-gate 		"pg_parent_id    INTEGER NOT NULL,"
3190Sstevel@tonic-gate 		"pg_name         CHAR(256) NOT NULL,"
3200Sstevel@tonic-gate 		"pg_type         CHAR(256) NOT NULL,"
3210Sstevel@tonic-gate 		"pg_flags        INTEGER NOT NULL,"
3220Sstevel@tonic-gate 		"pg_gen_id       INTEGER NOT NULL"
3230Sstevel@tonic-gate 	},
3240Sstevel@tonic-gate 
3250Sstevel@tonic-gate 	/*
3260Sstevel@tonic-gate 	 * prop_lnk_tbl links a particular pg_id and gen_id to a set of
3270Sstevel@tonic-gate 	 * (prop_name, prop_type, val_id) trios.
3280Sstevel@tonic-gate 	 */
3290Sstevel@tonic-gate 	{
3300Sstevel@tonic-gate 		"prop_lnk_tbl",
3310Sstevel@tonic-gate 		"lnk_prop_id     INTEGER PRIMARY KEY,"
3320Sstevel@tonic-gate 		"lnk_pg_id       INTEGER NOT NULL,"
3330Sstevel@tonic-gate 		"lnk_gen_id      INTEGER NOT NULL,"
3340Sstevel@tonic-gate 		"lnk_prop_name   CHAR(256) NOT NULL,"
3350Sstevel@tonic-gate 		"lnk_prop_type   CHAR(2) NOT NULL,"
3360Sstevel@tonic-gate 		"lnk_val_id      INTEGER"
3370Sstevel@tonic-gate 	},
3380Sstevel@tonic-gate 
3390Sstevel@tonic-gate 	/*
3400Sstevel@tonic-gate 	 * value_tbl maps a value_id to a set of values.  For any given
3417128Samaguire 	 * value_id, value_type is constant.  The table definition here
3427128Samaguire 	 * is repeated in backend_check_upgrade(),  and must be kept in-sync.
3430Sstevel@tonic-gate 	 */
3440Sstevel@tonic-gate 	{
3450Sstevel@tonic-gate 		"value_tbl",
3460Sstevel@tonic-gate 		"value_id        INTEGER NOT NULL,"
3470Sstevel@tonic-gate 		"value_type      CHAR(1) NOT NULL,"
3487128Samaguire 		"value_value     VARCHAR NOT NULL,"
3497128Samaguire 		"value_order     INTEGER DEFAULT 0"
3500Sstevel@tonic-gate 	},
3510Sstevel@tonic-gate 
3520Sstevel@tonic-gate 	/*
3530Sstevel@tonic-gate 	 * id_tbl has one row per id space
3540Sstevel@tonic-gate 	 */
3550Sstevel@tonic-gate 	{
3560Sstevel@tonic-gate 		"id_tbl",
3570Sstevel@tonic-gate 		"id_name         STRING NOT NULL,"
3580Sstevel@tonic-gate 		"id_next         INTEGER NOT NULL"
3590Sstevel@tonic-gate 	},
3600Sstevel@tonic-gate 
3610Sstevel@tonic-gate 	/*
3620Sstevel@tonic-gate 	 * schema_version has a single row, which contains
3630Sstevel@tonic-gate 	 * BACKEND_SCHEMA_VERSION at the time of creation.
3640Sstevel@tonic-gate 	 */
3650Sstevel@tonic-gate 	{
3660Sstevel@tonic-gate 		"schema_version",
3670Sstevel@tonic-gate 		"schema_version  INTEGER"
3680Sstevel@tonic-gate 	},
3690Sstevel@tonic-gate 	{ NULL, NULL }
3700Sstevel@tonic-gate };
3710Sstevel@tonic-gate 
3727128Samaguire /*
3737128Samaguire  * The indexing of value_tbl is repeated in backend_check_upgrade() and
3747128Samaguire  * must be kept in sync with the indexing specification here.
3757128Samaguire  */
3760Sstevel@tonic-gate static struct backend_idx_info idxs_common[] = { /* all backend types */
3770Sstevel@tonic-gate 	{ "pg_tbl",		"parent", "pg_parent_id" },
3780Sstevel@tonic-gate 	{ "pg_tbl",		"name",	"pg_parent_id, pg_name" },
3790Sstevel@tonic-gate 	{ "pg_tbl",		"type",	"pg_parent_id, pg_type" },
3800Sstevel@tonic-gate 	{ "prop_lnk_tbl",	"base",	"lnk_pg_id, lnk_gen_id" },
3810Sstevel@tonic-gate 	{ "prop_lnk_tbl",	"val",	"lnk_val_id" },
3820Sstevel@tonic-gate 	{ "value_tbl",		"id",	"value_id" },
3830Sstevel@tonic-gate 	{ "id_tbl",		"id",	"id_name" },
3840Sstevel@tonic-gate 	{ NULL, NULL, NULL }
3850Sstevel@tonic-gate };
3860Sstevel@tonic-gate 
3870Sstevel@tonic-gate struct run_single_int_info {
3880Sstevel@tonic-gate 	uint32_t	*rs_out;
3890Sstevel@tonic-gate 	int		rs_result;
3900Sstevel@tonic-gate };
3910Sstevel@tonic-gate 
392*11996SThomas.Whitten@Sun.COM static rep_protocol_responseid_t backend_copy_repository(const char *,
393*11996SThomas.Whitten@Sun.COM     const char *, int);
394*11996SThomas.Whitten@Sun.COM static rep_protocol_responseid_t backend_do_copy(const char *, int,
395*11996SThomas.Whitten@Sun.COM     const char *, int, size_t *);
396*11996SThomas.Whitten@Sun.COM 
397*11996SThomas.Whitten@Sun.COM /*
398*11996SThomas.Whitten@Sun.COM  * The flight recorder keeps track of events that happen primarily while
399*11996SThomas.Whitten@Sun.COM  * the system is booting.  Once the system is up an running, one can take a
400*11996SThomas.Whitten@Sun.COM  * gcore(1) of configd and examine the events with mdb.  Since we're most
401*11996SThomas.Whitten@Sun.COM  * interested in early boot events, we stop recording events when the
402*11996SThomas.Whitten@Sun.COM  * recorder is full.
403*11996SThomas.Whitten@Sun.COM  */
404*11996SThomas.Whitten@Sun.COM static void
flight_recorder_event(be_flight_type_t type,be_flight_status_t res)405*11996SThomas.Whitten@Sun.COM flight_recorder_event(be_flight_type_t type, be_flight_status_t res)
406*11996SThomas.Whitten@Sun.COM {
407*11996SThomas.Whitten@Sun.COM 	be_flight_event_t *data;
408*11996SThomas.Whitten@Sun.COM 	uint_t item;
409*11996SThomas.Whitten@Sun.COM 	uint_t sequence;
410*11996SThomas.Whitten@Sun.COM 
411*11996SThomas.Whitten@Sun.COM 	if (pthread_mutex_lock(&backend_flight_recorder_lock) != 0) {
412*11996SThomas.Whitten@Sun.COM 		atomic_inc_uint(&flight_recorder_missed);
413*11996SThomas.Whitten@Sun.COM 		return;
414*11996SThomas.Whitten@Sun.COM 	}
415*11996SThomas.Whitten@Sun.COM 	if (flight_recorder_next >= MAX_FLIGHT_RECORDER_EVENTS) {
416*11996SThomas.Whitten@Sun.COM 		/* Hit end of the array.  No more event recording. */
417*11996SThomas.Whitten@Sun.COM 		item = flight_recorder_next;
418*11996SThomas.Whitten@Sun.COM 	} else {
419*11996SThomas.Whitten@Sun.COM 		item = flight_recorder_next++;
420*11996SThomas.Whitten@Sun.COM 		sequence = flight_recorder_sequence++;
421*11996SThomas.Whitten@Sun.COM 	}
422*11996SThomas.Whitten@Sun.COM 	(void) pthread_mutex_unlock(&backend_flight_recorder_lock);
423*11996SThomas.Whitten@Sun.COM 
424*11996SThomas.Whitten@Sun.COM 	if (item >= MAX_FLIGHT_RECORDER_EVENTS) {
425*11996SThomas.Whitten@Sun.COM 		/* Array is filled.  Stop recording events */
426*11996SThomas.Whitten@Sun.COM 		atomic_inc_uint(&flight_recorder_missed);
427*11996SThomas.Whitten@Sun.COM 		return;
428*11996SThomas.Whitten@Sun.COM 	}
429*11996SThomas.Whitten@Sun.COM 	data = &flight_recorder[item];
430*11996SThomas.Whitten@Sun.COM 	(void) memset(data, 0, sizeof (*data));
431*11996SThomas.Whitten@Sun.COM 	data->bfe_type = type;
432*11996SThomas.Whitten@Sun.COM 	data->bfe_status = res;
433*11996SThomas.Whitten@Sun.COM 	data->bfe_sequence = sequence;
434*11996SThomas.Whitten@Sun.COM 	data->bfe_time = time(NULL);
435*11996SThomas.Whitten@Sun.COM }
436*11996SThomas.Whitten@Sun.COM 
4370Sstevel@tonic-gate /*ARGSUSED*/
4380Sstevel@tonic-gate static int
run_single_int_callback(void * arg,int columns,char ** vals,char ** names)4390Sstevel@tonic-gate run_single_int_callback(void *arg, int columns, char **vals, char **names)
4400Sstevel@tonic-gate {
4410Sstevel@tonic-gate 	struct run_single_int_info *info = arg;
4420Sstevel@tonic-gate 	uint32_t val;
4430Sstevel@tonic-gate 
4440Sstevel@tonic-gate 	char *endptr = vals[0];
4450Sstevel@tonic-gate 
4460Sstevel@tonic-gate 	assert(info->rs_result != REP_PROTOCOL_SUCCESS);
4470Sstevel@tonic-gate 	assert(columns == 1);
4480Sstevel@tonic-gate 
4490Sstevel@tonic-gate 	if (vals[0] == NULL)
4500Sstevel@tonic-gate 		return (BACKEND_CALLBACK_CONTINUE);
4510Sstevel@tonic-gate 
4520Sstevel@tonic-gate 	errno = 0;
4530Sstevel@tonic-gate 	val = strtoul(vals[0], &endptr, 10);
4540Sstevel@tonic-gate 	if ((val == 0 && endptr == vals[0]) || *endptr != 0 || errno != 0)
4550Sstevel@tonic-gate 		backend_panic("malformed integer \"%20s\"", vals[0]);
4560Sstevel@tonic-gate 
4570Sstevel@tonic-gate 	*info->rs_out = val;
4580Sstevel@tonic-gate 	info->rs_result = REP_PROTOCOL_SUCCESS;
4590Sstevel@tonic-gate 	return (BACKEND_CALLBACK_CONTINUE);
4600Sstevel@tonic-gate }
4610Sstevel@tonic-gate 
4620Sstevel@tonic-gate /*ARGSUSED*/
4630Sstevel@tonic-gate int
backend_fail_if_seen(void * arg,int columns,char ** vals,char ** names)4640Sstevel@tonic-gate backend_fail_if_seen(void *arg, int columns, char **vals, char **names)
4650Sstevel@tonic-gate {
4660Sstevel@tonic-gate 	return (BACKEND_CALLBACK_ABORT);
4670Sstevel@tonic-gate }
4680Sstevel@tonic-gate 
469407Sjwadams /*
470407Sjwadams  * check to see if we can successfully start a transaction;  if not, the
471407Sjwadams  * filesystem is mounted read-only.
472407Sjwadams  */
4730Sstevel@tonic-gate static int
backend_is_readonly(struct sqlite * db,const char * path)474407Sjwadams backend_is_readonly(struct sqlite *db, const char *path)
4750Sstevel@tonic-gate {
476407Sjwadams 	int r;
477407Sjwadams 	statvfs64_t stat;
478407Sjwadams 
479407Sjwadams 	if (statvfs64(path, &stat) == 0 && (stat.f_flag & ST_RDONLY))
480407Sjwadams 		return (SQLITE_READONLY);
481407Sjwadams 
482407Sjwadams 	r = sqlite_exec(db,
4830Sstevel@tonic-gate 	    "BEGIN TRANSACTION; "
4840Sstevel@tonic-gate 	    "UPDATE schema_version SET schema_version = schema_version; ",
485407Sjwadams 	    NULL, NULL, NULL);
4860Sstevel@tonic-gate 	(void) sqlite_exec(db, "ROLLBACK TRANSACTION", NULL, NULL, NULL);
4870Sstevel@tonic-gate 	return (r);
4880Sstevel@tonic-gate }
4890Sstevel@tonic-gate 
4900Sstevel@tonic-gate static void
backend_trace_sql(void * arg,const char * sql)4910Sstevel@tonic-gate backend_trace_sql(void *arg, const char *sql)
4920Sstevel@tonic-gate {
4930Sstevel@tonic-gate 	sqlite_backend_t *be = arg;
4940Sstevel@tonic-gate 
4950Sstevel@tonic-gate 	if (backend_print_trace) {
4960Sstevel@tonic-gate 		(void) fprintf(stderr, "%d: %s\n", be->be_type, sql);
4970Sstevel@tonic-gate 	}
4980Sstevel@tonic-gate }
4990Sstevel@tonic-gate 
5000Sstevel@tonic-gate static sqlite_backend_t be_info[BACKEND_TYPE_TOTAL];
5010Sstevel@tonic-gate static sqlite_backend_t *bes[BACKEND_TYPE_TOTAL];
5020Sstevel@tonic-gate 
5037128Samaguire /*
5047128Samaguire  * For a native build,  repositories are created from scratch, so upgrade
5057128Samaguire  * is not an issue.  This variable is implicitly protected by
5067128Samaguire  * bes[BACKEND_TYPE_NORMAL]->be_lock.
5077128Samaguire  */
5087128Samaguire #ifdef NATIVE_BUILD
5097128Samaguire static boolean_t be_normal_upgraded = B_TRUE;
5107128Samaguire #else
5117128Samaguire static boolean_t be_normal_upgraded = B_FALSE;
5127128Samaguire #endif	/* NATIVE_BUILD */
5137128Samaguire 
5147128Samaguire /*
5157128Samaguire  * Has backend been upgraded? In nonpersistent case, answer is always
5167128Samaguire  * yes.
5177128Samaguire  */
5187128Samaguire boolean_t
backend_is_upgraded(backend_tx_t * bt)5197128Samaguire backend_is_upgraded(backend_tx_t *bt)
5207128Samaguire {
5217128Samaguire 	if (bt->bt_type == BACKEND_TYPE_NONPERSIST)
5227128Samaguire 		return (B_TRUE);
5237128Samaguire 	return (be_normal_upgraded);
5247128Samaguire }
5257128Samaguire 
5260Sstevel@tonic-gate #define	BACKEND_PANIC_TIMEOUT	(50 * MILLISEC)
5270Sstevel@tonic-gate /*
5280Sstevel@tonic-gate  * backend_panic() -- some kind of database problem or corruption has been hit.
5290Sstevel@tonic-gate  * We attempt to quiesce the other database users -- all of the backend sql
5300Sstevel@tonic-gate  * entry points will call backend_panic(NULL) if a panic is in progress, as
5310Sstevel@tonic-gate  * will any attempt to start a transaction.
5320Sstevel@tonic-gate  *
5330Sstevel@tonic-gate  * We give threads holding a backend lock 50ms (BACKEND_PANIC_TIMEOUT) to
5340Sstevel@tonic-gate  * either drop the lock or call backend_panic().  If they don't respond in
5350Sstevel@tonic-gate  * time, we'll just exit anyway.
5360Sstevel@tonic-gate  */
5370Sstevel@tonic-gate void
backend_panic(const char * format,...)5380Sstevel@tonic-gate backend_panic(const char *format, ...)
5390Sstevel@tonic-gate {
5400Sstevel@tonic-gate 	int i;
5410Sstevel@tonic-gate 	va_list args;
5420Sstevel@tonic-gate 	int failed = 0;
5430Sstevel@tonic-gate 
5440Sstevel@tonic-gate 	(void) pthread_mutex_lock(&backend_panic_lock);
5450Sstevel@tonic-gate 	if (backend_panic_thread != 0) {
5460Sstevel@tonic-gate 		(void) pthread_mutex_unlock(&backend_panic_lock);
5470Sstevel@tonic-gate 		/*
5480Sstevel@tonic-gate 		 * first, drop any backend locks we're holding, then
5490Sstevel@tonic-gate 		 * sleep forever on the panic_cv.
5500Sstevel@tonic-gate 		 */
5510Sstevel@tonic-gate 		for (i = 0; i < BACKEND_TYPE_TOTAL; i++) {
5520Sstevel@tonic-gate 			if (bes[i] != NULL &&
5530Sstevel@tonic-gate 			    bes[i]->be_thread == pthread_self())
5540Sstevel@tonic-gate 				(void) pthread_mutex_unlock(&bes[i]->be_lock);
5550Sstevel@tonic-gate 		}
5560Sstevel@tonic-gate 		(void) pthread_mutex_lock(&backend_panic_lock);
5570Sstevel@tonic-gate 		for (;;)
5580Sstevel@tonic-gate 			(void) pthread_cond_wait(&backend_panic_cv,
5590Sstevel@tonic-gate 			    &backend_panic_lock);
5600Sstevel@tonic-gate 	}
5610Sstevel@tonic-gate 	backend_panic_thread = pthread_self();
5620Sstevel@tonic-gate 	(void) pthread_mutex_unlock(&backend_panic_lock);
5630Sstevel@tonic-gate 
5640Sstevel@tonic-gate 	for (i = 0; i < BACKEND_TYPE_TOTAL; i++) {
5650Sstevel@tonic-gate 		if (bes[i] != NULL && bes[i]->be_thread == pthread_self())
5660Sstevel@tonic-gate 			(void) pthread_mutex_unlock(&bes[i]->be_lock);
5670Sstevel@tonic-gate 	}
5680Sstevel@tonic-gate 
5690Sstevel@tonic-gate 	va_start(args, format);
5700Sstevel@tonic-gate 	configd_vcritical(format, args);
5710Sstevel@tonic-gate 	va_end(args);
5720Sstevel@tonic-gate 
5730Sstevel@tonic-gate 	for (i = 0; i < BACKEND_TYPE_TOTAL; i++) {
5740Sstevel@tonic-gate 		timespec_t rel;
5750Sstevel@tonic-gate 
5760Sstevel@tonic-gate 		rel.tv_sec = 0;
5770Sstevel@tonic-gate 		rel.tv_nsec = BACKEND_PANIC_TIMEOUT;
5780Sstevel@tonic-gate 
5790Sstevel@tonic-gate 		if (bes[i] != NULL && bes[i]->be_thread != pthread_self()) {
5800Sstevel@tonic-gate 			if (pthread_mutex_reltimedlock_np(&bes[i]->be_lock,
5810Sstevel@tonic-gate 			    &rel) != 0)
5820Sstevel@tonic-gate 				failed++;
5830Sstevel@tonic-gate 		}
5840Sstevel@tonic-gate 	}
5850Sstevel@tonic-gate 	if (failed) {
5860Sstevel@tonic-gate 		configd_critical("unable to quiesce database\n");
5870Sstevel@tonic-gate 	}
5880Sstevel@tonic-gate 
5890Sstevel@tonic-gate 	if (backend_panic_abort)
5900Sstevel@tonic-gate 		abort();
5910Sstevel@tonic-gate 
5920Sstevel@tonic-gate 	exit(CONFIGD_EXIT_DATABASE_BAD);
5930Sstevel@tonic-gate }
5940Sstevel@tonic-gate 
5950Sstevel@tonic-gate /*
5960Sstevel@tonic-gate  * Returns
5970Sstevel@tonic-gate  *   _SUCCESS
5980Sstevel@tonic-gate  *   _DONE - callback aborted query
5990Sstevel@tonic-gate  *   _NO_RESOURCES - out of memory (_FULL & _TOOBIG?)
6000Sstevel@tonic-gate  */
6010Sstevel@tonic-gate static int
backend_error(sqlite_backend_t * be,int error,char * errmsg)6020Sstevel@tonic-gate backend_error(sqlite_backend_t *be, int error, char *errmsg)
6030Sstevel@tonic-gate {
6040Sstevel@tonic-gate 	if (error == SQLITE_OK)
6050Sstevel@tonic-gate 		return (REP_PROTOCOL_SUCCESS);
6060Sstevel@tonic-gate 
6070Sstevel@tonic-gate 	switch (error) {
6080Sstevel@tonic-gate 	case SQLITE_ABORT:
6090Sstevel@tonic-gate 		free(errmsg);
6100Sstevel@tonic-gate 		return (REP_PROTOCOL_DONE);
6110Sstevel@tonic-gate 
6120Sstevel@tonic-gate 	case SQLITE_NOMEM:
6130Sstevel@tonic-gate 	case SQLITE_FULL:
6140Sstevel@tonic-gate 	case SQLITE_TOOBIG:
6150Sstevel@tonic-gate 		free(errmsg);
6160Sstevel@tonic-gate 		return (REP_PROTOCOL_FAIL_NO_RESOURCES);
6170Sstevel@tonic-gate 
6180Sstevel@tonic-gate 	default:
6190Sstevel@tonic-gate 		backend_panic("%s: db error: %s", be->be_path, errmsg);
6200Sstevel@tonic-gate 		/*NOTREACHED*/
6210Sstevel@tonic-gate 	}
6220Sstevel@tonic-gate }
6230Sstevel@tonic-gate 
6240Sstevel@tonic-gate static void
backend_backup_cleanup(const char ** out_arg,ssize_t out_sz)6250Sstevel@tonic-gate backend_backup_cleanup(const char **out_arg, ssize_t out_sz)
6260Sstevel@tonic-gate {
6270Sstevel@tonic-gate 	char **out = (char **)out_arg;
6280Sstevel@tonic-gate 
6290Sstevel@tonic-gate 	while (out_sz-- > 0)
6300Sstevel@tonic-gate 		free(*out++);
6310Sstevel@tonic-gate 	free(out_arg);
6320Sstevel@tonic-gate }
6330Sstevel@tonic-gate 
6340Sstevel@tonic-gate /*
6350Sstevel@tonic-gate  * builds a inverse-time-sorted array of backup files.  The path is a
6360Sstevel@tonic-gate  * a single buffer, and the pointers look like:
6370Sstevel@tonic-gate  *
6380Sstevel@tonic-gate  *	/this/is/a/full/path/to/repository-name-YYYYMMDDHHMMSS
6390Sstevel@tonic-gate  *	^pathname		^	       ^(pathname+pathlen)
6400Sstevel@tonic-gate  *				basename
6410Sstevel@tonic-gate  *
6420Sstevel@tonic-gate  * dirname will either be pathname, or ".".
6430Sstevel@tonic-gate  *
6440Sstevel@tonic-gate  * Returns the number of elements in the array, 0 if there are no previous
6450Sstevel@tonic-gate  * backups, or -1 on error.
6460Sstevel@tonic-gate  */
6470Sstevel@tonic-gate static ssize_t
backend_backup_get_prev(char * pathname,size_t pathlen,const char *** out_arg)6480Sstevel@tonic-gate backend_backup_get_prev(char *pathname, size_t pathlen, const char ***out_arg)
6490Sstevel@tonic-gate {
6500Sstevel@tonic-gate 	char b_start, b_end;
6510Sstevel@tonic-gate 	DIR *dir;
6520Sstevel@tonic-gate 	char **out = NULL;
6530Sstevel@tonic-gate 	char *name, *p;
6540Sstevel@tonic-gate 	char *dirname, *basename;
6550Sstevel@tonic-gate 	char *pathend;
6560Sstevel@tonic-gate 	struct dirent *ent;
6570Sstevel@tonic-gate 
6580Sstevel@tonic-gate 	size_t count = 0;
6590Sstevel@tonic-gate 	size_t baselen;
6600Sstevel@tonic-gate 
6610Sstevel@tonic-gate 	/*
6620Sstevel@tonic-gate 	 * year, month, day, hour, min, sec, plus an '_'.
6630Sstevel@tonic-gate 	 */
6640Sstevel@tonic-gate 	const size_t ndigits = 4 + 5*2 + 1;
6650Sstevel@tonic-gate 	const size_t baroffset = 4 + 2*2;
6660Sstevel@tonic-gate 
6670Sstevel@tonic-gate 	size_t idx;
6680Sstevel@tonic-gate 
6690Sstevel@tonic-gate 	pathend = pathname + pathlen;
6700Sstevel@tonic-gate 	b_end = *pathend;
6710Sstevel@tonic-gate 	*pathend = '\0';
6720Sstevel@tonic-gate 
6730Sstevel@tonic-gate 	basename = strrchr(pathname, '/');
6740Sstevel@tonic-gate 
6750Sstevel@tonic-gate 	if (basename != NULL) {
6760Sstevel@tonic-gate 		assert(pathend > pathname && basename < pathend);
6770Sstevel@tonic-gate 		basename++;
6780Sstevel@tonic-gate 		dirname = pathname;
6790Sstevel@tonic-gate 	} else {
6800Sstevel@tonic-gate 		basename = pathname;
6810Sstevel@tonic-gate 		dirname = ".";
6820Sstevel@tonic-gate 	}
6830Sstevel@tonic-gate 
6840Sstevel@tonic-gate 	baselen = strlen(basename);
6850Sstevel@tonic-gate 
6860Sstevel@tonic-gate 	/*
6870Sstevel@tonic-gate 	 * munge the string temporarily for the opendir(), then restore it.
6880Sstevel@tonic-gate 	 */
6890Sstevel@tonic-gate 	b_start = basename[0];
6900Sstevel@tonic-gate 
6910Sstevel@tonic-gate 	basename[0] = '\0';
6920Sstevel@tonic-gate 	dir = opendir(dirname);
6930Sstevel@tonic-gate 	basename[0] = b_start;		/* restore path */
6940Sstevel@tonic-gate 
6950Sstevel@tonic-gate 	if (dir == NULL)
6960Sstevel@tonic-gate 		goto fail;
6970Sstevel@tonic-gate 
6980Sstevel@tonic-gate 
6990Sstevel@tonic-gate 	while ((ent = readdir(dir)) != NULL) {
7000Sstevel@tonic-gate 		/*
7010Sstevel@tonic-gate 		 * Must match:
7020Sstevel@tonic-gate 		 *	basename-YYYYMMDD_HHMMSS
7030Sstevel@tonic-gate 		 * or we ignore it.
7040Sstevel@tonic-gate 		 */
7050Sstevel@tonic-gate 		if (strncmp(ent->d_name, basename, baselen) != 0)
7060Sstevel@tonic-gate 			continue;
7070Sstevel@tonic-gate 
7080Sstevel@tonic-gate 		name = ent->d_name;
7090Sstevel@tonic-gate 		if (name[baselen] != '-')
7100Sstevel@tonic-gate 			continue;
7110Sstevel@tonic-gate 
7120Sstevel@tonic-gate 		p = name + baselen + 1;
7130Sstevel@tonic-gate 
7140Sstevel@tonic-gate 		for (idx = 0; idx < ndigits; idx++) {
7150Sstevel@tonic-gate 			char c = p[idx];
7160Sstevel@tonic-gate 			if (idx == baroffset && c != '_')
7170Sstevel@tonic-gate 				break;
7180Sstevel@tonic-gate 			if (idx != baroffset && (c < '0' || c > '9'))
7190Sstevel@tonic-gate 				break;
7200Sstevel@tonic-gate 		}
7210Sstevel@tonic-gate 		if (idx != ndigits || p[idx] != '\0')
7220Sstevel@tonic-gate 			continue;
7230Sstevel@tonic-gate 
7240Sstevel@tonic-gate 		/*
7250Sstevel@tonic-gate 		 * We have a match.  insertion-sort it into our list.
7260Sstevel@tonic-gate 		 */
7270Sstevel@tonic-gate 		name = strdup(name);
7280Sstevel@tonic-gate 		if (name == NULL)
7290Sstevel@tonic-gate 			goto fail_closedir;
7300Sstevel@tonic-gate 		p = strrchr(name, '-');
7310Sstevel@tonic-gate 
7320Sstevel@tonic-gate 		for (idx = 0; idx < count; idx++) {
7330Sstevel@tonic-gate 			char *tmp = out[idx];
7340Sstevel@tonic-gate 			char *tp = strrchr(tmp, '-');
7350Sstevel@tonic-gate 
7360Sstevel@tonic-gate 			int cmp = strcmp(p, tp);
7370Sstevel@tonic-gate 			if (cmp == 0)
7380Sstevel@tonic-gate 				cmp = strcmp(name, tmp);
7390Sstevel@tonic-gate 
7400Sstevel@tonic-gate 			if (cmp == 0) {
7410Sstevel@tonic-gate 				free(name);
7420Sstevel@tonic-gate 				name = NULL;
7430Sstevel@tonic-gate 				break;
7440Sstevel@tonic-gate 			} else if (cmp > 0) {
7450Sstevel@tonic-gate 				out[idx] = name;
7460Sstevel@tonic-gate 				name = tmp;
7470Sstevel@tonic-gate 				p = tp;
7480Sstevel@tonic-gate 			}
7490Sstevel@tonic-gate 		}
7500Sstevel@tonic-gate 
7510Sstevel@tonic-gate 		if (idx == count) {
7520Sstevel@tonic-gate 			char **new_out = realloc(out,
7530Sstevel@tonic-gate 			    (count + 1) * sizeof (*out));
7540Sstevel@tonic-gate 
7550Sstevel@tonic-gate 			if (new_out == NULL) {
7560Sstevel@tonic-gate 				free(name);
7570Sstevel@tonic-gate 				goto fail_closedir;
7580Sstevel@tonic-gate 			}
7590Sstevel@tonic-gate 
7600Sstevel@tonic-gate 			out = new_out;
7610Sstevel@tonic-gate 			out[count++] = name;
7620Sstevel@tonic-gate 		} else {
7630Sstevel@tonic-gate 			assert(name == NULL);
7640Sstevel@tonic-gate 		}
7650Sstevel@tonic-gate 	}
7660Sstevel@tonic-gate 	(void) closedir(dir);
7670Sstevel@tonic-gate 
7680Sstevel@tonic-gate 	basename[baselen] = b_end;
7690Sstevel@tonic-gate 
7700Sstevel@tonic-gate 	*out_arg = (const char **)out;
7710Sstevel@tonic-gate 	return (count);
7720Sstevel@tonic-gate 
7730Sstevel@tonic-gate fail_closedir:
7740Sstevel@tonic-gate 	(void) closedir(dir);
7750Sstevel@tonic-gate fail:
7760Sstevel@tonic-gate 	basename[0] = b_start;
7770Sstevel@tonic-gate 	*pathend = b_end;
7780Sstevel@tonic-gate 
7790Sstevel@tonic-gate 	backend_backup_cleanup((const char **)out, count);
7800Sstevel@tonic-gate 
7810Sstevel@tonic-gate 	*out_arg = NULL;
7820Sstevel@tonic-gate 	return (-1);
7830Sstevel@tonic-gate }
7840Sstevel@tonic-gate 
7850Sstevel@tonic-gate /*
7860Sstevel@tonic-gate  * Copies the repository path into out, a buffer of out_len bytes,
7870Sstevel@tonic-gate  * removes the ".db" (or whatever) extension, and, if name is non-NULL,
7880Sstevel@tonic-gate  * appends "-name" to it.  If name is non-NULL, it can fail with:
7890Sstevel@tonic-gate  *
7900Sstevel@tonic-gate  *	_TRUNCATED	will not fit in buffer.
7910Sstevel@tonic-gate  *	_BAD_REQUEST	name is not a valid identifier
7920Sstevel@tonic-gate  */
7930Sstevel@tonic-gate static rep_protocol_responseid_t
backend_backup_base(sqlite_backend_t * be,const char * name,char * out,size_t out_len)7940Sstevel@tonic-gate backend_backup_base(sqlite_backend_t *be, const char *name,
7950Sstevel@tonic-gate     char *out, size_t out_len)
7960Sstevel@tonic-gate {
7970Sstevel@tonic-gate 	char *p, *q;
7980Sstevel@tonic-gate 	size_t len;
7990Sstevel@tonic-gate 
8000Sstevel@tonic-gate 	/*
8010Sstevel@tonic-gate 	 * for paths of the form /path/to/foo.db, we truncate at the final
8020Sstevel@tonic-gate 	 * '.'.
8030Sstevel@tonic-gate 	 */
804*11996SThomas.Whitten@Sun.COM 	(void) strlcpy(out, IS_VOLATILE(be) ? be->be_ppath : be->be_path,
805*11996SThomas.Whitten@Sun.COM 	    out_len);
8060Sstevel@tonic-gate 
8070Sstevel@tonic-gate 	p = strrchr(out, '/');
8080Sstevel@tonic-gate 	q = strrchr(out, '.');
8090Sstevel@tonic-gate 
8100Sstevel@tonic-gate 	if (p != NULL && q != NULL && q > p)
8110Sstevel@tonic-gate 		*q = 0;
8120Sstevel@tonic-gate 
8130Sstevel@tonic-gate 	if (name != NULL) {
8140Sstevel@tonic-gate 		len = strlen(out);
8150Sstevel@tonic-gate 		assert(len < out_len);
8160Sstevel@tonic-gate 
8170Sstevel@tonic-gate 		out += len;
8180Sstevel@tonic-gate 		out_len -= len;
8190Sstevel@tonic-gate 
8200Sstevel@tonic-gate 		len = strlen(name);
8210Sstevel@tonic-gate 
8220Sstevel@tonic-gate 		/*
8230Sstevel@tonic-gate 		 * verify that the name tag is entirely alphabetic,
8240Sstevel@tonic-gate 		 * non-empty, and not too long.
8250Sstevel@tonic-gate 		 */
8260Sstevel@tonic-gate 		if (len == 0 || len >= REP_PROTOCOL_NAME_LEN ||
8270Sstevel@tonic-gate 		    uu_check_name(name, UU_NAME_DOMAIN) < 0)
8280Sstevel@tonic-gate 			return (REP_PROTOCOL_FAIL_BAD_REQUEST);
8290Sstevel@tonic-gate 
8300Sstevel@tonic-gate 		if (snprintf(out, out_len, "-%s", name) >= out_len)
8310Sstevel@tonic-gate 			return (REP_PROTOCOL_FAIL_TRUNCATED);
8320Sstevel@tonic-gate 	}
8330Sstevel@tonic-gate 
8340Sstevel@tonic-gate 	return (REP_PROTOCOL_SUCCESS);
8350Sstevel@tonic-gate }
8360Sstevel@tonic-gate 
8370Sstevel@tonic-gate /*
838*11996SThomas.Whitten@Sun.COM  * Make a checkpoint of the repository, so that we can use it for a backup
839*11996SThomas.Whitten@Sun.COM  * when the root file system becomes read/write.  We'll first copy the
840*11996SThomas.Whitten@Sun.COM  * repository into a temporary file and then rename it to
841*11996SThomas.Whitten@Sun.COM  * REPOSITORY_CHECKPOINT.  This is protection against configd crashing in
842*11996SThomas.Whitten@Sun.COM  * the middle of the copy and leaving a partial copy at
843*11996SThomas.Whitten@Sun.COM  * REPOSITORY_CHECKPOINT.  Renames are atomic.
844*11996SThomas.Whitten@Sun.COM  */
845*11996SThomas.Whitten@Sun.COM static rep_protocol_responseid_t
backend_checkpoint_repository(sqlite_backend_t * be)846*11996SThomas.Whitten@Sun.COM backend_checkpoint_repository(sqlite_backend_t *be)
847*11996SThomas.Whitten@Sun.COM {
848*11996SThomas.Whitten@Sun.COM 	rep_protocol_responseid_t r;
849*11996SThomas.Whitten@Sun.COM 
850*11996SThomas.Whitten@Sun.COM 	assert(be->be_readonly);	/* Only need a checkpoint if / is ro */
851*11996SThomas.Whitten@Sun.COM 	assert(be->be_type == BACKEND_TYPE_NORMAL);
852*11996SThomas.Whitten@Sun.COM 	assert(be->be_checkpoint == NULL); /* Only 1 checkpoint */
853*11996SThomas.Whitten@Sun.COM 
854*11996SThomas.Whitten@Sun.COM 	r = backend_copy_repository(be->be_path, REPOSITORY_CHECKPOINT, 0);
855*11996SThomas.Whitten@Sun.COM 	if (r == REP_PROTOCOL_SUCCESS)
856*11996SThomas.Whitten@Sun.COM 		be->be_checkpoint = REPOSITORY_CHECKPOINT;
857*11996SThomas.Whitten@Sun.COM 
858*11996SThomas.Whitten@Sun.COM 	flight_recorder_event(BE_FLIGHT_EV_CHECKPOINT,
859*11996SThomas.Whitten@Sun.COM 	    r == REP_PROTOCOL_SUCCESS ? BE_FLIGHT_ST_SUCCESS :
860*11996SThomas.Whitten@Sun.COM 	    BE_FLIGHT_ST_FAIL);
861*11996SThomas.Whitten@Sun.COM 
862*11996SThomas.Whitten@Sun.COM 	return (r);
863*11996SThomas.Whitten@Sun.COM }
864*11996SThomas.Whitten@Sun.COM 
865*11996SThomas.Whitten@Sun.COM /*
866407Sjwadams  * See if a backup is needed.  We do a backup unless both files are
867407Sjwadams  * byte-for-byte identical.
868407Sjwadams  */
869407Sjwadams static int
backend_check_backup_needed(const char * rep_name,const char * backup_name)870407Sjwadams backend_check_backup_needed(const char *rep_name, const char *backup_name)
871407Sjwadams {
872407Sjwadams 	int repfd = open(rep_name, O_RDONLY);
873407Sjwadams 	int fd = open(backup_name, O_RDONLY);
874407Sjwadams 	struct stat s_rep, s_backup;
875407Sjwadams 	int c1, c2;
876407Sjwadams 
877407Sjwadams 	FILE *f_rep = NULL;
878407Sjwadams 	FILE *f_backup = NULL;
879407Sjwadams 
880407Sjwadams 	if (repfd < 0 || fd < 0)
881407Sjwadams 		goto fail;
882407Sjwadams 
883407Sjwadams 	if (fstat(repfd, &s_rep) < 0 || fstat(fd, &s_backup) < 0)
884407Sjwadams 		goto fail;
885407Sjwadams 
886407Sjwadams 	/*
887407Sjwadams 	 * if they are the same file, we need to do a backup to break the
888407Sjwadams 	 * hard link or symlink involved.
889407Sjwadams 	 */
890407Sjwadams 	if (s_rep.st_ino == s_backup.st_ino && s_rep.st_dev == s_backup.st_dev)
891407Sjwadams 		goto fail;
892407Sjwadams 
893407Sjwadams 	if (s_rep.st_size != s_backup.st_size)
894407Sjwadams 		goto fail;
895407Sjwadams 
896407Sjwadams 	if ((f_rep = fdopen(repfd, "r")) == NULL ||
897407Sjwadams 	    (f_backup = fdopen(fd, "r")) == NULL)
898407Sjwadams 		goto fail;
899407Sjwadams 
900407Sjwadams 	do {
901407Sjwadams 		c1 = getc(f_rep);
902407Sjwadams 		c2 = getc(f_backup);
903407Sjwadams 		if (c1 != c2)
904407Sjwadams 			goto fail;
905407Sjwadams 	} while (c1 != EOF);
906407Sjwadams 
907407Sjwadams 	if (!ferror(f_rep) && !ferror(f_backup)) {
908407Sjwadams 		(void) fclose(f_rep);
909407Sjwadams 		(void) fclose(f_backup);
910407Sjwadams 		(void) close(repfd);
911407Sjwadams 		(void) close(fd);
912407Sjwadams 		return (0);
913407Sjwadams 	}
914407Sjwadams 
915407Sjwadams fail:
916407Sjwadams 	if (f_rep != NULL)
917407Sjwadams 		(void) fclose(f_rep);
918407Sjwadams 	if (f_backup != NULL)
919407Sjwadams 		(void) fclose(f_backup);
920407Sjwadams 	if (repfd >= 0)
921407Sjwadams 		(void) close(repfd);
922407Sjwadams 	if (fd >= 0)
923407Sjwadams 		(void) close(fd);
924407Sjwadams 	return (1);
925407Sjwadams }
926407Sjwadams 
927407Sjwadams /*
9286035Sstevep  * This interface is called to perform the actual copy
9296035Sstevep  *
9306035Sstevep  * Return:
9316035Sstevep  *	_FAIL_UNKNOWN		read/write fails
9326035Sstevep  *	_FAIL_NO_RESOURCES	out of memory
9336035Sstevep  *	_SUCCESS		copy succeeds
9346035Sstevep  */
9356035Sstevep static rep_protocol_responseid_t
backend_do_copy(const char * src,int srcfd,const char * dst,int dstfd,size_t * sz)9366035Sstevep backend_do_copy(const char *src, int srcfd, const char *dst,
9376035Sstevep     int dstfd, size_t *sz)
9386035Sstevep {
9396035Sstevep 	char *buf;
9406035Sstevep 	off_t nrd, nwr, n, r_off = 0, w_off = 0;
9416035Sstevep 
9426035Sstevep 	if ((buf = malloc(8192)) == NULL)
9436035Sstevep 		return (REP_PROTOCOL_FAIL_NO_RESOURCES);
9446035Sstevep 
9456035Sstevep 	while ((nrd = read(srcfd, buf, 8192)) != 0) {
9466035Sstevep 		if (nrd < 0) {
9476035Sstevep 			if (errno == EINTR)
9486035Sstevep 				continue;
9496035Sstevep 
9506035Sstevep 			configd_critical(
9516035Sstevep 			    "Backend copy failed: fails to read from %s "
9526035Sstevep 			    "at offset %d: %s\n", src, r_off, strerror(errno));
9536035Sstevep 			free(buf);
9546035Sstevep 			return (REP_PROTOCOL_FAIL_UNKNOWN);
9556035Sstevep 		}
9566035Sstevep 
9576035Sstevep 		r_off += nrd;
9586035Sstevep 
9596035Sstevep 		nwr = 0;
9606035Sstevep 		do {
9616035Sstevep 			if ((n = write(dstfd, &buf[nwr], nrd - nwr)) < 0) {
9626035Sstevep 				if (errno == EINTR)
9636035Sstevep 					continue;
9646035Sstevep 
9656035Sstevep 				configd_critical(
9666035Sstevep 				    "Backend copy failed: fails to write to %s "
9676035Sstevep 				    "at offset %d: %s\n", dst, w_off,
9686035Sstevep 				    strerror(errno));
9696035Sstevep 				free(buf);
9706035Sstevep 				return (REP_PROTOCOL_FAIL_UNKNOWN);
9716035Sstevep 			}
9726035Sstevep 
9736035Sstevep 			nwr += n;
9746035Sstevep 			w_off += n;
9756035Sstevep 
9766035Sstevep 		} while (nwr < nrd);
9776035Sstevep 	}
9786035Sstevep 
9796035Sstevep 	if (sz)
9806035Sstevep 		*sz = w_off;
9816035Sstevep 
9826035Sstevep 	free(buf);
9836035Sstevep 	return (REP_PROTOCOL_SUCCESS);
9846035Sstevep }
9856035Sstevep 
9866035Sstevep /*
9870Sstevel@tonic-gate  * Can return:
9880Sstevel@tonic-gate  *	_BAD_REQUEST		name is not valid
9890Sstevel@tonic-gate  *	_TRUNCATED		name is too long for current repository path
9900Sstevel@tonic-gate  *	_UNKNOWN		failed for unknown reason (details written to
9910Sstevel@tonic-gate  *				console)
9920Sstevel@tonic-gate  *	_BACKEND_READONLY	backend is not writable
9936035Sstevep  *	_NO_RESOURCES		out of memory
9940Sstevel@tonic-gate  *	_SUCCESS		Backup completed successfully.
9950Sstevel@tonic-gate  */
9960Sstevel@tonic-gate static rep_protocol_responseid_t
backend_create_backup_locked(sqlite_backend_t * be,const char * name)9970Sstevel@tonic-gate backend_create_backup_locked(sqlite_backend_t *be, const char *name)
9980Sstevel@tonic-gate {
9990Sstevel@tonic-gate 	const char **old_list;
10000Sstevel@tonic-gate 	ssize_t old_sz;
10010Sstevel@tonic-gate 	ssize_t old_max = max_repository_backups;
10020Sstevel@tonic-gate 	ssize_t cur;
10030Sstevel@tonic-gate 	char *finalname;
10046035Sstevep 	char *finalpath;
10056035Sstevep 	char *tmppath;
10060Sstevel@tonic-gate 	int infd, outfd;
10070Sstevel@tonic-gate 	size_t len;
10080Sstevel@tonic-gate 	time_t now;
10090Sstevel@tonic-gate 	struct tm now_tm;
1010*11996SThomas.Whitten@Sun.COM 	be_flight_status_t backup_type;
10110Sstevel@tonic-gate 	rep_protocol_responseid_t result;
1012*11996SThomas.Whitten@Sun.COM 	const char *src;
1013*11996SThomas.Whitten@Sun.COM 	int use_checkpoint;
1014*11996SThomas.Whitten@Sun.COM 
1015*11996SThomas.Whitten@Sun.COM 	if (strcmp(name, REPOSITORY_BOOT_BACKUP) == 0) {
1016*11996SThomas.Whitten@Sun.COM 		backup_type = BE_FLIGHT_ST_BOOT_BACKUP;
1017*11996SThomas.Whitten@Sun.COM 	} else if (strcmp(name, "manifest_import") ==  0) {
1018*11996SThomas.Whitten@Sun.COM 		backup_type = BE_FLIGHT_ST_MI_BACKUP;
1019*11996SThomas.Whitten@Sun.COM 	} else {
1020*11996SThomas.Whitten@Sun.COM 		backup_type = BE_FLIGHT_ST_OTHER_BACKUP;
1021*11996SThomas.Whitten@Sun.COM 	}
1022*11996SThomas.Whitten@Sun.COM 	flight_recorder_event(BE_FLIGHT_EV_BACKUP_ENTER, backup_type);
10230Sstevel@tonic-gate 
10246035Sstevep 	if ((finalpath = malloc(PATH_MAX)) == NULL)
10256035Sstevep 		return (REP_PROTOCOL_FAIL_NO_RESOURCES);
10266035Sstevep 
10276035Sstevep 	if ((tmppath = malloc(PATH_MAX)) == NULL) {
10286035Sstevep 		free(finalpath);
10296035Sstevep 		return (REP_PROTOCOL_FAIL_NO_RESOURCES);
10306035Sstevep 	}
10310Sstevel@tonic-gate 
10326035Sstevep 	if (be->be_readonly) {
1033*11996SThomas.Whitten@Sun.COM 		flight_recorder_event(BE_FLIGHT_EV_NO_BACKUP, BE_FLIGHT_ST_RO);
10346035Sstevep 		result = REP_PROTOCOL_FAIL_BACKEND_READONLY;
10356035Sstevep 		goto out;
10366035Sstevep 	}
10376035Sstevep 
10386035Sstevep 	result = backend_backup_base(be, name, finalpath, PATH_MAX);
10390Sstevel@tonic-gate 	if (result != REP_PROTOCOL_SUCCESS)
10406035Sstevep 		goto out;
10410Sstevel@tonic-gate 
1042*11996SThomas.Whitten@Sun.COM 	/*
1043*11996SThomas.Whitten@Sun.COM 	 * If this is a boot backup and if we made a checkpoint before the
1044*11996SThomas.Whitten@Sun.COM 	 * root file system became read/write, then we should use the
1045*11996SThomas.Whitten@Sun.COM 	 * checkpoint as the source.  Otherwise, we'll use the actual
1046*11996SThomas.Whitten@Sun.COM 	 * repository as the source.
1047*11996SThomas.Whitten@Sun.COM 	 */
1048*11996SThomas.Whitten@Sun.COM 	if (be->be_checkpoint && name &&
1049*11996SThomas.Whitten@Sun.COM 	    strcmp(REPOSITORY_BOOT_BACKUP, name) == 0) {
1050*11996SThomas.Whitten@Sun.COM 		backup_type = BE_FLIGHT_ST_CHECKPOINT_BACKUP;
1051*11996SThomas.Whitten@Sun.COM 		use_checkpoint = 1;
1052*11996SThomas.Whitten@Sun.COM 		src = be->be_checkpoint;
1053*11996SThomas.Whitten@Sun.COM 	} else {
1054*11996SThomas.Whitten@Sun.COM 		backup_type = BE_FLIGHT_ST_REPO_BACKUP;
1055*11996SThomas.Whitten@Sun.COM 		use_checkpoint = 0;
1056*11996SThomas.Whitten@Sun.COM 		src = be->be_path;
1057*11996SThomas.Whitten@Sun.COM 	}
1058*11996SThomas.Whitten@Sun.COM 	flight_recorder_event(BE_FLIGHT_EV_BACKUP, backup_type);
1059*11996SThomas.Whitten@Sun.COM 	if (!backend_check_backup_needed(src, finalpath)) {
1060*11996SThomas.Whitten@Sun.COM 		/*
1061*11996SThomas.Whitten@Sun.COM 		 * No changes, so there is no need for a backup.
1062*11996SThomas.Whitten@Sun.COM 		 */
1063*11996SThomas.Whitten@Sun.COM 		flight_recorder_event(BE_FLIGHT_EV_NO_BACKUP,
1064*11996SThomas.Whitten@Sun.COM 		    BE_FLIGHT_ST_DUPLICATE);
10656035Sstevep 		result = REP_PROTOCOL_SUCCESS;
10666035Sstevep 		goto out;
1067407Sjwadams 	}
1068407Sjwadams 
10690Sstevel@tonic-gate 	/*
10700Sstevel@tonic-gate 	 * remember the original length, and the basename location
10710Sstevel@tonic-gate 	 */
10720Sstevel@tonic-gate 	len = strlen(finalpath);
10730Sstevel@tonic-gate 	finalname = strrchr(finalpath, '/');
10740Sstevel@tonic-gate 	if (finalname != NULL)
10750Sstevel@tonic-gate 		finalname++;
10760Sstevel@tonic-gate 	else
10770Sstevel@tonic-gate 		finalname = finalpath;
10780Sstevel@tonic-gate 
10796035Sstevep 	(void) strlcpy(tmppath, finalpath, PATH_MAX);
10806035Sstevep 	if (strlcat(tmppath, "-tmpXXXXXX", PATH_MAX) >= PATH_MAX) {
10816035Sstevep 		result = REP_PROTOCOL_FAIL_TRUNCATED;
10826035Sstevep 		goto out;
10836035Sstevep 	}
10840Sstevel@tonic-gate 
10850Sstevel@tonic-gate 	now = time(NULL);
10860Sstevel@tonic-gate 	if (localtime_r(&now, &now_tm) == NULL) {
10870Sstevel@tonic-gate 		configd_critical(
10880Sstevel@tonic-gate 		    "\"%s\" backup failed: localtime(3C) failed: %s\n", name,
1089*11996SThomas.Whitten@Sun.COM 		    strerror(errno));
10906035Sstevep 		result = REP_PROTOCOL_FAIL_UNKNOWN;
10916035Sstevep 		goto out;
10920Sstevel@tonic-gate 	}
10930Sstevel@tonic-gate 
10946035Sstevep 	if (strftime(finalpath + len, PATH_MAX - len,
10956035Sstevep 	    "-%Y""%m""%d""_""%H""%M""%S", &now_tm) >= PATH_MAX - len) {
10966035Sstevep 		result = REP_PROTOCOL_FAIL_TRUNCATED;
10976035Sstevep 		goto out;
10980Sstevel@tonic-gate 	}
10990Sstevel@tonic-gate 
1100*11996SThomas.Whitten@Sun.COM 	infd = open(src, O_RDONLY);
11010Sstevel@tonic-gate 	if (infd < 0) {
11020Sstevel@tonic-gate 		configd_critical("\"%s\" backup failed: opening %s: %s\n", name,
1103*11996SThomas.Whitten@Sun.COM 		    src, strerror(errno));
11046035Sstevep 		result = REP_PROTOCOL_FAIL_UNKNOWN;
11056035Sstevep 		goto out;
11060Sstevel@tonic-gate 	}
11070Sstevel@tonic-gate 
11080Sstevel@tonic-gate 	outfd = mkstemp(tmppath);
11090Sstevel@tonic-gate 	if (outfd < 0) {
11100Sstevel@tonic-gate 		configd_critical("\"%s\" backup failed: mkstemp(%s): %s\n",
11110Sstevel@tonic-gate 		    name, tmppath, strerror(errno));
11120Sstevel@tonic-gate 		(void) close(infd);
11136035Sstevep 		result = REP_PROTOCOL_FAIL_UNKNOWN;
11146035Sstevep 		goto out;
11150Sstevel@tonic-gate 	}
11160Sstevel@tonic-gate 
1117*11996SThomas.Whitten@Sun.COM 	if ((result = backend_do_copy(src, infd, (const char *)tmppath,
1118*11996SThomas.Whitten@Sun.COM 	    outfd, NULL)) != REP_PROTOCOL_SUCCESS)
11190Sstevel@tonic-gate 		goto fail;
11200Sstevel@tonic-gate 
11210Sstevel@tonic-gate 	/*
11220Sstevel@tonic-gate 	 * grab the old list before doing our re-name.
11230Sstevel@tonic-gate 	 */
11240Sstevel@tonic-gate 	if (old_max > 0)
11250Sstevel@tonic-gate 		old_sz = backend_backup_get_prev(finalpath, len, &old_list);
11260Sstevel@tonic-gate 
11270Sstevel@tonic-gate 	if (rename(tmppath, finalpath) < 0) {
11280Sstevel@tonic-gate 		configd_critical(
11290Sstevel@tonic-gate 		    "\"%s\" backup failed: rename(%s, %s): %s\n",
11300Sstevel@tonic-gate 		    name, tmppath, finalpath, strerror(errno));
11310Sstevel@tonic-gate 		result = REP_PROTOCOL_FAIL_UNKNOWN;
11320Sstevel@tonic-gate 		goto fail;
11330Sstevel@tonic-gate 	}
11340Sstevel@tonic-gate 
11350Sstevel@tonic-gate 	tmppath[len] = 0;	/* strip -XXXXXX, for reference symlink */
11360Sstevel@tonic-gate 
11370Sstevel@tonic-gate 	(void) unlink(tmppath);
11380Sstevel@tonic-gate 	if (symlink(finalname, tmppath) < 0) {
11390Sstevel@tonic-gate 		configd_critical(
11400Sstevel@tonic-gate 		    "\"%s\" backup completed, but updating "
11410Sstevel@tonic-gate 		    "\"%s\" symlink to \"%s\" failed: %s\n",
11420Sstevel@tonic-gate 		    name, tmppath, finalname, strerror(errno));
11430Sstevel@tonic-gate 	}
11440Sstevel@tonic-gate 
11450Sstevel@tonic-gate 	if (old_max > 0 && old_sz > 0) {
11460Sstevel@tonic-gate 		/* unlink all but the first (old_max - 1) files */
11470Sstevel@tonic-gate 		for (cur = old_max - 1; cur < old_sz; cur++) {
11480Sstevel@tonic-gate 			(void) strlcpy(finalname, old_list[cur],
11496035Sstevep 			    PATH_MAX - (finalname - finalpath));
11500Sstevel@tonic-gate 			if (unlink(finalpath) < 0)
11510Sstevel@tonic-gate 				configd_critical(
11520Sstevel@tonic-gate 				    "\"%s\" backup completed, but removing old "
11530Sstevel@tonic-gate 				    "file \"%s\" failed: %s\n",
11540Sstevel@tonic-gate 				    name, finalpath, strerror(errno));
11550Sstevel@tonic-gate 		}
11560Sstevel@tonic-gate 
11570Sstevel@tonic-gate 		backend_backup_cleanup(old_list, old_sz);
11580Sstevel@tonic-gate 	}
11590Sstevel@tonic-gate 
11600Sstevel@tonic-gate 	result = REP_PROTOCOL_SUCCESS;
1161*11996SThomas.Whitten@Sun.COM 	flight_recorder_event(BE_FLIGHT_EV_BACKUP, BE_FLIGHT_ST_SUCCESS);
11620Sstevel@tonic-gate 
11630Sstevel@tonic-gate fail:
11640Sstevel@tonic-gate 	(void) close(infd);
11650Sstevel@tonic-gate 	(void) close(outfd);
1166*11996SThomas.Whitten@Sun.COM 	if (result != REP_PROTOCOL_SUCCESS) {
1167*11996SThomas.Whitten@Sun.COM 		flight_recorder_event(BE_FLIGHT_EV_BACKUP, BE_FLIGHT_ST_FAIL);
11680Sstevel@tonic-gate 		(void) unlink(tmppath);
1169*11996SThomas.Whitten@Sun.COM 	}
11700Sstevel@tonic-gate 
11716035Sstevep out:
1172*11996SThomas.Whitten@Sun.COM 	/* Get rid of the checkpoint file now that we've used it. */
1173*11996SThomas.Whitten@Sun.COM 	if (use_checkpoint && (result == REP_PROTOCOL_SUCCESS)) {
1174*11996SThomas.Whitten@Sun.COM 		(void) unlink(be->be_checkpoint);
1175*11996SThomas.Whitten@Sun.COM 		be->be_checkpoint = NULL;
1176*11996SThomas.Whitten@Sun.COM 	}
11776035Sstevep 	free(finalpath);
11786035Sstevep 	free(tmppath);
11796035Sstevep 
11800Sstevel@tonic-gate 	return (result);
11810Sstevel@tonic-gate }
11820Sstevel@tonic-gate 
11837128Samaguire /*
11847128Samaguire  * Check if value_tbl has been upgraded in the main database,  and
11857128Samaguire  * if not (if the value_order column is not present),  and do_upgrade is true,
11867128Samaguire  * upgrade value_tbl in repository to contain the additional value_order
11877128Samaguire  * column. The version of sqlite used means ALTER TABLE is not
11887128Samaguire  * available, so we cannot simply use "ALTER TABLE value_tbl ADD COLUMN".
11897128Samaguire  * Rather we need to create a temporary table with the additional column,
11907128Samaguire  * import the value_tbl, drop the original value_tbl, recreate the value_tbl
11917128Samaguire  * with the additional column, import the values from value_tbl_tmp,
11927128Samaguire  * reindex and finally drop value_tbl_tmp.  During boot, we wish to check
11937128Samaguire  * if the repository has been upgraded before it is writable,  so that
11947128Samaguire  * property value retrieval can use the appropriate form of the SELECT
11957128Samaguire  * statement that retrieves property values.  As a result, we need to check
11967128Samaguire  * if the repository has been upgraded prior to the point when we can
11977128Samaguire  * actually carry out the update.
11987128Samaguire  */
11997128Samaguire void
backend_check_upgrade(sqlite_backend_t * be,boolean_t do_upgrade)12007128Samaguire backend_check_upgrade(sqlite_backend_t *be, boolean_t do_upgrade)
12017128Samaguire {
12027128Samaguire 	char *errp;
12037128Samaguire 	int r;
12047128Samaguire 
12057128Samaguire 	if (be_normal_upgraded)
12067128Samaguire 		return;
12077128Samaguire 	/*
12087128Samaguire 	 * Test if upgrade is needed. If value_order column does not exist,
12097128Samaguire 	 * we need to upgrade the schema.
12107128Samaguire 	 */
12117128Samaguire 	r = sqlite_exec(be->be_db, "SELECT value_order FROM value_tbl LIMIT 1;",
12127128Samaguire 	    NULL, NULL, NULL);
12137128Samaguire 	if (r == SQLITE_ERROR && do_upgrade) {
12147128Samaguire 		/* No value_order column - needs upgrade */
12157128Samaguire 		configd_info("Upgrading SMF repository format...");
12167128Samaguire 		r = sqlite_exec(be->be_db,
12177128Samaguire 		    "BEGIN TRANSACTION; "
12187128Samaguire 		    "CREATE TABLE value_tbl_tmp ( "
12197128Samaguire 		    "value_id   INTEGER NOT NULL, "
12207128Samaguire 		    "value_type CHAR(1) NOT NULL, "
12217128Samaguire 		    "value_value VARCHAR NOT NULL, "
12227128Samaguire 		    "value_order INTEGER DEFAULT 0); "
12237128Samaguire 		    "INSERT INTO value_tbl_tmp "
12247128Samaguire 		    "(value_id, value_type, value_value) "
12257128Samaguire 		    "SELECT value_id, value_type, value_value FROM value_tbl; "
12267128Samaguire 		    "DROP TABLE value_tbl; "
12277128Samaguire 		    "CREATE TABLE value_tbl( "
12287128Samaguire 		    "value_id   INTEGER NOT NULL, "
12297128Samaguire 		    "value_type CHAR(1) NOT NULL, "
12307128Samaguire 		    "value_value VARCHAR NOT NULL, "
12317128Samaguire 		    "value_order INTEGER DEFAULT 0); "
12327128Samaguire 		    "INSERT INTO value_tbl SELECT * FROM value_tbl_tmp; "
12337128Samaguire 		    "CREATE INDEX value_tbl_id ON value_tbl (value_id); "
12347128Samaguire 		    "DROP TABLE value_tbl_tmp; "
12357128Samaguire 		    "COMMIT TRANSACTION; "
12367128Samaguire 		    "VACUUM; ",
12377128Samaguire 		    NULL, NULL, &errp);
12387128Samaguire 		if (r == SQLITE_OK) {
12397128Samaguire 			configd_info("SMF repository upgrade is complete.");
12407128Samaguire 		} else {
12417128Samaguire 			backend_panic("%s: repository upgrade failed: %s",
12427128Samaguire 			    be->be_path, errp);
12437128Samaguire 			/* NOTREACHED */
12447128Samaguire 		}
12457128Samaguire 	}
12467128Samaguire 	if (r == SQLITE_OK)
12477128Samaguire 		be_normal_upgraded = B_TRUE;
12487128Samaguire 	else
12497128Samaguire 		be_normal_upgraded = B_FALSE;
12507128Samaguire }
12517128Samaguire 
1252407Sjwadams static int
backend_check_readonly(sqlite_backend_t * be,int writing,hrtime_t t)1253407Sjwadams backend_check_readonly(sqlite_backend_t *be, int writing, hrtime_t t)
1254407Sjwadams {
1255*11996SThomas.Whitten@Sun.COM 	const char *check_path;
1256407Sjwadams 	char *errp;
1257407Sjwadams 	struct sqlite *new;
1258407Sjwadams 	int r;
1259407Sjwadams 
1260407Sjwadams 	assert(be->be_readonly);
1261407Sjwadams 	assert(be == bes[BACKEND_TYPE_NORMAL]);
1262407Sjwadams 
1263407Sjwadams 	/*
1264407Sjwadams 	 * If we don't *need* to be writable, only check every once in a
1265407Sjwadams 	 * while.
1266407Sjwadams 	 */
1267407Sjwadams 	if (!writing) {
1268407Sjwadams 		if ((uint64_t)(t - be->be_lastcheck) <
1269407Sjwadams 		    BACKEND_READONLY_CHECK_INTERVAL)
1270407Sjwadams 			return (REP_PROTOCOL_SUCCESS);
1271407Sjwadams 		be->be_lastcheck = t;
1272407Sjwadams 	}
1273407Sjwadams 
1274*11996SThomas.Whitten@Sun.COM 	/*
1275*11996SThomas.Whitten@Sun.COM 	 * It could be that the repository has been moved to non-persistent
1276*11996SThomas.Whitten@Sun.COM 	 * storage for performance reasons.  In this case we need to check
1277*11996SThomas.Whitten@Sun.COM 	 * the persistent path to see if it is writable.  The
1278*11996SThomas.Whitten@Sun.COM 	 * non-persistent path will always be writable.
1279*11996SThomas.Whitten@Sun.COM 	 */
1280*11996SThomas.Whitten@Sun.COM 	check_path = IS_VOLATILE(be) ? be->be_ppath : be->be_path;
1281*11996SThomas.Whitten@Sun.COM 
1282*11996SThomas.Whitten@Sun.COM 	new = sqlite_open(check_path, 0600, &errp);
1283407Sjwadams 	if (new == NULL) {
1284*11996SThomas.Whitten@Sun.COM 		backend_panic("reopening %s: %s\n", check_path, errp);
1285407Sjwadams 		/*NOTREACHED*/
1286407Sjwadams 	}
1287*11996SThomas.Whitten@Sun.COM 	r = backend_is_readonly(new, check_path);
1288407Sjwadams 
1289407Sjwadams 	if (r != SQLITE_OK) {
1290*11996SThomas.Whitten@Sun.COM 		/*
1291*11996SThomas.Whitten@Sun.COM 		 * The underlying storage for the permanent repository is
1292*11996SThomas.Whitten@Sun.COM 		 * still read-only, so we don't want to change the state or
1293*11996SThomas.Whitten@Sun.COM 		 * move the checkpointed backup if it exists.  On the other
1294*11996SThomas.Whitten@Sun.COM 		 * hand if the repository has been copied to volatile
1295*11996SThomas.Whitten@Sun.COM 		 * storage, we'll let our caller go ahead and write to the
1296*11996SThomas.Whitten@Sun.COM 		 * database.
1297*11996SThomas.Whitten@Sun.COM 		 */
1298407Sjwadams 		sqlite_close(new);
1299*11996SThomas.Whitten@Sun.COM 		if (writing && (IS_VOLATILE(be) == 0))
1300407Sjwadams 			return (REP_PROTOCOL_FAIL_BACKEND_READONLY);
1301407Sjwadams 		return (REP_PROTOCOL_SUCCESS);
1302407Sjwadams 	}
1303407Sjwadams 
1304407Sjwadams 	/*
1305*11996SThomas.Whitten@Sun.COM 	 * We can write!  If the repository is not on volatile storage,
1306*11996SThomas.Whitten@Sun.COM 	 * swap the db handles.  Mark ourself as writable, upgrade the
1307*11996SThomas.Whitten@Sun.COM 	 * repository if necessary and make a backup.
1308407Sjwadams 	 */
1309407Sjwadams 	be->be_readonly = 0;
1310*11996SThomas.Whitten@Sun.COM 	flight_recorder_event(BE_FLIGHT_EV_TRANS_RW, BE_FLIGHT_ST_RW);
1311*11996SThomas.Whitten@Sun.COM 	if (IS_VOLATILE(be)) {
1312*11996SThomas.Whitten@Sun.COM 		/*
1313*11996SThomas.Whitten@Sun.COM 		 * If the repository is on volatile storage, don't switch
1314*11996SThomas.Whitten@Sun.COM 		 * the handles.  We'll continue to use the repository that
1315*11996SThomas.Whitten@Sun.COM 		 * is on tmpfs until we're told to move it back by one of
1316*11996SThomas.Whitten@Sun.COM 		 * our clients.  Clients, specifically manifest_import,
1317*11996SThomas.Whitten@Sun.COM 		 * move the repository to tmpfs for performance reasons,
1318*11996SThomas.Whitten@Sun.COM 		 * and that is the reason to not switch it back until we're
1319*11996SThomas.Whitten@Sun.COM 		 * told to do so.
1320*11996SThomas.Whitten@Sun.COM 		 */
1321*11996SThomas.Whitten@Sun.COM 		flight_recorder_event(BE_FLIGHT_EV_TRANS_RW,
1322*11996SThomas.Whitten@Sun.COM 		    BE_FLIGHT_ST_NO_SWITCH);
1323*11996SThomas.Whitten@Sun.COM 		sqlite_close(new);
1324*11996SThomas.Whitten@Sun.COM 	} else {
1325*11996SThomas.Whitten@Sun.COM 		flight_recorder_event(BE_FLIGHT_EV_TRANS_RW,
1326*11996SThomas.Whitten@Sun.COM 		    BE_FLIGHT_ST_SWITCH);
1327*11996SThomas.Whitten@Sun.COM 		sqlite_close(be->be_db);
1328*11996SThomas.Whitten@Sun.COM 		be->be_db = new;
1329*11996SThomas.Whitten@Sun.COM 	}
1330407Sjwadams 
13317128Samaguire 	if (be->be_type == BACKEND_TYPE_NORMAL)
13327128Samaguire 		backend_check_upgrade(be, B_TRUE);
13337128Samaguire 
1334407Sjwadams 	if (backend_create_backup_locked(be, REPOSITORY_BOOT_BACKUP) !=
1335407Sjwadams 	    REP_PROTOCOL_SUCCESS) {
1336407Sjwadams 		configd_critical(
1337407Sjwadams 		    "unable to create \"%s\" backup of \"%s\"\n",
1338407Sjwadams 		    REPOSITORY_BOOT_BACKUP, be->be_path);
1339407Sjwadams 	}
1340407Sjwadams 
1341407Sjwadams 	return (REP_PROTOCOL_SUCCESS);
1342407Sjwadams }
13430Sstevel@tonic-gate 
13440Sstevel@tonic-gate /*
13450Sstevel@tonic-gate  * If t is not BACKEND_TYPE_NORMAL, can fail with
13460Sstevel@tonic-gate  *   _BACKEND_ACCESS - backend does not exist
13470Sstevel@tonic-gate  *
13480Sstevel@tonic-gate  * If writing is nonzero, can also fail with
13490Sstevel@tonic-gate  *   _BACKEND_READONLY - backend is read-only
13500Sstevel@tonic-gate  */
13510Sstevel@tonic-gate static int
backend_lock(backend_type_t t,int writing,sqlite_backend_t ** bep)13520Sstevel@tonic-gate backend_lock(backend_type_t t, int writing, sqlite_backend_t **bep)
13530Sstevel@tonic-gate {
13540Sstevel@tonic-gate 	sqlite_backend_t *be = NULL;
13550Sstevel@tonic-gate 	hrtime_t ts, vts;
13560Sstevel@tonic-gate 
13570Sstevel@tonic-gate 	*bep = NULL;
13580Sstevel@tonic-gate 
13590Sstevel@tonic-gate 	assert(t == BACKEND_TYPE_NORMAL ||
13600Sstevel@tonic-gate 	    t == BACKEND_TYPE_NONPERSIST);
13610Sstevel@tonic-gate 
13620Sstevel@tonic-gate 	be = bes[t];
13630Sstevel@tonic-gate 	if (t == BACKEND_TYPE_NORMAL)
13640Sstevel@tonic-gate 		assert(be != NULL);		/* should always be there */
13650Sstevel@tonic-gate 
13660Sstevel@tonic-gate 	if (be == NULL)
13670Sstevel@tonic-gate 		return (REP_PROTOCOL_FAIL_BACKEND_ACCESS);
13680Sstevel@tonic-gate 
13690Sstevel@tonic-gate 	if (backend_panic_thread != 0)
13700Sstevel@tonic-gate 		backend_panic(NULL);		/* don't proceed */
13710Sstevel@tonic-gate 
13720Sstevel@tonic-gate 	ts = gethrtime();
13730Sstevel@tonic-gate 	vts = gethrvtime();
13740Sstevel@tonic-gate 	(void) pthread_mutex_lock(&be->be_lock);
13750Sstevel@tonic-gate 	UPDATE_TOTALS_WR(be, writing, bt_lock, ts, vts);
13760Sstevel@tonic-gate 
13770Sstevel@tonic-gate 	if (backend_panic_thread != 0) {
13780Sstevel@tonic-gate 		(void) pthread_mutex_unlock(&be->be_lock);
13790Sstevel@tonic-gate 		backend_panic(NULL);		/* don't proceed */
13800Sstevel@tonic-gate 	}
13810Sstevel@tonic-gate 	be->be_thread = pthread_self();
13820Sstevel@tonic-gate 
1383407Sjwadams 	if (be->be_readonly) {
13840Sstevel@tonic-gate 		int r;
13850Sstevel@tonic-gate 		assert(t == BACKEND_TYPE_NORMAL);
13860Sstevel@tonic-gate 
1387407Sjwadams 		r = backend_check_readonly(be, writing, ts);
1388407Sjwadams 		if (r != REP_PROTOCOL_SUCCESS) {
13890Sstevel@tonic-gate 			be->be_thread = 0;
13900Sstevel@tonic-gate 			(void) pthread_mutex_unlock(&be->be_lock);
1391407Sjwadams 			return (r);
13920Sstevel@tonic-gate 		}
1393407Sjwadams 	}
13940Sstevel@tonic-gate 
13950Sstevel@tonic-gate 	if (backend_do_trace)
13960Sstevel@tonic-gate 		(void) sqlite_trace(be->be_db, backend_trace_sql, be);
13970Sstevel@tonic-gate 	else
13980Sstevel@tonic-gate 		(void) sqlite_trace(be->be_db, NULL, NULL);
13990Sstevel@tonic-gate 
14000Sstevel@tonic-gate 	be->be_writing = writing;
14010Sstevel@tonic-gate 	*bep = be;
14020Sstevel@tonic-gate 	return (REP_PROTOCOL_SUCCESS);
14030Sstevel@tonic-gate }
14040Sstevel@tonic-gate 
14050Sstevel@tonic-gate static void
backend_unlock(sqlite_backend_t * be)14060Sstevel@tonic-gate backend_unlock(sqlite_backend_t *be)
14070Sstevel@tonic-gate {
14080Sstevel@tonic-gate 	be->be_writing = 0;
14090Sstevel@tonic-gate 	be->be_thread = 0;
14100Sstevel@tonic-gate 	(void) pthread_mutex_unlock(&be->be_lock);
14110Sstevel@tonic-gate }
14120Sstevel@tonic-gate 
14130Sstevel@tonic-gate static void
backend_destroy(sqlite_backend_t * be)14140Sstevel@tonic-gate backend_destroy(sqlite_backend_t *be)
14150Sstevel@tonic-gate {
14160Sstevel@tonic-gate 	if (be->be_db != NULL) {
14170Sstevel@tonic-gate 		sqlite_close(be->be_db);
14180Sstevel@tonic-gate 		be->be_db = NULL;
14190Sstevel@tonic-gate 	}
14200Sstevel@tonic-gate 	be->be_thread = 0;
14210Sstevel@tonic-gate 	(void) pthread_mutex_unlock(&be->be_lock);
14220Sstevel@tonic-gate 	(void) pthread_mutex_destroy(&be->be_lock);
14230Sstevel@tonic-gate }
14240Sstevel@tonic-gate 
14250Sstevel@tonic-gate static void
backend_create_finish(backend_type_t backend_id,sqlite_backend_t * be)14260Sstevel@tonic-gate backend_create_finish(backend_type_t backend_id, sqlite_backend_t *be)
14270Sstevel@tonic-gate {
14280Sstevel@tonic-gate 	assert(MUTEX_HELD(&be->be_lock));
14290Sstevel@tonic-gate 	assert(be == &be_info[backend_id]);
14300Sstevel@tonic-gate 
14310Sstevel@tonic-gate 	bes[backend_id] = be;
14320Sstevel@tonic-gate 	(void) pthread_mutex_unlock(&be->be_lock);
14330Sstevel@tonic-gate }
14340Sstevel@tonic-gate 
14350Sstevel@tonic-gate static int
backend_fd_write(int fd,const char * mess)14360Sstevel@tonic-gate backend_fd_write(int fd, const char *mess)
14370Sstevel@tonic-gate {
14380Sstevel@tonic-gate 	int len = strlen(mess);
14390Sstevel@tonic-gate 	int written;
14400Sstevel@tonic-gate 
14410Sstevel@tonic-gate 	while (len > 0) {
14420Sstevel@tonic-gate 		if ((written = write(fd, mess, len)) < 0)
14430Sstevel@tonic-gate 			return (-1);
14440Sstevel@tonic-gate 		mess += written;
14450Sstevel@tonic-gate 		len -= written;
14460Sstevel@tonic-gate 	}
14470Sstevel@tonic-gate 	return (0);
14480Sstevel@tonic-gate }
14490Sstevel@tonic-gate 
14500Sstevel@tonic-gate /*
14510Sstevel@tonic-gate  * Can return:
14520Sstevel@tonic-gate  *	_BAD_REQUEST		name is not valid
14530Sstevel@tonic-gate  *	_TRUNCATED		name is too long for current repository path
14540Sstevel@tonic-gate  *	_UNKNOWN		failed for unknown reason (details written to
14550Sstevel@tonic-gate  *				console)
14560Sstevel@tonic-gate  *	_BACKEND_READONLY	backend is not writable
14576035Sstevep  *	_NO_RESOURCES		out of memory
14580Sstevel@tonic-gate  *	_SUCCESS		Backup completed successfully.
14590Sstevel@tonic-gate  */
14600Sstevel@tonic-gate rep_protocol_responseid_t
backend_create_backup(const char * name)14610Sstevel@tonic-gate backend_create_backup(const char *name)
14620Sstevel@tonic-gate {
14630Sstevel@tonic-gate 	rep_protocol_responseid_t result;
14640Sstevel@tonic-gate 	sqlite_backend_t *be;
14650Sstevel@tonic-gate 
1466*11996SThomas.Whitten@Sun.COM 	flight_recorder_event(BE_FLIGHT_EV_BACKUP, BE_FLIGHT_ST_CLIENT);
14670Sstevel@tonic-gate 	result = backend_lock(BACKEND_TYPE_NORMAL, 0, &be);
14686035Sstevep 	assert(result == REP_PROTOCOL_SUCCESS);
14690Sstevel@tonic-gate 
14700Sstevel@tonic-gate 	result = backend_create_backup_locked(be, name);
14710Sstevel@tonic-gate 	backend_unlock(be);
14720Sstevel@tonic-gate 
14730Sstevel@tonic-gate 	return (result);
14740Sstevel@tonic-gate }
14750Sstevel@tonic-gate 
14766035Sstevep /*
1477*11996SThomas.Whitten@Sun.COM  * This function makes a copy of the repository at src, placing the copy at
1478*11996SThomas.Whitten@Sun.COM  * dst.  It is used to copy a repository on permanent storage to volatile
1479*11996SThomas.Whitten@Sun.COM  * storage or vice versa.  If the source file is on volatile storage, it is
1480*11996SThomas.Whitten@Sun.COM  * often times desirable to delete it after the copy has been made and
1481*11996SThomas.Whitten@Sun.COM  * verified.  To remove the source repository, set remove_src to 1.
14826035Sstevep  *
14836035Sstevep  * Can return:
14846035Sstevep  *
14856035Sstevep  *	REP_PROTOCOL_SUCCESS		successful copy and rename
14866035Sstevep  *	REP_PROTOCOL_FAIL_UNKNOWN	file operation error
14876035Sstevep  *	REP_PROTOCOL_FAIL_NO_RESOURCES	out of memory
14886035Sstevep  */
14896035Sstevep static rep_protocol_responseid_t
backend_copy_repository(const char * src,const char * dst,int remove_src)1490*11996SThomas.Whitten@Sun.COM backend_copy_repository(const char *src, const char *dst, int remove_src)
14916035Sstevep {
14926035Sstevep 	int srcfd, dstfd;
14936035Sstevep 	char *tmppath = malloc(PATH_MAX);
14946035Sstevep 	rep_protocol_responseid_t res = REP_PROTOCOL_SUCCESS;
14956035Sstevep 	struct stat s_buf;
14966035Sstevep 	size_t cpsz, sz;
14976035Sstevep 
14986035Sstevep 	if (tmppath == NULL) {
14996035Sstevep 		res = REP_PROTOCOL_FAIL_NO_RESOURCES;
15006035Sstevep 		goto out;
15016035Sstevep 	}
15026035Sstevep 
15036035Sstevep 	/*
15046035Sstevep 	 * Create and open the related db files
15056035Sstevep 	 */
15066035Sstevep 	(void) strlcpy(tmppath, dst, PATH_MAX);
15076035Sstevep 	sz = strlcat(tmppath, "-XXXXXX", PATH_MAX);
15086035Sstevep 	assert(sz < PATH_MAX);
15096035Sstevep 	if (sz >= PATH_MAX) {
15106035Sstevep 		configd_critical(
15116035Sstevep 		    "Backend copy failed: strlcat %s: overflow\n", tmppath);
15126035Sstevep 		abort();
15136035Sstevep 	}
15146035Sstevep 
15156035Sstevep 	if ((dstfd = mkstemp(tmppath)) < 0) {
15166035Sstevep 		configd_critical("Backend copy failed: mkstemp %s: %s\n",
15176035Sstevep 		    tmppath, strerror(errno));
15186035Sstevep 		res = REP_PROTOCOL_FAIL_UNKNOWN;
15196035Sstevep 		goto out;
15206035Sstevep 	}
15216035Sstevep 
15226035Sstevep 	if ((srcfd = open(src, O_RDONLY)) < 0) {
15236035Sstevep 		configd_critical("Backend copy failed: opening %s: %s\n",
15246035Sstevep 		    src, strerror(errno));
15256035Sstevep 		res = REP_PROTOCOL_FAIL_UNKNOWN;
15266035Sstevep 		goto errexit;
15276035Sstevep 	}
15286035Sstevep 
15296035Sstevep 	/*
15306035Sstevep 	 * fstat the backend before copy for sanity check.
15316035Sstevep 	 */
15326035Sstevep 	if (fstat(srcfd, &s_buf) < 0) {
15336035Sstevep 		configd_critical("Backend copy failed: fstat %s: %s\n",
15346035Sstevep 		    src, strerror(errno));
15356035Sstevep 		res = REP_PROTOCOL_FAIL_UNKNOWN;
15366035Sstevep 		goto errexit;
15376035Sstevep 	}
15386035Sstevep 
15396035Sstevep 	if ((res = backend_do_copy(src, srcfd, dst, dstfd, &cpsz)) !=
15406035Sstevep 	    REP_PROTOCOL_SUCCESS)
15416035Sstevep 		goto errexit;
15426035Sstevep 
15436035Sstevep 	if (cpsz != s_buf.st_size) {
15446035Sstevep 		configd_critical("Backend copy failed: incomplete copy\n");
15456035Sstevep 		res = REP_PROTOCOL_FAIL_UNKNOWN;
15466035Sstevep 		goto errexit;
15476035Sstevep 	}
15486035Sstevep 
15496035Sstevep 	/*
15506035Sstevep 	 * Rename tmppath to dst
15516035Sstevep 	 */
15526035Sstevep 	if (rename(tmppath, dst) < 0) {
15536035Sstevep 		configd_critical(
15546035Sstevep 		    "Backend copy failed: rename %s to %s: %s\n",
15556035Sstevep 		    tmppath, dst, strerror(errno));
15566035Sstevep 		res = REP_PROTOCOL_FAIL_UNKNOWN;
15576035Sstevep 	}
15586035Sstevep 
15596035Sstevep errexit:
15606035Sstevep 	if (res != REP_PROTOCOL_SUCCESS && unlink(tmppath) < 0)
15616035Sstevep 		configd_critical(
15626035Sstevep 		    "Backend copy failed: remove %s: %s\n",
15636035Sstevep 		    tmppath, strerror(errno));
15646035Sstevep 
15656035Sstevep 	(void) close(srcfd);
15666035Sstevep 	(void) close(dstfd);
15676035Sstevep 
15686035Sstevep out:
15696035Sstevep 	free(tmppath);
1570*11996SThomas.Whitten@Sun.COM 	if (remove_src) {
15716035Sstevep 		if (unlink(src) < 0)
15726035Sstevep 			configd_critical(
15736035Sstevep 			    "Backend copy failed: remove %s: %s\n",
15746035Sstevep 			    src, strerror(errno));
15756035Sstevep 	}
15766035Sstevep 
15776035Sstevep 	return (res);
15786035Sstevep }
15796035Sstevep 
15806035Sstevep /*
15816035Sstevep  * Perform sanity check on the repository.
15826035Sstevep  * Return 0 if check succeeds or -1 if fails.
15836035Sstevep  */
15846035Sstevep static int
backend_switch_check(struct sqlite * be_db,char ** errp)15856035Sstevep backend_switch_check(struct sqlite *be_db, char **errp)
15866035Sstevep {
15876035Sstevep 	struct run_single_int_info info;
15886035Sstevep 	uint32_t val = -1UL;
15896035Sstevep 	int r;
15906035Sstevep 
15916035Sstevep 	info.rs_out = &val;
15926035Sstevep 	info.rs_result = REP_PROTOCOL_FAIL_NOT_FOUND;
15936035Sstevep 
15946035Sstevep 	r = sqlite_exec(be_db,
15956035Sstevep 	    "SELECT schema_version FROM schema_version;",
15966035Sstevep 	    run_single_int_callback, &info, errp);
15976035Sstevep 
15986035Sstevep 	if (r == SQLITE_OK &&
15996035Sstevep 	    info.rs_result != REP_PROTOCOL_FAIL_NOT_FOUND &&
16006035Sstevep 	    val == BACKEND_SCHEMA_VERSION)
16016035Sstevep 		return (0);
16026035Sstevep 	else
16036035Sstevep 		return (-1);
16046035Sstevep }
16056035Sstevep 
16066035Sstevep /*
1607*11996SThomas.Whitten@Sun.COM  * backend_switch() implements the REP_PROTOCOL_SWITCH request from
1608*11996SThomas.Whitten@Sun.COM  * clients.  First, it blocks all other clients from accessing the
1609*11996SThomas.Whitten@Sun.COM  * repository by calling backend_lock to lock the repository.  It either
1610*11996SThomas.Whitten@Sun.COM  * copies the repository from it's permanent storage location
1611*11996SThomas.Whitten@Sun.COM  * (REPOSITORY_DB) to its fast volatile location (FAST_REPOSITORY_DB), or
1612*11996SThomas.Whitten@Sun.COM  * vice versa.  dir determines the direction of the copy.
1613*11996SThomas.Whitten@Sun.COM  *
1614*11996SThomas.Whitten@Sun.COM  *	dir = 0	Copy from permanent location to volatile location.
1615*11996SThomas.Whitten@Sun.COM  *	dir = 1	Copy from volatile location to permanent location.
16166035Sstevep  *
16176035Sstevep  * Can return:
16186035Sstevep  *	REP_PROTOCOL_SUCCESS			successful switch
16196035Sstevep  *	REP_PROTOCOL_FAIL_BACKEND_ACCESS	backen access fails
16206035Sstevep  *	REP_PROTOCOL_FAIL_BACKEND_READONLY	backend is not writable
16216035Sstevep  *	REP_PROTOCOL_FAIL_UNKNOWN		file operation error
16226035Sstevep  *	REP_PROTOCOL_FAIL_NO_RESOURCES		out of memory
16236035Sstevep  */
16246035Sstevep rep_protocol_responseid_t
backend_switch(int dir)1625*11996SThomas.Whitten@Sun.COM backend_switch(int dir)
16266035Sstevep {
16276035Sstevep 	rep_protocol_responseid_t result;
16286035Sstevep 	sqlite_backend_t *be;
16296035Sstevep 	struct sqlite *new;
16306035Sstevep 	char *errp;
16316035Sstevep 	const char *dst;
16326035Sstevep 
1633*11996SThomas.Whitten@Sun.COM 	flight_recorder_event(BE_FLIGHT_EV_SWITCH, BE_FLIGHT_ST_CLIENT);
1634*11996SThomas.Whitten@Sun.COM 
1635*11996SThomas.Whitten@Sun.COM 	/*
1636*11996SThomas.Whitten@Sun.COM 	 * If switching back to the main repository, lock for writing.
1637*11996SThomas.Whitten@Sun.COM 	 * Otherwise, lock for reading.
1638*11996SThomas.Whitten@Sun.COM 	 */
1639*11996SThomas.Whitten@Sun.COM 	result = backend_lock(BACKEND_TYPE_NORMAL, dir ? 1 : 0,
1640*11996SThomas.Whitten@Sun.COM 	    &be);
16416035Sstevep 	if (result != REP_PROTOCOL_SUCCESS)
16426035Sstevep 		return (result);
16436035Sstevep 
1644*11996SThomas.Whitten@Sun.COM 	if (dir) {
1645*11996SThomas.Whitten@Sun.COM 		flight_recorder_event(BE_FLIGHT_EV_SWITCH,
1646*11996SThomas.Whitten@Sun.COM 		    BE_FLIGHT_ST_PERMANENT);
16476035Sstevep 		dst = REPOSITORY_DB;
16486035Sstevep 	} else {
1649*11996SThomas.Whitten@Sun.COM 		flight_recorder_event(BE_FLIGHT_EV_SWITCH,
1650*11996SThomas.Whitten@Sun.COM 		    BE_FLIGHT_ST_FAST);
16516035Sstevep 		dst = FAST_REPOSITORY_DB;
16526035Sstevep 	}
16536035Sstevep 
16546035Sstevep 	/*
16556035Sstevep 	 * Do the actual copy and rename
16566035Sstevep 	 */
1657*11996SThomas.Whitten@Sun.COM 	if (strcmp(be->be_path, dst) == 0) {
1658*11996SThomas.Whitten@Sun.COM 		flight_recorder_event(BE_FLIGHT_EV_SWITCH,
1659*11996SThomas.Whitten@Sun.COM 		    BE_FLIGHT_ST_DUPLICATE);
1660*11996SThomas.Whitten@Sun.COM 		result = REP_PROTOCOL_SUCCESS;
1661*11996SThomas.Whitten@Sun.COM 		goto errout;
1662*11996SThomas.Whitten@Sun.COM 	}
1663*11996SThomas.Whitten@Sun.COM 
1664*11996SThomas.Whitten@Sun.COM 	result = backend_copy_repository(be->be_path, dst, dir);
16656035Sstevep 	if (result != REP_PROTOCOL_SUCCESS) {
16666035Sstevep 		goto errout;
16676035Sstevep 	}
16686035Sstevep 
16696035Sstevep 	/*
16706035Sstevep 	 * Do the backend sanity check and switch
16716035Sstevep 	 */
16726035Sstevep 	new = sqlite_open(dst, 0600, &errp);
16736035Sstevep 	if (new != NULL) {
16746035Sstevep 		/*
16756035Sstevep 		 * Sanity check
16766035Sstevep 		 */
16776035Sstevep 		if (backend_switch_check(new, &errp) == 0) {
16786035Sstevep 			free((char *)be->be_path);
16796035Sstevep 			be->be_path = strdup(dst);
16806035Sstevep 			if (be->be_path == NULL) {
16816035Sstevep 				configd_critical(
16826035Sstevep 				    "Backend switch failed: strdup %s: %s\n",
16836035Sstevep 				    dst, strerror(errno));
16846035Sstevep 				result = REP_PROTOCOL_FAIL_NO_RESOURCES;
16856035Sstevep 				sqlite_close(new);
16866035Sstevep 			} else {
16876035Sstevep 				sqlite_close(be->be_db);
16886035Sstevep 				be->be_db = new;
1689*11996SThomas.Whitten@Sun.COM 				if (dir) {
1690*11996SThomas.Whitten@Sun.COM 					/* We're back on permanent storage. */
1691*11996SThomas.Whitten@Sun.COM 					be->be_ppath = NULL;
1692*11996SThomas.Whitten@Sun.COM 				} else {
1693*11996SThomas.Whitten@Sun.COM 					/*
1694*11996SThomas.Whitten@Sun.COM 					 * Repository is now on volatile
1695*11996SThomas.Whitten@Sun.COM 					 * storage.  Save the location of
1696*11996SThomas.Whitten@Sun.COM 					 * the persistent repository.
1697*11996SThomas.Whitten@Sun.COM 					 */
1698*11996SThomas.Whitten@Sun.COM 					be->be_ppath = REPOSITORY_DB;
1699*11996SThomas.Whitten@Sun.COM 				}
17006035Sstevep 			}
17016035Sstevep 		} else {
17026035Sstevep 			configd_critical(
17036035Sstevep 			    "Backend switch failed: integrity check %s: %s\n",
17046035Sstevep 			    dst, errp);
17056035Sstevep 			result = REP_PROTOCOL_FAIL_BACKEND_ACCESS;
17066035Sstevep 		}
17076035Sstevep 	} else {
17086035Sstevep 		configd_critical("Backend switch failed: sqlite_open %s: %s\n",
17096035Sstevep 		    dst, errp);
17106035Sstevep 		result = REP_PROTOCOL_FAIL_BACKEND_ACCESS;
17116035Sstevep 	}
17126035Sstevep 
17136035Sstevep errout:
1714*11996SThomas.Whitten@Sun.COM 	if (result == REP_PROTOCOL_SUCCESS) {
1715*11996SThomas.Whitten@Sun.COM 		flight_recorder_event(BE_FLIGHT_EV_SWITCH,
1716*11996SThomas.Whitten@Sun.COM 		    BE_FLIGHT_ST_SUCCESS);
1717*11996SThomas.Whitten@Sun.COM 	} else {
1718*11996SThomas.Whitten@Sun.COM 		flight_recorder_event(BE_FLIGHT_EV_SWITCH, BE_FLIGHT_ST_FAIL);
1719*11996SThomas.Whitten@Sun.COM 	}
17206035Sstevep 	backend_unlock(be);
17216035Sstevep 	return (result);
17226035Sstevep }
17236035Sstevep 
17246035Sstevep /*
17256035Sstevep  * This routine is called to attempt the recovery of
17266035Sstevep  * the most recent valid repository if possible when configd
17276035Sstevep  * is restarted for some reasons or when system crashes
17286035Sstevep  * during the switch operation.  The repository databases
17296035Sstevep  * referenced here are indicators of successful switch
17306035Sstevep  * operations.
17316035Sstevep  */
1732*11996SThomas.Whitten@Sun.COM static backend_switch_results_t
backend_switch_recovery(void)17336035Sstevep backend_switch_recovery(void)
17346035Sstevep {
17356035Sstevep 	const char *fast_db = FAST_REPOSITORY_DB;
1736*11996SThomas.Whitten@Sun.COM 	char *errp = NULL;
17376035Sstevep 	struct stat s_buf;
17386035Sstevep 	struct sqlite *be_db;
1739*11996SThomas.Whitten@Sun.COM 	int r;
1740*11996SThomas.Whitten@Sun.COM 	backend_switch_results_t res = BACKEND_SWITCH_OK;
17416035Sstevep 
17426035Sstevep 	/*
17436035Sstevep 	 * A good transient db containing most recent data can
1744*11996SThomas.Whitten@Sun.COM 	 * exist if svc.configd crashes during the
17456035Sstevep 	 * switch operation.  If that is the case, check its
17466035Sstevep 	 * integrity and use it.
17476035Sstevep 	 */
17486035Sstevep 	if (stat(fast_db, &s_buf) < 0) {
1749*11996SThomas.Whitten@Sun.COM 		return (BACKEND_SWITCH_OK);
1750*11996SThomas.Whitten@Sun.COM 	}
1751*11996SThomas.Whitten@Sun.COM 
1752*11996SThomas.Whitten@Sun.COM 	/* Determine if persistent repository is read-only */
1753*11996SThomas.Whitten@Sun.COM 	be_db = sqlite_open(REPOSITORY_DB, 0600, &errp);
1754*11996SThomas.Whitten@Sun.COM 	if (be_db == NULL) {
1755*11996SThomas.Whitten@Sun.COM 		configd_critical("Unable to open \"%s\".  %s\n",
1756*11996SThomas.Whitten@Sun.COM 		    REPOSITORY_DB, errp == NULL ? "" : errp);
1757*11996SThomas.Whitten@Sun.COM 		free(errp);
1758*11996SThomas.Whitten@Sun.COM 		return (BACKEND_SWITCH_FATAL);
1759*11996SThomas.Whitten@Sun.COM 	}
1760*11996SThomas.Whitten@Sun.COM 	r = backend_is_readonly(be_db, REPOSITORY_DB);
1761*11996SThomas.Whitten@Sun.COM 	sqlite_close(be_db);
1762*11996SThomas.Whitten@Sun.COM 	if (r != SQLITE_OK) {
1763*11996SThomas.Whitten@Sun.COM 		if (r == SQLITE_READONLY) {
1764*11996SThomas.Whitten@Sun.COM 			return (BACKEND_SWITCH_RO);
1765*11996SThomas.Whitten@Sun.COM 		}
1766*11996SThomas.Whitten@Sun.COM 		return (BACKEND_SWITCH_FATAL);
17676035Sstevep 	}
17686035Sstevep 
17696035Sstevep 	/*
17706035Sstevep 	 * Do sanity check on the db
17716035Sstevep 	 */
17726035Sstevep 	be_db = sqlite_open(fast_db, 0600, &errp);
17736035Sstevep 
17746035Sstevep 	if (be_db != NULL) {
1775*11996SThomas.Whitten@Sun.COM 		if (backend_switch_check(be_db, &errp) == 0) {
1776*11996SThomas.Whitten@Sun.COM 			if (backend_copy_repository(fast_db,
1777*11996SThomas.Whitten@Sun.COM 			    REPOSITORY_DB, 1) != REP_PROTOCOL_SUCCESS) {
1778*11996SThomas.Whitten@Sun.COM 				res = BACKEND_SWITCH_FATAL;
1779*11996SThomas.Whitten@Sun.COM 			}
1780*11996SThomas.Whitten@Sun.COM 		}
1781*11996SThomas.Whitten@Sun.COM 		sqlite_close(be_db);
17826035Sstevep 	}
1783*11996SThomas.Whitten@Sun.COM 	free(errp);
1784*11996SThomas.Whitten@Sun.COM 
1785*11996SThomas.Whitten@Sun.COM 	/*
1786*11996SThomas.Whitten@Sun.COM 	 * If we get to this point, the fast_db has either been copied or
1787*11996SThomas.Whitten@Sun.COM 	 * it is useless.  Either way, get rid of it.
1788*11996SThomas.Whitten@Sun.COM 	 */
17896035Sstevep 	(void) unlink(fast_db);
1790*11996SThomas.Whitten@Sun.COM 
1791*11996SThomas.Whitten@Sun.COM 	return (res);
17926035Sstevep }
17936035Sstevep 
17940Sstevel@tonic-gate /*ARGSUSED*/
17950Sstevel@tonic-gate static int
backend_integrity_callback(void * private,int narg,char ** vals,char ** cols)17960Sstevel@tonic-gate backend_integrity_callback(void *private, int narg, char **vals, char **cols)
17970Sstevel@tonic-gate {
17980Sstevel@tonic-gate 	char **out = private;
17990Sstevel@tonic-gate 	char *old = *out;
18000Sstevel@tonic-gate 	char *new;
18010Sstevel@tonic-gate 	const char *info;
18020Sstevel@tonic-gate 	size_t len;
18030Sstevel@tonic-gate 	int x;
18040Sstevel@tonic-gate 
18050Sstevel@tonic-gate 	for (x = 0; x < narg; x++) {
18060Sstevel@tonic-gate 		if ((info = vals[x]) != NULL &&
18070Sstevel@tonic-gate 		    strcmp(info, "ok") != 0) {
18080Sstevel@tonic-gate 			len = (old == NULL)? 0 : strlen(old);
18090Sstevel@tonic-gate 			len += strlen(info) + 2;	/* '\n' + '\0' */
18100Sstevel@tonic-gate 
18110Sstevel@tonic-gate 			new = realloc(old, len);
18120Sstevel@tonic-gate 			if (new == NULL)
18130Sstevel@tonic-gate 				return (BACKEND_CALLBACK_ABORT);
18140Sstevel@tonic-gate 			if (old == NULL)
18150Sstevel@tonic-gate 				new[0] = 0;
18160Sstevel@tonic-gate 			old = *out = new;
18170Sstevel@tonic-gate 			(void) strlcat(new, info, len);
18180Sstevel@tonic-gate 			(void) strlcat(new, "\n", len);
18190Sstevel@tonic-gate 		}
18200Sstevel@tonic-gate 	}
18210Sstevel@tonic-gate 	return (BACKEND_CALLBACK_CONTINUE);
18220Sstevel@tonic-gate }
18230Sstevel@tonic-gate 
18240Sstevel@tonic-gate #define	BACKEND_CREATE_LOCKED		-2
18250Sstevel@tonic-gate #define	BACKEND_CREATE_FAIL		-1
18260Sstevel@tonic-gate #define	BACKEND_CREATE_SUCCESS		0
18270Sstevel@tonic-gate #define	BACKEND_CREATE_READONLY		1
18280Sstevel@tonic-gate #define	BACKEND_CREATE_NEED_INIT	2
18290Sstevel@tonic-gate static int
backend_create(backend_type_t backend_id,const char * db_file,sqlite_backend_t ** bep)18300Sstevel@tonic-gate backend_create(backend_type_t backend_id, const char *db_file,
18310Sstevel@tonic-gate     sqlite_backend_t **bep)
18320Sstevel@tonic-gate {
18330Sstevel@tonic-gate 	char *errp;
18340Sstevel@tonic-gate 	char *integrity_results = NULL;
18350Sstevel@tonic-gate 	sqlite_backend_t *be;
18360Sstevel@tonic-gate 	int r;
18370Sstevel@tonic-gate 	uint32_t val = -1UL;
18380Sstevel@tonic-gate 	struct run_single_int_info info;
18390Sstevel@tonic-gate 	int fd;
18400Sstevel@tonic-gate 
18410Sstevel@tonic-gate 	assert(backend_id >= 0 && backend_id < BACKEND_TYPE_TOTAL);
18420Sstevel@tonic-gate 
18430Sstevel@tonic-gate 	be = &be_info[backend_id];
18447128Samaguire 
18450Sstevel@tonic-gate 	assert(be->be_db == NULL);
18460Sstevel@tonic-gate 
18470Sstevel@tonic-gate 	(void) pthread_mutex_init(&be->be_lock, NULL);
18480Sstevel@tonic-gate 	(void) pthread_mutex_lock(&be->be_lock);
18490Sstevel@tonic-gate 
18500Sstevel@tonic-gate 	be->be_type = backend_id;
18510Sstevel@tonic-gate 	be->be_path = strdup(db_file);
18520Sstevel@tonic-gate 	if (be->be_path == NULL) {
18530Sstevel@tonic-gate 		perror("malloc");
18540Sstevel@tonic-gate 		goto fail;
18550Sstevel@tonic-gate 	}
18560Sstevel@tonic-gate 
18570Sstevel@tonic-gate 	be->be_db = sqlite_open(be->be_path, 0600, &errp);
18580Sstevel@tonic-gate 
18590Sstevel@tonic-gate 	if (be->be_db == NULL) {
18600Sstevel@tonic-gate 		if (strstr(errp, "out of memory") != NULL) {
18610Sstevel@tonic-gate 			configd_critical("%s: %s\n", db_file, errp);
18620Sstevel@tonic-gate 			free(errp);
18630Sstevel@tonic-gate 
18640Sstevel@tonic-gate 			goto fail;
18650Sstevel@tonic-gate 		}
18660Sstevel@tonic-gate 
18670Sstevel@tonic-gate 		/* report it as an integrity failure */
18680Sstevel@tonic-gate 		integrity_results = errp;
18690Sstevel@tonic-gate 		errp = NULL;
18700Sstevel@tonic-gate 		goto integrity_fail;
18710Sstevel@tonic-gate 	}
18720Sstevel@tonic-gate 
18730Sstevel@tonic-gate 	/*
18740Sstevel@tonic-gate 	 * check if we are inited and of the correct schema version
18750Sstevel@tonic-gate 	 *
18760Sstevel@tonic-gate 	 */
18770Sstevel@tonic-gate 	info.rs_out = &val;
18780Sstevel@tonic-gate 	info.rs_result = REP_PROTOCOL_FAIL_NOT_FOUND;
18790Sstevel@tonic-gate 
18800Sstevel@tonic-gate 	r = sqlite_exec(be->be_db, "SELECT schema_version FROM schema_version;",
18810Sstevel@tonic-gate 	    run_single_int_callback, &info, &errp);
18820Sstevel@tonic-gate 	if (r == SQLITE_ERROR &&
18830Sstevel@tonic-gate 	    strcmp("no such table: schema_version", errp) == 0) {
18840Sstevel@tonic-gate 		free(errp);
18850Sstevel@tonic-gate 		/*
18860Sstevel@tonic-gate 		 * Could be an empty repository, could be pre-schema_version
18870Sstevel@tonic-gate 		 * schema.  Check for id_tbl, which has always been there.
18880Sstevel@tonic-gate 		 */
18890Sstevel@tonic-gate 		r = sqlite_exec(be->be_db, "SELECT count() FROM id_tbl;",
18900Sstevel@tonic-gate 		    NULL, NULL, &errp);
18910Sstevel@tonic-gate 		if (r == SQLITE_ERROR &&
18920Sstevel@tonic-gate 		    strcmp("no such table: id_tbl", errp) == 0) {
18930Sstevel@tonic-gate 			free(errp);
18940Sstevel@tonic-gate 			*bep = be;
18950Sstevel@tonic-gate 			return (BACKEND_CREATE_NEED_INIT);
18960Sstevel@tonic-gate 		}
18970Sstevel@tonic-gate 
18980Sstevel@tonic-gate 		configd_critical("%s: schema version mismatch\n", db_file);
18990Sstevel@tonic-gate 		goto fail;
19000Sstevel@tonic-gate 	}
19010Sstevel@tonic-gate 	if (r == SQLITE_BUSY || r == SQLITE_LOCKED) {
19020Sstevel@tonic-gate 		free(errp);
19030Sstevel@tonic-gate 		*bep = NULL;
19040Sstevel@tonic-gate 		backend_destroy(be);
19050Sstevel@tonic-gate 		return (BACKEND_CREATE_LOCKED);
19060Sstevel@tonic-gate 	}
19070Sstevel@tonic-gate 	if (r == SQLITE_OK) {
19080Sstevel@tonic-gate 		if (info.rs_result == REP_PROTOCOL_FAIL_NOT_FOUND ||
19090Sstevel@tonic-gate 		    val != BACKEND_SCHEMA_VERSION) {
19100Sstevel@tonic-gate 			configd_critical("%s: schema version mismatch\n",
19110Sstevel@tonic-gate 			    db_file);
19120Sstevel@tonic-gate 			goto fail;
19130Sstevel@tonic-gate 		}
19140Sstevel@tonic-gate 	}
19150Sstevel@tonic-gate 
19160Sstevel@tonic-gate 	/*
19170Sstevel@tonic-gate 	 * pull in the whole database sequentially.
19180Sstevel@tonic-gate 	 */
19190Sstevel@tonic-gate 	if ((fd = open(db_file, O_RDONLY)) >= 0) {
19200Sstevel@tonic-gate 		size_t sz = 64 * 1024;
19210Sstevel@tonic-gate 		char *buffer = malloc(sz);
19220Sstevel@tonic-gate 		if (buffer != NULL) {
19230Sstevel@tonic-gate 			while (read(fd, buffer, sz) > 0)
19240Sstevel@tonic-gate 				;
19250Sstevel@tonic-gate 			free(buffer);
19260Sstevel@tonic-gate 		}
19270Sstevel@tonic-gate 		(void) close(fd);
19280Sstevel@tonic-gate 	}
19290Sstevel@tonic-gate 
19300Sstevel@tonic-gate 	/*
19310Sstevel@tonic-gate 	 * run an integrity check
19320Sstevel@tonic-gate 	 */
19330Sstevel@tonic-gate 	r = sqlite_exec(be->be_db, "PRAGMA integrity_check;",
19340Sstevel@tonic-gate 	    backend_integrity_callback, &integrity_results, &errp);
19350Sstevel@tonic-gate 
19360Sstevel@tonic-gate 	if (r == SQLITE_BUSY || r == SQLITE_LOCKED) {
19370Sstevel@tonic-gate 		free(errp);
19380Sstevel@tonic-gate 		*bep = NULL;
19390Sstevel@tonic-gate 		backend_destroy(be);
19400Sstevel@tonic-gate 		return (BACKEND_CREATE_LOCKED);
19410Sstevel@tonic-gate 	}
19420Sstevel@tonic-gate 	if (r == SQLITE_ABORT) {
19430Sstevel@tonic-gate 		free(errp);
19440Sstevel@tonic-gate 		errp = NULL;
19450Sstevel@tonic-gate 		integrity_results = "out of memory running integrity check\n";
19460Sstevel@tonic-gate 	} else if (r != SQLITE_OK && integrity_results == NULL) {
19470Sstevel@tonic-gate 		integrity_results = errp;
19480Sstevel@tonic-gate 		errp = NULL;
19490Sstevel@tonic-gate 	}
19500Sstevel@tonic-gate 
19510Sstevel@tonic-gate integrity_fail:
19520Sstevel@tonic-gate 	if (integrity_results != NULL) {
19530Sstevel@tonic-gate 		const char *fname = "/etc/svc/volatile/db_errors";
19540Sstevel@tonic-gate 		if ((fd = open(fname, O_CREAT|O_WRONLY|O_APPEND, 0600)) < 0) {
19550Sstevel@tonic-gate 			fname = NULL;
19560Sstevel@tonic-gate 		} else {
19570Sstevel@tonic-gate 			if (backend_fd_write(fd, "\n\n") < 0 ||
19580Sstevel@tonic-gate 			    backend_fd_write(fd, db_file) < 0 ||
19590Sstevel@tonic-gate 			    backend_fd_write(fd,
19600Sstevel@tonic-gate 			    ": PRAGMA integrity_check; failed.  Results:\n") <
19610Sstevel@tonic-gate 			    0 || backend_fd_write(fd, integrity_results) < 0 ||
19620Sstevel@tonic-gate 			    backend_fd_write(fd, "\n\n") < 0) {
19630Sstevel@tonic-gate 				fname = NULL;
19640Sstevel@tonic-gate 			}
19650Sstevel@tonic-gate 			(void) close(fd);
19660Sstevel@tonic-gate 		}
19670Sstevel@tonic-gate 
19680Sstevel@tonic-gate 		if (!is_main_repository ||
19690Sstevel@tonic-gate 		    backend_id == BACKEND_TYPE_NONPERSIST) {
19700Sstevel@tonic-gate 			if (fname != NULL)
19710Sstevel@tonic-gate 				configd_critical(
19720Sstevel@tonic-gate 				    "%s: integrity check failed. Details in "
19730Sstevel@tonic-gate 				    "%s\n", db_file, fname);
19740Sstevel@tonic-gate 			else
19750Sstevel@tonic-gate 				configd_critical(
19764931Spjung 				    "%s: integrity check failed.\n",
19770Sstevel@tonic-gate 				    db_file);
19780Sstevel@tonic-gate 		} else {
19790Sstevel@tonic-gate 			(void) fprintf(stderr,
19800Sstevel@tonic-gate "\n"
19810Sstevel@tonic-gate "svc.configd: smf(5) database integrity check of:\n"
19820Sstevel@tonic-gate "\n"
19830Sstevel@tonic-gate "    %s\n"
19840Sstevel@tonic-gate "\n"
19850Sstevel@tonic-gate "  failed. The database might be damaged or a media error might have\n"
19860Sstevel@tonic-gate "  prevented it from being verified.  Additional information useful to\n"
19870Sstevel@tonic-gate "  your service provider%s%s\n"
19880Sstevel@tonic-gate "\n"
19890Sstevel@tonic-gate "  The system will not be able to boot until you have restored a working\n"
19900Sstevel@tonic-gate "  database.  svc.startd(1M) will provide a sulogin(1M) prompt for recovery\n"
19910Sstevel@tonic-gate "  purposes.  The command:\n"
19920Sstevel@tonic-gate "\n"
19930Sstevel@tonic-gate "    /lib/svc/bin/restore_repository\n"
19940Sstevel@tonic-gate "\n"
19950Sstevel@tonic-gate "  can be run to restore a backup version of your repository.  See\n"
19960Sstevel@tonic-gate "  http://sun.com/msg/SMF-8000-MY for more information.\n"
19970Sstevel@tonic-gate "\n",
19984520Snw141292 			    db_file,
19994520Snw141292 			    (fname == NULL)? ":\n\n" : " is in:\n\n    ",
20004520Snw141292 			    (fname == NULL)? integrity_results : fname);
20010Sstevel@tonic-gate 		}
20020Sstevel@tonic-gate 		free(errp);
20030Sstevel@tonic-gate 		goto fail;
20040Sstevel@tonic-gate 	}
20050Sstevel@tonic-gate 
20060Sstevel@tonic-gate 	/*
20077128Samaguire 	 * Simply do check if backend has been upgraded.  We do not wish
20087128Samaguire 	 * to actually carry out upgrade here - the main repository may
20097128Samaguire 	 * not be writable at this point.  Actual upgrade is carried out
20107128Samaguire 	 * via backend_check_readonly().  This check is done so that
20117128Samaguire 	 * we determine repository state - upgraded or not - and then
20127128Samaguire 	 * the appropriate SELECT statement (value-ordered or not)
20137128Samaguire 	 * can be used when retrieving property values early in boot.
20147128Samaguire 	 */
20157128Samaguire 	if (backend_id == BACKEND_TYPE_NORMAL)
20167128Samaguire 		backend_check_upgrade(be, B_FALSE);
20177128Samaguire 	/*
20180Sstevel@tonic-gate 	 * check if we are writable
20190Sstevel@tonic-gate 	 */
2020407Sjwadams 	r = backend_is_readonly(be->be_db, be->be_path);
20210Sstevel@tonic-gate 
20220Sstevel@tonic-gate 	if (r == SQLITE_BUSY || r == SQLITE_LOCKED) {
20230Sstevel@tonic-gate 		free(errp);
20240Sstevel@tonic-gate 		*bep = NULL;
20250Sstevel@tonic-gate 		backend_destroy(be);
20260Sstevel@tonic-gate 		return (BACKEND_CREATE_LOCKED);
20270Sstevel@tonic-gate 	}
20280Sstevel@tonic-gate 	if (r != SQLITE_OK && r != SQLITE_FULL) {
20290Sstevel@tonic-gate 		free(errp);
20300Sstevel@tonic-gate 		be->be_readonly = 1;
20310Sstevel@tonic-gate 		*bep = be;
20320Sstevel@tonic-gate 		return (BACKEND_CREATE_READONLY);
20330Sstevel@tonic-gate 	}
20347128Samaguire 
20350Sstevel@tonic-gate 	*bep = be;
20360Sstevel@tonic-gate 	return (BACKEND_CREATE_SUCCESS);
20370Sstevel@tonic-gate 
20380Sstevel@tonic-gate fail:
20390Sstevel@tonic-gate 	*bep = NULL;
20400Sstevel@tonic-gate 	backend_destroy(be);
20410Sstevel@tonic-gate 	return (BACKEND_CREATE_FAIL);
20420Sstevel@tonic-gate }
20430Sstevel@tonic-gate 
20440Sstevel@tonic-gate /*
20450Sstevel@tonic-gate  * (arg & -arg) is, through the magic of twos-complement arithmetic, the
20460Sstevel@tonic-gate  * lowest set bit in arg.
20470Sstevel@tonic-gate  */
20480Sstevel@tonic-gate static size_t
round_up_to_p2(size_t arg)20490Sstevel@tonic-gate round_up_to_p2(size_t arg)
20500Sstevel@tonic-gate {
20510Sstevel@tonic-gate 	/*
20520Sstevel@tonic-gate 	 * Don't allow a zero result.
20530Sstevel@tonic-gate 	 */
20540Sstevel@tonic-gate 	assert(arg > 0 && ((ssize_t)arg > 0));
20550Sstevel@tonic-gate 
20560Sstevel@tonic-gate 	while ((arg & (arg - 1)) != 0)
20570Sstevel@tonic-gate 		arg += (arg & -arg);
20580Sstevel@tonic-gate 
20590Sstevel@tonic-gate 	return (arg);
20600Sstevel@tonic-gate }
20610Sstevel@tonic-gate 
20620Sstevel@tonic-gate /*
20630Sstevel@tonic-gate  * Returns
20640Sstevel@tonic-gate  *   _NO_RESOURCES - out of memory
20650Sstevel@tonic-gate  *   _BACKEND_ACCESS - backend type t (other than _NORMAL) doesn't exist
20660Sstevel@tonic-gate  *   _DONE - callback aborted query
20670Sstevel@tonic-gate  *   _SUCCESS
20680Sstevel@tonic-gate  */
20690Sstevel@tonic-gate int
backend_run(backend_type_t t,backend_query_t * q,backend_run_callback_f * cb,void * data)20700Sstevel@tonic-gate backend_run(backend_type_t t, backend_query_t *q,
20710Sstevel@tonic-gate     backend_run_callback_f *cb, void *data)
20720Sstevel@tonic-gate {
20730Sstevel@tonic-gate 	char *errmsg = NULL;
20740Sstevel@tonic-gate 	int ret;
20750Sstevel@tonic-gate 	sqlite_backend_t *be;
20760Sstevel@tonic-gate 	hrtime_t ts, vts;
20770Sstevel@tonic-gate 
20780Sstevel@tonic-gate 	if (q == NULL || q->bq_buf == NULL)
20790Sstevel@tonic-gate 		return (REP_PROTOCOL_FAIL_NO_RESOURCES);
20800Sstevel@tonic-gate 
20810Sstevel@tonic-gate 	if ((ret = backend_lock(t, 0, &be)) != REP_PROTOCOL_SUCCESS)
20820Sstevel@tonic-gate 		return (ret);
20830Sstevel@tonic-gate 
20840Sstevel@tonic-gate 	ts = gethrtime();
20850Sstevel@tonic-gate 	vts = gethrvtime();
20860Sstevel@tonic-gate 	ret = sqlite_exec(be->be_db, q->bq_buf, cb, data, &errmsg);
20870Sstevel@tonic-gate 	UPDATE_TOTALS(be, bt_exec, ts, vts);
20880Sstevel@tonic-gate 	ret = backend_error(be, ret, errmsg);
20890Sstevel@tonic-gate 	backend_unlock(be);
20900Sstevel@tonic-gate 
20910Sstevel@tonic-gate 	return (ret);
20920Sstevel@tonic-gate }
20930Sstevel@tonic-gate 
20940Sstevel@tonic-gate /*
20950Sstevel@tonic-gate  * Starts a "read-only" transaction -- i.e., locks out writers as long
20960Sstevel@tonic-gate  * as it is active.
20970Sstevel@tonic-gate  *
20980Sstevel@tonic-gate  * Fails with
20990Sstevel@tonic-gate  *   _NO_RESOURCES - out of memory
21000Sstevel@tonic-gate  *
21010Sstevel@tonic-gate  * If t is not _NORMAL, can also fail with
21020Sstevel@tonic-gate  *   _BACKEND_ACCESS - backend does not exist
21030Sstevel@tonic-gate  *
21040Sstevel@tonic-gate  * If writable is true, can also fail with
21050Sstevel@tonic-gate  *   _BACKEND_READONLY
21060Sstevel@tonic-gate  */
21070Sstevel@tonic-gate static int
backend_tx_begin_common(backend_type_t t,backend_tx_t ** txp,int writable)21080Sstevel@tonic-gate backend_tx_begin_common(backend_type_t t, backend_tx_t **txp, int writable)
21090Sstevel@tonic-gate {
21100Sstevel@tonic-gate 	backend_tx_t *ret;
21110Sstevel@tonic-gate 	sqlite_backend_t *be;
21120Sstevel@tonic-gate 	int r;
21130Sstevel@tonic-gate 
21140Sstevel@tonic-gate 	*txp = NULL;
21150Sstevel@tonic-gate 
21160Sstevel@tonic-gate 	ret = uu_zalloc(sizeof (*ret));
21170Sstevel@tonic-gate 	if (ret == NULL)
21180Sstevel@tonic-gate 		return (REP_PROTOCOL_FAIL_NO_RESOURCES);
21190Sstevel@tonic-gate 
21200Sstevel@tonic-gate 	if ((r = backend_lock(t, writable, &be)) != REP_PROTOCOL_SUCCESS) {
21210Sstevel@tonic-gate 		uu_free(ret);
21220Sstevel@tonic-gate 		return (r);
21230Sstevel@tonic-gate 	}
21240Sstevel@tonic-gate 
21250Sstevel@tonic-gate 	ret->bt_be = be;
21260Sstevel@tonic-gate 	ret->bt_readonly = !writable;
21270Sstevel@tonic-gate 	ret->bt_type = t;
21280Sstevel@tonic-gate 	ret->bt_full = 0;
21290Sstevel@tonic-gate 
21300Sstevel@tonic-gate 	*txp = ret;
21310Sstevel@tonic-gate 	return (REP_PROTOCOL_SUCCESS);
21320Sstevel@tonic-gate }
21330Sstevel@tonic-gate 
21340Sstevel@tonic-gate int
backend_tx_begin_ro(backend_type_t t,backend_tx_t ** txp)21350Sstevel@tonic-gate backend_tx_begin_ro(backend_type_t t, backend_tx_t **txp)
21360Sstevel@tonic-gate {
21370Sstevel@tonic-gate 	return (backend_tx_begin_common(t, txp, 0));
21380Sstevel@tonic-gate }
21390Sstevel@tonic-gate 
21400Sstevel@tonic-gate static void
backend_tx_end(backend_tx_t * tx)21410Sstevel@tonic-gate backend_tx_end(backend_tx_t *tx)
21420Sstevel@tonic-gate {
21430Sstevel@tonic-gate 	sqlite_backend_t *be;
21440Sstevel@tonic-gate 
21450Sstevel@tonic-gate 	be = tx->bt_be;
21460Sstevel@tonic-gate 
21470Sstevel@tonic-gate 	if (tx->bt_full) {
21480Sstevel@tonic-gate 		struct sqlite *new;
21490Sstevel@tonic-gate 
21500Sstevel@tonic-gate 		/*
21510Sstevel@tonic-gate 		 * sqlite tends to be sticky with SQLITE_FULL, so we try
21520Sstevel@tonic-gate 		 * to get a fresh database handle if we got a FULL warning
21530Sstevel@tonic-gate 		 * along the way.  If that fails, no harm done.
21540Sstevel@tonic-gate 		 */
21550Sstevel@tonic-gate 		new = sqlite_open(be->be_path, 0600, NULL);
21560Sstevel@tonic-gate 		if (new != NULL) {
21570Sstevel@tonic-gate 			sqlite_close(be->be_db);
21580Sstevel@tonic-gate 			be->be_db = new;
21590Sstevel@tonic-gate 		}
21600Sstevel@tonic-gate 	}
21610Sstevel@tonic-gate 	backend_unlock(be);
21620Sstevel@tonic-gate 	tx->bt_be = NULL;
21630Sstevel@tonic-gate 	uu_free(tx);
21640Sstevel@tonic-gate }
21650Sstevel@tonic-gate 
21660Sstevel@tonic-gate void
backend_tx_end_ro(backend_tx_t * tx)21670Sstevel@tonic-gate backend_tx_end_ro(backend_tx_t *tx)
21680Sstevel@tonic-gate {
21690Sstevel@tonic-gate 	assert(tx->bt_readonly);
21700Sstevel@tonic-gate 	backend_tx_end(tx);
21710Sstevel@tonic-gate }
21720Sstevel@tonic-gate 
21730Sstevel@tonic-gate /*
21740Sstevel@tonic-gate  * Fails with
21750Sstevel@tonic-gate  *   _NO_RESOURCES - out of memory
21760Sstevel@tonic-gate  *   _BACKEND_ACCESS
21770Sstevel@tonic-gate  *   _BACKEND_READONLY
21780Sstevel@tonic-gate  */
21790Sstevel@tonic-gate int
backend_tx_begin(backend_type_t t,backend_tx_t ** txp)21800Sstevel@tonic-gate backend_tx_begin(backend_type_t t, backend_tx_t **txp)
21810Sstevel@tonic-gate {
21820Sstevel@tonic-gate 	int r;
21830Sstevel@tonic-gate 	char *errmsg;
21840Sstevel@tonic-gate 	hrtime_t ts, vts;
21850Sstevel@tonic-gate 
21860Sstevel@tonic-gate 	r = backend_tx_begin_common(t, txp, 1);
21870Sstevel@tonic-gate 	if (r != REP_PROTOCOL_SUCCESS)
21880Sstevel@tonic-gate 		return (r);
21890Sstevel@tonic-gate 
21900Sstevel@tonic-gate 	ts = gethrtime();
21910Sstevel@tonic-gate 	vts = gethrvtime();
21920Sstevel@tonic-gate 	r = sqlite_exec((*txp)->bt_be->be_db, "BEGIN TRANSACTION", NULL, NULL,
21930Sstevel@tonic-gate 	    &errmsg);
21940Sstevel@tonic-gate 	UPDATE_TOTALS((*txp)->bt_be, bt_exec, ts, vts);
21950Sstevel@tonic-gate 	if (r == SQLITE_FULL)
21960Sstevel@tonic-gate 		(*txp)->bt_full = 1;
21970Sstevel@tonic-gate 	r = backend_error((*txp)->bt_be, r, errmsg);
21980Sstevel@tonic-gate 
21990Sstevel@tonic-gate 	if (r != REP_PROTOCOL_SUCCESS) {
22000Sstevel@tonic-gate 		assert(r != REP_PROTOCOL_DONE);
22010Sstevel@tonic-gate 		(void) sqlite_exec((*txp)->bt_be->be_db,
22020Sstevel@tonic-gate 		    "ROLLBACK TRANSACTION", NULL, NULL, NULL);
22030Sstevel@tonic-gate 		backend_tx_end(*txp);
22040Sstevel@tonic-gate 		*txp = NULL;
22050Sstevel@tonic-gate 		return (r);
22060Sstevel@tonic-gate 	}
22070Sstevel@tonic-gate 
22080Sstevel@tonic-gate 	(*txp)->bt_readonly = 0;
22090Sstevel@tonic-gate 
22100Sstevel@tonic-gate 	return (REP_PROTOCOL_SUCCESS);
22110Sstevel@tonic-gate }
22120Sstevel@tonic-gate 
22130Sstevel@tonic-gate void
backend_tx_rollback(backend_tx_t * tx)22140Sstevel@tonic-gate backend_tx_rollback(backend_tx_t *tx)
22150Sstevel@tonic-gate {
22160Sstevel@tonic-gate 	int r;
22170Sstevel@tonic-gate 	char *errmsg;
22180Sstevel@tonic-gate 	sqlite_backend_t *be;
22190Sstevel@tonic-gate 	hrtime_t ts, vts;
22200Sstevel@tonic-gate 
22210Sstevel@tonic-gate 	assert(tx != NULL && tx->bt_be != NULL && !tx->bt_readonly);
22220Sstevel@tonic-gate 	be = tx->bt_be;
22230Sstevel@tonic-gate 
22240Sstevel@tonic-gate 	ts = gethrtime();
22250Sstevel@tonic-gate 	vts = gethrvtime();
22260Sstevel@tonic-gate 	r = sqlite_exec(be->be_db, "ROLLBACK TRANSACTION", NULL, NULL,
22270Sstevel@tonic-gate 	    &errmsg);
22280Sstevel@tonic-gate 	UPDATE_TOTALS(be, bt_exec, ts, vts);
22290Sstevel@tonic-gate 	if (r == SQLITE_FULL)
22300Sstevel@tonic-gate 		tx->bt_full = 1;
22310Sstevel@tonic-gate 	(void) backend_error(be, r, errmsg);
22320Sstevel@tonic-gate 
22330Sstevel@tonic-gate 	backend_tx_end(tx);
22340Sstevel@tonic-gate }
22350Sstevel@tonic-gate 
22360Sstevel@tonic-gate /*
22370Sstevel@tonic-gate  * Fails with
22380Sstevel@tonic-gate  *   _NO_RESOURCES - out of memory
22390Sstevel@tonic-gate  */
22400Sstevel@tonic-gate int
backend_tx_commit(backend_tx_t * tx)22410Sstevel@tonic-gate backend_tx_commit(backend_tx_t *tx)
22420Sstevel@tonic-gate {
22430Sstevel@tonic-gate 	int r, r2;
22440Sstevel@tonic-gate 	char *errmsg;
22450Sstevel@tonic-gate 	sqlite_backend_t *be;
22460Sstevel@tonic-gate 	hrtime_t ts, vts;
22470Sstevel@tonic-gate 
22480Sstevel@tonic-gate 	assert(tx != NULL && tx->bt_be != NULL && !tx->bt_readonly);
22490Sstevel@tonic-gate 	be = tx->bt_be;
22500Sstevel@tonic-gate 	ts = gethrtime();
22510Sstevel@tonic-gate 	vts = gethrvtime();
22520Sstevel@tonic-gate 	r = sqlite_exec(be->be_db, "COMMIT TRANSACTION", NULL, NULL,
22530Sstevel@tonic-gate 	    &errmsg);
22540Sstevel@tonic-gate 	UPDATE_TOTALS(be, bt_exec, ts, vts);
22550Sstevel@tonic-gate 	if (r == SQLITE_FULL)
22560Sstevel@tonic-gate 		tx->bt_full = 1;
22570Sstevel@tonic-gate 
22580Sstevel@tonic-gate 	r = backend_error(be, r, errmsg);
22590Sstevel@tonic-gate 	assert(r != REP_PROTOCOL_DONE);
22600Sstevel@tonic-gate 
22610Sstevel@tonic-gate 	if (r != REP_PROTOCOL_SUCCESS) {
22620Sstevel@tonic-gate 		r2 = sqlite_exec(be->be_db, "ROLLBACK TRANSACTION", NULL, NULL,
22630Sstevel@tonic-gate 		    &errmsg);
22640Sstevel@tonic-gate 		r2 = backend_error(be, r2, errmsg);
22650Sstevel@tonic-gate 		if (r2 != REP_PROTOCOL_SUCCESS)
22660Sstevel@tonic-gate 			backend_panic("cannot rollback failed commit");
22670Sstevel@tonic-gate 
22680Sstevel@tonic-gate 		backend_tx_end(tx);
22690Sstevel@tonic-gate 		return (r);
22700Sstevel@tonic-gate 	}
22710Sstevel@tonic-gate 	backend_tx_end(tx);
22720Sstevel@tonic-gate 	return (REP_PROTOCOL_SUCCESS);
22730Sstevel@tonic-gate }
22740Sstevel@tonic-gate 
22750Sstevel@tonic-gate static const char *
id_space_to_name(enum id_space id)22760Sstevel@tonic-gate id_space_to_name(enum id_space id)
22770Sstevel@tonic-gate {
22780Sstevel@tonic-gate 	switch (id) {
22790Sstevel@tonic-gate 	case BACKEND_ID_SERVICE_INSTANCE:
22800Sstevel@tonic-gate 		return ("SI");
22810Sstevel@tonic-gate 	case BACKEND_ID_PROPERTYGRP:
22820Sstevel@tonic-gate 		return ("PG");
22830Sstevel@tonic-gate 	case BACKEND_ID_GENERATION:
22840Sstevel@tonic-gate 		return ("GEN");
22850Sstevel@tonic-gate 	case BACKEND_ID_PROPERTY:
22860Sstevel@tonic-gate 		return ("PROP");
22870Sstevel@tonic-gate 	case BACKEND_ID_VALUE:
22880Sstevel@tonic-gate 		return ("VAL");
22890Sstevel@tonic-gate 	case BACKEND_ID_SNAPNAME:
22900Sstevel@tonic-gate 		return ("SNAME");
22910Sstevel@tonic-gate 	case BACKEND_ID_SNAPSHOT:
22920Sstevel@tonic-gate 		return ("SHOT");
22930Sstevel@tonic-gate 	case BACKEND_ID_SNAPLEVEL:
22940Sstevel@tonic-gate 		return ("SLVL");
22950Sstevel@tonic-gate 	default:
22960Sstevel@tonic-gate 		abort();
22970Sstevel@tonic-gate 		/*NOTREACHED*/
22980Sstevel@tonic-gate 	}
22990Sstevel@tonic-gate }
23000Sstevel@tonic-gate 
23010Sstevel@tonic-gate /*
23020Sstevel@tonic-gate  * Returns a new id or 0 if the id argument is invalid or the query fails.
23030Sstevel@tonic-gate  */
23040Sstevel@tonic-gate uint32_t
backend_new_id(backend_tx_t * tx,enum id_space id)23050Sstevel@tonic-gate backend_new_id(backend_tx_t *tx, enum id_space id)
23060Sstevel@tonic-gate {
23070Sstevel@tonic-gate 	struct run_single_int_info info;
23080Sstevel@tonic-gate 	uint32_t new_id = 0;
23090Sstevel@tonic-gate 	const char *name = id_space_to_name(id);
23100Sstevel@tonic-gate 	char *errmsg;
23110Sstevel@tonic-gate 	int ret;
23120Sstevel@tonic-gate 	sqlite_backend_t *be;
23130Sstevel@tonic-gate 	hrtime_t ts, vts;
23140Sstevel@tonic-gate 
23150Sstevel@tonic-gate 	assert(tx != NULL && tx->bt_be != NULL && !tx->bt_readonly);
23160Sstevel@tonic-gate 	be = tx->bt_be;
23170Sstevel@tonic-gate 
23180Sstevel@tonic-gate 	info.rs_out = &new_id;
23190Sstevel@tonic-gate 	info.rs_result = REP_PROTOCOL_FAIL_NOT_FOUND;
23200Sstevel@tonic-gate 
23210Sstevel@tonic-gate 	ts = gethrtime();
23220Sstevel@tonic-gate 	vts = gethrvtime();
23230Sstevel@tonic-gate 	ret = sqlite_exec_printf(be->be_db,
23240Sstevel@tonic-gate 	    "SELECT id_next FROM id_tbl WHERE (id_name = '%q');"
23250Sstevel@tonic-gate 	    "UPDATE id_tbl SET id_next = id_next + 1 WHERE (id_name = '%q');",
23260Sstevel@tonic-gate 	    run_single_int_callback, &info, &errmsg, name, name);
23270Sstevel@tonic-gate 	UPDATE_TOTALS(be, bt_exec, ts, vts);
23280Sstevel@tonic-gate 	if (ret == SQLITE_FULL)
23290Sstevel@tonic-gate 		tx->bt_full = 1;
23300Sstevel@tonic-gate 
23310Sstevel@tonic-gate 	ret = backend_error(be, ret, errmsg);
23320Sstevel@tonic-gate 
23330Sstevel@tonic-gate 	if (ret != REP_PROTOCOL_SUCCESS) {
23340Sstevel@tonic-gate 		return (0);
23350Sstevel@tonic-gate 	}
23360Sstevel@tonic-gate 
23370Sstevel@tonic-gate 	return (new_id);
23380Sstevel@tonic-gate }
23390Sstevel@tonic-gate 
23400Sstevel@tonic-gate /*
23410Sstevel@tonic-gate  * Returns
23420Sstevel@tonic-gate  *   _NO_RESOURCES - out of memory
23430Sstevel@tonic-gate  *   _DONE - callback aborted query
23440Sstevel@tonic-gate  *   _SUCCESS
23450Sstevel@tonic-gate  */
23460Sstevel@tonic-gate int
backend_tx_run(backend_tx_t * tx,backend_query_t * q,backend_run_callback_f * cb,void * data)23470Sstevel@tonic-gate backend_tx_run(backend_tx_t *tx, backend_query_t *q,
23480Sstevel@tonic-gate     backend_run_callback_f *cb, void *data)
23490Sstevel@tonic-gate {
23500Sstevel@tonic-gate 	char *errmsg = NULL;
23510Sstevel@tonic-gate 	int ret;
23520Sstevel@tonic-gate 	sqlite_backend_t *be;
23530Sstevel@tonic-gate 	hrtime_t ts, vts;
23540Sstevel@tonic-gate 
23550Sstevel@tonic-gate 	assert(tx != NULL && tx->bt_be != NULL);
23560Sstevel@tonic-gate 	be = tx->bt_be;
23570Sstevel@tonic-gate 
23580Sstevel@tonic-gate 	if (q == NULL || q->bq_buf == NULL)
23590Sstevel@tonic-gate 		return (REP_PROTOCOL_FAIL_NO_RESOURCES);
23600Sstevel@tonic-gate 
23610Sstevel@tonic-gate 	ts = gethrtime();
23620Sstevel@tonic-gate 	vts = gethrvtime();
23630Sstevel@tonic-gate 	ret = sqlite_exec(be->be_db, q->bq_buf, cb, data, &errmsg);
23640Sstevel@tonic-gate 	UPDATE_TOTALS(be, bt_exec, ts, vts);
23650Sstevel@tonic-gate 	if (ret == SQLITE_FULL)
23660Sstevel@tonic-gate 		tx->bt_full = 1;
23670Sstevel@tonic-gate 	ret = backend_error(be, ret, errmsg);
23680Sstevel@tonic-gate 
23690Sstevel@tonic-gate 	return (ret);
23700Sstevel@tonic-gate }
23710Sstevel@tonic-gate 
23720Sstevel@tonic-gate /*
23730Sstevel@tonic-gate  * Returns
23740Sstevel@tonic-gate  *   _NO_RESOURCES - out of memory
23750Sstevel@tonic-gate  *   _NOT_FOUND - the query returned no results
23760Sstevel@tonic-gate  *   _SUCCESS - the query returned a single integer
23770Sstevel@tonic-gate  */
23780Sstevel@tonic-gate int
backend_tx_run_single_int(backend_tx_t * tx,backend_query_t * q,uint32_t * buf)23790Sstevel@tonic-gate backend_tx_run_single_int(backend_tx_t *tx, backend_query_t *q, uint32_t *buf)
23800Sstevel@tonic-gate {
23810Sstevel@tonic-gate 	struct run_single_int_info info;
23820Sstevel@tonic-gate 	int ret;
23830Sstevel@tonic-gate 
23840Sstevel@tonic-gate 	info.rs_out = buf;
23850Sstevel@tonic-gate 	info.rs_result = REP_PROTOCOL_FAIL_NOT_FOUND;
23860Sstevel@tonic-gate 
23870Sstevel@tonic-gate 	ret = backend_tx_run(tx, q, run_single_int_callback, &info);
23880Sstevel@tonic-gate 	assert(ret != REP_PROTOCOL_DONE);
23890Sstevel@tonic-gate 
23900Sstevel@tonic-gate 	if (ret != REP_PROTOCOL_SUCCESS)
23910Sstevel@tonic-gate 		return (ret);
23920Sstevel@tonic-gate 
23930Sstevel@tonic-gate 	return (info.rs_result);
23940Sstevel@tonic-gate }
23950Sstevel@tonic-gate 
23960Sstevel@tonic-gate /*
23970Sstevel@tonic-gate  * Fails with
23980Sstevel@tonic-gate  *   _NO_RESOURCES - out of memory
23990Sstevel@tonic-gate  */
24000Sstevel@tonic-gate int
backend_tx_run_update(backend_tx_t * tx,const char * format,...)24010Sstevel@tonic-gate backend_tx_run_update(backend_tx_t *tx, const char *format, ...)
24020Sstevel@tonic-gate {
24030Sstevel@tonic-gate 	va_list a;
24040Sstevel@tonic-gate 	char *errmsg;
24050Sstevel@tonic-gate 	int ret;
24060Sstevel@tonic-gate 	sqlite_backend_t *be;
24070Sstevel@tonic-gate 	hrtime_t ts, vts;
24080Sstevel@tonic-gate 
24090Sstevel@tonic-gate 	assert(tx != NULL && tx->bt_be != NULL && !tx->bt_readonly);
24100Sstevel@tonic-gate 	be = tx->bt_be;
24110Sstevel@tonic-gate 
24120Sstevel@tonic-gate 	va_start(a, format);
24130Sstevel@tonic-gate 	ts = gethrtime();
24140Sstevel@tonic-gate 	vts = gethrvtime();
24150Sstevel@tonic-gate 	ret = sqlite_exec_vprintf(be->be_db, format, NULL, NULL, &errmsg, a);
24160Sstevel@tonic-gate 	UPDATE_TOTALS(be, bt_exec, ts, vts);
24170Sstevel@tonic-gate 	if (ret == SQLITE_FULL)
24180Sstevel@tonic-gate 		tx->bt_full = 1;
24190Sstevel@tonic-gate 	va_end(a);
24200Sstevel@tonic-gate 	ret = backend_error(be, ret, errmsg);
24210Sstevel@tonic-gate 	assert(ret != REP_PROTOCOL_DONE);
24220Sstevel@tonic-gate 
24230Sstevel@tonic-gate 	return (ret);
24240Sstevel@tonic-gate }
24250Sstevel@tonic-gate 
24260Sstevel@tonic-gate /*
24270Sstevel@tonic-gate  * returns REP_PROTOCOL_FAIL_NOT_FOUND if no changes occured
24280Sstevel@tonic-gate  */
24290Sstevel@tonic-gate int
backend_tx_run_update_changed(backend_tx_t * tx,const char * format,...)24300Sstevel@tonic-gate backend_tx_run_update_changed(backend_tx_t *tx, const char *format, ...)
24310Sstevel@tonic-gate {
24320Sstevel@tonic-gate 	va_list a;
24330Sstevel@tonic-gate 	char *errmsg;
24340Sstevel@tonic-gate 	int ret;
24350Sstevel@tonic-gate 	sqlite_backend_t *be;
24360Sstevel@tonic-gate 	hrtime_t ts, vts;
24370Sstevel@tonic-gate 
24380Sstevel@tonic-gate 	assert(tx != NULL && tx->bt_be != NULL && !tx->bt_readonly);
24390Sstevel@tonic-gate 	be = tx->bt_be;
24400Sstevel@tonic-gate 
24410Sstevel@tonic-gate 	va_start(a, format);
24420Sstevel@tonic-gate 	ts = gethrtime();
24430Sstevel@tonic-gate 	vts = gethrvtime();
24440Sstevel@tonic-gate 	ret = sqlite_exec_vprintf(be->be_db, format, NULL, NULL, &errmsg, a);
24450Sstevel@tonic-gate 	UPDATE_TOTALS(be, bt_exec, ts, vts);
24460Sstevel@tonic-gate 	if (ret == SQLITE_FULL)
24470Sstevel@tonic-gate 		tx->bt_full = 1;
24480Sstevel@tonic-gate 	va_end(a);
24490Sstevel@tonic-gate 
24500Sstevel@tonic-gate 	ret = backend_error(be, ret, errmsg);
24510Sstevel@tonic-gate 
24520Sstevel@tonic-gate 	return (ret);
24530Sstevel@tonic-gate }
24540Sstevel@tonic-gate 
24550Sstevel@tonic-gate #define	BACKEND_ADD_SCHEMA(be, file, tbls, idxs) \
24560Sstevel@tonic-gate 	(backend_add_schema((be), (file), \
24570Sstevel@tonic-gate 	    (tbls), sizeof (tbls) / sizeof (*(tbls)), \
24580Sstevel@tonic-gate 	    (idxs), sizeof (idxs) / sizeof (*(idxs))))
24590Sstevel@tonic-gate 
24600Sstevel@tonic-gate static int
backend_add_schema(sqlite_backend_t * be,const char * file,struct backend_tbl_info * tbls,int tbl_count,struct backend_idx_info * idxs,int idx_count)24610Sstevel@tonic-gate backend_add_schema(sqlite_backend_t *be, const char *file,
24620Sstevel@tonic-gate     struct backend_tbl_info *tbls, int tbl_count,
24630Sstevel@tonic-gate     struct backend_idx_info *idxs, int idx_count)
24640Sstevel@tonic-gate {
24650Sstevel@tonic-gate 	int i;
24660Sstevel@tonic-gate 	char *errmsg;
24670Sstevel@tonic-gate 	int ret;
24680Sstevel@tonic-gate 
24690Sstevel@tonic-gate 	/*
24700Sstevel@tonic-gate 	 * Create the tables.
24710Sstevel@tonic-gate 	 */
24720Sstevel@tonic-gate 	for (i = 0; i < tbl_count; i++) {
24730Sstevel@tonic-gate 		if (tbls[i].bti_name == NULL) {
24740Sstevel@tonic-gate 			assert(i + 1 == tbl_count);
24750Sstevel@tonic-gate 			break;
24760Sstevel@tonic-gate 		}
24770Sstevel@tonic-gate 		ret = sqlite_exec_printf(be->be_db,
24780Sstevel@tonic-gate 		    "CREATE TABLE %s (%s);\n",
24790Sstevel@tonic-gate 		    NULL, NULL, &errmsg, tbls[i].bti_name, tbls[i].bti_cols);
24800Sstevel@tonic-gate 
24810Sstevel@tonic-gate 		if (ret != SQLITE_OK) {
24820Sstevel@tonic-gate 			configd_critical(
24830Sstevel@tonic-gate 			    "%s: %s table creation fails: %s\n", file,
24840Sstevel@tonic-gate 			    tbls[i].bti_name, errmsg);
24850Sstevel@tonic-gate 			free(errmsg);
24860Sstevel@tonic-gate 			return (-1);
24870Sstevel@tonic-gate 		}
24880Sstevel@tonic-gate 	}
24890Sstevel@tonic-gate 
24900Sstevel@tonic-gate 	/*
24910Sstevel@tonic-gate 	 * Make indices on key tables and columns.
24920Sstevel@tonic-gate 	 */
24930Sstevel@tonic-gate 	for (i = 0; i < idx_count; i++) {
24940Sstevel@tonic-gate 		if (idxs[i].bxi_tbl == NULL) {
24950Sstevel@tonic-gate 			assert(i + 1 == idx_count);
24960Sstevel@tonic-gate 			break;
24970Sstevel@tonic-gate 		}
24980Sstevel@tonic-gate 
24990Sstevel@tonic-gate 		ret = sqlite_exec_printf(be->be_db,
25000Sstevel@tonic-gate 		    "CREATE INDEX %s_%s ON %s (%s);\n",
25010Sstevel@tonic-gate 		    NULL, NULL, &errmsg, idxs[i].bxi_tbl, idxs[i].bxi_idx,
25020Sstevel@tonic-gate 		    idxs[i].bxi_tbl, idxs[i].bxi_cols);
25030Sstevel@tonic-gate 
25040Sstevel@tonic-gate 		if (ret != SQLITE_OK) {
25050Sstevel@tonic-gate 			configd_critical(
25060Sstevel@tonic-gate 			    "%s: %s_%s index creation fails: %s\n", file,
25070Sstevel@tonic-gate 			    idxs[i].bxi_tbl, idxs[i].bxi_idx, errmsg);
25080Sstevel@tonic-gate 			free(errmsg);
25090Sstevel@tonic-gate 			return (-1);
25100Sstevel@tonic-gate 		}
25110Sstevel@tonic-gate 	}
25120Sstevel@tonic-gate 	return (0);
25130Sstevel@tonic-gate }
25140Sstevel@tonic-gate 
25150Sstevel@tonic-gate static int
backend_init_schema(sqlite_backend_t * be,const char * db_file,backend_type_t t)25160Sstevel@tonic-gate backend_init_schema(sqlite_backend_t *be, const char *db_file, backend_type_t t)
25170Sstevel@tonic-gate {
25180Sstevel@tonic-gate 	int i;
25190Sstevel@tonic-gate 	char *errmsg;
25200Sstevel@tonic-gate 	int ret;
25210Sstevel@tonic-gate 
25220Sstevel@tonic-gate 	assert(t == BACKEND_TYPE_NORMAL || t == BACKEND_TYPE_NONPERSIST);
25230Sstevel@tonic-gate 
25240Sstevel@tonic-gate 	if (t == BACKEND_TYPE_NORMAL) {
25250Sstevel@tonic-gate 		ret = BACKEND_ADD_SCHEMA(be, db_file, tbls_normal, idxs_normal);
25260Sstevel@tonic-gate 	} else if (t == BACKEND_TYPE_NONPERSIST) {
25270Sstevel@tonic-gate 		ret = BACKEND_ADD_SCHEMA(be, db_file, tbls_np, idxs_np);
25280Sstevel@tonic-gate 	} else {
25290Sstevel@tonic-gate 		abort();		/* can't happen */
25300Sstevel@tonic-gate 	}
25310Sstevel@tonic-gate 
25320Sstevel@tonic-gate 	if (ret < 0) {
25330Sstevel@tonic-gate 		return (ret);
25340Sstevel@tonic-gate 	}
25350Sstevel@tonic-gate 
25360Sstevel@tonic-gate 	ret = BACKEND_ADD_SCHEMA(be, db_file, tbls_common, idxs_common);
25370Sstevel@tonic-gate 	if (ret < 0) {
25380Sstevel@tonic-gate 		return (ret);
25390Sstevel@tonic-gate 	}
25400Sstevel@tonic-gate 
25410Sstevel@tonic-gate 	/*
25420Sstevel@tonic-gate 	 * Add the schema version to the table
25430Sstevel@tonic-gate 	 */
25440Sstevel@tonic-gate 	ret = sqlite_exec_printf(be->be_db,
25450Sstevel@tonic-gate 	    "INSERT INTO schema_version (schema_version) VALUES (%d)",
25460Sstevel@tonic-gate 	    NULL, NULL, &errmsg, BACKEND_SCHEMA_VERSION);
25470Sstevel@tonic-gate 	if (ret != SQLITE_OK) {
25480Sstevel@tonic-gate 		configd_critical(
25490Sstevel@tonic-gate 		    "setting schema version fails: %s\n", errmsg);
25500Sstevel@tonic-gate 		free(errmsg);
25510Sstevel@tonic-gate 	}
25520Sstevel@tonic-gate 
25530Sstevel@tonic-gate 	/*
25540Sstevel@tonic-gate 	 * Populate id_tbl with initial IDs.
25550Sstevel@tonic-gate 	 */
25560Sstevel@tonic-gate 	for (i = 0; i < BACKEND_ID_INVALID; i++) {
25570Sstevel@tonic-gate 		const char *name = id_space_to_name(i);
25580Sstevel@tonic-gate 
25590Sstevel@tonic-gate 		ret = sqlite_exec_printf(be->be_db,
25600Sstevel@tonic-gate 		    "INSERT INTO id_tbl (id_name, id_next) "
25610Sstevel@tonic-gate 		    "VALUES ('%q', %d);", NULL, NULL, &errmsg, name, 1);
25620Sstevel@tonic-gate 		if (ret != SQLITE_OK) {
25630Sstevel@tonic-gate 			configd_critical(
25640Sstevel@tonic-gate 			    "id insertion for %s fails: %s\n", name, errmsg);
25650Sstevel@tonic-gate 			free(errmsg);
25660Sstevel@tonic-gate 			return (-1);
25670Sstevel@tonic-gate 		}
25680Sstevel@tonic-gate 	}
25690Sstevel@tonic-gate 	/*
25700Sstevel@tonic-gate 	 * Set the persistance of the database.  The normal database is marked
25710Sstevel@tonic-gate 	 * "synchronous", so that all writes are synchronized to stable storage
25720Sstevel@tonic-gate 	 * before proceeding.
25730Sstevel@tonic-gate 	 */
25740Sstevel@tonic-gate 	ret = sqlite_exec_printf(be->be_db,
25750Sstevel@tonic-gate 	    "PRAGMA default_synchronous = %s; PRAGMA synchronous = %s;",
25760Sstevel@tonic-gate 	    NULL, NULL, &errmsg,
25770Sstevel@tonic-gate 	    (t == BACKEND_TYPE_NORMAL)? "ON" : "OFF",
25780Sstevel@tonic-gate 	    (t == BACKEND_TYPE_NORMAL)? "ON" : "OFF");
25790Sstevel@tonic-gate 	if (ret != SQLITE_OK) {
25800Sstevel@tonic-gate 		configd_critical("pragma setting fails: %s\n", errmsg);
25810Sstevel@tonic-gate 		free(errmsg);
25820Sstevel@tonic-gate 		return (-1);
25830Sstevel@tonic-gate 	}
25840Sstevel@tonic-gate 
25850Sstevel@tonic-gate 	return (0);
25860Sstevel@tonic-gate }
25870Sstevel@tonic-gate 
25880Sstevel@tonic-gate int
backend_init(const char * db_file,const char * npdb_file,int have_np)25890Sstevel@tonic-gate backend_init(const char *db_file, const char *npdb_file, int have_np)
25900Sstevel@tonic-gate {
25910Sstevel@tonic-gate 	sqlite_backend_t *be;
2592*11996SThomas.Whitten@Sun.COM 	char *errp;
2593*11996SThomas.Whitten@Sun.COM 	struct sqlite *fast_db;
25940Sstevel@tonic-gate 	int r;
2595*11996SThomas.Whitten@Sun.COM 	backend_switch_results_t switch_result = BACKEND_SWITCH_OK;
25960Sstevel@tonic-gate 	int writable_persist = 1;
25970Sstevel@tonic-gate 
25980Sstevel@tonic-gate 	/* set up our temporary directory */
25990Sstevel@tonic-gate 	sqlite_temp_directory = "/etc/svc/volatile";
26000Sstevel@tonic-gate 
26010Sstevel@tonic-gate 	if (strcmp(SQLITE_VERSION, sqlite_version) != 0) {
26020Sstevel@tonic-gate 		configd_critical("Mismatched link!  (%s should be %s)\n",
26030Sstevel@tonic-gate 		    sqlite_version, SQLITE_VERSION);
26040Sstevel@tonic-gate 		return (CONFIGD_EXIT_DATABASE_INIT_FAILED);
26050Sstevel@tonic-gate 	}
26066035Sstevep 
26070Sstevel@tonic-gate 	if (db_file == NULL)
26080Sstevel@tonic-gate 		db_file = REPOSITORY_DB;
26095777Stw21770 	if (strcmp(db_file, REPOSITORY_DB) != 0) {
26105777Stw21770 		is_main_repository = 0;
26115777Stw21770 	}
26120Sstevel@tonic-gate 
2613*11996SThomas.Whitten@Sun.COM 	/*
2614*11996SThomas.Whitten@Sun.COM 	 * If the svc.configd crashed, there might be a leftover transient
2615*11996SThomas.Whitten@Sun.COM 	 * database at FAST_REPOSITORY_DB,which contains useful
2616*11996SThomas.Whitten@Sun.COM 	 * information.  Both early manifest import and late manifest
2617*11996SThomas.Whitten@Sun.COM 	 * import use svcadm to copy the repository to FAST_REPOSITORY_DB.
2618*11996SThomas.Whitten@Sun.COM 	 * One reason for doing this is that it improves the performance of
2619*11996SThomas.Whitten@Sun.COM 	 * manifest import.  The other reason is that the repository may be
2620*11996SThomas.Whitten@Sun.COM 	 * on read-only root in the case of early manifest import.
2621*11996SThomas.Whitten@Sun.COM 	 *
2622*11996SThomas.Whitten@Sun.COM 	 * If FAST_REPOSITORY_DB exists, it is an indication that
2623*11996SThomas.Whitten@Sun.COM 	 * svc.configd has been restarted for some reason.  Since we have
2624*11996SThomas.Whitten@Sun.COM 	 * no way of knowing where we are in the boot process, the safe
2625*11996SThomas.Whitten@Sun.COM 	 * thing to do is to move the repository back to it's non-transient
2626*11996SThomas.Whitten@Sun.COM 	 * location, REPOSITORY_DB.  This may slow manifest import
2627*11996SThomas.Whitten@Sun.COM 	 * performance, but it avoids the problem of missing the command to
2628*11996SThomas.Whitten@Sun.COM 	 * move the repository to permanent storage.
2629*11996SThomas.Whitten@Sun.COM 	 *
2630*11996SThomas.Whitten@Sun.COM 	 * There is a caveat, though.  If root is read-only, we'll need to
2631*11996SThomas.Whitten@Sun.COM 	 * leave the repository at FAST_REPOSITORY_DB.  If root is
2632*11996SThomas.Whitten@Sun.COM 	 * read-only, late manifest import has not yet run, so it will move
2633*11996SThomas.Whitten@Sun.COM 	 * the repository back to permanent storage when it runs.
2634*11996SThomas.Whitten@Sun.COM 	 */
2635*11996SThomas.Whitten@Sun.COM 	if (is_main_repository)
2636*11996SThomas.Whitten@Sun.COM 		switch_result = backend_switch_recovery();
2637*11996SThomas.Whitten@Sun.COM 
26380Sstevel@tonic-gate 	r = backend_create(BACKEND_TYPE_NORMAL, db_file, &be);
26390Sstevel@tonic-gate 	switch (r) {
26400Sstevel@tonic-gate 	case BACKEND_CREATE_FAIL:
26410Sstevel@tonic-gate 		return (CONFIGD_EXIT_DATABASE_INIT_FAILED);
26420Sstevel@tonic-gate 	case BACKEND_CREATE_LOCKED:
26430Sstevel@tonic-gate 		return (CONFIGD_EXIT_DATABASE_LOCKED);
26440Sstevel@tonic-gate 	case BACKEND_CREATE_SUCCESS:
26450Sstevel@tonic-gate 		break;		/* success */
26460Sstevel@tonic-gate 	case BACKEND_CREATE_READONLY:
26470Sstevel@tonic-gate 		writable_persist = 0;
26480Sstevel@tonic-gate 		break;
26490Sstevel@tonic-gate 	case BACKEND_CREATE_NEED_INIT:
26500Sstevel@tonic-gate 		if (backend_init_schema(be, db_file, BACKEND_TYPE_NORMAL)) {
26510Sstevel@tonic-gate 			backend_destroy(be);
26520Sstevel@tonic-gate 			return (CONFIGD_EXIT_DATABASE_INIT_FAILED);
26530Sstevel@tonic-gate 		}
26540Sstevel@tonic-gate 		break;
26550Sstevel@tonic-gate 	default:
26560Sstevel@tonic-gate 		abort();
26570Sstevel@tonic-gate 		/*NOTREACHED*/
26580Sstevel@tonic-gate 	}
26590Sstevel@tonic-gate 	backend_create_finish(BACKEND_TYPE_NORMAL, be);
2660*11996SThomas.Whitten@Sun.COM 	flight_recorder_event(BE_FLIGHT_EV_REPO_CREATE,
2661*11996SThomas.Whitten@Sun.COM 	    writable_persist == 1 ? BE_FLIGHT_ST_RW : BE_FLIGHT_ST_RO);
2662*11996SThomas.Whitten@Sun.COM 	/*
2663*11996SThomas.Whitten@Sun.COM 	 * If there was a transient repository that could not be copied
2664*11996SThomas.Whitten@Sun.COM 	 * back because the root file system was read-only, switch over to
2665*11996SThomas.Whitten@Sun.COM 	 * using the transient repository.
2666*11996SThomas.Whitten@Sun.COM 	 */
2667*11996SThomas.Whitten@Sun.COM 	if (switch_result == BACKEND_SWITCH_RO) {
2668*11996SThomas.Whitten@Sun.COM 		char *db_name_copy = NULL;
2669*11996SThomas.Whitten@Sun.COM 
2670*11996SThomas.Whitten@Sun.COM 		fast_db = sqlite_open(FAST_REPOSITORY_DB, 0600, &errp);
2671*11996SThomas.Whitten@Sun.COM 		if (fast_db == NULL) {
2672*11996SThomas.Whitten@Sun.COM 			/* Can't open fast repository.  Stick with permanent. */
2673*11996SThomas.Whitten@Sun.COM 			configd_critical("Cannot open \"%s\".  %s\n",
2674*11996SThomas.Whitten@Sun.COM 			    FAST_REPOSITORY_DB, errp == NULL ? "" : errp);
2675*11996SThomas.Whitten@Sun.COM 			free(errp);
2676*11996SThomas.Whitten@Sun.COM 		} else {
2677*11996SThomas.Whitten@Sun.COM 			db_name_copy = strdup(FAST_REPOSITORY_DB);
2678*11996SThomas.Whitten@Sun.COM 			if (db_name_copy == NULL) {
2679*11996SThomas.Whitten@Sun.COM 				configd_critical("backend_init: out of "
2680*11996SThomas.Whitten@Sun.COM 				    "memory.\n");
2681*11996SThomas.Whitten@Sun.COM 				sqlite_close(fast_db);
2682*11996SThomas.Whitten@Sun.COM 				return (CONFIGD_EXIT_INIT_FAILED);
2683*11996SThomas.Whitten@Sun.COM 			} else {
2684*11996SThomas.Whitten@Sun.COM 				flight_recorder_event(
2685*11996SThomas.Whitten@Sun.COM 				    BE_FLIGHT_EV_LINGERING_FAST,
2686*11996SThomas.Whitten@Sun.COM 				    BE_FLIGHT_ST_RO);
2687*11996SThomas.Whitten@Sun.COM 				sqlite_close(be->be_db);
2688*11996SThomas.Whitten@Sun.COM 				be->be_db = fast_db;
2689*11996SThomas.Whitten@Sun.COM 				be->be_ppath = be->be_path;
2690*11996SThomas.Whitten@Sun.COM 				be->be_path = db_name_copy;
2691*11996SThomas.Whitten@Sun.COM 			}
2692*11996SThomas.Whitten@Sun.COM 		}
2693*11996SThomas.Whitten@Sun.COM 	}
26940Sstevel@tonic-gate 
26950Sstevel@tonic-gate 	if (have_np) {
26960Sstevel@tonic-gate 		if (npdb_file == NULL)
26970Sstevel@tonic-gate 			npdb_file = NONPERSIST_DB;
26980Sstevel@tonic-gate 
26990Sstevel@tonic-gate 		r = backend_create(BACKEND_TYPE_NONPERSIST, npdb_file, &be);
27000Sstevel@tonic-gate 		switch (r) {
27010Sstevel@tonic-gate 		case BACKEND_CREATE_SUCCESS:
27020Sstevel@tonic-gate 			break;		/* success */
27030Sstevel@tonic-gate 		case BACKEND_CREATE_FAIL:
27040Sstevel@tonic-gate 			return (CONFIGD_EXIT_DATABASE_INIT_FAILED);
27050Sstevel@tonic-gate 		case BACKEND_CREATE_LOCKED:
27060Sstevel@tonic-gate 			return (CONFIGD_EXIT_DATABASE_LOCKED);
27070Sstevel@tonic-gate 		case BACKEND_CREATE_READONLY:
27080Sstevel@tonic-gate 			configd_critical("%s: unable to write\n", npdb_file);
27090Sstevel@tonic-gate 			return (CONFIGD_EXIT_DATABASE_INIT_FAILED);
27100Sstevel@tonic-gate 		case BACKEND_CREATE_NEED_INIT:
27110Sstevel@tonic-gate 			if (backend_init_schema(be, db_file,
27120Sstevel@tonic-gate 			    BACKEND_TYPE_NONPERSIST)) {
27130Sstevel@tonic-gate 				backend_destroy(be);
27140Sstevel@tonic-gate 				return (CONFIGD_EXIT_DATABASE_INIT_FAILED);
27150Sstevel@tonic-gate 			}
27160Sstevel@tonic-gate 			break;
27170Sstevel@tonic-gate 		default:
27180Sstevel@tonic-gate 			abort();
27190Sstevel@tonic-gate 			/*NOTREACHED*/
27200Sstevel@tonic-gate 		}
27210Sstevel@tonic-gate 		backend_create_finish(BACKEND_TYPE_NONPERSIST, be);
27220Sstevel@tonic-gate 
2723*11996SThomas.Whitten@Sun.COM 		if (r != BACKEND_CREATE_NEED_INIT) {
2724*11996SThomas.Whitten@Sun.COM 			flight_recorder_event(BE_FLIGHT_EV_RESTART,
2725*11996SThomas.Whitten@Sun.COM 			    BE_FLIGHT_ST_INFO);
2726*11996SThomas.Whitten@Sun.COM 		}
2727*11996SThomas.Whitten@Sun.COM 
27280Sstevel@tonic-gate 		/*
27290Sstevel@tonic-gate 		 * If we started up with a writable filesystem, but the
2730*11996SThomas.Whitten@Sun.COM 		 * non-persistent database needed initialization, we are
2731*11996SThomas.Whitten@Sun.COM 		 * booting a non-global zone or a system with a writable
2732*11996SThomas.Whitten@Sun.COM 		 * root (ZFS), so do a backup.  Checking to see if the
2733*11996SThomas.Whitten@Sun.COM 		 * non-persistent database needed initialization also keeps
2734*11996SThomas.Whitten@Sun.COM 		 * us from making additional backups if configd gets
2735*11996SThomas.Whitten@Sun.COM 		 * restarted.
27360Sstevel@tonic-gate 		 */
27370Sstevel@tonic-gate 		if (r == BACKEND_CREATE_NEED_INIT && writable_persist &&
27380Sstevel@tonic-gate 		    backend_lock(BACKEND_TYPE_NORMAL, 0, &be) ==
27390Sstevel@tonic-gate 		    REP_PROTOCOL_SUCCESS) {
27400Sstevel@tonic-gate 			if (backend_create_backup_locked(be,
27410Sstevel@tonic-gate 			    REPOSITORY_BOOT_BACKUP) != REP_PROTOCOL_SUCCESS) {
27420Sstevel@tonic-gate 				configd_critical(
27430Sstevel@tonic-gate 				    "unable to create \"%s\" backup of "
27440Sstevel@tonic-gate 				    "\"%s\"\n", REPOSITORY_BOOT_BACKUP,
27450Sstevel@tonic-gate 				    be->be_path);
27460Sstevel@tonic-gate 			}
27470Sstevel@tonic-gate 			backend_unlock(be);
27480Sstevel@tonic-gate 		}
2749*11996SThomas.Whitten@Sun.COM 
2750*11996SThomas.Whitten@Sun.COM 		/*
2751*11996SThomas.Whitten@Sun.COM 		 * On the other hand if we started with a read-only file
2752*11996SThomas.Whitten@Sun.COM 		 * system and the non-persistent database needed
2753*11996SThomas.Whitten@Sun.COM 		 * initialization, then we need to take a checkpoint of the
2754*11996SThomas.Whitten@Sun.COM 		 * repository.  We grab the checkpoint now before Early
2755*11996SThomas.Whitten@Sun.COM 		 * Manifest Import starts modifying the repository.  Then
2756*11996SThomas.Whitten@Sun.COM 		 * when the file system becomes writable, the checkpoint
2757*11996SThomas.Whitten@Sun.COM 		 * can be used to create the boot time backup of the
2758*11996SThomas.Whitten@Sun.COM 		 * repository.  Checking that the non-persistent database
2759*11996SThomas.Whitten@Sun.COM 		 * needed initialization, keeps us from making additional
2760*11996SThomas.Whitten@Sun.COM 		 * checkpoints if configd gets restarted.
2761*11996SThomas.Whitten@Sun.COM 		 */
2762*11996SThomas.Whitten@Sun.COM 		if (r == BACKEND_CREATE_NEED_INIT && writable_persist == 0 &&
2763*11996SThomas.Whitten@Sun.COM 		    backend_lock(BACKEND_TYPE_NORMAL, 0, &be) ==
2764*11996SThomas.Whitten@Sun.COM 		    REP_PROTOCOL_SUCCESS) {
2765*11996SThomas.Whitten@Sun.COM 			r = backend_checkpoint_repository(be);
2766*11996SThomas.Whitten@Sun.COM 			if (r != REP_PROTOCOL_SUCCESS) {
2767*11996SThomas.Whitten@Sun.COM 				configd_critical("unable to create checkpoint "
2768*11996SThomas.Whitten@Sun.COM 				    "of \"%s\"\n", be->be_path);
2769*11996SThomas.Whitten@Sun.COM 			}
2770*11996SThomas.Whitten@Sun.COM 			backend_unlock(be);
2771*11996SThomas.Whitten@Sun.COM 		}
2772*11996SThomas.Whitten@Sun.COM 
2773*11996SThomas.Whitten@Sun.COM 		/*
2774*11996SThomas.Whitten@Sun.COM 		 * If the non-persistent database did not need
2775*11996SThomas.Whitten@Sun.COM 		 * initialization, svc.configd has been restarted.  See if
2776*11996SThomas.Whitten@Sun.COM 		 * the boot time checkpoint exists.  If it does, use it to
2777*11996SThomas.Whitten@Sun.COM 		 * make a backup if root is writable.
2778*11996SThomas.Whitten@Sun.COM 		 */
2779*11996SThomas.Whitten@Sun.COM 		if (r != BACKEND_CREATE_NEED_INIT &&
2780*11996SThomas.Whitten@Sun.COM 		    backend_lock(BACKEND_TYPE_NORMAL, 0, &be) ==
2781*11996SThomas.Whitten@Sun.COM 		    REP_PROTOCOL_SUCCESS) {
2782*11996SThomas.Whitten@Sun.COM 			struct stat sb;
2783*11996SThomas.Whitten@Sun.COM 
2784*11996SThomas.Whitten@Sun.COM 			if ((stat(REPOSITORY_CHECKPOINT, &sb) == 0) &&
2785*11996SThomas.Whitten@Sun.COM 			    (sb.st_size > 0) && (sb.st_mode & S_IFREG)) {
2786*11996SThomas.Whitten@Sun.COM 				be->be_checkpoint = REPOSITORY_CHECKPOINT;
2787*11996SThomas.Whitten@Sun.COM 				flight_recorder_event(
2788*11996SThomas.Whitten@Sun.COM 				    BE_FLIGHT_EV_CHECKPOINT_EXISTS,
2789*11996SThomas.Whitten@Sun.COM 				    BE_FLIGHT_ST_INFO);
2790*11996SThomas.Whitten@Sun.COM 			}
2791*11996SThomas.Whitten@Sun.COM 
2792*11996SThomas.Whitten@Sun.COM 			/*
2793*11996SThomas.Whitten@Sun.COM 			 * If we have a checkpoint and root is writable,
2794*11996SThomas.Whitten@Sun.COM 			 * make the backup now.
2795*11996SThomas.Whitten@Sun.COM 			 */
2796*11996SThomas.Whitten@Sun.COM 			if (be->be_checkpoint && writable_persist) {
2797*11996SThomas.Whitten@Sun.COM 				if (backend_create_backup_locked(be,
2798*11996SThomas.Whitten@Sun.COM 				    REPOSITORY_BOOT_BACKUP) !=
2799*11996SThomas.Whitten@Sun.COM 				    REP_PROTOCOL_SUCCESS) {
2800*11996SThomas.Whitten@Sun.COM 					configd_critical(
2801*11996SThomas.Whitten@Sun.COM 					    "unable to create \"%s\" backup of "
2802*11996SThomas.Whitten@Sun.COM 					    "\"%s\"\n", REPOSITORY_BOOT_BACKUP,
2803*11996SThomas.Whitten@Sun.COM 					    be->be_path);
2804*11996SThomas.Whitten@Sun.COM 				}
2805*11996SThomas.Whitten@Sun.COM 			}
2806*11996SThomas.Whitten@Sun.COM 			backend_unlock(be);
2807*11996SThomas.Whitten@Sun.COM 		}
28080Sstevel@tonic-gate 	}
28097190Samaguire 
28107190Samaguire 	/*
28117190Samaguire 	 * If the persistent backend is writable at this point, upgrade it.
28127190Samaguire 	 * This can occur in a few cases, most notably on UFS roots if
28137190Samaguire 	 * we are operating on the backend from another root, as is the case
28147190Samaguire 	 * during alternate-root BFU.
28157190Samaguire 	 *
28167190Samaguire 	 * Otherwise, upgrade will occur via backend_check_readonly() when
28177190Samaguire 	 * the repository is re-opened read-write.
28187190Samaguire 	 */
28197190Samaguire 	if (writable_persist) {
28207190Samaguire 		r = backend_lock(BACKEND_TYPE_NORMAL, 1, &be);
28217190Samaguire 		assert(r == REP_PROTOCOL_SUCCESS);
28227190Samaguire 		backend_check_upgrade(be, B_TRUE);
28237190Samaguire 		backend_unlock(be);
28247190Samaguire 	}
28257190Samaguire 
28260Sstevel@tonic-gate 	return (CONFIGD_EXIT_OKAY);
28270Sstevel@tonic-gate }
28280Sstevel@tonic-gate 
28290Sstevel@tonic-gate /*
28300Sstevel@tonic-gate  * quiesce all database activity prior to exiting
28310Sstevel@tonic-gate  */
28320Sstevel@tonic-gate void
backend_fini(void)28330Sstevel@tonic-gate backend_fini(void)
28340Sstevel@tonic-gate {
28350Sstevel@tonic-gate 	sqlite_backend_t *be_normal, *be_np;
28360Sstevel@tonic-gate 
28370Sstevel@tonic-gate 	(void) backend_lock(BACKEND_TYPE_NORMAL, 1, &be_normal);
28380Sstevel@tonic-gate 	(void) backend_lock(BACKEND_TYPE_NONPERSIST, 1, &be_np);
28390Sstevel@tonic-gate }
28400Sstevel@tonic-gate 
28410Sstevel@tonic-gate #define	QUERY_BASE	128
28420Sstevel@tonic-gate backend_query_t *
backend_query_alloc(void)28430Sstevel@tonic-gate backend_query_alloc(void)
28440Sstevel@tonic-gate {
28450Sstevel@tonic-gate 	backend_query_t *q;
28460Sstevel@tonic-gate 	q = calloc(1, sizeof (backend_query_t));
28470Sstevel@tonic-gate 	if (q != NULL) {
28480Sstevel@tonic-gate 		q->bq_size = QUERY_BASE;
28490Sstevel@tonic-gate 		q->bq_buf = calloc(1, q->bq_size);
28500Sstevel@tonic-gate 		if (q->bq_buf == NULL) {
28510Sstevel@tonic-gate 			q->bq_size = 0;
28520Sstevel@tonic-gate 		}
28530Sstevel@tonic-gate 
28540Sstevel@tonic-gate 	}
28550Sstevel@tonic-gate 	return (q);
28560Sstevel@tonic-gate }
28570Sstevel@tonic-gate 
28580Sstevel@tonic-gate void
backend_query_append(backend_query_t * q,const char * value)28590Sstevel@tonic-gate backend_query_append(backend_query_t *q, const char *value)
28600Sstevel@tonic-gate {
28610Sstevel@tonic-gate 	char *alloc;
28620Sstevel@tonic-gate 	int count;
28630Sstevel@tonic-gate 	size_t size, old_len;
28640Sstevel@tonic-gate 
28650Sstevel@tonic-gate 	if (q == NULL) {
28660Sstevel@tonic-gate 		/* We'll discover the error when we try to run the query. */
28670Sstevel@tonic-gate 		return;
28680Sstevel@tonic-gate 	}
28690Sstevel@tonic-gate 
28700Sstevel@tonic-gate 	while (q->bq_buf != NULL) {
28710Sstevel@tonic-gate 		old_len = strlen(q->bq_buf);
28720Sstevel@tonic-gate 		size = q->bq_size;
28730Sstevel@tonic-gate 		count = strlcat(q->bq_buf, value, size);
28740Sstevel@tonic-gate 
28750Sstevel@tonic-gate 		if (count < size)
28760Sstevel@tonic-gate 			break;				/* success */
28770Sstevel@tonic-gate 
28780Sstevel@tonic-gate 		q->bq_buf[old_len] = 0;
28790Sstevel@tonic-gate 		size = round_up_to_p2(count + 1);
28800Sstevel@tonic-gate 
28810Sstevel@tonic-gate 		assert(size > q->bq_size);
28820Sstevel@tonic-gate 		alloc = realloc(q->bq_buf, size);
28830Sstevel@tonic-gate 		if (alloc == NULL) {
28840Sstevel@tonic-gate 			free(q->bq_buf);
28850Sstevel@tonic-gate 			q->bq_buf = NULL;
28860Sstevel@tonic-gate 			break;				/* can't grow */
28870Sstevel@tonic-gate 		}
28880Sstevel@tonic-gate 
28890Sstevel@tonic-gate 		q->bq_buf = alloc;
28900Sstevel@tonic-gate 		q->bq_size = size;
28910Sstevel@tonic-gate 	}
28920Sstevel@tonic-gate }
28930Sstevel@tonic-gate 
28940Sstevel@tonic-gate void
backend_query_add(backend_query_t * q,const char * format,...)28950Sstevel@tonic-gate backend_query_add(backend_query_t *q, const char *format, ...)
28960Sstevel@tonic-gate {
28970Sstevel@tonic-gate 	va_list args;
28980Sstevel@tonic-gate 	char *new;
28990Sstevel@tonic-gate 
29000Sstevel@tonic-gate 	if (q == NULL || q->bq_buf == NULL)
29010Sstevel@tonic-gate 		return;
29020Sstevel@tonic-gate 
29030Sstevel@tonic-gate 	va_start(args, format);
29040Sstevel@tonic-gate 	new = sqlite_vmprintf(format, args);
29050Sstevel@tonic-gate 	va_end(args);
29060Sstevel@tonic-gate 
29070Sstevel@tonic-gate 	if (new == NULL) {
29080Sstevel@tonic-gate 		free(q->bq_buf);
29090Sstevel@tonic-gate 		q->bq_buf = NULL;
29100Sstevel@tonic-gate 		return;
29110Sstevel@tonic-gate 	}
29120Sstevel@tonic-gate 
29130Sstevel@tonic-gate 	backend_query_append(q, new);
29140Sstevel@tonic-gate 
29150Sstevel@tonic-gate 	free(new);
29160Sstevel@tonic-gate }
29170Sstevel@tonic-gate 
29180Sstevel@tonic-gate void
backend_query_free(backend_query_t * q)29190Sstevel@tonic-gate backend_query_free(backend_query_t *q)
29200Sstevel@tonic-gate {
29210Sstevel@tonic-gate 	if (q != NULL) {
29220Sstevel@tonic-gate 		if (q->bq_buf != NULL) {
29230Sstevel@tonic-gate 			free(q->bq_buf);
29240Sstevel@tonic-gate 		}
29250Sstevel@tonic-gate 		free(q);
29260Sstevel@tonic-gate 	}
29270Sstevel@tonic-gate }
2928