]> granicus.if.org Git - postgresql/blob - src/bin/psql/common.c
If the password prompt goes to stderr, then the trailing newline should
[postgresql] / src / bin / psql / common.c
1 /*
2  * psql - the PostgreSQL interactive terminal
3  *
4  * Copyright 2000 by PostgreSQL Global Development Group
5  *
6  * $Header: /cvsroot/pgsql/src/bin/psql/common.c,v 1.32 2001/04/15 00:43:37 petere Exp $
7  */
8 #include "postgres_fe.h"
9
10 #include "common.h"
11
12 #include <errno.h>
13 #include <stdarg.h>
14 #ifdef HAVE_TERMIOS_H
15 #include <termios.h>
16 #endif
17 #ifndef HAVE_STRDUP
18 #include <strdup.h>
19 #endif
20 #include <signal.h>
21 #ifndef WIN32
22 #include <unistd.h>                             /* for write() */
23 #include <setjmp.h>
24 #else
25 #include <io.h>                                 /* for _write() */
26 #include <win32.h>
27 #endif
28
29 #include "libpq-fe.h"
30 #include "pqsignal.h"
31
32 #include "settings.h"
33 #include "variables.h"
34 #include "copy.h"
35 #include "prompt.h"
36 #include "print.h"
37 #include "mainloop.h"
38
39
40 /*
41  * "Safe" wrapper around strdup()
42  */
43 char *
44 xstrdup(const char *string)
45 {
46         char       *tmp;
47
48         if (!string)
49         {
50                 fprintf(stderr, "%s: xstrdup: cannot duplicate null pointer (internal error)\n",
51                                 pset.progname);
52                 exit(EXIT_FAILURE);
53         }
54         tmp = strdup(string);
55         if (!tmp)
56         {
57                 psql_error("out of memory\n");
58                 exit(EXIT_FAILURE);
59         }
60         return tmp;
61 }
62
63
64
65 /*
66  * setQFout
67  * -- handler for -o command line option and \o command
68  *
69  * Tries to open file fname (or pipe if fname starts with '|')
70  * and stores the file handle in pset)
71  * Upon failure, sets stdout and returns false.
72  */
73 bool
74 setQFout(const char *fname)
75 {
76         bool            status = true;
77
78         /* Close old file/pipe */
79         if (pset.queryFout && pset.queryFout != stdout && pset.queryFout != stderr)
80         {
81                 if (pset.queryFoutPipe)
82                         pclose(pset.queryFout);
83                 else
84                         fclose(pset.queryFout);
85         }
86
87         /* If no filename, set stdout */
88         if (!fname || fname[0] == '\0')
89         {
90                 pset.queryFout = stdout;
91                 pset.queryFoutPipe = false;
92         }
93         else if (*fname == '|')
94         {
95                 pset.queryFout = popen(fname + 1, "w");
96                 pset.queryFoutPipe = true;
97         }
98         else
99         {
100                 pset.queryFout = fopen(fname, "w");
101                 pset.queryFoutPipe = false;
102         }
103
104         if (!(pset.queryFout))
105         {
106                 psql_error("%s: %s\n", fname, strerror(errno));
107                 pset.queryFout = stdout;
108                 pset.queryFoutPipe = false;
109                 status = false;
110         }
111
112         /* Direct signals */
113 #ifndef WIN32
114         if (pset.queryFoutPipe)
115                 pqsignal(SIGPIPE, SIG_IGN);
116         else
117                 pqsignal(SIGPIPE, SIG_DFL);
118 #endif
119
120         return status;
121 }
122
123
124
125 /*
126  * Error reporting for scripts. Errors should look like
127  *       psql:filename:lineno: message
128  *
129  */
130 void
131 psql_error(const char *fmt,...)
132 {
133         va_list         ap;
134
135         fflush(stdout);
136         if (pset.queryFout != stdout)
137                 fflush(pset.queryFout);
138
139         if (pset.inputfile)
140                 fprintf(stderr, "%s:%s:%u: ", pset.progname, pset.inputfile, pset.lineno);
141         va_start(ap, fmt);
142         vfprintf(stderr, fmt, ap);
143         va_end(ap);
144 }
145
146
147
148 /*
149  * for backend NOTICES
150  */
151 void
152 NoticeProcessor(void *arg, const char *message)
153 {
154         (void) arg;                                     /* not used */
155         psql_error("%s", message);
156 }
157
158
159
160 /*
161  * simple_prompt
162  *
163  * Generalized function especially intended for reading in usernames and
164  * password interactively. Reads from stdin.
165  *
166  * prompt:              The prompt to print
167  * maxlen:              How many characters to accept
168  * echo:                Set to false if you want to hide what is entered (for passwords)
169  *
170  * Returns a malloc()'ed string with the input (w/o trailing newline).
171  */
172 static bool prompt_state;
173
174 char *
175 simple_prompt(const char *prompt, int maxlen, bool echo)
176 {
177         int                     length;
178         char       *destination;
179
180 #ifdef HAVE_TERMIOS_H
181         struct termios t_orig,
182                                 t;
183
184 #endif
185
186         destination = (char *) malloc(maxlen + 2);
187         if (!destination)
188                 return NULL;
189         if (prompt)
190                 fputs(prompt, stderr);
191
192         prompt_state = true;
193
194 #ifdef HAVE_TERMIOS_H
195         if (!echo)
196         {
197                 tcgetattr(0, &t);
198                 t_orig = t;
199                 t.c_lflag &= ~ECHO;
200                 tcsetattr(0, TCSADRAIN, &t);
201         }
202 #endif
203
204         if (fgets(destination, maxlen, stdin) == NULL)
205                 destination[0] = '\0';
206
207 #ifdef HAVE_TERMIOS_H
208         if (!echo)
209         {
210                 tcsetattr(0, TCSADRAIN, &t_orig);
211                 fputs("\n", stderr);
212         }
213 #endif
214
215         prompt_state = false;
216
217         length = strlen(destination);
218         if (length > 0 && destination[length - 1] != '\n')
219         {
220                 /* eat rest of the line */
221                 char            buf[128];
222                 int                     buflen;
223
224                 do
225                 {
226                         if (fgets(buf, sizeof(buf), stdin) == NULL)
227                                 break;
228                         buflen = strlen(buf);
229                 } while (buflen > 0 && buf[buflen - 1] != '\n');
230         }
231
232         if (length > 0 && destination[length - 1] == '\n')
233                 /* remove trailing newline */
234                 destination[length - 1] = '\0';
235
236         return destination;
237 }
238
239
240
241 /*
242  * Code to support query cancellation
243  *
244  * Before we start a query, we enable a SIGINT signal catcher that sends a
245  * cancel request to the backend. Note that sending the cancel directly from
246  * the signal handler is safe because PQrequestCancel() is written to make it
247  * so. We use write() to print to stdout because it's better to use simple
248  * facilities in a signal handler.
249  */
250
251 PGconn     *cancelConn;
252 volatile bool cancel_pressed;
253
254 #ifndef WIN32
255
256 #define write_stderr(String) write(fileno(stderr), String, strlen(String))
257
258 void
259 handle_sigint(SIGNAL_ARGS)
260 {
261         int                     save_errno = errno;
262
263         /* Don't muck around if copying in or prompting for a password. */
264         if ((copy_in_state && pset.cur_cmd_interactive) || prompt_state)
265                 return;
266
267         if (cancelConn == NULL)
268                 siglongjmp(main_loop_jmp, 1);
269
270         cancel_pressed = true;
271
272         if (PQrequestCancel(cancelConn))
273                 write_stderr("Cancel request sent\n");
274         else
275         {
276                 write_stderr("Could not send cancel request: ");
277                 write_stderr(PQerrorMessage(cancelConn));
278         }
279         errno = save_errno;                     /* just in case the write changed it */
280 }
281
282 #endif   /* not WIN32 */
283
284
285 /*
286  * PSQLexec
287  *
288  * This is the way to send "backdoor" queries (those not directly entered
289  * by the user). It is subject to -E but not -e.
290  */
291 PGresult   *
292 PSQLexec(const char *query)
293 {
294         PGresult   *res;
295         const char *var;
296
297         if (!pset.db)
298         {
299                 psql_error("You are currently not connected to a database.\n");
300                 return NULL;
301         }
302
303         var = GetVariable(pset.vars, "ECHO_HIDDEN");
304         if (var)
305         {
306                 printf("********* QUERY *********\n%s\n*************************\n\n", query);
307                 fflush(stdout);
308         }
309
310         if (var && strcmp(var, "noexec") == 0)
311                 return NULL;
312
313         cancelConn = pset.db;
314         res = PQexec(pset.db, query);
315         if (PQresultStatus(res) == PGRES_COPY_IN)
316                 copy_in_state = true;
317         /* keep cancel connection for copy out state */
318         if (PQresultStatus(res) != PGRES_COPY_OUT)
319                 cancelConn = NULL;
320
321         if (res && (PQresultStatus(res) == PGRES_COMMAND_OK ||
322                                 PQresultStatus(res) == PGRES_TUPLES_OK ||
323                                 PQresultStatus(res) == PGRES_COPY_IN ||
324                                 PQresultStatus(res) == PGRES_COPY_OUT)
325                 )
326                 return res;
327         else
328         {
329                 psql_error("%s", PQerrorMessage(pset.db));
330                 PQclear(res);
331
332                 if (PQstatus(pset.db) == CONNECTION_BAD)
333                 {
334                         if (!pset.cur_cmd_interactive)
335                         {
336                                 psql_error("connection to server was lost\n");
337                                 exit(EXIT_BADCONN);
338                         }
339                         fputs("The connection to the server was lost. Attempting reset: ", stderr);
340                         PQreset(pset.db);
341                         if (PQstatus(pset.db) == CONNECTION_BAD)
342                         {
343                                 fputs("Failed.\n", stderr);
344                                 PQfinish(pset.db);
345                                 pset.db = NULL;
346                                 SetVariable(pset.vars, "DBNAME", NULL);
347                                 SetVariable(pset.vars, "HOST", NULL);
348                                 SetVariable(pset.vars, "PORT", NULL);
349                                 SetVariable(pset.vars, "USER", NULL);
350                                 SetVariable(pset.vars, "ENCODING", NULL);
351                         }
352                         else
353                                 fputs("Succeeded.\n", stderr);
354                 }
355
356                 return NULL;
357         }
358 }
359
360
361
362 /*
363  * SendQuery: send the query string to the backend
364  * (and print out results)
365  *
366  * Note: This is the "front door" way to send a query. That is, use it to
367  * send queries actually entered by the user. These queries will be subject to
368  * single step mode.
369  * To send "back door" queries (generated by slash commands, etc.) in a
370  * controlled way, use PSQLexec().
371  *
372  * Returns true if the query executed successfully, false otherwise.
373  */
374 bool
375 SendQuery(const char *query)
376 {
377         bool            success = false;
378         PGresult   *results;
379         PGnotify   *notify;
380
381         if (!pset.db)
382         {
383                 psql_error("You are currently not connected to a database.\n");
384                 return false;
385         }
386
387         if (GetVariableBool(pset.vars, "SINGLESTEP"))
388         {
389                 char            buf[3];
390
391                 printf("***(Single step mode: Verify query)*********************************************\n"
392                            "%s\n"
393                            "***(press return to proceed or enter x and return to cancel)********************\n",
394                            query);
395                 fflush(stdout);
396                 if (fgets(buf, sizeof(buf), stdin) != NULL)
397                         if (buf[0] == 'x')
398                                 return false;
399         }
400         else
401         {
402                 const char *var = GetVariable(pset.vars, "ECHO");
403
404                 if (var && strncmp(var, "queries", strlen(var)) == 0)
405                         puts(query);
406         }
407
408         cancelConn = pset.db;
409         results = PQexec(pset.db, query);
410         if (PQresultStatus(results) == PGRES_COPY_IN)
411                 copy_in_state = true;
412         /* keep cancel connection for copy out state */
413         if (PQresultStatus(results) != PGRES_COPY_OUT)
414                 cancelConn = NULL;
415
416         if (results == NULL)
417         {
418                 fputs(PQerrorMessage(pset.db), pset.queryFout);
419                 success = false;
420         }
421         else
422         {
423                 switch (PQresultStatus(results))
424                 {
425                         case PGRES_TUPLES_OK:
426                                 /* write output to \g argument, if any */
427                                 if (pset.gfname)
428                                 {
429                                         FILE       *queryFout_copy = pset.queryFout;
430                                         bool            queryFoutPipe_copy = pset.queryFoutPipe;
431
432                                         pset.queryFout = stdout;        /* so it doesn't get
433                                                                                                  * closed */
434
435                                         /* open file/pipe */
436                                         if (!setQFout(pset.gfname))
437                                         {
438                                                 pset.queryFout = queryFout_copy;
439                                                 pset.queryFoutPipe = queryFoutPipe_copy;
440                                                 success = false;
441                                                 break;
442                                         }
443
444                                         printQuery(results, &pset.popt, pset.queryFout);
445
446                                         /* close file/pipe, restore old setting */
447                                         setQFout(NULL);
448
449                                         pset.queryFout = queryFout_copy;
450                                         pset.queryFoutPipe = queryFoutPipe_copy;
451
452                                         free(pset.gfname);
453                                         pset.gfname = NULL;
454
455                                         success = true;
456                                 }
457                                 else
458                                 {
459                                         printQuery(results, &pset.popt, pset.queryFout);
460                                         success = true;
461                                 }
462                                 break;
463                         case PGRES_EMPTY_QUERY:
464                                 success = true;
465                                 break;
466                         case PGRES_COMMAND_OK:
467                                 {
468                                         char            buf[10];
469
470                                         success = true;
471                                         sprintf(buf, "%u", (unsigned int) PQoidValue(results));
472                                         if (!QUIET())
473                                                 fprintf(pset.queryFout, "%s\n", PQcmdStatus(results));
474                                         SetVariable(pset.vars, "LASTOID", buf);
475                                         break;
476                                 }
477                         case PGRES_COPY_OUT:
478                                 success = handleCopyOut(pset.db, pset.queryFout);
479                                 break;
480
481                         case PGRES_COPY_IN:
482                                 if (pset.cur_cmd_interactive && !QUIET())
483                                         puts("Enter data to be copied followed by a newline.\n"
484                                                  "End with a backslash and a period on a line by itself.");
485
486                                 success = handleCopyIn(pset.db, pset.cur_cmd_source,
487                                                                            pset.cur_cmd_interactive ? get_prompt(PROMPT_COPY) : NULL);
488                                 break;
489
490                         case PGRES_NONFATAL_ERROR:
491                         case PGRES_FATAL_ERROR:
492                         case PGRES_BAD_RESPONSE:
493                                 success = false;
494                                 psql_error("%s", PQerrorMessage(pset.db));
495                                 break;
496                 }
497
498                 fflush(pset.queryFout);
499
500                 if (PQstatus(pset.db) == CONNECTION_BAD)
501                 {
502                         if (!pset.cur_cmd_interactive)
503                         {
504                                 psql_error("connection to server was lost\n");
505                                 exit(EXIT_BADCONN);
506                         }
507                         fputs("The connection to the server was lost. Attempting reset: ", stderr);
508                         PQreset(pset.db);
509                         if (PQstatus(pset.db) == CONNECTION_BAD)
510                         {
511                                 fputs("Failed.\n", stderr);
512                                 PQfinish(pset.db);
513                                 PQclear(results);
514                                 pset.db = NULL;
515                                 SetVariable(pset.vars, "DBNAME", NULL);
516                                 SetVariable(pset.vars, "HOST", NULL);
517                                 SetVariable(pset.vars, "PORT", NULL);
518                                 SetVariable(pset.vars, "USER", NULL);
519                                 SetVariable(pset.vars, "ENCODING", NULL);
520                                 return false;
521                         }
522                         else
523                                 fputs("Succeeded.\n", stderr);
524                 }
525
526                 /* check for asynchronous notification returns */
527                 while ((notify = PQnotifies(pset.db)) != NULL)
528                 {
529                         fprintf(pset.queryFout, "Asynchronous NOTIFY '%s' from backend with pid '%d' received.\n",
530                                         notify->relname, notify->be_pid);
531                         free(notify);
532                         fflush(pset.queryFout);
533                 }
534
535                 if (results)
536                         PQclear(results);
537         }
538
539         return success;
540 }