]> granicus.if.org Git - postgresql/blob - src/backend/utils/error/elog.c
0439c4c1d1821b35aed6c6a154671fe8c1d8e5a7
[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.213 2009/03/02 21:18:43 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 /*
686  * errmsg --- add a primary error message text to the current error
687  *
688  * In addition to the usual %-escapes recognized by printf, "%m" in
689  * fmt is replaced by the error message for the caller's value of errno.
690  *
691  * Note: no newline is needed at the end of the fmt string, since
692  * ereport will provide one for the output methods that need it.
693  */
694 int
695 errmsg(const char *fmt,...)
696 {
697         ErrorData  *edata = &errordata[errordata_stack_depth];
698         MemoryContext oldcontext;
699
700         recursion_depth++;
701         CHECK_STACK_DEPTH();
702         oldcontext = MemoryContextSwitchTo(ErrorContext);
703
704         EVALUATE_MESSAGE(message, false, true);
705
706         MemoryContextSwitchTo(oldcontext);
707         recursion_depth--;
708         return 0;                                       /* return value does not matter */
709 }
710
711
712 /*
713  * errmsg_internal --- add a primary error message text to the current error
714  *
715  * This is exactly like errmsg() except that strings passed to errmsg_internal
716  * are not translated, and are customarily left out of the
717  * internationalization message dictionary.  This should be used for "can't
718  * happen" cases that are probably not worth spending translation effort on.
719  * We also use this for certain cases where we *must* not try to translate
720  * the message because the translation would fail and result in infinite
721  * error recursion.
722  */
723 int
724 errmsg_internal(const char *fmt,...)
725 {
726         ErrorData  *edata = &errordata[errordata_stack_depth];
727         MemoryContext oldcontext;
728
729         recursion_depth++;
730         CHECK_STACK_DEPTH();
731         oldcontext = MemoryContextSwitchTo(ErrorContext);
732
733         EVALUATE_MESSAGE(message, false, false);
734
735         MemoryContextSwitchTo(oldcontext);
736         recursion_depth--;
737         return 0;                                       /* return value does not matter */
738 }
739
740
741 /*
742  * errdetail --- add a detail error message text to the current error
743  */
744 int
745 errdetail(const char *fmt,...)
746 {
747         ErrorData  *edata = &errordata[errordata_stack_depth];
748         MemoryContext oldcontext;
749
750         recursion_depth++;
751         CHECK_STACK_DEPTH();
752         oldcontext = MemoryContextSwitchTo(ErrorContext);
753
754         EVALUATE_MESSAGE(detail, false, true);
755
756         MemoryContextSwitchTo(oldcontext);
757         recursion_depth--;
758         return 0;                                       /* return value does not matter */
759 }
760
761
762 /*
763  * errdetail_log --- add a detail_log error message text to the current error
764  */
765 int
766 errdetail_log(const char *fmt,...)
767 {
768         ErrorData  *edata = &errordata[errordata_stack_depth];
769         MemoryContext oldcontext;
770
771         recursion_depth++;
772         CHECK_STACK_DEPTH();
773         oldcontext = MemoryContextSwitchTo(ErrorContext);
774
775         EVALUATE_MESSAGE(detail_log, false, true);
776
777         MemoryContextSwitchTo(oldcontext);
778         recursion_depth--;
779         return 0;                                       /* return value does not matter */
780 }
781
782
783 /*
784  * errhint --- add a hint error message text to the current error
785  */
786 int
787 errhint(const char *fmt,...)
788 {
789         ErrorData  *edata = &errordata[errordata_stack_depth];
790         MemoryContext oldcontext;
791
792         recursion_depth++;
793         CHECK_STACK_DEPTH();
794         oldcontext = MemoryContextSwitchTo(ErrorContext);
795
796         EVALUATE_MESSAGE(hint, false, true);
797
798         MemoryContextSwitchTo(oldcontext);
799         recursion_depth--;
800         return 0;                                       /* return value does not matter */
801 }
802
803
804 /*
805  * errcontext --- add a context error message text to the current error
806  *
807  * Unlike other cases, multiple calls are allowed to build up a stack of
808  * context information.  We assume earlier calls represent more-closely-nested
809  * states.
810  */
811 int
812 errcontext(const char *fmt,...)
813 {
814         ErrorData  *edata = &errordata[errordata_stack_depth];
815         MemoryContext oldcontext;
816
817         recursion_depth++;
818         CHECK_STACK_DEPTH();
819         oldcontext = MemoryContextSwitchTo(ErrorContext);
820
821         EVALUATE_MESSAGE(context, true, true);
822
823         MemoryContextSwitchTo(oldcontext);
824         recursion_depth--;
825         return 0;                                       /* return value does not matter */
826 }
827
828
829 /*
830  * errhidestmt --- optionally suppress STATEMENT: field of log entry
831  *
832  * This should be called if the message text already includes the statement.
833  */
834 int
835 errhidestmt(bool hide_stmt)
836 {
837         ErrorData  *edata = &errordata[errordata_stack_depth];
838
839         /* we don't bother incrementing recursion_depth */
840         CHECK_STACK_DEPTH();
841
842         edata->hide_stmt = hide_stmt;
843
844         return 0;                                       /* return value does not matter */
845 }
846
847
848 /*
849  * errfunction --- add reporting function name to the current error
850  *
851  * This is used when backwards compatibility demands that the function
852  * name appear in messages sent to old-protocol clients.  Note that the
853  * passed string is expected to be a non-freeable constant string.
854  */
855 int
856 errfunction(const char *funcname)
857 {
858         ErrorData  *edata = &errordata[errordata_stack_depth];
859
860         /* we don't bother incrementing recursion_depth */
861         CHECK_STACK_DEPTH();
862
863         edata->funcname = funcname;
864         edata->show_funcname = true;
865
866         return 0;                                       /* return value does not matter */
867 }
868
869 /*
870  * errposition --- add cursor position to the current error
871  */
872 int
873 errposition(int cursorpos)
874 {
875         ErrorData  *edata = &errordata[errordata_stack_depth];
876
877         /* we don't bother incrementing recursion_depth */
878         CHECK_STACK_DEPTH();
879
880         edata->cursorpos = cursorpos;
881
882         return 0;                                       /* return value does not matter */
883 }
884
885 /*
886  * internalerrposition --- add internal cursor position to the current error
887  */
888 int
889 internalerrposition(int cursorpos)
890 {
891         ErrorData  *edata = &errordata[errordata_stack_depth];
892
893         /* we don't bother incrementing recursion_depth */
894         CHECK_STACK_DEPTH();
895
896         edata->internalpos = cursorpos;
897
898         return 0;                                       /* return value does not matter */
899 }
900
901 /*
902  * internalerrquery --- add internal query text to the current error
903  *
904  * Can also pass NULL to drop the internal query text entry.  This case
905  * is intended for use in error callback subroutines that are editorializing
906  * on the layout of the error report.
907  */
908 int
909 internalerrquery(const char *query)
910 {
911         ErrorData  *edata = &errordata[errordata_stack_depth];
912
913         /* we don't bother incrementing recursion_depth */
914         CHECK_STACK_DEPTH();
915
916         if (edata->internalquery)
917         {
918                 pfree(edata->internalquery);
919                 edata->internalquery = NULL;
920         }
921
922         if (query)
923                 edata->internalquery = MemoryContextStrdup(ErrorContext, query);
924
925         return 0;                                       /* return value does not matter */
926 }
927
928 /*
929  * geterrcode --- return the currently set SQLSTATE error code
930  *
931  * This is only intended for use in error callback subroutines, since there
932  * is no other place outside elog.c where the concept is meaningful.
933  */
934 int
935 geterrcode(void)
936 {
937         ErrorData  *edata = &errordata[errordata_stack_depth];
938
939         /* we don't bother incrementing recursion_depth */
940         CHECK_STACK_DEPTH();
941
942         return edata->sqlerrcode;
943 }
944
945 /*
946  * geterrposition --- return the currently set error position (0 if none)
947  *
948  * This is only intended for use in error callback subroutines, since there
949  * is no other place outside elog.c where the concept is meaningful.
950  */
951 int
952 geterrposition(void)
953 {
954         ErrorData  *edata = &errordata[errordata_stack_depth];
955
956         /* we don't bother incrementing recursion_depth */
957         CHECK_STACK_DEPTH();
958
959         return edata->cursorpos;
960 }
961
962 /*
963  * getinternalerrposition --- same for internal error position
964  *
965  * This is only intended for use in error callback subroutines, since there
966  * is no other place outside elog.c where the concept is meaningful.
967  */
968 int
969 getinternalerrposition(void)
970 {
971         ErrorData  *edata = &errordata[errordata_stack_depth];
972
973         /* we don't bother incrementing recursion_depth */
974         CHECK_STACK_DEPTH();
975
976         return edata->internalpos;
977 }
978
979
980 /*
981  * elog_start --- startup for old-style API
982  *
983  * All that we do here is stash the hidden filename/lineno/funcname
984  * arguments into a stack entry.
985  *
986  * We need this to be separate from elog_finish because there's no other
987  * portable way to deal with inserting extra arguments into the elog call.
988  * (If macros with variable numbers of arguments were portable, it'd be
989  * easy, but they aren't.)
990  */
991 void
992 elog_start(const char *filename, int lineno, const char *funcname)
993 {
994         ErrorData  *edata;
995
996         if (++errordata_stack_depth >= ERRORDATA_STACK_SIZE)
997         {
998                 /*
999                  * Wups, stack not big enough.  We treat this as a PANIC condition
1000                  * because it suggests an infinite loop of errors during error
1001                  * recovery.  Note that the message is intentionally not localized,
1002                  * else failure to convert it to client encoding could cause further
1003                  * recursion.
1004                  */
1005                 errordata_stack_depth = -1;             /* make room on stack */
1006                 ereport(PANIC, (errmsg_internal("ERRORDATA_STACK_SIZE exceeded")));
1007         }
1008
1009         edata = &errordata[errordata_stack_depth];
1010         edata->filename = filename;
1011         edata->lineno = lineno;
1012         edata->funcname = funcname;
1013         /* errno is saved now so that error parameter eval can't change it */
1014         edata->saved_errno = errno;
1015 }
1016
1017 /*
1018  * elog_finish --- finish up for old-style API
1019  */
1020 void
1021 elog_finish(int elevel, const char *fmt,...)
1022 {
1023         ErrorData  *edata = &errordata[errordata_stack_depth];
1024         MemoryContext oldcontext;
1025
1026         CHECK_STACK_DEPTH();
1027
1028         /*
1029          * Do errstart() to see if we actually want to report the message.
1030          */
1031         errordata_stack_depth--;
1032         errno = edata->saved_errno;
1033         if (!errstart(elevel, edata->filename, edata->lineno, edata->funcname, NULL))
1034                 return;                                 /* nothing to do */
1035
1036         /*
1037          * Format error message just like errmsg_internal().
1038          */
1039         recursion_depth++;
1040         oldcontext = MemoryContextSwitchTo(ErrorContext);
1041
1042         EVALUATE_MESSAGE(message, false, false);
1043
1044         MemoryContextSwitchTo(oldcontext);
1045         recursion_depth--;
1046
1047         /*
1048          * And let errfinish() finish up.
1049          */
1050         errfinish(0);
1051 }
1052
1053 /*
1054  * Actual output of the top-of-stack error message
1055  *
1056  * In the ereport(ERROR) case this is called from PostgresMain (or not at all,
1057  * if the error is caught by somebody).  For all other severity levels this
1058  * is called by errfinish.
1059  */
1060 void
1061 EmitErrorReport(void)
1062 {
1063         ErrorData  *edata = &errordata[errordata_stack_depth];
1064         MemoryContext oldcontext;
1065
1066         recursion_depth++;
1067         CHECK_STACK_DEPTH();
1068         oldcontext = MemoryContextSwitchTo(ErrorContext);
1069
1070         /* Send to server log, if enabled */
1071         if (edata->output_to_server)
1072                 send_message_to_server_log(edata);
1073
1074         /* Send to client, if enabled */
1075         if (edata->output_to_client)
1076                 send_message_to_frontend(edata);
1077
1078         MemoryContextSwitchTo(oldcontext);
1079         recursion_depth--;
1080 }
1081
1082 /*
1083  * CopyErrorData --- obtain a copy of the topmost error stack entry
1084  *
1085  * This is only for use in error handler code.  The data is copied into the
1086  * current memory context, so callers should always switch away from
1087  * ErrorContext first; otherwise it will be lost when FlushErrorState is done.
1088  */
1089 ErrorData *
1090 CopyErrorData(void)
1091 {
1092         ErrorData  *edata = &errordata[errordata_stack_depth];
1093         ErrorData  *newedata;
1094
1095         /*
1096          * we don't increment recursion_depth because out-of-memory here does not
1097          * indicate a problem within the error subsystem.
1098          */
1099         CHECK_STACK_DEPTH();
1100
1101         Assert(CurrentMemoryContext != ErrorContext);
1102
1103         /* Copy the struct itself */
1104         newedata = (ErrorData *) palloc(sizeof(ErrorData));
1105         memcpy(newedata, edata, sizeof(ErrorData));
1106
1107         /* Make copies of separately-allocated fields */
1108         if (newedata->message)
1109                 newedata->message = pstrdup(newedata->message);
1110         if (newedata->detail)
1111                 newedata->detail = pstrdup(newedata->detail);
1112         if (newedata->detail_log)
1113                 newedata->detail_log = pstrdup(newedata->detail_log);
1114         if (newedata->hint)
1115                 newedata->hint = pstrdup(newedata->hint);
1116         if (newedata->context)
1117                 newedata->context = pstrdup(newedata->context);
1118         if (newedata->internalquery)
1119                 newedata->internalquery = pstrdup(newedata->internalquery);
1120
1121         return newedata;
1122 }
1123
1124 /*
1125  * FreeErrorData --- free the structure returned by CopyErrorData.
1126  *
1127  * Error handlers should use this in preference to assuming they know all
1128  * the separately-allocated fields.
1129  */
1130 void
1131 FreeErrorData(ErrorData *edata)
1132 {
1133         if (edata->message)
1134                 pfree(edata->message);
1135         if (edata->detail)
1136                 pfree(edata->detail);
1137         if (edata->detail_log)
1138                 pfree(edata->detail_log);
1139         if (edata->hint)
1140                 pfree(edata->hint);
1141         if (edata->context)
1142                 pfree(edata->context);
1143         if (edata->internalquery)
1144                 pfree(edata->internalquery);
1145         pfree(edata);
1146 }
1147
1148 /*
1149  * FlushErrorState --- flush the error state after error recovery
1150  *
1151  * This should be called by an error handler after it's done processing
1152  * the error; or as soon as it's done CopyErrorData, if it intends to
1153  * do stuff that is likely to provoke another error.  You are not "out" of
1154  * the error subsystem until you have done this.
1155  */
1156 void
1157 FlushErrorState(void)
1158 {
1159         /*
1160          * Reset stack to empty.  The only case where it would be more than one
1161          * deep is if we serviced an error that interrupted construction of
1162          * another message.  We assume control escaped out of that message
1163          * construction and won't ever go back.
1164          */
1165         errordata_stack_depth = -1;
1166         recursion_depth = 0;
1167         /* Delete all data in ErrorContext */
1168         MemoryContextResetAndDeleteChildren(ErrorContext);
1169 }
1170
1171 /*
1172  * ReThrowError --- re-throw a previously copied error
1173  *
1174  * A handler can do CopyErrorData/FlushErrorState to get out of the error
1175  * subsystem, then do some processing, and finally ReThrowError to re-throw
1176  * the original error.  This is slower than just PG_RE_THROW() but should
1177  * be used if the "some processing" is likely to incur another error.
1178  */
1179 void
1180 ReThrowError(ErrorData *edata)
1181 {
1182         ErrorData  *newedata;
1183
1184         Assert(edata->elevel == ERROR);
1185
1186         /* Push the data back into the error context */
1187         recursion_depth++;
1188         MemoryContextSwitchTo(ErrorContext);
1189
1190         if (++errordata_stack_depth >= ERRORDATA_STACK_SIZE)
1191         {
1192                 /*
1193                  * Wups, stack not big enough.  We treat this as a PANIC condition
1194                  * because it suggests an infinite loop of errors during error
1195                  * recovery.
1196                  */
1197                 errordata_stack_depth = -1;             /* make room on stack */
1198                 ereport(PANIC, (errmsg_internal("ERRORDATA_STACK_SIZE exceeded")));
1199         }
1200
1201         newedata = &errordata[errordata_stack_depth];
1202         memcpy(newedata, edata, sizeof(ErrorData));
1203
1204         /* Make copies of separately-allocated fields */
1205         if (newedata->message)
1206                 newedata->message = pstrdup(newedata->message);
1207         if (newedata->detail)
1208                 newedata->detail = pstrdup(newedata->detail);
1209         if (newedata->detail_log)
1210                 newedata->detail_log = pstrdup(newedata->detail_log);
1211         if (newedata->hint)
1212                 newedata->hint = pstrdup(newedata->hint);
1213         if (newedata->context)
1214                 newedata->context = pstrdup(newedata->context);
1215         if (newedata->internalquery)
1216                 newedata->internalquery = pstrdup(newedata->internalquery);
1217
1218         recursion_depth--;
1219         PG_RE_THROW();
1220 }
1221
1222 /*
1223  * pg_re_throw --- out-of-line implementation of PG_RE_THROW() macro
1224  */
1225 void
1226 pg_re_throw(void)
1227 {
1228         /* If possible, throw the error to the next outer setjmp handler */
1229         if (PG_exception_stack != NULL)
1230                 siglongjmp(*PG_exception_stack, 1);
1231         else
1232         {
1233                 /*
1234                  * If we get here, elog(ERROR) was thrown inside a PG_TRY block, which
1235                  * we have now exited only to discover that there is no outer setjmp
1236                  * handler to pass the error to.  Had the error been thrown outside
1237                  * the block to begin with, we'd have promoted the error to FATAL, so
1238                  * the correct behavior is to make it FATAL now; that is, emit it and
1239                  * then call proc_exit.
1240                  */
1241                 ErrorData  *edata = &errordata[errordata_stack_depth];
1242
1243                 Assert(errordata_stack_depth >= 0);
1244                 Assert(edata->elevel == ERROR);
1245                 edata->elevel = FATAL;
1246
1247                 /*
1248                  * At least in principle, the increase in severity could have changed
1249                  * where-to-output decisions, so recalculate.  This should stay in
1250                  * sync with errstart(), which see for comments.
1251                  */
1252                 if (IsPostmasterEnvironment)
1253                         edata->output_to_server = is_log_level_output(FATAL,
1254                                                                                                                   log_min_messages);
1255                 else
1256                         edata->output_to_server = (FATAL >= log_min_messages);
1257                 if (whereToSendOutput == DestRemote)
1258                 {
1259                         if (ClientAuthInProgress)
1260                                 edata->output_to_client = true;
1261                         else
1262                                 edata->output_to_client = (FATAL >= client_min_messages);
1263                 }
1264
1265                 /*
1266                  * We can use errfinish() for the rest, but we don't want it to call
1267                  * any error context routines a second time.  Since we know we are
1268                  * about to exit, it should be OK to just clear the context stack.
1269                  */
1270                 error_context_stack = NULL;
1271
1272                 errfinish(0);
1273         }
1274
1275         /* We mustn't return... */
1276         ExceptionalCondition("pg_re_throw tried to return", "FailedAssertion",
1277                                                  __FILE__, __LINE__);
1278
1279         /*
1280          * Since ExceptionalCondition isn't declared noreturn because of
1281          * TrapMacro(), we need this to keep gcc from complaining.
1282          */
1283         abort();
1284 }
1285
1286
1287 /*
1288  * Initialization of error output file
1289  */
1290 void
1291 DebugFileOpen(void)
1292 {
1293         int                     fd,
1294                                 istty;
1295
1296         if (OutputFileName[0])
1297         {
1298                 /*
1299                  * A debug-output file name was given.
1300                  *
1301                  * Make sure we can write the file, and find out if it's a tty.
1302                  */
1303                 if ((fd = open(OutputFileName, O_CREAT | O_APPEND | O_WRONLY,
1304                                            0666)) < 0)
1305                         ereport(FATAL,
1306                                         (errcode_for_file_access(),
1307                                   errmsg("could not open file \"%s\": %m", OutputFileName)));
1308                 istty = isatty(fd);
1309                 close(fd);
1310
1311                 /*
1312                  * Redirect our stderr to the debug output file.
1313                  */
1314                 if (!freopen(OutputFileName, "a", stderr))
1315                         ereport(FATAL,
1316                                         (errcode_for_file_access(),
1317                                          errmsg("could not reopen file \"%s\" as stderr: %m",
1318                                                         OutputFileName)));
1319
1320                 /*
1321                  * If the file is a tty and we're running under the postmaster, try to
1322                  * send stdout there as well (if it isn't a tty then stderr will block
1323                  * out stdout, so we may as well let stdout go wherever it was going
1324                  * before).
1325                  */
1326                 if (istty && IsUnderPostmaster)
1327                         if (!freopen(OutputFileName, "a", stdout))
1328                                 ereport(FATAL,
1329                                                 (errcode_for_file_access(),
1330                                                  errmsg("could not reopen file \"%s\" as stdout: %m",
1331                                                                 OutputFileName)));
1332         }
1333 }
1334
1335
1336 #ifdef HAVE_SYSLOG
1337
1338 /*
1339  * Set or update the parameters for syslog logging
1340  */
1341 void
1342 set_syslog_parameters(const char *ident, int facility)
1343 {
1344         /*
1345          * guc.c is likely to call us repeatedly with same parameters, so don't
1346          * thrash the syslog connection unnecessarily.  Also, we do not re-open
1347          * the connection until needed, since this routine will get called whether
1348          * or not Log_destination actually mentions syslog.
1349          *
1350          * Note that we make our own copy of the ident string rather than relying
1351          * on guc.c's.  This may be overly paranoid, but it ensures that we cannot
1352          * accidentally free a string that syslog is still using.
1353          */
1354         if (syslog_ident == NULL || strcmp(syslog_ident, ident) != 0 ||
1355                 syslog_facility != facility)
1356         {
1357                 if (openlog_done)
1358                 {
1359                         closelog();
1360                         openlog_done = false;
1361                 }
1362                 if (syslog_ident)
1363                         free(syslog_ident);
1364                 syslog_ident = strdup(ident);
1365                 /* if the strdup fails, we will cope in write_syslog() */
1366                 syslog_facility = facility;
1367         }
1368 }
1369
1370
1371 /*
1372  * Write a message line to syslog
1373  */
1374 static void
1375 write_syslog(int level, const char *line)
1376 {
1377         static unsigned long seq = 0;
1378
1379         int                     len;
1380         const char *nlpos;
1381
1382         /* Open syslog connection if not done yet */
1383         if (!openlog_done)
1384         {
1385                 openlog(syslog_ident ? syslog_ident : "postgres",
1386                                 LOG_PID | LOG_NDELAY | LOG_NOWAIT,
1387                                 syslog_facility);
1388                 openlog_done = true;
1389         }
1390
1391         /*
1392          * We add a sequence number to each log message to suppress "same"
1393          * messages.
1394          */
1395         seq++;
1396
1397         /*
1398          * Our problem here is that many syslog implementations don't handle long
1399          * messages in an acceptable manner. While this function doesn't help that
1400          * fact, it does work around by splitting up messages into smaller pieces.
1401          *
1402          * We divide into multiple syslog() calls if message is too long or if the
1403          * message contains embedded newline(s).
1404          */
1405         len = strlen(line);
1406         nlpos = strchr(line, '\n');
1407         if (len > PG_SYSLOG_LIMIT || nlpos != NULL)
1408         {
1409                 int                     chunk_nr = 0;
1410
1411                 while (len > 0)
1412                 {
1413                         char            buf[PG_SYSLOG_LIMIT + 1];
1414                         int                     buflen;
1415                         int                     i;
1416
1417                         /* if we start at a newline, move ahead one char */
1418                         if (line[0] == '\n')
1419                         {
1420                                 line++;
1421                                 len--;
1422                                 /* we need to recompute the next newline's position, too */
1423                                 nlpos = strchr(line, '\n');
1424                                 continue;
1425                         }
1426
1427                         /* copy one line, or as much as will fit, to buf */
1428                         if (nlpos != NULL)
1429                                 buflen = nlpos - line;
1430                         else
1431                                 buflen = len;
1432                         buflen = Min(buflen, PG_SYSLOG_LIMIT);
1433                         memcpy(buf, line, buflen);
1434                         buf[buflen] = '\0';
1435
1436                         /* trim to multibyte letter boundary */
1437                         buflen = pg_mbcliplen(buf, buflen, buflen);
1438                         if (buflen <= 0)
1439                                 return;
1440                         buf[buflen] = '\0';
1441
1442                         /* already word boundary? */
1443                         if (line[buflen] != '\0' &&
1444                                 !isspace((unsigned char) line[buflen]))
1445                         {
1446                                 /* try to divide at word boundary */
1447                                 i = buflen - 1;
1448                                 while (i > 0 && !isspace((unsigned char) buf[i]))
1449                                         i--;
1450
1451                                 if (i > 0)              /* else couldn't divide word boundary */
1452                                 {
1453                                         buflen = i;
1454                                         buf[i] = '\0';
1455                                 }
1456                         }
1457
1458                         chunk_nr++;
1459
1460                         syslog(level, "[%lu-%d] %s", seq, chunk_nr, buf);
1461                         line += buflen;
1462                         len -= buflen;
1463                 }
1464         }
1465         else
1466         {
1467                 /* message short enough */
1468                 syslog(level, "[%lu] %s", seq, line);
1469         }
1470 }
1471 #endif   /* HAVE_SYSLOG */
1472
1473 #ifdef WIN32
1474 /*
1475  * Write a message line to the windows event log
1476  */
1477 static void
1478 write_eventlog(int level, const char *line)
1479 {
1480         int                     eventlevel = EVENTLOG_ERROR_TYPE;
1481         static HANDLE evtHandle = INVALID_HANDLE_VALUE;
1482
1483         if (evtHandle == INVALID_HANDLE_VALUE)
1484         {
1485                 evtHandle = RegisterEventSource(NULL, "PostgreSQL");
1486                 if (evtHandle == NULL)
1487                 {
1488                         evtHandle = INVALID_HANDLE_VALUE;
1489                         return;
1490                 }
1491         }
1492
1493         switch (level)
1494         {
1495                 case DEBUG5:
1496                 case DEBUG4:
1497                 case DEBUG3:
1498                 case DEBUG2:
1499                 case DEBUG1:
1500                 case LOG:
1501                 case COMMERROR:
1502                 case INFO:
1503                 case NOTICE:
1504                         eventlevel = EVENTLOG_INFORMATION_TYPE;
1505                         break;
1506                 case WARNING:
1507                         eventlevel = EVENTLOG_WARNING_TYPE;
1508                         break;
1509                 case ERROR:
1510                 case FATAL:
1511                 case PANIC:
1512                 default:
1513                         eventlevel = EVENTLOG_ERROR_TYPE;
1514                         break;
1515         }
1516
1517
1518         ReportEvent(evtHandle,
1519                                 eventlevel,
1520                                 0,
1521                                 0,                              /* All events are Id 0 */
1522                                 NULL,
1523                                 1,
1524                                 0,
1525                                 &line,
1526                                 NULL);
1527 }
1528 #endif   /* WIN32 */
1529
1530 /*
1531  * setup formatted_log_time, for consistent times between CSV and regular logs
1532  */
1533 static void
1534 setup_formatted_log_time(void)
1535 {
1536         struct timeval tv;
1537         pg_time_t       stamp_time;
1538         pg_tz      *tz;
1539         char            msbuf[8];
1540
1541         gettimeofday(&tv, NULL);
1542         stamp_time = (pg_time_t) tv.tv_sec;
1543
1544         /*
1545          * Normally we print log timestamps in log_timezone, but during startup we
1546          * could get here before that's set. If so, fall back to gmt_timezone
1547          * (which guc.c ensures is set up before Log_line_prefix can become
1548          * nonempty).
1549          */
1550         tz = log_timezone ? log_timezone : gmt_timezone;
1551
1552         pg_strftime(formatted_log_time, FORMATTED_TS_LEN,
1553                                 /* leave room for milliseconds... */
1554                                 "%Y-%m-%d %H:%M:%S     %Z",
1555                                 pg_localtime(&stamp_time, tz));
1556
1557         /* 'paste' milliseconds into place... */
1558         sprintf(msbuf, ".%03d", (int) (tv.tv_usec / 1000));
1559         strncpy(formatted_log_time + 19, msbuf, 4);
1560 }
1561
1562 /*
1563  * setup formatted_start_time
1564  */
1565 static void
1566 setup_formatted_start_time(void)
1567 {
1568         pg_time_t       stamp_time = (pg_time_t) MyStartTime;
1569         pg_tz      *tz;
1570
1571         /*
1572          * Normally we print log timestamps in log_timezone, but during startup we
1573          * could get here before that's set. If so, fall back to gmt_timezone
1574          * (which guc.c ensures is set up before Log_line_prefix can become
1575          * nonempty).
1576          */
1577         tz = log_timezone ? log_timezone : gmt_timezone;
1578
1579         pg_strftime(formatted_start_time, FORMATTED_TS_LEN,
1580                                 "%Y-%m-%d %H:%M:%S %Z",
1581                                 pg_localtime(&stamp_time, tz));
1582 }
1583
1584 /*
1585  * Format tag info for log lines; append to the provided buffer.
1586  */
1587 static void
1588 log_line_prefix(StringInfo buf)
1589 {
1590         /* static counter for line numbers */
1591         static long log_line_number = 0;
1592
1593         /* has counter been reset in current process? */
1594         static int      log_my_pid = 0;
1595
1596         int                     format_len;
1597         int                     i;
1598
1599         /*
1600          * This is one of the few places where we'd rather not inherit a static
1601          * variable's value from the postmaster.  But since we will, reset it when
1602          * MyProcPid changes. MyStartTime also changes when MyProcPid does, so
1603          * reset the formatted start timestamp too.
1604          */
1605         if (log_my_pid != MyProcPid)
1606         {
1607                 log_line_number = 0;
1608                 log_my_pid = MyProcPid;
1609                 formatted_start_time[0] = '\0';
1610         }
1611         log_line_number++;
1612
1613         if (Log_line_prefix == NULL)
1614                 return;                                 /* in case guc hasn't run yet */
1615
1616         format_len = strlen(Log_line_prefix);
1617
1618         for (i = 0; i < format_len; i++)
1619         {
1620                 if (Log_line_prefix[i] != '%')
1621                 {
1622                         /* literal char, just copy */
1623                         appendStringInfoChar(buf, Log_line_prefix[i]);
1624                         continue;
1625                 }
1626                 /* go to char after '%' */
1627                 i++;
1628                 if (i >= format_len)
1629                         break;                          /* format error - ignore it */
1630
1631                 /* process the option */
1632                 switch (Log_line_prefix[i])
1633                 {
1634                         case 'u':
1635                                 if (MyProcPort)
1636                                 {
1637                                         const char *username = MyProcPort->user_name;
1638
1639                                         if (username == NULL || *username == '\0')
1640                                                 username = _("[unknown]");
1641                                         appendStringInfo(buf, "%s", username);
1642                                 }
1643                                 break;
1644                         case 'd':
1645                                 if (MyProcPort)
1646                                 {
1647                                         const char *dbname = MyProcPort->database_name;
1648
1649                                         if (dbname == NULL || *dbname == '\0')
1650                                                 dbname = _("[unknown]");
1651                                         appendStringInfo(buf, "%s", dbname);
1652                                 }
1653                                 break;
1654                         case 'c':
1655                                 appendStringInfo(buf, "%lx.%x", (long) (MyStartTime), MyProcPid);
1656                                 break;
1657                         case 'p':
1658                                 appendStringInfo(buf, "%d", MyProcPid);
1659                                 break;
1660                         case 'l':
1661                                 appendStringInfo(buf, "%ld", log_line_number);
1662                                 break;
1663                         case 'm':
1664                                 setup_formatted_log_time();
1665                                 appendStringInfoString(buf, formatted_log_time);
1666                                 break;
1667                         case 't':
1668                                 {
1669                                         pg_time_t       stamp_time = (pg_time_t) time(NULL);
1670                                         pg_tz      *tz;
1671                                         char            strfbuf[128];
1672
1673                                         tz = log_timezone ? log_timezone : gmt_timezone;
1674
1675                                         pg_strftime(strfbuf, sizeof(strfbuf),
1676                                                                 "%Y-%m-%d %H:%M:%S %Z",
1677                                                                 pg_localtime(&stamp_time, tz));
1678                                         appendStringInfoString(buf, strfbuf);
1679                                 }
1680                                 break;
1681                         case 's':
1682                                 if (formatted_start_time[0] == '\0')
1683                                         setup_formatted_start_time();
1684                                 appendStringInfoString(buf, formatted_start_time);
1685                                 break;
1686                         case 'i':
1687                                 if (MyProcPort)
1688                                 {
1689                                         const char *psdisp;
1690                                         int                     displen;
1691
1692                                         psdisp = get_ps_display(&displen);
1693                                         appendStringInfo(buf, "%.*s", displen, psdisp);
1694                                 }
1695                                 break;
1696                         case 'r':
1697                                 if (MyProcPort && MyProcPort->remote_host)
1698                                 {
1699                                         appendStringInfo(buf, "%s", MyProcPort->remote_host);
1700                                         if (MyProcPort->remote_port &&
1701                                                 MyProcPort->remote_port[0] != '\0')
1702                                                 appendStringInfo(buf, "(%s)",
1703                                                                                  MyProcPort->remote_port);
1704                                 }
1705                                 break;
1706                         case 'h':
1707                                 if (MyProcPort && MyProcPort->remote_host)
1708                                         appendStringInfo(buf, "%s", MyProcPort->remote_host);
1709                                 break;
1710                         case 'q':
1711                                 /* in postmaster and friends, stop if %q is seen */
1712                                 /* in a backend, just ignore */
1713                                 if (MyProcPort == NULL)
1714                                         i = format_len;
1715                                 break;
1716                         case 'v':
1717                                 /* keep VXID format in sync with lockfuncs.c */
1718                                 if (MyProc != NULL && MyProc->backendId != InvalidBackendId)
1719                                         appendStringInfo(buf, "%d/%u",
1720                                                                          MyProc->backendId, MyProc->lxid);
1721                                 break;
1722                         case 'x':
1723                                 appendStringInfo(buf, "%u", GetTopTransactionIdIfAny());
1724                                 break;
1725                         case '%':
1726                                 appendStringInfoChar(buf, '%');
1727                                 break;
1728                         default:
1729                                 /* format error - ignore it */
1730                                 break;
1731                 }
1732         }
1733 }
1734
1735 /*
1736  * append a CSV'd version of a string to a StringInfo
1737  * We use the PostgreSQL defaults for CSV, i.e. quote = escape = '"'
1738  * If it's NULL, append nothing.
1739  */
1740 static inline void
1741 appendCSVLiteral(StringInfo buf, const char *data)
1742 {
1743         const char *p = data;
1744         char            c;
1745
1746         /* avoid confusing an empty string with NULL */
1747         if (p == NULL)
1748                 return;
1749
1750         appendStringInfoCharMacro(buf, '"');
1751         while ((c = *p++) != '\0')
1752         {
1753                 if (c == '"')
1754                         appendStringInfoCharMacro(buf, '"');
1755                 appendStringInfoCharMacro(buf, c);
1756         }
1757         appendStringInfoCharMacro(buf, '"');
1758 }
1759
1760 /*
1761  * Constructs the error message, depending on the Errordata it gets, in a CSV
1762  * format which is described in doc/src/sgml/config.sgml.
1763  */
1764 static void
1765 write_csvlog(ErrorData *edata)
1766 {
1767         StringInfoData buf;
1768         bool    print_stmt = false;
1769
1770         /* static counter for line numbers */
1771         static long log_line_number = 0;
1772
1773         /* has counter been reset in current process? */
1774         static int      log_my_pid = 0;
1775
1776         /*
1777          * This is one of the few places where we'd rather not inherit a static
1778          * variable's value from the postmaster.  But since we will, reset it when
1779          * MyProcPid changes.
1780          */
1781         if (log_my_pid != MyProcPid)
1782         {
1783                 log_line_number = 0;
1784                 log_my_pid = MyProcPid;
1785                 formatted_start_time[0] = '\0';
1786         }
1787         log_line_number++;
1788
1789         initStringInfo(&buf);
1790
1791         /*
1792          * timestamp with milliseconds
1793          *
1794          * Check if the timestamp is already calculated for the syslog message,
1795          * and use it if so.  Otherwise, get the current timestamp.  This is done
1796          * to put same timestamp in both syslog and csvlog messages.
1797          */
1798         if (formatted_log_time[0] == '\0')
1799                 setup_formatted_log_time();
1800
1801         appendStringInfoString(&buf, formatted_log_time);
1802         appendStringInfoChar(&buf, ',');
1803
1804         /* username */
1805         if (MyProcPort)
1806                 appendCSVLiteral(&buf, MyProcPort->user_name);
1807         appendStringInfoChar(&buf, ',');
1808
1809         /* database name */
1810         if (MyProcPort)
1811                 appendCSVLiteral(&buf, MyProcPort->database_name);
1812         appendStringInfoChar(&buf, ',');
1813
1814         /* Process id  */
1815         if (MyProcPid != 0)
1816                 appendStringInfo(&buf, "%d", MyProcPid);
1817         appendStringInfoChar(&buf, ',');
1818
1819         /* Remote host and port */
1820         if (MyProcPort && MyProcPort->remote_host)
1821         {
1822                 appendStringInfoChar(&buf, '"');
1823                 appendStringInfo(&buf, "%s", MyProcPort->remote_host);
1824                 if (MyProcPort->remote_port && MyProcPort->remote_port[0] != '\0')
1825                         appendStringInfo(&buf, ":%s", MyProcPort->remote_port);
1826                 appendStringInfoChar(&buf, '"');
1827         }
1828         appendStringInfoChar(&buf, ',');
1829
1830         /* session id */
1831         appendStringInfo(&buf, "%lx.%x", (long) MyStartTime, MyProcPid);
1832         appendStringInfoChar(&buf, ',');
1833
1834         /* Line number */
1835         appendStringInfo(&buf, "%ld", log_line_number);
1836         appendStringInfoChar(&buf, ',');
1837
1838         /* PS display */
1839         if (MyProcPort)
1840         {
1841                 StringInfoData msgbuf;
1842                 const char *psdisp;
1843                 int                     displen;
1844
1845                 initStringInfo(&msgbuf);
1846
1847                 psdisp = get_ps_display(&displen);
1848                 appendStringInfo(&msgbuf, "%.*s", displen, psdisp);
1849                 appendCSVLiteral(&buf, msgbuf.data);
1850         
1851                 pfree(msgbuf.data);
1852         }
1853         appendStringInfoChar(&buf, ',');
1854
1855         /* session start timestamp */
1856         if (formatted_start_time[0] == '\0')
1857                 setup_formatted_start_time();
1858         appendStringInfoString(&buf, formatted_start_time);
1859         appendStringInfoChar(&buf, ',');
1860
1861         /* Virtual transaction id */
1862         /* keep VXID format in sync with lockfuncs.c */
1863         if (MyProc != NULL && MyProc->backendId != InvalidBackendId)
1864                 appendStringInfo(&buf, "%d/%u", MyProc->backendId, MyProc->lxid);
1865         appendStringInfoChar(&buf, ',');
1866
1867         /* Transaction id */
1868         appendStringInfo(&buf, "%u", GetTopTransactionIdIfAny());
1869         appendStringInfoChar(&buf, ',');
1870
1871         /* Error severity */
1872         appendStringInfo(&buf, "%s", error_severity(edata->elevel));
1873         appendStringInfoChar(&buf, ',');
1874
1875         /* SQL state code */
1876         appendStringInfo(&buf, "%s", unpack_sql_state(edata->sqlerrcode));
1877         appendStringInfoChar(&buf, ',');
1878
1879         /* errmessage */
1880         appendCSVLiteral(&buf, edata->message);
1881         appendStringInfoCharMacro(&buf, ',');
1882
1883         /* errdetail or errdetail_log */
1884         if (edata->detail_log)
1885                 appendCSVLiteral(&buf, edata->detail_log);
1886         else
1887                 appendCSVLiteral(&buf, edata->detail);
1888         appendStringInfoCharMacro(&buf, ',');
1889
1890         /* errhint */
1891         appendCSVLiteral(&buf, edata->hint);
1892         appendStringInfoCharMacro(&buf, ',');
1893
1894         /* internal query */
1895         appendCSVLiteral(&buf, edata->internalquery);
1896         appendStringInfoCharMacro(&buf, ',');
1897
1898         /* if printed internal query, print internal pos too */
1899         if (edata->internalpos > 0 && edata->internalquery != NULL)
1900                 appendStringInfo(&buf, "%d", edata->internalpos);
1901         appendStringInfoCharMacro(&buf, ',');
1902
1903         /* errcontext */
1904         appendCSVLiteral(&buf, edata->context);
1905         appendStringInfoCharMacro(&buf, ',');
1906
1907         /* user query --- only reported if not disabled by the caller */
1908         if (is_log_level_output(edata->elevel, log_min_error_statement) &&
1909                 debug_query_string != NULL &&
1910                 !edata->hide_stmt)
1911                 print_stmt = true;
1912         if (print_stmt)
1913                 appendCSVLiteral(&buf, debug_query_string);
1914         appendStringInfoCharMacro(&buf, ',');
1915         if (print_stmt && edata->cursorpos > 0)
1916                 appendStringInfo(&buf, "%d", edata->cursorpos);
1917         appendStringInfoCharMacro(&buf, ',');
1918
1919         /* file error location */
1920         if (Log_error_verbosity >= PGERROR_VERBOSE)
1921         {
1922                 StringInfoData  msgbuf;
1923
1924                 initStringInfo(&msgbuf);
1925
1926                 if (edata->funcname && edata->filename)
1927                         appendStringInfo(&msgbuf, "%s, %s:%d",
1928                                                          edata->funcname, edata->filename,
1929                                                          edata->lineno);
1930                 else if (edata->filename)
1931                         appendStringInfo(&msgbuf, "%s:%d",
1932                                                          edata->filename, edata->lineno);
1933                 appendCSVLiteral(&buf, msgbuf.data);
1934                 pfree(msgbuf.data);
1935         }
1936
1937         appendStringInfoChar(&buf, '\n');
1938
1939         /* If in the syslogger process, try to write messages direct to file */
1940         if (am_syslogger)
1941                 write_syslogger_file(buf.data, buf.len, LOG_DESTINATION_CSVLOG);
1942         else
1943                 write_pipe_chunks(buf.data, buf.len, LOG_DESTINATION_CSVLOG);
1944
1945         pfree(buf.data);
1946 }
1947
1948 /*
1949  * Unpack MAKE_SQLSTATE code. Note that this returns a pointer to a
1950  * static buffer.
1951  */
1952 char *
1953 unpack_sql_state(int sql_state)
1954 {
1955         static char buf[12];
1956         int                     i;
1957
1958         for (i = 0; i < 5; i++)
1959         {
1960                 buf[i] = PGUNSIXBIT(sql_state);
1961                 sql_state >>= 6;
1962         }
1963
1964         buf[i] = '\0';
1965         return buf;
1966 }
1967
1968
1969 /*
1970  * Write error report to server's log
1971  */
1972 static void
1973 send_message_to_server_log(ErrorData *edata)
1974 {
1975         StringInfoData buf;
1976
1977         initStringInfo(&buf);
1978
1979         formatted_log_time[0] = '\0';
1980
1981         log_line_prefix(&buf);
1982         appendStringInfo(&buf, "%s:  ", error_severity(edata->elevel));
1983
1984         if (Log_error_verbosity >= PGERROR_VERBOSE)
1985                 appendStringInfo(&buf, "%s: ", unpack_sql_state(edata->sqlerrcode));
1986
1987         if (edata->message)
1988                 append_with_tabs(&buf, edata->message);
1989         else
1990                 append_with_tabs(&buf, _("missing error text"));
1991
1992         if (edata->cursorpos > 0)
1993                 appendStringInfo(&buf, _(" at character %d"),
1994                                                  edata->cursorpos);
1995         else if (edata->internalpos > 0)
1996                 appendStringInfo(&buf, _(" at character %d"),
1997                                                  edata->internalpos);
1998
1999         appendStringInfoChar(&buf, '\n');
2000
2001         if (Log_error_verbosity >= PGERROR_DEFAULT)
2002         {
2003                 if (edata->detail_log)
2004                 {
2005                         log_line_prefix(&buf);
2006                         appendStringInfoString(&buf, _("DETAIL:  "));
2007                         append_with_tabs(&buf, edata->detail_log);
2008                         appendStringInfoChar(&buf, '\n');
2009                 }
2010                 else if (edata->detail)
2011                 {
2012                         log_line_prefix(&buf);
2013                         appendStringInfoString(&buf, _("DETAIL:  "));
2014                         append_with_tabs(&buf, edata->detail);
2015                         appendStringInfoChar(&buf, '\n');
2016                 }
2017                 if (edata->hint)
2018                 {
2019                         log_line_prefix(&buf);
2020                         appendStringInfoString(&buf, _("HINT:  "));
2021                         append_with_tabs(&buf, edata->hint);
2022                         appendStringInfoChar(&buf, '\n');
2023                 }
2024                 if (edata->internalquery)
2025                 {
2026                         log_line_prefix(&buf);
2027                         appendStringInfoString(&buf, _("QUERY:  "));
2028                         append_with_tabs(&buf, edata->internalquery);
2029                         appendStringInfoChar(&buf, '\n');
2030                 }
2031                 if (edata->context)
2032                 {
2033                         log_line_prefix(&buf);
2034                         appendStringInfoString(&buf, _("CONTEXT:  "));
2035                         append_with_tabs(&buf, edata->context);
2036                         appendStringInfoChar(&buf, '\n');
2037                 }
2038                 if (Log_error_verbosity >= PGERROR_VERBOSE)
2039                 {
2040                         /* assume no newlines in funcname or filename... */
2041                         if (edata->funcname && edata->filename)
2042                         {
2043                                 log_line_prefix(&buf);
2044                                 appendStringInfo(&buf, _("LOCATION:  %s, %s:%d\n"),
2045                                                                  edata->funcname, edata->filename,
2046                                                                  edata->lineno);
2047                         }
2048                         else if (edata->filename)
2049                         {
2050                                 log_line_prefix(&buf);
2051                                 appendStringInfo(&buf, _("LOCATION:  %s:%d\n"),
2052                                                                  edata->filename, edata->lineno);
2053                         }
2054                 }
2055         }
2056
2057         /*
2058          * If the user wants the query that generated this error logged, do it.
2059          */
2060         if (is_log_level_output(edata->elevel, log_min_error_statement) &&
2061                 debug_query_string != NULL &&
2062                 !edata->hide_stmt)
2063         {
2064                 log_line_prefix(&buf);
2065                 appendStringInfoString(&buf, _("STATEMENT:  "));
2066                 append_with_tabs(&buf, debug_query_string);
2067                 appendStringInfoChar(&buf, '\n');
2068         }
2069
2070 #ifdef HAVE_SYSLOG
2071         /* Write to syslog, if enabled */
2072         if (Log_destination & LOG_DESTINATION_SYSLOG)
2073         {
2074                 int                     syslog_level;
2075
2076                 switch (edata->elevel)
2077                 {
2078                         case DEBUG5:
2079                         case DEBUG4:
2080                         case DEBUG3:
2081                         case DEBUG2:
2082                         case DEBUG1:
2083                                 syslog_level = LOG_DEBUG;
2084                                 break;
2085                         case LOG:
2086                         case COMMERROR:
2087                         case INFO:
2088                                 syslog_level = LOG_INFO;
2089                                 break;
2090                         case NOTICE:
2091                         case WARNING:
2092                                 syslog_level = LOG_NOTICE;
2093                                 break;
2094                         case ERROR:
2095                                 syslog_level = LOG_WARNING;
2096                                 break;
2097                         case FATAL:
2098                                 syslog_level = LOG_ERR;
2099                                 break;
2100                         case PANIC:
2101                         default:
2102                                 syslog_level = LOG_CRIT;
2103                                 break;
2104                 }
2105
2106                 write_syslog(syslog_level, buf.data);
2107         }
2108 #endif   /* HAVE_SYSLOG */
2109
2110 #ifdef WIN32
2111         /* Write to eventlog, if enabled */
2112         if (Log_destination & LOG_DESTINATION_EVENTLOG)
2113         {
2114                 write_eventlog(edata->elevel, buf.data);
2115         }
2116 #endif   /* WIN32 */
2117
2118         /* Write to stderr, if enabled */
2119         if ((Log_destination & LOG_DESTINATION_STDERR) || whereToSendOutput == DestDebug)
2120         {
2121                 /*
2122                  * Use the chunking protocol if we know the syslogger should be
2123                  * catching stderr output, and we are not ourselves the syslogger.
2124                  * Otherwise, just do a vanilla write to stderr.
2125                  */
2126                 if (redirection_done && !am_syslogger)
2127                         write_pipe_chunks(buf.data, buf.len, LOG_DESTINATION_STDERR);
2128 #ifdef WIN32
2129
2130                 /*
2131                  * In a win32 service environment, there is no usable stderr. Capture
2132                  * anything going there and write it to the eventlog instead.
2133                  *
2134                  * If stderr redirection is active, it was OK to write to stderr above
2135                  * because that's really a pipe to the syslogger process.
2136                  */
2137                 else if (pgwin32_is_service())
2138                         write_eventlog(edata->elevel, buf.data);
2139 #endif
2140                 else
2141                         write(fileno(stderr), buf.data, buf.len);
2142         }
2143
2144         /* If in the syslogger process, try to write messages direct to file */
2145         if (am_syslogger)
2146                 write_syslogger_file(buf.data, buf.len, LOG_DESTINATION_STDERR);
2147
2148         /* Write to CSV log if enabled */
2149         if (Log_destination & LOG_DESTINATION_CSVLOG)
2150         {
2151                 if (redirection_done || am_syslogger)
2152                 {
2153                         /*
2154                          * send CSV data if it's safe to do so (syslogger doesn't need the
2155                          * pipe). First get back the space in the message buffer.
2156                          */
2157                         pfree(buf.data);
2158                         write_csvlog(edata);
2159                 }
2160                 else
2161                 {
2162                         const char *msg = _("Not safe to send CSV data\n");
2163
2164                         write(fileno(stderr), msg, strlen(msg));
2165                         if (!(Log_destination & LOG_DESTINATION_STDERR) &&
2166                                 whereToSendOutput != DestDebug)
2167                         {
2168                                 /* write message to stderr unless we just sent it above */
2169                                 write(fileno(stderr), buf.data, buf.len);
2170                         }
2171                         pfree(buf.data);
2172                 }
2173         }
2174         else
2175         {
2176                 pfree(buf.data);
2177         }
2178 }
2179
2180 /*
2181  * Send data to the syslogger using the chunked protocol
2182  */
2183 static void
2184 write_pipe_chunks(char *data, int len, int dest)
2185 {
2186         PipeProtoChunk p;
2187
2188         int                     fd = fileno(stderr);
2189
2190         Assert(len > 0);
2191
2192         p.proto.nuls[0] = p.proto.nuls[1] = '\0';
2193         p.proto.pid = MyProcPid;
2194
2195         /* write all but the last chunk */
2196         while (len > PIPE_MAX_PAYLOAD)
2197         {
2198                 p.proto.is_last = (dest == LOG_DESTINATION_CSVLOG ? 'F' : 'f');
2199                 p.proto.len = PIPE_MAX_PAYLOAD;
2200                 memcpy(p.proto.data, data, PIPE_MAX_PAYLOAD);
2201                 write(fd, &p, PIPE_HEADER_SIZE + PIPE_MAX_PAYLOAD);
2202                 data += PIPE_MAX_PAYLOAD;
2203                 len -= PIPE_MAX_PAYLOAD;
2204         }
2205
2206         /* write the last chunk */
2207         p.proto.is_last = (dest == LOG_DESTINATION_CSVLOG ? 'T' : 't');
2208         p.proto.len = len;
2209         memcpy(p.proto.data, data, len);
2210         write(fd, &p, PIPE_HEADER_SIZE + len);
2211 }
2212
2213
2214 /*
2215  * Append a text string to the error report being built for the client.
2216  *
2217  * This is ordinarily identical to pq_sendstring(), but if we are in
2218  * error recursion trouble we skip encoding conversion, because of the
2219  * possibility that the problem is a failure in the encoding conversion
2220  * subsystem itself.  Code elsewhere should ensure that the passed-in
2221  * strings will be plain 7-bit ASCII, and thus not in need of conversion,
2222  * in such cases.  (In particular, we disable localization of error messages
2223  * to help ensure that's true.)
2224  */
2225 static void
2226 err_sendstring(StringInfo buf, const char *str)
2227 {
2228         if (in_error_recursion_trouble())
2229                 pq_send_ascii_string(buf, str);
2230         else
2231                 pq_sendstring(buf, str);
2232 }
2233
2234 /*
2235  * Write error report to client
2236  */
2237 static void
2238 send_message_to_frontend(ErrorData *edata)
2239 {
2240         StringInfoData msgbuf;
2241
2242         /* 'N' (Notice) is for nonfatal conditions, 'E' is for errors */
2243         pq_beginmessage(&msgbuf, (edata->elevel < ERROR) ? 'N' : 'E');
2244
2245         if (PG_PROTOCOL_MAJOR(FrontendProtocol) >= 3)
2246         {
2247                 /* New style with separate fields */
2248                 char            tbuf[12];
2249                 int                     ssval;
2250                 int                     i;
2251
2252                 pq_sendbyte(&msgbuf, PG_DIAG_SEVERITY);
2253                 err_sendstring(&msgbuf, error_severity(edata->elevel));
2254
2255                 /* unpack MAKE_SQLSTATE code */
2256                 ssval = edata->sqlerrcode;
2257                 for (i = 0; i < 5; i++)
2258                 {
2259                         tbuf[i] = PGUNSIXBIT(ssval);
2260                         ssval >>= 6;
2261                 }
2262                 tbuf[i] = '\0';
2263
2264                 pq_sendbyte(&msgbuf, PG_DIAG_SQLSTATE);
2265                 err_sendstring(&msgbuf, tbuf);
2266
2267                 /* M field is required per protocol, so always send something */
2268                 pq_sendbyte(&msgbuf, PG_DIAG_MESSAGE_PRIMARY);
2269                 if (edata->message)
2270                         err_sendstring(&msgbuf, edata->message);
2271                 else
2272                         err_sendstring(&msgbuf, _("missing error text"));
2273
2274                 if (edata->detail)
2275                 {
2276                         pq_sendbyte(&msgbuf, PG_DIAG_MESSAGE_DETAIL);
2277                         err_sendstring(&msgbuf, edata->detail);
2278                 }
2279
2280                 /* detail_log is intentionally not used here */
2281
2282                 if (edata->hint)
2283                 {
2284                         pq_sendbyte(&msgbuf, PG_DIAG_MESSAGE_HINT);
2285                         err_sendstring(&msgbuf, edata->hint);
2286                 }
2287
2288                 if (edata->context)
2289                 {
2290                         pq_sendbyte(&msgbuf, PG_DIAG_CONTEXT);
2291                         err_sendstring(&msgbuf, edata->context);
2292                 }
2293
2294                 if (edata->cursorpos > 0)
2295                 {
2296                         snprintf(tbuf, sizeof(tbuf), "%d", edata->cursorpos);
2297                         pq_sendbyte(&msgbuf, PG_DIAG_STATEMENT_POSITION);
2298                         err_sendstring(&msgbuf, tbuf);
2299                 }
2300
2301                 if (edata->internalpos > 0)
2302                 {
2303                         snprintf(tbuf, sizeof(tbuf), "%d", edata->internalpos);
2304                         pq_sendbyte(&msgbuf, PG_DIAG_INTERNAL_POSITION);
2305                         err_sendstring(&msgbuf, tbuf);
2306                 }
2307
2308                 if (edata->internalquery)
2309                 {
2310                         pq_sendbyte(&msgbuf, PG_DIAG_INTERNAL_QUERY);
2311                         err_sendstring(&msgbuf, edata->internalquery);
2312                 }
2313
2314                 if (edata->filename)
2315                 {
2316                         pq_sendbyte(&msgbuf, PG_DIAG_SOURCE_FILE);
2317                         err_sendstring(&msgbuf, edata->filename);
2318                 }
2319
2320                 if (edata->lineno > 0)
2321                 {
2322                         snprintf(tbuf, sizeof(tbuf), "%d", edata->lineno);
2323                         pq_sendbyte(&msgbuf, PG_DIAG_SOURCE_LINE);
2324                         err_sendstring(&msgbuf, tbuf);
2325                 }
2326
2327                 if (edata->funcname)
2328                 {
2329                         pq_sendbyte(&msgbuf, PG_DIAG_SOURCE_FUNCTION);
2330                         err_sendstring(&msgbuf, edata->funcname);
2331                 }
2332
2333                 pq_sendbyte(&msgbuf, '\0');             /* terminator */
2334         }
2335         else
2336         {
2337                 /* Old style --- gin up a backwards-compatible message */
2338                 StringInfoData buf;
2339
2340                 initStringInfo(&buf);
2341
2342                 appendStringInfo(&buf, "%s:  ", error_severity(edata->elevel));
2343
2344                 if (edata->show_funcname && edata->funcname)
2345                         appendStringInfo(&buf, "%s: ", edata->funcname);
2346
2347                 if (edata->message)
2348                         appendStringInfoString(&buf, edata->message);
2349                 else
2350                         appendStringInfoString(&buf, _("missing error text"));
2351
2352                 if (edata->cursorpos > 0)
2353                         appendStringInfo(&buf, _(" at character %d"),
2354                                                          edata->cursorpos);
2355                 else if (edata->internalpos > 0)
2356                         appendStringInfo(&buf, _(" at character %d"),
2357                                                          edata->internalpos);
2358
2359                 appendStringInfoChar(&buf, '\n');
2360
2361                 err_sendstring(&msgbuf, buf.data);
2362
2363                 pfree(buf.data);
2364         }
2365
2366         pq_endmessage(&msgbuf);
2367
2368         /*
2369          * This flush is normally not necessary, since postgres.c will flush out
2370          * waiting data when control returns to the main loop. But it seems best
2371          * to leave it here, so that the client has some clue what happened if the
2372          * backend dies before getting back to the main loop ... error/notice
2373          * messages should not be a performance-critical path anyway, so an extra
2374          * flush won't hurt much ...
2375          */
2376         pq_flush();
2377 }
2378
2379
2380 /*
2381  * Support routines for formatting error messages.
2382  */
2383
2384
2385 /*
2386  * expand_fmt_string --- process special format codes in a format string
2387  *
2388  * We must replace %m with the appropriate strerror string, since vsnprintf
2389  * won't know what to do with it.
2390  *
2391  * The result is a palloc'd string.
2392  */
2393 static char *
2394 expand_fmt_string(const char *fmt, ErrorData *edata)
2395 {
2396         StringInfoData buf;
2397         const char *cp;
2398
2399         initStringInfo(&buf);
2400
2401         for (cp = fmt; *cp; cp++)
2402         {
2403                 if (cp[0] == '%' && cp[1] != '\0')
2404                 {
2405                         cp++;
2406                         if (*cp == 'm')
2407                         {
2408                                 /*
2409                                  * Replace %m by system error string.  If there are any %'s in
2410                                  * the string, we'd better double them so that vsnprintf won't
2411                                  * misinterpret.
2412                                  */
2413                                 const char *cp2;
2414
2415                                 cp2 = useful_strerror(edata->saved_errno);
2416                                 for (; *cp2; cp2++)
2417                                 {
2418                                         if (*cp2 == '%')
2419                                                 appendStringInfoCharMacro(&buf, '%');
2420                                         appendStringInfoCharMacro(&buf, *cp2);
2421                                 }
2422                         }
2423                         else
2424                         {
2425                                 /* copy % and next char --- this avoids trouble with %%m */
2426                                 appendStringInfoCharMacro(&buf, '%');
2427                                 appendStringInfoCharMacro(&buf, *cp);
2428                         }
2429                 }
2430                 else
2431                         appendStringInfoCharMacro(&buf, *cp);
2432         }
2433
2434         return buf.data;
2435 }
2436
2437
2438 /*
2439  * A slightly cleaned-up version of strerror()
2440  */
2441 static const char *
2442 useful_strerror(int errnum)
2443 {
2444         /* this buffer is only used if errno has a bogus value */
2445         static char errorstr_buf[48];
2446         const char *str;
2447
2448 #ifdef WIN32
2449         /* Winsock error code range, per WinError.h */
2450         if (errnum >= 10000 && errnum <= 11999)
2451                 return pgwin32_socket_strerror(errnum);
2452 #endif
2453         str = strerror(errnum);
2454
2455         /*
2456          * Some strerror()s return an empty string for out-of-range errno. This is
2457          * ANSI C spec compliant, but not exactly useful.
2458          */
2459         if (str == NULL || *str == '\0')
2460         {
2461                 snprintf(errorstr_buf, sizeof(errorstr_buf),
2462                 /*------
2463                   translator: This string will be truncated at 47
2464                   characters expanded. */
2465                                  _("operating system error %d"), errnum);
2466                 str = errorstr_buf;
2467         }
2468
2469         return str;
2470 }
2471
2472
2473 /*
2474  * error_severity --- get localized string representing elevel
2475  */
2476 static const char *
2477 error_severity(int elevel)
2478 {
2479         const char *prefix;
2480
2481         switch (elevel)
2482         {
2483                 case DEBUG1:
2484                 case DEBUG2:
2485                 case DEBUG3:
2486                 case DEBUG4:
2487                 case DEBUG5:
2488                         prefix = _("DEBUG");
2489                         break;
2490                 case LOG:
2491                 case COMMERROR:
2492                         prefix = _("LOG");
2493                         break;
2494                 case INFO:
2495                         prefix = _("INFO");
2496                         break;
2497                 case NOTICE:
2498                         prefix = _("NOTICE");
2499                         break;
2500                 case WARNING:
2501                         prefix = _("WARNING");
2502                         break;
2503                 case ERROR:
2504                         prefix = _("ERROR");
2505                         break;
2506                 case FATAL:
2507                         prefix = _("FATAL");
2508                         break;
2509                 case PANIC:
2510                         prefix = _("PANIC");
2511                         break;
2512                 default:
2513                         prefix = "???";
2514                         break;
2515         }
2516
2517         return prefix;
2518 }
2519
2520
2521 /*
2522  *      append_with_tabs
2523  *
2524  *      Append the string to the StringInfo buffer, inserting a tab after any
2525  *      newline.
2526  */
2527 static void
2528 append_with_tabs(StringInfo buf, const char *str)
2529 {
2530         char            ch;
2531
2532         while ((ch = *str++) != '\0')
2533         {
2534                 appendStringInfoCharMacro(buf, ch);
2535                 if (ch == '\n')
2536                         appendStringInfoCharMacro(buf, '\t');
2537         }
2538 }
2539
2540
2541 /*
2542  * Write errors to stderr (or by equal means when stderr is
2543  * not available). Used before ereport/elog can be used
2544  * safely (memory context, GUC load etc)
2545  */
2546 void
2547 write_stderr(const char *fmt,...)
2548 {
2549         va_list         ap;
2550
2551         fmt = _(fmt);
2552
2553         va_start(ap, fmt);
2554 #ifndef WIN32
2555         /* On Unix, we just fprintf to stderr */
2556         vfprintf(stderr, fmt, ap);
2557         fflush(stderr);
2558 #else
2559
2560         /*
2561          * On Win32, we print to stderr if running on a console, or write to
2562          * eventlog if running as a service
2563          */
2564         if (pgwin32_is_service())       /* Running as a service */
2565         {
2566                 char            errbuf[2048];           /* Arbitrary size? */
2567
2568                 vsnprintf(errbuf, sizeof(errbuf), fmt, ap);
2569
2570                 write_eventlog(ERROR, errbuf);
2571         }
2572         else
2573         {
2574                 /* Not running as service, write to stderr */
2575                 vfprintf(stderr, fmt, ap);
2576                 fflush(stderr);
2577         }
2578 #endif
2579         va_end(ap);
2580 }
2581
2582
2583 /*
2584  * is_log_level_output -- is elevel logically >= log_min_level?
2585  *
2586  * We use this for tests that should consider LOG to sort out-of-order,
2587  * between ERROR and FATAL.  Generally this is the right thing for testing
2588  * whether a message should go to the postmaster log, whereas a simple >=
2589  * test is correct for testing whether the message should go to the client.
2590  */
2591 static bool
2592 is_log_level_output(int elevel, int log_min_level)
2593 {
2594         if (elevel == LOG || elevel == COMMERROR)
2595         {
2596                 if (log_min_level == LOG || log_min_level <= ERROR)
2597                         return true;
2598         }
2599         else if (log_min_level == LOG)
2600         {
2601                 /* elevel != LOG */
2602                 if (elevel >= FATAL)
2603                         return true;
2604         }
2605         /* Neither is LOG */
2606         else if (elevel >= log_min_level)
2607                 return true;
2608
2609         return false;
2610 }