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.30 1997/11/21 18:10:15 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.
42 #include <unistd.h> /* for ttyname() */
43 #include <sys/types.h>
45 #include <sys/socket.h>
47 #include <netinet/in.h>
48 #include <netinet/tcp.h>
49 #include <arpa/inet.h>
53 #define SOMAXCONN 5 /* from Linux listen(2) man page */
54 #endif /* SOMAXCONN */
59 #include <libpq/pqsignal.h>
60 #include <libpq/auth.h>
61 #include <libpq/libpq.h> /* where the declarations go */
62 #include <storage/ipc.h>
70 FILE *Pfdebug; /* debugging libpq */
71 int PQAsyncNotifyWaiting; /* for async. notification */
73 /* --------------------------------
74 * pq_init - open portal file descriptors
75 * --------------------------------
80 Pfin = fdopen(fd, "r");
81 Pfout = fdopen(dup(fd), "w");
83 elog(FATAL, "pq_init: Couldn't initialize socket connection");
85 if (getenv("LIBPQ_DEBUG"))
95 /* -------------------------
98 * get a character from the input file,
100 * if Pfdebug is set, also echo the character fetched into Pfdebug
102 * used for debugging libpq
110 if (Pfdebug && c != EOF)
115 /* --------------------------------
116 * pq_gettty - return the name of the tty in the given buffer
117 * --------------------------------
122 strncpy(tp, ttyname(0), 19);
125 /* --------------------------------
126 * pq_getport - return the PGPORT setting
127 * --------------------------------
132 char *envport = getenv("PGPORT");
135 return (atoi(envport));
136 return (atoi(DEF_PGPORT));
139 /* --------------------------------
140 * pq_close - close input / output connections
141 * --------------------------------
156 PQAsyncNotifyWaiting = 0;
161 /* --------------------------------
162 * pq_flush - flush pending output
163 * --------------------------------
172 /* --------------------------------
173 * pq_getstr - get a null terminated string from connection
174 * --------------------------------
177 pq_getstr(char *s, int maxlen)
181 if (Pfin == (FILE *) NULL)
183 /* elog(DEBUG, "Input descriptor is null"); */
187 while (maxlen-- && (c = pq_getc(Pfin)) != EOF && c)
192 * If EOF reached let caller know.
193 * (This will only happen if we hit EOF before the string
194 * delimiter is reached.)
203 * USER FUNCTION - gets a newline-terminated string from the backend.
205 * Chiefly here so that applications can use "COPY <rel> to stdout"
206 * and read the output string. Returns a null-terminated string in s.
208 * PQgetline reads up to maxlen-1 characters (like fgets(3)) but strips
209 * the terminating \n (like gets(3)).
212 * EOF if it is detected or invalid arguments are given
213 * 0 if EOL is reached (i.e., \n has been read)
214 * (this is required for backward-compatibility -- this
215 * routine used to always return EOF or 0, assuming that
216 * the line ended within maxlen bytes.)
220 PQgetline(char *s, int maxlen)
222 if (!Pfin || !s || maxlen <= 1)
225 if (fgets(s, maxlen - 1, Pfin) == NULL)
227 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);
275 if (Pfin == (FILE *) NULL)
277 /* elog(DEBUG, "Input descriptor is null"); */
282 while (maxlen-- && (c = pq_getc(Pfin)) != EOF)
286 * If EOF reached let caller know
295 /* --------------------------------
296 * pq_getint - get an integer from connection
297 * we receive an integer a byte at a type and reconstruct it so that
298 * machines with different ENDIAN representations can talk to each
300 * --------------------------------
312 * mjl: Seems inconsisten w/ return value of pq_putint (void). Also,
313 * EOF is a valid return value for an int! XXX
319 status = ((n = fgetc(Pfin)) == EOF);
322 status = pqGetShort(&n, Pfin);
325 status = pqGetLong(&n, Pfin);
328 fprintf(stderr, "** Unsupported size %d\n", b);
334 "FATAL: pq_getint failed: errno=%d\n", errno);
335 fputs(PQerrormsg, stderr);
336 pqdebug("%s", PQerrormsg);
343 /* --------------------------------
344 * pq_putstr - send a null terminated string to connection
345 * --------------------------------
350 if (pqPutString(s, Pfout))
353 "FATAL: pq_putstr: fputs() failed: errno=%d\n", errno);
354 fputs(PQerrormsg, stderr);
355 pqdebug("%s", PQerrormsg);
359 /* --------------------------------
360 * pq_putnchar - send n characters to connection
361 * --------------------------------
364 pq_putnchar(char *s, int n)
366 if (pqPutNBytes(s, n, Pfout))
369 "FATAL: pq_putnchar: fputc() failed: errno=%d\n",
371 fputs(PQerrormsg, stderr);
372 pqdebug("%s", PQerrormsg);
376 /* --------------------------------
377 * pq_putint - send an integer to connection
378 * we chop an integer into bytes and send individual bytes
379 * machines with different ENDIAN representations can still talk to each
381 * --------------------------------
384 pq_putint(int i, int b)
395 status = (fputc(i, Pfout) == EOF);
398 status = pqPutShort(i, Pfout);
401 status = pqPutLong(i, Pfout);
404 fprintf(stderr, "** Unsupported size %d\n", b);
410 "FATAL: pq_putint failed: errno=%d\n", errno);
411 fputs(PQerrormsg, stderr);
412 pqdebug("%s", PQerrormsg);
417 * pq_sendoob - send a string over the out-of-band channel
418 * pq_recvoob - receive a string over the oob channel
419 * NB: Fortunately, the out-of-band channel doesn't conflict with
420 * buffered I/O because it is separate from regular com. channel.
424 pq_sendoob(char *msg, int len)
426 int fd = fileno(Pfout);
428 return (send(fd, msg, len, MSG_OOB));
432 pq_recvoob(char *msgPtr, int *lenPtr)
434 int fd = fileno(Pfout);
437 len = recv(fd, msgPtr + len, *lenPtr, MSG_OOB);
442 /* --------------------------------
443 * pq_getinaddr - initialize address from host and port number
444 * --------------------------------
447 pq_getinaddr(struct sockaddr_in * sin,
453 MemSet((char *) sin, 0, sizeof(*sin));
457 if (*host >= '0' && *host <= '9')
458 sin->sin_addr.s_addr = inet_addr(host);
461 if (!(hs = gethostbyname(host)))
466 if (hs->h_addrtype != AF_INET)
469 "FATAL: pq_getinaddr: %s not on Internet\n",
471 fputs(PQerrormsg, stderr);
472 pqdebug("%s", PQerrormsg);
475 memmove((char *) &sin->sin_addr,
480 sin->sin_family = AF_INET;
481 sin->sin_port = htons(port);
485 /* --------------------------------
486 * pq_getinserv - initialize address from host and servive name
487 * --------------------------------
490 pq_getinserv(struct sockaddr_in * sin, char *host, char *serv)
494 if (*serv >= '0' && *serv <= '9')
495 return (pq_getinaddr(sin, host, atoi(serv)));
496 if (!(ss = getservbyname(serv, NULL)))
499 "FATAL: pq_getinserv: unknown service: %s\n",
501 fputs(PQerrormsg, stderr);
502 pqdebug("%s", PQerrormsg);
505 return (pq_getinaddr(sin, host, ntohs(ss->s_port)));
509 * register an out-of-band listener proc--at most one allowed.
510 * This is used for receiving async. notification from the backend.
513 pq_regoob(void (*fptr) ())
515 int fd = fileno(Pfout);
518 ioctl(fd, FIOSSAIOOWN, getpid());
520 ioctl(fd, SIOCSPGRP, getpid());
522 fcntl(fd, F_SETOWN, getpid());
524 pqsignal(SIGURG, fptr);
530 pqsignal(SIGURG, SIG_DFL);
539 /* int len = sizeof(msg); */
542 if (pq_recvoob(msg, &len) >= 0)
545 printf("received notification: %s\n", msg);
546 PQAsyncNotifyWaiting = 1;
547 /* PQappendNotify(msg+1); */
553 printf("SIGURG but no data: len = %d, err=%d\n", len, errno);
558 * Streams -- wrapper around Unix socket system calls
561 * Stream functions are used for vanilla TCP connection protocol.
565 * StreamServerPort -- open a sock stream "listening" port.
567 * This initializes the Postmaster's connection
570 * ASSUME: that this doesn't need to be non-blocking because
571 * the Postmaster uses select() to tell when the socket
574 * RETURNS: STATUS_OK or STATUS_ERROR
577 static char sock_path[100] = "";
587 StreamServerPort(char *hostName, short portName, int *fdP)
591 struct sockaddr_in in;
592 struct sockaddr_un un;
600 family = ((hostName != NULL) ? AF_INET : AF_UNIX);
602 if ((fd = socket(family, SOCK_STREAM, 0)) < 0)
605 "FATAL: StreamServerPort: socket() failed: errno=%d\n",
607 fputs(PQerrormsg, stderr);
608 pqdebug("%s", PQerrormsg);
609 return (STATUS_ERROR);
611 if ((setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *) &one,
615 "FATAL: StreamServerPort: setsockopt (SO_REUSEADDR) failed: errno=%d\n",
617 fputs(PQerrormsg, stderr);
618 pqdebug("%s", PQerrormsg);
619 return (STATUS_ERROR);
621 bzero(&saddr, sizeof(saddr));
622 if (family == AF_UNIX)
624 saddr.un.sun_family = family;
625 len = UNIXSOCK_PATH(saddr.un, portName);
626 strcpy(sock_path, saddr.un.sun_path);
630 saddr.in.sin_family = family;
631 saddr.in.sin_addr.s_addr = htonl(INADDR_ANY);
632 saddr.in.sin_port = htons(portName);
633 len = sizeof saddr.in;
635 err = bind(fd, (struct sockaddr *) & saddr, len);
639 "FATAL: StreamServerPort: bind() failed: errno=%d\n",
641 pqdebug("%s", PQerrormsg);
642 strcat(PQerrormsg, "\tIs another postmaster already running on that port?\n");
643 if (family == AF_UNIX)
644 strcat(PQerrormsg, "\tIf not, remove socket node (/tmp/.s.PGSQL.<portnr>)and retry.\n");
646 strcat(PQerrormsg, "\tIf not, wait a few seconds and retry.\n");
647 fputs(PQerrormsg, stderr);
648 return (STATUS_ERROR);
651 listen(fd, SOMAXCONN);
654 * MS: I took this code from Dillon's version. It makes the listening
655 * port non-blocking. That is not necessary (and may tickle kernel
658 * fcntl(fd, F_SETFD, 1); fcntl(fd, F_SETFL, FNDELAY);
662 if (family == AF_UNIX)
664 chmod(sock_path, 0777);
671 * StreamConnection -- create a new connection with client using
674 * This one should be non-blocking.
676 * RETURNS: STATUS_OK or STATUS_ERROR
679 StreamConnection(int server_fd, Port *port)
683 int family = port->raddr.in.sin_family;
685 /* accept connection (and fill in the client (remote) address) */
686 len = family == AF_INET ?
687 sizeof(struct sockaddr_in) : sizeof(struct sockaddr_un);
689 if ((port->sock = accept(server_fd,
690 (struct sockaddr *) & port->raddr,
693 elog(WARN, "postmaster: StreamConnection: accept: %m");
694 return (STATUS_ERROR);
697 /* fill in the server (local) address */
699 if (getsockname(port->sock, (struct sockaddr *) & port->laddr,
702 elog(WARN, "postmaster: StreamConnection: getsockname: %m");
703 return (STATUS_ERROR);
705 if (family == AF_INET)
710 pe = getprotobyname("TCP");
713 elog(WARN, "postmaster: getprotobyname failed");
714 return (STATUS_ERROR);
716 if (setsockopt(port->sock, pe->p_proto, TCP_NODELAY,
717 &on, sizeof(on)) < 0)
719 elog(WARN, "postmaster: setsockopt failed");
720 return (STATUS_ERROR);
724 port->mask = 1 << port->sock;
726 /* reset to non-blocking */
727 fcntl(port->sock, F_SETFL, 1);
733 * StreamClose -- close a client/backend connection
736 StreamClose(int sock)
741 /* ---------------------------
742 * StreamOpen -- From client, initiate a connection with the
743 * server (Postmaster).
745 * RETURNS: STATUS_OK or STATUS_ERROR
747 * NOTE: connection is NOT established just because this
748 * routine exits. Local state is ok, but we haven't
749 * spoken to the postmaster yet.
750 * ---------------------------
753 StreamOpen(char *hostName, short portName, Port *port)
760 /* set up the server (remote) address */
761 MemSet((char *) &port->raddr, 0, sizeof(port->raddr));
764 if (!(hp = gethostbyname(hostName)) || hp->h_addrtype != AF_INET)
767 "FATAL: StreamOpen: unknown hostname: %s\n",
769 fputs(PQerrormsg, stderr);
770 pqdebug("%s", PQerrormsg);
771 return (STATUS_ERROR);
773 memmove((char *) &(port->raddr.in.sin_addr),
776 port->raddr.in.sin_family = AF_INET;
777 port->raddr.in.sin_port = htons(portName);
778 len = sizeof(struct sockaddr_in);
782 port->raddr.un.sun_family = AF_UNIX;
783 len = UNIXSOCK_PATH(port->raddr.un, portName);
785 /* connect to the server */
786 if ((port->sock = socket(port->raddr.in.sin_family, SOCK_STREAM, 0)) < 0)
789 "FATAL: StreamOpen: socket() failed: errno=%d\n",
791 fputs(PQerrormsg, stderr);
792 pqdebug("%s", PQerrormsg);
793 return (STATUS_ERROR);
795 err = connect(port->sock, (struct sockaddr *) & port->raddr, len);
799 "FATAL: StreamOpen: connect() failed: errno=%d\n",
801 fputs(PQerrormsg, stderr);
802 pqdebug("%s", PQerrormsg);
803 return (STATUS_ERROR);
806 /* fill in the client address */
807 if (getsockname(port->sock, (struct sockaddr *) & port->laddr,
811 "FATAL: StreamOpen: getsockname() failed: errno=%d\n",
813 fputs(PQerrormsg, stderr);
814 pqdebug("%s", PQerrormsg);
815 return (STATUS_ERROR);
821 static char *authentication_type_name[] = {
823 "the default authentication type",
827 "host-based authentication",
829 "plaintext password authentication"
833 name_of_authentication_type(int type)
837 if (type >= 1 && type <= LAST_AUTHENTICATION_TYPE)
839 result = authentication_type_name[type];
844 result = "<unknown authentication type>";