1 /*-------------------------------------------------------------------------
4 * Communication functions between the Frontend and the Backend
6 * Copyright (c) 1994, Regents of the University of California
10 * $Header: /cvsroot/pgsql/src/backend/libpq/pqcomm.c,v 1.44 1998/06/15 19:28:27 momjian Exp $
12 *-------------------------------------------------------------------------
16 * pq_gettty - return the name of the tty in the given buffer
17 * pq_getport - return the PGPORT setting
18 * pq_close - close input / output connections
19 * pq_flush - flush pending output
20 * pq_getstr - get a null terminated string from connection
21 * pq_getnchar - get n characters from connection
22 * pq_getint - get an integer from connection
23 * pq_putstr - send a null terminated string to connection
24 * pq_putnchar - send n characters to connection
25 * pq_putint - send an integer to connection
26 * pq_getinaddr - initialize address from host and port number
27 * pq_getinserv - initialize address from host and service name
28 * pq_connect - create remote input / output connection
29 * pq_accept - accept remote input / output connection
30 * pq_async_notify - receive notification from backend.
33 * These functions are used by both frontend applications and
34 * the postgres backend.
40 #if defined(HAVE_STRING_H)
48 #include <unistd.h> /* for ttyname() */
49 #include <sys/types.h>
51 #include <sys/socket.h>
54 #include <netinet/in.h>
55 #include <netinet/tcp.h>
56 #include <arpa/inet.h>
60 #define SOMAXCONN 5 /* from Linux listen(2) man page */
61 #endif /* SOMAXCONN */
64 #include "miscadmin.h"
65 #include "libpq/pqsignal.h"
66 #include "libpq/auth.h"
67 #include "libpq/libpq.h" /* where the declarations go */
68 #include "storage/ipc.h"
76 FILE *Pfdebug; /* debugging libpq */
77 int PQAsyncNotifyWaiting; /* for async. notification */
79 /* --------------------------------
80 * pq_init - open portal file descriptors
81 * --------------------------------
86 Pfin = fdopen(fd, "r");
87 Pfout = fdopen(dup(fd), "w");
89 elog(FATAL, "pq_init: Couldn't initialize socket connection");
91 if (getenv("LIBPQ_DEBUG"))
97 /* -------------------------
100 * get a character from the input file,
102 * if Pfdebug is set, also echo the character fetched into Pfdebug
104 * used for debugging libpq
112 if (Pfdebug && c != EOF)
117 /* --------------------------------
118 * pq_gettty - return the name of the tty in the given buffer
119 * --------------------------------
124 strncpy(tp, ttyname(0), 19);
127 /* --------------------------------
128 * pq_getport - return the PGPORT setting
129 * --------------------------------
134 char *envport = getenv("PGPORT");
137 return (atoi(envport));
138 return (atoi(DEF_PGPORT));
141 /* --------------------------------
142 * pq_close - close input / output connections
143 * --------------------------------
158 PQAsyncNotifyWaiting = 0;
163 /* --------------------------------
164 * pq_flush - flush pending output
165 * --------------------------------
174 /* --------------------------------
175 * pq_getstr - get a null terminated string from connection
176 * --------------------------------
179 pq_getstr(char *s, int maxlen)
183 if (Pfin == (FILE *) NULL)
185 /* elog(DEBUG, "Input descriptor is null"); */
189 while (maxlen-- && (c = pq_getc(Pfin)) != EOF && c)
194 * If EOF reached let caller know.
195 * (This will only happen if we hit EOF before the string
196 * delimiter is reached.)
205 * USER FUNCTION - gets a newline-terminated string from the backend.
207 * Chiefly here so that applications can use "COPY <rel> to stdout"
208 * and read the output string. Returns a null-terminated string in s.
210 * PQgetline reads up to maxlen-1 characters (like fgets(3)) but strips
211 * the terminating \n (like gets(3)).
214 * EOF if it is detected or invalid arguments are given
215 * 0 if EOL is reached (i.e., \n has been read)
216 * (this is required for backward-compatibility -- this
217 * routine used to always return EOF or 0, assuming that
218 * the line ended within maxlen bytes.)
222 PQgetline(char *s, int maxlen)
224 if (!Pfin || !s || maxlen <= 1)
227 if (fgets(s, maxlen - 1, Pfin) == NULL)
228 return feof(Pfin) ? EOF : 1;
245 * USER FUNCTION - sends a string to the backend.
247 * Chiefly here so that applications can use "COPY <rel> from stdin".
263 /* --------------------------------
264 * pq_getnchar - get n characters from connection
265 * --------------------------------
268 pq_getnchar(char *s, int off, int maxlen)
270 return pqGetNBytes(s + off, maxlen, Pfin);
273 /* --------------------------------
274 * pq_getint - get an integer from connection
275 * we receive an integer a byte at a type and reconstruct it so that
276 * machines with different ENDIAN representations can talk to each
278 * --------------------------------
290 * mjl: Seems inconsisten w/ return value of pq_putint (void). Also,
291 * EOF is a valid return value for an int! XXX
297 status = ((n = fgetc(Pfin)) == EOF);
300 status = pqGetShort(&n, Pfin);
303 status = pqGetLong(&n, Pfin);
306 fprintf(stderr, "** Unsupported size %d\n", b);
312 "FATAL: pq_getint failed: errno=%d\n", errno);
313 fputs(PQerrormsg, stderr);
314 pqdebug("%s", PQerrormsg);
321 /* --------------------------------
322 * pq_putstr - send a null terminated string to connection
323 * --------------------------------
328 if (pqPutString(s, Pfout))
331 "FATAL: pq_putstr: fputs() failed: errno=%d\n", errno);
332 fputs(PQerrormsg, stderr);
333 pqdebug("%s", PQerrormsg);
337 /* --------------------------------
338 * pq_putnchar - send n characters to connection
339 * --------------------------------
342 pq_putnchar(char *s, int n)
344 if (pqPutNBytes(s, n, Pfout))
347 "FATAL: pq_putnchar: fputc() failed: errno=%d\n",
349 fputs(PQerrormsg, stderr);
350 pqdebug("%s", PQerrormsg);
354 /* --------------------------------
355 * pq_putint - send an integer to connection
356 * we chop an integer into bytes and send individual bytes
357 * machines with different ENDIAN representations can still talk to each
359 * --------------------------------
362 pq_putint(int i, int b)
373 status = (fputc(i, Pfout) == EOF);
376 status = pqPutShort(i, Pfout);
379 status = pqPutLong(i, Pfout);
382 fprintf(stderr, "** Unsupported size %d\n", b);
388 "FATAL: pq_putint failed: errno=%d\n", errno);
389 fputs(PQerrormsg, stderr);
390 pqdebug("%s", PQerrormsg);
395 * pq_sendoob - send a string over the out-of-band channel
396 * pq_recvoob - receive a string over the oob channel
397 * NB: Fortunately, the out-of-band channel doesn't conflict with
398 * buffered I/O because it is separate from regular com. channel.
402 pq_sendoob(char *msg, int len)
404 int fd = fileno(Pfout);
406 return send(fd, msg, len, MSG_OOB);
410 pq_recvoob(char *msgPtr, int len)
412 int fd = fileno(Pfout);
414 return recv(fd, msgPtr, len, MSG_OOB);
417 /* --------------------------------
418 * pq_getinaddr - initialize address from host and port number
419 * --------------------------------
422 pq_getinaddr(struct sockaddr_in * sin,
428 MemSet((char *) sin, 0, sizeof(*sin));
432 if (*host >= '0' && *host <= '9')
433 sin->sin_addr.s_addr = inet_addr(host);
436 if (!(hs = gethostbyname(host)))
441 if (hs->h_addrtype != AF_INET)
444 "FATAL: pq_getinaddr: %s not on Internet\n",
446 fputs(PQerrormsg, stderr);
447 pqdebug("%s", PQerrormsg);
450 memmove((char *) &sin->sin_addr,
455 sin->sin_family = AF_INET;
456 sin->sin_port = htons(port);
460 /* --------------------------------
461 * pq_getinserv - initialize address from host and servive name
462 * --------------------------------
465 pq_getinserv(struct sockaddr_in * sin, char *host, char *serv)
469 if (*serv >= '0' && *serv <= '9')
470 return (pq_getinaddr(sin, host, atoi(serv)));
471 if (!(ss = getservbyname(serv, NULL)))
474 "FATAL: pq_getinserv: unknown service: %s\n",
476 fputs(PQerrormsg, stderr);
477 pqdebug("%s", PQerrormsg);
480 return (pq_getinaddr(sin, host, ntohs(ss->s_port)));
484 * register an out-of-band listener proc--at most one allowed.
485 * This is used for receiving async. notification from the backend.
488 pq_regoob(void (*fptr) ())
490 int fd = fileno(Pfout);
493 ioctl(fd, FIOSSAIOOWN, MyProcPid);
495 ioctl(fd, SIOCSPGRP, MyProcPid);
497 fcntl(fd, F_SETOWN, MyProcPid);
499 pqsignal(SIGURG, fptr);
505 pqsignal(SIGURG, SIG_DFL);
514 /* int len = sizeof(msg); */
517 if (pq_recvoob(msg, len) >= 0)
520 printf("received notification: %s\n", msg);
521 PQAsyncNotifyWaiting = 1;
522 /* PQappendNotify(msg+1); */
528 printf("SIGURG but no data: len = %d, err=%d\n", len, errno);
533 * Streams -- wrapper around Unix socket system calls
536 * Stream functions are used for vanilla TCP connection protocol.
540 * StreamServerPort -- open a sock stream "listening" port.
542 * This initializes the Postmaster's connection
545 * ASSUME: that this doesn't need to be non-blocking because
546 * the Postmaster uses select() to tell when the socket
549 * RETURNS: STATUS_OK or STATUS_ERROR
552 static char sock_path[MAXPGPATH + 1] = "";
555 * Shutdown routine for backend connection
556 * If a Unix socket is used for communication, explicitly close it.
561 Assert(sock_path[0]);
566 StreamServerPort(char *hostName, short portName, int *fdP)
575 family = ((hostName != NULL) ? AF_INET : AF_UNIX);
577 if ((fd = socket(family, SOCK_STREAM, 0)) < 0)
580 "FATAL: StreamServerPort: socket() failed: errno=%d\n",
582 fputs(PQerrormsg, stderr);
583 pqdebug("%s", PQerrormsg);
584 return (STATUS_ERROR);
586 if ((setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *) &one,
590 "FATAL: StreamServerPort: setsockopt (SO_REUSEADDR) failed: errno=%d\n",
592 fputs(PQerrormsg, stderr);
593 pqdebug("%s", PQerrormsg);
594 return (STATUS_ERROR);
596 bzero(&saddr, sizeof(saddr));
597 saddr.sa.sa_family = family;
598 if (family == AF_UNIX)
600 len = UNIXSOCK_PATH(saddr.un, portName);
601 strcpy(sock_path, saddr.un.sun_path);
605 saddr.in.sin_addr.s_addr = htonl(INADDR_ANY);
606 saddr.in.sin_port = htons(portName);
607 len = sizeof(struct sockaddr_in);
609 err = bind(fd, &saddr.sa, len);
613 "FATAL: StreamServerPort: bind() failed: errno=%d\n",
615 pqdebug("%s", PQerrormsg);
616 strcat(PQerrormsg, "\tIs another postmaster already running on that port?\n");
617 if (family == AF_UNIX)
618 strcat(PQerrormsg, "\tIf not, remove socket node (/tmp/.s.PGSQL.<portnumber>)and retry.\n");
620 strcat(PQerrormsg, "\tIf not, wait a few seconds and retry.\n");
621 fputs(PQerrormsg, stderr);
622 return (STATUS_ERROR);
625 if (family == AF_UNIX)
626 on_exitpg(StreamDoUnlink, NULL);
628 listen(fd, SOMAXCONN);
631 * MS: I took this code from Dillon's version. It makes the listening
632 * port non-blocking. That is not necessary (and may tickle kernel
635 * fcntl(fd, F_SETFD, 1); fcntl(fd, F_SETFL, FNDELAY);
639 if (family == AF_UNIX)
640 chmod(sock_path, 0777);
645 * StreamConnection -- create a new connection with client using
648 * This one should be non-blocking.
650 * RETURNS: STATUS_OK or STATUS_ERROR
653 StreamConnection(int server_fd, Port *port)
657 int family = port->raddr.sa.sa_family;
659 /* accept connection (and fill in the client (remote) address) */
660 len = family == AF_INET ?
661 sizeof(struct sockaddr_in) : sizeof(struct sockaddr_un);
663 if ((port->sock = accept(server_fd,
664 (struct sockaddr *) & port->raddr,
667 elog(ERROR, "postmaster: StreamConnection: accept: %m");
668 return (STATUS_ERROR);
671 /* fill in the server (local) address */
673 if (getsockname(port->sock, (struct sockaddr *) & port->laddr,
676 elog(ERROR, "postmaster: StreamConnection: getsockname: %m");
677 return (STATUS_ERROR);
679 if (family == AF_INET)
684 pe = getprotobyname("TCP");
687 elog(ERROR, "postmaster: getprotobyname failed");
688 return (STATUS_ERROR);
690 if (setsockopt(port->sock, pe->p_proto, TCP_NODELAY,
691 &on, sizeof(on)) < 0)
693 elog(ERROR, "postmaster: setsockopt failed");
694 return (STATUS_ERROR);
698 /* reset to non-blocking */
699 fcntl(port->sock, F_SETFL, 1);
705 * StreamClose -- close a client/backend connection
708 StreamClose(int sock)
713 /* ---------------------------
714 * StreamOpen -- From client, initiate a connection with the
715 * server (Postmaster).
717 * RETURNS: STATUS_OK or STATUS_ERROR
719 * NOTE: connection is NOT established just because this
720 * routine exits. Local state is ok, but we haven't
721 * spoken to the postmaster yet.
722 * ---------------------------
725 StreamOpen(char *hostName, short portName, Port *port)
732 /* set up the server (remote) address */
733 MemSet((char *) &port->raddr, 0, sizeof(port->raddr));
736 if (!(hp = gethostbyname(hostName)) || hp->h_addrtype != AF_INET)
739 "FATAL: StreamOpen: unknown hostname: %s\n",
741 fputs(PQerrormsg, stderr);
742 pqdebug("%s", PQerrormsg);
743 return (STATUS_ERROR);
745 memmove((char *) &(port->raddr.in.sin_addr),
748 port->raddr.in.sin_family = AF_INET;
749 port->raddr.in.sin_port = htons(portName);
750 len = sizeof(struct sockaddr_in);
754 port->raddr.un.sun_family = AF_UNIX;
755 len = UNIXSOCK_PATH(port->raddr.un, portName);
757 /* connect to the server */
758 if ((port->sock = socket(port->raddr.sa.sa_family, SOCK_STREAM, 0)) < 0)
761 "FATAL: StreamOpen: socket() failed: errno=%d\n",
763 fputs(PQerrormsg, stderr);
764 pqdebug("%s", PQerrormsg);
765 return (STATUS_ERROR);
767 err = connect(port->sock, &port->raddr.sa, len);
771 "FATAL: StreamOpen: connect() failed: errno=%d\n",
773 fputs(PQerrormsg, stderr);
774 pqdebug("%s", PQerrormsg);
775 return (STATUS_ERROR);
778 /* fill in the client address */
779 if (getsockname(port->sock, &port->laddr.sa, &len) < 0)
782 "FATAL: StreamOpen: getsockname() failed: errno=%d\n",
784 fputs(PQerrormsg, stderr);
785 pqdebug("%s", PQerrormsg);
786 return (STATUS_ERROR);