]> granicus.if.org Git - postgresql/blob - src/backend/utils/error/elog.c
Remove GUC log_statement, log_pid, log_timestamp, log_source_port.
[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 condition is to force any
28  * such messages up to ERROR level if they aren't already (so that we will
29  * not need to return to the outer elog.c call), and to reset the ErrorContext
30  * to empty before trying to process the inner message.  Since ErrorContext
31  * is guaranteed to have at least 8K of space in it (see mcxt.c), we should
32  * be able to process an "out of memory" message successfully.
33  *
34  *
35  * Portions Copyright (c) 1996-2003, PostgreSQL Global Development Group
36  * Portions Copyright (c) 1994, Regents of the University of California
37  *
38  *
39  * IDENTIFICATION
40  *        $PostgreSQL: pgsql/src/backend/utils/error/elog.c,v 1.128 2004/03/15 15:56:23 momjian Exp $
41  *
42  *-------------------------------------------------------------------------
43  */
44 #include "postgres.h"
45
46 #include <time.h>
47 #include <fcntl.h>
48 #include <errno.h>
49 #include <unistd.h>
50 #include <signal.h>
51 #include <sys/time.h>
52 #include <ctype.h>
53 #ifdef HAVE_SYSLOG
54 #include <syslog.h>
55 #endif
56
57 #include "libpq/libpq.h"
58 #include "libpq/pqformat.h"
59 #include "mb/pg_wchar.h"
60 #include "miscadmin.h"
61 #include "storage/ipc.h"
62 #include "tcop/tcopprot.h"
63 #include "utils/memutils.h"
64 #include "utils/guc.h"
65
66
67 /* Global variables */
68 ErrorContextCallback *error_context_stack = NULL;
69
70 /* GUC parameters */
71 PGErrorVerbosity Log_error_verbosity = PGERROR_VERBOSE;
72 char       *Log_line_prefix = ""; /* format for extra log line info */
73
74 #ifdef HAVE_SYSLOG
75 /*
76  * 0 = only stdout/stderr
77  * 1 = stdout+stderr and syslog
78  * 2 = syslog only
79  * ... in theory anyway
80  */
81 int                     Use_syslog = 0;
82 char       *Syslog_facility;    /* openlog() parameters */
83 char       *Syslog_ident;
84
85 static void write_syslog(int level, const char *line);
86
87 #else
88
89 #define Use_syslog 0
90 #endif   /* HAVE_SYSLOG */
91
92
93 /*
94  * ErrorData holds the data accumulated during any one ereport() cycle.
95  * Any non-NULL pointers must point to palloc'd data in ErrorContext.
96  * (The const pointers are an exception; we assume they point at non-freeable
97  * constant strings.)
98  */
99
100 typedef struct ErrorData
101 {
102         int                     elevel;                 /* error level */
103         bool            output_to_server;               /* will report to server log? */
104         bool            output_to_client;               /* will report to client? */
105         bool            show_funcname;  /* true to force funcname inclusion */
106         const char *filename;           /* __FILE__ of ereport() call */
107         int                     lineno;                 /* __LINE__ of ereport() call */
108         const char *funcname;           /* __func__ of ereport() call */
109         int                     sqlerrcode;             /* encoded ERRSTATE */
110         char       *message;            /* primary error message */
111         char       *detail;                     /* detail error message */
112         char       *hint;                       /* hint message */
113         char       *context;            /* context message */
114         int                     cursorpos;              /* cursor index into query string */
115         int                     saved_errno;    /* errno at entry */
116 } ErrorData;
117
118 /* We provide a small stack of ErrorData records for re-entrant cases */
119 #define ERRORDATA_STACK_SIZE  5
120
121 static ErrorData errordata[ERRORDATA_STACK_SIZE];
122
123 static int      errordata_stack_depth = -1; /* index of topmost active frame */
124
125 static int      recursion_depth = 0;    /* to detect actual recursion */
126
127
128 /* Macro for checking errordata_stack_depth is reasonable */
129 #define CHECK_STACK_DEPTH() \
130         do { \
131                 if (errordata_stack_depth < 0) \
132                 { \
133                         errordata_stack_depth = -1; \
134                         ereport(ERROR, (errmsg_internal("errstart was not called"))); \
135                 } \
136         } while (0)
137
138
139 static void send_message_to_server_log(ErrorData *edata);
140 static void send_message_to_frontend(ErrorData *edata);
141 static char *expand_fmt_string(const char *fmt, ErrorData *edata);
142 static const char *useful_strerror(int errnum);
143 static const char *error_severity(int elevel);
144 static void append_with_tabs(StringInfo buf, const char *str);
145 static const char *log_line_prefix(void);
146
147 /*
148  * errstart --- begin an error-reporting cycle
149  *
150  * Create a stack entry and store the given parameters in it.  Subsequently,
151  * errmsg() and perhaps other routines will be called to further populate
152  * the stack entry.  Finally, errfinish() will be called to actually process
153  * the error report.
154  *
155  * Returns TRUE in normal case.  Returns FALSE to short-circuit the error
156  * report (if it's a warning or lower and not to be reported anywhere).
157  */
158 bool
159 errstart(int elevel, const char *filename, int lineno,
160                  const char *funcname)
161 {
162         ErrorData  *edata;
163         bool            output_to_server = false;
164         bool            output_to_client = false;
165
166         /*
167          * First decide whether we need to process this report at all; if it's
168          * warning or less and not enabled for logging, just return FALSE
169          * without starting up any error logging machinery.
170          */
171
172         /*
173          * Convert initialization errors into fatal errors. This is probably
174          * redundant, because Warn_restart_ready won't be set anyway.
175          */
176         if (elevel == ERROR && IsInitProcessingMode())
177                 elevel = FATAL;
178
179         /*
180          * If we are inside a critical section, all errors become PANIC
181          * errors.      See miscadmin.h.
182          */
183         if (elevel >= ERROR)
184         {
185                 if (CritSectionCount > 0)
186                         elevel = PANIC;
187         }
188
189         /* Determine whether message is enabled for server log output */
190         if (IsPostmasterEnvironment)
191         {
192                 /* Complicated because LOG is sorted out-of-order for this purpose */
193                 if (elevel == LOG || elevel == COMMERROR)
194                 {
195                         if (log_min_messages == LOG)
196                                 output_to_server = true;
197                         else if (log_min_messages < FATAL)
198                                 output_to_server = true;
199                 }
200                 else
201                 {
202                         /* elevel != LOG */
203                         if (log_min_messages == LOG)
204                         {
205                                 if (elevel >= FATAL)
206                                         output_to_server = true;
207                         }
208                         /* Neither is LOG */
209                         else if (elevel >= log_min_messages)
210                                 output_to_server = true;
211                 }
212         }
213         else
214         {
215                 /* In bootstrap/standalone case, do not sort LOG out-of-order */
216                 output_to_server = (elevel >= log_min_messages);
217         }
218
219         /* Determine whether message is enabled for client output */
220         if (whereToSendOutput == Remote && elevel != COMMERROR)
221         {
222                 /*
223                  * client_min_messages is honored only after we complete the
224                  * authentication handshake.  This is required both for security
225                  * reasons and because many clients can't handle NOTICE messages
226                  * during authentication.
227                  */
228                 if (ClientAuthInProgress)
229                         output_to_client = (elevel >= ERROR);
230                 else
231                         output_to_client = (elevel >= client_min_messages ||
232                                                                 elevel == INFO);
233         }
234
235         /* Skip processing effort if non-error message will not be output */
236         if (elevel < ERROR && !output_to_server && !output_to_client)
237                 return false;
238
239         /*
240          * Okay, crank up a stack entry to store the info in.
241          */
242
243         if (recursion_depth++ > 0)
244         {
245                 /*
246                  * Ooops, error during error processing.  Clear ErrorContext and
247                  * force level up to ERROR or greater, as discussed at top of
248                  * file.  Adjust output decisions too.
249                  */
250                 MemoryContextReset(ErrorContext);
251                 output_to_server = true;
252                 if (whereToSendOutput == Remote && elevel != COMMERROR)
253                         output_to_client = true;
254                 elevel = Max(elevel, ERROR);
255
256                 /*
257                  * If we recurse more than once, the problem might be something
258                  * broken in a context traceback routine.  Abandon them too.
259                  */
260                 if (recursion_depth > 2)
261                         error_context_stack = NULL;
262         }
263         if (++errordata_stack_depth >= ERRORDATA_STACK_SIZE)
264         {
265                 /* Wups, stack not big enough */
266                 int                     i;
267
268                 elevel = Max(elevel, ERROR);
269
270                 /*
271                  * Don't forget any FATAL/PANIC status on the stack (see comments
272                  * in errfinish)
273                  */
274                 for (i = 0; i < errordata_stack_depth; i++)
275                         elevel = Max(elevel, errordata[i].elevel);
276                 /* Clear the stack and try again */
277                 errordata_stack_depth = -1;
278                 ereport(elevel, (errmsg_internal("ERRORDATA_STACK_SIZE exceeded")));
279         }
280
281         /* Initialize data for this error frame */
282         edata = &errordata[errordata_stack_depth];
283         MemSet(edata, 0, sizeof(ErrorData));
284         edata->elevel = elevel;
285         edata->output_to_server = output_to_server;
286         edata->output_to_client = output_to_client;
287         edata->filename = filename;
288         edata->lineno = lineno;
289         edata->funcname = funcname;
290         /* Select default errcode based on elevel */
291         if (elevel >= ERROR)
292                 edata->sqlerrcode = ERRCODE_INTERNAL_ERROR;
293         else if (elevel == WARNING)
294                 edata->sqlerrcode = ERRCODE_WARNING;
295         else
296                 edata->sqlerrcode = ERRCODE_SUCCESSFUL_COMPLETION;
297         /* errno is saved here so that error parameter eval can't change it */
298         edata->saved_errno = errno;
299
300         recursion_depth--;
301         return true;
302 }
303
304 /*
305  * errfinish --- end an error-reporting cycle
306  *
307  * Produce the appropriate error report(s) and pop the error stack.
308  *
309  * If elevel is ERROR or worse, control does not return to the caller.
310  * See elog.h for the error level definitions.
311  */
312 void
313 errfinish(int dummy,...)
314 {
315         ErrorData  *edata = &errordata[errordata_stack_depth];
316         int                     elevel = edata->elevel;
317         MemoryContext oldcontext;
318         ErrorContextCallback *econtext;
319
320         recursion_depth++;
321         CHECK_STACK_DEPTH();
322
323         /*
324          * Do processing in ErrorContext, which we hope has enough reserved
325          * space to report an error.
326          */
327         oldcontext = MemoryContextSwitchTo(ErrorContext);
328
329         /*
330          * Call any context callback functions.  Errors occurring in callback
331          * functions will be treated as recursive errors --- this ensures we
332          * will avoid infinite recursion (see errstart).
333          */
334         for (econtext = error_context_stack;
335                  econtext != NULL;
336                  econtext = econtext->previous)
337                 (*econtext->callback) (econtext->arg);
338
339         /* Send to server log, if enabled */
340         if (edata->output_to_server)
341                 send_message_to_server_log(edata);
342
343         /*
344          * Abort any old-style COPY OUT in progress when an error is detected.
345          * This hack is necessary because of poor design of old-style copy
346          * protocol.  Note we must do this even if client is fool enough to
347          * have set client_min_messages above ERROR, so don't look at
348          * output_to_client.
349          */
350         if (elevel >= ERROR && whereToSendOutput == Remote)
351                 pq_endcopyout(true);
352
353         /* Send to client, if enabled */
354         if (edata->output_to_client)
355                 send_message_to_frontend(edata);
356
357         /* Now free up subsidiary data attached to stack entry, and release it */
358         if (edata->message)
359                 pfree(edata->message);
360         if (edata->detail)
361                 pfree(edata->detail);
362         if (edata->hint)
363                 pfree(edata->hint);
364         if (edata->context)
365                 pfree(edata->context);
366
367         MemoryContextSwitchTo(oldcontext);
368
369         errordata_stack_depth--;
370         recursion_depth--;
371
372         /*
373          * If the error level is ERROR or more, we are not going to return to
374          * caller; therefore, if there is any stacked error already in
375          * progress it will be lost.  This is more or less okay, except we do
376          * not want to have a FATAL or PANIC error downgraded because the
377          * reporting process was interrupted by a lower-grade error.  So check
378          * the stack and make sure we panic if panic is warranted.
379          */
380         if (elevel >= ERROR)
381         {
382                 int                     i;
383
384                 for (i = 0; i <= errordata_stack_depth; i++)
385                         elevel = Max(elevel, errordata[i].elevel);
386
387                 /*
388                  * Also, be sure to reset the stack to empty.  We do not clear
389                  * ErrorContext here, though; PostgresMain does that later on.
390                  */
391                 errordata_stack_depth = -1;
392                 recursion_depth = 0;
393                 error_context_stack = NULL;
394         }
395
396         /*
397          * Perform error recovery action as specified by elevel.
398          */
399         if (elevel == ERROR || elevel == FATAL)
400         {
401                 /* Prevent immediate interrupt while entering error recovery */
402                 ImmediateInterruptOK = false;
403
404                 /*
405                  * If we just reported a startup failure, the client will
406                  * disconnect on receiving it, so don't send any more to the
407                  * client.
408                  */
409                 if (!Warn_restart_ready && whereToSendOutput == Remote)
410                         whereToSendOutput = None;
411
412                 /*
413                  * For a FATAL error, we let proc_exit clean up and exit.
414                  *
415                  * There are several other cases in which we treat ERROR as FATAL and
416                  * go directly to proc_exit:
417                  *
418                  * 1. ExitOnAnyError mode switch is set (initdb uses this).
419                  *
420                  * 2. we have not yet entered the main backend loop (ie, we are in
421                  * the postmaster or in backend startup); we have noplace to
422                  * recover.
423                  *
424                  * 3. the error occurred after proc_exit has begun to run.      (It's
425                  * proc_exit's responsibility to see that this doesn't turn into
426                  * infinite recursion!)
427                  *
428                  * In the last case, we exit with nonzero exit code to indicate that
429                  * something's pretty wrong.  We also want to exit with nonzero
430                  * exit code if not running under the postmaster (for example, if
431                  * we are being run from the initdb script, we'd better return an
432                  * error status).
433                  */
434                 if (elevel == FATAL ||
435                         ExitOnAnyError ||
436                         !Warn_restart_ready ||
437                         proc_exit_inprogress)
438                 {
439                         /*
440                          * fflush here is just to improve the odds that we get to see
441                          * the error message, in case things are so hosed that
442                          * proc_exit crashes.  Any other code you might be tempted to
443                          * add here should probably be in an on_proc_exit callback
444                          * instead.
445                          */
446                         fflush(stdout);
447                         fflush(stderr);
448                         proc_exit(proc_exit_inprogress || !IsUnderPostmaster);
449                 }
450
451                 /*
452                  * Guard against infinite loop from errors during error recovery.
453                  */
454                 if (InError)
455                         ereport(PANIC, (errmsg("error during error recovery, giving up")));
456                 InError = true;
457
458                 /*
459                  * Otherwise we can return to the main loop in postgres.c.
460                  */
461                 siglongjmp(Warn_restart, 1);
462         }
463
464         if (elevel >= PANIC)
465         {
466                 /*
467                  * Serious crash time. Postmaster will observe nonzero process
468                  * exit status and kill the other backends too.
469                  *
470                  * XXX: what if we are *in* the postmaster?  abort() won't kill our
471                  * children...
472                  */
473                 ImmediateInterruptOK = false;
474                 fflush(stdout);
475                 fflush(stderr);
476                 abort();
477         }
478
479         /* We reach here if elevel <= WARNING. OK to return to caller. */
480 }
481
482
483 /*
484  * errcode --- add SQLSTATE error code to the current error
485  *
486  * The code is expected to be represented as per MAKE_SQLSTATE().
487  */
488 int
489 errcode(int sqlerrcode)
490 {
491         ErrorData  *edata = &errordata[errordata_stack_depth];
492
493         /* we don't bother incrementing recursion_depth */
494         CHECK_STACK_DEPTH();
495
496         edata->sqlerrcode = sqlerrcode;
497
498         return 0;                                       /* return value does not matter */
499 }
500
501
502 /*
503  * errcode_for_file_access --- add SQLSTATE error code to the current error
504  *
505  * The SQLSTATE code is chosen based on the saved errno value.  We assume
506  * that the failing operation was some type of disk file access.
507  *
508  * NOTE: the primary error message string should generally include %m
509  * when this is used.
510  */
511 int
512 errcode_for_file_access(void)
513 {
514         ErrorData  *edata = &errordata[errordata_stack_depth];
515
516         /* we don't bother incrementing recursion_depth */
517         CHECK_STACK_DEPTH();
518
519         switch (edata->saved_errno)
520         {
521                         /* Permission-denied failures */
522                 case EPERM:                             /* Not super-user */
523                 case EACCES:                    /* Permission denied */
524 #ifdef EROFS
525                 case EROFS:                             /* Read only file system */
526 #endif
527                         edata->sqlerrcode = ERRCODE_INSUFFICIENT_PRIVILEGE;
528                         break;
529
530                         /* File not found */
531                 case ENOENT:                    /* No such file or directory */
532                         edata->sqlerrcode = ERRCODE_UNDEFINED_FILE;
533                         break;
534
535                         /* Duplicate file */
536                 case EEXIST:                    /* File exists */
537                         edata->sqlerrcode = ERRCODE_DUPLICATE_FILE;
538                         break;
539
540                         /* Wrong object type or state */
541                 case ENOTDIR:                   /* Not a directory */
542                 case EISDIR:                    /* Is a directory */
543 #if defined(ENOTEMPTY) && (ENOTEMPTY != EEXIST) /* same code on AIX */
544                 case ENOTEMPTY:                 /* Directory not empty */
545 #endif
546                         edata->sqlerrcode = ERRCODE_WRONG_OBJECT_TYPE;
547                         break;
548
549                         /* Insufficient resources */
550                 case ENOSPC:                    /* No space left on device */
551                         edata->sqlerrcode = ERRCODE_DISK_FULL;
552                         break;
553
554                 case ENFILE:                    /* File table overflow */
555                 case EMFILE:                    /* Too many open files */
556                         edata->sqlerrcode = ERRCODE_INSUFFICIENT_RESOURCES;
557                         break;
558
559                         /* Hardware failure */
560                 case EIO:                               /* I/O error */
561                         edata->sqlerrcode = ERRCODE_IO_ERROR;
562                         break;
563
564                         /* All else is classified as internal errors */
565                 default:
566                         edata->sqlerrcode = ERRCODE_INTERNAL_ERROR;
567                         break;
568         }
569
570         return 0;                                       /* return value does not matter */
571 }
572
573 /*
574  * errcode_for_socket_access --- add SQLSTATE error code to the current error
575  *
576  * The SQLSTATE code is chosen based on the saved errno value.  We assume
577  * that the failing operation was some type of socket access.
578  *
579  * NOTE: the primary error message string should generally include %m
580  * when this is used.
581  */
582 int
583 errcode_for_socket_access(void)
584 {
585         ErrorData  *edata = &errordata[errordata_stack_depth];
586
587         /* we don't bother incrementing recursion_depth */
588         CHECK_STACK_DEPTH();
589
590         switch (edata->saved_errno)
591         {
592                         /* Loss of connection */
593                 case EPIPE:
594 #ifdef ECONNRESET
595                 case ECONNRESET:
596 #endif
597                         edata->sqlerrcode = ERRCODE_CONNECTION_FAILURE;
598                         break;
599
600                         /* All else is classified as internal errors */
601                 default:
602                         edata->sqlerrcode = ERRCODE_INTERNAL_ERROR;
603                         break;
604         }
605
606         return 0;                                       /* return value does not matter */
607 }
608
609
610 /*
611  * This macro handles expansion of a format string and associated parameters;
612  * it's common code for errmsg(), errdetail(), etc.  Must be called inside
613  * a routine that is declared like "const char *fmt, ..." and has an edata
614  * pointer set up.      The message is assigned to edata->targetfield, or
615  * appended to it if appendval is true.
616  *
617  * Note: we pstrdup the buffer rather than just transferring its storage
618  * to the edata field because the buffer might be considerably larger than
619  * really necessary.
620  */
621 #define EVALUATE_MESSAGE(targetfield, appendval)  \
622         { \
623                 char               *fmtbuf; \
624                 StringInfoData  buf; \
625                 /* Internationalize the error format string */ \
626                 fmt = gettext(fmt); \
627                 /* Expand %m in format string */ \
628                 fmtbuf = expand_fmt_string(fmt, edata); \
629                 initStringInfo(&buf); \
630                 if ((appendval) && edata->targetfield) \
631                         appendStringInfo(&buf, "%s\n", edata->targetfield); \
632                 /* Generate actual output --- have to use appendStringInfoVA */ \
633                 for (;;) \
634                 { \
635                         va_list         args; \
636                         bool            success; \
637                         va_start(args, fmt); \
638                         success = appendStringInfoVA(&buf, fmtbuf, args); \
639                         va_end(args); \
640                         if (success) \
641                                 break; \
642                         enlargeStringInfo(&buf, buf.maxlen); \
643                 } \
644                 /* Done with expanded fmt */ \
645                 pfree(fmtbuf); \
646                 /* Save the completed message into the stack item */ \
647                 if (edata->targetfield) \
648                         pfree(edata->targetfield); \
649                 edata->targetfield = pstrdup(buf.data); \
650                 pfree(buf.data); \
651         }
652
653
654 /*
655  * errmsg --- add a primary error message text to the current error
656  *
657  * In addition to the usual %-escapes recognized by printf, "%m" in
658  * fmt is replaced by the error message for the caller's value of errno.
659  *
660  * Note: no newline is needed at the end of the fmt string, since
661  * ereport will provide one for the output methods that need it.
662  */
663 int
664 errmsg(const char *fmt,...)
665 {
666         ErrorData  *edata = &errordata[errordata_stack_depth];
667         MemoryContext oldcontext;
668
669         recursion_depth++;
670         CHECK_STACK_DEPTH();
671         oldcontext = MemoryContextSwitchTo(ErrorContext);
672
673         EVALUATE_MESSAGE(message, false);
674
675         MemoryContextSwitchTo(oldcontext);
676         recursion_depth--;
677         return 0;                                       /* return value does not matter */
678 }
679
680
681 /*
682  * errmsg_internal --- add a primary error message text to the current error
683  *
684  * This is exactly like errmsg() except that strings passed to errmsg_internal
685  * are customarily left out of the internationalization message dictionary.
686  * This should be used for "can't happen" cases that are probably not worth
687  * spending translation effort on.
688  */
689 int
690 errmsg_internal(const char *fmt,...)
691 {
692         ErrorData  *edata = &errordata[errordata_stack_depth];
693         MemoryContext oldcontext;
694
695         recursion_depth++;
696         CHECK_STACK_DEPTH();
697         oldcontext = MemoryContextSwitchTo(ErrorContext);
698
699         EVALUATE_MESSAGE(message, false);
700
701         MemoryContextSwitchTo(oldcontext);
702         recursion_depth--;
703         return 0;                                       /* return value does not matter */
704 }
705
706
707 /*
708  * errdetail --- add a detail error message text to the current error
709  */
710 int
711 errdetail(const char *fmt,...)
712 {
713         ErrorData  *edata = &errordata[errordata_stack_depth];
714         MemoryContext oldcontext;
715
716         recursion_depth++;
717         CHECK_STACK_DEPTH();
718         oldcontext = MemoryContextSwitchTo(ErrorContext);
719
720         EVALUATE_MESSAGE(detail, false);
721
722         MemoryContextSwitchTo(oldcontext);
723         recursion_depth--;
724         return 0;                                       /* return value does not matter */
725 }
726
727
728 /*
729  * errhint --- add a hint error message text to the current error
730  */
731 int
732 errhint(const char *fmt,...)
733 {
734         ErrorData  *edata = &errordata[errordata_stack_depth];
735         MemoryContext oldcontext;
736
737         recursion_depth++;
738         CHECK_STACK_DEPTH();
739         oldcontext = MemoryContextSwitchTo(ErrorContext);
740
741         EVALUATE_MESSAGE(hint, false);
742
743         MemoryContextSwitchTo(oldcontext);
744         recursion_depth--;
745         return 0;                                       /* return value does not matter */
746 }
747
748
749 /*
750  * errcontext --- add a context error message text to the current error
751  *
752  * Unlike other cases, multiple calls are allowed to build up a stack of
753  * context information.  We assume earlier calls represent more-closely-nested
754  * states.
755  */
756 int
757 errcontext(const char *fmt,...)
758 {
759         ErrorData  *edata = &errordata[errordata_stack_depth];
760         MemoryContext oldcontext;
761
762         recursion_depth++;
763         CHECK_STACK_DEPTH();
764         oldcontext = MemoryContextSwitchTo(ErrorContext);
765
766         EVALUATE_MESSAGE(context, true);
767
768         MemoryContextSwitchTo(oldcontext);
769         recursion_depth--;
770         return 0;                                       /* return value does not matter */
771 }
772
773
774 /*
775  * errfunction --- add reporting function name to the current error
776  *
777  * This is used when backwards compatibility demands that the function
778  * name appear in messages sent to old-protocol clients.  Note that the
779  * passed string is expected to be a non-freeable constant string.
780  */
781 int
782 errfunction(const char *funcname)
783 {
784         ErrorData  *edata = &errordata[errordata_stack_depth];
785
786         /* we don't bother incrementing recursion_depth */
787         CHECK_STACK_DEPTH();
788
789         edata->funcname = funcname;
790         edata->show_funcname = true;
791
792         return 0;                                       /* return value does not matter */
793 }
794
795 /*
796  * errposition --- add cursor position to the current error
797  */
798 int
799 errposition(int cursorpos)
800 {
801         ErrorData  *edata = &errordata[errordata_stack_depth];
802
803         /* we don't bother incrementing recursion_depth */
804         CHECK_STACK_DEPTH();
805
806         edata->cursorpos = cursorpos;
807
808         return 0;                                       /* return value does not matter */
809 }
810
811
812 /*
813  * elog_finish --- finish up for old-style API
814  *
815  * The elog() macro already called errstart, but with ERROR rather than
816  * the true elevel.
817  */
818 void
819 elog_finish(int elevel, const char *fmt,...)
820 {
821         ErrorData  *edata = &errordata[errordata_stack_depth];
822         MemoryContext oldcontext;
823
824         CHECK_STACK_DEPTH();
825
826         /*
827          * We need to redo errstart() because the elog macro had to call it
828          * with bogus elevel.
829          */
830         errordata_stack_depth--;
831         errno = edata->saved_errno;
832         if (!errstart(elevel, edata->filename, edata->lineno, edata->funcname))
833                 return;                                 /* nothing to do */
834
835         /*
836          * Format error message just like errmsg().
837          */
838         recursion_depth++;
839         oldcontext = MemoryContextSwitchTo(ErrorContext);
840
841         EVALUATE_MESSAGE(message, false);
842
843         MemoryContextSwitchTo(oldcontext);
844         recursion_depth--;
845
846         /*
847          * And let errfinish() finish up.
848          */
849         errfinish(0);
850 }
851
852
853 /*
854  * Initialization of error output file
855  */
856 void
857 DebugFileOpen(void)
858 {
859         int                     fd,
860                                 istty;
861
862         if (OutputFileName[0])
863         {
864                 /*
865                  * A debug-output file name was given.
866                  *
867                  * Make sure we can write the file, and find out if it's a tty.
868                  */
869                 if ((fd = open(OutputFileName, O_CREAT | O_APPEND | O_WRONLY,
870                                            0666)) < 0)
871                         ereport(FATAL,
872                                         (errcode_for_file_access(),
873                                    errmsg("could not open file \"%s\": %m", OutputFileName)));
874                 istty = isatty(fd);
875                 close(fd);
876
877                 /*
878                  * Redirect our stderr to the debug output file.
879                  */
880                 if (!freopen(OutputFileName, "a", stderr))
881                         ereport(FATAL,
882                                         (errcode_for_file_access(),
883                                          errmsg("could not reopen file \"%s\" as stderr: %m",
884                                                         OutputFileName)));
885
886                 /*
887                  * If the file is a tty and we're running under the postmaster,
888                  * try to send stdout there as well (if it isn't a tty then stderr
889                  * will block out stdout, so we may as well let stdout go wherever
890                  * it was going before).
891                  */
892                 if (istty && IsUnderPostmaster)
893                         if (!freopen(OutputFileName, "a", stdout))
894                                 ereport(FATAL,
895                                                 (errcode_for_file_access(),
896                                                  errmsg("could not reopen file \"%s\" as stdout: %m",
897                                                                 OutputFileName)));
898         }
899 }
900
901
902
903 #ifdef HAVE_SYSLOG
904
905 #ifndef PG_SYSLOG_LIMIT
906 #define PG_SYSLOG_LIMIT 128
907 #endif
908
909 /*
910  * Write a message line to syslog if the syslog option is set.
911  *
912  * Our problem here is that many syslog implementations don't handle
913  * long messages in an acceptable manner. While this function doesn't
914  * help that fact, it does work around by splitting up messages into
915  * smaller pieces.
916  */
917 static void
918 write_syslog(int level, const char *line)
919 {
920         static bool openlog_done = false;
921         static unsigned long seq = 0;
922         static int      syslog_fac = LOG_LOCAL0;
923
924         int                     len = strlen(line);
925
926         if (Use_syslog == 0)
927                 return;
928
929         if (!openlog_done)
930         {
931                 if (strcasecmp(Syslog_facility, "LOCAL0") == 0)
932                         syslog_fac = LOG_LOCAL0;
933                 if (strcasecmp(Syslog_facility, "LOCAL1") == 0)
934                         syslog_fac = LOG_LOCAL1;
935                 if (strcasecmp(Syslog_facility, "LOCAL2") == 0)
936                         syslog_fac = LOG_LOCAL2;
937                 if (strcasecmp(Syslog_facility, "LOCAL3") == 0)
938                         syslog_fac = LOG_LOCAL3;
939                 if (strcasecmp(Syslog_facility, "LOCAL4") == 0)
940                         syslog_fac = LOG_LOCAL4;
941                 if (strcasecmp(Syslog_facility, "LOCAL5") == 0)
942                         syslog_fac = LOG_LOCAL5;
943                 if (strcasecmp(Syslog_facility, "LOCAL6") == 0)
944                         syslog_fac = LOG_LOCAL6;
945                 if (strcasecmp(Syslog_facility, "LOCAL7") == 0)
946                         syslog_fac = LOG_LOCAL7;
947                 openlog(Syslog_ident, LOG_PID | LOG_NDELAY, syslog_fac);
948                 openlog_done = true;
949         }
950
951         /*
952          * We add a sequence number to each log message to suppress "same"
953          * messages.
954          */
955         seq++;
956
957         /* divide into multiple syslog() calls if message is too long */
958         /* or if the message contains embedded NewLine(s) '\n' */
959         if (len > PG_SYSLOG_LIMIT || strchr(line, '\n') != NULL)
960         {
961                 int                     chunk_nr = 0;
962
963                 while (len > 0)
964                 {
965                         char            buf[PG_SYSLOG_LIMIT + 1];
966                         int                     buflen;
967                         int                     i;
968
969                         /* if we start at a newline, move ahead one char */
970                         if (line[0] == '\n')
971                         {
972                                 line++;
973                                 len--;
974                                 continue;
975                         }
976
977                         strncpy(buf, line, PG_SYSLOG_LIMIT);
978                         buf[PG_SYSLOG_LIMIT] = '\0';
979                         if (strchr(buf, '\n') != NULL)
980                                 *strchr(buf, '\n') = '\0';
981
982                         buflen = strlen(buf);
983
984                         /* trim to multibyte letter boundary */
985                         buflen = pg_mbcliplen(buf, buflen, buflen);
986                         if (buflen <= 0)
987                                 return;
988                         buf[buflen] = '\0';
989
990                         /* already word boundary? */
991                         if (!isspace((unsigned char) line[buflen]) &&
992                                 line[buflen] != '\0')
993                         {
994                                 /* try to divide at word boundary */
995                                 i = buflen - 1;
996                                 while (i > 0 && !isspace((unsigned char) buf[i]))
997                                         i--;
998
999                                 if (i > 0)              /* else couldn't divide word boundary */
1000                                 {
1001                                         buflen = i;
1002                                         buf[i] = '\0';
1003                                 }
1004                         }
1005
1006                         chunk_nr++;
1007
1008                         syslog(level, "[%lu-%d] %s", seq, chunk_nr, buf);
1009                         line += buflen;
1010                         len -= buflen;
1011                 }
1012         }
1013         else
1014         {
1015                 /* message short enough */
1016                 syslog(level, "[%lu] %s", seq, line);
1017         }
1018 }
1019 #endif   /* HAVE_SYSLOG */
1020
1021 /*
1022  * Format tag info for log lines 
1023  */
1024 static const char * 
1025 log_line_prefix(void)
1026 {
1027
1028         /* static accumulator for line numbers */
1029         static int log_line_number = 0;
1030  
1031         /* space for option string + one of each option, plus some room to spare */
1032         /* Note: if more identifiers are built in this will have to increase */
1033         static char *result = NULL;
1034         int format_len = strlen(Log_line_prefix);
1035         int result_len = 2*NAMEDATALEN + format_len +120 ;
1036
1037         if (result == NULL)
1038                 result = malloc(result_len);
1039         result[0] = '\0';
1040
1041         if (format_len > 0)
1042         {
1043                 int i,j;
1044                 char * dbname = NULL;
1045                 char * username = NULL;
1046                 time_t stamp_time;
1047                 log_line_number++;
1048                 if (MyProcPort != NULL)
1049                 {
1050                         dbname  = MyProcPort->database_name;
1051                         username = MyProcPort->user_name;
1052                         if (dbname == NULL || *dbname == '\0')
1053                                 dbname = gettext("[unknown]");
1054                         if (username == NULL || *username == '\0')
1055                                 username = gettext("[unknown]");
1056                 }
1057
1058                 /*
1059                  * invariant through each iteration of this loop:
1060                  *  . j is the index of the trailing null on result
1061                  *  . result_len - j is the number of chars we have room for
1062                  *    including the trailing null
1063                  *  . there is room to write at least one more non-null char plus the
1064                  *    trailing null
1065                  */
1066                 for (i = 0, j=0; i < format_len && j < result_len-1; i++)
1067                 {
1068                         if(Log_line_prefix[i] != '%')
1069                         {
1070                                 /* literal char, just copy */
1071                                 result[j]=Log_line_prefix[i];
1072                                 j++;
1073                                 result[j] = '\0';
1074                                 continue;
1075                         }
1076                         else if (i == format_len - 1)
1077                         {
1078                                 /* format error - skip it */
1079                                 continue;
1080                         }
1081
1082                         /* go to char after '%' */
1083                         i++;
1084
1085                         /* in postmaster and friends, skip non-applicable options,
1086                          * stop if %x is seen
1087                          */
1088                         if (MyProcPort == NULL)
1089                         {
1090                                 if (Log_line_prefix[i] == 'x')
1091                                         break;
1092                                 if (strchr("udcsir",Log_line_prefix[i]) != NULL)
1093                                         continue;
1094                         }
1095
1096                         /* process the option */
1097                         switch (Log_line_prefix[i])
1098                         {
1099                                 case 'u': 
1100                                         j += snprintf(result+j,result_len-j,"%s",username);
1101                                         break;
1102                                 case 'd': 
1103                                         j += snprintf(result+j,result_len-j,"%s",dbname);
1104                                         break;
1105                                 case 'c':
1106                                         j += snprintf(result+j,result_len-j,"%lx.%lx",
1107                                                                   (long)(MyProcPort->session_start.tv_sec),
1108                                                                   (long)MyProcPid);
1109                                         break;
1110                                 case 'p':
1111                                         j += snprintf(result+j,result_len-j,"%ld",(long)MyProcPid);
1112                                         break;
1113                                 case 'l':
1114                                         j += snprintf(result+j,result_len-j,"%d",log_line_number);
1115                                         break;
1116                                 case 't':
1117                                         stamp_time = time(NULL);
1118                                         j += strftime(result+j, result_len-j, "%Y-%m-%d %H:%M:%S",
1119                                                          localtime(&stamp_time));
1120                                         break;
1121                                 case 's':
1122                                         j += strftime(result+j, result_len-j, "%Y-%m-%d %H:%M:%S",
1123                                                          localtime(&(MyProcPort->session_start.tv_sec)));
1124                                         break;
1125                                 case 'i':
1126                                         j += snprintf(result+j,result_len-j,"%s",
1127                                                                   MyProcPort->commandTag);
1128                                         break;
1129                                 case 'r':
1130                                         j += snprintf(result+j,result_len-j,"%s",
1131                                                                   MyProcPort->remote_host);
1132                                         if (strlen(MyProcPort->remote_port) > 0)
1133                                                 j += snprintf(result+j,result_len-j,"(%s)",
1134                                                                           MyProcPort->remote_port);
1135                                         break;
1136                                 case 'x': 
1137                                         /* non-postmaster case - just ignore */
1138                                         break;
1139                                 case '%': 
1140                                         result[j] = '%';
1141                                         j++;
1142                                         result[j] = '\0';
1143                                         break;
1144                                 default:
1145                                         /* format error - skip it */
1146                                         break;
1147                         }
1148                 }
1149         }
1150         return result;
1151 }
1152
1153
1154 /*
1155  * Write error report to server's log
1156  */
1157 static void
1158 send_message_to_server_log(ErrorData *edata)
1159 {
1160         StringInfoData buf;
1161
1162         initStringInfo(&buf);
1163
1164         appendStringInfo(&buf, "%s%s:  ", 
1165                                          log_line_prefix(), error_severity(edata->elevel));
1166
1167         if (Log_error_verbosity >= PGERROR_VERBOSE)
1168         {
1169                 /* unpack MAKE_SQLSTATE code */
1170                 char            tbuf[12];
1171                 int                     ssval;
1172                 int                     i;
1173
1174                 ssval = edata->sqlerrcode;
1175                 for (i = 0; i < 5; i++)
1176                 {
1177                         tbuf[i] = PGUNSIXBIT(ssval);
1178                         ssval >>= 6;
1179                 }
1180                 tbuf[i] = '\0';
1181                 appendStringInfo(&buf, "%s: ", tbuf);
1182         }
1183
1184         if (edata->message)
1185                 append_with_tabs(&buf, edata->message);
1186         else
1187                 append_with_tabs(&buf, gettext("missing error text"));
1188
1189         if (edata->cursorpos > 0)
1190                 appendStringInfo(&buf, gettext(" at character %d"), edata->cursorpos);
1191
1192         appendStringInfoChar(&buf, '\n');
1193
1194         if (Log_error_verbosity >= PGERROR_DEFAULT)
1195         {
1196                 if (edata->detail)
1197                 {
1198                         appendStringInfoString(&buf, log_line_prefix() );
1199                         appendStringInfoString(&buf, gettext("DETAIL:  "));
1200                         append_with_tabs(&buf, edata->detail);
1201                         appendStringInfoChar(&buf, '\n');
1202                 }
1203                 if (edata->hint)
1204                 {
1205                         appendStringInfoString(&buf, log_line_prefix() );
1206                         appendStringInfoString(&buf, gettext("HINT:  "));
1207                         append_with_tabs(&buf, edata->hint);
1208                         appendStringInfoChar(&buf, '\n');
1209                 }
1210                 if (edata->context)
1211                 {
1212                         appendStringInfoString(&buf, log_line_prefix() );
1213                         appendStringInfoString(&buf, gettext("CONTEXT:  "));
1214                         append_with_tabs(&buf, edata->context);
1215                         appendStringInfoChar(&buf, '\n');
1216                 }
1217                 if (Log_error_verbosity >= PGERROR_VERBOSE)
1218                 {
1219                         /* assume no newlines in funcname or filename... */
1220                         if (edata->funcname && edata->filename)
1221                                 appendStringInfo(&buf, gettext("%sLOCATION:  %s, %s:%d\n"),
1222                                                                  log_line_prefix(),
1223                                                                  edata->funcname, edata->filename,
1224                                                                  edata->lineno);
1225                         else if (edata->filename)
1226                                 appendStringInfo(&buf, gettext("%sLOCATION:  %s:%d\n"),
1227                                                                  log_line_prefix(),
1228                                                                  edata->filename, edata->lineno);
1229                 }
1230         }
1231
1232         /*
1233          * If the user wants the query that generated this error logged, do it.
1234          */
1235         if (edata->elevel >= log_min_error_statement && debug_query_string != NULL)
1236         {
1237                 appendStringInfoString(&buf, log_line_prefix() );
1238                 appendStringInfoString(&buf, gettext("STATEMENT:  "));
1239                 append_with_tabs(&buf, debug_query_string);
1240                 appendStringInfoChar(&buf, '\n');
1241         }
1242
1243
1244 #ifdef HAVE_SYSLOG
1245         /* Write to syslog, if enabled */
1246         if (Use_syslog >= 1)
1247         {
1248                 int                     syslog_level;
1249
1250                 switch (edata->elevel)
1251                 {
1252                         case DEBUG5:
1253                         case DEBUG4:
1254                         case DEBUG3:
1255                         case DEBUG2:
1256                         case DEBUG1:
1257                                 syslog_level = LOG_DEBUG;
1258                                 break;
1259                         case LOG:
1260                         case COMMERROR:
1261                         case INFO:
1262                                 syslog_level = LOG_INFO;
1263                                 break;
1264                         case NOTICE:
1265                         case WARNING:
1266                                 syslog_level = LOG_NOTICE;
1267                                 break;
1268                         case ERROR:
1269                                 syslog_level = LOG_WARNING;
1270                                 break;
1271                         case FATAL:
1272                                 syslog_level = LOG_ERR;
1273                                 break;
1274                         case PANIC:
1275                         default:
1276                                 syslog_level = LOG_CRIT;
1277                                 break;
1278                 }
1279
1280                 write_syslog(syslog_level, buf.data);
1281         }
1282 #endif   /* HAVE_SYSLOG */
1283
1284         /* Write to stderr, if enabled */
1285         if (Use_syslog <= 1 || whereToSendOutput == Debug)
1286         {
1287                 /*
1288                  * Timestamp and PID are only used for stderr output --- we assume
1289                  * the syslog daemon will supply them for us in the other case.
1290                  */
1291                 fprintf(stderr, "%s",buf.data);
1292         }
1293
1294         pfree(buf.data);
1295 }
1296
1297
1298 /*
1299  * Write error report to client
1300  */
1301 static void
1302 send_message_to_frontend(ErrorData *edata)
1303 {
1304         StringInfoData msgbuf;
1305
1306         /* 'N' (Notice) is for nonfatal conditions, 'E' is for errors */
1307         pq_beginmessage(&msgbuf, (edata->elevel < ERROR) ? 'N' : 'E');
1308
1309         if (PG_PROTOCOL_MAJOR(FrontendProtocol) >= 3)
1310         {
1311                 /* New style with separate fields */
1312                 char            tbuf[12];
1313                 int                     ssval;
1314                 int                     i;
1315
1316                 pq_sendbyte(&msgbuf, PG_DIAG_SEVERITY);
1317                 pq_sendstring(&msgbuf, error_severity(edata->elevel));
1318
1319                 /* unpack MAKE_SQLSTATE code */
1320                 ssval = edata->sqlerrcode;
1321                 for (i = 0; i < 5; i++)
1322                 {
1323                         tbuf[i] = PGUNSIXBIT(ssval);
1324                         ssval >>= 6;
1325                 }
1326                 tbuf[i] = '\0';
1327
1328                 pq_sendbyte(&msgbuf, PG_DIAG_SQLSTATE);
1329                 pq_sendstring(&msgbuf, tbuf);
1330
1331                 /* M field is required per protocol, so always send something */
1332                 pq_sendbyte(&msgbuf, PG_DIAG_MESSAGE_PRIMARY);
1333                 if (edata->message)
1334                         pq_sendstring(&msgbuf, edata->message);
1335                 else
1336                         pq_sendstring(&msgbuf, gettext("missing error text"));
1337
1338                 if (edata->detail)
1339                 {
1340                         pq_sendbyte(&msgbuf, PG_DIAG_MESSAGE_DETAIL);
1341                         pq_sendstring(&msgbuf, edata->detail);
1342                 }
1343
1344                 if (edata->hint)
1345                 {
1346                         pq_sendbyte(&msgbuf, PG_DIAG_MESSAGE_HINT);
1347                         pq_sendstring(&msgbuf, edata->hint);
1348                 }
1349
1350                 if (edata->context)
1351                 {
1352                         pq_sendbyte(&msgbuf, PG_DIAG_CONTEXT);
1353                         pq_sendstring(&msgbuf, edata->context);
1354                 }
1355
1356                 if (edata->cursorpos > 0)
1357                 {
1358                         snprintf(tbuf, sizeof(tbuf), "%d", edata->cursorpos);
1359                         pq_sendbyte(&msgbuf, PG_DIAG_STATEMENT_POSITION);
1360                         pq_sendstring(&msgbuf, tbuf);
1361                 }
1362
1363                 if (edata->filename)
1364                 {
1365                         pq_sendbyte(&msgbuf, PG_DIAG_SOURCE_FILE);
1366                         pq_sendstring(&msgbuf, edata->filename);
1367                 }
1368
1369                 if (edata->lineno > 0)
1370                 {
1371                         snprintf(tbuf, sizeof(tbuf), "%d", edata->lineno);
1372                         pq_sendbyte(&msgbuf, PG_DIAG_SOURCE_LINE);
1373                         pq_sendstring(&msgbuf, tbuf);
1374                 }
1375
1376                 if (edata->funcname)
1377                 {
1378                         pq_sendbyte(&msgbuf, PG_DIAG_SOURCE_FUNCTION);
1379                         pq_sendstring(&msgbuf, edata->funcname);
1380                 }
1381
1382                 pq_sendbyte(&msgbuf, '\0');             /* terminator */
1383         }
1384         else
1385         {
1386                 /* Old style --- gin up a backwards-compatible message */
1387                 StringInfoData buf;
1388
1389                 initStringInfo(&buf);
1390
1391                 appendStringInfo(&buf, "%s:  ", error_severity(edata->elevel));
1392
1393                 if (edata->show_funcname && edata->funcname)
1394                         appendStringInfo(&buf, "%s: ", edata->funcname);
1395
1396                 if (edata->message)
1397                         appendStringInfoString(&buf, edata->message);
1398                 else
1399                         appendStringInfoString(&buf, gettext("missing error text"));
1400
1401                 if (edata->cursorpos > 0)
1402                         appendStringInfo(&buf, gettext(" at character %d"),
1403                                                          edata->cursorpos);
1404
1405                 appendStringInfoChar(&buf, '\n');
1406
1407                 pq_sendstring(&msgbuf, buf.data);
1408
1409                 pfree(buf.data);
1410         }
1411
1412         pq_endmessage(&msgbuf);
1413
1414         /*
1415          * This flush is normally not necessary, since postgres.c will flush
1416          * out waiting data when control returns to the main loop. But it
1417          * seems best to leave it here, so that the client has some clue what
1418          * happened if the backend dies before getting back to the main loop
1419          * ... error/notice messages should not be a performance-critical path
1420          * anyway, so an extra flush won't hurt much ...
1421          */
1422         pq_flush();
1423 }
1424
1425
1426 /*
1427  * Support routines for formatting error messages.
1428  */
1429
1430
1431 /*
1432  * expand_fmt_string --- process special format codes in a format string
1433  *
1434  * We must replace %m with the appropriate strerror string, since vsnprintf
1435  * won't know what to do with it.
1436  *
1437  * The result is a palloc'd string.
1438  */
1439 static char *
1440 expand_fmt_string(const char *fmt, ErrorData *edata)
1441 {
1442         StringInfoData buf;
1443         const char *cp;
1444
1445         initStringInfo(&buf);
1446
1447         for (cp = fmt; *cp; cp++)
1448         {
1449                 if (cp[0] == '%' && cp[1] != '\0')
1450                 {
1451                         cp++;
1452                         if (*cp == 'm')
1453                         {
1454                                 /*
1455                                  * Replace %m by system error string.  If there are any
1456                                  * %'s in the string, we'd better double them so that
1457                                  * vsnprintf won't misinterpret.
1458                                  */
1459                                 const char *cp2;
1460
1461                                 cp2 = useful_strerror(edata->saved_errno);
1462                                 for (; *cp2; cp2++)
1463                                 {
1464                                         if (*cp2 == '%')
1465                                                 appendStringInfoCharMacro(&buf, '%');
1466                                         appendStringInfoCharMacro(&buf, *cp2);
1467                                 }
1468                         }
1469                         else
1470                         {
1471                                 /* copy % and next char --- this avoids trouble with %%m */
1472                                 appendStringInfoCharMacro(&buf, '%');
1473                                 appendStringInfoCharMacro(&buf, *cp);
1474                         }
1475                 }
1476                 else
1477                         appendStringInfoCharMacro(&buf, *cp);
1478         }
1479
1480         return buf.data;
1481 }
1482
1483
1484 /*
1485  * A slightly cleaned-up version of strerror()
1486  */
1487 static const char *
1488 useful_strerror(int errnum)
1489 {
1490         /* this buffer is only used if errno has a bogus value */
1491         static char errorstr_buf[48];
1492         const char *str;
1493
1494         str = strerror(errnum);
1495
1496         /*
1497          * Some strerror()s return an empty string for out-of-range errno.
1498          * This is ANSI C spec compliant, but not exactly useful.
1499          */
1500         if (str == NULL || *str == '\0')
1501         {
1502                 /*
1503                  * translator: This string will be truncated at 47 characters
1504                  * expanded.
1505                  */
1506                 snprintf(errorstr_buf, sizeof(errorstr_buf),
1507                                  gettext("operating system error %d"), errnum);
1508                 str = errorstr_buf;
1509         }
1510
1511         return str;
1512 }
1513
1514
1515 /*
1516  * error_severity --- get localized string representing elevel
1517  */
1518 static const char *
1519 error_severity(int elevel)
1520 {
1521         const char *prefix;
1522
1523         switch (elevel)
1524         {
1525                 case DEBUG1:
1526                 case DEBUG2:
1527                 case DEBUG3:
1528                 case DEBUG4:
1529                 case DEBUG5:
1530                         prefix = gettext("DEBUG");
1531                         break;
1532                 case LOG:
1533                 case COMMERROR:
1534                         prefix = gettext("LOG");
1535                         break;
1536                 case INFO:
1537                         prefix = gettext("INFO");
1538                         break;
1539                 case NOTICE:
1540                         prefix = gettext("NOTICE");
1541                         break;
1542                 case WARNING:
1543                         prefix = gettext("WARNING");
1544                         break;
1545                 case ERROR:
1546                         prefix = gettext("ERROR");
1547                         break;
1548                 case FATAL:
1549                         prefix = gettext("FATAL");
1550                         break;
1551                 case PANIC:
1552                         prefix = gettext("PANIC");
1553                         break;
1554                 default:
1555                         prefix = "???";
1556                         break;
1557         }
1558
1559         return prefix;
1560 }
1561
1562
1563 /*
1564  *      append_with_tabs
1565  *
1566  *      Append the string to the StringInfo buffer, inserting a tab after any
1567  *      newline.
1568  */
1569 static void
1570 append_with_tabs(StringInfo buf, const char *str)
1571 {
1572         char    ch;
1573
1574         while ((ch = *str++) != '\0')
1575         {
1576                 appendStringInfoCharMacro(buf, ch);
1577                 if (ch == '\n')
1578                         appendStringInfoCharMacro(buf, '\t');
1579         }
1580 }