1 /*-------------------------------------------------------------------------
4 * functions related to setting up a connection to the backend
6 * Copyright (c) 1994, Regents of the University of California
10 * $Header: /cvsroot/pgsql/src/interfaces/libpq/fe-connect.c,v 1.21 1996/11/26 07:38:55 bryanh Exp $
12 *-------------------------------------------------------------------------
16 #include <sys/types.h>
17 #include <sys/socket.h>
26 #include <ctype.h> /* for isspace() */
29 #include "libpq/pqcomm.h" /* for decls of MsgType, PacketBuf, StartupInfo */
37 #if defined(ultrix4) || defined(next)
38 /* ultrix is lame and doesn't have strdup in libc for some reason */
39 /* [TRH] So doesn't NEXTSTEP. But whaddaya expect for a non-ANSI
40 standard function? (My, my. Touchy today, are we?) */
42 strdup(const char *string)
46 if ((nstr = malloc(strlen(string)+1)) != NULL)
52 /* use a local version instead of the one found in pqpacket.c */
53 static ConnStatusType connectDB(PGconn *conn);
55 static int packetSend(Port *port, PacketBuf *buf, PacketLen len,
57 static void startup2PacketBuf(StartupInfo* s, PacketBuf* res);
58 static void freePGconn(PGconn *conn);
59 static void closePGconn(PGconn *conn);
60 static int conninfo_parse(const char *conninfo, char *errorMessage);
61 static char *conninfo_getval(char *keyword);
62 static void conninfo_free(void);
64 #define NOTIFYLIST_INITIAL_SIZE 10
65 #define NOTIFYLIST_GROWBY 10
69 * Definition of the conninfo parameters and their fallback resources.
70 * If Environment-Var and Compiled-in are specified as NULL, no
71 * fallback is available. If after all no value can be determined
72 * for an option, an error is returned.
74 * The values for dbname and user are treated special in conninfo_parse.
75 * If the Compiled-in resource is specified as a NULL value, the
76 * user is determined by fe_getauthname() and for dbname the user
79 * The Label and Disp-Char entries are provided for applications that
80 * want to use PQconndefaults() to create a generic database connection
81 * dialog. Disp-Char is defined as follows:
82 * "" Normal input field
85 static PQconninfoOption PQconninfoOptions[] = {
86 /* ----------------------------------------------------------------- */
87 /* Option-name Environment-Var Compiled-in Current value */
89 /* ----------------- --------------- --------------- --------------- */
90 { "user", "PGUSER", NULL, NULL,
91 "Database-User", "", 20 },
93 { "dbname", "PGDATABASE", NULL, NULL,
94 "Database-Name", "", 20 },
96 { "host", "PGHOST", DefaultHost, NULL,
97 "Database-Host", "", 40 },
99 { "port", "PGPORT", DEF_PGPORT, NULL,
100 "Database-Port", "", 6 },
102 { "tty", "PGTTY", DefaultTty, NULL,
103 "Backend-Debug-TTY", "D", 40 },
105 { "options", "PGOPTIONS", DefaultOption, NULL,
106 "Backend-Debug-Options", "D", 40 },
107 /* ----------------- --------------- --------------- --------------- */
108 { NULL, NULL, NULL, NULL,
115 * establishes a connectin to a postgres backend through the postmaster
116 * using connection information in a string.
118 * The conninfo string is a list of
122 * definitions. Value might be a single value containing no whitespaces
123 * or a single quoted string. If a single quote should appear everywhere
124 * in the value, it must be escaped with a backslash like \'
126 * Returns a PGconn* which is needed for all subsequent libpq calls
127 * if the status field of the connection returned is CONNECTION_BAD,
128 * then some fields may be null'ed out instead of having valid values
132 PQconnectdb(const char *conninfo)
135 PQconninfoOption *option;
136 char errorMessage[ERROR_MSG_LENGTH];
139 * Allocate memory for the conn structure
142 conn = (PGconn*)malloc(sizeof(PGconn));
145 "FATAL: PQsetdb() -- unable to allocate memory for a PGconn");
146 return (PGconn*)NULL;
148 memset((char *)conn, 0, sizeof(PGconn));
151 * Parse the conninfo string and get the fallback resources
154 if(conninfo_parse(conninfo, errorMessage) < 0) {
155 conn->status = CONNECTION_BAD;
156 strcpy(conn->errorMessage, errorMessage);
162 * Check that we have all connection parameters
165 for(option = PQconninfoOptions; option->keyword != NULL; option++) {
166 if(option->val != NULL) continue; /* Value was in conninfo */
169 * No value was found for this option. Return an error.
172 conn->status = CONNECTION_BAD;
173 sprintf(conn->errorMessage,
174 "ERROR: PQconnectdb(): Cannot determine a value for option '%s'.\n",
176 strcat(conn->errorMessage,
177 "Option not specified in conninfo string");
178 if(option->environ) {
179 strcat(conn->errorMessage,
180 ", environment variable ");
181 strcat(conn->errorMessage, option->environ);
182 strcat(conn->errorMessage, "\nnot set");
184 strcat(conn->errorMessage, " and no compiled in default value.\n");
190 * Setup the conn structure
195 conn->Pfdebug = NULL;
197 conn->notifyList = DLNewList();
199 conn->pghost = strdup(conninfo_getval("host"));
200 conn->pgport = strdup(conninfo_getval("port"));
201 conn->pgtty = strdup(conninfo_getval("tty"));
202 conn->pgoptions = strdup(conninfo_getval("options"));
203 conn->pguser = strdup(conninfo_getval("user"));
204 conn->dbName = strdup(conninfo_getval("dbname"));
207 * Free the connection info - all is in conn now
213 * Connect to the database
216 conn->status = connectDB(conn);
217 if (conn->status == CONNECTION_OK) {
219 /* Send a blank query to make sure everything works; in particular, that
222 res = PQexec(conn," ");
223 if (res == NULL || res->resultStatus != PGRES_EMPTY_QUERY) {
224 /* PQexec has put error message in conn->errorMessage */
236 * Parse an empty string like PQconnectdb() would do and return the
237 * address of the connection options structure. Using this function
238 * an application might determine all possible options and their
239 * current default values.
245 char errorMessage[ERROR_MSG_LENGTH];
247 conninfo_parse("", errorMessage);
248 return PQconninfoOptions;
254 * establishes a connection to a postgres backend through the postmaster
255 * at the specified host and port.
257 * returns a PGconn* which is needed for all subsequent libpq calls
258 * if the status field of the connection returned is CONNECTION_BAD,
259 * then some fields may be null'ed out instead of having valid values
261 * Uses these environment variables:
263 * PGHOST identifies host to which to connect if <pghost> argument
264 * is NULL or a null string.
266 * PGPORT identifies TCP port to which to connect if <pgport> argument
267 * is NULL or a null string.
269 * PGTTY identifies tty to which to send messages if <pgtty> argument
270 * is NULL or a null string.
272 * PGOPTIONS identifies connection options if <pgoptions> argument is
273 * NULL or a null string.
275 * PGUSER Postgres username to associate with the connection.
277 * PGDATABASE name of database to which to connect if <pgdatabase>
278 * argument is NULL or a null string
280 * None of the above need be defined. There are defaults for all of them.
285 PQsetdb(const char *pghost, const char* pgport, const char* pgoptions, const char* pgtty, const char* dbName)
289 char errorMessage[ERROR_MSG_LENGTH];
290 /* An error message from some service we call. */
292 /* We encountered an error that prevents successful completion */
294 conn = (PGconn*)malloc(sizeof(PGconn));
298 "FATAL: PQsetdb() -- unable to allocate memory for a PGconn");
302 conn->Pfdebug = NULL;
304 conn->notifyList = DLNewList();
306 if (!pghost || pghost[0] == '\0') {
307 if (!(tmp = getenv("PGHOST"))) {
310 conn->pghost = strdup(tmp);
312 conn->pghost = strdup(pghost);
314 if (!pgport || pgport[0] == '\0') {
315 if (!(tmp = getenv("PGPORT"))) {
318 conn->pgport = strdup(tmp);
320 conn->pgport = strdup(pgport);
322 if (!pgtty || pgtty[0] == '\0') {
323 if (!(tmp = getenv("PGTTY"))) {
326 conn->pgtty = strdup(tmp);
328 conn->pgtty = strdup(pgtty);
330 if (!pgoptions || pgoptions[0] == '\0') {
331 if (!(tmp = getenv("PGOPTIONS"))) {
334 conn->pgoptions = strdup(tmp);
336 conn->pgoptions = strdup(pgoptions);
338 if ((tmp = getenv("PGUSER"))) {
340 conn->pguser = strdup(tmp);
342 tmp = fe_getauthname(errorMessage);
345 sprintf(conn->errorMessage,
346 "FATAL: PQsetdb: Unable to determine a Postgres username!\n");
354 if (((tmp = (char *)dbName) && (dbName[0] != '\0')) ||
355 ((tmp = getenv("PGDATABASE")))) {
356 conn->dbName = strdup(tmp);
357 } else conn->dbName = strdup(conn->pguser);
358 } else conn->dbName = NULL;
360 if (error) conn->status = CONNECTION_BAD;
362 conn->status = connectDB(conn);
363 /* Puts message in conn->errorMessage */
364 if (conn->status == CONNECTION_OK) {
366 /* Send a blank query to make sure everything works;
367 in particular, that the database exists.
369 res = PQexec(conn," ");
370 if (res == NULL || res->resultStatus != PGRES_EMPTY_QUERY) {
371 /* PQexec has put error message in conn->errorMessage */
384 * make a connection to the backend so it is ready to receive queries.
385 * return CONNECTION_OK if successful, CONNECTION_BAD if not.
388 static ConnStatusType
389 connectDB(PGconn *conn)
397 int laddrlen = sizeof(struct sockaddr);
398 Port *port = conn->port;
403 // Initialize the startup packet.
405 // This data structure is used for the seq-packet protocol. It
406 // describes the frontend-backend connection.
410 strncpy(startup.user,conn->pguser,sizeof(startup.user));
411 strncpy(startup.database,conn->dbName,sizeof(startup.database));
412 strncpy(startup.tty,conn->pgtty,sizeof(startup.tty));
413 if (conn->pgoptions) {
414 strncpy(startup.options,conn->pgoptions, sizeof(startup.options));
417 startup.options[0]='\0';
418 startup.execFile[0]='\0'; /* not used */
422 // Open a connection to postmaster/backend.
425 port = (Port *) malloc(sizeof(Port));
426 memset((char *) port, 0, sizeof(Port));
428 if (!(hp = gethostbyname(conn->pghost)) || hp->h_addrtype != AF_INET) {
429 (void) sprintf(conn->errorMessage,
430 "connectDB() -- unknown hostname: %s\n",
432 goto connect_errReturn;
434 memset((char *) &port->raddr, 0, sizeof(port->raddr));
435 memmove((char *) &(port->raddr.sin_addr),
438 port->raddr.sin_family = AF_INET;
439 portno = atoi(conn->pgport);
440 port->raddr.sin_port = htons((unsigned short)(portno));
442 /* connect to the server */
443 if ((port->sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
444 (void) sprintf(conn->errorMessage,
445 "connectDB() -- socket() failed: errno=%d\n%s\n",
446 errno, strerror(errno));
447 goto connect_errReturn;
449 if (connect(port->sock, (struct sockaddr *)&port->raddr,
450 sizeof(port->raddr)) < 0) {
451 (void) sprintf(conn->errorMessage,
452 "connectDB() failed: Is the postmaster running at '%s' on port '%s'?\n",
453 conn->pghost,conn->pgport);
454 goto connect_errReturn;
458 /* fill in the client address */
459 if (getsockname(port->sock, (struct sockaddr *) &port->laddr,
461 (void) sprintf(conn->errorMessage,
462 "connectDB() -- getsockname() failed: errno=%d\n%s\n",
463 errno, strerror(errno));
464 goto connect_errReturn;
467 /* by this point, connection has been opened */
468 msgtype = fe_getauthsvc(conn->errorMessage);
470 /* pacBuf = startup2PacketBuf(&startup);*/
471 startup2PacketBuf(&startup, &pacBuf);
472 pacBuf.msgtype = (MsgType) htonl(msgtype);
473 status = packetSend(port, &pacBuf, sizeof(PacketBuf), BLOCKING);
475 if (status == STATUS_ERROR)
477 sprintf(conn->errorMessage,
478 "connectDB() -- couldn't send complete packet: errno=%d\n%s\n", errno,strerror(errno));
479 goto connect_errReturn;
482 /* authenticate as required*/
483 if (fe_sendauth(msgtype, port, conn->pghost,
484 conn->errorMessage) != STATUS_OK) {
485 (void) sprintf(conn->errorMessage,
486 "connectDB() -- authentication failed with %s\n",
488 goto connect_errReturn;
491 /* set up the socket file descriptors */
492 conn->Pfout = fdopen(port->sock, "w");
493 conn->Pfin = fdopen(dup(port->sock), "r");
494 if (!conn->Pfout || !conn->Pfin) {
495 (void) sprintf(conn->errorMessage,
496 "connectDB() -- fdopen() failed: errno=%d\n%s\n",
497 errno, strerror(errno));
498 goto connect_errReturn;
503 return CONNECTION_OK;
506 return CONNECTION_BAD;
512 * - free the PGconn data structure
516 freePGconn(PGconn *conn)
518 if (conn->pghost) free(conn->pghost);
519 if (conn->pgtty) free(conn->pgtty);
520 if (conn->pgoptions) free(conn->pgoptions);
521 if (conn->pgport) free(conn->pgport);
522 if (conn->dbName) free(conn->dbName);
523 if (conn->pguser) free(conn->pguser);
524 if (conn->notifyList) DLFreeList(conn->notifyList);
530 - properly close a connection to the backend
533 closePGconn(PGconn *conn)
535 struct sigaction ignore_action;
536 /* This is used as a constant, but not declared as such because the
537 sigaction structure is defined differently on different systems */
538 struct sigaction oldaction;
540 /* If connection is already gone, that's cool. No reason for kernel
541 to kill us when we try to write to it. So ignore SIGPIPE signals.
543 ignore_action.sa_handler = SIG_IGN;
544 sigemptyset(&ignore_action.sa_mask);
545 ignore_action.sa_flags = 0;
546 sigaction(SIGPIPE, (struct sigaction *) &ignore_action, &oldaction);
548 fputs("X\0", conn->Pfout);
550 sigaction(SIGPIPE, &oldaction, NULL);
551 if (conn->Pfout) fclose(conn->Pfout);
552 if (conn->Pfin) fclose(conn->Pfin);
553 if (conn->Pfdebug) fclose(conn->Pfdebug);
554 conn->status = CONNECTION_BAD; /* Well, not really _bad_ - just absent */
559 properly close a connection to the backend
560 also frees the PGconn data structure so it shouldn't be re-used
564 PQfinish(PGconn *conn)
567 fprintf(stderr,"PQfinish() -- pointer to PGconn is null");
569 if (conn->status == CONNECTION_OK)
576 resets the connection to the backend
577 closes the existing connection and makes a new one
580 PQreset(PGconn *conn)
583 fprintf(stderr,"PQreset() -- pointer to PGconn is null");
586 conn->status = connectDB(conn);
593 this is just like PacketSend(), defined in backend/libpq/pqpacket.c
594 but we define it here to avoid linking in all of libpq.a
596 * packetSend -- send a single-packet message.
598 * RETURNS: STATUS_ERROR if the write fails, STATUS_OK otherwise.
599 * SIDE_EFFECTS: may block.
600 * NOTES: Non-blocking writes would significantly complicate
601 * buffer management. For now, we're not going to do it.
605 packetSend(Port *port,
611 int addrLen = sizeof(struct sockaddr_in);
615 len = sendto(port->sock, (Addr) buf, totalLen, /* flags */ 0,
616 (struct sockaddr *)&(port->raddr), addrLen);
618 if (len < totalLen) {
619 return(STATUS_ERROR);
626 * startup2PacketBuf()
628 * this is just like StartupInfo2Packet(), defined in backend/libpq/pqpacket.c
629 * but we repeat it here so we don't have to link in libpq.a
631 * converts a StartupInfo structure to a PacketBuf
634 startup2PacketBuf(StartupInfo* s, PacketBuf* res)
638 /* res = (PacketBuf*)malloc(sizeof(PacketBuf)); */
639 res->len = htonl(sizeof(PacketBuf));
640 /* use \n to delimit the strings */
645 strncpy(tmp, s->database, sizeof(s->database));
646 tmp += sizeof(s->database);
647 strncpy(tmp, s->user, sizeof(s->user));
648 tmp += sizeof(s->user);
649 strncpy(tmp, s->options, sizeof(s->options));
650 tmp += sizeof(s->options);
651 strncpy(tmp, s->execFile, sizeof(s->execFile));
652 tmp += sizeof(s->execFile);
653 strncpy(tmp, s->tty, sizeof(s->execFile));
657 * Conninfo parser routine
660 static int conninfo_parse(const char *conninfo, char *errorMessage)
668 PQconninfoOption *option;
669 char errortmp[ERROR_MSG_LENGTH];
673 if((buf = strdup(conninfo)) == NULL) {
675 "FATAL: cannot allocate memory for copy of conninfo string\n");
681 /* Skip blanks before the parameter name */
687 /* Get the parameter name */
706 /* Check that there is a following '=' */
708 sprintf(errorMessage,
709 "ERROR: PQconnectdb() - Missing '=' after '%s' in conninfo\n",
716 /* Skip blanks after the '=' */
748 sprintf(errorMessage,
749 "ERROR: PQconnectdb() - unterminated quoted string in conninfo\n");
770 * Now we have the name and the value. Search
771 * for the param record.
774 for(option = PQconninfoOptions; option->keyword != NULL; option++) {
775 if(!strcmp(option->keyword, pname)) {
779 if(option->keyword == NULL) {
780 sprintf(errorMessage,
781 "ERROR: PQconnectdb() - unknown option '%s'\n",
791 option->val = strdup(pval);
797 * Get the fallback resources for parameters not specified
798 * in the conninfo string.
801 for(option = PQconninfoOptions; option->keyword != NULL; option++) {
802 if(option->val != NULL) continue; /* Value was in conninfo */
805 * Try to get the environment variable fallback
808 if(option->environ != NULL) {
809 if((tmp = getenv(option->environ)) != NULL) {
810 option->val = strdup(tmp);
816 * No environment variable specified or this one isn't set -
820 if(option->compiled != NULL) {
821 option->val = strdup(option->compiled);
826 * Special handling for user
829 if(!strcmp(option->keyword, "user")) {
830 tmp = fe_getauthname(errortmp);
832 option->val = strdup(tmp);
837 * Special handling for dbname
840 if(!strcmp(option->keyword, "dbname")) {
841 tmp = conninfo_getval("user");
843 option->val = strdup(tmp);
853 conninfo_getval(char *keyword)
855 PQconninfoOption *option;
857 for(option = PQconninfoOptions; option->keyword != NULL; option++) {
858 if (!strcmp(option->keyword, keyword)) {
870 PQconninfoOption *option;
872 for(option = PQconninfoOptions; option->keyword != NULL; option++) {
873 if(option->val != NULL) {
880 /* =========== accessor functions for PGconn ========= */
885 fprintf(stderr,"PQdb() -- pointer to PGconn is null");
895 fprintf(stderr,"PQuser() -- pointer to PGconn is null");
905 fprintf(stderr,"PQhost() -- pointer to PGconn is null");
913 PQoptions(PGconn* conn)
916 fprintf(stderr,"PQoptions() -- pointer to PGconn is null");
919 return conn->pgoptions;
926 fprintf(stderr,"PQtty() -- pointer to PGconn is null");
936 fprintf(stderr,"PQport() -- pointer to PGconn is null");
943 PQstatus(PGconn* conn)
946 fprintf(stderr,"PQstatus() -- pointer to PGconn is null");
947 return CONNECTION_BAD;
953 PQerrorMessage(PGconn* conn)
956 fprintf(stderr,"PQerrorMessage() -- pointer to PGconn is null");
959 return conn->errorMessage;
963 PQtrace(PGconn *conn, FILE* debug_port)
966 conn->status == CONNECTION_BAD) {
970 conn->Pfdebug = debug_port;
974 PQuntrace(PGconn *conn)
977 conn->status == CONNECTION_BAD) {
981 fflush(conn->Pfdebug);
982 fclose(conn->Pfdebug);
983 conn->Pfdebug = NULL;