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