]> granicus.if.org Git - postgresql/blob - src/interfaces/libpq/fe-auth.c
Allow pg_ctl to determine the server is up when getting a request for a
[postgresql] / src / interfaces / libpq / fe-auth.c
1 /*-------------------------------------------------------------------------
2  *
3  * fe-auth.c
4  *         The front-end (client) authorization routines
5  *
6  * Portions Copyright (c) 1996-2004, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  * NOTE: the error message strings returned by this module must not
10  * exceed INITIAL_EXPBUFFER_SIZE (currently 256 bytes).
11  *
12  * IDENTIFICATION
13  *        $PostgreSQL: pgsql/src/interfaces/libpq/fe-auth.c,v 1.94 2004/10/16 03:10:17 momjian Exp $
14  *
15  *-------------------------------------------------------------------------
16  */
17
18 /*
19  * INTERFACE ROUTINES
20  *         frontend (client) routines:
21  *              fe_sendauth                             send authentication information
22  *              fe_getauthname                  get user's name according to the client side
23  *                                                              of the authentication system
24  *              fe_setauthsvc                   set frontend authentication service
25  *              fe_getauthsvc                   get current frontend authentication service
26  *
27  *
28  *
29  */
30
31 #include "postgres_fe.h"
32
33 #ifdef WIN32
34 #include "win32.h"
35 #else
36 #include <unistd.h>
37 #include <fcntl.h>
38 #include <errno.h>
39 #include <sys/types.h>
40 #include <sys/param.h>                  /* for MAXHOSTNAMELEN on most */
41 #include <sys/socket.h>
42 #if defined(HAVE_STRUCT_CMSGCRED) || defined(HAVE_STRUCT_FCRED) || defined(HAVE_STRUCT_SOCKCRED)
43 #include <sys/uio.h>
44 #include <sys/ucred.h>
45 #endif
46 #ifndef  MAXHOSTNAMELEN
47 #include <netdb.h>                              /* for MAXHOSTNAMELEN on some */
48 #endif
49 #include <pwd.h>
50 #endif
51
52 #ifdef HAVE_CRYPT_H
53 #include <crypt.h>
54 #endif
55
56 #include "libpq-fe.h"
57 #include "libpq-int.h"
58 #include "fe-auth.h"
59 #include "libpq/crypt.h"
60
61
62 /*
63  * common definitions for generic fe/be routines
64  */
65
66 #define STARTUP_MSG             7               /* Initialise a connection */
67 #define STARTUP_KRB4_MSG        10      /* krb4 session follows */
68 #define STARTUP_KRB5_MSG        11      /* krb5 session follows */
69 #define STARTUP_PASSWORD_MSG    14              /* Password follows */
70
71 struct authsvc
72 {
73         const char *name;                       /* service nickname (for command line) */
74         MsgType         msgtype;                /* startup packet header type */
75         int                     allowed;                /* initially allowed (before command line
76                                                                  * option parsing)? */
77 };
78
79 /*
80  * Command-line parsing routines use this structure to map nicknames
81  * onto service types (and the startup packets to use with them).
82  *
83  * Programs receiving an authentication request use this structure to
84  * decide which authentication service types are currently permitted.
85  * By default, all authentication systems compiled into the system are
86  * allowed.  Unauthenticated connections are disallowed unless there
87  * isn't any authentication system.
88  */
89 static const struct authsvc authsvcs[] = {
90 #ifdef KRB4
91         {"krb4", STARTUP_KRB4_MSG, 1},
92         {"kerberos", STARTUP_KRB4_MSG, 1},
93 #endif   /* KRB4 */
94 #ifdef KRB5
95         {"krb5", STARTUP_KRB5_MSG, 1},
96         {"kerberos", STARTUP_KRB5_MSG, 1},
97 #endif   /* KRB5 */
98         {UNAUTHNAME, STARTUP_MSG,
99 #if defined(KRB4) || defined(KRB5)
100                 0
101 #else                                                   /* !(KRB4 || KRB5) */
102                 1
103 #endif   /* !(KRB4 || KRB5) */
104         },
105         {"password", STARTUP_PASSWORD_MSG, 0}
106 };
107
108 static const int n_authsvcs = sizeof(authsvcs) / sizeof(struct authsvc);
109
110 #ifdef KRB4
111 /*
112  * MIT Kerberos authentication system - protocol version 4
113  */
114
115 #include "krb.h"
116
117 /* for some reason, this is not defined in krb.h ... */
118 extern char *tkt_string(void);
119
120 /*
121  * pg_krb4_init -- initialization performed before any Kerberos calls are made
122  *
123  * For v4, all we need to do is make sure the library routines get the right
124  * ticket file if we want them to see a special one.  (They will open the file
125  * themselves.)
126  */
127 static void
128 pg_krb4_init()
129 {
130         char       *realm;
131         static int      init_done = 0;
132
133         if (init_done)
134                 return;
135         init_done = 1;
136
137         /*
138          * If the user set PGREALM, then we use a ticket file with a special
139          * name: <usual-ticket-file-name>@<PGREALM-value>
140          */
141         if ((realm = getenv("PGREALM")))
142         {
143                 char            tktbuf[MAXPGPATH];
144
145                 (void) snprintf(tktbuf, sizeof(tktbuf), "%s@%s", tkt_string(), realm);
146                 krb_set_tkt_string(tktbuf);
147         }
148 }
149
150 /*
151  * pg_krb4_authname -- returns a pointer to static space containing whatever
152  *                                         name the user has authenticated to the system
153  *
154  * We obtain this information by digging around in the ticket file.
155  */
156 static char *
157 pg_krb4_authname(char *PQerrormsg)
158 {
159         char            instance[INST_SZ + 1];
160         char            realm[REALM_SZ + 1];
161         int                     status;
162         static char name[SNAME_SZ + 1] = "";
163
164         if (name[0])
165                 return name;
166
167         pg_krb4_init();
168
169         name[SNAME_SZ] = '\0';
170         status = krb_get_tf_fullname(tkt_string(), name, instance, realm);
171         if (status != KSUCCESS)
172         {
173                 snprintf(PQerrormsg, PQERRORMSG_LENGTH,
174                                  "pg_krb4_authname: krb_get_tf_fullname: %s\n",
175                                  krb_err_txt[status]);
176                 return NULL;
177         }
178         return name;
179 }
180
181 /*
182  * pg_krb4_sendauth -- client routine to send authentication information to
183  *                                         the server
184  *
185  * This routine does not do mutual authentication, nor does it return enough
186  * information to do encrypted connections.  But then, if we want to do
187  * encrypted connections, we'll have to redesign the whole RPC mechanism
188  * anyway.
189  *
190  * If the user is too lazy to feed us a hostname, we try to come up with
191  * something other than "localhost" since the hostname is used as an
192  * instance and instance names in v4 databases are usually actual hostnames
193  * (canonicalized to omit all domain suffixes).
194  */
195 static int
196 pg_krb4_sendauth(char *PQerrormsg, int sock,
197                                  struct sockaddr_in * laddr,
198                                  struct sockaddr_in * raddr,
199                                  const char *hostname)
200 {
201         long            krbopts = 0;    /* one-way authentication */
202         KTEXT_ST        clttkt;
203         int                     status;
204         char            hostbuf[MAXHOSTNAMELEN];
205         const char *realm = getenv("PGREALM");          /* NULL == current realm */
206
207         if (!hostname || !(*hostname))
208         {
209                 if (gethostname(hostbuf, MAXHOSTNAMELEN) < 0)
210                         strcpy(hostbuf, "localhost");
211                 hostname = hostbuf;
212         }
213
214         pg_krb4_init();
215
216         status = krb_sendauth(krbopts,
217                                                   sock,
218                                                   &clttkt,
219                                                   PG_KRB_SRVNAM,
220                                                   hostname,
221                                                   realm,
222                                                   (u_long) 0,
223                                                   NULL,
224                                                   NULL,
225                                                   NULL,
226                                                   laddr,
227                                                   raddr,
228                                                   PG_KRB4_VERSION);
229         if (status != KSUCCESS)
230         {
231                 snprintf(PQerrormsg, PQERRORMSG_LENGTH,
232                                  libpq_gettext("Kerberos 4 error: %s\n"),
233                                  krb_err_txt[status]);
234                 return STATUS_ERROR;
235         }
236         return STATUS_OK;
237 }
238 #endif   /* KRB4 */
239
240 #ifdef KRB5
241 /*
242  * MIT Kerberos authentication system - protocol version 5
243  */
244
245 #include <krb5.h>
246 #include <com_err.h>
247
248 /*
249  * pg_an_to_ln -- return the local name corresponding to an authentication
250  *                                name
251  *
252  * XXX Assumes that the first aname component is the user name.  This is NOT
253  *         necessarily so, since an aname can actually be something out of your
254  *         worst X.400 nightmare, like
255  *                ORGANIZATION=U. C. Berkeley/NAME=Paul M. Aoki@CS.BERKELEY.EDU
256  *         Note that the MIT an_to_ln code does the same thing if you don't
257  *         provide an aname mapping database...it may be a better idea to use
258  *         krb5_an_to_ln, except that it punts if multiple components are found,
259  *         and we can't afford to punt.
260  */
261 static char *
262 pg_an_to_ln(char *aname)
263 {
264         char       *p;
265
266         if ((p = strchr(aname, '/')) || (p = strchr(aname, '@')))
267                 *p = '\0';
268         return aname;
269 }
270
271
272 /*
273  * Various krb5 state which is not connection specific, and a flag to
274  * indicate whether we have initialised it yet.
275  */
276 static int      pg_krb5_initialised;
277 static krb5_context pg_krb5_context;
278 static krb5_ccache pg_krb5_ccache;
279 static krb5_principal pg_krb5_client;
280 static char *pg_krb5_name;
281
282
283 static int
284 pg_krb5_init(char *PQerrormsg)
285 {
286         krb5_error_code retval;
287
288         if (pg_krb5_initialised)
289                 return STATUS_OK;
290
291         retval = krb5_init_context(&pg_krb5_context);
292         if (retval)
293         {
294                 snprintf(PQerrormsg, PQERRORMSG_LENGTH,
295                                  "pg_krb5_init: krb5_init_context: %s\n",
296                                  error_message(retval));
297                 return STATUS_ERROR;
298         }
299
300         retval = krb5_cc_default(pg_krb5_context, &pg_krb5_ccache);
301         if (retval)
302         {
303                 snprintf(PQerrormsg, PQERRORMSG_LENGTH,
304                                  "pg_krb5_init: krb5_cc_default: %s\n",
305                                  error_message(retval));
306                 krb5_free_context(pg_krb5_context);
307                 return STATUS_ERROR;
308         }
309
310         retval = krb5_cc_get_principal(pg_krb5_context, pg_krb5_ccache,
311                                                                    &pg_krb5_client);
312         if (retval)
313         {
314                 snprintf(PQerrormsg, PQERRORMSG_LENGTH,
315                                  "pg_krb5_init: krb5_cc_get_principal: %s\n",
316                                  error_message(retval));
317                 krb5_cc_close(pg_krb5_context, pg_krb5_ccache);
318                 krb5_free_context(pg_krb5_context);
319                 return STATUS_ERROR;
320         }
321
322         retval = krb5_unparse_name(pg_krb5_context, pg_krb5_client, &pg_krb5_name);
323         if (retval)
324         {
325                 snprintf(PQerrormsg, PQERRORMSG_LENGTH,
326                                  "pg_krb5_init: krb5_unparse_name: %s\n",
327                                  error_message(retval));
328                 krb5_free_principal(pg_krb5_context, pg_krb5_client);
329                 krb5_cc_close(pg_krb5_context, pg_krb5_ccache);
330                 krb5_free_context(pg_krb5_context);
331                 return STATUS_ERROR;
332         }
333
334         pg_krb5_name = pg_an_to_ln(pg_krb5_name);
335
336         pg_krb5_initialised = 1;
337         return STATUS_OK;
338 }
339
340
341 /*
342  * pg_krb5_authname -- returns a pointer to static space containing whatever
343  *                                         name the user has authenticated to the system
344   */
345 static const char *
346 pg_krb5_authname(char *PQerrormsg)
347 {
348         if (pg_krb5_init(PQerrormsg) != STATUS_OK)
349                 return NULL;
350
351         return pg_krb5_name;
352 }
353
354
355 /*
356  * pg_krb5_sendauth -- client routine to send authentication information to
357  *                                         the server
358  */
359 static int
360 pg_krb5_sendauth(char *PQerrormsg, int sock, const char *hostname)
361 {
362         krb5_error_code retval;
363         int                     ret;
364         krb5_principal server;
365         krb5_auth_context auth_context = NULL;
366         krb5_error *err_ret = NULL;
367         int                     flags;
368
369         ret = pg_krb5_init(PQerrormsg);
370         if (ret != STATUS_OK)
371                 return ret;
372
373         retval = krb5_sname_to_principal(pg_krb5_context, hostname, PG_KRB_SRVNAM,
374                                                                          KRB5_NT_SRV_HST, &server);
375         if (retval)
376         {
377                 snprintf(PQerrormsg, PQERRORMSG_LENGTH,
378                                  "pg_krb5_sendauth: krb5_sname_to_principal: %s\n",
379                                  error_message(retval));
380                 return STATUS_ERROR;
381         }
382
383         /*
384          * libpq uses a non-blocking socket. But kerberos needs a blocking
385          * socket, and we have to block somehow to do mutual authentication
386          * anyway. So we temporarily make it blocking.
387          */
388         flags = fcntl(sock, F_GETFL);
389         if (flags < 0 || fcntl(sock, F_SETFL, (long) (flags & ~O_NONBLOCK)))
390         {
391                 char            sebuf[256];
392
393                 snprintf(PQerrormsg, PQERRORMSG_LENGTH,
394                                  libpq_gettext("could not set socket to blocking mode: %s\n"), pqStrerror(errno, sebuf, sizeof(sebuf)));
395                 krb5_free_principal(pg_krb5_context, server);
396                 return STATUS_ERROR;
397         }
398
399         retval = krb5_sendauth(pg_krb5_context, &auth_context,
400                                                    (krb5_pointer) & sock, PG_KRB_SRVNAM,
401                                                    pg_krb5_client, server,
402                                                    AP_OPTS_MUTUAL_REQUIRED,
403                                                    NULL, 0,             /* no creds, use ccache instead */
404                                                    pg_krb5_ccache, &err_ret, NULL, NULL);
405         if (retval)
406         {
407                 if (retval == KRB5_SENDAUTH_REJECTED && err_ret)
408                 {
409 #if defined(HAVE_KRB5_ERROR_TEXT_DATA)
410                         snprintf(PQerrormsg, PQERRORMSG_LENGTH,
411                           libpq_gettext("Kerberos 5 authentication rejected: %*s\n"),
412                                          (int) err_ret->text.length, err_ret->text.data);
413 #elif defined(HAVE_KRB5_ERROR_E_DATA)
414                         snprintf(PQerrormsg, PQERRORMSG_LENGTH,
415                           libpq_gettext("Kerberos 5 authentication rejected: %*s\n"),
416                                          (int) err_ret->e_data->length,
417                                          (const char *) err_ret->e_data->data);
418 #else
419 #error "bogus configuration"
420 #endif
421                 }
422                 else
423                 {
424                         snprintf(PQerrormsg, PQERRORMSG_LENGTH,
425                                          "krb5_sendauth: %s\n", error_message(retval));
426                 }
427
428                 if (err_ret)
429                         krb5_free_error(pg_krb5_context, err_ret);
430
431                 ret = STATUS_ERROR;
432         }
433
434         krb5_free_principal(pg_krb5_context, server);
435
436         if (fcntl(sock, F_SETFL, (long) flags))
437         {
438                 char            sebuf[256];
439
440                 snprintf(PQerrormsg, PQERRORMSG_LENGTH,
441                                  libpq_gettext("could not restore non-blocking mode on socket: %s\n"),
442                                  pqStrerror(errno, sebuf, sizeof(sebuf)));
443                 ret = STATUS_ERROR;
444         }
445
446         return ret;
447 }
448 #endif   /* KRB5 */
449
450 /*
451  * Respond to AUTH_REQ_SCM_CREDS challenge.
452  *
453  * Note: current backends will not use this challenge if HAVE_GETPEEREID
454  * or SO_PEERCRED is defined, but pre-7.4 backends might, so compile the
455  * code anyway.
456  */
457 static int
458 pg_local_sendauth(char *PQerrormsg, PGconn *conn)
459 {
460 #if defined(HAVE_STRUCT_CMSGCRED) || defined(HAVE_STRUCT_FCRED) || \
461         (defined(HAVE_STRUCT_SOCKCRED) && defined(LOCAL_CREDS))
462         char            buf;
463         struct iovec iov;
464         struct msghdr msg;
465
466 #ifdef HAVE_STRUCT_CMSGCRED
467         /* Prevent padding */
468         char            cmsgmem[sizeof(struct cmsghdr) + sizeof(struct cmsgcred)];
469
470         /* Point to start of first structure */
471         struct cmsghdr *cmsg = (struct cmsghdr *) cmsgmem;
472 #endif
473
474         /*
475          * The backend doesn't care what we send here, but it wants exactly
476          * one character to force recvmsg() to block and wait for us.
477          */
478         buf = '\0';
479         iov.iov_base = &buf;
480         iov.iov_len = 1;
481
482         memset(&msg, 0, sizeof(msg));
483         msg.msg_iov = &iov;
484         msg.msg_iovlen = 1;
485
486 #ifdef HAVE_STRUCT_CMSGCRED
487         /* Create control header, FreeBSD */
488         msg.msg_control = cmsg;
489         msg.msg_controllen = sizeof(cmsgmem);
490         memset(cmsg, 0, sizeof(cmsgmem));
491         cmsg->cmsg_len = sizeof(cmsgmem);
492         cmsg->cmsg_level = SOL_SOCKET;
493         cmsg->cmsg_type = SCM_CREDS;
494 #endif
495
496         if (sendmsg(conn->sock, &msg, 0) == -1)
497         {
498                 char            sebuf[256];
499
500                 snprintf(PQerrormsg, PQERRORMSG_LENGTH,
501                                  "pg_local_sendauth: sendmsg: %s\n",
502                                  pqStrerror(errno, sebuf, sizeof(sebuf)));
503                 return STATUS_ERROR;
504         }
505         return STATUS_OK;
506 #else
507         snprintf(PQerrormsg, PQERRORMSG_LENGTH,
508                 libpq_gettext("SCM_CRED authentication method not supported\n"));
509         return STATUS_ERROR;
510 #endif
511 }
512
513 static int
514 pg_password_sendauth(PGconn *conn, const char *password, AuthRequest areq)
515 {
516         int                     ret;
517         char       *crypt_pwd;
518
519         /* Encrypt the password if needed. */
520
521         switch (areq)
522         {
523                 case AUTH_REQ_MD5:
524                         {
525                                 char       *crypt_pwd2;
526
527                                 if (!(crypt_pwd = malloc(MD5_PASSWD_LEN + 1)) ||
528                                         !(crypt_pwd2 = malloc(MD5_PASSWD_LEN + 1)))
529                                 {
530                                         perror("malloc");
531                                         return STATUS_ERROR;
532                                 }
533                                 if (!EncryptMD5(password, conn->pguser,
534                                                                 strlen(conn->pguser), crypt_pwd2))
535                                 {
536                                         free(crypt_pwd);
537                                         free(crypt_pwd2);
538                                         return STATUS_ERROR;
539                                 }
540                                 if (!EncryptMD5(crypt_pwd2 + strlen("md5"), conn->md5Salt,
541                                                                 sizeof(conn->md5Salt), crypt_pwd))
542                                 {
543                                         free(crypt_pwd);
544                                         free(crypt_pwd2);
545                                         return STATUS_ERROR;
546                                 }
547                                 free(crypt_pwd2);
548                                 break;
549                         }
550                 case AUTH_REQ_CRYPT:
551                         {
552                                 char            salt[3];
553
554                                 StrNCpy(salt, conn->cryptSalt, 3);
555                                 crypt_pwd = crypt(password, salt);
556                                 break;
557                         }
558                 case AUTH_REQ_PASSWORD:
559                         /* discard const so we can assign it */
560                         crypt_pwd = (char *) password;
561                         break;
562                 default:
563                         return STATUS_ERROR;
564         }
565         /* Packet has a message type as of protocol 3.0 */
566         if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
567                 ret = pqPacketSend(conn, 'p', crypt_pwd, strlen(crypt_pwd) + 1);
568         else
569                 ret = pqPacketSend(conn, 0, crypt_pwd, strlen(crypt_pwd) + 1);
570         if (areq == AUTH_REQ_MD5)
571                 free(crypt_pwd);
572         return ret;
573 }
574
575 /*
576  * fe_sendauth -- client demux routine for outgoing authentication information
577  */
578 int
579 fe_sendauth(AuthRequest areq, PGconn *conn, const char *hostname,
580                         const char *password, char *PQerrormsg)
581 {
582 #if !defined(KRB4) && !defined(KRB5)
583         (void) hostname;                        /* not used */
584 #endif
585
586         switch (areq)
587         {
588                 case AUTH_REQ_OK:
589                         break;
590
591                 case AUTH_REQ_KRB4:
592 #ifdef KRB4
593                         pglock_thread();
594                         if (pg_krb4_sendauth(PQerrormsg, conn->sock,
595                                                            (struct sockaddr_in *) & conn->laddr.addr,
596                                                            (struct sockaddr_in *) & conn->raddr.addr,
597                                                                  hostname) != STATUS_OK)
598                         {
599                                 snprintf(PQerrormsg, PQERRORMSG_LENGTH,
600                                         libpq_gettext("Kerberos 4 authentication failed\n"));
601                                 pgunlock_thread();
602                                 return STATUS_ERROR;
603                         }
604                         pgunlock_thread();
605                         break;
606 #else
607                         snprintf(PQerrormsg, PQERRORMSG_LENGTH,
608                          libpq_gettext("Kerberos 4 authentication not supported\n"));
609                         return STATUS_ERROR;
610 #endif
611
612                 case AUTH_REQ_KRB5:
613 #ifdef KRB5
614                         pglock_thread();
615                         if (pg_krb5_sendauth(PQerrormsg, conn->sock,
616                                                                  hostname) != STATUS_OK)
617                         {
618                                 snprintf(PQerrormsg, PQERRORMSG_LENGTH,
619                                         libpq_gettext("Kerberos 5 authentication failed\n"));
620                                 pgunlock_thread();
621                                 return STATUS_ERROR;
622                         }
623                         pgunlock_thread();
624                         break;
625 #else
626                         snprintf(PQerrormsg, PQERRORMSG_LENGTH,
627                          libpq_gettext("Kerberos 5 authentication not supported\n"));
628                         return STATUS_ERROR;
629 #endif
630
631                 case AUTH_REQ_MD5:
632                 case AUTH_REQ_CRYPT:
633                 case AUTH_REQ_PASSWORD:
634                         if (password == NULL || *password == '\0')
635                         {
636                                 (void) snprintf(PQerrormsg, PQERRORMSG_LENGTH,
637                                                                 PQnoPasswordSupplied);
638                                 return STATUS_ERROR;
639                         }
640                         if (pg_password_sendauth(conn, password, areq) != STATUS_OK)
641                         {
642                                 (void) snprintf(PQerrormsg, PQERRORMSG_LENGTH,
643                                  "fe_sendauth: error sending password authentication\n");
644                                 return STATUS_ERROR;
645                         }
646                         break;
647
648                 case AUTH_REQ_SCM_CREDS:
649                         if (pg_local_sendauth(PQerrormsg, conn) != STATUS_OK)
650                                 return STATUS_ERROR;
651                         break;
652
653                 default:
654                         snprintf(PQerrormsg, PQERRORMSG_LENGTH,
655                                          libpq_gettext("authentication method %u not supported\n"), areq);
656                         return STATUS_ERROR;
657         }
658
659         return STATUS_OK;
660 }
661
662 /*
663  * fe_setauthsvc
664  * fe_getauthsvc
665  *
666  * Set/return the authentication service currently selected for use by the
667  * frontend. (You can only use one in the frontend, obviously.)
668  *
669  * NB: This is not thread-safe if different threads try to select different
670  * authentication services!  It's OK for fe_getauthsvc to select the default,
671  * since that will be the same for all threads, but direct application use
672  * of fe_setauthsvc is not thread-safe.  However, use of fe_setauthsvc is
673  * deprecated anyway...
674  */
675
676 static int      pg_authsvc = -1;
677
678 void
679 fe_setauthsvc(const char *name, char *PQerrormsg)
680 {
681         int                     i;
682
683         for (i = 0; i < n_authsvcs; ++i)
684                 if (strcmp(name, authsvcs[i].name) == 0)
685                 {
686                         pg_authsvc = i;
687                         break;
688                 }
689         if (i == n_authsvcs)
690         {
691                 snprintf(PQerrormsg, PQERRORMSG_LENGTH,
692                                  libpq_gettext("invalid authentication service name \"%s\", ignored\n"),
693                                  name);
694         }
695         return;
696 }
697
698 MsgType
699 fe_getauthsvc(char *PQerrormsg)
700 {
701         if (pg_authsvc < 0 || pg_authsvc >= n_authsvcs)
702         {
703                 fe_setauthsvc(DEFAULT_CLIENT_AUTHSVC, PQerrormsg);
704                 if (pg_authsvc < 0 || pg_authsvc >= n_authsvcs)
705                 {
706                         /* Can only get here if DEFAULT_CLIENT_AUTHSVC is misdefined */
707                         return 0;
708                 }
709         }
710         return authsvcs[pg_authsvc].msgtype;
711 }
712
713 /*
714  * fe_getauthname -- returns a pointer to dynamic space containing whatever
715  *                                       name the user has authenticated to the system
716  * if there is an error, return the error message in PQerrormsg
717  */
718 char *
719 fe_getauthname(char *PQerrormsg)
720 {
721         const char *name = NULL;
722         char       *authn = NULL;
723         MsgType         authsvc;
724
725         authsvc = fe_getauthsvc(PQerrormsg);
726
727         /* this just guards against broken DEFAULT_CLIENT_AUTHSVC, see above */
728         if (authsvc == 0)
729                 return NULL;                    /* leave original error message in place */
730
731         pglock_thread();
732 #ifdef KRB4
733         if (authsvc == STARTUP_KRB4_MSG)
734                 name = pg_krb4_authname(PQerrormsg);
735 #endif
736 #ifdef KRB5
737         if (authsvc == STARTUP_KRB5_MSG)
738                 name = pg_krb5_authname(PQerrormsg);
739 #endif
740
741         if (authsvc == STARTUP_MSG
742                 || (authsvc == STARTUP_KRB4_MSG && !name)
743                 || (authsvc == STARTUP_KRB5_MSG && !name))
744         {
745 #ifdef WIN32
746                 char            username[128];
747                 DWORD           namesize = sizeof(username) - 1;
748
749                 if (GetUserName(username, &namesize))
750                         name = username;
751 #else
752                 char            pwdbuf[BUFSIZ];
753                 struct passwd pwdstr;
754                 struct passwd *pw = NULL;
755
756                 if (pqGetpwuid(geteuid(), &pwdstr,
757                                            pwdbuf, sizeof(pwdbuf), &pw) == 0)
758                         name = pw->pw_name;
759 #endif
760         }
761
762         if (authsvc != STARTUP_MSG && authsvc != STARTUP_KRB4_MSG && authsvc != STARTUP_KRB5_MSG)
763                 snprintf(PQerrormsg, PQERRORMSG_LENGTH,
764                                  libpq_gettext("fe_getauthname: invalid authentication system: %d\n"),
765                                  authsvc);
766
767         if (name && (authn = (char *) malloc(strlen(name) + 1)))
768                 strcpy(authn, name);
769         pgunlock_thread();
770         return authn;
771 }