~ubuntu-branches/ubuntu/oneiric/postgresql-9.1/oneiric-security

« back to all changes in this revision

Viewing changes to src/backend/utils/error/elog.c

  • Committer: Bazaar Package Importer
  • Author(s): Martin Pitt
  • Date: 2011-05-11 10:41:53 UTC
  • Revision ID: james.westby@ubuntu.com-20110511104153-psbh2o58553fv1m0
Tags: upstream-9.1~beta1
ImportĀ upstreamĀ versionĀ 9.1~beta1

Show diffs side-by-side

added added

removed removed

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