1 /*-------------------------------------------------------------------------
2  *
3  * elog.c
4  *	  error logging and reporting
5  *
6  * Because of the extremely high rate at which log messages can be generated,
7  * we need to be mindful of the performance cost of obtaining any information
8  * that may be logged.  Also, it's important to keep in mind that this code may
9  * get called from within an aborted transaction, in which case operations
10  * such as syscache lookups are unsafe.
11  *
12  * Some notes about recursion and errors during error processing:
13  *
14  * We need to be robust about recursive-error scenarios --- for example,
15  * if we run out of memory, it's important to be able to report that fact.
16  * There are a number of considerations that go into this.
17  *
18  * First, distinguish between re-entrant use and actual recursion.  It
19  * is possible for an error or warning message to be emitted while the
20  * parameters for an error message are being computed.  In this case
21  * errstart has been called for the outer message, and some field values
22  * may have already been saved, but we are not actually recursing.  We handle
23  * this by providing a (small) stack of ErrorData records.  The inner message
24  * can be computed and sent without disturbing the state of the outer message.
25  * (If the inner message is actually an error, this isn't very interesting
26  * because control won't come back to the outer message generator ... but
27  * if the inner message is only debug or log data, this is critical.)
28  *
29  * Second, actual recursion will occur if an error is reported by one of
30  * the elog.c routines or something they call.  By far the most probable
31  * scenario of this sort is "out of memory"; and it's also the nastiest
32  * to handle because we'd likely also run out of memory while trying to
33  * report this error!  Our escape hatch for this case is to reset the
34  * ErrorContext to empty before trying to process the inner error.  Since
35  * ErrorContext is guaranteed to have at least 8K of space in it (see mcxt.c),
36  * we should be able to process an "out of memory" message successfully.
37  * Since we lose the prior error state due to the reset, we won't be able
38  * to return to processing the original error, but we wouldn't have anyway.
39  * (NOTE: the escape hatch is not used for recursive situations where the
40  * inner message is of less than ERROR severity; in that case we just
41  * try to process it and return normally.  Usually this will work, but if
42  * it ends up in infinite recursion, we will PANIC due to error stack
43  * overflow.)
44  *
45  *
46  * Portions Copyright (c) 1996-2017, PostgreSQL Global Development Group
47  * Portions Copyright (c) 1994, Regents of the University of California
48  *
49  *
50  * IDENTIFICATION
51  *	  src/backend/utils/error/elog.c
52  *
53  *-------------------------------------------------------------------------
54  */
55 #include "postgres.h"
56 
57 #include <fcntl.h>
58 #include <time.h>
59 #include <unistd.h>
60 #include <signal.h>
61 #include <ctype.h>
62 #ifdef HAVE_SYSLOG
63 #include <syslog.h>
64 #endif
65 
66 #include "access/transam.h"
67 #include "access/xact.h"
68 #include "libpq/libpq.h"
69 #include "libpq/pqformat.h"
70 #include "mb/pg_wchar.h"
71 #include "miscadmin.h"
72 #include "postmaster/postmaster.h"
73 #include "postmaster/syslogger.h"
74 #include "storage/ipc.h"
75 #include "storage/proc.h"
76 #include "tcop/tcopprot.h"
77 #include "utils/guc.h"
78 #include "utils/memutils.h"
79 #include "utils/ps_status.h"
80 
81 
82 /* In this module, access gettext() via err_gettext() */
83 #undef _
84 #define _(x) err_gettext(x)
85 
86 
87 /* Global variables */
88 ErrorContextCallback *error_context_stack = NULL;
89 
90 sigjmp_buf *PG_exception_stack = NULL;
91 
92 extern bool redirection_done;
93 
94 /*
95  * Hook for intercepting messages before they are sent to the server log.
96  * Note that the hook will not get called for messages that are suppressed
97  * by log_min_messages.  Also note that logging hooks implemented in preload
98  * libraries will miss any log messages that are generated before the
99  * library is loaded.
100  */
101 emit_log_hook_type emit_log_hook = NULL;
102 
103 /* GUC parameters */
104 int			Log_error_verbosity = PGERROR_VERBOSE;
105 char	   *Log_line_prefix = NULL; /* format for extra log line info */
106 int			Log_destination = LOG_DESTINATION_STDERR;
107 char	   *Log_destination_string = NULL;
108 bool		syslog_sequence_numbers = true;
109 bool		syslog_split_messages = true;
110 
111 #ifdef HAVE_SYSLOG
112 
113 /*
114  * Max string length to send to syslog().  Note that this doesn't count the
115  * sequence-number prefix we add, and of course it doesn't count the prefix
116  * added by syslog itself.  Solaris and sysklogd truncate the final message
117  * at 1024 bytes, so this value leaves 124 bytes for those prefixes.  (Most
118  * other syslog implementations seem to have limits of 2KB or so.)
119  */
120 #ifndef PG_SYSLOG_LIMIT
121 #define PG_SYSLOG_LIMIT 900
122 #endif
123 
124 static bool openlog_done = false;
125 static char *syslog_ident = NULL;
126 static int	syslog_facility = LOG_LOCAL0;
127 
128 static void write_syslog(int level, const char *line);
129 #endif
130 
131 #ifdef WIN32
132 extern char *event_source;
133 
134 static void write_eventlog(int level, const char *line, int len);
135 #endif
136 
137 /* We provide a small stack of ErrorData records for re-entrant cases */
138 #define ERRORDATA_STACK_SIZE  5
139 
140 static ErrorData errordata[ERRORDATA_STACK_SIZE];
141 
142 static int	errordata_stack_depth = -1; /* index of topmost active frame */
143 
144 static int	recursion_depth = 0;	/* to detect actual recursion */
145 
146 /*
147  * Saved timeval and buffers for formatted timestamps that might be used by
148  * both log_line_prefix and csv logs.
149  */
150 static struct timeval saved_timeval;
151 static bool saved_timeval_set = false;
152 
153 #define FORMATTED_TS_LEN 128
154 static char formatted_start_time[FORMATTED_TS_LEN];
155 static char formatted_log_time[FORMATTED_TS_LEN];
156 
157 
158 /* Macro for checking errordata_stack_depth is reasonable */
159 #define CHECK_STACK_DEPTH() \
160 	do { \
161 		if (errordata_stack_depth < 0) \
162 		{ \
163 			errordata_stack_depth = -1; \
164 			ereport(ERROR, (errmsg_internal("errstart was not called"))); \
165 		} \
166 	} while (0)
167 
168 
169 static const char *err_gettext(const char *str) pg_attribute_format_arg(1);
170 static void set_errdata_field(MemoryContextData *cxt, char **ptr, const char *str);
171 static void write_console(const char *line, int len);
172 static void setup_formatted_log_time(void);
173 static void setup_formatted_start_time(void);
174 static const char *process_log_prefix_padding(const char *p, int *padding);
175 static void log_line_prefix(StringInfo buf, ErrorData *edata);
176 static void write_csvlog(ErrorData *edata);
177 static void send_message_to_server_log(ErrorData *edata);
178 static void write_pipe_chunks(char *data, int len, int dest);
179 static void send_message_to_frontend(ErrorData *edata);
180 static char *expand_fmt_string(const char *fmt, ErrorData *edata);
181 static const char *useful_strerror(int errnum);
182 static const char *get_errno_symbol(int errnum);
183 static const char *error_severity(int elevel);
184 static void append_with_tabs(StringInfo buf, const char *str);
185 static bool is_log_level_output(int elevel, int log_min_level);
186 
187 
188 /*
189  * in_error_recursion_trouble --- are we at risk of infinite error recursion?
190  *
191  * This function exists to provide common control of various fallback steps
192  * that we take if we think we are facing infinite error recursion.  See the
193  * callers for details.
194  */
195 bool
in_error_recursion_trouble(void)196 in_error_recursion_trouble(void)
197 {
198 	/* Pull the plug if recurse more than once */
199 	return (recursion_depth > 2);
200 }
201 
202 /*
203  * One of those fallback steps is to stop trying to localize the error
204  * message, since there's a significant probability that that's exactly
205  * what's causing the recursion.
206  */
207 static inline const char *
err_gettext(const char * str)208 err_gettext(const char *str)
209 {
210 #ifdef ENABLE_NLS
211 	if (in_error_recursion_trouble())
212 		return str;
213 	else
214 		return gettext(str);
215 #else
216 	return str;
217 #endif
218 }
219 
220 
221 /*
222  * errstart --- begin an error-reporting cycle
223  *
224  * Create a stack entry and store the given parameters in it.  Subsequently,
225  * errmsg() and perhaps other routines will be called to further populate
226  * the stack entry.  Finally, errfinish() will be called to actually process
227  * the error report.
228  *
229  * Returns TRUE in normal case.  Returns FALSE to short-circuit the error
230  * report (if it's a warning or lower and not to be reported anywhere).
231  */
232 bool
errstart(int elevel,const char * filename,int lineno,const char * funcname,const char * domain)233 errstart(int elevel, const char *filename, int lineno,
234 		 const char *funcname, const char *domain)
235 {
236 	ErrorData  *edata;
237 	bool		output_to_server;
238 	bool		output_to_client = false;
239 	int			i;
240 
241 	/*
242 	 * Check some cases in which we want to promote an error into a more
243 	 * severe error.  None of this logic applies for non-error messages.
244 	 */
245 	if (elevel >= ERROR)
246 	{
247 		/*
248 		 * If we are inside a critical section, all errors become PANIC
249 		 * errors.  See miscadmin.h.
250 		 */
251 		if (CritSectionCount > 0)
252 			elevel = PANIC;
253 
254 		/*
255 		 * Check reasons for treating ERROR as FATAL:
256 		 *
257 		 * 1. we have no handler to pass the error to (implies we are in the
258 		 * postmaster or in backend startup).
259 		 *
260 		 * 2. ExitOnAnyError mode switch is set (initdb uses this).
261 		 *
262 		 * 3. the error occurred after proc_exit has begun to run.  (It's
263 		 * proc_exit's responsibility to see that this doesn't turn into
264 		 * infinite recursion!)
265 		 */
266 		if (elevel == ERROR)
267 		{
268 			if (PG_exception_stack == NULL ||
269 				ExitOnAnyError ||
270 				proc_exit_inprogress)
271 				elevel = FATAL;
272 		}
273 
274 		/*
275 		 * If the error level is ERROR or more, errfinish is not going to
276 		 * return to caller; therefore, if there is any stacked error already
277 		 * in progress it will be lost.  This is more or less okay, except we
278 		 * do not want to have a FATAL or PANIC error downgraded because the
279 		 * reporting process was interrupted by a lower-grade error.  So check
280 		 * the stack and make sure we panic if panic is warranted.
281 		 */
282 		for (i = 0; i <= errordata_stack_depth; i++)
283 			elevel = Max(elevel, errordata[i].elevel);
284 	}
285 
286 	/*
287 	 * Now decide whether we need to process this report at all; if it's
288 	 * warning or less and not enabled for logging, just return FALSE without
289 	 * starting up any error logging machinery.
290 	 */
291 
292 	/* Determine whether message is enabled for server log output */
293 	output_to_server = is_log_level_output(elevel, log_min_messages);
294 
295 	/* Determine whether message is enabled for client output */
296 	if (whereToSendOutput == DestRemote && elevel != LOG_SERVER_ONLY)
297 	{
298 		/*
299 		 * client_min_messages is honored only after we complete the
300 		 * authentication handshake.  This is required both for security
301 		 * reasons and because many clients can't handle NOTICE messages
302 		 * during authentication.
303 		 */
304 		if (ClientAuthInProgress)
305 			output_to_client = (elevel >= ERROR);
306 		else
307 			output_to_client = (elevel >= client_min_messages ||
308 								elevel == INFO);
309 	}
310 
311 	/* Skip processing effort if non-error message will not be output */
312 	if (elevel < ERROR && !output_to_server && !output_to_client)
313 		return false;
314 
315 	/*
316 	 * We need to do some actual work.  Make sure that memory context
317 	 * initialization has finished, else we can't do anything useful.
318 	 */
319 	if (ErrorContext == NULL)
320 	{
321 		/* Oops, hard crash time; very little we can do safely here */
322 		write_stderr("error occurred at %s:%d before error message processing is available\n",
323 					 filename ? filename : "(unknown file)", lineno);
324 		exit(2);
325 	}
326 
327 	/*
328 	 * Okay, crank up a stack entry to store the info in.
329 	 */
330 
331 	if (recursion_depth++ > 0 && elevel >= ERROR)
332 	{
333 		/*
334 		 * Oops, error during error processing.  Clear ErrorContext as
335 		 * discussed at top of file.  We will not return to the original
336 		 * error's reporter or handler, so we don't need it.
337 		 */
338 		MemoryContextReset(ErrorContext);
339 
340 		/*
341 		 * Infinite error recursion might be due to something broken in a
342 		 * context traceback routine.  Abandon them too.  We also abandon
343 		 * attempting to print the error statement (which, if long, could
344 		 * itself be the source of the recursive failure).
345 		 */
346 		if (in_error_recursion_trouble())
347 		{
348 			error_context_stack = NULL;
349 			debug_query_string = NULL;
350 		}
351 	}
352 	if (++errordata_stack_depth >= ERRORDATA_STACK_SIZE)
353 	{
354 		/*
355 		 * Wups, stack not big enough.  We treat this as a PANIC condition
356 		 * because it suggests an infinite loop of errors during error
357 		 * recovery.
358 		 */
359 		errordata_stack_depth = -1; /* make room on stack */
360 		ereport(PANIC, (errmsg_internal("ERRORDATA_STACK_SIZE exceeded")));
361 	}
362 
363 	/* Initialize data for this error frame */
364 	edata = &errordata[errordata_stack_depth];
365 	MemSet(edata, 0, sizeof(ErrorData));
366 	edata->elevel = elevel;
367 	edata->output_to_server = output_to_server;
368 	edata->output_to_client = output_to_client;
369 	if (filename)
370 	{
371 		const char *slash;
372 
373 		/* keep only base name, useful especially for vpath builds */
374 		slash = strrchr(filename, '/');
375 		if (slash)
376 			filename = slash + 1;
377 	}
378 	edata->filename = filename;
379 	edata->lineno = lineno;
380 	edata->funcname = funcname;
381 	/* the default text domain is the backend's */
382 	edata->domain = domain ? domain : PG_TEXTDOMAIN("postgres");
383 	/* initialize context_domain the same way (see set_errcontext_domain()) */
384 	edata->context_domain = edata->domain;
385 	/* Select default errcode based on elevel */
386 	if (elevel >= ERROR)
387 		edata->sqlerrcode = ERRCODE_INTERNAL_ERROR;
388 	else if (elevel == WARNING)
389 		edata->sqlerrcode = ERRCODE_WARNING;
390 	else
391 		edata->sqlerrcode = ERRCODE_SUCCESSFUL_COMPLETION;
392 	/* errno is saved here so that error parameter eval can't change it */
393 	edata->saved_errno = errno;
394 
395 	/*
396 	 * Any allocations for this error state level should go into ErrorContext
397 	 */
398 	edata->assoc_context = ErrorContext;
399 
400 	recursion_depth--;
401 	return true;
402 }
403 
404 /*
405  * errfinish --- end an error-reporting cycle
406  *
407  * Produce the appropriate error report(s) and pop the error stack.
408  *
409  * If elevel is ERROR or worse, control does not return to the caller.
410  * See elog.h for the error level definitions.
411  */
412 void
errfinish(int dummy,...)413 errfinish(int dummy,...)
414 {
415 	ErrorData  *edata = &errordata[errordata_stack_depth];
416 	int			elevel;
417 	MemoryContext oldcontext;
418 	ErrorContextCallback *econtext;
419 
420 	recursion_depth++;
421 	CHECK_STACK_DEPTH();
422 	elevel = edata->elevel;
423 
424 	/*
425 	 * Do processing in ErrorContext, which we hope has enough reserved space
426 	 * to report an error.
427 	 */
428 	oldcontext = MemoryContextSwitchTo(ErrorContext);
429 
430 	/*
431 	 * Call any context callback functions.  Errors occurring in callback
432 	 * functions will be treated as recursive errors --- this ensures we will
433 	 * avoid infinite recursion (see errstart).
434 	 */
435 	for (econtext = error_context_stack;
436 		 econtext != NULL;
437 		 econtext = econtext->previous)
438 		(*econtext->callback) (econtext->arg);
439 
440 	/*
441 	 * If ERROR (not more nor less) we pass it off to the current handler.
442 	 * Printing it and popping the stack is the responsibility of the handler.
443 	 */
444 	if (elevel == ERROR)
445 	{
446 		/*
447 		 * We do some minimal cleanup before longjmp'ing so that handlers can
448 		 * execute in a reasonably sane state.
449 		 *
450 		 * Reset InterruptHoldoffCount in case we ereport'd from inside an
451 		 * interrupt holdoff section.  (We assume here that no handler will
452 		 * itself be inside a holdoff section.  If necessary, such a handler
453 		 * could save and restore InterruptHoldoffCount for itself, but this
454 		 * should make life easier for most.)
455 		 */
456 		InterruptHoldoffCount = 0;
457 		QueryCancelHoldoffCount = 0;
458 
459 		CritSectionCount = 0;	/* should be unnecessary, but... */
460 
461 		/*
462 		 * Note that we leave CurrentMemoryContext set to ErrorContext. The
463 		 * handler should reset it to something else soon.
464 		 */
465 
466 		recursion_depth--;
467 		PG_RE_THROW();
468 	}
469 
470 	/*
471 	 * If we are doing FATAL or PANIC, abort any old-style COPY OUT in
472 	 * progress, so that we can report the message before dying.  (Without
473 	 * this, pq_putmessage will refuse to send the message at all, which is
474 	 * what we want for NOTICE messages, but not for fatal exits.) This hack
475 	 * is necessary because of poor design of old-style copy protocol.
476 	 */
477 	if (elevel >= FATAL && whereToSendOutput == DestRemote)
478 		pq_endcopyout(true);
479 
480 	/* Emit the message to the right places */
481 	EmitErrorReport();
482 
483 	/* Now free up subsidiary data attached to stack entry, and release it */
484 	if (edata->message)
485 		pfree(edata->message);
486 	if (edata->detail)
487 		pfree(edata->detail);
488 	if (edata->detail_log)
489 		pfree(edata->detail_log);
490 	if (edata->hint)
491 		pfree(edata->hint);
492 	if (edata->context)
493 		pfree(edata->context);
494 	if (edata->schema_name)
495 		pfree(edata->schema_name);
496 	if (edata->table_name)
497 		pfree(edata->table_name);
498 	if (edata->column_name)
499 		pfree(edata->column_name);
500 	if (edata->datatype_name)
501 		pfree(edata->datatype_name);
502 	if (edata->constraint_name)
503 		pfree(edata->constraint_name);
504 	if (edata->internalquery)
505 		pfree(edata->internalquery);
506 
507 	errordata_stack_depth--;
508 
509 	/* Exit error-handling context */
510 	MemoryContextSwitchTo(oldcontext);
511 	recursion_depth--;
512 
513 	/*
514 	 * Perform error recovery action as specified by elevel.
515 	 */
516 	if (elevel == FATAL)
517 	{
518 		/*
519 		 * For a FATAL error, we let proc_exit clean up and exit.
520 		 *
521 		 * If we just reported a startup failure, the client will disconnect
522 		 * on receiving it, so don't send any more to the client.
523 		 */
524 		if (PG_exception_stack == NULL && whereToSendOutput == DestRemote)
525 			whereToSendOutput = DestNone;
526 
527 		/*
528 		 * fflush here is just to improve the odds that we get to see the
529 		 * error message, in case things are so hosed that proc_exit crashes.
530 		 * Any other code you might be tempted to add here should probably be
531 		 * in an on_proc_exit or on_shmem_exit callback instead.
532 		 */
533 		fflush(stdout);
534 		fflush(stderr);
535 
536 		/*
537 		 * Do normal process-exit cleanup, then return exit code 1 to indicate
538 		 * FATAL termination.  The postmaster may or may not consider this
539 		 * worthy of panic, depending on which subprocess returns it.
540 		 */
541 		proc_exit(1);
542 	}
543 
544 	if (elevel >= PANIC)
545 	{
546 		/*
547 		 * Serious crash time. Postmaster will observe SIGABRT process exit
548 		 * status and kill the other backends too.
549 		 *
550 		 * XXX: what if we are *in* the postmaster?  abort() won't kill our
551 		 * children...
552 		 */
553 		fflush(stdout);
554 		fflush(stderr);
555 		abort();
556 	}
557 
558 	/*
559 	 * Check for cancel/die interrupt first --- this is so that the user can
560 	 * stop a query emitting tons of notice or warning messages, even if it's
561 	 * in a loop that otherwise fails to check for interrupts.
562 	 */
563 	CHECK_FOR_INTERRUPTS();
564 }
565 
566 
567 /*
568  * errcode --- add SQLSTATE error code to the current error
569  *
570  * The code is expected to be represented as per MAKE_SQLSTATE().
571  */
572 int
errcode(int sqlerrcode)573 errcode(int sqlerrcode)
574 {
575 	ErrorData  *edata = &errordata[errordata_stack_depth];
576 
577 	/* we don't bother incrementing recursion_depth */
578 	CHECK_STACK_DEPTH();
579 
580 	edata->sqlerrcode = sqlerrcode;
581 
582 	return 0;					/* return value does not matter */
583 }
584 
585 
586 /*
587  * errcode_for_file_access --- add SQLSTATE error code to the current error
588  *
589  * The SQLSTATE code is chosen based on the saved errno value.  We assume
590  * that the failing operation was some type of disk file access.
591  *
592  * NOTE: the primary error message string should generally include %m
593  * when this is used.
594  */
595 int
errcode_for_file_access(void)596 errcode_for_file_access(void)
597 {
598 	ErrorData  *edata = &errordata[errordata_stack_depth];
599 
600 	/* we don't bother incrementing recursion_depth */
601 	CHECK_STACK_DEPTH();
602 
603 	switch (edata->saved_errno)
604 	{
605 			/* Permission-denied failures */
606 		case EPERM:				/* Not super-user */
607 		case EACCES:			/* Permission denied */
608 #ifdef EROFS
609 		case EROFS:				/* Read only file system */
610 #endif
611 			edata->sqlerrcode = ERRCODE_INSUFFICIENT_PRIVILEGE;
612 			break;
613 
614 			/* File not found */
615 		case ENOENT:			/* No such file or directory */
616 			edata->sqlerrcode = ERRCODE_UNDEFINED_FILE;
617 			break;
618 
619 			/* Duplicate file */
620 		case EEXIST:			/* File exists */
621 			edata->sqlerrcode = ERRCODE_DUPLICATE_FILE;
622 			break;
623 
624 			/* Wrong object type or state */
625 		case ENOTDIR:			/* Not a directory */
626 		case EISDIR:			/* Is a directory */
627 #if defined(ENOTEMPTY) && (ENOTEMPTY != EEXIST) /* same code on AIX */
628 		case ENOTEMPTY:			/* Directory not empty */
629 #endif
630 			edata->sqlerrcode = ERRCODE_WRONG_OBJECT_TYPE;
631 			break;
632 
633 			/* Insufficient resources */
634 		case ENOSPC:			/* No space left on device */
635 			edata->sqlerrcode = ERRCODE_DISK_FULL;
636 			break;
637 
638 		case ENFILE:			/* File table overflow */
639 		case EMFILE:			/* Too many open files */
640 			edata->sqlerrcode = ERRCODE_INSUFFICIENT_RESOURCES;
641 			break;
642 
643 			/* Hardware failure */
644 		case EIO:				/* I/O error */
645 			edata->sqlerrcode = ERRCODE_IO_ERROR;
646 			break;
647 
648 			/* All else is classified as internal errors */
649 		default:
650 			edata->sqlerrcode = ERRCODE_INTERNAL_ERROR;
651 			break;
652 	}
653 
654 	return 0;					/* return value does not matter */
655 }
656 
657 /*
658  * errcode_for_socket_access --- add SQLSTATE error code to the current error
659  *
660  * The SQLSTATE code is chosen based on the saved errno value.  We assume
661  * that the failing operation was some type of socket access.
662  *
663  * NOTE: the primary error message string should generally include %m
664  * when this is used.
665  */
666 int
errcode_for_socket_access(void)667 errcode_for_socket_access(void)
668 {
669 	ErrorData  *edata = &errordata[errordata_stack_depth];
670 
671 	/* we don't bother incrementing recursion_depth */
672 	CHECK_STACK_DEPTH();
673 
674 	switch (edata->saved_errno)
675 	{
676 			/* Loss of connection */
677 		case EPIPE:
678 #ifdef ECONNRESET
679 		case ECONNRESET:
680 #endif
681 			edata->sqlerrcode = ERRCODE_CONNECTION_FAILURE;
682 			break;
683 
684 			/* All else is classified as internal errors */
685 		default:
686 			edata->sqlerrcode = ERRCODE_INTERNAL_ERROR;
687 			break;
688 	}
689 
690 	return 0;					/* return value does not matter */
691 }
692 
693 
694 /*
695  * This macro handles expansion of a format string and associated parameters;
696  * it's common code for errmsg(), errdetail(), etc.  Must be called inside
697  * a routine that is declared like "const char *fmt, ..." and has an edata
698  * pointer set up.  The message is assigned to edata->targetfield, or
699  * appended to it if appendval is true.  The message is subject to translation
700  * if translateit is true.
701  *
702  * Note: we pstrdup the buffer rather than just transferring its storage
703  * to the edata field because the buffer might be considerably larger than
704  * really necessary.
705  */
706 #define EVALUATE_MESSAGE(domain, targetfield, appendval, translateit)	\
707 	{ \
708 		char		   *fmtbuf; \
709 		StringInfoData	buf; \
710 		/* Internationalize the error format string */ \
711 		if ((translateit) && !in_error_recursion_trouble()) \
712 			fmt = dgettext((domain), fmt);				  \
713 		/* Expand %m in format string */ \
714 		fmtbuf = expand_fmt_string(fmt, edata); \
715 		initStringInfo(&buf); \
716 		if ((appendval) && edata->targetfield) { \
717 			appendStringInfoString(&buf, edata->targetfield); \
718 			appendStringInfoChar(&buf, '\n'); \
719 		} \
720 		/* Generate actual output --- have to use appendStringInfoVA */ \
721 		for (;;) \
722 		{ \
723 			va_list		args; \
724 			int			needed; \
725 			va_start(args, fmt); \
726 			needed = appendStringInfoVA(&buf, fmtbuf, args); \
727 			va_end(args); \
728 			if (needed == 0) \
729 				break; \
730 			enlargeStringInfo(&buf, needed); \
731 		} \
732 		/* Done with expanded fmt */ \
733 		pfree(fmtbuf); \
734 		/* Save the completed message into the stack item */ \
735 		if (edata->targetfield) \
736 			pfree(edata->targetfield); \
737 		edata->targetfield = pstrdup(buf.data); \
738 		pfree(buf.data); \
739 	}
740 
741 /*
742  * Same as above, except for pluralized error messages.  The calling routine
743  * must be declared like "const char *fmt_singular, const char *fmt_plural,
744  * unsigned long n, ...".  Translation is assumed always wanted.
745  */
746 #define EVALUATE_MESSAGE_PLURAL(domain, targetfield, appendval)  \
747 	{ \
748 		const char	   *fmt; \
749 		char		   *fmtbuf; \
750 		StringInfoData	buf; \
751 		/* Internationalize the error format string */ \
752 		if (!in_error_recursion_trouble()) \
753 			fmt = dngettext((domain), fmt_singular, fmt_plural, n); \
754 		else \
755 			fmt = (n == 1 ? fmt_singular : fmt_plural); \
756 		/* Expand %m in format string */ \
757 		fmtbuf = expand_fmt_string(fmt, edata); \
758 		initStringInfo(&buf); \
759 		if ((appendval) && edata->targetfield) { \
760 			appendStringInfoString(&buf, edata->targetfield); \
761 			appendStringInfoChar(&buf, '\n'); \
762 		} \
763 		/* Generate actual output --- have to use appendStringInfoVA */ \
764 		for (;;) \
765 		{ \
766 			va_list		args; \
767 			int			needed; \
768 			va_start(args, n); \
769 			needed = appendStringInfoVA(&buf, fmtbuf, args); \
770 			va_end(args); \
771 			if (needed == 0) \
772 				break; \
773 			enlargeStringInfo(&buf, needed); \
774 		} \
775 		/* Done with expanded fmt */ \
776 		pfree(fmtbuf); \
777 		/* Save the completed message into the stack item */ \
778 		if (edata->targetfield) \
779 			pfree(edata->targetfield); \
780 		edata->targetfield = pstrdup(buf.data); \
781 		pfree(buf.data); \
782 	}
783 
784 
785 /*
786  * errmsg --- add a primary error message text to the current error
787  *
788  * In addition to the usual %-escapes recognized by printf, "%m" in
789  * fmt is replaced by the error message for the caller's value of errno.
790  *
791  * Note: no newline is needed at the end of the fmt string, since
792  * ereport will provide one for the output methods that need it.
793  */
794 int
errmsg(const char * fmt,...)795 errmsg(const char *fmt,...)
796 {
797 	ErrorData  *edata = &errordata[errordata_stack_depth];
798 	MemoryContext oldcontext;
799 
800 	recursion_depth++;
801 	CHECK_STACK_DEPTH();
802 	oldcontext = MemoryContextSwitchTo(edata->assoc_context);
803 
804 	edata->message_id = fmt;
805 	EVALUATE_MESSAGE(edata->domain, message, false, true);
806 
807 	MemoryContextSwitchTo(oldcontext);
808 	recursion_depth--;
809 	return 0;					/* return value does not matter */
810 }
811 
812 
813 /*
814  * errmsg_internal --- add a primary error message text to the current error
815  *
816  * This is exactly like errmsg() except that strings passed to errmsg_internal
817  * are not translated, and are customarily left out of the
818  * internationalization message dictionary.  This should be used for "can't
819  * happen" cases that are probably not worth spending translation effort on.
820  * We also use this for certain cases where we *must* not try to translate
821  * the message because the translation would fail and result in infinite
822  * error recursion.
823  */
824 int
errmsg_internal(const char * fmt,...)825 errmsg_internal(const char *fmt,...)
826 {
827 	ErrorData  *edata = &errordata[errordata_stack_depth];
828 	MemoryContext oldcontext;
829 
830 	recursion_depth++;
831 	CHECK_STACK_DEPTH();
832 	oldcontext = MemoryContextSwitchTo(edata->assoc_context);
833 
834 	edata->message_id = fmt;
835 	EVALUATE_MESSAGE(edata->domain, message, false, false);
836 
837 	MemoryContextSwitchTo(oldcontext);
838 	recursion_depth--;
839 	return 0;					/* return value does not matter */
840 }
841 
842 
843 /*
844  * errmsg_plural --- add a primary error message text to the current error,
845  * with support for pluralization of the message text
846  */
847 int
errmsg_plural(const char * fmt_singular,const char * fmt_plural,unsigned long n,...)848 errmsg_plural(const char *fmt_singular, const char *fmt_plural,
849 			  unsigned long n,...)
850 {
851 	ErrorData  *edata = &errordata[errordata_stack_depth];
852 	MemoryContext oldcontext;
853 
854 	recursion_depth++;
855 	CHECK_STACK_DEPTH();
856 	oldcontext = MemoryContextSwitchTo(edata->assoc_context);
857 
858 	edata->message_id = fmt_singular;
859 	EVALUATE_MESSAGE_PLURAL(edata->domain, message, false);
860 
861 	MemoryContextSwitchTo(oldcontext);
862 	recursion_depth--;
863 	return 0;					/* return value does not matter */
864 }
865 
866 
867 /*
868  * errdetail --- add a detail error message text to the current error
869  */
870 int
errdetail(const char * fmt,...)871 errdetail(const char *fmt,...)
872 {
873 	ErrorData  *edata = &errordata[errordata_stack_depth];
874 	MemoryContext oldcontext;
875 
876 	recursion_depth++;
877 	CHECK_STACK_DEPTH();
878 	oldcontext = MemoryContextSwitchTo(edata->assoc_context);
879 
880 	EVALUATE_MESSAGE(edata->domain, detail, false, true);
881 
882 	MemoryContextSwitchTo(oldcontext);
883 	recursion_depth--;
884 	return 0;					/* return value does not matter */
885 }
886 
887 
888 /*
889  * errdetail_internal --- add a detail error message text to the current error
890  *
891  * This is exactly like errdetail() except that strings passed to
892  * errdetail_internal are not translated, and are customarily left out of the
893  * internationalization message dictionary.  This should be used for detail
894  * messages that seem not worth translating for one reason or another
895  * (typically, that they don't seem to be useful to average users).
896  */
897 int
errdetail_internal(const char * fmt,...)898 errdetail_internal(const char *fmt,...)
899 {
900 	ErrorData  *edata = &errordata[errordata_stack_depth];
901 	MemoryContext oldcontext;
902 
903 	recursion_depth++;
904 	CHECK_STACK_DEPTH();
905 	oldcontext = MemoryContextSwitchTo(edata->assoc_context);
906 
907 	EVALUATE_MESSAGE(edata->domain, detail, false, false);
908 
909 	MemoryContextSwitchTo(oldcontext);
910 	recursion_depth--;
911 	return 0;					/* return value does not matter */
912 }
913 
914 
915 /*
916  * errdetail_log --- add a detail_log error message text to the current error
917  */
918 int
errdetail_log(const char * fmt,...)919 errdetail_log(const char *fmt,...)
920 {
921 	ErrorData  *edata = &errordata[errordata_stack_depth];
922 	MemoryContext oldcontext;
923 
924 	recursion_depth++;
925 	CHECK_STACK_DEPTH();
926 	oldcontext = MemoryContextSwitchTo(edata->assoc_context);
927 
928 	EVALUATE_MESSAGE(edata->domain, detail_log, false, true);
929 
930 	MemoryContextSwitchTo(oldcontext);
931 	recursion_depth--;
932 	return 0;					/* return value does not matter */
933 }
934 
935 /*
936  * errdetail_log_plural --- add a detail_log error message text to the current error
937  * with support for pluralization of the message text
938  */
939 int
errdetail_log_plural(const char * fmt_singular,const char * fmt_plural,unsigned long n,...)940 errdetail_log_plural(const char *fmt_singular, const char *fmt_plural,
941 					 unsigned long n,...)
942 {
943 	ErrorData  *edata = &errordata[errordata_stack_depth];
944 	MemoryContext oldcontext;
945 
946 	recursion_depth++;
947 	CHECK_STACK_DEPTH();
948 	oldcontext = MemoryContextSwitchTo(edata->assoc_context);
949 
950 	EVALUATE_MESSAGE_PLURAL(edata->domain, detail_log, false);
951 
952 	MemoryContextSwitchTo(oldcontext);
953 	recursion_depth--;
954 	return 0;					/* return value does not matter */
955 }
956 
957 
958 /*
959  * errdetail_plural --- add a detail error message text to the current error,
960  * with support for pluralization of the message text
961  */
962 int
errdetail_plural(const char * fmt_singular,const char * fmt_plural,unsigned long n,...)963 errdetail_plural(const char *fmt_singular, const char *fmt_plural,
964 				 unsigned long n,...)
965 {
966 	ErrorData  *edata = &errordata[errordata_stack_depth];
967 	MemoryContext oldcontext;
968 
969 	recursion_depth++;
970 	CHECK_STACK_DEPTH();
971 	oldcontext = MemoryContextSwitchTo(edata->assoc_context);
972 
973 	EVALUATE_MESSAGE_PLURAL(edata->domain, detail, false);
974 
975 	MemoryContextSwitchTo(oldcontext);
976 	recursion_depth--;
977 	return 0;					/* return value does not matter */
978 }
979 
980 
981 /*
982  * errhint --- add a hint error message text to the current error
983  */
984 int
errhint(const char * fmt,...)985 errhint(const char *fmt,...)
986 {
987 	ErrorData  *edata = &errordata[errordata_stack_depth];
988 	MemoryContext oldcontext;
989 
990 	recursion_depth++;
991 	CHECK_STACK_DEPTH();
992 	oldcontext = MemoryContextSwitchTo(edata->assoc_context);
993 
994 	EVALUATE_MESSAGE(edata->domain, hint, false, true);
995 
996 	MemoryContextSwitchTo(oldcontext);
997 	recursion_depth--;
998 	return 0;					/* return value does not matter */
999 }
1000 
1001 
1002 /*
1003  * errcontext_msg --- add a context error message text to the current error
1004  *
1005  * Unlike other cases, multiple calls are allowed to build up a stack of
1006  * context information.  We assume earlier calls represent more-closely-nested
1007  * states.
1008  */
1009 int
errcontext_msg(const char * fmt,...)1010 errcontext_msg(const char *fmt,...)
1011 {
1012 	ErrorData  *edata = &errordata[errordata_stack_depth];
1013 	MemoryContext oldcontext;
1014 
1015 	recursion_depth++;
1016 	CHECK_STACK_DEPTH();
1017 	oldcontext = MemoryContextSwitchTo(edata->assoc_context);
1018 
1019 	EVALUATE_MESSAGE(edata->context_domain, context, true, true);
1020 
1021 	MemoryContextSwitchTo(oldcontext);
1022 	recursion_depth--;
1023 	return 0;					/* return value does not matter */
1024 }
1025 
1026 /*
1027  * set_errcontext_domain --- set message domain to be used by errcontext()
1028  *
1029  * errcontext_msg() can be called from a different module than the original
1030  * ereport(), so we cannot use the message domain passed in errstart() to
1031  * translate it.  Instead, each errcontext_msg() call should be preceded by
1032  * a set_errcontext_domain() call to specify the domain.  This is usually
1033  * done transparently by the errcontext() macro.
1034  *
1035  * Although errcontext is primarily meant for use at call sites distant from
1036  * the original ereport call, there are a few places that invoke errcontext
1037  * within ereport.  The expansion of errcontext as a comma expression calling
1038  * set_errcontext_domain then errcontext_msg is problematic in this case,
1039  * because the intended comma expression becomes two arguments to errfinish,
1040  * which the compiler is at liberty to evaluate in either order.  But in
1041  * such a case, the set_errcontext_domain calls must be selecting the same
1042  * TEXTDOMAIN value that the errstart call did, so order does not matter
1043  * so long as errstart initializes context_domain along with domain.
1044  */
1045 int
set_errcontext_domain(const char * domain)1046 set_errcontext_domain(const char *domain)
1047 {
1048 	ErrorData  *edata = &errordata[errordata_stack_depth];
1049 
1050 	/* we don't bother incrementing recursion_depth */
1051 	CHECK_STACK_DEPTH();
1052 
1053 	/* the default text domain is the backend's */
1054 	edata->context_domain = domain ? domain : PG_TEXTDOMAIN("postgres");
1055 
1056 	return 0;					/* return value does not matter */
1057 }
1058 
1059 
1060 /*
1061  * errhidestmt --- optionally suppress STATEMENT: field of log entry
1062  *
1063  * This should be called if the message text already includes the statement.
1064  */
1065 int
errhidestmt(bool hide_stmt)1066 errhidestmt(bool hide_stmt)
1067 {
1068 	ErrorData  *edata = &errordata[errordata_stack_depth];
1069 
1070 	/* we don't bother incrementing recursion_depth */
1071 	CHECK_STACK_DEPTH();
1072 
1073 	edata->hide_stmt = hide_stmt;
1074 
1075 	return 0;					/* return value does not matter */
1076 }
1077 
1078 /*
1079  * errhidecontext --- optionally suppress CONTEXT: field of log entry
1080  *
1081  * This should only be used for verbose debugging messages where the repeated
1082  * inclusion of context would bloat the log volume too much.
1083  */
1084 int
errhidecontext(bool hide_ctx)1085 errhidecontext(bool hide_ctx)
1086 {
1087 	ErrorData  *edata = &errordata[errordata_stack_depth];
1088 
1089 	/* we don't bother incrementing recursion_depth */
1090 	CHECK_STACK_DEPTH();
1091 
1092 	edata->hide_ctx = hide_ctx;
1093 
1094 	return 0;					/* return value does not matter */
1095 }
1096 
1097 
1098 /*
1099  * errfunction --- add reporting function name to the current error
1100  *
1101  * This is used when backwards compatibility demands that the function
1102  * name appear in messages sent to old-protocol clients.  Note that the
1103  * passed string is expected to be a non-freeable constant string.
1104  */
1105 int
errfunction(const char * funcname)1106 errfunction(const char *funcname)
1107 {
1108 	ErrorData  *edata = &errordata[errordata_stack_depth];
1109 
1110 	/* we don't bother incrementing recursion_depth */
1111 	CHECK_STACK_DEPTH();
1112 
1113 	edata->funcname = funcname;
1114 	edata->show_funcname = true;
1115 
1116 	return 0;					/* return value does not matter */
1117 }
1118 
1119 /*
1120  * errposition --- add cursor position to the current error
1121  */
1122 int
errposition(int cursorpos)1123 errposition(int cursorpos)
1124 {
1125 	ErrorData  *edata = &errordata[errordata_stack_depth];
1126 
1127 	/* we don't bother incrementing recursion_depth */
1128 	CHECK_STACK_DEPTH();
1129 
1130 	edata->cursorpos = cursorpos;
1131 
1132 	return 0;					/* return value does not matter */
1133 }
1134 
1135 /*
1136  * internalerrposition --- add internal cursor position to the current error
1137  */
1138 int
internalerrposition(int cursorpos)1139 internalerrposition(int cursorpos)
1140 {
1141 	ErrorData  *edata = &errordata[errordata_stack_depth];
1142 
1143 	/* we don't bother incrementing recursion_depth */
1144 	CHECK_STACK_DEPTH();
1145 
1146 	edata->internalpos = cursorpos;
1147 
1148 	return 0;					/* return value does not matter */
1149 }
1150 
1151 /*
1152  * internalerrquery --- add internal query text to the current error
1153  *
1154  * Can also pass NULL to drop the internal query text entry.  This case
1155  * is intended for use in error callback subroutines that are editorializing
1156  * on the layout of the error report.
1157  */
1158 int
internalerrquery(const char * query)1159 internalerrquery(const char *query)
1160 {
1161 	ErrorData  *edata = &errordata[errordata_stack_depth];
1162 
1163 	/* we don't bother incrementing recursion_depth */
1164 	CHECK_STACK_DEPTH();
1165 
1166 	if (edata->internalquery)
1167 	{
1168 		pfree(edata->internalquery);
1169 		edata->internalquery = NULL;
1170 	}
1171 
1172 	if (query)
1173 		edata->internalquery = MemoryContextStrdup(edata->assoc_context, query);
1174 
1175 	return 0;					/* return value does not matter */
1176 }
1177 
1178 /*
1179  * err_generic_string -- used to set individual ErrorData string fields
1180  * identified by PG_DIAG_xxx codes.
1181  *
1182  * This intentionally only supports fields that don't use localized strings,
1183  * so that there are no translation considerations.
1184  *
1185  * Most potential callers should not use this directly, but instead prefer
1186  * higher-level abstractions, such as errtablecol() (see relcache.c).
1187  */
1188 int
err_generic_string(int field,const char * str)1189 err_generic_string(int field, const char *str)
1190 {
1191 	ErrorData  *edata = &errordata[errordata_stack_depth];
1192 
1193 	/* we don't bother incrementing recursion_depth */
1194 	CHECK_STACK_DEPTH();
1195 
1196 	switch (field)
1197 	{
1198 		case PG_DIAG_SCHEMA_NAME:
1199 			set_errdata_field(edata->assoc_context, &edata->schema_name, str);
1200 			break;
1201 		case PG_DIAG_TABLE_NAME:
1202 			set_errdata_field(edata->assoc_context, &edata->table_name, str);
1203 			break;
1204 		case PG_DIAG_COLUMN_NAME:
1205 			set_errdata_field(edata->assoc_context, &edata->column_name, str);
1206 			break;
1207 		case PG_DIAG_DATATYPE_NAME:
1208 			set_errdata_field(edata->assoc_context, &edata->datatype_name, str);
1209 			break;
1210 		case PG_DIAG_CONSTRAINT_NAME:
1211 			set_errdata_field(edata->assoc_context, &edata->constraint_name, str);
1212 			break;
1213 		default:
1214 			elog(ERROR, "unsupported ErrorData field id: %d", field);
1215 			break;
1216 	}
1217 
1218 	return 0;					/* return value does not matter */
1219 }
1220 
1221 /*
1222  * set_errdata_field --- set an ErrorData string field
1223  */
1224 static void
set_errdata_field(MemoryContextData * cxt,char ** ptr,const char * str)1225 set_errdata_field(MemoryContextData *cxt, char **ptr, const char *str)
1226 {
1227 	Assert(*ptr == NULL);
1228 	*ptr = MemoryContextStrdup(cxt, str);
1229 }
1230 
1231 /*
1232  * geterrcode --- return the currently set SQLSTATE error code
1233  *
1234  * This is only intended for use in error callback subroutines, since there
1235  * is no other place outside elog.c where the concept is meaningful.
1236  */
1237 int
geterrcode(void)1238 geterrcode(void)
1239 {
1240 	ErrorData  *edata = &errordata[errordata_stack_depth];
1241 
1242 	/* we don't bother incrementing recursion_depth */
1243 	CHECK_STACK_DEPTH();
1244 
1245 	return edata->sqlerrcode;
1246 }
1247 
1248 /*
1249  * geterrposition --- return the currently set error position (0 if none)
1250  *
1251  * This is only intended for use in error callback subroutines, since there
1252  * is no other place outside elog.c where the concept is meaningful.
1253  */
1254 int
geterrposition(void)1255 geterrposition(void)
1256 {
1257 	ErrorData  *edata = &errordata[errordata_stack_depth];
1258 
1259 	/* we don't bother incrementing recursion_depth */
1260 	CHECK_STACK_DEPTH();
1261 
1262 	return edata->cursorpos;
1263 }
1264 
1265 /*
1266  * getinternalerrposition --- same for internal error position
1267  *
1268  * This is only intended for use in error callback subroutines, since there
1269  * is no other place outside elog.c where the concept is meaningful.
1270  */
1271 int
getinternalerrposition(void)1272 getinternalerrposition(void)
1273 {
1274 	ErrorData  *edata = &errordata[errordata_stack_depth];
1275 
1276 	/* we don't bother incrementing recursion_depth */
1277 	CHECK_STACK_DEPTH();
1278 
1279 	return edata->internalpos;
1280 }
1281 
1282 
1283 /*
1284  * elog_start --- startup for old-style API
1285  *
1286  * All that we do here is stash the hidden filename/lineno/funcname
1287  * arguments into a stack entry, along with the current value of errno.
1288  *
1289  * We need this to be separate from elog_finish because there's no other
1290  * C89-compliant way to deal with inserting extra arguments into the elog
1291  * call.  (When using C99's __VA_ARGS__, we could possibly merge this with
1292  * elog_finish, but there doesn't seem to be a good way to save errno before
1293  * evaluating the format arguments if we do that.)
1294  */
1295 void
elog_start(const char * filename,int lineno,const char * funcname)1296 elog_start(const char *filename, int lineno, const char *funcname)
1297 {
1298 	ErrorData  *edata;
1299 
1300 	/* Make sure that memory context initialization has finished */
1301 	if (ErrorContext == NULL)
1302 	{
1303 		/* Oops, hard crash time; very little we can do safely here */
1304 		write_stderr("error occurred at %s:%d before error message processing is available\n",
1305 					 filename ? filename : "(unknown file)", lineno);
1306 		exit(2);
1307 	}
1308 
1309 	if (++errordata_stack_depth >= ERRORDATA_STACK_SIZE)
1310 	{
1311 		/*
1312 		 * Wups, stack not big enough.  We treat this as a PANIC condition
1313 		 * because it suggests an infinite loop of errors during error
1314 		 * recovery.  Note that the message is intentionally not localized,
1315 		 * else failure to convert it to client encoding could cause further
1316 		 * recursion.
1317 		 */
1318 		errordata_stack_depth = -1; /* make room on stack */
1319 		ereport(PANIC, (errmsg_internal("ERRORDATA_STACK_SIZE exceeded")));
1320 	}
1321 
1322 	edata = &errordata[errordata_stack_depth];
1323 	if (filename)
1324 	{
1325 		const char *slash;
1326 
1327 		/* keep only base name, useful especially for vpath builds */
1328 		slash = strrchr(filename, '/');
1329 		if (slash)
1330 			filename = slash + 1;
1331 	}
1332 	edata->filename = filename;
1333 	edata->lineno = lineno;
1334 	edata->funcname = funcname;
1335 	/* errno is saved now so that error parameter eval can't change it */
1336 	edata->saved_errno = errno;
1337 
1338 	/* Use ErrorContext for any allocations done at this level. */
1339 	edata->assoc_context = ErrorContext;
1340 }
1341 
1342 /*
1343  * elog_finish --- finish up for old-style API
1344  */
1345 void
elog_finish(int elevel,const char * fmt,...)1346 elog_finish(int elevel, const char *fmt,...)
1347 {
1348 	ErrorData  *edata = &errordata[errordata_stack_depth];
1349 	MemoryContext oldcontext;
1350 
1351 	CHECK_STACK_DEPTH();
1352 
1353 	/*
1354 	 * Do errstart() to see if we actually want to report the message.
1355 	 */
1356 	errordata_stack_depth--;
1357 	errno = edata->saved_errno;
1358 	if (!errstart(elevel, edata->filename, edata->lineno, edata->funcname, NULL))
1359 		return;					/* nothing to do */
1360 
1361 	/*
1362 	 * Format error message just like errmsg_internal().
1363 	 */
1364 	recursion_depth++;
1365 	oldcontext = MemoryContextSwitchTo(edata->assoc_context);
1366 
1367 	edata->message_id = fmt;
1368 	EVALUATE_MESSAGE(edata->domain, message, false, false);
1369 
1370 	MemoryContextSwitchTo(oldcontext);
1371 	recursion_depth--;
1372 
1373 	/*
1374 	 * And let errfinish() finish up.
1375 	 */
1376 	errfinish(0);
1377 }
1378 
1379 
1380 /*
1381  * Functions to allow construction of error message strings separately from
1382  * the ereport() call itself.
1383  *
1384  * The expected calling convention is
1385  *
1386  *	pre_format_elog_string(errno, domain), var = format_elog_string(format,...)
1387  *
1388  * which can be hidden behind a macro such as GUC_check_errdetail().  We
1389  * assume that any functions called in the arguments of format_elog_string()
1390  * cannot result in re-entrant use of these functions --- otherwise the wrong
1391  * text domain might be used, or the wrong errno substituted for %m.  This is
1392  * okay for the current usage with GUC check hooks, but might need further
1393  * effort someday.
1394  *
1395  * The result of format_elog_string() is stored in ErrorContext, and will
1396  * therefore survive until FlushErrorState() is called.
1397  */
1398 static int	save_format_errnumber;
1399 static const char *save_format_domain;
1400 
1401 void
pre_format_elog_string(int errnumber,const char * domain)1402 pre_format_elog_string(int errnumber, const char *domain)
1403 {
1404 	/* Save errno before evaluation of argument functions can change it */
1405 	save_format_errnumber = errnumber;
1406 	/* Save caller's text domain */
1407 	save_format_domain = domain;
1408 }
1409 
1410 char *
format_elog_string(const char * fmt,...)1411 format_elog_string(const char *fmt,...)
1412 {
1413 	ErrorData	errdata;
1414 	ErrorData  *edata;
1415 	MemoryContext oldcontext;
1416 
1417 	/* Initialize a mostly-dummy error frame */
1418 	edata = &errdata;
1419 	MemSet(edata, 0, sizeof(ErrorData));
1420 	/* the default text domain is the backend's */
1421 	edata->domain = save_format_domain ? save_format_domain : PG_TEXTDOMAIN("postgres");
1422 	/* set the errno to be used to interpret %m */
1423 	edata->saved_errno = save_format_errnumber;
1424 
1425 	oldcontext = MemoryContextSwitchTo(ErrorContext);
1426 
1427 	edata->message_id = fmt;
1428 	EVALUATE_MESSAGE(edata->domain, message, false, true);
1429 
1430 	MemoryContextSwitchTo(oldcontext);
1431 
1432 	return edata->message;
1433 }
1434 
1435 
1436 /*
1437  * Actual output of the top-of-stack error message
1438  *
1439  * In the ereport(ERROR) case this is called from PostgresMain (or not at all,
1440  * if the error is caught by somebody).  For all other severity levels this
1441  * is called by errfinish.
1442  */
1443 void
EmitErrorReport(void)1444 EmitErrorReport(void)
1445 {
1446 	ErrorData  *edata = &errordata[errordata_stack_depth];
1447 	MemoryContext oldcontext;
1448 
1449 	recursion_depth++;
1450 	CHECK_STACK_DEPTH();
1451 	oldcontext = MemoryContextSwitchTo(edata->assoc_context);
1452 
1453 	/*
1454 	 * Call hook before sending message to log.  The hook function is allowed
1455 	 * to turn off edata->output_to_server, so we must recheck that afterward.
1456 	 * Making any other change in the content of edata is not considered
1457 	 * supported.
1458 	 *
1459 	 * Note: the reason why the hook can only turn off output_to_server, and
1460 	 * not turn it on, is that it'd be unreliable: we will never get here at
1461 	 * all if errstart() deems the message uninteresting.  A hook that could
1462 	 * make decisions in that direction would have to hook into errstart(),
1463 	 * where it would have much less information available.  emit_log_hook is
1464 	 * intended for custom log filtering and custom log message transmission
1465 	 * mechanisms.
1466 	 *
1467 	 * The log hook has access to both the translated and original English
1468 	 * error message text, which is passed through to allow it to be used as a
1469 	 * message identifier. Note that the original text is not available for
1470 	 * detail, detail_log, hint and context text elements.
1471 	 */
1472 	if (edata->output_to_server && emit_log_hook)
1473 		(*emit_log_hook) (edata);
1474 
1475 	/* Send to server log, if enabled */
1476 	if (edata->output_to_server)
1477 		send_message_to_server_log(edata);
1478 
1479 	/* Send to client, if enabled */
1480 	if (edata->output_to_client)
1481 		send_message_to_frontend(edata);
1482 
1483 	MemoryContextSwitchTo(oldcontext);
1484 	recursion_depth--;
1485 }
1486 
1487 /*
1488  * CopyErrorData --- obtain a copy of the topmost error stack entry
1489  *
1490  * This is only for use in error handler code.  The data is copied into the
1491  * current memory context, so callers should always switch away from
1492  * ErrorContext first; otherwise it will be lost when FlushErrorState is done.
1493  */
1494 ErrorData *
CopyErrorData(void)1495 CopyErrorData(void)
1496 {
1497 	ErrorData  *edata = &errordata[errordata_stack_depth];
1498 	ErrorData  *newedata;
1499 
1500 	/*
1501 	 * we don't increment recursion_depth because out-of-memory here does not
1502 	 * indicate a problem within the error subsystem.
1503 	 */
1504 	CHECK_STACK_DEPTH();
1505 
1506 	Assert(CurrentMemoryContext != ErrorContext);
1507 
1508 	/* Copy the struct itself */
1509 	newedata = (ErrorData *) palloc(sizeof(ErrorData));
1510 	memcpy(newedata, edata, sizeof(ErrorData));
1511 
1512 	/* Make copies of separately-allocated fields */
1513 	if (newedata->message)
1514 		newedata->message = pstrdup(newedata->message);
1515 	if (newedata->detail)
1516 		newedata->detail = pstrdup(newedata->detail);
1517 	if (newedata->detail_log)
1518 		newedata->detail_log = pstrdup(newedata->detail_log);
1519 	if (newedata->hint)
1520 		newedata->hint = pstrdup(newedata->hint);
1521 	if (newedata->context)
1522 		newedata->context = pstrdup(newedata->context);
1523 	if (newedata->schema_name)
1524 		newedata->schema_name = pstrdup(newedata->schema_name);
1525 	if (newedata->table_name)
1526 		newedata->table_name = pstrdup(newedata->table_name);
1527 	if (newedata->column_name)
1528 		newedata->column_name = pstrdup(newedata->column_name);
1529 	if (newedata->datatype_name)
1530 		newedata->datatype_name = pstrdup(newedata->datatype_name);
1531 	if (newedata->constraint_name)
1532 		newedata->constraint_name = pstrdup(newedata->constraint_name);
1533 	if (newedata->internalquery)
1534 		newedata->internalquery = pstrdup(newedata->internalquery);
1535 
1536 	/* Use the calling context for string allocation */
1537 	newedata->assoc_context = CurrentMemoryContext;
1538 
1539 	return newedata;
1540 }
1541 
1542 /*
1543  * FreeErrorData --- free the structure returned by CopyErrorData.
1544  *
1545  * Error handlers should use this in preference to assuming they know all
1546  * the separately-allocated fields.
1547  */
1548 void
FreeErrorData(ErrorData * edata)1549 FreeErrorData(ErrorData *edata)
1550 {
1551 	if (edata->message)
1552 		pfree(edata->message);
1553 	if (edata->detail)
1554 		pfree(edata->detail);
1555 	if (edata->detail_log)
1556 		pfree(edata->detail_log);
1557 	if (edata->hint)
1558 		pfree(edata->hint);
1559 	if (edata->context)
1560 		pfree(edata->context);
1561 	if (edata->schema_name)
1562 		pfree(edata->schema_name);
1563 	if (edata->table_name)
1564 		pfree(edata->table_name);
1565 	if (edata->column_name)
1566 		pfree(edata->column_name);
1567 	if (edata->datatype_name)
1568 		pfree(edata->datatype_name);
1569 	if (edata->constraint_name)
1570 		pfree(edata->constraint_name);
1571 	if (edata->internalquery)
1572 		pfree(edata->internalquery);
1573 	pfree(edata);
1574 }
1575 
1576 /*
1577  * FlushErrorState --- flush the error state after error recovery
1578  *
1579  * This should be called by an error handler after it's done processing
1580  * the error; or as soon as it's done CopyErrorData, if it intends to
1581  * do stuff that is likely to provoke another error.  You are not "out" of
1582  * the error subsystem until you have done this.
1583  */
1584 void
FlushErrorState(void)1585 FlushErrorState(void)
1586 {
1587 	/*
1588 	 * Reset stack to empty.  The only case where it would be more than one
1589 	 * deep is if we serviced an error that interrupted construction of
1590 	 * another message.  We assume control escaped out of that message
1591 	 * construction and won't ever go back.
1592 	 */
1593 	errordata_stack_depth = -1;
1594 	recursion_depth = 0;
1595 	/* Delete all data in ErrorContext */
1596 	MemoryContextResetAndDeleteChildren(ErrorContext);
1597 }
1598 
1599 /*
1600  * ThrowErrorData --- report an error described by an ErrorData structure
1601  *
1602  * This is somewhat like ReThrowError, but it allows elevels besides ERROR,
1603  * and the boolean flags such as output_to_server are computed via the
1604  * default rules rather than being copied from the given ErrorData.
1605  * This is primarily used to re-report errors originally reported by
1606  * background worker processes and then propagated (with or without
1607  * modification) to the backend responsible for them.
1608  */
1609 void
ThrowErrorData(ErrorData * edata)1610 ThrowErrorData(ErrorData *edata)
1611 {
1612 	ErrorData  *newedata;
1613 	MemoryContext oldcontext;
1614 
1615 	if (!errstart(edata->elevel, edata->filename, edata->lineno,
1616 				  edata->funcname, NULL))
1617 		return;					/* error is not to be reported at all */
1618 
1619 	newedata = &errordata[errordata_stack_depth];
1620 	recursion_depth++;
1621 	oldcontext = MemoryContextSwitchTo(newedata->assoc_context);
1622 
1623 	/* Copy the supplied fields to the error stack entry. */
1624 	if (edata->sqlerrcode != 0)
1625 		newedata->sqlerrcode = edata->sqlerrcode;
1626 	if (edata->message)
1627 		newedata->message = pstrdup(edata->message);
1628 	if (edata->detail)
1629 		newedata->detail = pstrdup(edata->detail);
1630 	if (edata->detail_log)
1631 		newedata->detail_log = pstrdup(edata->detail_log);
1632 	if (edata->hint)
1633 		newedata->hint = pstrdup(edata->hint);
1634 	if (edata->context)
1635 		newedata->context = pstrdup(edata->context);
1636 	/* assume message_id is not available */
1637 	if (edata->schema_name)
1638 		newedata->schema_name = pstrdup(edata->schema_name);
1639 	if (edata->table_name)
1640 		newedata->table_name = pstrdup(edata->table_name);
1641 	if (edata->column_name)
1642 		newedata->column_name = pstrdup(edata->column_name);
1643 	if (edata->datatype_name)
1644 		newedata->datatype_name = pstrdup(edata->datatype_name);
1645 	if (edata->constraint_name)
1646 		newedata->constraint_name = pstrdup(edata->constraint_name);
1647 	newedata->cursorpos = edata->cursorpos;
1648 	newedata->internalpos = edata->internalpos;
1649 	if (edata->internalquery)
1650 		newedata->internalquery = pstrdup(edata->internalquery);
1651 
1652 	MemoryContextSwitchTo(oldcontext);
1653 	recursion_depth--;
1654 
1655 	/* Process the error. */
1656 	errfinish(0);
1657 }
1658 
1659 /*
1660  * ReThrowError --- re-throw a previously copied error
1661  *
1662  * A handler can do CopyErrorData/FlushErrorState to get out of the error
1663  * subsystem, then do some processing, and finally ReThrowError to re-throw
1664  * the original error.  This is slower than just PG_RE_THROW() but should
1665  * be used if the "some processing" is likely to incur another error.
1666  */
1667 void
ReThrowError(ErrorData * edata)1668 ReThrowError(ErrorData *edata)
1669 {
1670 	ErrorData  *newedata;
1671 
1672 	Assert(edata->elevel == ERROR);
1673 
1674 	/* Push the data back into the error context */
1675 	recursion_depth++;
1676 	MemoryContextSwitchTo(ErrorContext);
1677 
1678 	if (++errordata_stack_depth >= ERRORDATA_STACK_SIZE)
1679 	{
1680 		/*
1681 		 * Wups, stack not big enough.  We treat this as a PANIC condition
1682 		 * because it suggests an infinite loop of errors during error
1683 		 * recovery.
1684 		 */
1685 		errordata_stack_depth = -1; /* make room on stack */
1686 		ereport(PANIC, (errmsg_internal("ERRORDATA_STACK_SIZE exceeded")));
1687 	}
1688 
1689 	newedata = &errordata[errordata_stack_depth];
1690 	memcpy(newedata, edata, sizeof(ErrorData));
1691 
1692 	/* Make copies of separately-allocated fields */
1693 	if (newedata->message)
1694 		newedata->message = pstrdup(newedata->message);
1695 	if (newedata->detail)
1696 		newedata->detail = pstrdup(newedata->detail);
1697 	if (newedata->detail_log)
1698 		newedata->detail_log = pstrdup(newedata->detail_log);
1699 	if (newedata->hint)
1700 		newedata->hint = pstrdup(newedata->hint);
1701 	if (newedata->context)
1702 		newedata->context = pstrdup(newedata->context);
1703 	if (newedata->schema_name)
1704 		newedata->schema_name = pstrdup(newedata->schema_name);
1705 	if (newedata->table_name)
1706 		newedata->table_name = pstrdup(newedata->table_name);
1707 	if (newedata->column_name)
1708 		newedata->column_name = pstrdup(newedata->column_name);
1709 	if (newedata->datatype_name)
1710 		newedata->datatype_name = pstrdup(newedata->datatype_name);
1711 	if (newedata->constraint_name)
1712 		newedata->constraint_name = pstrdup(newedata->constraint_name);
1713 	if (newedata->internalquery)
1714 		newedata->internalquery = pstrdup(newedata->internalquery);
1715 
1716 	/* Reset the assoc_context to be ErrorContext */
1717 	newedata->assoc_context = ErrorContext;
1718 
1719 	recursion_depth--;
1720 	PG_RE_THROW();
1721 }
1722 
1723 /*
1724  * pg_re_throw --- out-of-line implementation of PG_RE_THROW() macro
1725  */
1726 void
pg_re_throw(void)1727 pg_re_throw(void)
1728 {
1729 	/* If possible, throw the error to the next outer setjmp handler */
1730 	if (PG_exception_stack != NULL)
1731 		siglongjmp(*PG_exception_stack, 1);
1732 	else
1733 	{
1734 		/*
1735 		 * If we get here, elog(ERROR) was thrown inside a PG_TRY block, which
1736 		 * we have now exited only to discover that there is no outer setjmp
1737 		 * handler to pass the error to.  Had the error been thrown outside
1738 		 * the block to begin with, we'd have promoted the error to FATAL, so
1739 		 * the correct behavior is to make it FATAL now; that is, emit it and
1740 		 * then call proc_exit.
1741 		 */
1742 		ErrorData  *edata = &errordata[errordata_stack_depth];
1743 
1744 		Assert(errordata_stack_depth >= 0);
1745 		Assert(edata->elevel == ERROR);
1746 		edata->elevel = FATAL;
1747 
1748 		/*
1749 		 * At least in principle, the increase in severity could have changed
1750 		 * where-to-output decisions, so recalculate.  This should stay in
1751 		 * sync with errstart(), which see for comments.
1752 		 */
1753 		if (IsPostmasterEnvironment)
1754 			edata->output_to_server = is_log_level_output(FATAL,
1755 														  log_min_messages);
1756 		else
1757 			edata->output_to_server = (FATAL >= log_min_messages);
1758 		if (whereToSendOutput == DestRemote)
1759 			edata->output_to_client = true;
1760 
1761 		/*
1762 		 * We can use errfinish() for the rest, but we don't want it to call
1763 		 * any error context routines a second time.  Since we know we are
1764 		 * about to exit, it should be OK to just clear the context stack.
1765 		 */
1766 		error_context_stack = NULL;
1767 
1768 		errfinish(0);
1769 	}
1770 
1771 	/* Doesn't return ... */
1772 	ExceptionalCondition("pg_re_throw tried to return", "FailedAssertion",
1773 						 __FILE__, __LINE__);
1774 }
1775 
1776 
1777 /*
1778  * GetErrorContextStack - Return the context stack, for display/diags
1779  *
1780  * Returns a pstrdup'd string in the caller's context which includes the PG
1781  * error call stack.  It is the caller's responsibility to ensure this string
1782  * is pfree'd (or its context cleaned up) when done.
1783  *
1784  * This information is collected by traversing the error contexts and calling
1785  * each context's callback function, each of which is expected to call
1786  * errcontext() to return a string which can be presented to the user.
1787  */
1788 char *
GetErrorContextStack(void)1789 GetErrorContextStack(void)
1790 {
1791 	ErrorData  *edata;
1792 	ErrorContextCallback *econtext;
1793 
1794 	/*
1795 	 * Okay, crank up a stack entry to store the info in.
1796 	 */
1797 	recursion_depth++;
1798 
1799 	if (++errordata_stack_depth >= ERRORDATA_STACK_SIZE)
1800 	{
1801 		/*
1802 		 * Wups, stack not big enough.  We treat this as a PANIC condition
1803 		 * because it suggests an infinite loop of errors during error
1804 		 * recovery.
1805 		 */
1806 		errordata_stack_depth = -1; /* make room on stack */
1807 		ereport(PANIC, (errmsg_internal("ERRORDATA_STACK_SIZE exceeded")));
1808 	}
1809 
1810 	/*
1811 	 * Things look good so far, so initialize our error frame
1812 	 */
1813 	edata = &errordata[errordata_stack_depth];
1814 	MemSet(edata, 0, sizeof(ErrorData));
1815 
1816 	/*
1817 	 * Set up assoc_context to be the caller's context, so any allocations
1818 	 * done (which will include edata->context) will use their context.
1819 	 */
1820 	edata->assoc_context = CurrentMemoryContext;
1821 
1822 	/*
1823 	 * Call any context callback functions to collect the context information
1824 	 * into edata->context.
1825 	 *
1826 	 * Errors occurring in callback functions should go through the regular
1827 	 * error handling code which should handle any recursive errors, though we
1828 	 * double-check above, just in case.
1829 	 */
1830 	for (econtext = error_context_stack;
1831 		 econtext != NULL;
1832 		 econtext = econtext->previous)
1833 		(*econtext->callback) (econtext->arg);
1834 
1835 	/*
1836 	 * Clean ourselves off the stack, any allocations done should have been
1837 	 * using edata->assoc_context, which we set up earlier to be the caller's
1838 	 * context, so we're free to just remove our entry off the stack and
1839 	 * decrement recursion depth and exit.
1840 	 */
1841 	errordata_stack_depth--;
1842 	recursion_depth--;
1843 
1844 	/*
1845 	 * Return a pointer to the string the caller asked for, which should have
1846 	 * been allocated in their context.
1847 	 */
1848 	return edata->context;
1849 }
1850 
1851 
1852 /*
1853  * Initialization of error output file
1854  */
1855 void
DebugFileOpen(void)1856 DebugFileOpen(void)
1857 {
1858 	int			fd,
1859 				istty;
1860 
1861 	if (OutputFileName[0])
1862 	{
1863 		/*
1864 		 * A debug-output file name was given.
1865 		 *
1866 		 * Make sure we can write the file, and find out if it's a tty.
1867 		 */
1868 		if ((fd = open(OutputFileName, O_CREAT | O_APPEND | O_WRONLY,
1869 					   0666)) < 0)
1870 			ereport(FATAL,
1871 					(errcode_for_file_access(),
1872 					 errmsg("could not open file \"%s\": %m", OutputFileName)));
1873 		istty = isatty(fd);
1874 		close(fd);
1875 
1876 		/*
1877 		 * Redirect our stderr to the debug output file.
1878 		 */
1879 		if (!freopen(OutputFileName, "a", stderr))
1880 			ereport(FATAL,
1881 					(errcode_for_file_access(),
1882 					 errmsg("could not reopen file \"%s\" as stderr: %m",
1883 							OutputFileName)));
1884 
1885 		/*
1886 		 * If the file is a tty and we're running under the postmaster, try to
1887 		 * send stdout there as well (if it isn't a tty then stderr will block
1888 		 * out stdout, so we may as well let stdout go wherever it was going
1889 		 * before).
1890 		 */
1891 		if (istty && IsUnderPostmaster)
1892 			if (!freopen(OutputFileName, "a", stdout))
1893 				ereport(FATAL,
1894 						(errcode_for_file_access(),
1895 						 errmsg("could not reopen file \"%s\" as stdout: %m",
1896 								OutputFileName)));
1897 	}
1898 }
1899 
1900 
1901 #ifdef HAVE_SYSLOG
1902 
1903 /*
1904  * Set or update the parameters for syslog logging
1905  */
1906 void
set_syslog_parameters(const char * ident,int facility)1907 set_syslog_parameters(const char *ident, int facility)
1908 {
1909 	/*
1910 	 * guc.c is likely to call us repeatedly with same parameters, so don't
1911 	 * thrash the syslog connection unnecessarily.  Also, we do not re-open
1912 	 * the connection until needed, since this routine will get called whether
1913 	 * or not Log_destination actually mentions syslog.
1914 	 *
1915 	 * Note that we make our own copy of the ident string rather than relying
1916 	 * on guc.c's.  This may be overly paranoid, but it ensures that we cannot
1917 	 * accidentally free a string that syslog is still using.
1918 	 */
1919 	if (syslog_ident == NULL || strcmp(syslog_ident, ident) != 0 ||
1920 		syslog_facility != facility)
1921 	{
1922 		if (openlog_done)
1923 		{
1924 			closelog();
1925 			openlog_done = false;
1926 		}
1927 		if (syslog_ident)
1928 			free(syslog_ident);
1929 		syslog_ident = strdup(ident);
1930 		/* if the strdup fails, we will cope in write_syslog() */
1931 		syslog_facility = facility;
1932 	}
1933 }
1934 
1935 
1936 /*
1937  * Write a message line to syslog
1938  */
1939 static void
write_syslog(int level,const char * line)1940 write_syslog(int level, const char *line)
1941 {
1942 	static unsigned long seq = 0;
1943 
1944 	int			len;
1945 	const char *nlpos;
1946 
1947 	/* Open syslog connection if not done yet */
1948 	if (!openlog_done)
1949 	{
1950 		openlog(syslog_ident ? syslog_ident : "postgres",
1951 				LOG_PID | LOG_NDELAY | LOG_NOWAIT,
1952 				syslog_facility);
1953 		openlog_done = true;
1954 	}
1955 
1956 	/*
1957 	 * We add a sequence number to each log message to suppress "same"
1958 	 * messages.
1959 	 */
1960 	seq++;
1961 
1962 	/*
1963 	 * Our problem here is that many syslog implementations don't handle long
1964 	 * messages in an acceptable manner. While this function doesn't help that
1965 	 * fact, it does work around by splitting up messages into smaller pieces.
1966 	 *
1967 	 * We divide into multiple syslog() calls if message is too long or if the
1968 	 * message contains embedded newline(s).
1969 	 */
1970 	len = strlen(line);
1971 	nlpos = strchr(line, '\n');
1972 	if (syslog_split_messages && (len > PG_SYSLOG_LIMIT || nlpos != NULL))
1973 	{
1974 		int			chunk_nr = 0;
1975 
1976 		while (len > 0)
1977 		{
1978 			char		buf[PG_SYSLOG_LIMIT + 1];
1979 			int			buflen;
1980 			int			i;
1981 
1982 			/* if we start at a newline, move ahead one char */
1983 			if (line[0] == '\n')
1984 			{
1985 				line++;
1986 				len--;
1987 				/* we need to recompute the next newline's position, too */
1988 				nlpos = strchr(line, '\n');
1989 				continue;
1990 			}
1991 
1992 			/* copy one line, or as much as will fit, to buf */
1993 			if (nlpos != NULL)
1994 				buflen = nlpos - line;
1995 			else
1996 				buflen = len;
1997 			buflen = Min(buflen, PG_SYSLOG_LIMIT);
1998 			memcpy(buf, line, buflen);
1999 			buf[buflen] = '\0';
2000 
2001 			/* trim to multibyte letter boundary */
2002 			buflen = pg_mbcliplen(buf, buflen, buflen);
2003 			if (buflen <= 0)
2004 				return;
2005 			buf[buflen] = '\0';
2006 
2007 			/* already word boundary? */
2008 			if (line[buflen] != '\0' &&
2009 				!isspace((unsigned char) line[buflen]))
2010 			{
2011 				/* try to divide at word boundary */
2012 				i = buflen - 1;
2013 				while (i > 0 && !isspace((unsigned char) buf[i]))
2014 					i--;
2015 
2016 				if (i > 0)		/* else couldn't divide word boundary */
2017 				{
2018 					buflen = i;
2019 					buf[i] = '\0';
2020 				}
2021 			}
2022 
2023 			chunk_nr++;
2024 
2025 			if (syslog_sequence_numbers)
2026 				syslog(level, "[%lu-%d] %s", seq, chunk_nr, buf);
2027 			else
2028 				syslog(level, "[%d] %s", chunk_nr, buf);
2029 
2030 			line += buflen;
2031 			len -= buflen;
2032 		}
2033 	}
2034 	else
2035 	{
2036 		/* message short enough */
2037 		if (syslog_sequence_numbers)
2038 			syslog(level, "[%lu] %s", seq, line);
2039 		else
2040 			syslog(level, "%s", line);
2041 	}
2042 }
2043 #endif							/* HAVE_SYSLOG */
2044 
2045 #ifdef WIN32
2046 /*
2047  * Get the PostgreSQL equivalent of the Windows ANSI code page.  "ANSI" system
2048  * interfaces (e.g. CreateFileA()) expect string arguments in this encoding.
2049  * Every process in a given system will find the same value at all times.
2050  */
2051 static int
GetACPEncoding(void)2052 GetACPEncoding(void)
2053 {
2054 	static int	encoding = -2;
2055 
2056 	if (encoding == -2)
2057 		encoding = pg_codepage_to_encoding(GetACP());
2058 
2059 	return encoding;
2060 }
2061 
2062 /*
2063  * Write a message line to the windows event log
2064  */
2065 static void
write_eventlog(int level,const char * line,int len)2066 write_eventlog(int level, const char *line, int len)
2067 {
2068 	WCHAR	   *utf16;
2069 	int			eventlevel = EVENTLOG_ERROR_TYPE;
2070 	static HANDLE evtHandle = INVALID_HANDLE_VALUE;
2071 
2072 	if (evtHandle == INVALID_HANDLE_VALUE)
2073 	{
2074 		evtHandle = RegisterEventSource(NULL,
2075 										event_source ? event_source : DEFAULT_EVENT_SOURCE);
2076 		if (evtHandle == NULL)
2077 		{
2078 			evtHandle = INVALID_HANDLE_VALUE;
2079 			return;
2080 		}
2081 	}
2082 
2083 	switch (level)
2084 	{
2085 		case DEBUG5:
2086 		case DEBUG4:
2087 		case DEBUG3:
2088 		case DEBUG2:
2089 		case DEBUG1:
2090 		case LOG:
2091 		case LOG_SERVER_ONLY:
2092 		case INFO:
2093 		case NOTICE:
2094 			eventlevel = EVENTLOG_INFORMATION_TYPE;
2095 			break;
2096 		case WARNING:
2097 			eventlevel = EVENTLOG_WARNING_TYPE;
2098 			break;
2099 		case ERROR:
2100 		case FATAL:
2101 		case PANIC:
2102 		default:
2103 			eventlevel = EVENTLOG_ERROR_TYPE;
2104 			break;
2105 	}
2106 
2107 	/*
2108 	 * If message character encoding matches the encoding expected by
2109 	 * ReportEventA(), call it to avoid the hazards of conversion.  Otherwise,
2110 	 * try to convert the message to UTF16 and write it with ReportEventW().
2111 	 * Fall back on ReportEventA() if conversion failed.
2112 	 *
2113 	 * Since we palloc the structure required for conversion, also fall
2114 	 * through to writing unconverted if we have not yet set up
2115 	 * CurrentMemoryContext.
2116 	 *
2117 	 * Also verify that we are not on our way into error recursion trouble due
2118 	 * to error messages thrown deep inside pgwin32_message_to_UTF16().
2119 	 */
2120 	if (!in_error_recursion_trouble() &&
2121 		CurrentMemoryContext != NULL &&
2122 		GetMessageEncoding() != GetACPEncoding())
2123 	{
2124 		utf16 = pgwin32_message_to_UTF16(line, len, NULL);
2125 		if (utf16)
2126 		{
2127 			ReportEventW(evtHandle,
2128 						 eventlevel,
2129 						 0,
2130 						 0,		/* All events are Id 0 */
2131 						 NULL,
2132 						 1,
2133 						 0,
2134 						 (LPCWSTR *) &utf16,
2135 						 NULL);
2136 			/* XXX Try ReportEventA() when ReportEventW() fails? */
2137 
2138 			pfree(utf16);
2139 			return;
2140 		}
2141 	}
2142 	ReportEventA(evtHandle,
2143 				 eventlevel,
2144 				 0,
2145 				 0,				/* All events are Id 0 */
2146 				 NULL,
2147 				 1,
2148 				 0,
2149 				 &line,
2150 				 NULL);
2151 }
2152 #endif							/* WIN32 */
2153 
2154 static void
write_console(const char * line,int len)2155 write_console(const char *line, int len)
2156 {
2157 	int			rc;
2158 
2159 #ifdef WIN32
2160 
2161 	/*
2162 	 * Try to convert the message to UTF16 and write it with WriteConsoleW().
2163 	 * Fall back on write() if anything fails.
2164 	 *
2165 	 * In contrast to write_eventlog(), don't skip straight to write() based
2166 	 * on the applicable encodings.  Unlike WriteConsoleW(), write() depends
2167 	 * on the suitability of the console output code page.  Since we put
2168 	 * stderr into binary mode in SubPostmasterMain(), write() skips the
2169 	 * necessary translation anyway.
2170 	 *
2171 	 * WriteConsoleW() will fail if stderr is redirected, so just fall through
2172 	 * to writing unconverted to the logfile in this case.
2173 	 *
2174 	 * Since we palloc the structure required for conversion, also fall
2175 	 * through to writing unconverted if we have not yet set up
2176 	 * CurrentMemoryContext.
2177 	 */
2178 	if (!in_error_recursion_trouble() &&
2179 		!redirection_done &&
2180 		CurrentMemoryContext != NULL)
2181 	{
2182 		WCHAR	   *utf16;
2183 		int			utf16len;
2184 
2185 		utf16 = pgwin32_message_to_UTF16(line, len, &utf16len);
2186 		if (utf16 != NULL)
2187 		{
2188 			HANDLE		stdHandle;
2189 			DWORD		written;
2190 
2191 			stdHandle = GetStdHandle(STD_ERROR_HANDLE);
2192 			if (WriteConsoleW(stdHandle, utf16, utf16len, &written, NULL))
2193 			{
2194 				pfree(utf16);
2195 				return;
2196 			}
2197 
2198 			/*
2199 			 * In case WriteConsoleW() failed, fall back to writing the
2200 			 * message unconverted.
2201 			 */
2202 			pfree(utf16);
2203 		}
2204 	}
2205 #else
2206 
2207 	/*
2208 	 * Conversion on non-win32 platforms is not implemented yet. It requires
2209 	 * non-throw version of pg_do_encoding_conversion(), that converts
2210 	 * unconvertable characters to '?' without errors.
2211 	 */
2212 #endif
2213 
2214 	/*
2215 	 * We ignore any error from write() here.  We have no useful way to report
2216 	 * it ... certainly whining on stderr isn't likely to be productive.
2217 	 */
2218 	rc = write(fileno(stderr), line, len);
2219 	(void) rc;
2220 }
2221 
2222 /*
2223  * setup formatted_log_time, for consistent times between CSV and regular logs
2224  */
2225 static void
setup_formatted_log_time(void)2226 setup_formatted_log_time(void)
2227 {
2228 	pg_time_t	stamp_time;
2229 	char		msbuf[13];
2230 
2231 	if (!saved_timeval_set)
2232 	{
2233 		gettimeofday(&saved_timeval, NULL);
2234 		saved_timeval_set = true;
2235 	}
2236 
2237 	stamp_time = (pg_time_t) saved_timeval.tv_sec;
2238 
2239 	/*
2240 	 * Note: we expect that guc.c will ensure that log_timezone is set up (at
2241 	 * least with a minimal GMT value) before Log_line_prefix can become
2242 	 * nonempty or CSV mode can be selected.
2243 	 */
2244 	pg_strftime(formatted_log_time, FORMATTED_TS_LEN,
2245 	/* leave room for milliseconds... */
2246 				"%Y-%m-%d %H:%M:%S     %Z",
2247 				pg_localtime(&stamp_time, log_timezone));
2248 
2249 	/* 'paste' milliseconds into place... */
2250 	sprintf(msbuf, ".%03d", (int) (saved_timeval.tv_usec / 1000));
2251 	memcpy(formatted_log_time + 19, msbuf, 4);
2252 }
2253 
2254 /*
2255  * setup formatted_start_time
2256  */
2257 static void
setup_formatted_start_time(void)2258 setup_formatted_start_time(void)
2259 {
2260 	pg_time_t	stamp_time = (pg_time_t) MyStartTime;
2261 
2262 	/*
2263 	 * Note: we expect that guc.c will ensure that log_timezone is set up (at
2264 	 * least with a minimal GMT value) before Log_line_prefix can become
2265 	 * nonempty or CSV mode can be selected.
2266 	 */
2267 	pg_strftime(formatted_start_time, FORMATTED_TS_LEN,
2268 				"%Y-%m-%d %H:%M:%S %Z",
2269 				pg_localtime(&stamp_time, log_timezone));
2270 }
2271 
2272 /*
2273  * process_log_prefix_padding --- helper function for processing the format
2274  * string in log_line_prefix
2275  *
2276  * Note: This function returns NULL if it finds something which
2277  * it deems invalid in the format string.
2278  */
2279 static const char *
process_log_prefix_padding(const char * p,int * ppadding)2280 process_log_prefix_padding(const char *p, int *ppadding)
2281 {
2282 	int			paddingsign = 1;
2283 	int			padding = 0;
2284 
2285 	if (*p == '-')
2286 	{
2287 		p++;
2288 
2289 		if (*p == '\0')			/* Did the buf end in %- ? */
2290 			return NULL;
2291 		paddingsign = -1;
2292 	}
2293 
2294 	/* generate an int version of the numerical string */
2295 	while (*p >= '0' && *p <= '9')
2296 		padding = padding * 10 + (*p++ - '0');
2297 
2298 	/* format is invalid if it ends with the padding number */
2299 	if (*p == '\0')
2300 		return NULL;
2301 
2302 	padding *= paddingsign;
2303 	*ppadding = padding;
2304 	return p;
2305 }
2306 
2307 /*
2308  * Format tag info for log lines; append to the provided buffer.
2309  */
2310 static void
log_line_prefix(StringInfo buf,ErrorData * edata)2311 log_line_prefix(StringInfo buf, ErrorData *edata)
2312 {
2313 	/* static counter for line numbers */
2314 	static long log_line_number = 0;
2315 
2316 	/* has counter been reset in current process? */
2317 	static int	log_my_pid = 0;
2318 	int			padding;
2319 	const char *p;
2320 
2321 	/*
2322 	 * This is one of the few places where we'd rather not inherit a static
2323 	 * variable's value from the postmaster.  But since we will, reset it when
2324 	 * MyProcPid changes. MyStartTime also changes when MyProcPid does, so
2325 	 * reset the formatted start timestamp too.
2326 	 */
2327 	if (log_my_pid != MyProcPid)
2328 	{
2329 		log_line_number = 0;
2330 		log_my_pid = MyProcPid;
2331 		formatted_start_time[0] = '\0';
2332 	}
2333 	log_line_number++;
2334 
2335 	if (Log_line_prefix == NULL)
2336 		return;					/* in case guc hasn't run yet */
2337 
2338 	for (p = Log_line_prefix; *p != '\0'; p++)
2339 	{
2340 		if (*p != '%')
2341 		{
2342 			/* literal char, just copy */
2343 			appendStringInfoChar(buf, *p);
2344 			continue;
2345 		}
2346 
2347 		/* must be a '%', so skip to the next char */
2348 		p++;
2349 		if (*p == '\0')
2350 			break;				/* format error - ignore it */
2351 		else if (*p == '%')
2352 		{
2353 			/* string contains %% */
2354 			appendStringInfoChar(buf, '%');
2355 			continue;
2356 		}
2357 
2358 
2359 		/*
2360 		 * Process any formatting which may exist after the '%'.  Note that
2361 		 * process_log_prefix_padding moves p past the padding number if it
2362 		 * exists.
2363 		 *
2364 		 * Note: Since only '-', '0' to '9' are valid formatting characters we
2365 		 * can do a quick check here to pre-check for formatting. If the char
2366 		 * is not formatting then we can skip a useless function call.
2367 		 *
2368 		 * Further note: At least on some platforms, passing %*s rather than
2369 		 * %s to appendStringInfo() is substantially slower, so many of the
2370 		 * cases below avoid doing that unless non-zero padding is in fact
2371 		 * specified.
2372 		 */
2373 		if (*p > '9')
2374 			padding = 0;
2375 		else if ((p = process_log_prefix_padding(p, &padding)) == NULL)
2376 			break;
2377 
2378 		/* process the option */
2379 		switch (*p)
2380 		{
2381 			case 'a':
2382 				if (MyProcPort)
2383 				{
2384 					const char *appname = application_name;
2385 
2386 					if (appname == NULL || *appname == '\0')
2387 						appname = _("[unknown]");
2388 					if (padding != 0)
2389 						appendStringInfo(buf, "%*s", padding, appname);
2390 					else
2391 						appendStringInfoString(buf, appname);
2392 				}
2393 				else if (padding != 0)
2394 					appendStringInfoSpaces(buf,
2395 										   padding > 0 ? padding : -padding);
2396 
2397 				break;
2398 			case 'u':
2399 				if (MyProcPort)
2400 				{
2401 					const char *username = MyProcPort->user_name;
2402 
2403 					if (username == NULL || *username == '\0')
2404 						username = _("[unknown]");
2405 					if (padding != 0)
2406 						appendStringInfo(buf, "%*s", padding, username);
2407 					else
2408 						appendStringInfoString(buf, username);
2409 				}
2410 				else if (padding != 0)
2411 					appendStringInfoSpaces(buf,
2412 										   padding > 0 ? padding : -padding);
2413 				break;
2414 			case 'd':
2415 				if (MyProcPort)
2416 				{
2417 					const char *dbname = MyProcPort->database_name;
2418 
2419 					if (dbname == NULL || *dbname == '\0')
2420 						dbname = _("[unknown]");
2421 					if (padding != 0)
2422 						appendStringInfo(buf, "%*s", padding, dbname);
2423 					else
2424 						appendStringInfoString(buf, dbname);
2425 				}
2426 				else if (padding != 0)
2427 					appendStringInfoSpaces(buf,
2428 										   padding > 0 ? padding : -padding);
2429 				break;
2430 			case 'c':
2431 				if (padding != 0)
2432 				{
2433 					char		strfbuf[128];
2434 
2435 					snprintf(strfbuf, sizeof(strfbuf) - 1, "%lx.%x",
2436 							 (long) (MyStartTime), MyProcPid);
2437 					appendStringInfo(buf, "%*s", padding, strfbuf);
2438 				}
2439 				else
2440 					appendStringInfo(buf, "%lx.%x", (long) (MyStartTime), MyProcPid);
2441 				break;
2442 			case 'p':
2443 				if (padding != 0)
2444 					appendStringInfo(buf, "%*d", padding, MyProcPid);
2445 				else
2446 					appendStringInfo(buf, "%d", MyProcPid);
2447 				break;
2448 			case 'l':
2449 				if (padding != 0)
2450 					appendStringInfo(buf, "%*ld", padding, log_line_number);
2451 				else
2452 					appendStringInfo(buf, "%ld", log_line_number);
2453 				break;
2454 			case 'm':
2455 				setup_formatted_log_time();
2456 				if (padding != 0)
2457 					appendStringInfo(buf, "%*s", padding, formatted_log_time);
2458 				else
2459 					appendStringInfoString(buf, formatted_log_time);
2460 				break;
2461 			case 't':
2462 				{
2463 					pg_time_t	stamp_time = (pg_time_t) time(NULL);
2464 					char		strfbuf[128];
2465 
2466 					pg_strftime(strfbuf, sizeof(strfbuf),
2467 								"%Y-%m-%d %H:%M:%S %Z",
2468 								pg_localtime(&stamp_time, log_timezone));
2469 					if (padding != 0)
2470 						appendStringInfo(buf, "%*s", padding, strfbuf);
2471 					else
2472 						appendStringInfoString(buf, strfbuf);
2473 				}
2474 				break;
2475 			case 'n':
2476 				{
2477 					char		strfbuf[128];
2478 
2479 					if (!saved_timeval_set)
2480 					{
2481 						gettimeofday(&saved_timeval, NULL);
2482 						saved_timeval_set = true;
2483 					}
2484 
2485 					snprintf(strfbuf, sizeof(strfbuf), "%ld.%03d",
2486 							 (long) saved_timeval.tv_sec,
2487 							 (int) (saved_timeval.tv_usec / 1000));
2488 
2489 					if (padding != 0)
2490 						appendStringInfo(buf, "%*s", padding, strfbuf);
2491 					else
2492 						appendStringInfoString(buf, strfbuf);
2493 				}
2494 				break;
2495 			case 's':
2496 				if (formatted_start_time[0] == '\0')
2497 					setup_formatted_start_time();
2498 				if (padding != 0)
2499 					appendStringInfo(buf, "%*s", padding, formatted_start_time);
2500 				else
2501 					appendStringInfoString(buf, formatted_start_time);
2502 				break;
2503 			case 'i':
2504 				if (MyProcPort)
2505 				{
2506 					const char *psdisp;
2507 					int			displen;
2508 
2509 					psdisp = get_ps_display(&displen);
2510 					if (padding != 0)
2511 						appendStringInfo(buf, "%*s", padding, psdisp);
2512 					else
2513 						appendBinaryStringInfo(buf, psdisp, displen);
2514 
2515 				}
2516 				else if (padding != 0)
2517 					appendStringInfoSpaces(buf,
2518 										   padding > 0 ? padding : -padding);
2519 				break;
2520 			case 'r':
2521 				if (MyProcPort && MyProcPort->remote_host)
2522 				{
2523 					if (padding != 0)
2524 					{
2525 						if (MyProcPort->remote_port && MyProcPort->remote_port[0] != '\0')
2526 						{
2527 							/*
2528 							 * This option is slightly special as the port
2529 							 * number may be appended onto the end. Here we
2530 							 * need to build 1 string which contains the
2531 							 * remote_host and optionally the remote_port (if
2532 							 * set) so we can properly align the string.
2533 							 */
2534 
2535 							char	   *hostport;
2536 
2537 							hostport = psprintf("%s(%s)", MyProcPort->remote_host, MyProcPort->remote_port);
2538 							appendStringInfo(buf, "%*s", padding, hostport);
2539 							pfree(hostport);
2540 						}
2541 						else
2542 							appendStringInfo(buf, "%*s", padding, MyProcPort->remote_host);
2543 					}
2544 					else
2545 					{
2546 						/* padding is 0, so we don't need a temp buffer */
2547 						appendStringInfoString(buf, MyProcPort->remote_host);
2548 						if (MyProcPort->remote_port &&
2549 							MyProcPort->remote_port[0] != '\0')
2550 							appendStringInfo(buf, "(%s)",
2551 											 MyProcPort->remote_port);
2552 					}
2553 
2554 				}
2555 				else if (padding != 0)
2556 					appendStringInfoSpaces(buf,
2557 										   padding > 0 ? padding : -padding);
2558 				break;
2559 			case 'h':
2560 				if (MyProcPort && MyProcPort->remote_host)
2561 				{
2562 					if (padding != 0)
2563 						appendStringInfo(buf, "%*s", padding, MyProcPort->remote_host);
2564 					else
2565 						appendStringInfoString(buf, MyProcPort->remote_host);
2566 				}
2567 				else if (padding != 0)
2568 					appendStringInfoSpaces(buf,
2569 										   padding > 0 ? padding : -padding);
2570 				break;
2571 			case 'q':
2572 				/* in postmaster and friends, stop if %q is seen */
2573 				/* in a backend, just ignore */
2574 				if (MyProcPort == NULL)
2575 					return;
2576 				break;
2577 			case 'v':
2578 				/* keep VXID format in sync with lockfuncs.c */
2579 				if (MyProc != NULL && MyProc->backendId != InvalidBackendId)
2580 				{
2581 					if (padding != 0)
2582 					{
2583 						char		strfbuf[128];
2584 
2585 						snprintf(strfbuf, sizeof(strfbuf) - 1, "%d/%u",
2586 								 MyProc->backendId, MyProc->lxid);
2587 						appendStringInfo(buf, "%*s", padding, strfbuf);
2588 					}
2589 					else
2590 						appendStringInfo(buf, "%d/%u", MyProc->backendId, MyProc->lxid);
2591 				}
2592 				else if (padding != 0)
2593 					appendStringInfoSpaces(buf,
2594 										   padding > 0 ? padding : -padding);
2595 				break;
2596 			case 'x':
2597 				if (padding != 0)
2598 					appendStringInfo(buf, "%*u", padding, GetTopTransactionIdIfAny());
2599 				else
2600 					appendStringInfo(buf, "%u", GetTopTransactionIdIfAny());
2601 				break;
2602 			case 'e':
2603 				if (padding != 0)
2604 					appendStringInfo(buf, "%*s", padding, unpack_sql_state(edata->sqlerrcode));
2605 				else
2606 					appendStringInfoString(buf, unpack_sql_state(edata->sqlerrcode));
2607 				break;
2608 			default:
2609 				/* format error - ignore it */
2610 				break;
2611 		}
2612 	}
2613 }
2614 
2615 /*
2616  * append a CSV'd version of a string to a StringInfo
2617  * We use the PostgreSQL defaults for CSV, i.e. quote = escape = '"'
2618  * If it's NULL, append nothing.
2619  */
2620 static inline void
appendCSVLiteral(StringInfo buf,const char * data)2621 appendCSVLiteral(StringInfo buf, const char *data)
2622 {
2623 	const char *p = data;
2624 	char		c;
2625 
2626 	/* avoid confusing an empty string with NULL */
2627 	if (p == NULL)
2628 		return;
2629 
2630 	appendStringInfoCharMacro(buf, '"');
2631 	while ((c = *p++) != '\0')
2632 	{
2633 		if (c == '"')
2634 			appendStringInfoCharMacro(buf, '"');
2635 		appendStringInfoCharMacro(buf, c);
2636 	}
2637 	appendStringInfoCharMacro(buf, '"');
2638 }
2639 
2640 /*
2641  * Constructs the error message, depending on the Errordata it gets, in a CSV
2642  * format which is described in doc/src/sgml/config.sgml.
2643  */
2644 static void
write_csvlog(ErrorData * edata)2645 write_csvlog(ErrorData *edata)
2646 {
2647 	StringInfoData buf;
2648 	bool		print_stmt = false;
2649 
2650 	/* static counter for line numbers */
2651 	static long log_line_number = 0;
2652 
2653 	/* has counter been reset in current process? */
2654 	static int	log_my_pid = 0;
2655 
2656 	/*
2657 	 * This is one of the few places where we'd rather not inherit a static
2658 	 * variable's value from the postmaster.  But since we will, reset it when
2659 	 * MyProcPid changes.
2660 	 */
2661 	if (log_my_pid != MyProcPid)
2662 	{
2663 		log_line_number = 0;
2664 		log_my_pid = MyProcPid;
2665 		formatted_start_time[0] = '\0';
2666 	}
2667 	log_line_number++;
2668 
2669 	initStringInfo(&buf);
2670 
2671 	/*
2672 	 * timestamp with milliseconds
2673 	 *
2674 	 * Check if the timestamp is already calculated for the syslog message,
2675 	 * and use it if so.  Otherwise, get the current timestamp.  This is done
2676 	 * to put same timestamp in both syslog and csvlog messages.
2677 	 */
2678 	if (formatted_log_time[0] == '\0')
2679 		setup_formatted_log_time();
2680 
2681 	appendStringInfoString(&buf, formatted_log_time);
2682 	appendStringInfoChar(&buf, ',');
2683 
2684 	/* username */
2685 	if (MyProcPort)
2686 		appendCSVLiteral(&buf, MyProcPort->user_name);
2687 	appendStringInfoChar(&buf, ',');
2688 
2689 	/* database name */
2690 	if (MyProcPort)
2691 		appendCSVLiteral(&buf, MyProcPort->database_name);
2692 	appendStringInfoChar(&buf, ',');
2693 
2694 	/* Process id  */
2695 	if (MyProcPid != 0)
2696 		appendStringInfo(&buf, "%d", MyProcPid);
2697 	appendStringInfoChar(&buf, ',');
2698 
2699 	/* Remote host and port */
2700 	if (MyProcPort && MyProcPort->remote_host)
2701 	{
2702 		appendStringInfoChar(&buf, '"');
2703 		appendStringInfoString(&buf, MyProcPort->remote_host);
2704 		if (MyProcPort->remote_port && MyProcPort->remote_port[0] != '\0')
2705 		{
2706 			appendStringInfoChar(&buf, ':');
2707 			appendStringInfoString(&buf, MyProcPort->remote_port);
2708 		}
2709 		appendStringInfoChar(&buf, '"');
2710 	}
2711 	appendStringInfoChar(&buf, ',');
2712 
2713 	/* session id */
2714 	appendStringInfo(&buf, "%lx.%x", (long) MyStartTime, MyProcPid);
2715 	appendStringInfoChar(&buf, ',');
2716 
2717 	/* Line number */
2718 	appendStringInfo(&buf, "%ld", log_line_number);
2719 	appendStringInfoChar(&buf, ',');
2720 
2721 	/* PS display */
2722 	if (MyProcPort)
2723 	{
2724 		StringInfoData msgbuf;
2725 		const char *psdisp;
2726 		int			displen;
2727 
2728 		initStringInfo(&msgbuf);
2729 
2730 		psdisp = get_ps_display(&displen);
2731 		appendBinaryStringInfo(&msgbuf, psdisp, displen);
2732 		appendCSVLiteral(&buf, msgbuf.data);
2733 
2734 		pfree(msgbuf.data);
2735 	}
2736 	appendStringInfoChar(&buf, ',');
2737 
2738 	/* session start timestamp */
2739 	if (formatted_start_time[0] == '\0')
2740 		setup_formatted_start_time();
2741 	appendStringInfoString(&buf, formatted_start_time);
2742 	appendStringInfoChar(&buf, ',');
2743 
2744 	/* Virtual transaction id */
2745 	/* keep VXID format in sync with lockfuncs.c */
2746 	if (MyProc != NULL && MyProc->backendId != InvalidBackendId)
2747 		appendStringInfo(&buf, "%d/%u", MyProc->backendId, MyProc->lxid);
2748 	appendStringInfoChar(&buf, ',');
2749 
2750 	/* Transaction id */
2751 	appendStringInfo(&buf, "%u", GetTopTransactionIdIfAny());
2752 	appendStringInfoChar(&buf, ',');
2753 
2754 	/* Error severity */
2755 	appendStringInfoString(&buf, _(error_severity(edata->elevel)));
2756 	appendStringInfoChar(&buf, ',');
2757 
2758 	/* SQL state code */
2759 	appendStringInfoString(&buf, unpack_sql_state(edata->sqlerrcode));
2760 	appendStringInfoChar(&buf, ',');
2761 
2762 	/* errmessage */
2763 	appendCSVLiteral(&buf, edata->message);
2764 	appendStringInfoChar(&buf, ',');
2765 
2766 	/* errdetail or errdetail_log */
2767 	if (edata->detail_log)
2768 		appendCSVLiteral(&buf, edata->detail_log);
2769 	else
2770 		appendCSVLiteral(&buf, edata->detail);
2771 	appendStringInfoChar(&buf, ',');
2772 
2773 	/* errhint */
2774 	appendCSVLiteral(&buf, edata->hint);
2775 	appendStringInfoChar(&buf, ',');
2776 
2777 	/* internal query */
2778 	appendCSVLiteral(&buf, edata->internalquery);
2779 	appendStringInfoChar(&buf, ',');
2780 
2781 	/* if printed internal query, print internal pos too */
2782 	if (edata->internalpos > 0 && edata->internalquery != NULL)
2783 		appendStringInfo(&buf, "%d", edata->internalpos);
2784 	appendStringInfoChar(&buf, ',');
2785 
2786 	/* errcontext */
2787 	if (!edata->hide_ctx)
2788 		appendCSVLiteral(&buf, edata->context);
2789 	appendStringInfoChar(&buf, ',');
2790 
2791 	/* user query --- only reported if not disabled by the caller */
2792 	if (is_log_level_output(edata->elevel, log_min_error_statement) &&
2793 		debug_query_string != NULL &&
2794 		!edata->hide_stmt)
2795 		print_stmt = true;
2796 	if (print_stmt)
2797 		appendCSVLiteral(&buf, debug_query_string);
2798 	appendStringInfoChar(&buf, ',');
2799 	if (print_stmt && edata->cursorpos > 0)
2800 		appendStringInfo(&buf, "%d", edata->cursorpos);
2801 	appendStringInfoChar(&buf, ',');
2802 
2803 	/* file error location */
2804 	if (Log_error_verbosity >= PGERROR_VERBOSE)
2805 	{
2806 		StringInfoData msgbuf;
2807 
2808 		initStringInfo(&msgbuf);
2809 
2810 		if (edata->funcname && edata->filename)
2811 			appendStringInfo(&msgbuf, "%s, %s:%d",
2812 							 edata->funcname, edata->filename,
2813 							 edata->lineno);
2814 		else if (edata->filename)
2815 			appendStringInfo(&msgbuf, "%s:%d",
2816 							 edata->filename, edata->lineno);
2817 		appendCSVLiteral(&buf, msgbuf.data);
2818 		pfree(msgbuf.data);
2819 	}
2820 	appendStringInfoChar(&buf, ',');
2821 
2822 	/* application name */
2823 	if (application_name)
2824 		appendCSVLiteral(&buf, application_name);
2825 
2826 	appendStringInfoChar(&buf, '\n');
2827 
2828 	/* If in the syslogger process, try to write messages direct to file */
2829 	if (am_syslogger)
2830 		write_syslogger_file(buf.data, buf.len, LOG_DESTINATION_CSVLOG);
2831 	else
2832 		write_pipe_chunks(buf.data, buf.len, LOG_DESTINATION_CSVLOG);
2833 
2834 	pfree(buf.data);
2835 }
2836 
2837 /*
2838  * Unpack MAKE_SQLSTATE code. Note that this returns a pointer to a
2839  * static buffer.
2840  */
2841 char *
unpack_sql_state(int sql_state)2842 unpack_sql_state(int sql_state)
2843 {
2844 	static char buf[12];
2845 	int			i;
2846 
2847 	for (i = 0; i < 5; i++)
2848 	{
2849 		buf[i] = PGUNSIXBIT(sql_state);
2850 		sql_state >>= 6;
2851 	}
2852 
2853 	buf[i] = '\0';
2854 	return buf;
2855 }
2856 
2857 
2858 /*
2859  * Write error report to server's log
2860  */
2861 static void
send_message_to_server_log(ErrorData * edata)2862 send_message_to_server_log(ErrorData *edata)
2863 {
2864 	StringInfoData buf;
2865 
2866 	initStringInfo(&buf);
2867 
2868 	saved_timeval_set = false;
2869 	formatted_log_time[0] = '\0';
2870 
2871 	log_line_prefix(&buf, edata);
2872 	appendStringInfo(&buf, "%s:  ", _(error_severity(edata->elevel)));
2873 
2874 	if (Log_error_verbosity >= PGERROR_VERBOSE)
2875 		appendStringInfo(&buf, "%s: ", unpack_sql_state(edata->sqlerrcode));
2876 
2877 	if (edata->message)
2878 		append_with_tabs(&buf, edata->message);
2879 	else
2880 		append_with_tabs(&buf, _("missing error text"));
2881 
2882 	if (edata->cursorpos > 0)
2883 		appendStringInfo(&buf, _(" at character %d"),
2884 						 edata->cursorpos);
2885 	else if (edata->internalpos > 0)
2886 		appendStringInfo(&buf, _(" at character %d"),
2887 						 edata->internalpos);
2888 
2889 	appendStringInfoChar(&buf, '\n');
2890 
2891 	if (Log_error_verbosity >= PGERROR_DEFAULT)
2892 	{
2893 		if (edata->detail_log)
2894 		{
2895 			log_line_prefix(&buf, edata);
2896 			appendStringInfoString(&buf, _("DETAIL:  "));
2897 			append_with_tabs(&buf, edata->detail_log);
2898 			appendStringInfoChar(&buf, '\n');
2899 		}
2900 		else if (edata->detail)
2901 		{
2902 			log_line_prefix(&buf, edata);
2903 			appendStringInfoString(&buf, _("DETAIL:  "));
2904 			append_with_tabs(&buf, edata->detail);
2905 			appendStringInfoChar(&buf, '\n');
2906 		}
2907 		if (edata->hint)
2908 		{
2909 			log_line_prefix(&buf, edata);
2910 			appendStringInfoString(&buf, _("HINT:  "));
2911 			append_with_tabs(&buf, edata->hint);
2912 			appendStringInfoChar(&buf, '\n');
2913 		}
2914 		if (edata->internalquery)
2915 		{
2916 			log_line_prefix(&buf, edata);
2917 			appendStringInfoString(&buf, _("QUERY:  "));
2918 			append_with_tabs(&buf, edata->internalquery);
2919 			appendStringInfoChar(&buf, '\n');
2920 		}
2921 		if (edata->context && !edata->hide_ctx)
2922 		{
2923 			log_line_prefix(&buf, edata);
2924 			appendStringInfoString(&buf, _("CONTEXT:  "));
2925 			append_with_tabs(&buf, edata->context);
2926 			appendStringInfoChar(&buf, '\n');
2927 		}
2928 		if (Log_error_verbosity >= PGERROR_VERBOSE)
2929 		{
2930 			/* assume no newlines in funcname or filename... */
2931 			if (edata->funcname && edata->filename)
2932 			{
2933 				log_line_prefix(&buf, edata);
2934 				appendStringInfo(&buf, _("LOCATION:  %s, %s:%d\n"),
2935 								 edata->funcname, edata->filename,
2936 								 edata->lineno);
2937 			}
2938 			else if (edata->filename)
2939 			{
2940 				log_line_prefix(&buf, edata);
2941 				appendStringInfo(&buf, _("LOCATION:  %s:%d\n"),
2942 								 edata->filename, edata->lineno);
2943 			}
2944 		}
2945 	}
2946 
2947 	/*
2948 	 * If the user wants the query that generated this error logged, do it.
2949 	 */
2950 	if (is_log_level_output(edata->elevel, log_min_error_statement) &&
2951 		debug_query_string != NULL &&
2952 		!edata->hide_stmt)
2953 	{
2954 		log_line_prefix(&buf, edata);
2955 		appendStringInfoString(&buf, _("STATEMENT:  "));
2956 		append_with_tabs(&buf, debug_query_string);
2957 		appendStringInfoChar(&buf, '\n');
2958 	}
2959 
2960 #ifdef HAVE_SYSLOG
2961 	/* Write to syslog, if enabled */
2962 	if (Log_destination & LOG_DESTINATION_SYSLOG)
2963 	{
2964 		int			syslog_level;
2965 
2966 		switch (edata->elevel)
2967 		{
2968 			case DEBUG5:
2969 			case DEBUG4:
2970 			case DEBUG3:
2971 			case DEBUG2:
2972 			case DEBUG1:
2973 				syslog_level = LOG_DEBUG;
2974 				break;
2975 			case LOG:
2976 			case LOG_SERVER_ONLY:
2977 			case INFO:
2978 				syslog_level = LOG_INFO;
2979 				break;
2980 			case NOTICE:
2981 			case WARNING:
2982 				syslog_level = LOG_NOTICE;
2983 				break;
2984 			case ERROR:
2985 				syslog_level = LOG_WARNING;
2986 				break;
2987 			case FATAL:
2988 				syslog_level = LOG_ERR;
2989 				break;
2990 			case PANIC:
2991 			default:
2992 				syslog_level = LOG_CRIT;
2993 				break;
2994 		}
2995 
2996 		write_syslog(syslog_level, buf.data);
2997 	}
2998 #endif							/* HAVE_SYSLOG */
2999 
3000 #ifdef WIN32
3001 	/* Write to eventlog, if enabled */
3002 	if (Log_destination & LOG_DESTINATION_EVENTLOG)
3003 	{
3004 		write_eventlog(edata->elevel, buf.data, buf.len);
3005 	}
3006 #endif							/* WIN32 */
3007 
3008 	/* Write to stderr, if enabled */
3009 	if ((Log_destination & LOG_DESTINATION_STDERR) || whereToSendOutput == DestDebug)
3010 	{
3011 		/*
3012 		 * Use the chunking protocol if we know the syslogger should be
3013 		 * catching stderr output, and we are not ourselves the syslogger.
3014 		 * Otherwise, just do a vanilla write to stderr.
3015 		 */
3016 		if (redirection_done && !am_syslogger)
3017 			write_pipe_chunks(buf.data, buf.len, LOG_DESTINATION_STDERR);
3018 #ifdef WIN32
3019 
3020 		/*
3021 		 * In a win32 service environment, there is no usable stderr. Capture
3022 		 * anything going there and write it to the eventlog instead.
3023 		 *
3024 		 * If stderr redirection is active, it was OK to write to stderr above
3025 		 * because that's really a pipe to the syslogger process.
3026 		 */
3027 		else if (pgwin32_is_service())
3028 			write_eventlog(edata->elevel, buf.data, buf.len);
3029 #endif
3030 		else
3031 			write_console(buf.data, buf.len);
3032 	}
3033 
3034 	/* If in the syslogger process, try to write messages direct to file */
3035 	if (am_syslogger)
3036 		write_syslogger_file(buf.data, buf.len, LOG_DESTINATION_STDERR);
3037 
3038 	/* Write to CSV log if enabled */
3039 	if (Log_destination & LOG_DESTINATION_CSVLOG)
3040 	{
3041 		if (redirection_done || am_syslogger)
3042 		{
3043 			/*
3044 			 * send CSV data if it's safe to do so (syslogger doesn't need the
3045 			 * pipe). First get back the space in the message buffer.
3046 			 */
3047 			pfree(buf.data);
3048 			write_csvlog(edata);
3049 		}
3050 		else
3051 		{
3052 			/*
3053 			 * syslogger not up (yet), so just dump the message to stderr,
3054 			 * unless we already did so above.
3055 			 */
3056 			if (!(Log_destination & LOG_DESTINATION_STDERR) &&
3057 				whereToSendOutput != DestDebug)
3058 				write_console(buf.data, buf.len);
3059 			pfree(buf.data);
3060 		}
3061 	}
3062 	else
3063 	{
3064 		pfree(buf.data);
3065 	}
3066 }
3067 
3068 /*
3069  * Send data to the syslogger using the chunked protocol
3070  *
3071  * Note: when there are multiple backends writing into the syslogger pipe,
3072  * it's critical that each write go into the pipe indivisibly, and not
3073  * get interleaved with data from other processes.  Fortunately, the POSIX
3074  * spec requires that writes to pipes be atomic so long as they are not
3075  * more than PIPE_BUF bytes long.  So we divide long messages into chunks
3076  * that are no more than that length, and send one chunk per write() call.
3077  * The collector process knows how to reassemble the chunks.
3078  *
3079  * Because of the atomic write requirement, there are only two possible
3080  * results from write() here: -1 for failure, or the requested number of
3081  * bytes.  There is not really anything we can do about a failure; retry would
3082  * probably be an infinite loop, and we can't even report the error usefully.
3083  * (There is noplace else we could send it!)  So we might as well just ignore
3084  * the result from write().  However, on some platforms you get a compiler
3085  * warning from ignoring write()'s result, so do a little dance with casting
3086  * rc to void to shut up the compiler.
3087  */
3088 static void
write_pipe_chunks(char * data,int len,int dest)3089 write_pipe_chunks(char *data, int len, int dest)
3090 {
3091 	PipeProtoChunk p;
3092 	int			fd = fileno(stderr);
3093 	int			rc;
3094 
3095 	Assert(len > 0);
3096 
3097 	p.proto.nuls[0] = p.proto.nuls[1] = '\0';
3098 	p.proto.pid = MyProcPid;
3099 
3100 	/* write all but the last chunk */
3101 	while (len > PIPE_MAX_PAYLOAD)
3102 	{
3103 		p.proto.is_last = (dest == LOG_DESTINATION_CSVLOG ? 'F' : 'f');
3104 		p.proto.len = PIPE_MAX_PAYLOAD;
3105 		memcpy(p.proto.data, data, PIPE_MAX_PAYLOAD);
3106 		rc = write(fd, &p, PIPE_HEADER_SIZE + PIPE_MAX_PAYLOAD);
3107 		(void) rc;
3108 		data += PIPE_MAX_PAYLOAD;
3109 		len -= PIPE_MAX_PAYLOAD;
3110 	}
3111 
3112 	/* write the last chunk */
3113 	p.proto.is_last = (dest == LOG_DESTINATION_CSVLOG ? 'T' : 't');
3114 	p.proto.len = len;
3115 	memcpy(p.proto.data, data, len);
3116 	rc = write(fd, &p, PIPE_HEADER_SIZE + len);
3117 	(void) rc;
3118 }
3119 
3120 
3121 /*
3122  * Append a text string to the error report being built for the client.
3123  *
3124  * This is ordinarily identical to pq_sendstring(), but if we are in
3125  * error recursion trouble we skip encoding conversion, because of the
3126  * possibility that the problem is a failure in the encoding conversion
3127  * subsystem itself.  Code elsewhere should ensure that the passed-in
3128  * strings will be plain 7-bit ASCII, and thus not in need of conversion,
3129  * in such cases.  (In particular, we disable localization of error messages
3130  * to help ensure that's true.)
3131  */
3132 static void
err_sendstring(StringInfo buf,const char * str)3133 err_sendstring(StringInfo buf, const char *str)
3134 {
3135 	if (in_error_recursion_trouble())
3136 		pq_send_ascii_string(buf, str);
3137 	else
3138 		pq_sendstring(buf, str);
3139 }
3140 
3141 /*
3142  * Write error report to client
3143  */
3144 static void
send_message_to_frontend(ErrorData * edata)3145 send_message_to_frontend(ErrorData *edata)
3146 {
3147 	StringInfoData msgbuf;
3148 
3149 	/* 'N' (Notice) is for nonfatal conditions, 'E' is for errors */
3150 	pq_beginmessage(&msgbuf, (edata->elevel < ERROR) ? 'N' : 'E');
3151 
3152 	if (PG_PROTOCOL_MAJOR(FrontendProtocol) >= 3)
3153 	{
3154 		/* New style with separate fields */
3155 		const char *sev;
3156 		char		tbuf[12];
3157 		int			ssval;
3158 		int			i;
3159 
3160 		sev = error_severity(edata->elevel);
3161 		pq_sendbyte(&msgbuf, PG_DIAG_SEVERITY);
3162 		err_sendstring(&msgbuf, _(sev));
3163 		pq_sendbyte(&msgbuf, PG_DIAG_SEVERITY_NONLOCALIZED);
3164 		err_sendstring(&msgbuf, sev);
3165 
3166 		/* unpack MAKE_SQLSTATE code */
3167 		ssval = edata->sqlerrcode;
3168 		for (i = 0; i < 5; i++)
3169 		{
3170 			tbuf[i] = PGUNSIXBIT(ssval);
3171 			ssval >>= 6;
3172 		}
3173 		tbuf[i] = '\0';
3174 
3175 		pq_sendbyte(&msgbuf, PG_DIAG_SQLSTATE);
3176 		err_sendstring(&msgbuf, tbuf);
3177 
3178 		/* M field is required per protocol, so always send something */
3179 		pq_sendbyte(&msgbuf, PG_DIAG_MESSAGE_PRIMARY);
3180 		if (edata->message)
3181 			err_sendstring(&msgbuf, edata->message);
3182 		else
3183 			err_sendstring(&msgbuf, _("missing error text"));
3184 
3185 		if (edata->detail)
3186 		{
3187 			pq_sendbyte(&msgbuf, PG_DIAG_MESSAGE_DETAIL);
3188 			err_sendstring(&msgbuf, edata->detail);
3189 		}
3190 
3191 		/* detail_log is intentionally not used here */
3192 
3193 		if (edata->hint)
3194 		{
3195 			pq_sendbyte(&msgbuf, PG_DIAG_MESSAGE_HINT);
3196 			err_sendstring(&msgbuf, edata->hint);
3197 		}
3198 
3199 		if (edata->context)
3200 		{
3201 			pq_sendbyte(&msgbuf, PG_DIAG_CONTEXT);
3202 			err_sendstring(&msgbuf, edata->context);
3203 		}
3204 
3205 		if (edata->schema_name)
3206 		{
3207 			pq_sendbyte(&msgbuf, PG_DIAG_SCHEMA_NAME);
3208 			err_sendstring(&msgbuf, edata->schema_name);
3209 		}
3210 
3211 		if (edata->table_name)
3212 		{
3213 			pq_sendbyte(&msgbuf, PG_DIAG_TABLE_NAME);
3214 			err_sendstring(&msgbuf, edata->table_name);
3215 		}
3216 
3217 		if (edata->column_name)
3218 		{
3219 			pq_sendbyte(&msgbuf, PG_DIAG_COLUMN_NAME);
3220 			err_sendstring(&msgbuf, edata->column_name);
3221 		}
3222 
3223 		if (edata->datatype_name)
3224 		{
3225 			pq_sendbyte(&msgbuf, PG_DIAG_DATATYPE_NAME);
3226 			err_sendstring(&msgbuf, edata->datatype_name);
3227 		}
3228 
3229 		if (edata->constraint_name)
3230 		{
3231 			pq_sendbyte(&msgbuf, PG_DIAG_CONSTRAINT_NAME);
3232 			err_sendstring(&msgbuf, edata->constraint_name);
3233 		}
3234 
3235 		if (edata->cursorpos > 0)
3236 		{
3237 			snprintf(tbuf, sizeof(tbuf), "%d", edata->cursorpos);
3238 			pq_sendbyte(&msgbuf, PG_DIAG_STATEMENT_POSITION);
3239 			err_sendstring(&msgbuf, tbuf);
3240 		}
3241 
3242 		if (edata->internalpos > 0)
3243 		{
3244 			snprintf(tbuf, sizeof(tbuf), "%d", edata->internalpos);
3245 			pq_sendbyte(&msgbuf, PG_DIAG_INTERNAL_POSITION);
3246 			err_sendstring(&msgbuf, tbuf);
3247 		}
3248 
3249 		if (edata->internalquery)
3250 		{
3251 			pq_sendbyte(&msgbuf, PG_DIAG_INTERNAL_QUERY);
3252 			err_sendstring(&msgbuf, edata->internalquery);
3253 		}
3254 
3255 		if (edata->filename)
3256 		{
3257 			pq_sendbyte(&msgbuf, PG_DIAG_SOURCE_FILE);
3258 			err_sendstring(&msgbuf, edata->filename);
3259 		}
3260 
3261 		if (edata->lineno > 0)
3262 		{
3263 			snprintf(tbuf, sizeof(tbuf), "%d", edata->lineno);
3264 			pq_sendbyte(&msgbuf, PG_DIAG_SOURCE_LINE);
3265 			err_sendstring(&msgbuf, tbuf);
3266 		}
3267 
3268 		if (edata->funcname)
3269 		{
3270 			pq_sendbyte(&msgbuf, PG_DIAG_SOURCE_FUNCTION);
3271 			err_sendstring(&msgbuf, edata->funcname);
3272 		}
3273 
3274 		pq_sendbyte(&msgbuf, '\0'); /* terminator */
3275 	}
3276 	else
3277 	{
3278 		/* Old style --- gin up a backwards-compatible message */
3279 		StringInfoData buf;
3280 
3281 		initStringInfo(&buf);
3282 
3283 		appendStringInfo(&buf, "%s:  ", _(error_severity(edata->elevel)));
3284 
3285 		if (edata->show_funcname && edata->funcname)
3286 			appendStringInfo(&buf, "%s: ", edata->funcname);
3287 
3288 		if (edata->message)
3289 			appendStringInfoString(&buf, edata->message);
3290 		else
3291 			appendStringInfoString(&buf, _("missing error text"));
3292 
3293 		if (edata->cursorpos > 0)
3294 			appendStringInfo(&buf, _(" at character %d"),
3295 							 edata->cursorpos);
3296 		else if (edata->internalpos > 0)
3297 			appendStringInfo(&buf, _(" at character %d"),
3298 							 edata->internalpos);
3299 
3300 		appendStringInfoChar(&buf, '\n');
3301 
3302 		err_sendstring(&msgbuf, buf.data);
3303 
3304 		pfree(buf.data);
3305 	}
3306 
3307 	pq_endmessage(&msgbuf);
3308 
3309 	/*
3310 	 * This flush is normally not necessary, since postgres.c will flush out
3311 	 * waiting data when control returns to the main loop. But it seems best
3312 	 * to leave it here, so that the client has some clue what happened if the
3313 	 * backend dies before getting back to the main loop ... error/notice
3314 	 * messages should not be a performance-critical path anyway, so an extra
3315 	 * flush won't hurt much ...
3316 	 */
3317 	pq_flush();
3318 }
3319 
3320 
3321 /*
3322  * Support routines for formatting error messages.
3323  */
3324 
3325 
3326 /*
3327  * expand_fmt_string --- process special format codes in a format string
3328  *
3329  * We must replace %m with the appropriate strerror string, since vsnprintf
3330  * won't know what to do with it.
3331  *
3332  * The result is a palloc'd string.
3333  */
3334 static char *
expand_fmt_string(const char * fmt,ErrorData * edata)3335 expand_fmt_string(const char *fmt, ErrorData *edata)
3336 {
3337 	StringInfoData buf;
3338 	const char *cp;
3339 
3340 	initStringInfo(&buf);
3341 
3342 	for (cp = fmt; *cp; cp++)
3343 	{
3344 		if (cp[0] == '%' && cp[1] != '\0')
3345 		{
3346 			cp++;
3347 			if (*cp == 'm')
3348 			{
3349 				/*
3350 				 * Replace %m by system error string.  If there are any %'s in
3351 				 * the string, we'd better double them so that vsnprintf won't
3352 				 * misinterpret.
3353 				 */
3354 				const char *cp2;
3355 
3356 				cp2 = useful_strerror(edata->saved_errno);
3357 				for (; *cp2; cp2++)
3358 				{
3359 					if (*cp2 == '%')
3360 						appendStringInfoCharMacro(&buf, '%');
3361 					appendStringInfoCharMacro(&buf, *cp2);
3362 				}
3363 			}
3364 			else
3365 			{
3366 				/* copy % and next char --- this avoids trouble with %%m */
3367 				appendStringInfoCharMacro(&buf, '%');
3368 				appendStringInfoCharMacro(&buf, *cp);
3369 			}
3370 		}
3371 		else
3372 			appendStringInfoCharMacro(&buf, *cp);
3373 	}
3374 
3375 	return buf.data;
3376 }
3377 
3378 
3379 /*
3380  * A slightly cleaned-up version of strerror()
3381  */
3382 static const char *
useful_strerror(int errnum)3383 useful_strerror(int errnum)
3384 {
3385 	/* this buffer is only used if strerror() and get_errno_symbol() fail */
3386 	static char errorstr_buf[48];
3387 	const char *str;
3388 
3389 #ifdef WIN32
3390 	/* Winsock error code range, per WinError.h */
3391 	if (errnum >= 10000 && errnum <= 11999)
3392 		return pgwin32_socket_strerror(errnum);
3393 #endif
3394 	str = strerror(errnum);
3395 
3396 	/*
3397 	 * Some strerror()s return an empty string for out-of-range errno.  This
3398 	 * is ANSI C spec compliant, but not exactly useful.  Also, we may get
3399 	 * back strings of question marks if libc cannot transcode the message to
3400 	 * the codeset specified by LC_CTYPE.  If we get nothing useful, first try
3401 	 * get_errno_symbol(), and if that fails, print the numeric errno.
3402 	 */
3403 	if (str == NULL || *str == '\0' || *str == '?')
3404 		str = get_errno_symbol(errnum);
3405 
3406 	if (str == NULL)
3407 	{
3408 		snprintf(errorstr_buf, sizeof(errorstr_buf),
3409 		/*------
3410 		  translator: This string will be truncated at 47
3411 		  characters expanded. */
3412 				 _("operating system error %d"), errnum);
3413 		str = errorstr_buf;
3414 	}
3415 
3416 	return str;
3417 }
3418 
3419 /*
3420  * Returns a symbol (e.g. "ENOENT") for an errno code.
3421  * Returns NULL if the code is unrecognized.
3422  */
3423 static const char *
get_errno_symbol(int errnum)3424 get_errno_symbol(int errnum)
3425 {
3426 	switch (errnum)
3427 	{
3428 		case E2BIG:
3429 			return "E2BIG";
3430 		case EACCES:
3431 			return "EACCES";
3432 #ifdef EADDRINUSE
3433 		case EADDRINUSE:
3434 			return "EADDRINUSE";
3435 #endif
3436 #ifdef EADDRNOTAVAIL
3437 		case EADDRNOTAVAIL:
3438 			return "EADDRNOTAVAIL";
3439 #endif
3440 		case EAFNOSUPPORT:
3441 			return "EAFNOSUPPORT";
3442 #ifdef EAGAIN
3443 		case EAGAIN:
3444 			return "EAGAIN";
3445 #endif
3446 #ifdef EALREADY
3447 		case EALREADY:
3448 			return "EALREADY";
3449 #endif
3450 		case EBADF:
3451 			return "EBADF";
3452 #ifdef EBADMSG
3453 		case EBADMSG:
3454 			return "EBADMSG";
3455 #endif
3456 		case EBUSY:
3457 			return "EBUSY";
3458 		case ECHILD:
3459 			return "ECHILD";
3460 #ifdef ECONNABORTED
3461 		case ECONNABORTED:
3462 			return "ECONNABORTED";
3463 #endif
3464 		case ECONNREFUSED:
3465 			return "ECONNREFUSED";
3466 #ifdef ECONNRESET
3467 		case ECONNRESET:
3468 			return "ECONNRESET";
3469 #endif
3470 		case EDEADLK:
3471 			return "EDEADLK";
3472 		case EDOM:
3473 			return "EDOM";
3474 		case EEXIST:
3475 			return "EEXIST";
3476 		case EFAULT:
3477 			return "EFAULT";
3478 		case EFBIG:
3479 			return "EFBIG";
3480 #ifdef EHOSTUNREACH
3481 		case EHOSTUNREACH:
3482 			return "EHOSTUNREACH";
3483 #endif
3484 		case EIDRM:
3485 			return "EIDRM";
3486 		case EINPROGRESS:
3487 			return "EINPROGRESS";
3488 		case EINTR:
3489 			return "EINTR";
3490 		case EINVAL:
3491 			return "EINVAL";
3492 		case EIO:
3493 			return "EIO";
3494 #ifdef EISCONN
3495 		case EISCONN:
3496 			return "EISCONN";
3497 #endif
3498 		case EISDIR:
3499 			return "EISDIR";
3500 #ifdef ELOOP
3501 		case ELOOP:
3502 			return "ELOOP";
3503 #endif
3504 		case EMFILE:
3505 			return "EMFILE";
3506 		case EMLINK:
3507 			return "EMLINK";
3508 		case EMSGSIZE:
3509 			return "EMSGSIZE";
3510 		case ENAMETOOLONG:
3511 			return "ENAMETOOLONG";
3512 		case ENFILE:
3513 			return "ENFILE";
3514 		case ENOBUFS:
3515 			return "ENOBUFS";
3516 		case ENODEV:
3517 			return "ENODEV";
3518 		case ENOENT:
3519 			return "ENOENT";
3520 		case ENOEXEC:
3521 			return "ENOEXEC";
3522 		case ENOMEM:
3523 			return "ENOMEM";
3524 		case ENOSPC:
3525 			return "ENOSPC";
3526 		case ENOSYS:
3527 			return "ENOSYS";
3528 #ifdef ENOTCONN
3529 		case ENOTCONN:
3530 			return "ENOTCONN";
3531 #endif
3532 		case ENOTDIR:
3533 			return "ENOTDIR";
3534 #if defined(ENOTEMPTY) && (ENOTEMPTY != EEXIST) /* same code on AIX */
3535 		case ENOTEMPTY:
3536 			return "ENOTEMPTY";
3537 #endif
3538 #ifdef ENOTSOCK
3539 		case ENOTSOCK:
3540 			return "ENOTSOCK";
3541 #endif
3542 #ifdef ENOTSUP
3543 		case ENOTSUP:
3544 			return "ENOTSUP";
3545 #endif
3546 		case ENOTTY:
3547 			return "ENOTTY";
3548 		case ENXIO:
3549 			return "ENXIO";
3550 #if defined(EOPNOTSUPP) && (!defined(ENOTSUP) || (EOPNOTSUPP != ENOTSUP))
3551 		case EOPNOTSUPP:
3552 			return "EOPNOTSUPP";
3553 #endif
3554 #ifdef EOVERFLOW
3555 		case EOVERFLOW:
3556 			return "EOVERFLOW";
3557 #endif
3558 		case EPERM:
3559 			return "EPERM";
3560 		case EPIPE:
3561 			return "EPIPE";
3562 		case EPROTONOSUPPORT:
3563 			return "EPROTONOSUPPORT";
3564 		case ERANGE:
3565 			return "ERANGE";
3566 #ifdef EROFS
3567 		case EROFS:
3568 			return "EROFS";
3569 #endif
3570 		case ESRCH:
3571 			return "ESRCH";
3572 #ifdef ETIMEDOUT
3573 		case ETIMEDOUT:
3574 			return "ETIMEDOUT";
3575 #endif
3576 #ifdef ETXTBSY
3577 		case ETXTBSY:
3578 			return "ETXTBSY";
3579 #endif
3580 #if defined(EWOULDBLOCK) && (!defined(EAGAIN) || (EWOULDBLOCK != EAGAIN))
3581 		case EWOULDBLOCK:
3582 			return "EWOULDBLOCK";
3583 #endif
3584 		case EXDEV:
3585 			return "EXDEV";
3586 	}
3587 
3588 	return NULL;
3589 }
3590 
3591 
3592 /*
3593  * error_severity --- get string representing elevel
3594  *
3595  * The string is not localized here, but we mark the strings for translation
3596  * so that callers can invoke _() on the result.
3597  */
3598 static const char *
error_severity(int elevel)3599 error_severity(int elevel)
3600 {
3601 	const char *prefix;
3602 
3603 	switch (elevel)
3604 	{
3605 		case DEBUG1:
3606 		case DEBUG2:
3607 		case DEBUG3:
3608 		case DEBUG4:
3609 		case DEBUG5:
3610 			prefix = gettext_noop("DEBUG");
3611 			break;
3612 		case LOG:
3613 		case LOG_SERVER_ONLY:
3614 			prefix = gettext_noop("LOG");
3615 			break;
3616 		case INFO:
3617 			prefix = gettext_noop("INFO");
3618 			break;
3619 		case NOTICE:
3620 			prefix = gettext_noop("NOTICE");
3621 			break;
3622 		case WARNING:
3623 			prefix = gettext_noop("WARNING");
3624 			break;
3625 		case ERROR:
3626 			prefix = gettext_noop("ERROR");
3627 			break;
3628 		case FATAL:
3629 			prefix = gettext_noop("FATAL");
3630 			break;
3631 		case PANIC:
3632 			prefix = gettext_noop("PANIC");
3633 			break;
3634 		default:
3635 			prefix = "???";
3636 			break;
3637 	}
3638 
3639 	return prefix;
3640 }
3641 
3642 
3643 /*
3644  *	append_with_tabs
3645  *
3646  *	Append the string to the StringInfo buffer, inserting a tab after any
3647  *	newline.
3648  */
3649 static void
append_with_tabs(StringInfo buf,const char * str)3650 append_with_tabs(StringInfo buf, const char *str)
3651 {
3652 	char		ch;
3653 
3654 	while ((ch = *str++) != '\0')
3655 	{
3656 		appendStringInfoCharMacro(buf, ch);
3657 		if (ch == '\n')
3658 			appendStringInfoCharMacro(buf, '\t');
3659 	}
3660 }
3661 
3662 
3663 /*
3664  * Write errors to stderr (or by equal means when stderr is
3665  * not available). Used before ereport/elog can be used
3666  * safely (memory context, GUC load etc)
3667  */
3668 void
write_stderr(const char * fmt,...)3669 write_stderr(const char *fmt,...)
3670 {
3671 	va_list		ap;
3672 
3673 #ifdef WIN32
3674 	char		errbuf[2048];	/* Arbitrary size? */
3675 #endif
3676 
3677 	fmt = _(fmt);
3678 
3679 	va_start(ap, fmt);
3680 #ifndef WIN32
3681 	/* On Unix, we just fprintf to stderr */
3682 	vfprintf(stderr, fmt, ap);
3683 	fflush(stderr);
3684 #else
3685 	vsnprintf(errbuf, sizeof(errbuf), fmt, ap);
3686 
3687 	/*
3688 	 * On Win32, we print to stderr if running on a console, or write to
3689 	 * eventlog if running as a service
3690 	 */
3691 	if (pgwin32_is_service())	/* Running as a service */
3692 	{
3693 		write_eventlog(ERROR, errbuf, strlen(errbuf));
3694 	}
3695 	else
3696 	{
3697 		/* Not running as service, write to stderr */
3698 		write_console(errbuf, strlen(errbuf));
3699 		fflush(stderr);
3700 	}
3701 #endif
3702 	va_end(ap);
3703 }
3704 
3705 
3706 /*
3707  * is_log_level_output -- is elevel logically >= log_min_level?
3708  *
3709  * We use this for tests that should consider LOG to sort out-of-order,
3710  * between ERROR and FATAL.  Generally this is the right thing for testing
3711  * whether a message should go to the postmaster log, whereas a simple >=
3712  * test is correct for testing whether the message should go to the client.
3713  */
3714 static bool
is_log_level_output(int elevel,int log_min_level)3715 is_log_level_output(int elevel, int log_min_level)
3716 {
3717 	if (elevel == LOG || elevel == LOG_SERVER_ONLY)
3718 	{
3719 		if (log_min_level == LOG || log_min_level <= ERROR)
3720 			return true;
3721 	}
3722 	else if (log_min_level == LOG)
3723 	{
3724 		/* elevel != LOG */
3725 		if (elevel >= FATAL)
3726 			return true;
3727 	}
3728 	/* Neither is LOG */
3729 	else if (elevel >= log_min_level)
3730 		return true;
3731 
3732 	return false;
3733 }
3734 
3735 /*
3736  * Adjust the level of a recovery-related message per trace_recovery_messages.
3737  *
3738  * The argument is the default log level of the message, eg, DEBUG2.  (This
3739  * should only be applied to DEBUGn log messages, otherwise it's a no-op.)
3740  * If the level is >= trace_recovery_messages, we return LOG, causing the
3741  * message to be logged unconditionally (for most settings of
3742  * log_min_messages).  Otherwise, we return the argument unchanged.
3743  * The message will then be shown based on the setting of log_min_messages.
3744  *
3745  * Intention is to keep this for at least the whole of the 9.0 production
3746  * release, so we can more easily diagnose production problems in the field.
3747  * It should go away eventually, though, because it's an ugly and
3748  * hard-to-explain kluge.
3749  */
3750 int
trace_recovery(int trace_level)3751 trace_recovery(int trace_level)
3752 {
3753 	if (trace_level < LOG &&
3754 		trace_level >= trace_recovery_messages)
3755 		return LOG;
3756 
3757 	return trace_level;
3758 }
3759