summaryrefslogtreecommitdiff
path: root/src/backend/commands/variable.c
blob: 1a351b62876d18ac4835cf65dc5790343bbb60a4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
/*-------------------------------------------------------------------------
 *
 * variable.c
 *		Routines for handling specialized SET variables.
 *
 *
 * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group
 * Portions Copyright (c) 1994, Regents of the University of California
 *
 *
 * IDENTIFICATION
 *	  $Header: /cvsroot/pgsql/src/backend/commands/variable.c,v 1.71.2.5 2008/01/03 21:25:58 tgl Exp $
 *
 *-------------------------------------------------------------------------
 */

#include "postgres.h"

#include <ctype.h>
#include <time.h>

#include "access/xact.h"
#include "catalog/pg_shadow.h"
#include "commands/variable.h"
#include "miscadmin.h"
#include "utils/builtins.h"
#include "utils/guc.h"
#include "utils/syscache.h"
#include "utils/tqual.h"
#include "mb/pg_wchar.h"

/*
 * DATESTYLE
 */

/*
 * assign_datestyle: GUC assign_hook for datestyle
 */
const char *
assign_datestyle(const char *value, bool doit, bool interactive)
{
	int			newDateStyle = DateStyle;
	bool		newEuroDates = EuroDates;
	bool		ok = true;
	int			dcnt = 0,
				ecnt = 0;
	char	   *rawstring;
	char	   *result;
	List	   *elemlist;
	List	   *l;

	/* Need a modifiable copy of string */
	rawstring = pstrdup(value);

	/* Parse string into list of identifiers */
	if (!SplitIdentifierString(rawstring, ',', &elemlist))
	{
		/* syntax error in list */
		pfree(rawstring);
		freeList(elemlist);
		if (interactive)
			elog(ERROR, "SET DATESTYLE: invalid list syntax");
		return NULL;
	}

	foreach(l, elemlist)
	{
		char	   *tok = (char *) lfirst(l);

		/* Ugh. Somebody ought to write a table driven version -- mjl */

		if (strcasecmp(tok, "ISO") == 0)
		{
			newDateStyle = USE_ISO_DATES;
			dcnt++;
		}
		else if (strcasecmp(tok, "SQL") == 0)
		{
			newDateStyle = USE_SQL_DATES;
			dcnt++;
		}
		else if (strncasecmp(tok, "POSTGRESQL", 8) == 0)
		{
			newDateStyle = USE_POSTGRES_DATES;
			dcnt++;
		}
		else if (strcasecmp(tok, "GERMAN") == 0)
		{
			newDateStyle = USE_GERMAN_DATES;
			dcnt++;
			if ((ecnt > 0) && (!newEuroDates))
				ok = false;
			newEuroDates = TRUE;
		}
		else if (strncasecmp(tok, "EURO", 4) == 0)
		{
			newEuroDates = TRUE;
			ecnt++;
		}
		else if (strcasecmp(tok, "US") == 0
				 || strncasecmp(tok, "NONEURO", 7) == 0)
		{
			newEuroDates = FALSE;
			ecnt++;
			if ((dcnt > 0) && (newDateStyle == USE_GERMAN_DATES))
				ok = false;
		}
		else if (strcasecmp(tok, "DEFAULT") == 0)
		{
			/*
			 * Easiest way to get the current DEFAULT state is to fetch
			 * the DEFAULT string from guc.c and recursively parse it.
			 *
			 * We can't simply "return assign_datestyle(...)" because we need
			 * to handle constructs like "DEFAULT, ISO".
			 */
			int			saveDateStyle = DateStyle;
			bool		saveEuroDates = EuroDates;
			const char *subval;

			subval = assign_datestyle(GetConfigOptionResetString("datestyle"),
									  true, interactive);
			newDateStyle = DateStyle;
			newEuroDates = EuroDates;
			DateStyle = saveDateStyle;
			EuroDates = saveEuroDates;
			if (!subval)
			{
				ok = false;
				break;
			}
			/* Here we know that our own return value is always malloc'd */
			/* when doit is true */
			free((char *) subval);
			dcnt++;
			ecnt++;
		}
		else
		{
			if (interactive)
				elog(ERROR, "SET DATESTYLE: unrecognized keyword %s", tok);
			ok = false;
			break;
		}
	}

	if (dcnt > 1 || ecnt > 1)
		ok = false;

	pfree(rawstring);
	freeList(elemlist);

	if (!ok)
	{
		if (interactive)
			elog(ERROR, "SET DATESTYLE: conflicting specifications");
		return NULL;
	}

	/*
	 * If we aren't going to do the assignment, just return OK indicator.
	 */
	if (!doit)
		return value;

	/*
	 * Prepare the canonical string to return.	GUC wants it malloc'd.
	 */
	result = (char *) malloc(32);
	if (!result)
		return NULL;

	switch (newDateStyle)
	{
		case USE_ISO_DATES:
			strcpy(result, "ISO");
			break;
		case USE_SQL_DATES:
			strcpy(result, "SQL");
			break;
		case USE_GERMAN_DATES:
			strcpy(result, "GERMAN");
			break;
		default:
			strcpy(result, "POSTGRESQL");
			break;
	}
	strcat(result, newEuroDates ? ", EURO" : ", US");

	/*
	 * Finally, it's safe to assign to the global variables; the
	 * assignment cannot fail now.
	 */
	DateStyle = newDateStyle;
	EuroDates = newEuroDates;

	return result;
}

/*
 * show_datestyle: GUC show_hook for datestyle
 */
const char *
show_datestyle(void)
{
	static char buf[64];

	switch (DateStyle)
	{
		case USE_ISO_DATES:
			strcpy(buf, "ISO");
			break;
		case USE_SQL_DATES:
			strcpy(buf, "SQL");
			break;
		case USE_GERMAN_DATES:
			strcpy(buf, "German");
			break;
		default:
			strcpy(buf, "Postgres");
			break;
	};
	strcat(buf, " with ");
	strcat(buf, ((EuroDates) ? "European" : "US (NonEuropean)"));
	strcat(buf, " conventions");

	return buf;
}


/*
 * TIMEZONE
 */

/*
 * Storage for TZ env var is allocated with an arbitrary size of 64 bytes.
 */
static char tzbuf[64];

/*
 * assign_timezone: GUC assign_hook for timezone
 */
const char *
assign_timezone(const char *value, bool doit, bool interactive)
{
	char	   *result;
	char	   *endptr;
	double		hours;

	/*
	 * Check for INTERVAL 'foo'
	 */
	if (strncasecmp(value, "interval", 8) == 0)
	{
		const char *valueptr = value;
		char	   *val;
		Interval   *interval;

		valueptr += 8;
		while (isspace((unsigned char) *valueptr))
			valueptr++;
		if (*valueptr++ != '\'')
			return NULL;
		val = pstrdup(valueptr);
		/* Check and remove trailing quote */
		endptr = strchr(val, '\'');
		if (!endptr || endptr[1] != '\0')
		{
			pfree(val);
			return NULL;
		}
		*endptr = '\0';

		/*
		 * Try to parse it.  XXX an invalid interval format will result in
		 * elog, which is not desirable for GUC.  We did what we could to
		 * guard against this in flatten_set_variable_args, but a string
		 * coming in from postgresql.conf might contain anything.
		 */
		interval = DatumGetIntervalP(DirectFunctionCall3(interval_in,
													CStringGetDatum(val),
											ObjectIdGetDatum(InvalidOid),
													 Int32GetDatum(-1)));
		pfree(val);
		if (interval->month != 0)
		{
			if (interactive)
				elog(ERROR, "SET TIME ZONE: illegal INTERVAL; month not allowed");
			pfree(interval);
			return NULL;
		}
		if (doit)
		{
#ifdef HAVE_INT64_TIMESTAMP
			CTimeZone = interval->time / INT64CONST(1000000);
#else
			CTimeZone = interval->time;
#endif
			HasCTZSet = true;
		}
		pfree(interval);
	}
	else
	{
		/*
		 * Try it as a numeric number of hours (possibly fractional).
		 */
		hours = strtod(value, &endptr);
		if (endptr != value && *endptr == '\0')
		{
			if (doit)
			{
				CTimeZone = hours * 3600;
				HasCTZSet = true;
			}
		}
		else if (strcasecmp(value, "UNKNOWN") == 0)
		{
			/*
			 * Clear any TZ value we may have established.
			 *
			 * unsetenv() works fine, but is BSD, not POSIX, and is not
			 * available under Solaris, among others. Apparently putenv()
			 * called as below clears the process-specific environment
			 * variables.  Other reasonable arguments to putenv() (e.g.
			 * "TZ=", "TZ", "") result in a core dump (under Linux
			 * anyway). - thomas 1998-01-26
			 */
			if (doit)
			{
				if (tzbuf[0] == 'T')
				{
					strcpy(tzbuf, "=");
					if (putenv(tzbuf) != 0)
						elog(ERROR, "Unable to clear TZ environment variable");
					tzset();
				}
				HasCTZSet = false;
			}
		}
		else
		{
			/*
			 * Otherwise assume it is a timezone name.
			 *
			 * XXX unfortunately we have no reasonable way to check whether a
			 * timezone name is good, so we have to just assume that it
			 * is.
			 */
			if (doit)
			{
				strcpy(tzbuf, "TZ=");
				strncat(tzbuf, value, sizeof(tzbuf) - 4);
				if (putenv(tzbuf) != 0) /* shouldn't happen? */
					elog(LOG, "assign_timezone: putenv failed");
				tzset();
				HasCTZSet = false;
			}
		}
	}

	/*
	 * If we aren't going to do the assignment, just return OK indicator.
	 */
	if (!doit)
		return value;

	/*
	 * Prepare the canonical string to return.	GUC wants it malloc'd.
	 */
	result = (char *) malloc(sizeof(tzbuf));
	if (!result)
		return NULL;

	if (HasCTZSet)
	{
		snprintf(result, sizeof(tzbuf), "%.5f",
				 (double) CTimeZone / 3600.0);
	}
	else if (tzbuf[0] == 'T')
		strcpy(result, tzbuf + 3);
	else
		strcpy(result, "UNKNOWN");

	return result;
}

/*
 * show_timezone: GUC show_hook for timezone
 */
const char *
show_timezone(void)
{
	char	   *tzn;

	if (HasCTZSet)
	{
		Interval	interval;

		interval.month = 0;
#ifdef HAVE_INT64_TIMESTAMP
		interval.time = CTimeZone * INT64CONST(1000000);
#else
		interval.time = CTimeZone;
#endif

		tzn = DatumGetCString(DirectFunctionCall1(interval_out,
										  IntervalPGetDatum(&interval)));
	}
	else
		tzn = getenv("TZ");

	if (tzn != NULL)
		return tzn;

	return "unknown";
}


/*
 * SET TRANSACTION ISOLATION LEVEL
 */

const char *
assign_XactIsoLevel(const char *value, bool doit, bool interactive)
{
	if (doit && interactive && SerializableSnapshot != NULL)
		elog(ERROR, "SET TRANSACTION ISOLATION LEVEL must be called before any query");

	if (strcmp(value, "serializable") == 0)
	{
		if (doit)
			XactIsoLevel = XACT_SERIALIZABLE;
	}
	else if (strcmp(value, "read committed") == 0)
	{
		if (doit)
			XactIsoLevel = XACT_READ_COMMITTED;
	}
	else if (strcmp(value, "default") == 0)
	{
		if (doit)
			XactIsoLevel = DefaultXactIsoLevel;
	}
	else
		return NULL;

	return value;
}

const char *
show_XactIsoLevel(void)
{
	if (XactIsoLevel == XACT_SERIALIZABLE)
		return "SERIALIZABLE";
	else
		return "READ COMMITTED";
}


/*
 * Random number seed
 */

bool
assign_random_seed(double value, bool doit, bool interactive)
{
	/* Can't really roll back on error, so ignore non-interactive setting */
	if (doit && interactive)
		DirectFunctionCall1(setseed, Float8GetDatum(value));
	return true;
}

const char *
show_random_seed(void)
{
	return "unavailable";
}


/*
 * encoding handling functions
 */

const char *
assign_client_encoding(const char *value, bool doit, bool interactive)
{
	int			encoding;

	encoding = pg_valid_client_encoding(value);
	if (encoding < 0)
		return NULL;

	/*
	 * XXX SetClientEncoding depends on namespace functions which are not
	 * available at startup time. So we accept requested client encoding
	 * anyway which might not be valid (e.g. no conversion procs
	 * available).
	 */
	if (SetClientEncoding(encoding, doit) < 0)
	{
		if (interactive)
			elog(ERROR, "Conversion between %s and %s is not supported",
				 value, GetDatabaseEncodingName());
		return NULL;
	}
	return value;
}


const char *
assign_server_encoding(const char *value, bool doit, bool interactive)
{
	if (interactive)
		elog(ERROR, "SET SERVER_ENCODING is not supported");
	/* Pretend never to fail in noninteractive case */
	return value;
}

const char *
show_server_encoding(void)
{
	return GetDatabaseEncodingName();
}


/*
 * SET SESSION AUTHORIZATION
 *
 * When resetting session auth after an error, we can't expect to do catalog
 * lookups.  Hence, the stored form of the value must provide a numeric userid
 * that can be re-used directly.  We store the string in the form of
 * NAMEDATALEN 'x's followed by the numeric userid --- this cannot conflict
 * with any valid user name, because of the NAMEDATALEN limit on names.
 * (NOTE: we rely on guc.c to have properly truncated any incoming value,
 * but not to truncate already-stored values.  See GUC_IS_NAME processing.)
 */
const char *
assign_session_authorization(const char *value, bool doit, bool interactive)
{
	Oid			usesysid = 0;
	char	   *result;

	if (strspn(value, "x") == NAMEDATALEN)
	{
		/* might be a saved numeric userid */
		char	   *endptr;

		usesysid = (Oid) strtoul(value + NAMEDATALEN, &endptr, 10);

		if (endptr != value + NAMEDATALEN && *endptr == '\0')
		{
			/* syntactically valid, so use the numeric user ID */
		}
		else
			usesysid = 0;
	}

	if (usesysid == 0)
	{
		/* not a saved ID, so look it up */
		HeapTuple	userTup;

		if (InSecurityDefinerContext())
		{
			/*
			 * Disallow SET SESSION AUTHORIZATION inside a security definer
			 * context.  We need to do this because when we exit the context,
			 * GUC won't be notified, leaving things out of sync.  Note that
			 * this test is positioned so that restoring a previously saved
			 * setting isn't prevented.
			 */
			if (interactive)
				elog(ERROR, "cannot set session authorization within security-definer function");
			return NULL;
		}

		if (! IsTransactionState())
		{
			/*
			 * Can't do catalog lookups, so fail.  The upshot of this is
			 * that session_authorization cannot be set in postgresql.conf,
			 * which seems like a good thing anyway.
			 */
			return NULL;
		}

		userTup = SearchSysCache(SHADOWNAME,
								 PointerGetDatum(value),
								 0, 0, 0);
		if (!HeapTupleIsValid(userTup))
		{
			if (interactive)
				elog(ERROR, "user \"%s\" does not exist", value);
			return NULL;
		}

		usesysid = ((Form_pg_shadow) GETSTRUCT(userTup))->usesysid;

		ReleaseSysCache(userTup);
	}

	if (doit)
		SetSessionAuthorization(usesysid);

	result = (char *) malloc(NAMEDATALEN + 32);
	if (!result)
		return NULL;

	memset(result, 'x', NAMEDATALEN);

	snprintf(result + NAMEDATALEN, 32, "%lu", (unsigned long) usesysid);

	return result;
}

const char *
show_session_authorization(void)
{
	/*
	 * We can't use the stored string; see comments for
	 * assign_session_authorization
	 */
	return GetUserNameFromId(GetSessionUserId());
}