]> granicus.if.org Git - postgresql/blob - src/backend/utils/error/elog.c
Improve the recently-added support for properly pluralized error messages
[postgresql] / src / backend / utils / error / elog.c
1 /*-------------------------------------------------------------------------
2  *
3  * elog.c
4  *        error logging and reporting
5  *
6  * Some notes about recursion and errors during error processing:
7  *
8  * We need to be robust about recursive-error scenarios --- for example,
9  * if we run out of memory, it's important to be able to report that fact.
10  * There are a number of considerations that go into this.
11  *
12  * First, distinguish between re-entrant use and actual recursion.      It
13  * is possible for an error or warning message to be emitted while the
14  * parameters for an error message are being computed.  In this case
15  * errstart has been called for the outer message, and some field values
16  * may have already been saved, but we are not actually recursing.      We handle
17  * this by providing a (small) stack of ErrorData records.      The inner message
18  * can be computed and sent without disturbing the state of the outer message.
19  * (If the inner message is actually an error, this isn't very interesting
20  * because control won't come back to the outer message generator ... but
21  * if the inner message is only debug or log data, this is critical.)
22  *
23  * Second, actual recursion will occur if an error is reported by one of
24  * the elog.c routines or something they call.  By far the most probable
25  * scenario of this sort is "out of memory"; and it's also the nastiest
26  * to handle because we'd likely also run out of memory while trying to
27  * report this error!  Our escape hatch for this case is to reset the
28  * ErrorContext to empty before trying to process the inner error.      Since
29  * ErrorContext is guaranteed to have at least 8K of space in it (see mcxt.c),
30  * we should be able to process an "out of memory" message successfully.
31  * Since we lose the prior error state due to the reset, we won't be able
32  * to return to processing the original error, but we wouldn't have anyway.
33  * (NOTE: the escape hatch is not used for recursive situations where the
34  * inner message is of less than ERROR severity; in that case we just
35  * try to process it and return normally.  Usually this will work, but if
36  * it ends up in infinite recursion, we will PANIC due to error stack
37  * overflow.)
38  *
39  *
40  * Portions Copyright (c) 1996-2009, PostgreSQL Global Development Group
41  * Portions Copyright (c) 1994, Regents of the University of California
42  *
43  *
44  * IDENTIFICATION
45  *        $PostgreSQL: pgsql/src/backend/utils/error/elog.c,v 1.214 2009/06/04 18:33:07 tgl Exp $
46  *
47  *-------------------------------------------------------------------------
48  */
49 #include "postgres.h"
50
51 #include <fcntl.h>
52 #include <time.h>
53 #include <unistd.h>
54 #include <signal.h>
55 #include <ctype.h>
56 #ifdef HAVE_SYSLOG
57 #include <syslog.h>
58 #endif
59
60 #include "access/transam.h"
61 #include "access/xact.h"
62 #include "libpq/libpq.h"
63 #include "libpq/pqformat.h"
64 #include "mb/pg_wchar.h"
65 #include "miscadmin.h"
66 #include "postmaster/postmaster.h"
67 #include "postmaster/syslogger.h"
68 #include "storage/ipc.h"
69 #include "storage/proc.h"
70 #include "tcop/tcopprot.h"
71 #include "utils/memutils.h"
72 #include "utils/ps_status.h"
73
74
75 #undef _
76 #define _(x) err_gettext(x)
77
78 /* Global variables */
79 ErrorContextCallback *error_context_stack = NULL;
80
81 sigjmp_buf *PG_exception_stack = NULL;
82
83 extern bool redirection_done;
84
85 /* GUC parameters */
86 int                     Log_error_verbosity = PGERROR_VERBOSE;
87 char       *Log_line_prefix = NULL;             /* format for extra log line info */
88 int                     Log_destination = LOG_DESTINATION_STDERR;
89
90 #ifdef HAVE_SYSLOG
91
92 /*
93  * Max string length to send to syslog().  Note that this doesn't count the
94  * sequence-number prefix we add, and of course it doesn't count the prefix
95  * added by syslog itself.  On many implementations it seems that the hard
96  * limit is approximately 2K bytes including both those prefixes.
97  */
98 #ifndef PG_SYSLOG_LIMIT
99 #define PG_SYSLOG_LIMIT 1024
100 #endif
101
102 static bool openlog_done = false;
103 static char *syslog_ident = NULL;
104 static int      syslog_facility = LOG_LOCAL0;
105
106 static void write_syslog(int level, const char *line);
107 #endif
108
109 #ifdef WIN32
110 static void write_eventlog(int level, const char *line);
111 #endif
112
113 /* We provide a small stack of ErrorData records for re-entrant cases */
114 #define ERRORDATA_STACK_SIZE  5
115
116 static ErrorData errordata[ERRORDATA_STACK_SIZE];
117
118 static int      errordata_stack_depth = -1; /* index of topmost active frame */
119
120 static int      recursion_depth = 0;    /* to detect actual recursion */
121
122 /* buffers for formatted timestamps that might be used by both
123  * log_line_prefix and csv logs.
124  */
125
126 #define FORMATTED_TS_LEN 128
127 static char formatted_start_time[FORMATTED_TS_LEN];
128 static char formatted_log_time[FORMATTED_TS_LEN];
129
130
131 /* Macro for checking errordata_stack_depth is reasonable */
132 #define CHECK_STACK_DEPTH() \
133         do { \
134                 if (errordata_stack_depth < 0) \
135                 { \
136                         errordata_stack_depth = -1; \
137                         ereport(ERROR, (errmsg_internal("errstart was not called"))); \
138                 } \
139         } while (0)
140
141
142 static void log_line_prefix(StringInfo buf);
143 static void send_message_to_server_log(ErrorData *edata);
144 static void send_message_to_frontend(ErrorData *edata);
145 static char *expand_fmt_string(const char *fmt, ErrorData *edata);
146 static const char *useful_strerror(int errnum);
147 static const char *error_severity(int elevel);
148 static void append_with_tabs(StringInfo buf, const char *str);
149 static bool is_log_level_output(int elevel, int log_min_level);
150 static void write_pipe_chunks(char *data, int len, int dest);
151 static void write_csvlog(ErrorData *edata);
152 static void setup_formatted_log_time(void);
153 static void setup_formatted_start_time(void);
154
155
156 /*
157  * in_error_recursion_trouble --- are we at risk of infinite error recursion?
158  *
159  * This function exists to provide common control of various fallback steps
160  * that we take if we think we are facing infinite error recursion.  See the
161  * callers for details.
162  */
163 bool
164 in_error_recursion_trouble(void)
165 {
166         /* Pull the plug if recurse more than once */
167         return (recursion_depth > 2);
168 }
169
170 /*
171  * One of those fallback steps is to stop trying to localize the error
172  * message, since there's a significant probability that that's exactly
173  * what's causing the recursion.
174  */
175 static inline const char *
176 err_gettext(const char *str)
177 {
178 #ifdef ENABLE_NLS
179         if (in_error_recursion_trouble())
180                 return str;
181         else
182                 return gettext(str);
183 #else
184         return str;
185 #endif
186 }
187
188
189 /*
190  * errstart --- begin an error-reporting cycle
191  *
192  * Create a stack entry and store the given parameters in it.  Subsequently,
193  * errmsg() and perhaps other routines will be called to further populate
194  * the stack entry.  Finally, errfinish() will be called to actually process
195  * the error report.
196  *
197  * Returns TRUE in normal case.  Returns FALSE to short-circuit the error
198  * report (if it's a warning or lower and not to be reported anywhere).
199  */
200 bool
201 errstart(int elevel, const char *filename, int lineno,
202                  const char *funcname, const char *domain)
203 {
204         ErrorData  *edata;
205         bool            output_to_server;
206         bool            output_to_client = false;
207         int                     i;
208
209         /*
210          * Check some cases in which we want to promote an error into a more
211          * severe error.  None of this logic applies for non-error messages.
212          */
213         if (elevel >= ERROR)
214         {
215                 /*
216                  * If we are inside a critical section, all errors become PANIC
217                  * errors.      See miscadmin.h.
218                  */
219                 if (CritSectionCount > 0)
220                         elevel = PANIC;
221
222                 /*
223                  * Check reasons for treating ERROR as FATAL:
224                  *
225                  * 1. we have no handler to pass the error to (implies we are in the
226                  * postmaster or in backend startup).
227                  *
228                  * 2. ExitOnAnyError mode switch is set (initdb uses this).
229                  *
230                  * 3. the error occurred after proc_exit has begun to run.      (It's
231                  * proc_exit's responsibility to see that this doesn't turn into
232                  * infinite recursion!)
233                  */
234                 if (elevel == ERROR)
235                 {
236                         if (PG_exception_stack == NULL ||
237                                 ExitOnAnyError ||
238                                 proc_exit_inprogress)
239                                 elevel = FATAL;
240                 }
241
242                 /*
243                  * If the error level is ERROR or more, errfinish is not going to
244                  * return to caller; therefore, if there is any stacked error already
245                  * in progress it will be lost.  This is more or less okay, except we
246                  * do not want to have a FATAL or PANIC error downgraded because the
247                  * reporting process was interrupted by a lower-grade error.  So check
248                  * the stack and make sure we panic if panic is warranted.
249                  */
250                 for (i = 0; i <= errordata_stack_depth; i++)
251                         elevel = Max(elevel, errordata[i].elevel);
252         }
253
254         /*
255          * Now decide whether we need to process this report at all; if it's
256          * warning or less and not enabled for logging, just return FALSE without
257          * starting up any error logging machinery.
258          */
259
260         /* Determine whether message is enabled for server log output */
261         if (IsPostmasterEnvironment)
262                 output_to_server = is_log_level_output(elevel, log_min_messages);
263         else
264                 /* In bootstrap/standalone case, do not sort LOG out-of-order */
265                 output_to_server = (elevel >= log_min_messages);
266
267         /* Determine whether message is enabled for client output */
268         if (whereToSendOutput == DestRemote && elevel != COMMERROR)
269         {
270                 /*
271                  * client_min_messages is honored only after we complete the
272                  * authentication handshake.  This is required both for security
273                  * reasons and because many clients can't handle NOTICE messages
274                  * during authentication.
275                  */
276                 if (ClientAuthInProgress)
277                         output_to_client = (elevel >= ERROR);
278                 else
279                         output_to_client = (elevel >= client_min_messages ||
280                                                                 elevel == INFO);
281         }
282
283         /* Skip processing effort if non-error message will not be output */
284         if (elevel < ERROR && !output_to_server && !output_to_client)
285                 return false;
286
287         /*
288          * Okay, crank up a stack entry to store the info in.
289          */
290
291         if (recursion_depth++ > 0 && elevel >= ERROR)
292         {
293                 /*
294                  * Ooops, error during error processing.  Clear ErrorContext as
295                  * discussed at top of file.  We will not return to the original
296                  * error's reporter or handler, so we don't need it.
297                  */
298                 MemoryContextReset(ErrorContext);
299
300                 /*
301                  * Infinite error recursion might be due to something broken
302                  * in a context traceback routine.      Abandon them too.  We also abandon
303                  * attempting to print the error statement (which, if long, could
304                  * itself be the source of the recursive failure).
305                  */
306                 if (in_error_recursion_trouble())
307                 {
308                         error_context_stack = NULL;
309                         debug_query_string = NULL;
310                 }
311         }
312         if (++errordata_stack_depth >= ERRORDATA_STACK_SIZE)
313         {
314                 /*
315                  * Wups, stack not big enough.  We treat this as a PANIC condition
316                  * because it suggests an infinite loop of errors during error
317                  * recovery.
318                  */
319                 errordata_stack_depth = -1;             /* make room on stack */
320                 ereport(PANIC, (errmsg_internal("ERRORDATA_STACK_SIZE exceeded")));
321         }
322
323         /* Initialize data for this error frame */
324         edata = &errordata[errordata_stack_depth];
325         MemSet(edata, 0, sizeof(ErrorData));
326         edata->elevel = elevel;
327         edata->output_to_server = output_to_server;
328         edata->output_to_client = output_to_client;
329         edata->filename = filename;
330         edata->lineno = lineno;
331         edata->funcname = funcname;
332         /* the default text domain is the backend's */
333         edata->domain = domain ? domain : PG_TEXTDOMAIN("postgres");
334         /* Select default errcode based on elevel */
335         if (elevel >= ERROR)
336                 edata->sqlerrcode = ERRCODE_INTERNAL_ERROR;
337         else if (elevel == WARNING)
338                 edata->sqlerrcode = ERRCODE_WARNING;
339         else
340                 edata->sqlerrcode = ERRCODE_SUCCESSFUL_COMPLETION;
341         /* errno is saved here so that error parameter eval can't change it */
342         edata->saved_errno = errno;
343
344         recursion_depth--;
345         return true;
346 }
347
348 /*
349  * errfinish --- end an error-reporting cycle
350  *
351  * Produce the appropriate error report(s) and pop the error stack.
352  *
353  * If elevel is ERROR or worse, control does not return to the caller.
354  * See elog.h for the error level definitions.
355  */
356 void
357 errfinish(int dummy,...)
358 {
359         ErrorData  *edata = &errordata[errordata_stack_depth];
360         int                     elevel = edata->elevel;
361         MemoryContext oldcontext;
362         ErrorContextCallback *econtext;
363
364         recursion_depth++;
365         CHECK_STACK_DEPTH();
366
367         /*
368          * Do processing in ErrorContext, which we hope has enough reserved space
369          * to report an error.
370          */
371         oldcontext = MemoryContextSwitchTo(ErrorContext);
372
373         /*
374          * Call any context callback functions.  Errors occurring in callback
375          * functions will be treated as recursive errors --- this ensures we will
376          * avoid infinite recursion (see errstart).
377          */
378         for (econtext = error_context_stack;
379                  econtext != NULL;
380                  econtext = econtext->previous)
381                 (*econtext->callback) (econtext->arg);
382
383         /*
384          * If ERROR (not more nor less) we pass it off to the current handler.
385          * Printing it and popping the stack is the responsibility of the handler.
386          */
387         if (elevel == ERROR)
388         {
389                 /*
390                  * We do some minimal cleanup before longjmp'ing so that handlers can
391                  * execute in a reasonably sane state.
392                  */
393
394                 /* This is just in case the error came while waiting for input */
395                 ImmediateInterruptOK = false;
396
397                 /*
398                  * Reset InterruptHoldoffCount in case we ereport'd from inside an
399                  * interrupt holdoff section.  (We assume here that no handler will
400                  * itself be inside a holdoff section.  If necessary, such a handler
401                  * could save and restore InterruptHoldoffCount for itself, but this
402                  * should make life easier for most.)
403                  */
404                 InterruptHoldoffCount = 0;
405
406                 CritSectionCount = 0;   /* should be unnecessary, but... */
407
408                 /*
409                  * Note that we leave CurrentMemoryContext set to ErrorContext. The
410                  * handler should reset it to something else soon.
411                  */
412
413                 recursion_depth--;
414                 PG_RE_THROW();
415         }
416
417         /*
418          * If we are doing FATAL or PANIC, abort any old-style COPY OUT in
419          * progress, so that we can report the message before dying.  (Without
420          * this, pq_putmessage will refuse to send the message at all, which is
421          * what we want for NOTICE messages, but not for fatal exits.) This hack
422          * is necessary because of poor design of old-style copy protocol.      Note
423          * we must do this even if client is fool enough to have set
424          * client_min_messages above FATAL, so don't look at output_to_client.
425          */
426         if (elevel >= FATAL && whereToSendOutput == DestRemote)
427                 pq_endcopyout(true);
428
429         /* Emit the message to the right places */
430         EmitErrorReport();
431
432         /* Now free up subsidiary data attached to stack entry, and release it */
433         if (edata->message)
434                 pfree(edata->message);
435         if (edata->detail)
436                 pfree(edata->detail);
437         if (edata->detail_log)
438                 pfree(edata->detail_log);
439         if (edata->hint)
440                 pfree(edata->hint);
441         if (edata->context)
442                 pfree(edata->context);
443         if (edata->internalquery)
444                 pfree(edata->internalquery);
445
446         errordata_stack_depth--;
447
448         /* Exit error-handling context */
449         MemoryContextSwitchTo(oldcontext);
450         recursion_depth--;
451
452         /*
453          * Perform error recovery action as specified by elevel.
454          */
455         if (elevel == FATAL)
456         {
457                 /*
458                  * For a FATAL error, we let proc_exit clean up and exit.
459                  */
460                 ImmediateInterruptOK = false;
461
462                 /*
463                  * If we just reported a startup failure, the client will disconnect
464                  * on receiving it, so don't send any more to the client.
465                  */
466                 if (PG_exception_stack == NULL && whereToSendOutput == DestRemote)
467                         whereToSendOutput = DestNone;
468
469                 /*
470                  * fflush here is just to improve the odds that we get to see the
471                  * error message, in case things are so hosed that proc_exit crashes.
472                  * Any other code you might be tempted to add here should probably be
473                  * in an on_proc_exit or on_shmem_exit callback instead.
474                  */
475                 fflush(stdout);
476                 fflush(stderr);
477
478                 /*
479                  * Do normal process-exit cleanup, then return exit code 1 to indicate
480                  * FATAL termination.  The postmaster may or may not consider this
481                  * worthy of panic, depending on which subprocess returns it.
482                  */
483                 proc_exit(1);
484         }
485
486         if (elevel >= PANIC)
487         {
488                 /*
489                  * Serious crash time. Postmaster will observe SIGABRT process exit
490                  * status and kill the other backends too.
491                  *
492                  * XXX: what if we are *in* the postmaster?  abort() won't kill our
493                  * children...
494                  */
495                 ImmediateInterruptOK = false;
496                 fflush(stdout);
497                 fflush(stderr);
498                 abort();
499         }
500
501         /*
502          * We reach here if elevel <= WARNING. OK to return to caller.
503          *
504          * But check for cancel/die interrupt first --- this is so that the user
505          * can stop a query emitting tons of notice or warning messages, even if
506          * it's in a loop that otherwise fails to check for interrupts.
507          */
508         CHECK_FOR_INTERRUPTS();
509 }
510
511
512 /*
513  * errcode --- add SQLSTATE error code to the current error
514  *
515  * The code is expected to be represented as per MAKE_SQLSTATE().
516  */
517 int
518 errcode(int sqlerrcode)
519 {
520         ErrorData  *edata = &errordata[errordata_stack_depth];
521
522         /* we don't bother incrementing recursion_depth */
523         CHECK_STACK_DEPTH();
524
525         edata->sqlerrcode = sqlerrcode;
526
527         return 0;                                       /* return value does not matter */
528 }
529
530
531 /*
532  * errcode_for_file_access --- add SQLSTATE error code to the current error
533  *
534  * The SQLSTATE code is chosen based on the saved errno value.  We assume
535  * that the failing operation was some type of disk file access.
536  *
537  * NOTE: the primary error message string should generally include %m
538  * when this is used.
539  */
540 int
541 errcode_for_file_access(void)
542 {
543         ErrorData  *edata = &errordata[errordata_stack_depth];
544
545         /* we don't bother incrementing recursion_depth */
546         CHECK_STACK_DEPTH();
547
548         switch (edata->saved_errno)
549         {
550                         /* Permission-denied failures */
551                 case EPERM:                             /* Not super-user */
552                 case EACCES:                    /* Permission denied */
553 #ifdef EROFS
554                 case EROFS:                             /* Read only file system */
555 #endif
556                         edata->sqlerrcode = ERRCODE_INSUFFICIENT_PRIVILEGE;
557                         break;
558
559                         /* File not found */
560                 case ENOENT:                    /* No such file or directory */
561                         edata->sqlerrcode = ERRCODE_UNDEFINED_FILE;
562                         break;
563
564                         /* Duplicate file */
565                 case EEXIST:                    /* File exists */
566                         edata->sqlerrcode = ERRCODE_DUPLICATE_FILE;
567                         break;
568
569                         /* Wrong object type or state */
570                 case ENOTDIR:                   /* Not a directory */
571                 case EISDIR:                    /* Is a directory */
572 #if defined(ENOTEMPTY) && (ENOTEMPTY != EEXIST) /* same code on AIX */
573                 case ENOTEMPTY: /* Directory not empty */
574 #endif
575                         edata->sqlerrcode = ERRCODE_WRONG_OBJECT_TYPE;
576                         break;
577
578                         /* Insufficient resources */
579                 case ENOSPC:                    /* No space left on device */
580                         edata->sqlerrcode = ERRCODE_DISK_FULL;
581                         break;
582
583                 case ENFILE:                    /* File table overflow */
584                 case EMFILE:                    /* Too many open files */
585                         edata->sqlerrcode = ERRCODE_INSUFFICIENT_RESOURCES;
586                         break;
587
588                         /* Hardware failure */
589                 case EIO:                               /* I/O error */
590                         edata->sqlerrcode = ERRCODE_IO_ERROR;
591                         break;
592
593                         /* All else is classified as internal errors */
594                 default:
595                         edata->sqlerrcode = ERRCODE_INTERNAL_ERROR;
596                         break;
597         }
598
599         return 0;                                       /* return value does not matter */
600 }
601
602 /*
603  * errcode_for_socket_access --- add SQLSTATE error code to the current error
604  *
605  * The SQLSTATE code is chosen based on the saved errno value.  We assume
606  * that the failing operation was some type of socket access.
607  *
608  * NOTE: the primary error message string should generally include %m
609  * when this is used.
610  */
611 int
612 errcode_for_socket_access(void)
613 {
614         ErrorData  *edata = &errordata[errordata_stack_depth];
615
616         /* we don't bother incrementing recursion_depth */
617         CHECK_STACK_DEPTH();
618
619         switch (edata->saved_errno)
620         {
621                         /* Loss of connection */
622                 case EPIPE:
623 #ifdef ECONNRESET
624                 case ECONNRESET:
625 #endif
626                         edata->sqlerrcode = ERRCODE_CONNECTION_FAILURE;
627                         break;
628
629                         /* All else is classified as internal errors */
630                 default:
631                         edata->sqlerrcode = ERRCODE_INTERNAL_ERROR;
632                         break;
633         }
634
635         return 0;                                       /* return value does not matter */
636 }
637
638
639 /*
640  * This macro handles expansion of a format string and associated parameters;
641  * it's common code for errmsg(), errdetail(), etc.  Must be called inside
642  * a routine that is declared like "const char *fmt, ..." and has an edata
643  * pointer set up.      The message is assigned to edata->targetfield, or
644  * appended to it if appendval is true.  The message is subject to translation
645  * if translateit is true.
646  *
647  * Note: we pstrdup the buffer rather than just transferring its storage
648  * to the edata field because the buffer might be considerably larger than
649  * really necessary.
650  */
651 #define EVALUATE_MESSAGE(targetfield, appendval, translateit)  \
652         { \
653                 char               *fmtbuf; \
654                 StringInfoData  buf; \
655                 /* Internationalize the error format string */ \
656                 if (translateit && !in_error_recursion_trouble()) \
657                         fmt = dgettext(edata->domain, fmt); \
658                 /* Expand %m in format string */ \
659                 fmtbuf = expand_fmt_string(fmt, edata); \
660                 initStringInfo(&buf); \
661                 if ((appendval) && edata->targetfield) \
662                         appendStringInfo(&buf, "%s\n", edata->targetfield); \
663                 /* Generate actual output --- have to use appendStringInfoVA */ \
664                 for (;;) \
665                 { \
666                         va_list         args; \
667                         bool            success; \
668                         va_start(args, fmt); \
669                         success = appendStringInfoVA(&buf, fmtbuf, args); \
670                         va_end(args); \
671                         if (success) \
672                                 break; \
673                         enlargeStringInfo(&buf, buf.maxlen); \
674                 } \
675                 /* Done with expanded fmt */ \
676                 pfree(fmtbuf); \
677                 /* Save the completed message into the stack item */ \
678                 if (edata->targetfield) \
679                         pfree(edata->targetfield); \
680                 edata->targetfield = pstrdup(buf.data); \
681                 pfree(buf.data); \
682         }
683
684 /*
685  * Same as above, except for pluralized error messages.  The calling routine
686  * must be declared like "const char *fmt_singular, const char *fmt_plural,
687  * unsigned long n, ...".  Translation is assumed always wanted.
688  */
689 #define EVALUATE_MESSAGE_PLURAL(targetfield, appendval)  \
690         { \
691                 const char         *fmt; \
692                 char               *fmtbuf; \
693                 StringInfoData  buf; \
694                 /* Internationalize the error format string */ \
695                 if (!in_error_recursion_trouble()) \
696                         fmt = dngettext(edata->domain, fmt_singular, fmt_plural, n); \
697                 else \
698                         fmt = (n == 1 ? fmt_singular : fmt_plural); \
699                 /* Expand %m in format string */ \
700                 fmtbuf = expand_fmt_string(fmt, edata); \
701                 initStringInfo(&buf); \
702                 if ((appendval) && edata->targetfield) \
703                         appendStringInfo(&buf, "%s\n", edata->targetfield); \
704                 /* Generate actual output --- have to use appendStringInfoVA */ \
705                 for (;;) \
706                 { \
707                         va_list         args; \
708                         bool            success; \
709                         va_start(args, n); \
710                         success = appendStringInfoVA(&buf, fmtbuf, args); \
711                         va_end(args); \
712                         if (success) \
713                                 break; \
714                         enlargeStringInfo(&buf, buf.maxlen); \
715                 } \
716                 /* Done with expanded fmt */ \
717                 pfree(fmtbuf); \
718                 /* Save the completed message into the stack item */ \
719                 if (edata->targetfield) \
720                         pfree(edata->targetfield); \
721                 edata->targetfield = pstrdup(buf.data); \
722                 pfree(buf.data); \
723         }
724
725
726 /*
727  * errmsg --- add a primary error message text to the current error
728  *
729  * In addition to the usual %-escapes recognized by printf, "%m" in
730  * fmt is replaced by the error message for the caller's value of errno.
731  *
732  * Note: no newline is needed at the end of the fmt string, since
733  * ereport will provide one for the output methods that need it.
734  */
735 int
736 errmsg(const char *fmt,...)
737 {
738         ErrorData  *edata = &errordata[errordata_stack_depth];
739         MemoryContext oldcontext;
740
741         recursion_depth++;
742         CHECK_STACK_DEPTH();
743         oldcontext = MemoryContextSwitchTo(ErrorContext);
744
745         EVALUATE_MESSAGE(message, false, true);
746
747         MemoryContextSwitchTo(oldcontext);
748         recursion_depth--;
749         return 0;                                       /* return value does not matter */
750 }
751
752
753 /*
754  * errmsg_internal --- add a primary error message text to the current error
755  *
756  * This is exactly like errmsg() except that strings passed to errmsg_internal
757  * are not translated, and are customarily left out of the
758  * internationalization message dictionary.  This should be used for "can't
759  * happen" cases that are probably not worth spending translation effort on.
760  * We also use this for certain cases where we *must* not try to translate
761  * the message because the translation would fail and result in infinite
762  * error recursion.
763  */
764 int
765 errmsg_internal(const char *fmt,...)
766 {
767         ErrorData  *edata = &errordata[errordata_stack_depth];
768         MemoryContext oldcontext;
769
770         recursion_depth++;
771         CHECK_STACK_DEPTH();
772         oldcontext = MemoryContextSwitchTo(ErrorContext);
773
774         EVALUATE_MESSAGE(message, false, false);
775
776         MemoryContextSwitchTo(oldcontext);
777         recursion_depth--;
778         return 0;                                       /* return value does not matter */
779 }
780
781
782 /*
783  * errmsg_plural --- add a primary error message text to the current error,
784  * with support for pluralization of the message text
785  */
786 int
787 errmsg_plural(const char *fmt_singular, const char *fmt_plural,
788                           unsigned long n, ...)
789 {
790         ErrorData  *edata = &errordata[errordata_stack_depth];
791         MemoryContext oldcontext;
792
793         recursion_depth++;
794         CHECK_STACK_DEPTH();
795         oldcontext = MemoryContextSwitchTo(ErrorContext);
796
797         EVALUATE_MESSAGE_PLURAL(message, false);
798
799         MemoryContextSwitchTo(oldcontext);
800         recursion_depth--;
801         return 0;                                       /* return value does not matter */
802 }
803
804
805 /*
806  * errdetail --- add a detail error message text to the current error
807  */
808 int
809 errdetail(const char *fmt,...)
810 {
811         ErrorData  *edata = &errordata[errordata_stack_depth];
812         MemoryContext oldcontext;
813
814         recursion_depth++;
815         CHECK_STACK_DEPTH();
816         oldcontext = MemoryContextSwitchTo(ErrorContext);
817
818         EVALUATE_MESSAGE(detail, false, true);
819
820         MemoryContextSwitchTo(oldcontext);
821         recursion_depth--;
822         return 0;                                       /* return value does not matter */
823 }
824
825
826 /*
827  * errdetail_log --- add a detail_log error message text to the current error
828  */
829 int
830 errdetail_log(const char *fmt,...)
831 {
832         ErrorData  *edata = &errordata[errordata_stack_depth];
833         MemoryContext oldcontext;
834
835         recursion_depth++;
836         CHECK_STACK_DEPTH();
837         oldcontext = MemoryContextSwitchTo(ErrorContext);
838
839         EVALUATE_MESSAGE(detail_log, false, true);
840
841         MemoryContextSwitchTo(oldcontext);
842         recursion_depth--;
843         return 0;                                       /* return value does not matter */
844 }
845
846
847 /*
848  * errdetail_plural --- add a detail error message text to the current error,
849  * with support for pluralization of the message text
850  */
851 int
852 errdetail_plural(const char *fmt_singular, const char *fmt_plural,
853                                  unsigned long n, ...)
854 {
855         ErrorData  *edata = &errordata[errordata_stack_depth];
856         MemoryContext oldcontext;
857
858         recursion_depth++;
859         CHECK_STACK_DEPTH();
860         oldcontext = MemoryContextSwitchTo(ErrorContext);
861
862         EVALUATE_MESSAGE_PLURAL(detail, false);
863
864         MemoryContextSwitchTo(oldcontext);
865         recursion_depth--;
866         return 0;                                       /* return value does not matter */
867 }
868
869
870 /*
871  * errhint --- add a hint error message text to the current error
872  */
873 int
874 errhint(const char *fmt,...)
875 {
876         ErrorData  *edata = &errordata[errordata_stack_depth];
877         MemoryContext oldcontext;
878
879         recursion_depth++;
880         CHECK_STACK_DEPTH();
881         oldcontext = MemoryContextSwitchTo(ErrorContext);
882
883         EVALUATE_MESSAGE(hint, false, true);
884
885         MemoryContextSwitchTo(oldcontext);
886         recursion_depth--;
887         return 0;                                       /* return value does not matter */
888 }
889
890
891 /*
892  * errcontext --- add a context error message text to the current error
893  *
894  * Unlike other cases, multiple calls are allowed to build up a stack of
895  * context information.  We assume earlier calls represent more-closely-nested
896  * states.
897  */
898 int
899 errcontext(const char *fmt,...)
900 {
901         ErrorData  *edata = &errordata[errordata_stack_depth];
902         MemoryContext oldcontext;
903
904         recursion_depth++;
905         CHECK_STACK_DEPTH();
906         oldcontext = MemoryContextSwitchTo(ErrorContext);
907
908         EVALUATE_MESSAGE(context, true, true);
909
910         MemoryContextSwitchTo(oldcontext);
911         recursion_depth--;
912         return 0;                                       /* return value does not matter */
913 }
914
915
916 /*
917  * errhidestmt --- optionally suppress STATEMENT: field of log entry
918  *
919  * This should be called if the message text already includes the statement.
920  */
921 int
922 errhidestmt(bool hide_stmt)
923 {
924         ErrorData  *edata = &errordata[errordata_stack_depth];
925
926         /* we don't bother incrementing recursion_depth */
927         CHECK_STACK_DEPTH();
928
929         edata->hide_stmt = hide_stmt;
930
931         return 0;                                       /* return value does not matter */
932 }
933
934
935 /*
936  * errfunction --- add reporting function name to the current error
937  *
938  * This is used when backwards compatibility demands that the function
939  * name appear in messages sent to old-protocol clients.  Note that the
940  * passed string is expected to be a non-freeable constant string.
941  */
942 int
943 errfunction(const char *funcname)
944 {
945         ErrorData  *edata = &errordata[errordata_stack_depth];
946
947         /* we don't bother incrementing recursion_depth */
948         CHECK_STACK_DEPTH();
949
950         edata->funcname = funcname;
951         edata->show_funcname = true;
952
953         return 0;                                       /* return value does not matter */
954 }
955
956 /*
957  * errposition --- add cursor position to the current error
958  */
959 int
960 errposition(int cursorpos)
961 {
962         ErrorData  *edata = &errordata[errordata_stack_depth];
963
964         /* we don't bother incrementing recursion_depth */
965         CHECK_STACK_DEPTH();
966
967         edata->cursorpos = cursorpos;
968
969         return 0;                                       /* return value does not matter */
970 }
971
972 /*
973  * internalerrposition --- add internal cursor position to the current error
974  */
975 int
976 internalerrposition(int cursorpos)
977 {
978         ErrorData  *edata = &errordata[errordata_stack_depth];
979
980         /* we don't bother incrementing recursion_depth */
981         CHECK_STACK_DEPTH();
982
983         edata->internalpos = cursorpos;
984
985         return 0;                                       /* return value does not matter */
986 }
987
988 /*
989  * internalerrquery --- add internal query text to the current error
990  *
991  * Can also pass NULL to drop the internal query text entry.  This case
992  * is intended for use in error callback subroutines that are editorializing
993  * on the layout of the error report.
994  */
995 int
996 internalerrquery(const char *query)
997 {
998         ErrorData  *edata = &errordata[errordata_stack_depth];
999
1000         /* we don't bother incrementing recursion_depth */
1001         CHECK_STACK_DEPTH();
1002
1003         if (edata->internalquery)
1004         {
1005                 pfree(edata->internalquery);
1006                 edata->internalquery = NULL;
1007         }
1008
1009         if (query)
1010                 edata->internalquery = MemoryContextStrdup(ErrorContext, query);
1011
1012         return 0;                                       /* return value does not matter */
1013 }
1014
1015 /*
1016  * geterrcode --- return the currently set SQLSTATE error code
1017  *
1018  * This is only intended for use in error callback subroutines, since there
1019  * is no other place outside elog.c where the concept is meaningful.
1020  */
1021 int
1022 geterrcode(void)
1023 {
1024         ErrorData  *edata = &errordata[errordata_stack_depth];
1025
1026         /* we don't bother incrementing recursion_depth */
1027         CHECK_STACK_DEPTH();
1028
1029         return edata->sqlerrcode;
1030 }
1031
1032 /*
1033  * geterrposition --- return the currently set error position (0 if none)
1034  *
1035  * This is only intended for use in error callback subroutines, since there
1036  * is no other place outside elog.c where the concept is meaningful.
1037  */
1038 int
1039 geterrposition(void)
1040 {
1041         ErrorData  *edata = &errordata[errordata_stack_depth];
1042
1043         /* we don't bother incrementing recursion_depth */
1044         CHECK_STACK_DEPTH();
1045
1046         return edata->cursorpos;
1047 }
1048
1049 /*
1050  * getinternalerrposition --- same for internal error position
1051  *
1052  * This is only intended for use in error callback subroutines, since there
1053  * is no other place outside elog.c where the concept is meaningful.
1054  */
1055 int
1056 getinternalerrposition(void)
1057 {
1058         ErrorData  *edata = &errordata[errordata_stack_depth];
1059
1060         /* we don't bother incrementing recursion_depth */
1061         CHECK_STACK_DEPTH();
1062
1063         return edata->internalpos;
1064 }
1065
1066
1067 /*
1068  * elog_start --- startup for old-style API
1069  *
1070  * All that we do here is stash the hidden filename/lineno/funcname
1071  * arguments into a stack entry.
1072  *
1073  * We need this to be separate from elog_finish because there's no other
1074  * portable way to deal with inserting extra arguments into the elog call.
1075  * (If macros with variable numbers of arguments were portable, it'd be
1076  * easy, but they aren't.)
1077  */
1078 void
1079 elog_start(const char *filename, int lineno, const char *funcname)
1080 {
1081         ErrorData  *edata;
1082
1083         if (++errordata_stack_depth >= ERRORDATA_STACK_SIZE)
1084         {
1085                 /*
1086                  * Wups, stack not big enough.  We treat this as a PANIC condition
1087                  * because it suggests an infinite loop of errors during error
1088                  * recovery.  Note that the message is intentionally not localized,
1089                  * else failure to convert it to client encoding could cause further
1090                  * recursion.
1091                  */
1092                 errordata_stack_depth = -1;             /* make room on stack */
1093                 ereport(PANIC, (errmsg_internal("ERRORDATA_STACK_SIZE exceeded")));
1094         }
1095
1096         edata = &errordata[errordata_stack_depth];
1097         edata->filename = filename;
1098         edata->lineno = lineno;
1099         edata->funcname = funcname;
1100         /* errno is saved now so that error parameter eval can't change it */
1101         edata->saved_errno = errno;
1102 }
1103
1104 /*
1105  * elog_finish --- finish up for old-style API
1106  */
1107 void
1108 elog_finish(int elevel, const char *fmt,...)
1109 {
1110         ErrorData  *edata = &errordata[errordata_stack_depth];
1111         MemoryContext oldcontext;
1112
1113         CHECK_STACK_DEPTH();
1114
1115         /*
1116          * Do errstart() to see if we actually want to report the message.
1117          */
1118         errordata_stack_depth--;
1119         errno = edata->saved_errno;
1120         if (!errstart(elevel, edata->filename, edata->lineno, edata->funcname, NULL))
1121                 return;                                 /* nothing to do */
1122
1123         /*
1124          * Format error message just like errmsg_internal().
1125          */
1126         recursion_depth++;
1127         oldcontext = MemoryContextSwitchTo(ErrorContext);
1128
1129         EVALUATE_MESSAGE(message, false, false);
1130
1131         MemoryContextSwitchTo(oldcontext);
1132         recursion_depth--;
1133
1134         /*
1135          * And let errfinish() finish up.
1136          */
1137         errfinish(0);
1138 }
1139
1140 /*
1141  * Actual output of the top-of-stack error message
1142  *
1143  * In the ereport(ERROR) case this is called from PostgresMain (or not at all,
1144  * if the error is caught by somebody).  For all other severity levels this
1145  * is called by errfinish.
1146  */
1147 void
1148 EmitErrorReport(void)
1149 {
1150         ErrorData  *edata = &errordata[errordata_stack_depth];
1151         MemoryContext oldcontext;
1152
1153         recursion_depth++;
1154         CHECK_STACK_DEPTH();
1155         oldcontext = MemoryContextSwitchTo(ErrorContext);
1156
1157         /* Send to server log, if enabled */
1158         if (edata->output_to_server)
1159                 send_message_to_server_log(edata);
1160
1161         /* Send to client, if enabled */
1162         if (edata->output_to_client)
1163                 send_message_to_frontend(edata);
1164
1165         MemoryContextSwitchTo(oldcontext);
1166         recursion_depth--;
1167 }
1168
1169 /*
1170  * CopyErrorData --- obtain a copy of the topmost error stack entry
1171  *
1172  * This is only for use in error handler code.  The data is copied into the
1173  * current memory context, so callers should always switch away from
1174  * ErrorContext first; otherwise it will be lost when FlushErrorState is done.
1175  */
1176 ErrorData *
1177 CopyErrorData(void)
1178 {
1179         ErrorData  *edata = &errordata[errordata_stack_depth];
1180         ErrorData  *newedata;
1181
1182         /*
1183          * we don't increment recursion_depth because out-of-memory here does not
1184          * indicate a problem within the error subsystem.
1185          */
1186         CHECK_STACK_DEPTH();
1187
1188         Assert(CurrentMemoryContext != ErrorContext);
1189
1190         /* Copy the struct itself */
1191         newedata = (ErrorData *) palloc(sizeof(ErrorData));
1192         memcpy(newedata, edata, sizeof(ErrorData));
1193
1194         /* Make copies of separately-allocated fields */
1195         if (newedata->message)
1196                 newedata->message = pstrdup(newedata->message);
1197         if (newedata->detail)
1198                 newedata->detail = pstrdup(newedata->detail);
1199         if (newedata->detail_log)
1200                 newedata->detail_log = pstrdup(newedata->detail_log);
1201         if (newedata->hint)
1202                 newedata->hint = pstrdup(newedata->hint);
1203         if (newedata->context)
1204                 newedata->context = pstrdup(newedata->context);
1205         if (newedata->internalquery)
1206                 newedata->internalquery = pstrdup(newedata->internalquery);
1207
1208         return newedata;
1209 }
1210
1211 /*
1212  * FreeErrorData --- free the structure returned by CopyErrorData.
1213  *
1214  * Error handlers should use this in preference to assuming they know all
1215  * the separately-allocated fields.
1216  */
1217 void
1218 FreeErrorData(ErrorData *edata)
1219 {
1220         if (edata->message)
1221                 pfree(edata->message);
1222         if (edata->detail)
1223                 pfree(edata->detail);
1224         if (edata->detail_log)
1225                 pfree(edata->detail_log);
1226         if (edata->hint)
1227                 pfree(edata->hint);
1228         if (edata->context)
1229                 pfree(edata->context);
1230         if (edata->internalquery)
1231                 pfree(edata->internalquery);
1232         pfree(edata);
1233 }
1234
1235 /*
1236  * FlushErrorState --- flush the error state after error recovery
1237  *
1238  * This should be called by an error handler after it's done processing
1239  * the error; or as soon as it's done CopyErrorData, if it intends to
1240  * do stuff that is likely to provoke another error.  You are not "out" of
1241  * the error subsystem until you have done this.
1242  */
1243 void
1244 FlushErrorState(void)
1245 {
1246         /*
1247          * Reset stack to empty.  The only case where it would be more than one
1248          * deep is if we serviced an error that interrupted construction of
1249          * another message.  We assume control escaped out of that message
1250          * construction and won't ever go back.
1251          */
1252         errordata_stack_depth = -1;
1253         recursion_depth = 0;
1254         /* Delete all data in ErrorContext */
1255         MemoryContextResetAndDeleteChildren(ErrorContext);
1256 }
1257
1258 /*
1259  * ReThrowError --- re-throw a previously copied error
1260  *
1261  * A handler can do CopyErrorData/FlushErrorState to get out of the error
1262  * subsystem, then do some processing, and finally ReThrowError to re-throw
1263  * the original error.  This is slower than just PG_RE_THROW() but should
1264  * be used if the "some processing" is likely to incur another error.
1265  */
1266 void
1267 ReThrowError(ErrorData *edata)
1268 {
1269         ErrorData  *newedata;
1270
1271         Assert(edata->elevel == ERROR);
1272
1273         /* Push the data back into the error context */
1274         recursion_depth++;
1275         MemoryContextSwitchTo(ErrorContext);
1276
1277         if (++errordata_stack_depth >= ERRORDATA_STACK_SIZE)
1278         {
1279                 /*
1280                  * Wups, stack not big enough.  We treat this as a PANIC condition
1281                  * because it suggests an infinite loop of errors during error
1282                  * recovery.
1283                  */
1284                 errordata_stack_depth = -1;             /* make room on stack */
1285                 ereport(PANIC, (errmsg_internal("ERRORDATA_STACK_SIZE exceeded")));
1286         }
1287
1288         newedata = &errordata[errordata_stack_depth];
1289         memcpy(newedata, edata, sizeof(ErrorData));
1290
1291         /* Make copies of separately-allocated fields */
1292         if (newedata->message)
1293                 newedata->message = pstrdup(newedata->message);
1294         if (newedata->detail)
1295                 newedata->detail = pstrdup(newedata->detail);
1296         if (newedata->detail_log)
1297                 newedata->detail_log = pstrdup(newedata->detail_log);
1298         if (newedata->hint)
1299                 newedata->hint = pstrdup(newedata->hint);
1300         if (newedata->context)
1301                 newedata->context = pstrdup(newedata->context);
1302         if (newedata->internalquery)
1303                 newedata->internalquery = pstrdup(newedata->internalquery);
1304
1305         recursion_depth--;
1306         PG_RE_THROW();
1307 }
1308
1309 /*
1310  * pg_re_throw --- out-of-line implementation of PG_RE_THROW() macro
1311  */
1312 void
1313 pg_re_throw(void)
1314 {
1315         /* If possible, throw the error to the next outer setjmp handler */
1316         if (PG_exception_stack != NULL)
1317                 siglongjmp(*PG_exception_stack, 1);
1318         else
1319         {
1320                 /*
1321                  * If we get here, elog(ERROR) was thrown inside a PG_TRY block, which
1322                  * we have now exited only to discover that there is no outer setjmp
1323                  * handler to pass the error to.  Had the error been thrown outside
1324                  * the block to begin with, we'd have promoted the error to FATAL, so
1325                  * the correct behavior is to make it FATAL now; that is, emit it and
1326                  * then call proc_exit.
1327                  */
1328                 ErrorData  *edata = &errordata[errordata_stack_depth];
1329
1330                 Assert(errordata_stack_depth >= 0);
1331                 Assert(edata->elevel == ERROR);
1332                 edata->elevel = FATAL;
1333
1334                 /*
1335                  * At least in principle, the increase in severity could have changed
1336                  * where-to-output decisions, so recalculate.  This should stay in
1337                  * sync with errstart(), which see for comments.
1338                  */
1339                 if (IsPostmasterEnvironment)
1340                         edata->output_to_server = is_log_level_output(FATAL,
1341                                                                                                                   log_min_messages);
1342                 else
1343                         edata->output_to_server = (FATAL >= log_min_messages);
1344                 if (whereToSendOutput == DestRemote)
1345                 {
1346                         if (ClientAuthInProgress)
1347                                 edata->output_to_client = true;
1348                         else
1349                                 edata->output_to_client = (FATAL >= client_min_messages);
1350                 }
1351
1352                 /*
1353                  * We can use errfinish() for the rest, but we don't want it to call
1354                  * any error context routines a second time.  Since we know we are
1355                  * about to exit, it should be OK to just clear the context stack.
1356                  */
1357                 error_context_stack = NULL;
1358
1359                 errfinish(0);
1360         }
1361
1362         /* We mustn't return... */
1363         ExceptionalCondition("pg_re_throw tried to return", "FailedAssertion",
1364                                                  __FILE__, __LINE__);
1365
1366         /*
1367          * Since ExceptionalCondition isn't declared noreturn because of
1368          * TrapMacro(), we need this to keep gcc from complaining.
1369          */
1370         abort();
1371 }
1372
1373
1374 /*
1375  * Initialization of error output file
1376  */
1377 void
1378 DebugFileOpen(void)
1379 {
1380         int                     fd,
1381                                 istty;
1382
1383         if (OutputFileName[0])
1384         {
1385                 /*
1386                  * A debug-output file name was given.
1387                  *
1388                  * Make sure we can write the file, and find out if it's a tty.
1389                  */
1390                 if ((fd = open(OutputFileName, O_CREAT | O_APPEND | O_WRONLY,
1391                                            0666)) < 0)
1392                         ereport(FATAL,
1393                                         (errcode_for_file_access(),
1394                                   errmsg("could not open file \"%s\": %m", OutputFileName)));
1395                 istty = isatty(fd);
1396                 close(fd);
1397
1398                 /*
1399                  * Redirect our stderr to the debug output file.
1400                  */
1401                 if (!freopen(OutputFileName, "a", stderr))
1402                         ereport(FATAL,
1403                                         (errcode_for_file_access(),
1404                                          errmsg("could not reopen file \"%s\" as stderr: %m",
1405                                                         OutputFileName)));
1406
1407                 /*
1408                  * If the file is a tty and we're running under the postmaster, try to
1409                  * send stdout there as well (if it isn't a tty then stderr will block
1410                  * out stdout, so we may as well let stdout go wherever it was going
1411                  * before).
1412                  */
1413                 if (istty && IsUnderPostmaster)
1414                         if (!freopen(OutputFileName, "a", stdout))
1415                                 ereport(FATAL,
1416                                                 (errcode_for_file_access(),
1417                                                  errmsg("could not reopen file \"%s\" as stdout: %m",
1418                                                                 OutputFileName)));
1419         }
1420 }
1421
1422
1423 #ifdef HAVE_SYSLOG
1424
1425 /*
1426  * Set or update the parameters for syslog logging
1427  */
1428 void
1429 set_syslog_parameters(const char *ident, int facility)
1430 {
1431         /*
1432          * guc.c is likely to call us repeatedly with same parameters, so don't
1433          * thrash the syslog connection unnecessarily.  Also, we do not re-open
1434          * the connection until needed, since this routine will get called whether
1435          * or not Log_destination actually mentions syslog.
1436          *
1437          * Note that we make our own copy of the ident string rather than relying
1438          * on guc.c's.  This may be overly paranoid, but it ensures that we cannot
1439          * accidentally free a string that syslog is still using.
1440          */
1441         if (syslog_ident == NULL || strcmp(syslog_ident, ident) != 0 ||
1442                 syslog_facility != facility)
1443         {
1444                 if (openlog_done)
1445                 {
1446                         closelog();
1447                         openlog_done = false;
1448                 }
1449                 if (syslog_ident)
1450                         free(syslog_ident);
1451                 syslog_ident = strdup(ident);
1452                 /* if the strdup fails, we will cope in write_syslog() */
1453                 syslog_facility = facility;
1454         }
1455 }
1456
1457
1458 /*
1459  * Write a message line to syslog
1460  */
1461 static void
1462 write_syslog(int level, const char *line)
1463 {
1464         static unsigned long seq = 0;
1465
1466         int                     len;
1467         const char *nlpos;
1468
1469         /* Open syslog connection if not done yet */
1470         if (!openlog_done)
1471         {
1472                 openlog(syslog_ident ? syslog_ident : "postgres",
1473                                 LOG_PID | LOG_NDELAY | LOG_NOWAIT,
1474                                 syslog_facility);
1475                 openlog_done = true;
1476         }
1477
1478         /*
1479          * We add a sequence number to each log message to suppress "same"
1480          * messages.
1481          */
1482         seq++;
1483
1484         /*
1485          * Our problem here is that many syslog implementations don't handle long
1486          * messages in an acceptable manner. While this function doesn't help that
1487          * fact, it does work around by splitting up messages into smaller pieces.
1488          *
1489          * We divide into multiple syslog() calls if message is too long or if the
1490          * message contains embedded newline(s).
1491          */
1492         len = strlen(line);
1493         nlpos = strchr(line, '\n');
1494         if (len > PG_SYSLOG_LIMIT || nlpos != NULL)
1495         {
1496                 int                     chunk_nr = 0;
1497
1498                 while (len > 0)
1499                 {
1500                         char            buf[PG_SYSLOG_LIMIT + 1];
1501                         int                     buflen;
1502                         int                     i;
1503
1504                         /* if we start at a newline, move ahead one char */
1505                         if (line[0] == '\n')
1506                         {
1507                                 line++;
1508                                 len--;
1509                                 /* we need to recompute the next newline's position, too */
1510                                 nlpos = strchr(line, '\n');
1511                                 continue;
1512                         }
1513
1514                         /* copy one line, or as much as will fit, to buf */
1515                         if (nlpos != NULL)
1516                                 buflen = nlpos - line;
1517                         else
1518                                 buflen = len;
1519                         buflen = Min(buflen, PG_SYSLOG_LIMIT);
1520                         memcpy(buf, line, buflen);
1521                         buf[buflen] = '\0';
1522
1523                         /* trim to multibyte letter boundary */
1524                         buflen = pg_mbcliplen(buf, buflen, buflen);
1525                         if (buflen <= 0)
1526                                 return;
1527                         buf[buflen] = '\0';
1528
1529                         /* already word boundary? */
1530                         if (line[buflen] != '\0' &&
1531                                 !isspace((unsigned char) line[buflen]))
1532                         {
1533                                 /* try to divide at word boundary */
1534                                 i = buflen - 1;
1535                                 while (i > 0 && !isspace((unsigned char) buf[i]))
1536                                         i--;
1537
1538                                 if (i > 0)              /* else couldn't divide word boundary */
1539                                 {
1540                                         buflen = i;
1541                                         buf[i] = '\0';
1542                                 }
1543                         }
1544
1545                         chunk_nr++;
1546
1547                         syslog(level, "[%lu-%d] %s", seq, chunk_nr, buf);
1548                         line += buflen;
1549                         len -= buflen;
1550                 }
1551         }
1552         else
1553         {
1554                 /* message short enough */
1555                 syslog(level, "[%lu] %s", seq, line);
1556         }
1557 }
1558 #endif   /* HAVE_SYSLOG */
1559
1560 #ifdef WIN32
1561 /*
1562  * Write a message line to the windows event log
1563  */
1564 static void
1565 write_eventlog(int level, const char *line)
1566 {
1567         int                     eventlevel = EVENTLOG_ERROR_TYPE;
1568         static HANDLE evtHandle = INVALID_HANDLE_VALUE;
1569
1570         if (evtHandle == INVALID_HANDLE_VALUE)
1571         {
1572                 evtHandle = RegisterEventSource(NULL, "PostgreSQL");
1573                 if (evtHandle == NULL)
1574                 {
1575                         evtHandle = INVALID_HANDLE_VALUE;
1576                         return;
1577                 }
1578         }
1579
1580         switch (level)
1581         {
1582                 case DEBUG5:
1583                 case DEBUG4:
1584                 case DEBUG3:
1585                 case DEBUG2:
1586                 case DEBUG1:
1587                 case LOG:
1588                 case COMMERROR:
1589                 case INFO:
1590                 case NOTICE:
1591                         eventlevel = EVENTLOG_INFORMATION_TYPE;
1592                         break;
1593                 case WARNING:
1594                         eventlevel = EVENTLOG_WARNING_TYPE;
1595                         break;
1596                 case ERROR:
1597                 case FATAL:
1598                 case PANIC:
1599                 default:
1600                         eventlevel = EVENTLOG_ERROR_TYPE;
1601                         break;
1602         }
1603
1604
1605         ReportEvent(evtHandle,
1606                                 eventlevel,
1607                                 0,
1608                                 0,                              /* All events are Id 0 */
1609                                 NULL,
1610                                 1,
1611                                 0,
1612                                 &line,
1613                                 NULL);
1614 }
1615 #endif   /* WIN32 */
1616
1617 /*
1618  * setup formatted_log_time, for consistent times between CSV and regular logs
1619  */
1620 static void
1621 setup_formatted_log_time(void)
1622 {
1623         struct timeval tv;
1624         pg_time_t       stamp_time;
1625         pg_tz      *tz;
1626         char            msbuf[8];
1627
1628         gettimeofday(&tv, NULL);
1629         stamp_time = (pg_time_t) tv.tv_sec;
1630
1631         /*
1632          * Normally we print log timestamps in log_timezone, but during startup we
1633          * could get here before that's set. If so, fall back to gmt_timezone
1634          * (which guc.c ensures is set up before Log_line_prefix can become
1635          * nonempty).
1636          */
1637         tz = log_timezone ? log_timezone : gmt_timezone;
1638
1639         pg_strftime(formatted_log_time, FORMATTED_TS_LEN,
1640                                 /* leave room for milliseconds... */
1641                                 "%Y-%m-%d %H:%M:%S     %Z",
1642                                 pg_localtime(&stamp_time, tz));
1643
1644         /* 'paste' milliseconds into place... */
1645         sprintf(msbuf, ".%03d", (int) (tv.tv_usec / 1000));
1646         strncpy(formatted_log_time + 19, msbuf, 4);
1647 }
1648
1649 /*
1650  * setup formatted_start_time
1651  */
1652 static void
1653 setup_formatted_start_time(void)
1654 {
1655         pg_time_t       stamp_time = (pg_time_t) MyStartTime;
1656         pg_tz      *tz;
1657
1658         /*
1659          * Normally we print log timestamps in log_timezone, but during startup we
1660          * could get here before that's set. If so, fall back to gmt_timezone
1661          * (which guc.c ensures is set up before Log_line_prefix can become
1662          * nonempty).
1663          */
1664         tz = log_timezone ? log_timezone : gmt_timezone;
1665
1666         pg_strftime(formatted_start_time, FORMATTED_TS_LEN,
1667                                 "%Y-%m-%d %H:%M:%S %Z",
1668                                 pg_localtime(&stamp_time, tz));
1669 }
1670
1671 /*
1672  * Format tag info for log lines; append to the provided buffer.
1673  */
1674 static void
1675 log_line_prefix(StringInfo buf)
1676 {
1677         /* static counter for line numbers */
1678         static long log_line_number = 0;
1679
1680         /* has counter been reset in current process? */
1681         static int      log_my_pid = 0;
1682
1683         int                     format_len;
1684         int                     i;
1685
1686         /*
1687          * This is one of the few places where we'd rather not inherit a static
1688          * variable's value from the postmaster.  But since we will, reset it when
1689          * MyProcPid changes. MyStartTime also changes when MyProcPid does, so
1690          * reset the formatted start timestamp too.
1691          */
1692         if (log_my_pid != MyProcPid)
1693         {
1694                 log_line_number = 0;
1695                 log_my_pid = MyProcPid;
1696                 formatted_start_time[0] = '\0';
1697         }
1698         log_line_number++;
1699
1700         if (Log_line_prefix == NULL)
1701                 return;                                 /* in case guc hasn't run yet */
1702
1703         format_len = strlen(Log_line_prefix);
1704
1705         for (i = 0; i < format_len; i++)
1706         {
1707                 if (Log_line_prefix[i] != '%')
1708                 {
1709                         /* literal char, just copy */
1710                         appendStringInfoChar(buf, Log_line_prefix[i]);
1711                         continue;
1712                 }
1713                 /* go to char after '%' */
1714                 i++;
1715                 if (i >= format_len)
1716                         break;                          /* format error - ignore it */
1717
1718                 /* process the option */
1719                 switch (Log_line_prefix[i])
1720                 {
1721                         case 'u':
1722                                 if (MyProcPort)
1723                                 {
1724                                         const char *username = MyProcPort->user_name;
1725
1726                                         if (username == NULL || *username == '\0')
1727                                                 username = _("[unknown]");
1728                                         appendStringInfo(buf, "%s", username);
1729                                 }
1730                                 break;
1731                         case 'd':
1732                                 if (MyProcPort)
1733                                 {
1734                                         const char *dbname = MyProcPort->database_name;
1735
1736                                         if (dbname == NULL || *dbname == '\0')
1737                                                 dbname = _("[unknown]");
1738                                         appendStringInfo(buf, "%s", dbname);
1739                                 }
1740                                 break;
1741                         case 'c':
1742                                 appendStringInfo(buf, "%lx.%x", (long) (MyStartTime), MyProcPid);
1743                                 break;
1744                         case 'p':
1745                                 appendStringInfo(buf, "%d", MyProcPid);
1746                                 break;
1747                         case 'l':
1748                                 appendStringInfo(buf, "%ld", log_line_number);
1749                                 break;
1750                         case 'm':
1751                                 setup_formatted_log_time();
1752                                 appendStringInfoString(buf, formatted_log_time);
1753                                 break;
1754                         case 't':
1755                                 {
1756                                         pg_time_t       stamp_time = (pg_time_t) time(NULL);
1757                                         pg_tz      *tz;
1758                                         char            strfbuf[128];
1759
1760                                         tz = log_timezone ? log_timezone : gmt_timezone;
1761
1762                                         pg_strftime(strfbuf, sizeof(strfbuf),
1763                                                                 "%Y-%m-%d %H:%M:%S %Z",
1764                                                                 pg_localtime(&stamp_time, tz));
1765                                         appendStringInfoString(buf, strfbuf);
1766                                 }
1767                                 break;
1768                         case 's':
1769                                 if (formatted_start_time[0] == '\0')
1770                                         setup_formatted_start_time();
1771                                 appendStringInfoString(buf, formatted_start_time);
1772                                 break;
1773                         case 'i':
1774                                 if (MyProcPort)
1775                                 {
1776                                         const char *psdisp;
1777                                         int                     displen;
1778
1779                                         psdisp = get_ps_display(&displen);
1780                                         appendStringInfo(buf, "%.*s", displen, psdisp);
1781                                 }
1782                                 break;
1783                         case 'r':
1784                                 if (MyProcPort && MyProcPort->remote_host)
1785                                 {
1786                                         appendStringInfo(buf, "%s", MyProcPort->remote_host);
1787                                         if (MyProcPort->remote_port &&
1788                                                 MyProcPort->remote_port[0] != '\0')
1789                                                 appendStringInfo(buf, "(%s)",
1790                                                                                  MyProcPort->remote_port);
1791                                 }
1792                                 break;
1793                         case 'h':
1794                                 if (MyProcPort && MyProcPort->remote_host)
1795                                         appendStringInfo(buf, "%s", MyProcPort->remote_host);
1796                                 break;
1797                         case 'q':
1798                                 /* in postmaster and friends, stop if %q is seen */
1799                                 /* in a backend, just ignore */
1800                                 if (MyProcPort == NULL)
1801                                         i = format_len;
1802                                 break;
1803                         case 'v':
1804                                 /* keep VXID format in sync with lockfuncs.c */
1805                                 if (MyProc != NULL && MyProc->backendId != InvalidBackendId)
1806                                         appendStringInfo(buf, "%d/%u",
1807                                                                          MyProc->backendId, MyProc->lxid);
1808                                 break;
1809                         case 'x':
1810                                 appendStringInfo(buf, "%u", GetTopTransactionIdIfAny());
1811                                 break;
1812                         case '%':
1813                                 appendStringInfoChar(buf, '%');
1814                                 break;
1815                         default:
1816                                 /* format error - ignore it */
1817                                 break;
1818                 }
1819         }
1820 }
1821
1822 /*
1823  * append a CSV'd version of a string to a StringInfo
1824  * We use the PostgreSQL defaults for CSV, i.e. quote = escape = '"'
1825  * If it's NULL, append nothing.
1826  */
1827 static inline void
1828 appendCSVLiteral(StringInfo buf, const char *data)
1829 {
1830         const char *p = data;
1831         char            c;
1832
1833         /* avoid confusing an empty string with NULL */
1834         if (p == NULL)
1835                 return;
1836
1837         appendStringInfoCharMacro(buf, '"');
1838         while ((c = *p++) != '\0')
1839         {
1840                 if (c == '"')
1841                         appendStringInfoCharMacro(buf, '"');
1842                 appendStringInfoCharMacro(buf, c);
1843         }
1844         appendStringInfoCharMacro(buf, '"');
1845 }
1846
1847 /*
1848  * Constructs the error message, depending on the Errordata it gets, in a CSV
1849  * format which is described in doc/src/sgml/config.sgml.
1850  */
1851 static void
1852 write_csvlog(ErrorData *edata)
1853 {
1854         StringInfoData buf;
1855         bool    print_stmt = false;
1856
1857         /* static counter for line numbers */
1858         static long log_line_number = 0;
1859
1860         /* has counter been reset in current process? */
1861         static int      log_my_pid = 0;
1862
1863         /*
1864          * This is one of the few places where we'd rather not inherit a static
1865          * variable's value from the postmaster.  But since we will, reset it when
1866          * MyProcPid changes.
1867          */
1868         if (log_my_pid != MyProcPid)
1869         {
1870                 log_line_number = 0;
1871                 log_my_pid = MyProcPid;
1872                 formatted_start_time[0] = '\0';
1873         }
1874         log_line_number++;
1875
1876         initStringInfo(&buf);
1877
1878         /*
1879          * timestamp with milliseconds
1880          *
1881          * Check if the timestamp is already calculated for the syslog message,
1882          * and use it if so.  Otherwise, get the current timestamp.  This is done
1883          * to put same timestamp in both syslog and csvlog messages.
1884          */
1885         if (formatted_log_time[0] == '\0')
1886                 setup_formatted_log_time();
1887
1888         appendStringInfoString(&buf, formatted_log_time);
1889         appendStringInfoChar(&buf, ',');
1890
1891         /* username */
1892         if (MyProcPort)
1893                 appendCSVLiteral(&buf, MyProcPort->user_name);
1894         appendStringInfoChar(&buf, ',');
1895
1896         /* database name */
1897         if (MyProcPort)
1898                 appendCSVLiteral(&buf, MyProcPort->database_name);
1899         appendStringInfoChar(&buf, ',');
1900
1901         /* Process id  */
1902         if (MyProcPid != 0)
1903                 appendStringInfo(&buf, "%d", MyProcPid);
1904         appendStringInfoChar(&buf, ',');
1905
1906         /* Remote host and port */
1907         if (MyProcPort && MyProcPort->remote_host)
1908         {
1909                 appendStringInfoChar(&buf, '"');
1910                 appendStringInfo(&buf, "%s", MyProcPort->remote_host);
1911                 if (MyProcPort->remote_port && MyProcPort->remote_port[0] != '\0')
1912                         appendStringInfo(&buf, ":%s", MyProcPort->remote_port);
1913                 appendStringInfoChar(&buf, '"');
1914         }
1915         appendStringInfoChar(&buf, ',');
1916
1917         /* session id */
1918         appendStringInfo(&buf, "%lx.%x", (long) MyStartTime, MyProcPid);
1919         appendStringInfoChar(&buf, ',');
1920
1921         /* Line number */
1922         appendStringInfo(&buf, "%ld", log_line_number);
1923         appendStringInfoChar(&buf, ',');
1924
1925         /* PS display */
1926         if (MyProcPort)
1927         {
1928                 StringInfoData msgbuf;
1929                 const char *psdisp;
1930                 int                     displen;
1931
1932                 initStringInfo(&msgbuf);
1933
1934                 psdisp = get_ps_display(&displen);
1935                 appendStringInfo(&msgbuf, "%.*s", displen, psdisp);
1936                 appendCSVLiteral(&buf, msgbuf.data);
1937         
1938                 pfree(msgbuf.data);
1939         }
1940         appendStringInfoChar(&buf, ',');
1941
1942         /* session start timestamp */
1943         if (formatted_start_time[0] == '\0')
1944                 setup_formatted_start_time();
1945         appendStringInfoString(&buf, formatted_start_time);
1946         appendStringInfoChar(&buf, ',');
1947
1948         /* Virtual transaction id */
1949         /* keep VXID format in sync with lockfuncs.c */
1950         if (MyProc != NULL && MyProc->backendId != InvalidBackendId)
1951                 appendStringInfo(&buf, "%d/%u", MyProc->backendId, MyProc->lxid);
1952         appendStringInfoChar(&buf, ',');
1953
1954         /* Transaction id */
1955         appendStringInfo(&buf, "%u", GetTopTransactionIdIfAny());
1956         appendStringInfoChar(&buf, ',');
1957
1958         /* Error severity */
1959         appendStringInfo(&buf, "%s", error_severity(edata->elevel));
1960         appendStringInfoChar(&buf, ',');
1961
1962         /* SQL state code */
1963         appendStringInfo(&buf, "%s", unpack_sql_state(edata->sqlerrcode));
1964         appendStringInfoChar(&buf, ',');
1965
1966         /* errmessage */
1967         appendCSVLiteral(&buf, edata->message);
1968         appendStringInfoCharMacro(&buf, ',');
1969
1970         /* errdetail or errdetail_log */
1971         if (edata->detail_log)
1972                 appendCSVLiteral(&buf, edata->detail_log);
1973         else
1974                 appendCSVLiteral(&buf, edata->detail);
1975         appendStringInfoCharMacro(&buf, ',');
1976
1977         /* errhint */
1978         appendCSVLiteral(&buf, edata->hint);
1979         appendStringInfoCharMacro(&buf, ',');
1980
1981         /* internal query */
1982         appendCSVLiteral(&buf, edata->internalquery);
1983         appendStringInfoCharMacro(&buf, ',');
1984
1985         /* if printed internal query, print internal pos too */
1986         if (edata->internalpos > 0 && edata->internalquery != NULL)
1987                 appendStringInfo(&buf, "%d", edata->internalpos);
1988         appendStringInfoCharMacro(&buf, ',');
1989
1990         /* errcontext */
1991         appendCSVLiteral(&buf, edata->context);
1992         appendStringInfoCharMacro(&buf, ',');
1993
1994         /* user query --- only reported if not disabled by the caller */
1995         if (is_log_level_output(edata->elevel, log_min_error_statement) &&
1996                 debug_query_string != NULL &&
1997                 !edata->hide_stmt)
1998                 print_stmt = true;
1999         if (print_stmt)
2000                 appendCSVLiteral(&buf, debug_query_string);
2001         appendStringInfoCharMacro(&buf, ',');
2002         if (print_stmt && edata->cursorpos > 0)
2003                 appendStringInfo(&buf, "%d", edata->cursorpos);
2004         appendStringInfoCharMacro(&buf, ',');
2005
2006         /* file error location */
2007         if (Log_error_verbosity >= PGERROR_VERBOSE)
2008         {
2009                 StringInfoData  msgbuf;
2010
2011                 initStringInfo(&msgbuf);
2012
2013                 if (edata->funcname && edata->filename)
2014                         appendStringInfo(&msgbuf, "%s, %s:%d",
2015                                                          edata->funcname, edata->filename,
2016                                                          edata->lineno);
2017                 else if (edata->filename)
2018                         appendStringInfo(&msgbuf, "%s:%d",
2019                                                          edata->filename, edata->lineno);
2020                 appendCSVLiteral(&buf, msgbuf.data);
2021                 pfree(msgbuf.data);
2022         }
2023
2024         appendStringInfoChar(&buf, '\n');
2025
2026         /* If in the syslogger process, try to write messages direct to file */
2027         if (am_syslogger)
2028                 write_syslogger_file(buf.data, buf.len, LOG_DESTINATION_CSVLOG);
2029         else
2030                 write_pipe_chunks(buf.data, buf.len, LOG_DESTINATION_CSVLOG);
2031
2032         pfree(buf.data);
2033 }
2034
2035 /*
2036  * Unpack MAKE_SQLSTATE code. Note that this returns a pointer to a
2037  * static buffer.
2038  */
2039 char *
2040 unpack_sql_state(int sql_state)
2041 {
2042         static char buf[12];
2043         int                     i;
2044
2045         for (i = 0; i < 5; i++)
2046         {
2047                 buf[i] = PGUNSIXBIT(sql_state);
2048                 sql_state >>= 6;
2049         }
2050
2051         buf[i] = '\0';
2052         return buf;
2053 }
2054
2055
2056 /*
2057  * Write error report to server's log
2058  */
2059 static void
2060 send_message_to_server_log(ErrorData *edata)
2061 {
2062         StringInfoData buf;
2063
2064         initStringInfo(&buf);
2065
2066         formatted_log_time[0] = '\0';
2067
2068         log_line_prefix(&buf);
2069         appendStringInfo(&buf, "%s:  ", error_severity(edata->elevel));
2070
2071         if (Log_error_verbosity >= PGERROR_VERBOSE)
2072                 appendStringInfo(&buf, "%s: ", unpack_sql_state(edata->sqlerrcode));
2073
2074         if (edata->message)
2075                 append_with_tabs(&buf, edata->message);
2076         else
2077                 append_with_tabs(&buf, _("missing error text"));
2078
2079         if (edata->cursorpos > 0)
2080                 appendStringInfo(&buf, _(" at character %d"),
2081                                                  edata->cursorpos);
2082         else if (edata->internalpos > 0)
2083                 appendStringInfo(&buf, _(" at character %d"),
2084                                                  edata->internalpos);
2085
2086         appendStringInfoChar(&buf, '\n');
2087
2088         if (Log_error_verbosity >= PGERROR_DEFAULT)
2089         {
2090                 if (edata->detail_log)
2091                 {
2092                         log_line_prefix(&buf);
2093                         appendStringInfoString(&buf, _("DETAIL:  "));
2094                         append_with_tabs(&buf, edata->detail_log);
2095                         appendStringInfoChar(&buf, '\n');
2096                 }
2097                 else if (edata->detail)
2098                 {
2099                         log_line_prefix(&buf);
2100                         appendStringInfoString(&buf, _("DETAIL:  "));
2101                         append_with_tabs(&buf, edata->detail);
2102                         appendStringInfoChar(&buf, '\n');
2103                 }
2104                 if (edata->hint)
2105                 {
2106                         log_line_prefix(&buf);
2107                         appendStringInfoString(&buf, _("HINT:  "));
2108                         append_with_tabs(&buf, edata->hint);
2109                         appendStringInfoChar(&buf, '\n');
2110                 }
2111                 if (edata->internalquery)
2112                 {
2113                         log_line_prefix(&buf);
2114                         appendStringInfoString(&buf, _("QUERY:  "));
2115                         append_with_tabs(&buf, edata->internalquery);
2116                         appendStringInfoChar(&buf, '\n');
2117                 }
2118                 if (edata->context)
2119                 {
2120                         log_line_prefix(&buf);
2121                         appendStringInfoString(&buf, _("CONTEXT:  "));
2122                         append_with_tabs(&buf, edata->context);
2123                         appendStringInfoChar(&buf, '\n');
2124                 }
2125                 if (Log_error_verbosity >= PGERROR_VERBOSE)
2126                 {
2127                         /* assume no newlines in funcname or filename... */
2128                         if (edata->funcname && edata->filename)
2129                         {
2130                                 log_line_prefix(&buf);
2131                                 appendStringInfo(&buf, _("LOCATION:  %s, %s:%d\n"),
2132                                                                  edata->funcname, edata->filename,
2133                                                                  edata->lineno);
2134                         }
2135                         else if (edata->filename)
2136                         {
2137                                 log_line_prefix(&buf);
2138                                 appendStringInfo(&buf, _("LOCATION:  %s:%d\n"),
2139                                                                  edata->filename, edata->lineno);
2140                         }
2141                 }
2142         }
2143
2144         /*
2145          * If the user wants the query that generated this error logged, do it.
2146          */
2147         if (is_log_level_output(edata->elevel, log_min_error_statement) &&
2148                 debug_query_string != NULL &&
2149                 !edata->hide_stmt)
2150         {
2151                 log_line_prefix(&buf);
2152                 appendStringInfoString(&buf, _("STATEMENT:  "));
2153                 append_with_tabs(&buf, debug_query_string);
2154                 appendStringInfoChar(&buf, '\n');
2155         }
2156
2157 #ifdef HAVE_SYSLOG
2158         /* Write to syslog, if enabled */
2159         if (Log_destination & LOG_DESTINATION_SYSLOG)
2160         {
2161                 int                     syslog_level;
2162
2163                 switch (edata->elevel)
2164                 {
2165                         case DEBUG5:
2166                         case DEBUG4:
2167                         case DEBUG3:
2168                         case DEBUG2:
2169                         case DEBUG1:
2170                                 syslog_level = LOG_DEBUG;
2171                                 break;
2172                         case LOG:
2173                         case COMMERROR:
2174                         case INFO:
2175                                 syslog_level = LOG_INFO;
2176                                 break;
2177                         case NOTICE:
2178                         case WARNING:
2179                                 syslog_level = LOG_NOTICE;
2180                                 break;
2181                         case ERROR:
2182                                 syslog_level = LOG_WARNING;
2183                                 break;
2184                         case FATAL:
2185                                 syslog_level = LOG_ERR;
2186                                 break;
2187                         case PANIC:
2188                         default:
2189                                 syslog_level = LOG_CRIT;
2190                                 break;
2191                 }
2192
2193                 write_syslog(syslog_level, buf.data);
2194         }
2195 #endif   /* HAVE_SYSLOG */
2196
2197 #ifdef WIN32
2198         /* Write to eventlog, if enabled */
2199         if (Log_destination & LOG_DESTINATION_EVENTLOG)
2200         {
2201                 write_eventlog(edata->elevel, buf.data);
2202         }
2203 #endif   /* WIN32 */
2204
2205         /* Write to stderr, if enabled */
2206         if ((Log_destination & LOG_DESTINATION_STDERR) || whereToSendOutput == DestDebug)
2207         {
2208                 /*
2209                  * Use the chunking protocol if we know the syslogger should be
2210                  * catching stderr output, and we are not ourselves the syslogger.
2211                  * Otherwise, just do a vanilla write to stderr.
2212                  */
2213                 if (redirection_done && !am_syslogger)
2214                         write_pipe_chunks(buf.data, buf.len, LOG_DESTINATION_STDERR);
2215 #ifdef WIN32
2216
2217                 /*
2218                  * In a win32 service environment, there is no usable stderr. Capture
2219                  * anything going there and write it to the eventlog instead.
2220                  *
2221                  * If stderr redirection is active, it was OK to write to stderr above
2222                  * because that's really a pipe to the syslogger process.
2223                  */
2224                 else if (pgwin32_is_service())
2225                         write_eventlog(edata->elevel, buf.data);
2226 #endif
2227                 else
2228                         write(fileno(stderr), buf.data, buf.len);
2229         }
2230
2231         /* If in the syslogger process, try to write messages direct to file */
2232         if (am_syslogger)
2233                 write_syslogger_file(buf.data, buf.len, LOG_DESTINATION_STDERR);
2234
2235         /* Write to CSV log if enabled */
2236         if (Log_destination & LOG_DESTINATION_CSVLOG)
2237         {
2238                 if (redirection_done || am_syslogger)
2239                 {
2240                         /*
2241                          * send CSV data if it's safe to do so (syslogger doesn't need the
2242                          * pipe). First get back the space in the message buffer.
2243                          */
2244                         pfree(buf.data);
2245                         write_csvlog(edata);
2246                 }
2247                 else
2248                 {
2249                         const char *msg = _("Not safe to send CSV data\n");
2250
2251                         write(fileno(stderr), msg, strlen(msg));
2252                         if (!(Log_destination & LOG_DESTINATION_STDERR) &&
2253                                 whereToSendOutput != DestDebug)
2254                         {
2255                                 /* write message to stderr unless we just sent it above */
2256                                 write(fileno(stderr), buf.data, buf.len);
2257                         }
2258                         pfree(buf.data);
2259                 }
2260         }
2261         else
2262         {
2263                 pfree(buf.data);
2264         }
2265 }
2266
2267 /*
2268  * Send data to the syslogger using the chunked protocol
2269  */
2270 static void
2271 write_pipe_chunks(char *data, int len, int dest)
2272 {
2273         PipeProtoChunk p;
2274
2275         int                     fd = fileno(stderr);
2276
2277         Assert(len > 0);
2278
2279         p.proto.nuls[0] = p.proto.nuls[1] = '\0';
2280         p.proto.pid = MyProcPid;
2281
2282         /* write all but the last chunk */
2283         while (len > PIPE_MAX_PAYLOAD)
2284         {
2285                 p.proto.is_last = (dest == LOG_DESTINATION_CSVLOG ? 'F' : 'f');
2286                 p.proto.len = PIPE_MAX_PAYLOAD;
2287                 memcpy(p.proto.data, data, PIPE_MAX_PAYLOAD);
2288                 write(fd, &p, PIPE_HEADER_SIZE + PIPE_MAX_PAYLOAD);
2289                 data += PIPE_MAX_PAYLOAD;
2290                 len -= PIPE_MAX_PAYLOAD;
2291         }
2292
2293         /* write the last chunk */
2294         p.proto.is_last = (dest == LOG_DESTINATION_CSVLOG ? 'T' : 't');
2295         p.proto.len = len;
2296         memcpy(p.proto.data, data, len);
2297         write(fd, &p, PIPE_HEADER_SIZE + len);
2298 }
2299
2300
2301 /*
2302  * Append a text string to the error report being built for the client.
2303  *
2304  * This is ordinarily identical to pq_sendstring(), but if we are in
2305  * error recursion trouble we skip encoding conversion, because of the
2306  * possibility that the problem is a failure in the encoding conversion
2307  * subsystem itself.  Code elsewhere should ensure that the passed-in
2308  * strings will be plain 7-bit ASCII, and thus not in need of conversion,
2309  * in such cases.  (In particular, we disable localization of error messages
2310  * to help ensure that's true.)
2311  */
2312 static void
2313 err_sendstring(StringInfo buf, const char *str)
2314 {
2315         if (in_error_recursion_trouble())
2316                 pq_send_ascii_string(buf, str);
2317         else
2318                 pq_sendstring(buf, str);
2319 }
2320
2321 /*
2322  * Write error report to client
2323  */
2324 static void
2325 send_message_to_frontend(ErrorData *edata)
2326 {
2327         StringInfoData msgbuf;
2328
2329         /* 'N' (Notice) is for nonfatal conditions, 'E' is for errors */
2330         pq_beginmessage(&msgbuf, (edata->elevel < ERROR) ? 'N' : 'E');
2331
2332         if (PG_PROTOCOL_MAJOR(FrontendProtocol) >= 3)
2333         {
2334                 /* New style with separate fields */
2335                 char            tbuf[12];
2336                 int                     ssval;
2337                 int                     i;
2338
2339                 pq_sendbyte(&msgbuf, PG_DIAG_SEVERITY);
2340                 err_sendstring(&msgbuf, error_severity(edata->elevel));
2341
2342                 /* unpack MAKE_SQLSTATE code */
2343                 ssval = edata->sqlerrcode;
2344                 for (i = 0; i < 5; i++)
2345                 {
2346                         tbuf[i] = PGUNSIXBIT(ssval);
2347                         ssval >>= 6;
2348                 }
2349                 tbuf[i] = '\0';
2350
2351                 pq_sendbyte(&msgbuf, PG_DIAG_SQLSTATE);
2352                 err_sendstring(&msgbuf, tbuf);
2353
2354                 /* M field is required per protocol, so always send something */
2355                 pq_sendbyte(&msgbuf, PG_DIAG_MESSAGE_PRIMARY);
2356                 if (edata->message)
2357                         err_sendstring(&msgbuf, edata->message);
2358                 else
2359                         err_sendstring(&msgbuf, _("missing error text"));
2360
2361                 if (edata->detail)
2362                 {
2363                         pq_sendbyte(&msgbuf, PG_DIAG_MESSAGE_DETAIL);
2364                         err_sendstring(&msgbuf, edata->detail);
2365                 }
2366
2367                 /* detail_log is intentionally not used here */
2368
2369                 if (edata->hint)
2370                 {
2371                         pq_sendbyte(&msgbuf, PG_DIAG_MESSAGE_HINT);
2372                         err_sendstring(&msgbuf, edata->hint);
2373                 }
2374
2375                 if (edata->context)
2376                 {
2377                         pq_sendbyte(&msgbuf, PG_DIAG_CONTEXT);
2378                         err_sendstring(&msgbuf, edata->context);
2379                 }
2380
2381                 if (edata->cursorpos > 0)
2382                 {
2383                         snprintf(tbuf, sizeof(tbuf), "%d", edata->cursorpos);
2384                         pq_sendbyte(&msgbuf, PG_DIAG_STATEMENT_POSITION);
2385                         err_sendstring(&msgbuf, tbuf);
2386                 }
2387
2388                 if (edata->internalpos > 0)
2389                 {
2390                         snprintf(tbuf, sizeof(tbuf), "%d", edata->internalpos);
2391                         pq_sendbyte(&msgbuf, PG_DIAG_INTERNAL_POSITION);
2392                         err_sendstring(&msgbuf, tbuf);
2393                 }
2394
2395                 if (edata->internalquery)
2396                 {
2397                         pq_sendbyte(&msgbuf, PG_DIAG_INTERNAL_QUERY);
2398                         err_sendstring(&msgbuf, edata->internalquery);
2399                 }
2400
2401                 if (edata->filename)
2402                 {
2403                         pq_sendbyte(&msgbuf, PG_DIAG_SOURCE_FILE);
2404                         err_sendstring(&msgbuf, edata->filename);
2405                 }
2406
2407                 if (edata->lineno > 0)
2408                 {
2409                         snprintf(tbuf, sizeof(tbuf), "%d", edata->lineno);
2410                         pq_sendbyte(&msgbuf, PG_DIAG_SOURCE_LINE);
2411                         err_sendstring(&msgbuf, tbuf);
2412                 }
2413
2414                 if (edata->funcname)
2415                 {
2416                         pq_sendbyte(&msgbuf, PG_DIAG_SOURCE_FUNCTION);
2417                         err_sendstring(&msgbuf, edata->funcname);
2418                 }
2419
2420                 pq_sendbyte(&msgbuf, '\0');             /* terminator */
2421         }
2422         else
2423         {
2424                 /* Old style --- gin up a backwards-compatible message */
2425                 StringInfoData buf;
2426
2427                 initStringInfo(&buf);
2428
2429                 appendStringInfo(&buf, "%s:  ", error_severity(edata->elevel));
2430
2431                 if (edata->show_funcname && edata->funcname)
2432                         appendStringInfo(&buf, "%s: ", edata->funcname);
2433
2434                 if (edata->message)
2435                         appendStringInfoString(&buf, edata->message);
2436                 else
2437                         appendStringInfoString(&buf, _("missing error text"));
2438
2439                 if (edata->cursorpos > 0)
2440                         appendStringInfo(&buf, _(" at character %d"),
2441                                                          edata->cursorpos);
2442                 else if (edata->internalpos > 0)
2443                         appendStringInfo(&buf, _(" at character %d"),
2444                                                          edata->internalpos);
2445
2446                 appendStringInfoChar(&buf, '\n');
2447
2448                 err_sendstring(&msgbuf, buf.data);
2449
2450                 pfree(buf.data);
2451         }
2452
2453         pq_endmessage(&msgbuf);
2454
2455         /*
2456          * This flush is normally not necessary, since postgres.c will flush out
2457          * waiting data when control returns to the main loop. But it seems best
2458          * to leave it here, so that the client has some clue what happened if the
2459          * backend dies before getting back to the main loop ... error/notice
2460          * messages should not be a performance-critical path anyway, so an extra
2461          * flush won't hurt much ...
2462          */
2463         pq_flush();
2464 }
2465
2466
2467 /*
2468  * Support routines for formatting error messages.
2469  */
2470
2471
2472 /*
2473  * expand_fmt_string --- process special format codes in a format string
2474  *
2475  * We must replace %m with the appropriate strerror string, since vsnprintf
2476  * won't know what to do with it.
2477  *
2478  * The result is a palloc'd string.
2479  */
2480 static char *
2481 expand_fmt_string(const char *fmt, ErrorData *edata)
2482 {
2483         StringInfoData buf;
2484         const char *cp;
2485
2486         initStringInfo(&buf);
2487
2488         for (cp = fmt; *cp; cp++)
2489         {
2490                 if (cp[0] == '%' && cp[1] != '\0')
2491                 {
2492                         cp++;
2493                         if (*cp == 'm')
2494                         {
2495                                 /*
2496                                  * Replace %m by system error string.  If there are any %'s in
2497                                  * the string, we'd better double them so that vsnprintf won't
2498                                  * misinterpret.
2499                                  */
2500                                 const char *cp2;
2501
2502                                 cp2 = useful_strerror(edata->saved_errno);
2503                                 for (; *cp2; cp2++)
2504                                 {
2505                                         if (*cp2 == '%')
2506                                                 appendStringInfoCharMacro(&buf, '%');
2507                                         appendStringInfoCharMacro(&buf, *cp2);
2508                                 }
2509                         }
2510                         else
2511                         {
2512                                 /* copy % and next char --- this avoids trouble with %%m */
2513                                 appendStringInfoCharMacro(&buf, '%');
2514                                 appendStringInfoCharMacro(&buf, *cp);
2515                         }
2516                 }
2517                 else
2518                         appendStringInfoCharMacro(&buf, *cp);
2519         }
2520
2521         return buf.data;
2522 }
2523
2524
2525 /*
2526  * A slightly cleaned-up version of strerror()
2527  */
2528 static const char *
2529 useful_strerror(int errnum)
2530 {
2531         /* this buffer is only used if errno has a bogus value */
2532         static char errorstr_buf[48];
2533         const char *str;
2534
2535 #ifdef WIN32
2536         /* Winsock error code range, per WinError.h */
2537         if (errnum >= 10000 && errnum <= 11999)
2538                 return pgwin32_socket_strerror(errnum);
2539 #endif
2540         str = strerror(errnum);
2541
2542         /*
2543          * Some strerror()s return an empty string for out-of-range errno. This is
2544          * ANSI C spec compliant, but not exactly useful.
2545          */
2546         if (str == NULL || *str == '\0')
2547         {
2548                 snprintf(errorstr_buf, sizeof(errorstr_buf),
2549                 /*------
2550                   translator: This string will be truncated at 47
2551                   characters expanded. */
2552                                  _("operating system error %d"), errnum);
2553                 str = errorstr_buf;
2554         }
2555
2556         return str;
2557 }
2558
2559
2560 /*
2561  * error_severity --- get localized string representing elevel
2562  */
2563 static const char *
2564 error_severity(int elevel)
2565 {
2566         const char *prefix;
2567
2568         switch (elevel)
2569         {
2570                 case DEBUG1:
2571                 case DEBUG2:
2572                 case DEBUG3:
2573                 case DEBUG4:
2574                 case DEBUG5:
2575                         prefix = _("DEBUG");
2576                         break;
2577                 case LOG:
2578                 case COMMERROR:
2579                         prefix = _("LOG");
2580                         break;
2581                 case INFO:
2582                         prefix = _("INFO");
2583                         break;
2584                 case NOTICE:
2585                         prefix = _("NOTICE");
2586                         break;
2587                 case WARNING:
2588                         prefix = _("WARNING");
2589                         break;
2590                 case ERROR:
2591                         prefix = _("ERROR");
2592                         break;
2593                 case FATAL:
2594                         prefix = _("FATAL");
2595                         break;
2596                 case PANIC:
2597                         prefix = _("PANIC");
2598                         break;
2599                 default:
2600                         prefix = "???";
2601                         break;
2602         }
2603
2604         return prefix;
2605 }
2606
2607
2608 /*
2609  *      append_with_tabs
2610  *
2611  *      Append the string to the StringInfo buffer, inserting a tab after any
2612  *      newline.
2613  */
2614 static void
2615 append_with_tabs(StringInfo buf, const char *str)
2616 {
2617         char            ch;
2618
2619         while ((ch = *str++) != '\0')
2620         {
2621                 appendStringInfoCharMacro(buf, ch);
2622                 if (ch == '\n')
2623                         appendStringInfoCharMacro(buf, '\t');
2624         }
2625 }
2626
2627
2628 /*
2629  * Write errors to stderr (or by equal means when stderr is
2630  * not available). Used before ereport/elog can be used
2631  * safely (memory context, GUC load etc)
2632  */
2633 void
2634 write_stderr(const char *fmt,...)
2635 {
2636         va_list         ap;
2637
2638         fmt = _(fmt);
2639
2640         va_start(ap, fmt);
2641 #ifndef WIN32
2642         /* On Unix, we just fprintf to stderr */
2643         vfprintf(stderr, fmt, ap);
2644         fflush(stderr);
2645 #else
2646
2647         /*
2648          * On Win32, we print to stderr if running on a console, or write to
2649          * eventlog if running as a service
2650          */
2651         if (pgwin32_is_service())       /* Running as a service */
2652         {
2653                 char            errbuf[2048];           /* Arbitrary size? */
2654
2655                 vsnprintf(errbuf, sizeof(errbuf), fmt, ap);
2656
2657                 write_eventlog(ERROR, errbuf);
2658         }
2659         else
2660         {
2661                 /* Not running as service, write to stderr */
2662                 vfprintf(stderr, fmt, ap);
2663                 fflush(stderr);
2664         }
2665 #endif
2666         va_end(ap);
2667 }
2668
2669
2670 /*
2671  * is_log_level_output -- is elevel logically >= log_min_level?
2672  *
2673  * We use this for tests that should consider LOG to sort out-of-order,
2674  * between ERROR and FATAL.  Generally this is the right thing for testing
2675  * whether a message should go to the postmaster log, whereas a simple >=
2676  * test is correct for testing whether the message should go to the client.
2677  */
2678 static bool
2679 is_log_level_output(int elevel, int log_min_level)
2680 {
2681         if (elevel == LOG || elevel == COMMERROR)
2682         {
2683                 if (log_min_level == LOG || log_min_level <= ERROR)
2684                         return true;
2685         }
2686         else if (log_min_level == LOG)
2687         {
2688                 /* elevel != LOG */
2689                 if (elevel >= FATAL)
2690                         return true;
2691         }
2692         /* Neither is LOG */
2693         else if (elevel >= log_min_level)
2694                 return true;
2695
2696         return false;
2697 }