]> granicus.if.org Git - postgresql/blob - src/interfaces/libpq/fe-auth.c
Clean up code in libpq that obtains user's home directory: make a single
[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-2005, 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.98 2005/01/04 23:18:25 tgl 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
247 /*
248  * pg_an_to_ln -- return the local name corresponding to an authentication
249  *                                name
250  *
251  * XXX Assumes that the first aname component is the user name.  This is NOT
252  *         necessarily so, since an aname can actually be something out of your
253  *         worst X.400 nightmare, like
254  *                ORGANIZATION=U. C. Berkeley/NAME=Paul M. Aoki@CS.BERKELEY.EDU
255  *         Note that the MIT an_to_ln code does the same thing if you don't
256  *         provide an aname mapping database...it may be a better idea to use
257  *         krb5_an_to_ln, except that it punts if multiple components are found,
258  *         and we can't afford to punt.
259  */
260 static char *
261 pg_an_to_ln(char *aname)
262 {
263         char       *p;
264
265         if ((p = strchr(aname, '/')) || (p = strchr(aname, '@')))
266                 *p = '\0';
267         return aname;
268 }
269
270
271 /*
272  * Various krb5 state which is not connection specific, and a flag to
273  * indicate whether we have initialised it yet.
274  */
275 static int      pg_krb5_initialised;
276 static krb5_context pg_krb5_context;
277 static krb5_ccache pg_krb5_ccache;
278 static krb5_principal pg_krb5_client;
279 static char *pg_krb5_name;
280
281
282 static int
283 pg_krb5_init(char *PQerrormsg)
284 {
285         krb5_error_code retval;
286
287         if (pg_krb5_initialised)
288                 return STATUS_OK;
289
290         retval = krb5_init_context(&pg_krb5_context);
291         if (retval)
292         {
293                 snprintf(PQerrormsg, PQERRORMSG_LENGTH,
294                                  "pg_krb5_init: krb5_init_context: %s\n",
295                                  error_message(retval));
296                 return STATUS_ERROR;
297         }
298
299         retval = krb5_cc_default(pg_krb5_context, &pg_krb5_ccache);
300         if (retval)
301         {
302                 snprintf(PQerrormsg, PQERRORMSG_LENGTH,
303                                  "pg_krb5_init: krb5_cc_default: %s\n",
304                                  error_message(retval));
305                 krb5_free_context(pg_krb5_context);
306                 return STATUS_ERROR;
307         }
308
309         retval = krb5_cc_get_principal(pg_krb5_context, pg_krb5_ccache,
310                                                                    &pg_krb5_client);
311         if (retval)
312         {
313                 snprintf(PQerrormsg, PQERRORMSG_LENGTH,
314                                  "pg_krb5_init: krb5_cc_get_principal: %s\n",
315                                  error_message(retval));
316                 krb5_cc_close(pg_krb5_context, pg_krb5_ccache);
317                 krb5_free_context(pg_krb5_context);
318                 return STATUS_ERROR;
319         }
320
321         retval = krb5_unparse_name(pg_krb5_context, pg_krb5_client, &pg_krb5_name);
322         if (retval)
323         {
324                 snprintf(PQerrormsg, PQERRORMSG_LENGTH,
325                                  "pg_krb5_init: krb5_unparse_name: %s\n",
326                                  error_message(retval));
327                 krb5_free_principal(pg_krb5_context, pg_krb5_client);
328                 krb5_cc_close(pg_krb5_context, pg_krb5_ccache);
329                 krb5_free_context(pg_krb5_context);
330                 return STATUS_ERROR;
331         }
332
333         pg_krb5_name = pg_an_to_ln(pg_krb5_name);
334
335         pg_krb5_initialised = 1;
336         return STATUS_OK;
337 }
338
339
340 /*
341  * pg_krb5_authname -- returns a pointer to static space containing whatever
342  *                                         name the user has authenticated to the system
343   */
344 static const char *
345 pg_krb5_authname(char *PQerrormsg)
346 {
347         if (pg_krb5_init(PQerrormsg) != STATUS_OK)
348                 return NULL;
349
350         return pg_krb5_name;
351 }
352
353
354 /*
355  * pg_krb5_sendauth -- client routine to send authentication information to
356  *                                         the server
357  */
358 static int
359 pg_krb5_sendauth(char *PQerrormsg, int sock, const char *hostname)
360 {
361         krb5_error_code retval;
362         int                     ret;
363         krb5_principal server;
364         krb5_auth_context auth_context = NULL;
365         krb5_error *err_ret = NULL;
366         int                     flags;
367
368         ret = pg_krb5_init(PQerrormsg);
369         if (ret != STATUS_OK)
370                 return ret;
371
372         retval = krb5_sname_to_principal(pg_krb5_context, hostname, PG_KRB_SRVNAM,
373                                                                          KRB5_NT_SRV_HST, &server);
374         if (retval)
375         {
376                 snprintf(PQerrormsg, PQERRORMSG_LENGTH,
377                                  "pg_krb5_sendauth: krb5_sname_to_principal: %s\n",
378                                  error_message(retval));
379                 return STATUS_ERROR;
380         }
381
382         /*
383          * libpq uses a non-blocking socket. But kerberos needs a blocking
384          * socket, and we have to block somehow to do mutual authentication
385          * anyway. So we temporarily make it blocking.
386          */
387         flags = fcntl(sock, F_GETFL);
388         if (flags < 0 || fcntl(sock, F_SETFL, (long) (flags & ~O_NONBLOCK)))
389         {
390                 char            sebuf[256];
391
392                 snprintf(PQerrormsg, PQERRORMSG_LENGTH,
393                                  libpq_gettext("could not set socket to blocking mode: %s\n"), pqStrerror(errno, sebuf, sizeof(sebuf)));
394                 krb5_free_principal(pg_krb5_context, server);
395                 return STATUS_ERROR;
396         }
397
398         retval = krb5_sendauth(pg_krb5_context, &auth_context,
399                                                    (krb5_pointer) & sock, PG_KRB_SRVNAM,
400                                                    pg_krb5_client, server,
401                                                    AP_OPTS_MUTUAL_REQUIRED,
402                                                    NULL, 0,             /* no creds, use ccache instead */
403                                                    pg_krb5_ccache, &err_ret, NULL, NULL);
404         if (retval)
405         {
406                 if (retval == KRB5_SENDAUTH_REJECTED && err_ret)
407                 {
408 #if defined(HAVE_KRB5_ERROR_TEXT_DATA)
409                         snprintf(PQerrormsg, PQERRORMSG_LENGTH,
410                           libpq_gettext("Kerberos 5 authentication rejected: %*s\n"),
411                                          (int) err_ret->text.length, err_ret->text.data);
412 #elif defined(HAVE_KRB5_ERROR_E_DATA)
413                         snprintf(PQerrormsg, PQERRORMSG_LENGTH,
414                           libpq_gettext("Kerberos 5 authentication rejected: %*s\n"),
415                                          (int) err_ret->e_data->length,
416                                          (const char *) err_ret->e_data->data);
417 #else
418 #error "bogus configuration"
419 #endif
420                 }
421                 else
422                 {
423                         snprintf(PQerrormsg, PQERRORMSG_LENGTH,
424                                          "krb5_sendauth: %s\n", error_message(retval));
425                 }
426
427                 if (err_ret)
428                         krb5_free_error(pg_krb5_context, err_ret);
429
430                 ret = STATUS_ERROR;
431         }
432
433         krb5_free_principal(pg_krb5_context, server);
434
435         if (fcntl(sock, F_SETFL, (long) flags))
436         {
437                 char            sebuf[256];
438
439                 snprintf(PQerrormsg, PQERRORMSG_LENGTH,
440                                  libpq_gettext("could not restore non-blocking mode on socket: %s\n"),
441                                  pqStrerror(errno, sebuf, sizeof(sebuf)));
442                 ret = STATUS_ERROR;
443         }
444
445         return ret;
446 }
447 #endif   /* KRB5 */
448
449 /*
450  * Respond to AUTH_REQ_SCM_CREDS challenge.
451  *
452  * Note: current backends will not use this challenge if HAVE_GETPEEREID
453  * or SO_PEERCRED is defined, but pre-7.4 backends might, so compile the
454  * code anyway.
455  */
456 static int
457 pg_local_sendauth(char *PQerrormsg, PGconn *conn)
458 {
459 #if defined(HAVE_STRUCT_CMSGCRED) || defined(HAVE_STRUCT_FCRED) || \
460         (defined(HAVE_STRUCT_SOCKCRED) && defined(LOCAL_CREDS))
461         char            buf;
462         struct iovec iov;
463         struct msghdr msg;
464
465 #ifdef HAVE_STRUCT_CMSGCRED
466         /* Prevent padding */
467         char            cmsgmem[sizeof(struct cmsghdr) + sizeof(struct cmsgcred)];
468
469         /* Point to start of first structure */
470         struct cmsghdr *cmsg = (struct cmsghdr *) cmsgmem;
471 #endif
472
473         /*
474          * The backend doesn't care what we send here, but it wants exactly
475          * one character to force recvmsg() to block and wait for us.
476          */
477         buf = '\0';
478         iov.iov_base = &buf;
479         iov.iov_len = 1;
480
481         memset(&msg, 0, sizeof(msg));
482         msg.msg_iov = &iov;
483         msg.msg_iovlen = 1;
484
485 #ifdef HAVE_STRUCT_CMSGCRED
486         /* Create control header, FreeBSD */
487         msg.msg_control = cmsg;
488         msg.msg_controllen = sizeof(cmsgmem);
489         memset(cmsg, 0, sizeof(cmsgmem));
490         cmsg->cmsg_len = sizeof(cmsgmem);
491         cmsg->cmsg_level = SOL_SOCKET;
492         cmsg->cmsg_type = SCM_CREDS;
493 #endif
494
495         if (sendmsg(conn->sock, &msg, 0) == -1)
496         {
497                 char            sebuf[256];
498
499                 snprintf(PQerrormsg, PQERRORMSG_LENGTH,
500                                  "pg_local_sendauth: sendmsg: %s\n",
501                                  pqStrerror(errno, sebuf, sizeof(sebuf)));
502                 return STATUS_ERROR;
503         }
504         return STATUS_OK;
505 #else
506         snprintf(PQerrormsg, PQERRORMSG_LENGTH,
507                 libpq_gettext("SCM_CRED authentication method not supported\n"));
508         return STATUS_ERROR;
509 #endif
510 }
511
512 static int
513 pg_password_sendauth(PGconn *conn, const char *password, AuthRequest areq)
514 {
515         int                     ret;
516         char       *crypt_pwd;
517
518         /* Encrypt the password if needed. */
519
520         switch (areq)
521         {
522                 case AUTH_REQ_MD5:
523                         {
524                                 char       *crypt_pwd2;
525
526                                 if (!(crypt_pwd = malloc(MD5_PASSWD_LEN + 1)) ||
527                                         !(crypt_pwd2 = malloc(MD5_PASSWD_LEN + 1)))
528                                 {
529                                         fprintf(stderr, libpq_gettext("out of memory\n"));
530                                         return STATUS_ERROR;
531                                 }
532                                 if (!EncryptMD5(password, conn->pguser,
533                                                                 strlen(conn->pguser), crypt_pwd2))
534                                 {
535                                         free(crypt_pwd);
536                                         free(crypt_pwd2);
537                                         return STATUS_ERROR;
538                                 }
539                                 if (!EncryptMD5(crypt_pwd2 + strlen("md5"), conn->md5Salt,
540                                                                 sizeof(conn->md5Salt), crypt_pwd))
541                                 {
542                                         free(crypt_pwd);
543                                         free(crypt_pwd2);
544                                         return STATUS_ERROR;
545                                 }
546                                 free(crypt_pwd2);
547                                 break;
548                         }
549                 case AUTH_REQ_CRYPT:
550                         {
551                                 char            salt[3];
552
553                                 StrNCpy(salt, conn->cryptSalt, 3);
554                                 crypt_pwd = crypt(password, salt);
555                                 break;
556                         }
557                 case AUTH_REQ_PASSWORD:
558                         /* discard const so we can assign it */
559                         crypt_pwd = (char *) password;
560                         break;
561                 default:
562                         return STATUS_ERROR;
563         }
564         /* Packet has a message type as of protocol 3.0 */
565         if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
566                 ret = pqPacketSend(conn, 'p', crypt_pwd, strlen(crypt_pwd) + 1);
567         else
568                 ret = pqPacketSend(conn, 0, crypt_pwd, strlen(crypt_pwd) + 1);
569         if (areq == AUTH_REQ_MD5)
570                 free(crypt_pwd);
571         return ret;
572 }
573
574 /*
575  * fe_sendauth -- client demux routine for outgoing authentication information
576  */
577 int
578 fe_sendauth(AuthRequest areq, PGconn *conn, const char *hostname,
579                         const char *password, char *PQerrormsg)
580 {
581 #if !defined(KRB4) && !defined(KRB5)
582         (void) hostname;                        /* not used */
583 #endif
584
585         switch (areq)
586         {
587                 case AUTH_REQ_OK:
588                         break;
589
590                 case AUTH_REQ_KRB4:
591 #ifdef KRB4
592                         pglock_thread();
593                         if (pg_krb4_sendauth(PQerrormsg, conn->sock,
594                                                            (struct sockaddr_in *) & conn->laddr.addr,
595                                                            (struct sockaddr_in *) & conn->raddr.addr,
596                                                                  hostname) != STATUS_OK)
597                         {
598                                 snprintf(PQerrormsg, PQERRORMSG_LENGTH,
599                                         libpq_gettext("Kerberos 4 authentication failed\n"));
600                                 pgunlock_thread();
601                                 return STATUS_ERROR;
602                         }
603                         pgunlock_thread();
604                         break;
605 #else
606                         snprintf(PQerrormsg, PQERRORMSG_LENGTH,
607                          libpq_gettext("Kerberos 4 authentication not supported\n"));
608                         return STATUS_ERROR;
609 #endif
610
611                 case AUTH_REQ_KRB5:
612 #ifdef KRB5
613                         pglock_thread();
614                         if (pg_krb5_sendauth(PQerrormsg, conn->sock,
615                                                                  hostname) != STATUS_OK)
616                         {
617                                 snprintf(PQerrormsg, PQERRORMSG_LENGTH,
618                                         libpq_gettext("Kerberos 5 authentication failed\n"));
619                                 pgunlock_thread();
620                                 return STATUS_ERROR;
621                         }
622                         pgunlock_thread();
623                         break;
624 #else
625                         snprintf(PQerrormsg, PQERRORMSG_LENGTH,
626                          libpq_gettext("Kerberos 5 authentication not supported\n"));
627                         return STATUS_ERROR;
628 #endif
629
630                 case AUTH_REQ_MD5:
631                 case AUTH_REQ_CRYPT:
632                 case AUTH_REQ_PASSWORD:
633                         if (password == NULL || *password == '\0')
634                         {
635                                 (void) snprintf(PQerrormsg, PQERRORMSG_LENGTH,
636                                                                 PQnoPasswordSupplied);
637                                 return STATUS_ERROR;
638                         }
639                         if (pg_password_sendauth(conn, password, areq) != STATUS_OK)
640                         {
641                                 (void) snprintf(PQerrormsg, PQERRORMSG_LENGTH,
642                                  "fe_sendauth: error sending password authentication\n");
643                                 return STATUS_ERROR;
644                         }
645                         break;
646
647                 case AUTH_REQ_SCM_CREDS:
648                         if (pg_local_sendauth(PQerrormsg, conn) != STATUS_OK)
649                                 return STATUS_ERROR;
650                         break;
651
652                 default:
653                         snprintf(PQerrormsg, PQERRORMSG_LENGTH,
654                                          libpq_gettext("authentication method %u not supported\n"), areq);
655                         return STATUS_ERROR;
656         }
657
658         return STATUS_OK;
659 }
660
661 /*
662  * fe_setauthsvc
663  * fe_getauthsvc
664  *
665  * Set/return the authentication service currently selected for use by the
666  * frontend. (You can only use one in the frontend, obviously.)
667  *
668  * NB: This is not thread-safe if different threads try to select different
669  * authentication services!  It's OK for fe_getauthsvc to select the default,
670  * since that will be the same for all threads, but direct application use
671  * of fe_setauthsvc is not thread-safe.  However, use of fe_setauthsvc is
672  * deprecated anyway...
673  */
674
675 static int      pg_authsvc = -1;
676
677 void
678 fe_setauthsvc(const char *name, char *PQerrormsg)
679 {
680         int                     i;
681
682         for (i = 0; i < n_authsvcs; ++i)
683                 if (strcmp(name, authsvcs[i].name) == 0)
684                 {
685                         pg_authsvc = i;
686                         break;
687                 }
688         if (i == n_authsvcs)
689         {
690                 snprintf(PQerrormsg, PQERRORMSG_LENGTH,
691                                  libpq_gettext("invalid authentication service name \"%s\", ignored\n"),
692                                  name);
693         }
694         return;
695 }
696
697 MsgType
698 fe_getauthsvc(char *PQerrormsg)
699 {
700         if (pg_authsvc < 0 || pg_authsvc >= n_authsvcs)
701         {
702                 fe_setauthsvc(DEFAULT_CLIENT_AUTHSVC, PQerrormsg);
703                 if (pg_authsvc < 0 || pg_authsvc >= n_authsvcs)
704                 {
705                         /* Can only get here if DEFAULT_CLIENT_AUTHSVC is misdefined */
706                         return 0;
707                 }
708         }
709         return authsvcs[pg_authsvc].msgtype;
710 }
711
712 /*
713  * fe_getauthname -- returns a pointer to dynamic space containing whatever
714  *                                       name the user has authenticated to the system
715  * if there is an error, return the error message in PQerrormsg
716  */
717 char *
718 fe_getauthname(char *PQerrormsg)
719 {
720         const char *name = NULL;
721         char       *authn;
722         MsgType         authsvc;
723 #ifdef WIN32
724         char            username[128];
725         DWORD           namesize = sizeof(username) - 1;
726 #else
727         char            pwdbuf[BUFSIZ];
728         struct passwd pwdstr;
729         struct passwd *pw = NULL;
730 #endif
731
732         authsvc = fe_getauthsvc(PQerrormsg);
733
734         /* this just guards against broken DEFAULT_CLIENT_AUTHSVC, see above */
735         if (authsvc == 0)
736                 return NULL;                    /* leave original error message in place */
737
738         pglock_thread();
739
740 #ifdef KRB4
741         if (authsvc == STARTUP_KRB4_MSG)
742                 name = pg_krb4_authname(PQerrormsg);
743 #endif
744 #ifdef KRB5
745         if (authsvc == STARTUP_KRB5_MSG)
746                 name = pg_krb5_authname(PQerrormsg);
747 #endif
748
749         if (authsvc == STARTUP_MSG
750                 || (authsvc == STARTUP_KRB4_MSG && !name)
751                 || (authsvc == STARTUP_KRB5_MSG && !name))
752         {
753 #ifdef WIN32
754                 if (GetUserName(username, &namesize))
755                         name = username;
756 #else
757                 if (pqGetpwuid(geteuid(), &pwdstr, 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         authn = name ? strdup(name) : NULL;
768
769         pgunlock_thread();
770
771         return authn;
772 }