]> granicus.if.org Git - postgresql/blob - src/backend/utils/error/elog.c
Tweak elog.c's logic for promoting errors into more severe errors.
[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-2004, 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.149 2004/09/05 02:01:41 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 "libpq/libpq.h"
61 #include "libpq/pqformat.h"
62 #include "mb/pg_wchar.h"
63 #include "miscadmin.h"
64 #include "postmaster/postmaster.h"
65 #include "postmaster/syslogger.h"
66 #include "storage/ipc.h"
67 #include "tcop/tcopprot.h"
68 #include "utils/memutils.h"
69 #include "utils/guc.h"
70
71
72 /* Global variables */
73 ErrorContextCallback *error_context_stack = NULL;
74
75 sigjmp_buf *PG_exception_stack = NULL;
76
77 /* GUC parameters */
78 PGErrorVerbosity Log_error_verbosity = PGERROR_VERBOSE;
79 char       *Log_line_prefix = NULL;             /* format for extra log line info */
80 int                     Log_destination = LOG_DESTINATION_STDERR;
81
82 #ifdef HAVE_SYSLOG
83 char       *Syslog_facility;    /* openlog() parameters */
84 char       *Syslog_ident;
85
86 static void write_syslog(int level, const char *line);
87 #endif
88 #ifdef WIN32
89 static void write_eventlog(int level, const char *line);
90 #endif
91
92 /* We provide a small stack of ErrorData records for re-entrant cases */
93 #define ERRORDATA_STACK_SIZE  5
94
95 static ErrorData errordata[ERRORDATA_STACK_SIZE];
96
97 static int      errordata_stack_depth = -1; /* index of topmost active frame */
98
99 static int      recursion_depth = 0;    /* to detect actual recursion */
100
101
102 /* Macro for checking errordata_stack_depth is reasonable */
103 #define CHECK_STACK_DEPTH() \
104         do { \
105                 if (errordata_stack_depth < 0) \
106                 { \
107                         errordata_stack_depth = -1; \
108                         ereport(ERROR, (errmsg_internal("errstart was not called"))); \
109                 } \
110         } while (0)
111
112
113 static void log_line_prefix(StringInfo buf);
114 static void send_message_to_server_log(ErrorData *edata);
115 static void send_message_to_frontend(ErrorData *edata);
116 static char *expand_fmt_string(const char *fmt, ErrorData *edata);
117 static const char *useful_strerror(int errnum);
118 static const char *error_severity(int elevel);
119 static void append_with_tabs(StringInfo buf, const char *str);
120
121
122 /*
123  * errstart --- begin an error-reporting cycle
124  *
125  * Create a stack entry and store the given parameters in it.  Subsequently,
126  * errmsg() and perhaps other routines will be called to further populate
127  * the stack entry.  Finally, errfinish() will be called to actually process
128  * the error report.
129  *
130  * Returns TRUE in normal case.  Returns FALSE to short-circuit the error
131  * report (if it's a warning or lower and not to be reported anywhere).
132  */
133 bool
134 errstart(int elevel, const char *filename, int lineno,
135                  const char *funcname)
136 {
137         ErrorData  *edata;
138         bool            output_to_server = false;
139         bool            output_to_client = false;
140         int                     i;
141
142         /*
143          * Check some cases in which we want to promote an error into a more
144          * severe error.  None of this logic applies for non-error messages.
145          */
146         if (elevel >= ERROR)
147         {
148                 /*
149                  * If we are inside a critical section, all errors become PANIC
150                  * errors.      See miscadmin.h.
151                  */
152                 if (CritSectionCount > 0)
153                         elevel = PANIC;
154
155                 /*
156                  * Check reasons for treating ERROR as FATAL:
157                  *
158                  * 1. we have no handler to pass the error to (implies we are in the
159                  * postmaster or in backend startup).
160                  *
161                  * 2. ExitOnAnyError mode switch is set (initdb uses this).
162                  *
163                  * 3. the error occurred after proc_exit has begun to run.      (It's
164                  * proc_exit's responsibility to see that this doesn't turn into
165                  * infinite recursion!)
166                  */
167                 if (elevel == ERROR)
168                 {
169                         if (PG_exception_stack == NULL ||
170                                 ExitOnAnyError ||
171                                 proc_exit_inprogress)
172                                 elevel = FATAL;
173                 }
174
175                 /*
176                  * If the error level is ERROR or more, errfinish is not going to
177                  * return to caller; therefore, if there is any stacked error already
178                  * in progress it will be lost.  This is more or less okay, except we
179                  * do not want to have a FATAL or PANIC error downgraded because the
180                  * reporting process was interrupted by a lower-grade error.  So check
181                  * the stack and make sure we panic if panic is warranted.
182                  */
183                 for (i = 0; i <= errordata_stack_depth; i++)
184                         elevel = Max(elevel, errordata[i].elevel);
185         }
186
187         /*
188          * Now decide whether we need to process this report at all; if it's
189          * warning or less and not enabled for logging, just return FALSE
190          * without starting up any error logging machinery.
191          */
192
193         /* Determine whether message is enabled for server log output */
194         if (IsPostmasterEnvironment)
195         {
196                 /* Complicated because LOG is sorted out-of-order for this purpose */
197                 if (elevel == LOG || elevel == COMMERROR)
198                 {
199                         if (log_min_messages == LOG)
200                                 output_to_server = true;
201                         else if (log_min_messages < FATAL)
202                                 output_to_server = true;
203                 }
204                 else
205                 {
206                         /* elevel != LOG */
207                         if (log_min_messages == LOG)
208                         {
209                                 if (elevel >= FATAL)
210                                         output_to_server = true;
211                         }
212                         /* Neither is LOG */
213                         else if (elevel >= log_min_messages)
214                                 output_to_server = true;
215                 }
216         }
217         else
218         {
219                 /* In bootstrap/standalone case, do not sort LOG out-of-order */
220                 output_to_server = (elevel >= log_min_messages);
221         }
222
223         /* Determine whether message is enabled for client output */
224         if (whereToSendOutput == Remote && elevel != COMMERROR)
225         {
226                 /*
227                  * client_min_messages is honored only after we complete the
228                  * authentication handshake.  This is required both for security
229                  * reasons and because many clients can't handle NOTICE messages
230                  * during authentication.
231                  */
232                 if (ClientAuthInProgress)
233                         output_to_client = (elevel >= ERROR);
234                 else
235                         output_to_client = (elevel >= client_min_messages ||
236                                                                 elevel == INFO);
237         }
238
239         /* Skip processing effort if non-error message will not be output */
240         if (elevel < ERROR && !output_to_server && !output_to_client)
241                 return false;
242
243         /*
244          * Okay, crank up a stack entry to store the info in.
245          */
246
247         if (recursion_depth++ > 0 && elevel >= ERROR)
248         {
249                 /*
250                  * Ooops, error during error processing.  Clear ErrorContext as
251                  * discussed at top of file.  We will not return to the original
252                  * error's reporter or handler, so we don't need it.
253                  */
254                 MemoryContextReset(ErrorContext);
255
256                 /*
257                  * If we recurse more than once, the problem might be something
258                  * broken in a context traceback routine.  Abandon them too.
259                  */
260                 if (recursion_depth > 2)
261                         error_context_stack = NULL;
262         }
263         if (++errordata_stack_depth >= ERRORDATA_STACK_SIZE)
264         {
265                 /*
266                  * Wups, stack not big enough.  We treat this as a PANIC condition
267                  * because it suggests an infinite loop of errors during error
268                  * recovery.
269                  */
270                 errordata_stack_depth = -1;             /* make room on stack */
271                 ereport(PANIC, (errmsg_internal("ERRORDATA_STACK_SIZE exceeded")));
272         }
273
274         /* Initialize data for this error frame */
275         edata = &errordata[errordata_stack_depth];
276         MemSet(edata, 0, sizeof(ErrorData));
277         edata->elevel = elevel;
278         edata->output_to_server = output_to_server;
279         edata->output_to_client = output_to_client;
280         edata->filename = filename;
281         edata->lineno = lineno;
282         edata->funcname = funcname;
283         /* Select default errcode based on elevel */
284         if (elevel >= ERROR)
285                 edata->sqlerrcode = ERRCODE_INTERNAL_ERROR;
286         else if (elevel == WARNING)
287                 edata->sqlerrcode = ERRCODE_WARNING;
288         else
289                 edata->sqlerrcode = ERRCODE_SUCCESSFUL_COMPLETION;
290         /* errno is saved here so that error parameter eval can't change it */
291         edata->saved_errno = errno;
292
293         recursion_depth--;
294         return true;
295 }
296
297 /*
298  * errfinish --- end an error-reporting cycle
299  *
300  * Produce the appropriate error report(s) and pop the error stack.
301  *
302  * If elevel is ERROR or worse, control does not return to the caller.
303  * See elog.h for the error level definitions.
304  */
305 void
306 errfinish(int dummy,...)
307 {
308         ErrorData  *edata = &errordata[errordata_stack_depth];
309         int                     elevel = edata->elevel;
310         MemoryContext oldcontext;
311         ErrorContextCallback *econtext;
312
313         recursion_depth++;
314         CHECK_STACK_DEPTH();
315
316         /*
317          * Do processing in ErrorContext, which we hope has enough reserved
318          * space to report an error.
319          */
320         oldcontext = MemoryContextSwitchTo(ErrorContext);
321
322         /*
323          * Call any context callback functions.  Errors occurring in callback
324          * functions will be treated as recursive errors --- this ensures we
325          * will avoid infinite recursion (see errstart).
326          */
327         for (econtext = error_context_stack;
328                  econtext != NULL;
329                  econtext = econtext->previous)
330                 (*econtext->callback) (econtext->arg);
331
332         /*
333          * If ERROR (not more nor less) we pass it off to the current handler.
334          * Printing it and popping the stack is the responsibility of
335          * the handler.
336          */
337         if (elevel == ERROR)
338         {
339                 /*
340                  * We do some minimal cleanup before longjmp'ing so that handlers
341                  * can execute in a reasonably sane state.
342                  */
343
344                 /* This is just in case the error came while waiting for input */
345                 ImmediateInterruptOK = false;
346
347                 /*
348                  * Reset InterruptHoldoffCount in case we ereport'd from
349                  * inside an interrupt holdoff section.  (We assume here that
350                  * no handler will itself be inside a holdoff section.  If
351                  * necessary, such a handler could save and restore
352                  * InterruptHoldoffCount for itself, but this should make life
353                  * easier for most.)
354                  */
355                 InterruptHoldoffCount = 0;
356
357                 CritSectionCount = 0;           /* should be unnecessary, but... */
358
359                 /*
360                  * Note that we leave CurrentMemoryContext set to ErrorContext.
361                  * The handler should reset it to something else soon.
362                  */
363
364                 recursion_depth--;
365                 PG_RE_THROW();
366         }
367
368         /*
369          * If we are doing FATAL or PANIC, abort any old-style COPY OUT in
370          * progress, so that we can report the message before dying.  (Without
371          * this, pq_putmessage will refuse to send the message at all, which
372          * is what we want for NOTICE messages, but not for fatal exits.) This
373          * hack is necessary because of poor design of old-style copy
374          * protocol.  Note we must do this even if client is fool enough to
375          * have set client_min_messages above FATAL, so don't look at
376          * output_to_client.
377          */
378         if (elevel >= FATAL && whereToSendOutput == Remote)
379                 pq_endcopyout(true);
380
381         /* Emit the message to the right places */
382         EmitErrorReport();
383
384         /* Now free up subsidiary data attached to stack entry, and release it */
385         if (edata->message)
386                 pfree(edata->message);
387         if (edata->detail)
388                 pfree(edata->detail);
389         if (edata->hint)
390                 pfree(edata->hint);
391         if (edata->context)
392                 pfree(edata->context);
393         if (edata->internalquery)
394                 pfree(edata->internalquery);
395
396         errordata_stack_depth--;
397
398         /* Exit error-handling context */
399         MemoryContextSwitchTo(oldcontext);
400         recursion_depth--;
401
402         /*
403          * Perform error recovery action as specified by elevel.
404          */
405         if (elevel == FATAL)
406         {
407                 /*
408                  * For a FATAL error, we let proc_exit clean up and exit.
409                  */
410                 ImmediateInterruptOK = false;
411
412                 /*
413                  * If we just reported a startup failure, the client will
414                  * disconnect on receiving it, so don't send any more to the
415                  * client.
416                  */
417                 if (PG_exception_stack == NULL && whereToSendOutput == Remote)
418                         whereToSendOutput = None;
419
420                 /*
421                  * fflush here is just to improve the odds that we get to see the
422                  * error message, in case things are so hosed that proc_exit
423                  * crashes.  Any other code you might be tempted to add here
424                  * should probably be in an on_proc_exit callback instead.
425                  */
426                 fflush(stdout);
427                 fflush(stderr);
428
429                 /*
430                  * If proc_exit is already running, we exit with nonzero exit code
431                  * to indicate that something's pretty wrong.  We also want to
432                  * exit with nonzero exit code if not running under the postmaster
433                  * (for example, if we are being run from the initdb script, we'd
434                  * better return an error status).
435                  */
436                 proc_exit(proc_exit_inprogress || !IsUnderPostmaster);
437         }
438
439         if (elevel >= PANIC)
440         {
441                 /*
442                  * Serious crash time. Postmaster will observe nonzero process
443                  * exit status and kill the other backends too.
444                  *
445                  * XXX: what if we are *in* the postmaster?  abort() won't kill our
446                  * children...
447                  */
448                 ImmediateInterruptOK = false;
449                 fflush(stdout);
450                 fflush(stderr);
451                 abort();
452         }
453
454         /* We reach here if elevel <= WARNING. OK to return to caller. */
455 }
456
457
458 /*
459  * errcode --- add SQLSTATE error code to the current error
460  *
461  * The code is expected to be represented as per MAKE_SQLSTATE().
462  */
463 int
464 errcode(int sqlerrcode)
465 {
466         ErrorData  *edata = &errordata[errordata_stack_depth];
467
468         /* we don't bother incrementing recursion_depth */
469         CHECK_STACK_DEPTH();
470
471         edata->sqlerrcode = sqlerrcode;
472
473         return 0;                                       /* return value does not matter */
474 }
475
476
477 /*
478  * errcode_for_file_access --- add SQLSTATE error code to the current error
479  *
480  * The SQLSTATE code is chosen based on the saved errno value.  We assume
481  * that the failing operation was some type of disk file access.
482  *
483  * NOTE: the primary error message string should generally include %m
484  * when this is used.
485  */
486 int
487 errcode_for_file_access(void)
488 {
489         ErrorData  *edata = &errordata[errordata_stack_depth];
490
491         /* we don't bother incrementing recursion_depth */
492         CHECK_STACK_DEPTH();
493
494         switch (edata->saved_errno)
495         {
496                         /* Permission-denied failures */
497                 case EPERM:                             /* Not super-user */
498                 case EACCES:                    /* Permission denied */
499 #ifdef EROFS
500                 case EROFS:                             /* Read only file system */
501 #endif
502                         edata->sqlerrcode = ERRCODE_INSUFFICIENT_PRIVILEGE;
503                         break;
504
505                         /* File not found */
506                 case ENOENT:                    /* No such file or directory */
507                         edata->sqlerrcode = ERRCODE_UNDEFINED_FILE;
508                         break;
509
510                         /* Duplicate file */
511                 case EEXIST:                    /* File exists */
512                         edata->sqlerrcode = ERRCODE_DUPLICATE_FILE;
513                         break;
514
515                         /* Wrong object type or state */
516                 case ENOTDIR:                   /* Not a directory */
517                 case EISDIR:                    /* Is a directory */
518 #if defined(ENOTEMPTY) && (ENOTEMPTY != EEXIST) /* same code on AIX */
519                 case ENOTEMPTY: /* Directory not empty */
520 #endif
521                         edata->sqlerrcode = ERRCODE_WRONG_OBJECT_TYPE;
522                         break;
523
524                         /* Insufficient resources */
525                 case ENOSPC:                    /* No space left on device */
526                         edata->sqlerrcode = ERRCODE_DISK_FULL;
527                         break;
528
529                 case ENFILE:                    /* File table overflow */
530                 case EMFILE:                    /* Too many open files */
531                         edata->sqlerrcode = ERRCODE_INSUFFICIENT_RESOURCES;
532                         break;
533
534                         /* Hardware failure */
535                 case EIO:                               /* I/O error */
536                         edata->sqlerrcode = ERRCODE_IO_ERROR;
537                         break;
538
539                         /* All else is classified as internal errors */
540                 default:
541                         edata->sqlerrcode = ERRCODE_INTERNAL_ERROR;
542                         break;
543         }
544
545         return 0;                                       /* return value does not matter */
546 }
547
548 /*
549  * errcode_for_socket_access --- add SQLSTATE error code to the current error
550  *
551  * The SQLSTATE code is chosen based on the saved errno value.  We assume
552  * that the failing operation was some type of socket access.
553  *
554  * NOTE: the primary error message string should generally include %m
555  * when this is used.
556  */
557 int
558 errcode_for_socket_access(void)
559 {
560         ErrorData  *edata = &errordata[errordata_stack_depth];
561
562         /* we don't bother incrementing recursion_depth */
563         CHECK_STACK_DEPTH();
564
565         switch (edata->saved_errno)
566         {
567                         /* Loss of connection */
568                 case EPIPE:
569 #ifdef ECONNRESET
570                 case ECONNRESET:
571 #endif
572                         edata->sqlerrcode = ERRCODE_CONNECTION_FAILURE;
573                         break;
574
575                         /* All else is classified as internal errors */
576                 default:
577                         edata->sqlerrcode = ERRCODE_INTERNAL_ERROR;
578                         break;
579         }
580
581         return 0;                                       /* return value does not matter */
582 }
583
584
585 /*
586  * This macro handles expansion of a format string and associated parameters;
587  * it's common code for errmsg(), errdetail(), etc.  Must be called inside
588  * a routine that is declared like "const char *fmt, ..." and has an edata
589  * pointer set up.      The message is assigned to edata->targetfield, or
590  * appended to it if appendval is true.
591  *
592  * Note: we pstrdup the buffer rather than just transferring its storage
593  * to the edata field because the buffer might be considerably larger than
594  * really necessary.
595  */
596 #define EVALUATE_MESSAGE(targetfield, appendval)  \
597         { \
598                 char               *fmtbuf; \
599                 StringInfoData  buf; \
600                 /* Internationalize the error format string */ \
601                 fmt = gettext(fmt); \
602                 /* Expand %m in format string */ \
603                 fmtbuf = expand_fmt_string(fmt, edata); \
604                 initStringInfo(&buf); \
605                 if ((appendval) && edata->targetfield) \
606                         appendStringInfo(&buf, "%s\n", edata->targetfield); \
607                 /* Generate actual output --- have to use appendStringInfoVA */ \
608                 for (;;) \
609                 { \
610                         va_list         args; \
611                         bool            success; \
612                         va_start(args, fmt); \
613                         success = appendStringInfoVA(&buf, fmtbuf, args); \
614                         va_end(args); \
615                         if (success) \
616                                 break; \
617                         enlargeStringInfo(&buf, buf.maxlen); \
618                 } \
619                 /* Done with expanded fmt */ \
620                 pfree(fmtbuf); \
621                 /* Save the completed message into the stack item */ \
622                 if (edata->targetfield) \
623                         pfree(edata->targetfield); \
624                 edata->targetfield = pstrdup(buf.data); \
625                 pfree(buf.data); \
626         }
627
628
629 /*
630  * errmsg --- add a primary error message text to the current error
631  *
632  * In addition to the usual %-escapes recognized by printf, "%m" in
633  * fmt is replaced by the error message for the caller's value of errno.
634  *
635  * Note: no newline is needed at the end of the fmt string, since
636  * ereport will provide one for the output methods that need it.
637  */
638 int
639 errmsg(const char *fmt,...)
640 {
641         ErrorData  *edata = &errordata[errordata_stack_depth];
642         MemoryContext oldcontext;
643
644         recursion_depth++;
645         CHECK_STACK_DEPTH();
646         oldcontext = MemoryContextSwitchTo(ErrorContext);
647
648         EVALUATE_MESSAGE(message, false);
649
650         MemoryContextSwitchTo(oldcontext);
651         recursion_depth--;
652         return 0;                                       /* return value does not matter */
653 }
654
655
656 /*
657  * errmsg_internal --- add a primary error message text to the current error
658  *
659  * This is exactly like errmsg() except that strings passed to errmsg_internal
660  * are customarily left out of the internationalization message dictionary.
661  * This should be used for "can't happen" cases that are probably not worth
662  * spending translation effort on.
663  */
664 int
665 errmsg_internal(const char *fmt,...)
666 {
667         ErrorData  *edata = &errordata[errordata_stack_depth];
668         MemoryContext oldcontext;
669
670         recursion_depth++;
671         CHECK_STACK_DEPTH();
672         oldcontext = MemoryContextSwitchTo(ErrorContext);
673
674         EVALUATE_MESSAGE(message, false);
675
676         MemoryContextSwitchTo(oldcontext);
677         recursion_depth--;
678         return 0;                                       /* return value does not matter */
679 }
680
681
682 /*
683  * errdetail --- add a detail error message text to the current error
684  */
685 int
686 errdetail(const char *fmt,...)
687 {
688         ErrorData  *edata = &errordata[errordata_stack_depth];
689         MemoryContext oldcontext;
690
691         recursion_depth++;
692         CHECK_STACK_DEPTH();
693         oldcontext = MemoryContextSwitchTo(ErrorContext);
694
695         EVALUATE_MESSAGE(detail, false);
696
697         MemoryContextSwitchTo(oldcontext);
698         recursion_depth--;
699         return 0;                                       /* return value does not matter */
700 }
701
702
703 /*
704  * errhint --- add a hint error message text to the current error
705  */
706 int
707 errhint(const char *fmt,...)
708 {
709         ErrorData  *edata = &errordata[errordata_stack_depth];
710         MemoryContext oldcontext;
711
712         recursion_depth++;
713         CHECK_STACK_DEPTH();
714         oldcontext = MemoryContextSwitchTo(ErrorContext);
715
716         EVALUATE_MESSAGE(hint, false);
717
718         MemoryContextSwitchTo(oldcontext);
719         recursion_depth--;
720         return 0;                                       /* return value does not matter */
721 }
722
723
724 /*
725  * errcontext --- add a context error message text to the current error
726  *
727  * Unlike other cases, multiple calls are allowed to build up a stack of
728  * context information.  We assume earlier calls represent more-closely-nested
729  * states.
730  */
731 int
732 errcontext(const char *fmt,...)
733 {
734         ErrorData  *edata = &errordata[errordata_stack_depth];
735         MemoryContext oldcontext;
736
737         recursion_depth++;
738         CHECK_STACK_DEPTH();
739         oldcontext = MemoryContextSwitchTo(ErrorContext);
740
741         EVALUATE_MESSAGE(context, true);
742
743         MemoryContextSwitchTo(oldcontext);
744         recursion_depth--;
745         return 0;                                       /* return value does not matter */
746 }
747
748
749 /*
750  * errfunction --- add reporting function name to the current error
751  *
752  * This is used when backwards compatibility demands that the function
753  * name appear in messages sent to old-protocol clients.  Note that the
754  * passed string is expected to be a non-freeable constant string.
755  */
756 int
757 errfunction(const char *funcname)
758 {
759         ErrorData  *edata = &errordata[errordata_stack_depth];
760
761         /* we don't bother incrementing recursion_depth */
762         CHECK_STACK_DEPTH();
763
764         edata->funcname = funcname;
765         edata->show_funcname = true;
766
767         return 0;                                       /* return value does not matter */
768 }
769
770 /*
771  * errposition --- add cursor position to the current error
772  */
773 int
774 errposition(int cursorpos)
775 {
776         ErrorData  *edata = &errordata[errordata_stack_depth];
777
778         /* we don't bother incrementing recursion_depth */
779         CHECK_STACK_DEPTH();
780
781         edata->cursorpos = cursorpos;
782
783         return 0;                                       /* return value does not matter */
784 }
785
786 /*
787  * internalerrposition --- add internal cursor position to the current error
788  */
789 int
790 internalerrposition(int cursorpos)
791 {
792         ErrorData  *edata = &errordata[errordata_stack_depth];
793
794         /* we don't bother incrementing recursion_depth */
795         CHECK_STACK_DEPTH();
796
797         edata->internalpos = cursorpos;
798
799         return 0;                                       /* return value does not matter */
800 }
801
802 /*
803  * internalerrquery --- add internal query text to the current error
804  *
805  * Can also pass NULL to drop the internal query text entry.  This case
806  * is intended for use in error callback subroutines that are editorializing
807  * on the layout of the error report.
808  */
809 int
810 internalerrquery(const char *query)
811 {
812         ErrorData  *edata = &errordata[errordata_stack_depth];
813
814         /* we don't bother incrementing recursion_depth */
815         CHECK_STACK_DEPTH();
816
817         if (edata->internalquery)
818         {
819                 pfree(edata->internalquery);
820                 edata->internalquery = NULL;
821         }
822
823         if (query)
824                 edata->internalquery = MemoryContextStrdup(ErrorContext, query);
825
826         return 0;                                       /* return value does not matter */
827 }
828
829 /*
830  * geterrposition --- return the currently set error position (0 if none)
831  *
832  * This is only intended for use in error callback subroutines, since there
833  * is no other place outside elog.c where the concept is meaningful.
834  */
835 int
836 geterrposition(void)
837 {
838         ErrorData  *edata = &errordata[errordata_stack_depth];
839
840         /* we don't bother incrementing recursion_depth */
841         CHECK_STACK_DEPTH();
842
843         return edata->cursorpos;
844 }
845
846 /*
847  * getinternalerrposition --- same for internal error position
848  *
849  * This is only intended for use in error callback subroutines, since there
850  * is no other place outside elog.c where the concept is meaningful.
851  */
852 int
853 getinternalerrposition(void)
854 {
855         ErrorData  *edata = &errordata[errordata_stack_depth];
856
857         /* we don't bother incrementing recursion_depth */
858         CHECK_STACK_DEPTH();
859
860         return edata->internalpos;
861 }
862
863
864 /*
865  * elog_finish --- finish up for old-style API
866  *
867  * The elog() macro already called errstart, but with ERROR rather than
868  * the true elevel.
869  */
870 void
871 elog_finish(int elevel, const char *fmt,...)
872 {
873         ErrorData  *edata = &errordata[errordata_stack_depth];
874         MemoryContext oldcontext;
875
876         CHECK_STACK_DEPTH();
877
878         /*
879          * We need to redo errstart() because the elog macro had to call it
880          * with bogus elevel.
881          */
882         errordata_stack_depth--;
883         errno = edata->saved_errno;
884         if (!errstart(elevel, edata->filename, edata->lineno, edata->funcname))
885                 return;                                 /* nothing to do */
886
887         /*
888          * Format error message just like errmsg().
889          */
890         recursion_depth++;
891         oldcontext = MemoryContextSwitchTo(ErrorContext);
892
893         EVALUATE_MESSAGE(message, false);
894
895         MemoryContextSwitchTo(oldcontext);
896         recursion_depth--;
897
898         /*
899          * And let errfinish() finish up.
900          */
901         errfinish(0);
902 }
903
904 /*
905  * Actual output of the top-of-stack error message
906  *
907  * In the ereport(ERROR) case this is called from PostgresMain (or not at all,
908  * if the error is caught by somebody).  For all other severity levels this
909  * is called by errfinish.
910  */
911 void
912 EmitErrorReport(void)
913 {
914         ErrorData  *edata = &errordata[errordata_stack_depth];
915         MemoryContext oldcontext;
916
917         recursion_depth++;
918         CHECK_STACK_DEPTH();
919         oldcontext = MemoryContextSwitchTo(ErrorContext);
920
921         /* Send to server log, if enabled */
922         if (edata->output_to_server)
923                 send_message_to_server_log(edata);
924
925         /* Send to client, if enabled */
926         if (edata->output_to_client)
927                 send_message_to_frontend(edata);
928
929         MemoryContextSwitchTo(oldcontext);
930         recursion_depth--;
931 }
932
933 /*
934  * CopyErrorData --- obtain a copy of the topmost error stack entry
935  *
936  * This is only for use in error handler code.  The data is copied into the
937  * current memory context, so callers should always switch away from
938  * ErrorContext first; otherwise it will be lost when FlushErrorState is done.
939  */
940 ErrorData *
941 CopyErrorData(void)
942 {
943         ErrorData  *edata = &errordata[errordata_stack_depth];
944         ErrorData  *newedata;
945
946         /*
947          * we don't increment recursion_depth because out-of-memory here does
948          * not indicate a problem within the error subsystem.
949          */
950         CHECK_STACK_DEPTH();
951
952         Assert(CurrentMemoryContext != ErrorContext);
953
954         /* Copy the struct itself */
955         newedata = (ErrorData *) palloc(sizeof(ErrorData));
956         memcpy(newedata, edata, sizeof(ErrorData));
957
958         /* Make copies of separately-allocated fields */
959         if (newedata->message)
960                 newedata->message = pstrdup(newedata->message);
961         if (newedata->detail)
962                 newedata->detail = pstrdup(newedata->detail);
963         if (newedata->hint)
964                 newedata->hint = pstrdup(newedata->hint);
965         if (newedata->context)
966                 newedata->context = pstrdup(newedata->context);
967         if (newedata->internalquery)
968                 newedata->internalquery = pstrdup(newedata->internalquery);
969
970         return newedata;
971 }
972
973 /*
974  * FreeErrorData --- free the structure returned by CopyErrorData.
975  *
976  * Error handlers should use this in preference to assuming they know all
977  * the separately-allocated fields.
978  */
979 void
980 FreeErrorData(ErrorData *edata)
981 {
982         if (edata->message)
983                 pfree(edata->message);
984         if (edata->detail)
985                 pfree(edata->detail);
986         if (edata->hint)
987                 pfree(edata->hint);
988         if (edata->context)
989                 pfree(edata->context);
990         if (edata->internalquery)
991                 pfree(edata->internalquery);
992         pfree(edata);
993 }
994
995 /*
996  * FlushErrorState --- flush the error state after error recovery
997  *
998  * This should be called by an error handler after it's done processing
999  * the error; or as soon as it's done CopyErrorData, if it intends to
1000  * do stuff that is likely to provoke another error.  You are not "out" of
1001  * the error subsystem until you have done this.
1002  */
1003 void
1004 FlushErrorState(void)
1005 {
1006         /*
1007          * Reset stack to empty.  The only case where it would be more than
1008          * one deep is if we serviced an error that interrupted construction
1009          * of another message.  We assume control escaped out of that message
1010          * construction and won't ever go back.
1011          */
1012         errordata_stack_depth = -1;
1013         recursion_depth = 0;
1014         /* Delete all data in ErrorContext */
1015         MemoryContextResetAndDeleteChildren(ErrorContext);
1016 }
1017
1018 /*
1019  * ReThrowError --- re-throw a previously copied error
1020  *
1021  * A handler can do CopyErrorData/FlushErrorState to get out of the error
1022  * subsystem, then do some processing, and finally ReThrowError to re-throw
1023  * the original error.  This is slower than just PG_RE_THROW() but should
1024  * be used if the "some processing" is likely to incur another error.
1025  */
1026 void
1027 ReThrowError(ErrorData *edata)
1028 {
1029         ErrorData  *newedata;
1030
1031         Assert(edata->elevel == ERROR);
1032
1033         /* Push the data back into the error context */
1034         recursion_depth++;
1035         MemoryContextSwitchTo(ErrorContext);
1036
1037         if (++errordata_stack_depth >= ERRORDATA_STACK_SIZE)
1038         {
1039                 /*
1040                  * Wups, stack not big enough.  We treat this as a PANIC condition
1041                  * because it suggests an infinite loop of errors during error
1042                  * recovery.
1043                  */
1044                 errordata_stack_depth = -1;             /* make room on stack */
1045                 ereport(PANIC, (errmsg_internal("ERRORDATA_STACK_SIZE exceeded")));
1046         }
1047
1048         newedata = &errordata[errordata_stack_depth];
1049         memcpy(newedata, edata, sizeof(ErrorData));
1050
1051         /* Make copies of separately-allocated fields */
1052         if (newedata->message)
1053                 newedata->message = pstrdup(newedata->message);
1054         if (newedata->detail)
1055                 newedata->detail = pstrdup(newedata->detail);
1056         if (newedata->hint)
1057                 newedata->hint = pstrdup(newedata->hint);
1058         if (newedata->context)
1059                 newedata->context = pstrdup(newedata->context);
1060         if (newedata->internalquery)
1061                 newedata->internalquery = pstrdup(newedata->internalquery);
1062
1063         recursion_depth--;
1064         PG_RE_THROW();
1065 }
1066
1067 /*
1068  * Initialization of error output file
1069  */
1070 void
1071 DebugFileOpen(void)
1072 {
1073         int                     fd,
1074                                 istty;
1075
1076         if (OutputFileName[0])
1077         {
1078                 /*
1079                  * A debug-output file name was given.
1080                  *
1081                  * Make sure we can write the file, and find out if it's a tty.
1082                  */
1083                 if ((fd = open(OutputFileName, O_CREAT | O_APPEND | O_WRONLY,
1084                                            0666)) < 0)
1085                         ereport(FATAL,
1086                                         (errcode_for_file_access(),
1087                           errmsg("could not open file \"%s\": %m", OutputFileName)));
1088                 istty = isatty(fd);
1089                 close(fd);
1090
1091                 /*
1092                  * Redirect our stderr to the debug output file.
1093                  */
1094                 if (!freopen(OutputFileName, "a", stderr))
1095                         ereport(FATAL,
1096                                         (errcode_for_file_access(),
1097                                          errmsg("could not reopen file \"%s\" as stderr: %m",
1098                                                         OutputFileName)));
1099
1100                 /*
1101                  * If the file is a tty and we're running under the postmaster,
1102                  * try to send stdout there as well (if it isn't a tty then stderr
1103                  * will block out stdout, so we may as well let stdout go wherever
1104                  * it was going before).
1105                  */
1106                 if (istty && IsUnderPostmaster)
1107                         if (!freopen(OutputFileName, "a", stdout))
1108                                 ereport(FATAL,
1109                                                 (errcode_for_file_access(),
1110                                          errmsg("could not reopen file \"%s\" as stdout: %m",
1111                                                         OutputFileName)));
1112         }
1113 }
1114
1115
1116
1117 #ifdef HAVE_SYSLOG
1118
1119 #ifndef PG_SYSLOG_LIMIT
1120 #define PG_SYSLOG_LIMIT 128
1121 #endif
1122
1123 /*
1124  * Write a message line to syslog if the syslog option is set.
1125  *
1126  * Our problem here is that many syslog implementations don't handle
1127  * long messages in an acceptable manner. While this function doesn't
1128  * help that fact, it does work around by splitting up messages into
1129  * smaller pieces.
1130  */
1131 static void
1132 write_syslog(int level, const char *line)
1133 {
1134         static bool openlog_done = false;
1135         static unsigned long seq = 0;
1136         static int      syslog_fac = LOG_LOCAL0;
1137
1138         int                     len = strlen(line);
1139
1140         if (!openlog_done)
1141         {
1142                 if (pg_strcasecmp(Syslog_facility, "LOCAL0") == 0)
1143                         syslog_fac = LOG_LOCAL0;
1144                 if (pg_strcasecmp(Syslog_facility, "LOCAL1") == 0)
1145                         syslog_fac = LOG_LOCAL1;
1146                 if (pg_strcasecmp(Syslog_facility, "LOCAL2") == 0)
1147                         syslog_fac = LOG_LOCAL2;
1148                 if (pg_strcasecmp(Syslog_facility, "LOCAL3") == 0)
1149                         syslog_fac = LOG_LOCAL3;
1150                 if (pg_strcasecmp(Syslog_facility, "LOCAL4") == 0)
1151                         syslog_fac = LOG_LOCAL4;
1152                 if (pg_strcasecmp(Syslog_facility, "LOCAL5") == 0)
1153                         syslog_fac = LOG_LOCAL5;
1154                 if (pg_strcasecmp(Syslog_facility, "LOCAL6") == 0)
1155                         syslog_fac = LOG_LOCAL6;
1156                 if (pg_strcasecmp(Syslog_facility, "LOCAL7") == 0)
1157                         syslog_fac = LOG_LOCAL7;
1158                 openlog(Syslog_ident, LOG_PID | LOG_NDELAY | LOG_NOWAIT, syslog_fac);
1159                 openlog_done = true;
1160         }
1161
1162         /*
1163          * We add a sequence number to each log message to suppress "same"
1164          * messages.
1165          */
1166         seq++;
1167
1168         /* divide into multiple syslog() calls if message is too long */
1169         /* or if the message contains embedded NewLine(s) '\n' */
1170         if (len > PG_SYSLOG_LIMIT || strchr(line, '\n') != NULL)
1171         {
1172                 int                     chunk_nr = 0;
1173
1174                 while (len > 0)
1175                 {
1176                         char            buf[PG_SYSLOG_LIMIT + 1];
1177                         int                     buflen;
1178                         int                     i;
1179
1180                         /* if we start at a newline, move ahead one char */
1181                         if (line[0] == '\n')
1182                         {
1183                                 line++;
1184                                 len--;
1185                                 continue;
1186                         }
1187
1188                         strncpy(buf, line, PG_SYSLOG_LIMIT);
1189                         buf[PG_SYSLOG_LIMIT] = '\0';
1190                         if (strchr(buf, '\n') != NULL)
1191                                 *strchr(buf, '\n') = '\0';
1192
1193                         buflen = strlen(buf);
1194
1195                         /* trim to multibyte letter boundary */
1196                         buflen = pg_mbcliplen(buf, buflen, buflen);
1197                         if (buflen <= 0)
1198                                 return;
1199                         buf[buflen] = '\0';
1200
1201                         /* already word boundary? */
1202                         if (!isspace((unsigned char) line[buflen]) &&
1203                                 line[buflen] != '\0')
1204                         {
1205                                 /* try to divide at word boundary */
1206                                 i = buflen - 1;
1207                                 while (i > 0 && !isspace((unsigned char) buf[i]))
1208                                         i--;
1209
1210                                 if (i > 0)              /* else couldn't divide word boundary */
1211                                 {
1212                                         buflen = i;
1213                                         buf[i] = '\0';
1214                                 }
1215                         }
1216
1217                         chunk_nr++;
1218
1219                         syslog(level, "[%lu-%d] %s", seq, chunk_nr, buf);
1220                         line += buflen;
1221                         len -= buflen;
1222                 }
1223         }
1224         else
1225         {
1226                 /* message short enough */
1227                 syslog(level, "[%lu] %s", seq, line);
1228         }
1229 }
1230 #endif   /* HAVE_SYSLOG */
1231 #ifdef WIN32
1232 /*
1233  * Write a message line to the windows event log
1234  */
1235 static void
1236 write_eventlog(int level, const char *line)
1237 {
1238         static HANDLE evtHandle = INVALID_HANDLE_VALUE;
1239
1240         if (evtHandle == INVALID_HANDLE_VALUE)
1241         {
1242                 evtHandle = RegisterEventSource(NULL, "PostgreSQL");
1243                 if (evtHandle == NULL)
1244                 {
1245                         evtHandle = INVALID_HANDLE_VALUE;
1246                         return;
1247                 }
1248         }
1249
1250         ReportEvent(evtHandle,
1251                                 level,
1252                                 0,
1253                                 0,                              /* All events are Id 0 */
1254                                 NULL,
1255                                 1,
1256                                 0,
1257                                 &line,
1258                                 NULL);
1259 }
1260 #endif   /* WIN32 */
1261
1262 /*
1263  * Format tag info for log lines; append to the provided buffer.
1264  */
1265 static void
1266 log_line_prefix(StringInfo buf)
1267 {
1268         /* static counter for line numbers */
1269         static long log_line_number = 0;
1270
1271         /* has counter been reset in current process? */
1272         static int      log_my_pid = 0;
1273
1274         int                     format_len;
1275         int                     i;
1276
1277         /*
1278          * This is one of the few places where we'd rather not inherit a
1279          * static variable's value from the postmaster.  But since we will,
1280          * reset it when MyProcPid changes.
1281          */
1282         if (log_my_pid != MyProcPid)
1283         {
1284                 log_line_number = 0;
1285                 log_my_pid = MyProcPid;
1286         }
1287         log_line_number++;
1288
1289         if (Log_line_prefix == NULL)
1290                 return;                                 /* in case guc hasn't run yet */
1291
1292         format_len = strlen(Log_line_prefix);
1293
1294         for (i = 0; i < format_len; i++)
1295         {
1296                 if (Log_line_prefix[i] != '%')
1297                 {
1298                         /* literal char, just copy */
1299                         appendStringInfoChar(buf, Log_line_prefix[i]);
1300                         continue;
1301                 }
1302                 /* go to char after '%' */
1303                 i++;
1304                 if (i >= format_len)
1305                 {
1306                         /* format error - ignore it */
1307                         break;
1308                 }
1309
1310                 /* process the option */
1311                 switch (Log_line_prefix[i])
1312                 {
1313                         case 'u':
1314                                 if (MyProcPort)
1315                                 {
1316                                         const char *username = MyProcPort->user_name;
1317
1318                                         if (username == NULL || *username == '\0')
1319                                                 username = gettext("[unknown]");
1320                                         appendStringInfo(buf, "%s", username);
1321                                 }
1322                                 break;
1323                         case 'd':
1324                                 if (MyProcPort)
1325                                 {
1326                                         const char *dbname = MyProcPort->database_name;
1327
1328                                         if (dbname == NULL || *dbname == '\0')
1329                                                 dbname = gettext("[unknown]");
1330                                         appendStringInfo(buf, "%s", dbname);
1331                                 }
1332                                 break;
1333                         case 'c':
1334                                 if (MyProcPort)
1335                                 {
1336                                         appendStringInfo(buf, "%lx.%lx",
1337                                                            (long) (MyProcPort->session_start.tv_sec),
1338                                                                          (long) MyProcPid);
1339                                 }
1340                                 break;
1341                         case 'p':
1342                                 appendStringInfo(buf, "%ld", (long) MyProcPid);
1343                                 break;
1344                         case 'l':
1345                                 appendStringInfo(buf, "%ld", log_line_number);
1346                                 break;
1347                         case 't':
1348                                 {
1349                                         /*
1350                                          * Note: for %t and %s we deliberately use the C
1351                                          * library's strftime/localtime, and not the
1352                                          * equivalent functions from src/timezone.      This
1353                                          * ensures that all backends will report log entries
1354                                          * in the same timezone, namely whatever C-library
1355                                          * setting they inherit from the postmaster.  If we
1356                                          * used src/timezone then local settings of the
1357                                          * TimeZone GUC variable would confuse the log.
1358                                          */
1359                                         time_t          stamp_time = time(NULL);
1360                                         char            strfbuf[128];
1361
1362                                         strftime(strfbuf, sizeof(strfbuf),
1363                                                          "%Y-%m-%d %H:%M:%S %Z",
1364                                                          localtime(&stamp_time));
1365                                         appendStringInfoString(buf, strfbuf);
1366                                 }
1367                                 break;
1368                         case 's':
1369                                 if (MyProcPort)
1370                                 {
1371                                         time_t          stamp_time = MyProcPort->session_start.tv_sec;
1372                                         char            strfbuf[128];
1373
1374                                         strftime(strfbuf, sizeof(strfbuf),
1375                                                          "%Y-%m-%d %H:%M:%S %Z",
1376                                                          localtime(&stamp_time));
1377                                         appendStringInfoString(buf, strfbuf);
1378                                 }
1379                                 break;
1380                         case 'i':
1381                                 if (MyProcPort)
1382                                         appendStringInfo(buf, "%s", MyProcPort->commandTag);
1383                                 break;
1384                         case 'r':
1385                                 if (MyProcPort)
1386                                 {
1387                                         appendStringInfo(buf, "%s", MyProcPort->remote_host);
1388                                         if (strlen(MyProcPort->remote_port) > 0)
1389                                                 appendStringInfo(buf, "(%s)",
1390                                                                                  MyProcPort->remote_port);
1391                                 }
1392                                 break;
1393                         case 'x':
1394                                 /* in postmaster and friends, stop if %x is seen */
1395                                 /* in a backend, just ignore */
1396                                 if (MyProcPort == NULL)
1397                                         i = format_len;
1398                                 break;
1399                         case '%':
1400                                 appendStringInfoChar(buf, '%');
1401                                 break;
1402                         default:
1403                                 /* format error - ignore it */
1404                                 break;
1405                 }
1406         }
1407 }
1408
1409
1410 /*
1411  * Write error report to server's log
1412  */
1413 static void
1414 send_message_to_server_log(ErrorData *edata)
1415 {
1416         StringInfoData buf;
1417
1418         initStringInfo(&buf);
1419
1420         log_line_prefix(&buf);
1421         appendStringInfo(&buf, "%s:  ", error_severity(edata->elevel));
1422
1423         if (Log_error_verbosity >= PGERROR_VERBOSE)
1424         {
1425                 /* unpack MAKE_SQLSTATE code */
1426                 char            tbuf[12];
1427                 int                     ssval;
1428                 int                     i;
1429
1430                 ssval = edata->sqlerrcode;
1431                 for (i = 0; i < 5; i++)
1432                 {
1433                         tbuf[i] = PGUNSIXBIT(ssval);
1434                         ssval >>= 6;
1435                 }
1436                 tbuf[i] = '\0';
1437                 appendStringInfo(&buf, "%s: ", tbuf);
1438         }
1439
1440         if (edata->message)
1441                 append_with_tabs(&buf, edata->message);
1442         else
1443                 append_with_tabs(&buf, gettext("missing error text"));
1444
1445         if (edata->cursorpos > 0)
1446                 appendStringInfo(&buf, gettext(" at character %d"),
1447                                                  edata->cursorpos);
1448         else if (edata->internalpos > 0)
1449                 appendStringInfo(&buf, gettext(" at character %d"),
1450                                                  edata->internalpos);
1451
1452         appendStringInfoChar(&buf, '\n');
1453
1454         if (Log_error_verbosity >= PGERROR_DEFAULT)
1455         {
1456                 if (edata->detail)
1457                 {
1458                         log_line_prefix(&buf);
1459                         appendStringInfoString(&buf, gettext("DETAIL:  "));
1460                         append_with_tabs(&buf, edata->detail);
1461                         appendStringInfoChar(&buf, '\n');
1462                 }
1463                 if (edata->hint)
1464                 {
1465                         log_line_prefix(&buf);
1466                         appendStringInfoString(&buf, gettext("HINT:  "));
1467                         append_with_tabs(&buf, edata->hint);
1468                         appendStringInfoChar(&buf, '\n');
1469                 }
1470                 if (edata->internalquery)
1471                 {
1472                         log_line_prefix(&buf);
1473                         appendStringInfoString(&buf, gettext("QUERY:  "));
1474                         append_with_tabs(&buf, edata->internalquery);
1475                         appendStringInfoChar(&buf, '\n');
1476                 }
1477                 if (edata->context)
1478                 {
1479                         log_line_prefix(&buf);
1480                         appendStringInfoString(&buf, gettext("CONTEXT:  "));
1481                         append_with_tabs(&buf, edata->context);
1482                         appendStringInfoChar(&buf, '\n');
1483                 }
1484                 if (Log_error_verbosity >= PGERROR_VERBOSE)
1485                 {
1486                         /* assume no newlines in funcname or filename... */
1487                         if (edata->funcname && edata->filename)
1488                         {
1489                                 log_line_prefix(&buf);
1490                                 appendStringInfo(&buf, gettext("LOCATION:  %s, %s:%d\n"),
1491                                                                  edata->funcname, edata->filename,
1492                                                                  edata->lineno);
1493                         }
1494                         else if (edata->filename)
1495                         {
1496                                 log_line_prefix(&buf);
1497                                 appendStringInfo(&buf, gettext("LOCATION:  %s:%d\n"),
1498                                                                  edata->filename, edata->lineno);
1499                         }
1500                 }
1501         }
1502
1503         /*
1504          * If the user wants the query that generated this error logged, do
1505          * it.
1506          */
1507         if (edata->elevel >= log_min_error_statement && debug_query_string != NULL)
1508         {
1509                 log_line_prefix(&buf);
1510                 appendStringInfoString(&buf, gettext("STATEMENT:  "));
1511                 append_with_tabs(&buf, debug_query_string);
1512                 appendStringInfoChar(&buf, '\n');
1513         }
1514
1515
1516 #ifdef HAVE_SYSLOG
1517         /* Write to syslog, if enabled */
1518         if (Log_destination & LOG_DESTINATION_SYSLOG)
1519         {
1520                 int                     syslog_level;
1521
1522                 switch (edata->elevel)
1523                 {
1524                         case DEBUG5:
1525                         case DEBUG4:
1526                         case DEBUG3:
1527                         case DEBUG2:
1528                         case DEBUG1:
1529                                 syslog_level = LOG_DEBUG;
1530                                 break;
1531                         case LOG:
1532                         case COMMERROR:
1533                         case INFO:
1534                                 syslog_level = LOG_INFO;
1535                                 break;
1536                         case NOTICE:
1537                         case WARNING:
1538                                 syslog_level = LOG_NOTICE;
1539                                 break;
1540                         case ERROR:
1541                                 syslog_level = LOG_WARNING;
1542                                 break;
1543                         case FATAL:
1544                                 syslog_level = LOG_ERR;
1545                                 break;
1546                         case PANIC:
1547                         default:
1548                                 syslog_level = LOG_CRIT;
1549                                 break;
1550                 }
1551
1552                 write_syslog(syslog_level, buf.data);
1553         }
1554 #endif   /* HAVE_SYSLOG */
1555 #ifdef WIN32
1556         if (Log_destination & LOG_DESTINATION_EVENTLOG)
1557         {
1558                 int                     eventlog_level;
1559
1560                 switch (edata->elevel)
1561                 {
1562                         case DEBUG5:
1563                         case DEBUG4:
1564                         case DEBUG3:
1565                         case DEBUG2:
1566                         case DEBUG1:
1567                         case LOG:
1568                         case COMMERROR:
1569                         case INFO:
1570                         case NOTICE:
1571                                 eventlog_level = EVENTLOG_INFORMATION_TYPE;
1572                                 break;
1573                         case WARNING:
1574                                 eventlog_level = EVENTLOG_WARNING_TYPE;
1575                                 break;
1576                         case ERROR:
1577                         case FATAL:
1578                         case PANIC:
1579                         default:
1580                                 eventlog_level = EVENTLOG_ERROR_TYPE;
1581                                 break;
1582                 }
1583                 write_eventlog(eventlog_level, buf.data);
1584         }
1585 #endif   /* WIN32 */
1586         /* Write to stderr, if enabled */
1587         if ((Log_destination & LOG_DESTINATION_STDERR) || whereToSendOutput == Debug)
1588                 fprintf(stderr, "%s", buf.data);
1589
1590         /* If in the syslogger process, try to write messages direct to file */
1591         if (am_syslogger)
1592                 write_syslogger_file(buf.data, buf.len);
1593
1594         pfree(buf.data);
1595 }
1596
1597
1598 /*
1599  * Write error report to client
1600  */
1601 static void
1602 send_message_to_frontend(ErrorData *edata)
1603 {
1604         StringInfoData msgbuf;
1605
1606         /* 'N' (Notice) is for nonfatal conditions, 'E' is for errors */
1607         pq_beginmessage(&msgbuf, (edata->elevel < ERROR) ? 'N' : 'E');
1608
1609         if (PG_PROTOCOL_MAJOR(FrontendProtocol) >= 3)
1610         {
1611                 /* New style with separate fields */
1612                 char            tbuf[12];
1613                 int                     ssval;
1614                 int                     i;
1615
1616                 pq_sendbyte(&msgbuf, PG_DIAG_SEVERITY);
1617                 pq_sendstring(&msgbuf, error_severity(edata->elevel));
1618
1619                 /* unpack MAKE_SQLSTATE code */
1620                 ssval = edata->sqlerrcode;
1621                 for (i = 0; i < 5; i++)
1622                 {
1623                         tbuf[i] = PGUNSIXBIT(ssval);
1624                         ssval >>= 6;
1625                 }
1626                 tbuf[i] = '\0';
1627
1628                 pq_sendbyte(&msgbuf, PG_DIAG_SQLSTATE);
1629                 pq_sendstring(&msgbuf, tbuf);
1630
1631                 /* M field is required per protocol, so always send something */
1632                 pq_sendbyte(&msgbuf, PG_DIAG_MESSAGE_PRIMARY);
1633                 if (edata->message)
1634                         pq_sendstring(&msgbuf, edata->message);
1635                 else
1636                         pq_sendstring(&msgbuf, gettext("missing error text"));
1637
1638                 if (edata->detail)
1639                 {
1640                         pq_sendbyte(&msgbuf, PG_DIAG_MESSAGE_DETAIL);
1641                         pq_sendstring(&msgbuf, edata->detail);
1642                 }
1643
1644                 if (edata->hint)
1645                 {
1646                         pq_sendbyte(&msgbuf, PG_DIAG_MESSAGE_HINT);
1647                         pq_sendstring(&msgbuf, edata->hint);
1648                 }
1649
1650                 if (edata->context)
1651                 {
1652                         pq_sendbyte(&msgbuf, PG_DIAG_CONTEXT);
1653                         pq_sendstring(&msgbuf, edata->context);
1654                 }
1655
1656                 if (edata->cursorpos > 0)
1657                 {
1658                         snprintf(tbuf, sizeof(tbuf), "%d", edata->cursorpos);
1659                         pq_sendbyte(&msgbuf, PG_DIAG_STATEMENT_POSITION);
1660                         pq_sendstring(&msgbuf, tbuf);
1661                 }
1662
1663                 if (edata->internalpos > 0)
1664                 {
1665                         snprintf(tbuf, sizeof(tbuf), "%d", edata->internalpos);
1666                         pq_sendbyte(&msgbuf, PG_DIAG_INTERNAL_POSITION);
1667                         pq_sendstring(&msgbuf, tbuf);
1668                 }
1669
1670                 if (edata->internalquery)
1671                 {
1672                         pq_sendbyte(&msgbuf, PG_DIAG_INTERNAL_QUERY);
1673                         pq_sendstring(&msgbuf, edata->internalquery);
1674                 }
1675
1676                 if (edata->filename)
1677                 {
1678                         pq_sendbyte(&msgbuf, PG_DIAG_SOURCE_FILE);
1679                         pq_sendstring(&msgbuf, edata->filename);
1680                 }
1681
1682                 if (edata->lineno > 0)
1683                 {
1684                         snprintf(tbuf, sizeof(tbuf), "%d", edata->lineno);
1685                         pq_sendbyte(&msgbuf, PG_DIAG_SOURCE_LINE);
1686                         pq_sendstring(&msgbuf, tbuf);
1687                 }
1688
1689                 if (edata->funcname)
1690                 {
1691                         pq_sendbyte(&msgbuf, PG_DIAG_SOURCE_FUNCTION);
1692                         pq_sendstring(&msgbuf, edata->funcname);
1693                 }
1694
1695                 pq_sendbyte(&msgbuf, '\0');             /* terminator */
1696         }
1697         else
1698         {
1699                 /* Old style --- gin up a backwards-compatible message */
1700                 StringInfoData buf;
1701
1702                 initStringInfo(&buf);
1703
1704                 appendStringInfo(&buf, "%s:  ", error_severity(edata->elevel));
1705
1706                 if (edata->show_funcname && edata->funcname)
1707                         appendStringInfo(&buf, "%s: ", edata->funcname);
1708
1709                 if (edata->message)
1710                         appendStringInfoString(&buf, edata->message);
1711                 else
1712                         appendStringInfoString(&buf, gettext("missing error text"));
1713
1714                 if (edata->cursorpos > 0)
1715                         appendStringInfo(&buf, gettext(" at character %d"),
1716                                                          edata->cursorpos);
1717                 else if (edata->internalpos > 0)
1718                         appendStringInfo(&buf, gettext(" at character %d"),
1719                                                          edata->internalpos);
1720
1721                 appendStringInfoChar(&buf, '\n');
1722
1723                 pq_sendstring(&msgbuf, buf.data);
1724
1725                 pfree(buf.data);
1726         }
1727
1728         pq_endmessage(&msgbuf);
1729
1730         /*
1731          * This flush is normally not necessary, since postgres.c will flush
1732          * out waiting data when control returns to the main loop. But it
1733          * seems best to leave it here, so that the client has some clue what
1734          * happened if the backend dies before getting back to the main loop
1735          * ... error/notice messages should not be a performance-critical path
1736          * anyway, so an extra flush won't hurt much ...
1737          */
1738         pq_flush();
1739 }
1740
1741
1742 /*
1743  * Support routines for formatting error messages.
1744  */
1745
1746
1747 /*
1748  * expand_fmt_string --- process special format codes in a format string
1749  *
1750  * We must replace %m with the appropriate strerror string, since vsnprintf
1751  * won't know what to do with it.
1752  *
1753  * The result is a palloc'd string.
1754  */
1755 static char *
1756 expand_fmt_string(const char *fmt, ErrorData *edata)
1757 {
1758         StringInfoData buf;
1759         const char *cp;
1760
1761         initStringInfo(&buf);
1762
1763         for (cp = fmt; *cp; cp++)
1764         {
1765                 if (cp[0] == '%' && cp[1] != '\0')
1766                 {
1767                         cp++;
1768                         if (*cp == 'm')
1769                         {
1770                                 /*
1771                                  * Replace %m by system error string.  If there are any
1772                                  * %'s in the string, we'd better double them so that
1773                                  * vsnprintf won't misinterpret.
1774                                  */
1775                                 const char *cp2;
1776
1777                                 cp2 = useful_strerror(edata->saved_errno);
1778                                 for (; *cp2; cp2++)
1779                                 {
1780                                         if (*cp2 == '%')
1781                                                 appendStringInfoCharMacro(&buf, '%');
1782                                         appendStringInfoCharMacro(&buf, *cp2);
1783                                 }
1784                         }
1785                         else
1786                         {
1787                                 /* copy % and next char --- this avoids trouble with %%m */
1788                                 appendStringInfoCharMacro(&buf, '%');
1789                                 appendStringInfoCharMacro(&buf, *cp);
1790                         }
1791                 }
1792                 else
1793                         appendStringInfoCharMacro(&buf, *cp);
1794         }
1795
1796         return buf.data;
1797 }
1798
1799
1800 /*
1801  * A slightly cleaned-up version of strerror()
1802  */
1803 static const char *
1804 useful_strerror(int errnum)
1805 {
1806         /* this buffer is only used if errno has a bogus value */
1807         static char errorstr_buf[48];
1808         const char *str;
1809
1810 #ifdef WIN32
1811         /* Winsock error code range, per WinError.h */
1812         if (errnum >= 10000 && errnum <= 11999)
1813                 return pgwin32_socket_strerror(errnum);
1814 #endif
1815         str = strerror(errnum);
1816
1817         /*
1818          * Some strerror()s return an empty string for out-of-range errno.
1819          * This is ANSI C spec compliant, but not exactly useful.
1820          */
1821         if (str == NULL || *str == '\0')
1822         {
1823                 /*
1824                  * translator: This string will be truncated at 47 characters
1825                  * expanded.
1826                  */
1827                 snprintf(errorstr_buf, sizeof(errorstr_buf),
1828                                  gettext("operating system error %d"), errnum);
1829                 str = errorstr_buf;
1830         }
1831
1832         return str;
1833 }
1834
1835
1836 /*
1837  * error_severity --- get localized string representing elevel
1838  */
1839 static const char *
1840 error_severity(int elevel)
1841 {
1842         const char *prefix;
1843
1844         switch (elevel)
1845         {
1846                 case DEBUG1:
1847                 case DEBUG2:
1848                 case DEBUG3:
1849                 case DEBUG4:
1850                 case DEBUG5:
1851                         prefix = gettext("DEBUG");
1852                         break;
1853                 case LOG:
1854                 case COMMERROR:
1855                         prefix = gettext("LOG");
1856                         break;
1857                 case INFO:
1858                         prefix = gettext("INFO");
1859                         break;
1860                 case NOTICE:
1861                         prefix = gettext("NOTICE");
1862                         break;
1863                 case WARNING:
1864                         prefix = gettext("WARNING");
1865                         break;
1866                 case ERROR:
1867                         prefix = gettext("ERROR");
1868                         break;
1869                 case FATAL:
1870                         prefix = gettext("FATAL");
1871                         break;
1872                 case PANIC:
1873                         prefix = gettext("PANIC");
1874                         break;
1875                 default:
1876                         prefix = "???";
1877                         break;
1878         }
1879
1880         return prefix;
1881 }
1882
1883
1884 /*
1885  *      append_with_tabs
1886  *
1887  *      Append the string to the StringInfo buffer, inserting a tab after any
1888  *      newline.
1889  */
1890 static void
1891 append_with_tabs(StringInfo buf, const char *str)
1892 {
1893         char            ch;
1894
1895         while ((ch = *str++) != '\0')
1896         {
1897                 appendStringInfoCharMacro(buf, ch);
1898                 if (ch == '\n')
1899                         appendStringInfoCharMacro(buf, '\t');
1900         }
1901 }
1902
1903
1904 /*
1905  * Write errors to stderr (or by equal means when stderr is
1906  * not available). Used before ereport/elog can be used
1907  * safely (memory context, GUC load etc)
1908  */
1909 void
1910 write_stderr(const char *fmt,...)
1911 {
1912         va_list         ap;
1913
1914         fmt = gettext(fmt);
1915
1916         va_start(ap, fmt);
1917 #ifndef WIN32
1918         /* On Unix, we just fprintf to stderr */
1919         vfprintf(stderr, fmt, ap);
1920 #else
1921
1922         /*
1923          * On Win32, we print to stderr if running on a console, or write to
1924          * eventlog if running as a service
1925          */
1926         if (pgwin32_is_service())       /* Running as a service */
1927         {
1928                 char            errbuf[2048];           /* Arbitrary size? */
1929
1930                 vsnprintf(errbuf, sizeof(errbuf), fmt, ap);
1931
1932                 write_eventlog(EVENTLOG_ERROR_TYPE, errbuf);
1933         }
1934         else
1935 /* Not running as service, write to stderr */
1936                 vfprintf(stderr, fmt, ap);
1937 #endif
1938         va_end(ap);
1939 }