Postfix3.3.1
dict_sqlite.c
[詳解]
1 /*++
2 /* NAME
3 /* dict_sqlite 3
4 /* SUMMARY
5 /* dictionary manager interface to SQLite3 databases
6 /* SYNOPSIS
7 /* #include <dict_sqlite.h>
8 /*
9 /* DICT *dict_sqlite_open(name, open_flags, dict_flags)
10 /* const char *name;
11 /* int open_flags;
12 /* int dict_flags;
13 /* DESCRIPTION
14 /* dict_sqlite_open() creates a dictionary of type 'sqlite'.
15 /* This dictionary is an interface for the postfix key->value
16 /* mappings to SQLite. The result is a pointer to the installed
17 /* dictionary.
18 /* .PP
19 /* Arguments:
20 /* .IP name
21 /* Either the path to the SQLite configuration file (if it
22 /* starts with '/' or '.'), or the prefix which will be used
23 /* to obtain main.cf configuration parameters for this search.
24 /*
25 /* In the first case, the configuration parameters below are
26 /* specified in the file as \fIname\fR=\fIvalue\fR pairs.
27 /*
28 /* In the second case, the configuration parameters are prefixed
29 /* with the value of \fIname\fR and an underscore, and they
30 /* are specified in main.cf. For example, if this value is
31 /* \fIsqlitecon\fR, the parameters would look like
32 /* \fIsqlitecon_dbpath\fR, \fIsqlitecon_query\fR, and so on.
33 /* .IP open_flags
34 /* Must be O_RDONLY.
35 /* .IP dict_flags
36 /* See dict_open(3).
37 /* .PP
38 /* Configuration parameters:
39 /* .IP dbpath
40 /* Path to SQLite database
41 /* .IP query
42 /* Query template. Before the query is actually issued, variable
43 /* substitutions are performed. See sqlite_table(5) for details.
44 /* .IP result_format
45 /* The format used to expand results from queries. Substitutions
46 /* are performed as described in sqlite_table(5). Defaults to
47 /* returning the lookup result unchanged.
48 /* .IP expansion_limit
49 /* Limit (if any) on the total number of lookup result values.
50 /* Lookups which exceed the limit fail with dict->error=DICT_ERR_RETRY.
51 /* Note that each non-empty (and non-NULL) column of a
52 /* multi-column result row counts as one result.
53 /* .IP "select_field, where_field, additional_conditions"
54 /* Legacy query interface.
55 /* SEE ALSO
56 /* dict(3) generic dictionary manager
57 /* AUTHOR(S)
58 /* Axel Steiner
59 /* ast@treibsand.com
60 /*
61 /* Adopted and updated by:
62 /* Wietse Venema
63 /* IBM T.J. Watson Research
64 /* P.O. Box 704
65 /* Yorktown Heights, NY 10598, USA
66 /*--*/
67 
68 /* System library. */
69 
70 #include <sys_defs.h>
71 #include <string.h>
72 
73 #ifdef HAS_SQLITE
74 #include <sqlite3.h>
75 
76 #if !defined(SQLITE_VERSION_NUMBER) || (SQLITE_VERSION_NUMBER < 3005004)
77 #define sqlite3_prepare_v2 sqlite3_prepare
78 #endif
79 
80 /* Utility library. */
81 
82 #include <msg.h>
83 #include <dict.h>
84 #include <vstring.h>
85 #include <stringops.h>
86 #include <mymalloc.h>
87 
88 /* Global library. */
89 
90 #include <cfg_parser.h>
91 #include <db_common.h>
92 
93 /* Application-specific. */
94 
95 #include <dict_sqlite.h>
96 
97 typedef struct {
98  DICT dict; /* generic member */
99  CFG_PARSER *parser; /* common parameter parser */
100  sqlite3 *db; /* sqlite handle */
101  char *query; /* db_common_expand() query */
102  char *result_format; /* db_common_expand() result_format */
103  void *ctx; /* db_common_parse() context */
104  char *dbpath; /* dbpath config attribute */
105  int expansion_limit; /* expansion_limit config attribute */
106 } DICT_SQLITE;
107 
108 /* dict_sqlite_quote - escape SQL metacharacters in input string */
109 
110 static void dict_sqlite_quote(DICT *dict, const char *raw_text, VSTRING *result)
111 {
112  char *quoted_text;
113 
114  quoted_text = sqlite3_mprintf("%q", raw_text);
115  /* Fix 20100616 */
116  if (quoted_text == 0)
117  msg_fatal("dict_sqlite_quote: out of memory");
118  vstring_strcat(result, quoted_text);
119  sqlite3_free(quoted_text);
120 }
121 
122 /* dict_sqlite_close - close the database */
123 
124 static void dict_sqlite_close(DICT *dict)
125 {
126  const char *myname = "dict_sqlite_close";
127  DICT_SQLITE *dict_sqlite = (DICT_SQLITE *) dict;
128 
129  if (msg_verbose)
130  msg_info("%s: %s", myname, dict_sqlite->parser->name);
131 
132  if (sqlite3_close(dict_sqlite->db) != SQLITE_OK)
133  msg_fatal("%s: close %s failed", myname, dict_sqlite->parser->name);
134  cfg_parser_free(dict_sqlite->parser);
135  myfree(dict_sqlite->dbpath);
136  myfree(dict_sqlite->query);
137  myfree(dict_sqlite->result_format);
138  if (dict_sqlite->ctx)
139  db_common_free_ctx(dict_sqlite->ctx);
140  if (dict->fold_buf)
141  vstring_free(dict->fold_buf);
142  dict_free(dict);
143 }
144 
145 /* dict_sqlite_lookup - find database entry */
146 
147 static const char *dict_sqlite_lookup(DICT *dict, const char *name)
148 {
149  const char *myname = "dict_sqlite_lookup";
150  DICT_SQLITE *dict_sqlite = (DICT_SQLITE *) dict;
151  sqlite3_stmt *sql_stmt;
152  const char *query_remainder;
153  static VSTRING *query;
154  static VSTRING *result;
155  const char *retval;
156  int expansion = 0;
157  int status;
158  int domain_rc;
159 
160  /*
161  * In case of return without lookup (skipped key, etc.).
162  */
163  dict->error = 0;
164 
165  /*
166  * Don't frustrate future attempts to make Postfix UTF-8 transparent.
167  */
168  if ((dict->flags & DICT_FLAG_UTF8_ACTIVE) == 0
169  && !valid_utf8_string(name, strlen(name))) {
170  if (msg_verbose)
171  msg_info("%s: %s: Skipping lookup of non-UTF-8 key '%s'",
172  myname, dict_sqlite->parser->name, name);
173  return (0);
174  }
175 
176  /*
177  * Optionally fold the key. Folding may be enabled on on-the-fly.
178  */
179  if (dict->flags & DICT_FLAG_FOLD_FIX) {
180  if (dict->fold_buf == 0)
181  dict->fold_buf = vstring_alloc(100);
182  vstring_strcpy(dict->fold_buf, name);
183  name = lowercase(vstring_str(dict->fold_buf));
184  }
185 
186  /*
187  * Apply the optional domain filter for email address lookups.
188  */
189  if ((domain_rc = db_common_check_domain(dict_sqlite->ctx, name)) == 0) {
190  if (msg_verbose)
191  msg_info("%s: %s: Skipping lookup of '%s'",
192  myname, dict_sqlite->parser->name, name);
193  return (0);
194  }
195  if (domain_rc < 0)
196  DICT_ERR_VAL_RETURN(dict, domain_rc, (char *) 0);
197 
198  /*
199  * Expand the query and query the database.
200  */
201 #define INIT_VSTR(buf, len) do { \
202  if (buf == 0) \
203  buf = vstring_alloc(len); \
204  VSTRING_RESET(buf); \
205  VSTRING_TERMINATE(buf); \
206  } while (0)
207 
208  INIT_VSTR(query, 10);
209 
210  if (!db_common_expand(dict_sqlite->ctx, dict_sqlite->query,
211  name, 0, query, dict_sqlite_quote))
212  return (0);
213 
214  if (msg_verbose)
215  msg_info("%s: %s: Searching with query %s",
216  myname, dict_sqlite->parser->name, vstring_str(query));
217 
218  if (sqlite3_prepare_v2(dict_sqlite->db, vstring_str(query), -1,
219  &sql_stmt, &query_remainder) != SQLITE_OK)
220  msg_fatal("%s: %s: SQL prepare failed: %s\n",
221  myname, dict_sqlite->parser->name,
222  sqlite3_errmsg(dict_sqlite->db));
223 
224  if (*query_remainder && msg_verbose)
225  msg_info("%s: %s: Ignoring text at end of query: %s",
226  myname, dict_sqlite->parser->name, query_remainder);
227 
228  /*
229  * Retrieve and expand the result(s).
230  */
231  INIT_VSTR(result, 10);
232  while ((status = sqlite3_step(sql_stmt)) != SQLITE_DONE) {
233  if (status == SQLITE_ROW) {
234  if (db_common_expand(dict_sqlite->ctx, dict_sqlite->result_format,
235  (const char *) sqlite3_column_text(sql_stmt, 0),
236  name, result, 0)
237  && dict_sqlite->expansion_limit > 0
238  && ++expansion > dict_sqlite->expansion_limit) {
239  msg_warn("%s: %s: Expansion limit exceeded for key '%s'",
240  myname, dict_sqlite->parser->name, name);
241  dict->error = DICT_ERR_RETRY;
242  break;
243  }
244  }
245  /* Fix 20100616 */
246  else {
247  msg_warn("%s: %s: SQL step failed for query '%s': %s\n",
248  myname, dict_sqlite->parser->name,
249  vstring_str(query), sqlite3_errmsg(dict_sqlite->db));
250  dict->error = DICT_ERR_RETRY;
251  break;
252  }
253  }
254 
255  /*
256  * Clean up.
257  */
258  if (sqlite3_finalize(sql_stmt))
259  msg_fatal("%s: %s: SQL finalize failed for query '%s': %s\n",
260  myname, dict_sqlite->parser->name,
261  vstring_str(query), sqlite3_errmsg(dict_sqlite->db));
262 
263  return ((dict->error == 0 && *(retval = vstring_str(result)) != 0) ?
264  retval : 0);
265 }
266 
267 /* sqlite_parse_config - parse sqlite configuration file */
268 
269 static void sqlite_parse_config(DICT_SQLITE *dict_sqlite, const char *sqlitecf)
270 {
271  VSTRING *buf;
272 
273  /*
274  * Parse the primary configuration parameters, and emulate the legacy
275  * query interface if necessary. This simplifies migration from one SQL
276  * database type to another.
277  */
278  dict_sqlite->dbpath = cfg_get_str(dict_sqlite->parser, "dbpath", "", 1, 0);
279  dict_sqlite->query = cfg_get_str(dict_sqlite->parser, "query", NULL, 0, 0);
280  if (dict_sqlite->query == 0) {
281  buf = vstring_alloc(100);
282  db_common_sql_build_query(buf, dict_sqlite->parser);
283  dict_sqlite->query = vstring_export(buf);
284  }
285  dict_sqlite->result_format =
286  cfg_get_str(dict_sqlite->parser, "result_format", "%s", 1, 0);
287  dict_sqlite->expansion_limit =
288  cfg_get_int(dict_sqlite->parser, "expansion_limit", 0, 0, 0);
289 
290  /*
291  * Parse the query / result templates and the optional domain filter.
292  */
293  dict_sqlite->ctx = 0;
294  (void) db_common_parse(&dict_sqlite->dict, &dict_sqlite->ctx,
295  dict_sqlite->query, 1);
296  (void) db_common_parse(0, &dict_sqlite->ctx, dict_sqlite->result_format, 0);
297  db_common_parse_domain(dict_sqlite->parser, dict_sqlite->ctx);
298 
299  /*
300  * Maps that use substring keys should only be used with the full input
301  * key.
302  */
303  if (db_common_dict_partial(dict_sqlite->ctx))
304  dict_sqlite->dict.flags |= DICT_FLAG_PATTERN;
305  else
306  dict_sqlite->dict.flags |= DICT_FLAG_FIXED;
307 }
308 
309 /* dict_sqlite_open - open sqlite database */
310 
311 DICT *dict_sqlite_open(const char *name, int open_flags, int dict_flags)
312 {
313  DICT_SQLITE *dict_sqlite;
314  CFG_PARSER *parser;
315 
316  /*
317  * Sanity checks.
318  */
319  if (open_flags != O_RDONLY)
320  return (dict_surrogate(DICT_TYPE_SQLITE, name, open_flags, dict_flags,
321  "%s:%s map requires O_RDONLY access mode",
322  DICT_TYPE_SQLITE, name));
323 
324  /*
325  * Open the configuration file.
326  */
327  if ((parser = cfg_parser_alloc(name)) == 0)
328  return (dict_surrogate(DICT_TYPE_SQLITE, name, open_flags, dict_flags,
329  "open %s: %m", name));
330 
331  dict_sqlite = (DICT_SQLITE *) dict_alloc(DICT_TYPE_SQLITE, name,
332  sizeof(DICT_SQLITE));
333  dict_sqlite->dict.lookup = dict_sqlite_lookup;
334  dict_sqlite->dict.close = dict_sqlite_close;
335  dict_sqlite->dict.flags = dict_flags;
336 
337  dict_sqlite->parser = parser;
338  sqlite_parse_config(dict_sqlite, name);
339 
340  if (sqlite3_open(dict_sqlite->dbpath, &dict_sqlite->db))
341  msg_fatal("%s:%s: Can't open database: %s\n",
342  DICT_TYPE_SQLITE, name, sqlite3_errmsg(dict_sqlite->db));
343 
344  dict_sqlite->dict.owner = cfg_get_owner(dict_sqlite->parser);
345 
346  return (DICT_DEBUG (&dict_sqlite->dict));
347 }
348 
349 #endif
int msg_verbose
Definition: msg.c:177
void myfree(void *ptr)
Definition: mymalloc.c:207
void db_common_sql_build_query(VSTRING *query, CFG_PARSER *parser)
Definition: db_common.c:539
#define vstring_str(vp)
Definition: vstring.h:71
#define DICT_FLAG_FIXED
Definition: dict.h:114
int flags
Definition: dict.h:81
int valid_utf8_string(const char *, ssize_t)
#define DICT_ERR_RETRY
Definition: dict.h:178
int cfg_get_int(const CFG_PARSER *parser, const char *name, int defval, int min, int max)
Definition: cfg_parser.c:281
#define DICT_FLAG_FOLD_FIX
Definition: dict.h:124
void db_common_free_ctx(void *ctxPtr)
Definition: db_common.c:288
VSTRING * vstring_strcpy(VSTRING *vp, const char *src)
Definition: vstring.c:431
int db_common_dict_partial(void *ctxPtr)
Definition: db_common.c:276
Definition: dict.h:78
void db_common_parse_domain(CFG_PARSER *parser, void *ctxPtr)
Definition: db_common.c:251
int db_common_expand(void *ctxArg, const char *format, const char *value, const char *key, VSTRING *result, db_quote_callback_t quote_func)
Definition: db_common.c:299
void msg_warn(const char *fmt,...)
Definition: msg.c:215
VSTRING * vstring_alloc(ssize_t len)
Definition: vstring.c:353
int error
Definition: dict.h:94
int db_common_check_domain(void *ctxPtr, const char *addr)
Definition: db_common.c:521
char * lowercase(char *string)
Definition: lowercase.c:34
const char *(* lookup)(struct DICT *, const char *)
Definition: dict.h:82
NORETURN msg_fatal(const char *fmt,...)
Definition: msg.c:249
#define DICT_ERR_VAL_RETURN(dict, err, val)
Definition: dict.h:192
#define DICT_TYPE_SQLITE
Definition: dict_sqlite.h:22
char * cfg_get_str(const CFG_PARSER *parser, const char *name, const char *defval, int min, int max)
Definition: cfg_parser.c:261
#define DICT_FLAG_PATTERN
Definition: dict.h:115
void dict_free(DICT *)
Definition: dict_alloc.c:163
DICT * dict_sqlite_open(const char *, int, int)
CFG_PARSER * cfg_parser_free(CFG_PARSER *parser)
Definition: cfg_parser.c:309
CFG_PARSER * cfg_parser_alloc(const char *pname)
Definition: cfg_parser.c:227
VSTRING * vstring_free(VSTRING *vp)
Definition: vstring.c:380
int db_common_parse(DICT *dict, void **ctxPtr, const char *format, int query)
Definition: db_common.c:185
DICT * dict_alloc(const char *, const char *, ssize_t)
Definition: dict_alloc.c:135
VSTRING * fold_buf
Definition: dict.h:92
#define cfg_get_owner(cfg)
Definition: cfg_parser.h:38
VSTRING * vstring_strcat(VSTRING *vp, const char *src)
Definition: vstring.c:459
char * vstring_export(VSTRING *vp)
Definition: vstring.c:569
DICT * dict_surrogate(const char *dict_type, const char *dict_name, int open_flags, int dict_flags, const char *fmt,...)
#define DICT_FLAG_UTF8_ACTIVE
Definition: dict.h:131
void msg_info(const char *fmt,...)
Definition: msg.c:199