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.16 1996/11/10 01:46:14 bryanh Exp $
12 *-------------------------------------------------------------------------
16 #include <sys/types.h>
17 #include <sys/socket.h>
25 #include <ctype.h> /* for isspace() */
28 #include "libpq/pqcomm.h" /* for decls of MsgType, PacketBuf, StartupInfo */
32 #if defined(ultrix4) || defined(next)
33 /* ultrix is lame and doesn't have strdup in libc for some reason */
34 /* [TRH] So doesn't NEXTSTEP. But whaddaya expect for a non-ANSI
35 standard function? (My, my. Touchy today, are we?) */
38 strdup(const char *string)
42 if ((nstr = malloc(strlen(string)+1)) != NULL)
48 /* use a local version instead of the one found in pqpacket.c */
49 static ConnStatusType connectDB(PGconn *conn);
51 static int packetSend(Port *port, PacketBuf *buf, PacketLen len,
53 static void startup2PacketBuf(StartupInfo* s, PacketBuf* res);
54 static void freePGconn(PGconn *conn);
55 static void closePGconn(PGconn *conn);
56 static int conninfo_parse(const char *conninfo, char *errorMessage);
57 static char *conninfo_getval(char *keyword);
58 static void conninfo_free();
60 #define NOTIFYLIST_INITIAL_SIZE 10
61 #define NOTIFYLIST_GROWBY 10
65 * Definition of the conninfo parametes and their fallback resources.
66 * If Environment-Var and Compiled-in are specified as NULL, no
67 * fallback is available. If after all no value can be determined
68 * for an option, an error is returned.
70 * The values for dbname and user are treated special in conninfo_parse.
71 * If the Compiled-in resource is specified as a NULL value, the
72 * user is determined by fe_getauthname() and for dbname the user
75 * The Label and Disp-Char entries are provided for applications that
76 * want to use PQconndefaults() to create a generic database connection
77 * dialog. Disp-Char is defined as follows:
78 * "" Normal input field
81 static PQconninfoOption PQconninfoOptions[] = {
82 /* ----------------------------------------------------------------- */
83 /* Option-name Environment-Var Compiled-in Current value */
85 /* ----------------- --------------- --------------- --------------- */
86 { "user", "PGUSER", NULL, NULL,
87 "Database-User", "", 20 },
89 { "dbname", "PGDATABASE", NULL, NULL,
90 "Database-Name", "", 20 },
92 { "host", "PGHOST", DefaultHost, NULL,
93 "Database-Host", "", 40 },
95 { "port", "PGPORT", POSTPORT, NULL,
96 "Database-Port", "", 6 },
98 { "tty", "PGTTY", DefaultTty, NULL,
99 "Backend-Debug-TTY", "D", 40 },
101 { "options", "PGOPTIONS", DefaultOption, NULL,
102 "Backend-Debug-Options", "D", 40 },
103 /* ----------------- --------------- --------------- --------------- */
104 { NULL, NULL, NULL, NULL,
111 * establishes a connectin to a postgres backend through the postmaster
112 * using connection information in a string.
114 * The conninfo string is a list of
118 * definitions. Value might be a single value containing no whitespaces
119 * or a single quoted string. If a single quote should appear everywhere
120 * in the value, it must be escaped with a backslash like \'
122 * Returns a PGconn* which is needed for all subsequent libpq calls
123 * if the status field of the connection returned is CONNECTION_BAD,
124 * then some fields may be null'ed out instead of having valid values
128 PQconnectdb(const char *conninfo)
131 PQconninfoOption *option;
132 char errorMessage[ERROR_MSG_LENGTH];
135 * Allocate memory for the conn structure
138 conn = (PGconn*)malloc(sizeof(PGconn));
141 "FATAL: PQsetdb() -- unable to allocate memory for a PGconn");
142 return (PGconn*)NULL;
144 memset((char *)conn, 0, sizeof(PGconn));
147 * Parse the conninfo string and get the fallback resources
150 if(conninfo_parse(conninfo, errorMessage) < 0) {
151 conn->status = CONNECTION_BAD;
152 strcpy(conn->errorMessage, errorMessage);
158 * Check that we have all connection parameters
161 for(option = PQconninfoOptions; option->keyword != NULL; option++) {
162 if(option->val != NULL) continue; /* Value was in conninfo */
165 * No value was found for this option. Return an error.
168 conn->status = CONNECTION_BAD;
169 sprintf(conn->errorMessage,
170 "ERROR: PQconnectdb(): Cannot determine a value for option '%s'.\n",
172 strcat(conn->errorMessage,
173 "Option not specified in conninfo string");
174 if(option->environ) {
175 strcat(conn->errorMessage,
176 ", environment variable ");
177 strcat(conn->errorMessage, option->environ);
178 strcat(conn->errorMessage, "\nnot set");
180 strcat(conn->errorMessage, " and no compiled in default value.\n");
186 * Setup the conn structure
191 conn->Pfdebug = NULL;
193 conn->notifyList = DLNewList();
195 conn->pghost = strdup(conninfo_getval("host"));
196 conn->pgport = strdup(conninfo_getval("port"));
197 conn->pgtty = strdup(conninfo_getval("tty"));
198 conn->pgoptions = strdup(conninfo_getval("options"));
199 conn->pguser = strdup(conninfo_getval("user"));
200 conn->dbName = strdup(conninfo_getval("dbname"));
203 * Free the connection info - all is in conn now
209 * Connect to the database
212 conn->status = connectDB(conn);
213 if (conn->status == CONNECTION_OK) {
215 /* Send a blank query to make sure everything works; in particular, that
218 res = PQexec(conn," ");
219 if (res == NULL || res->resultStatus != PGRES_EMPTY_QUERY) {
220 /* PQexec has put error message in conn->errorMessage */
232 * Parse an empty string like PQconnectdb() would do and return the
233 * address of the connection options structure. Using this function
234 * an application might determine all possible options and their
235 * current default values.
241 char errorMessage[ERROR_MSG_LENGTH];
243 conninfo_parse("", errorMessage);
244 return PQconninfoOptions;
250 * establishes a connection to a postgres backend through the postmaster
251 * at the specified host and port.
253 * returns a PGconn* which is needed for all subsequent libpq calls
254 * if the status field of the connection returned is CONNECTION_BAD,
255 * then some fields may be null'ed out instead of having valid values
257 * Uses these environment variables:
259 * PGHOST identifies host to which to connect if <pghost> argument
260 * is NULL or a null string.
262 * PGPORT identifies TCP port to which to connect if <pgport> argument
263 * is NULL or a null string.
265 * PGTTY identifies tty to which to send messages if <pgtty> argument
266 * is NULL or a null string.
268 * PGOPTIONS identifies connection options if <pgoptions> argument is
269 * NULL or a null string.
271 * PGUSER Postgres username to associate with the connection.
273 * PGDATABASE name of database to which to connect if <pgdatabase>
274 * argument is NULL or a null string
276 * None of the above need be defined. There are defaults for all of them.
281 PQsetdb(const char *pghost, const char* pgport, const char* pgoptions, const char* pgtty, const char* dbName)
285 char errorMessage[ERROR_MSG_LENGTH];
286 /* An error message from some service we call. */
288 /* We encountered an error that prevents successful completion */
290 conn = (PGconn*)malloc(sizeof(PGconn));
294 "FATAL: PQsetdb() -- unable to allocate memory for a PGconn");
298 conn->Pfdebug = NULL;
300 conn->notifyList = DLNewList();
302 if (!pghost || pghost[0] == '\0') {
303 if (!(tmp = getenv("PGHOST"))) {
306 conn->pghost = strdup(tmp);
308 conn->pghost = strdup(pghost);
310 if (!pgport || pgport[0] == '\0') {
311 if (!(tmp = getenv("PGPORT"))) {
314 conn->pgport = strdup(tmp);
316 conn->pgport = strdup(pgport);
318 if (!pgtty || pgtty[0] == '\0') {
319 if (!(tmp = getenv("PGTTY"))) {
322 conn->pgtty = strdup(tmp);
324 conn->pgtty = strdup(pgtty);
326 if (!pgoptions || pgoptions[0] == '\0') {
327 if (!(tmp = getenv("PGOPTIONS"))) {
330 conn->pgoptions = strdup(tmp);
332 conn->pgoptions = strdup(pgoptions);
334 if ((tmp = getenv("PGUSER"))) {
336 conn->pguser = strdup(tmp);
338 tmp = fe_getauthname(errorMessage);
341 sprintf(conn->errorMessage,
342 "FATAL: PQsetdb: Unable to determine a Postgres username!\n");
350 if (((tmp = (char *)dbName) && (dbName[0] != '\0')) ||
351 ((tmp = getenv("PGDATABASE")))) {
352 conn->dbName = strdup(tmp);
353 } else conn->dbName = strdup(conn->pguser);
354 } else conn->dbName = NULL;
356 if (error) conn->status = CONNECTION_BAD;
358 conn->status = connectDB(conn);
359 /* Puts message in conn->errorMessage */
360 if (conn->status == CONNECTION_OK) {
362 /* Send a blank query to make sure everything works;
363 in particular, that the database exists.
365 res = PQexec(conn," ");
366 if (res == NULL || res->resultStatus != PGRES_EMPTY_QUERY) {
367 /* PQexec has put error message in conn->errorMessage */
380 * make a connection to the backend so it is ready to receive queries.
381 * return CONNECTION_OK if successful, CONNECTION_BAD if not.
384 static ConnStatusType
385 connectDB(PGconn *conn)
393 int laddrlen = sizeof(struct sockaddr);
394 Port *port = conn->port;
399 // Initialize the startup packet.
401 // This data structure is used for the seq-packet protocol. It
402 // describes the frontend-backend connection.
406 strncpy(startup.user,conn->pguser,sizeof(startup.user));
407 strncpy(startup.database,conn->dbName,sizeof(startup.database));
408 strncpy(startup.tty,conn->pgtty,sizeof(startup.tty));
409 if (conn->pgoptions) {
410 strncpy(startup.options,conn->pgoptions, sizeof(startup.options));
413 startup.options[0]='\0';
414 startup.execFile[0]='\0'; /* not used */
418 // Open a connection to postmaster/backend.
421 port = (Port *) malloc(sizeof(Port));
422 memset((char *) port, 0, sizeof(Port));
424 if (!(hp = gethostbyname(conn->pghost)) || hp->h_addrtype != AF_INET) {
425 (void) sprintf(conn->errorMessage,
426 "connectDB() -- unknown hostname: %s\n",
428 goto connect_errReturn;
430 memset((char *) &port->raddr, 0, sizeof(port->raddr));
431 memmove((char *) &(port->raddr.sin_addr),
434 port->raddr.sin_family = AF_INET;
435 portno = atoi(conn->pgport);
436 port->raddr.sin_port = htons((unsigned short)(portno));
438 /* connect to the server */
439 if ((port->sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
440 (void) sprintf(conn->errorMessage,
441 "connectDB() -- socket() failed: errno=%d\n%s\n",
442 errno, strerror(errno));
443 goto connect_errReturn;
445 if (connect(port->sock, (struct sockaddr *)&port->raddr,
446 sizeof(port->raddr)) < 0) {
447 (void) sprintf(conn->errorMessage,
448 "connectDB() failed: Is the postmaster running at '%s' on port '%s'?\n",
449 conn->pghost,conn->pgport);
450 goto connect_errReturn;
454 /* fill in the client address */
455 if (getsockname(port->sock, (struct sockaddr *) &port->laddr,
457 (void) sprintf(conn->errorMessage,
458 "connectDB() -- getsockname() failed: errno=%d\n%s\n",
459 errno, strerror(errno));
460 goto connect_errReturn;
463 /* by this point, connection has been opened */
464 msgtype = fe_getauthsvc(conn->errorMessage);
466 /* pacBuf = startup2PacketBuf(&startup);*/
467 startup2PacketBuf(&startup, &pacBuf);
468 pacBuf.msgtype = (MsgType) htonl(msgtype);
469 status = packetSend(port, &pacBuf, sizeof(PacketBuf), BLOCKING);
471 if (status == STATUS_ERROR)
473 sprintf(conn->errorMessage,
474 "connectDB() -- couldn't send complete packet: errno=%d\n%s\n", errno,strerror(errno));
475 goto connect_errReturn;
478 /* authenticate as required*/
479 if (fe_sendauth(msgtype, port, conn->pghost,
480 conn->errorMessage) != STATUS_OK) {
481 (void) sprintf(conn->errorMessage,
482 "connectDB() -- authentication failed with %s\n",
484 goto connect_errReturn;
487 /* set up the socket file descriptors */
488 conn->Pfout = fdopen(port->sock, "w");
489 conn->Pfin = fdopen(dup(port->sock), "r");
490 if (!conn->Pfout || !conn->Pfin) {
491 (void) sprintf(conn->errorMessage,
492 "connectDB() -- fdopen() failed: errno=%d\n%s\n",
493 errno, strerror(errno));
494 goto connect_errReturn;
499 return CONNECTION_OK;
502 return CONNECTION_BAD;
508 * - free the PGconn data structure
512 freePGconn(PGconn *conn)
514 if (conn->pghost) free(conn->pghost);
515 if (conn->pgtty) free(conn->pgtty);
516 if (conn->pgoptions) free(conn->pgoptions);
517 if (conn->pgport) free(conn->pgport);
518 if (conn->dbName) free(conn->dbName);
519 if (conn->pguser) free(conn->pguser);
520 if (conn->notifyList) DLFreeList(conn->notifyList);
526 - properly close a connection to the backend
529 closePGconn(PGconn *conn)
531 struct sigaction ignore_action;
532 /* This is used as a constant, but not declared as such because the
533 sigaction structure is defined differently on different systems */
534 struct sigaction oldaction;
536 /* If connection is already gone, that's cool. No reason for kernel
537 to kill us when we try to write to it. So ignore SIGPIPE signals.
539 ignore_action.sa_handler = SIG_IGN;
540 sigemptyset(&ignore_action.sa_mask);
541 ignore_action.sa_flags = 0;
542 sigaction(SIGPIPE, (struct sigaction *) &ignore_action, &oldaction);
544 fputs("X\0", conn->Pfout);
546 sigaction(SIGPIPE, &oldaction, NULL);
547 if (conn->Pfout) fclose(conn->Pfout);
548 if (conn->Pfin) fclose(conn->Pfin);
549 if (conn->Pfdebug) fclose(conn->Pfdebug);
550 conn->status = CONNECTION_BAD; /* Well, not really _bad_ - just absent */
555 properly close a connection to the backend
556 also frees the PGconn data structure so it shouldn't be re-used
560 PQfinish(PGconn *conn)
563 fprintf(stderr,"PQfinish() -- pointer to PGconn is null");
565 if (conn->status == CONNECTION_OK)
572 resets the connection to the backend
573 closes the existing connection and makes a new one
576 PQreset(PGconn *conn)
579 fprintf(stderr,"PQreset() -- pointer to PGconn is null");
582 conn->status = connectDB(conn);
589 this is just like PacketSend(), defined in backend/libpq/pqpacket.c
590 but we define it here to avoid linking in all of libpq.a
592 * packetSend -- send a single-packet message.
594 * RETURNS: STATUS_ERROR if the write fails, STATUS_OK otherwise.
595 * SIDE_EFFECTS: may block.
596 * NOTES: Non-blocking writes would significantly complicate
597 * buffer management. For now, we're not going to do it.
601 packetSend(Port *port,
607 int addrLen = sizeof(struct sockaddr_in);
611 len = sendto(port->sock, (Addr) buf, totalLen, /* flags */ 0,
612 (struct sockaddr *)&(port->raddr), addrLen);
614 if (len < totalLen) {
615 return(STATUS_ERROR);
622 * startup2PacketBuf()
624 * this is just like StartupInfo2Packet(), defined in backend/libpq/pqpacket.c
625 * but we repeat it here so we don't have to link in libpq.a
627 * converts a StartupInfo structure to a PacketBuf
630 startup2PacketBuf(StartupInfo* s, PacketBuf* res)
634 /* res = (PacketBuf*)malloc(sizeof(PacketBuf)); */
635 res->len = htonl(sizeof(PacketBuf));
636 /* use \n to delimit the strings */
641 strncpy(tmp, s->database, sizeof(s->database));
642 tmp += sizeof(s->database);
643 strncpy(tmp, s->user, sizeof(s->user));
644 tmp += sizeof(s->user);
645 strncpy(tmp, s->options, sizeof(s->options));
646 tmp += sizeof(s->options);
647 strncpy(tmp, s->execFile, sizeof(s->execFile));
648 tmp += sizeof(s->execFile);
649 strncpy(tmp, s->tty, sizeof(s->execFile));
653 * Conninfo parser routine
656 static int conninfo_parse(const char *conninfo, char *errorMessage)
664 PQconninfoOption *option;
665 char errortmp[ERROR_MSG_LENGTH];
669 if((buf = strdup(conninfo)) == NULL) {
671 "FATAL: cannot allocate memory for copy of conninfo string\n");
677 /* Skip blanks before the parameter name */
683 /* Get the parameter name */
702 /* Check that there is a following '=' */
704 sprintf(errorMessage,
705 "ERROR: PQconnectdb() - Missing '=' after '%s' in conninfo\n",
712 /* Skip blanks after the '=' */
744 sprintf(errorMessage,
745 "ERROR: PQconnectdb() - unterminated quoted string in conninfo\n");
766 * Now we have the name and the value. Search
767 * for the param record.
770 for(option = PQconninfoOptions; option->keyword != NULL; option++) {
771 if(!strcmp(option->keyword, pname)) {
775 if(option->keyword == NULL) {
776 sprintf(errorMessage,
777 "ERROR: PQconnectdb() - unknown option '%s'\n",
787 option->val = strdup(pval);
793 * Get the fallback resources for parameters not specified
794 * in the conninfo string.
797 for(option = PQconninfoOptions; option->keyword != NULL; option++) {
798 if(option->val != NULL) continue; /* Value was in conninfo */
801 * Try to get the environment variable fallback
804 if(option->environ != NULL) {
805 if((tmp = getenv(option->environ)) != NULL) {
806 option->val = strdup(tmp);
812 * No environment variable specified or this one isn't set -
816 if(option->compiled != NULL) {
817 option->val = strdup(option->compiled);
822 * Special handling for user
825 if(!strcmp(option->keyword, "user")) {
826 tmp = fe_getauthname(errortmp);
828 option->val = strdup(tmp);
833 * Special handling for dbname
836 if(!strcmp(option->keyword, "dbname")) {
837 tmp = conninfo_getval("user");
839 option->val = strdup(tmp);
849 conninfo_getval(char *keyword)
851 PQconninfoOption *option;
853 for(option = PQconninfoOptions; option->keyword != NULL; option++) {
854 if (!strcmp(option->keyword, keyword)) {
866 PQconninfoOption *option;
868 for(option = PQconninfoOptions; option->keyword != NULL; option++) {
869 if(option->val != NULL) {
876 /* =========== accessor functions for PGconn ========= */
881 fprintf(stderr,"PQdb() -- pointer to PGconn is null");
891 fprintf(stderr,"PQuser() -- pointer to PGconn is null");
901 fprintf(stderr,"PQhost() -- pointer to PGconn is null");
909 PQoptions(PGconn* conn)
912 fprintf(stderr,"PQoptions() -- pointer to PGconn is null");
915 return conn->pgoptions;
922 fprintf(stderr,"PQtty() -- pointer to PGconn is null");
932 fprintf(stderr,"PQport() -- pointer to PGconn is null");
939 PQstatus(PGconn* conn)
942 fprintf(stderr,"PQstatus() -- pointer to PGconn is null");
943 return CONNECTION_BAD;
949 PQerrorMessage(PGconn* conn)
952 fprintf(stderr,"PQerrorMessage() -- pointer to PGconn is null");
955 return conn->errorMessage;
959 PQtrace(PGconn *conn, FILE* debug_port)
962 conn->status == CONNECTION_BAD) {
966 conn->Pfdebug = debug_port;
970 PQuntrace(PGconn *conn)
973 conn->status == CONNECTION_BAD) {
977 fflush(conn->Pfdebug);
978 fclose(conn->Pfdebug);
979 conn->Pfdebug = NULL;