]> granicus.if.org Git - postgresql/blob - src/interfaces/libpq/fe-secure.c
Allow full SSL certificate verification (wherein libpq checks its host name
[postgresql] / src / interfaces / libpq / fe-secure.c
1 /*-------------------------------------------------------------------------
2  *
3  * fe-secure.c
4  *        functions related to setting up a secure connection to the backend.
5  *        Secure connections are expected to provide confidentiality,
6  *        message integrity and endpoint authentication.
7  *
8  *
9  * Portions Copyright (c) 1996-2010, PostgreSQL Global Development Group
10  * Portions Copyright (c) 1994, Regents of the University of California
11  *
12  *
13  * IDENTIFICATION
14  *        $PostgreSQL: pgsql/src/interfaces/libpq/fe-secure.c,v 1.136 2010/07/14 17:09:45 tgl Exp $
15  *
16  * NOTES
17  *
18  *        We don't provide informational callbacks here (like
19  *        info_cb() in be-secure.c), since there's no good mechanism to
20  *        display such information to the user.
21  *
22  *-------------------------------------------------------------------------
23  */
24
25 #include "postgres_fe.h"
26
27 #include <signal.h>
28 #include <fcntl.h>
29 #include <ctype.h>
30
31 #include "libpq-fe.h"
32 #include "fe-auth.h"
33 #include "pqsignal.h"
34 #include "libpq-int.h"
35
36 #ifdef WIN32
37 #include "win32.h"
38 #else
39 #include <sys/socket.h>
40 #include <unistd.h>
41 #include <netdb.h>
42 #include <netinet/in.h>
43 #ifdef HAVE_NETINET_TCP_H
44 #include <netinet/tcp.h>
45 #endif
46 #include <arpa/inet.h>
47 #endif
48
49 #include <sys/stat.h>
50
51 #ifdef ENABLE_THREAD_SAFETY
52 #ifdef WIN32
53 #include "pthread-win32.h"
54 #else
55 #include <pthread.h>
56 #endif
57 #endif
58
59 #ifdef USE_SSL
60
61 #include <openssl/ssl.h>
62 #if (SSLEAY_VERSION_NUMBER >= 0x00907000L)
63 #include <openssl/conf.h>
64 #endif
65 #ifdef USE_SSL_ENGINE
66 #include <openssl/engine.h>
67 #endif
68
69
70 #ifndef WIN32
71 #define USER_CERT_FILE          ".postgresql/postgresql.crt"
72 #define USER_KEY_FILE           ".postgresql/postgresql.key"
73 #define ROOT_CERT_FILE          ".postgresql/root.crt"
74 #define ROOT_CRL_FILE           ".postgresql/root.crl"
75 #else
76 /* On Windows, the "home" directory is already PostgreSQL-specific */
77 #define USER_CERT_FILE          "postgresql.crt"
78 #define USER_KEY_FILE           "postgresql.key"
79 #define ROOT_CERT_FILE          "root.crt"
80 #define ROOT_CRL_FILE           "root.crl"
81 #endif
82
83 static bool verify_peer_name_matches_certificate(PGconn *);
84 static int      verify_cb(int ok, X509_STORE_CTX *ctx);
85 static int      init_ssl_system(PGconn *conn);
86 static void destroy_ssl_system(void);
87 static int      initialize_SSL(PGconn *conn);
88 static void destroySSL(void);
89 static PostgresPollingStatusType open_client_SSL(PGconn *);
90 static void close_SSL(PGconn *);
91 static char *SSLerrmessage(void);
92 static void SSLerrfree(char *buf);
93
94 static bool pq_init_ssl_lib = true;
95 static bool pq_init_crypto_lib = true;
96 static SSL_CTX *SSL_context = NULL;
97
98 #ifdef ENABLE_THREAD_SAFETY
99 static long ssl_open_connections = 0;
100
101 #ifndef WIN32
102 static pthread_mutex_t ssl_config_mutex = PTHREAD_MUTEX_INITIALIZER;
103 #else
104 static pthread_mutex_t ssl_config_mutex = NULL;
105 static long win32_ssl_create_mutex = 0;
106 #endif
107 #endif   /* ENABLE_THREAD_SAFETY */
108 #endif   /* SSL */
109
110
111 /*
112  * Macros to handle disabling and then restoring the state of SIGPIPE handling.
113  * On Windows, these are all no-ops since there's no SIGPIPEs.
114  */
115
116 #ifndef WIN32
117
118 #define SIGPIPE_MASKED(conn)    ((conn)->sigpipe_so || (conn)->sigpipe_flag)
119
120 #ifdef ENABLE_THREAD_SAFETY
121
122 struct sigpipe_info
123 {
124         sigset_t        oldsigmask;
125         bool            sigpipe_pending;
126         bool            got_epipe;
127 };
128
129 #define DECLARE_SIGPIPE_INFO(spinfo) struct sigpipe_info spinfo
130
131 #define DISABLE_SIGPIPE(conn, spinfo, failaction) \
132         do { \
133                 (spinfo).got_epipe = false; \
134                 if (!SIGPIPE_MASKED(conn)) \
135                 { \
136                         if (pq_block_sigpipe(&(spinfo).oldsigmask, \
137                                                                  &(spinfo).sigpipe_pending) < 0) \
138                                 failaction; \
139                 } \
140         } while (0)
141
142 #define REMEMBER_EPIPE(spinfo, cond) \
143         do { \
144                 if (cond) \
145                         (spinfo).got_epipe = true; \
146         } while (0)
147
148 #define RESTORE_SIGPIPE(conn, spinfo) \
149         do { \
150                 if (!SIGPIPE_MASKED(conn)) \
151                         pq_reset_sigpipe(&(spinfo).oldsigmask, (spinfo).sigpipe_pending, \
152                                                          (spinfo).got_epipe); \
153         } while (0)
154 #else                                                   /* !ENABLE_THREAD_SAFETY */
155
156 #define DECLARE_SIGPIPE_INFO(spinfo) pqsigfunc spinfo = NULL
157
158 #define DISABLE_SIGPIPE(conn, spinfo, failaction) \
159         do { \
160                 if (!SIGPIPE_MASKED(conn)) \
161                         spinfo = pqsignal(SIGPIPE, SIG_IGN); \
162         } while (0)
163
164 #define REMEMBER_EPIPE(spinfo, cond)
165
166 #define RESTORE_SIGPIPE(conn, spinfo) \
167         do { \
168                 if (!SIGPIPE_MASKED(conn)) \
169                         pqsignal(SIGPIPE, spinfo); \
170         } while (0)
171 #endif   /* ENABLE_THREAD_SAFETY */
172 #else                                                   /* WIN32 */
173
174 #define DECLARE_SIGPIPE_INFO(spinfo)
175 #define DISABLE_SIGPIPE(conn, spinfo, failaction)
176 #define REMEMBER_EPIPE(spinfo, cond)
177 #define RESTORE_SIGPIPE(conn, spinfo)
178 #endif   /* WIN32 */
179
180 /* ------------------------------------------------------------ */
181 /*                       Procedures common to all secure sessions                       */
182 /* ------------------------------------------------------------ */
183
184
185 /*
186  *      Exported function to allow application to tell us it's already
187  *      initialized OpenSSL.
188  */
189 void
190 PQinitSSL(int do_init)
191 {
192         PQinitOpenSSL(do_init, do_init);
193 }
194
195 /*
196  *      Exported function to allow application to tell us it's already
197  *      initialized OpenSSL and/or libcrypto.
198  */
199 void
200 PQinitOpenSSL(int do_ssl, int do_crypto)
201 {
202 #ifdef USE_SSL
203 #ifdef ENABLE_THREAD_SAFETY
204
205         /*
206          * Disallow changing the flags while we have open connections, else we'd
207          * get completely confused.
208          */
209         if (ssl_open_connections != 0)
210                 return;
211 #endif
212
213         pq_init_ssl_lib = do_ssl;
214         pq_init_crypto_lib = do_crypto;
215 #endif
216 }
217
218 /*
219  *      Initialize global SSL context
220  */
221 int
222 pqsecure_initialize(PGconn *conn)
223 {
224         int                     r = 0;
225
226 #ifdef USE_SSL
227         r = init_ssl_system(conn);
228 #endif
229
230         return r;
231 }
232
233 /*
234  *      Destroy global context
235  */
236 void
237 pqsecure_destroy(void)
238 {
239 #ifdef USE_SSL
240         destroySSL();
241 #endif
242 }
243
244 /*
245  *      Begin or continue negotiating a secure session.
246  */
247 PostgresPollingStatusType
248 pqsecure_open_client(PGconn *conn)
249 {
250 #ifdef USE_SSL
251         /* First time through? */
252         if (conn->ssl == NULL)
253         {
254                 /* We cannot use MSG_NOSIGNAL to block SIGPIPE when using SSL */
255                 conn->sigpipe_flag = false;
256
257                 /* Create a connection-specific SSL object */
258                 if (!(conn->ssl = SSL_new(SSL_context)) ||
259                         !SSL_set_app_data(conn->ssl, conn) ||
260                         !SSL_set_fd(conn->ssl, conn->sock))
261                 {
262                         char       *err = SSLerrmessage();
263
264                         printfPQExpBuffer(&conn->errorMessage,
265                                    libpq_gettext("could not establish SSL connection: %s\n"),
266                                                           err);
267                         SSLerrfree(err);
268                         close_SSL(conn);
269                         return PGRES_POLLING_FAILED;
270                 }
271
272                 /*
273                  * Load client certificate, private key, and trusted CA certs.
274                  */
275                 if (initialize_SSL(conn) != 0)
276                 {
277                         /* initialize_SSL already put a message in conn->errorMessage */
278                         close_SSL(conn);
279                         return PGRES_POLLING_FAILED;
280                 }
281         }
282
283         /* Begin or continue the actual handshake */
284         return open_client_SSL(conn);
285 #else
286         /* shouldn't get here */
287         return PGRES_POLLING_FAILED;
288 #endif
289 }
290
291 /*
292  *      Close secure session.
293  */
294 void
295 pqsecure_close(PGconn *conn)
296 {
297 #ifdef USE_SSL
298         if (conn->ssl)
299                 close_SSL(conn);
300 #endif
301 }
302
303 /*
304  *      Read data from a secure connection.
305  */
306 ssize_t
307 pqsecure_read(PGconn *conn, void *ptr, size_t len)
308 {
309         ssize_t         n;
310
311 #ifdef USE_SSL
312         if (conn->ssl)
313         {
314                 int                     err;
315
316                 DECLARE_SIGPIPE_INFO(spinfo);
317
318                 /* SSL_read can write to the socket, so we need to disable SIGPIPE */
319                 DISABLE_SIGPIPE(conn, spinfo, return -1);
320
321 rloop:
322                 SOCK_ERRNO_SET(0);
323                 n = SSL_read(conn->ssl, ptr, len);
324                 err = SSL_get_error(conn->ssl, n);
325                 switch (err)
326                 {
327                         case SSL_ERROR_NONE:
328                                 break;
329                         case SSL_ERROR_WANT_READ:
330                                 n = 0;
331                                 break;
332                         case SSL_ERROR_WANT_WRITE:
333
334                                 /*
335                                  * Returning 0 here would cause caller to wait for read-ready,
336                                  * which is not correct since what SSL wants is wait for
337                                  * write-ready.  The former could get us stuck in an infinite
338                                  * wait, so don't risk it; busy-loop instead.
339                                  */
340                                 goto rloop;
341                         case SSL_ERROR_SYSCALL:
342                                 {
343                                         char            sebuf[256];
344
345                                         if (n == -1)
346                                         {
347                                                 REMEMBER_EPIPE(spinfo, SOCK_ERRNO == EPIPE);
348                                                 printfPQExpBuffer(&conn->errorMessage,
349                                                                         libpq_gettext("SSL SYSCALL error: %s\n"),
350                                                         SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
351                                         }
352                                         else
353                                         {
354                                                 printfPQExpBuffer(&conn->errorMessage,
355                                                  libpq_gettext("SSL SYSCALL error: EOF detected\n"));
356
357                                                 SOCK_ERRNO_SET(ECONNRESET);
358                                                 n = -1;
359                                         }
360                                         break;
361                                 }
362                         case SSL_ERROR_SSL:
363                                 {
364                                         char       *err = SSLerrmessage();
365
366                                         printfPQExpBuffer(&conn->errorMessage,
367                                                                           libpq_gettext("SSL error: %s\n"), err);
368                                         SSLerrfree(err);
369                                 }
370                                 /* fall through */
371                         case SSL_ERROR_ZERO_RETURN:
372                                 SOCK_ERRNO_SET(ECONNRESET);
373                                 n = -1;
374                                 break;
375                         default:
376                                 printfPQExpBuffer(&conn->errorMessage,
377                                                   libpq_gettext("unrecognized SSL error code: %d\n"),
378                                                                   err);
379                                 n = -1;
380                                 break;
381                 }
382
383                 RESTORE_SIGPIPE(conn, spinfo);
384         }
385         else
386 #endif
387                 n = recv(conn->sock, ptr, len, 0);
388
389         return n;
390 }
391
392 /*
393  *      Write data to a secure connection.
394  */
395 ssize_t
396 pqsecure_write(PGconn *conn, const void *ptr, size_t len)
397 {
398         ssize_t         n;
399
400         DECLARE_SIGPIPE_INFO(spinfo);
401
402 #ifdef USE_SSL
403         if (conn->ssl)
404         {
405                 int                     err;
406
407                 DISABLE_SIGPIPE(conn, spinfo, return -1);
408
409                 SOCK_ERRNO_SET(0);
410                 n = SSL_write(conn->ssl, ptr, len);
411                 err = SSL_get_error(conn->ssl, n);
412                 switch (err)
413                 {
414                         case SSL_ERROR_NONE:
415                                 break;
416                         case SSL_ERROR_WANT_READ:
417
418                                 /*
419                                  * Returning 0 here causes caller to wait for write-ready,
420                                  * which is not really the right thing, but it's the best we
421                                  * can do.
422                                  */
423                                 n = 0;
424                                 break;
425                         case SSL_ERROR_WANT_WRITE:
426                                 n = 0;
427                                 break;
428                         case SSL_ERROR_SYSCALL:
429                                 {
430                                         char            sebuf[256];
431
432                                         if (n == -1)
433                                         {
434                                                 REMEMBER_EPIPE(spinfo, SOCK_ERRNO == EPIPE);
435                                                 printfPQExpBuffer(&conn->errorMessage,
436                                                                         libpq_gettext("SSL SYSCALL error: %s\n"),
437                                                         SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
438                                         }
439                                         else
440                                         {
441                                                 printfPQExpBuffer(&conn->errorMessage,
442                                                  libpq_gettext("SSL SYSCALL error: EOF detected\n"));
443                                                 SOCK_ERRNO_SET(ECONNRESET);
444                                                 n = -1;
445                                         }
446                                         break;
447                                 }
448                         case SSL_ERROR_SSL:
449                                 {
450                                         char       *err = SSLerrmessage();
451
452                                         printfPQExpBuffer(&conn->errorMessage,
453                                                                           libpq_gettext("SSL error: %s\n"), err);
454                                         SSLerrfree(err);
455                                 }
456                                 /* fall through */
457                         case SSL_ERROR_ZERO_RETURN:
458                                 SOCK_ERRNO_SET(ECONNRESET);
459                                 n = -1;
460                                 break;
461                         default:
462                                 printfPQExpBuffer(&conn->errorMessage,
463                                                   libpq_gettext("unrecognized SSL error code: %d\n"),
464                                                                   err);
465                                 n = -1;
466                                 break;
467                 }
468         }
469         else
470 #endif
471         {
472                 int                     flags = 0;
473
474 #ifdef MSG_NOSIGNAL
475                 if (conn->sigpipe_flag)
476                         flags |= MSG_NOSIGNAL;
477
478 retry_masked:
479 #endif   /* MSG_NOSIGNAL */
480
481                 DISABLE_SIGPIPE(conn, spinfo, return -1);
482
483                 n = send(conn->sock, ptr, len, flags);
484
485                 if (n < 0)
486                 {
487                         /*
488                          * If we see an EINVAL, it may be because MSG_NOSIGNAL isn't
489                          * available on this machine.  So, clear sigpipe_flag so we don't
490                          * try the flag again, and retry the send().
491                          */
492 #ifdef MSG_NOSIGNAL
493                         if (flags != 0 && SOCK_ERRNO == EINVAL)
494                         {
495                                 conn->sigpipe_flag = false;
496                                 flags = 0;
497                                 goto retry_masked;
498                         }
499 #endif   /* MSG_NOSIGNAL */
500
501                         REMEMBER_EPIPE(spinfo, SOCK_ERRNO == EPIPE);
502                 }
503         }
504
505         RESTORE_SIGPIPE(conn, spinfo);
506
507         return n;
508 }
509
510 /* ------------------------------------------------------------ */
511 /*                                                SSL specific code                                             */
512 /* ------------------------------------------------------------ */
513 #ifdef USE_SSL
514
515 /*
516  *      Certificate verification callback
517  *
518  *      This callback allows us to log intermediate problems during
519  *      verification, but there doesn't seem to be a clean way to get
520  *      our PGconn * structure.  So we can't log anything!
521  *
522  *      This callback also allows us to override the default acceptance
523  *      criteria (e.g., accepting self-signed or expired certs), but
524  *      for now we accept the default checks.
525  */
526 static int
527 verify_cb(int ok, X509_STORE_CTX *ctx)
528 {
529         return ok;
530 }
531
532
533 /*
534  * Check if a wildcard certificate matches the server hostname.
535  *
536  * The rule for this is:
537  *      1. We only match the '*' character as wildcard
538  *      2. We match only wildcards at the start of the string
539  *      3. The '*' character does *not* match '.', meaning that we match only
540  *         a single pathname component.
541  *      4. We don't support more than one '*' in a single pattern.
542  *
543  * This is roughly in line with RFC2818, but contrary to what most browsers
544  * appear to be implementing (point 3 being the difference)
545  *
546  * Matching is always case-insensitive, since DNS is case insensitive.
547  */
548 static int
549 wildcard_certificate_match(const char *pattern, const char *string)
550 {
551         int                     lenpat = strlen(pattern);
552         int                     lenstr = strlen(string);
553
554         /* If we don't start with a wildcard, it's not a match (rule 1 & 2) */
555         if (lenpat < 3 ||
556                 pattern[0] != '*' ||
557                 pattern[1] != '.')
558                 return 0;
559
560         if (lenpat > lenstr)
561                 /* If pattern is longer than the string, we can never match */
562                 return 0;
563
564         if (pg_strcasecmp(pattern + 1, string + lenstr - lenpat + 1) != 0)
565
566                 /*
567                  * If string does not end in pattern (minus the wildcard), we don't
568                  * match
569                  */
570                 return 0;
571
572         if (strchr(string, '.') < string + lenstr - lenpat)
573
574                 /*
575                  * If there is a dot left of where the pattern started to match, we
576                  * don't match (rule 3)
577                  */
578                 return 0;
579
580         /* String ended with pattern, and didn't have a dot before, so we match */
581         return 1;
582 }
583
584
585 /*
586  *      Verify that common name resolves to peer.
587  */
588 static bool
589 verify_peer_name_matches_certificate(PGconn *conn)
590 {
591         /*
592          * If told not to verify the peer name, don't do it. Return true indicating
593          * that the verification was successful.
594          */
595         if (strcmp(conn->sslmode, "verify-full") != 0)
596                 return true;
597
598         if (!(conn->pghost && conn->pghost[0] != '\0'))
599         {
600                 printfPQExpBuffer(&conn->errorMessage,
601                                                   libpq_gettext("host name must be specified for a verified SSL connection\n"));
602                 return false;
603         }
604         else
605         {
606                 /*
607                  * Compare CN to originally given hostname.
608                  *
609                  * XXX: Should support alternate names here
610                  */
611                 if (pg_strcasecmp(conn->peer_cn, conn->pghost) == 0)
612                         /* Exact name match */
613                         return true;
614                 else if (wildcard_certificate_match(conn->peer_cn, conn->pghost))
615                         /* Matched wildcard certificate */
616                         return true;
617                 else
618                 {
619                         printfPQExpBuffer(&conn->errorMessage,
620                                                           libpq_gettext("server common name \"%s\" does not match host name \"%s\"\n"),
621                                                           conn->peer_cn, conn->pghost);
622                         return false;
623                 }
624         }
625 }
626
627 #ifdef ENABLE_THREAD_SAFETY
628 /*
629  *      Callback functions for OpenSSL internal locking
630  */
631
632 static unsigned long
633 pq_threadidcallback(void)
634 {
635         /*
636          * This is not standards-compliant.  pthread_self() returns pthread_t, and
637          * shouldn't be cast to unsigned long, but CRYPTO_set_id_callback requires
638          * it, so we have to do it.
639          */
640         return (unsigned long) pthread_self();
641 }
642
643 static pthread_mutex_t *pq_lockarray;
644
645 static void
646 pq_lockingcallback(int mode, int n, const char *file, int line)
647 {
648         if (mode & CRYPTO_LOCK)
649         {
650                 if (pthread_mutex_lock(&pq_lockarray[n]))
651                         PGTHREAD_ERROR("failed to lock mutex");
652         }
653         else
654         {
655                 if (pthread_mutex_unlock(&pq_lockarray[n]))
656                         PGTHREAD_ERROR("failed to unlock mutex");
657         }
658 }
659 #endif   /* ENABLE_THREAD_SAFETY */
660
661 /*
662  * Initialize SSL system, in particular creating the SSL_context object
663  * that will be shared by all SSL-using connections in this process.
664  *
665  * In threadsafe mode, this includes setting up libcrypto callback functions
666  * to do thread locking.
667  *
668  * If the caller has told us (through PQinitOpenSSL) that he's taking care
669  * of libcrypto, we expect that callbacks are already set, and won't try to
670  * override it.
671  *
672  * The conn parameter is only used to be able to pass back an error
673  * message - no connection-local setup is made here.
674  *
675  * Returns 0 if OK, -1 on failure (with a message in conn->errorMessage).
676  */
677 static int
678 init_ssl_system(PGconn *conn)
679 {
680 #ifdef ENABLE_THREAD_SAFETY
681 #ifdef WIN32
682         /* Also see similar code in fe-connect.c, default_threadlock() */
683         if (ssl_config_mutex == NULL)
684         {
685                 while (InterlockedExchange(&win32_ssl_create_mutex, 1) == 1)
686                          /* loop, another thread own the lock */ ;
687                 if (ssl_config_mutex == NULL)
688                 {
689                         if (pthread_mutex_init(&ssl_config_mutex, NULL))
690                                 return -1;
691                 }
692                 InterlockedExchange(&win32_ssl_create_mutex, 0);
693         }
694 #endif
695         if (pthread_mutex_lock(&ssl_config_mutex))
696                 return -1;
697
698         if (pq_init_crypto_lib)
699         {
700                 /*
701                  * If necessary, set up an array to hold locks for libcrypto.
702                  * libcrypto will tell us how big to make this array.
703                  */
704                 if (pq_lockarray == NULL)
705                 {
706                         int                     i;
707
708                         pq_lockarray = malloc(sizeof(pthread_mutex_t) * CRYPTO_num_locks());
709                         if (!pq_lockarray)
710                         {
711                                 pthread_mutex_unlock(&ssl_config_mutex);
712                                 return -1;
713                         }
714                         for (i = 0; i < CRYPTO_num_locks(); i++)
715                         {
716                                 if (pthread_mutex_init(&pq_lockarray[i], NULL))
717                                 {
718                                         free(pq_lockarray);
719                                         pq_lockarray = NULL;
720                                         pthread_mutex_unlock(&ssl_config_mutex);
721                                         return -1;
722                                 }
723                         }
724                 }
725
726                 if (ssl_open_connections++ == 0)
727                 {
728                         /* These are only required for threaded libcrypto applications */
729                         CRYPTO_set_id_callback(pq_threadidcallback);
730                         CRYPTO_set_locking_callback(pq_lockingcallback);
731                 }
732         }
733 #endif   /* ENABLE_THREAD_SAFETY */
734
735         if (!SSL_context)
736         {
737                 if (pq_init_ssl_lib)
738                 {
739 #if SSLEAY_VERSION_NUMBER >= 0x00907000L
740                         OPENSSL_config(NULL);
741 #endif
742                         SSL_library_init();
743                         SSL_load_error_strings();
744                 }
745
746                 SSL_context = SSL_CTX_new(TLSv1_method());
747                 if (!SSL_context)
748                 {
749                         char       *err = SSLerrmessage();
750
751                         printfPQExpBuffer(&conn->errorMessage,
752                                                  libpq_gettext("could not create SSL context: %s\n"),
753                                                           err);
754                         SSLerrfree(err);
755 #ifdef ENABLE_THREAD_SAFETY
756                         pthread_mutex_unlock(&ssl_config_mutex);
757 #endif
758                         return -1;
759                 }
760         }
761
762 #ifdef ENABLE_THREAD_SAFETY
763         pthread_mutex_unlock(&ssl_config_mutex);
764 #endif
765         return 0;
766 }
767
768 /*
769  *      This function is needed because if the libpq library is unloaded
770  *      from the application, the callback functions will no longer exist when
771  *      libcrypto is used by other parts of the system.  For this reason,
772  *      we unregister the callback functions when the last libpq
773  *      connection is closed.  (The same would apply for OpenSSL callbacks
774  *      if we had any.)
775  *
776  *      Callbacks are only set when we're compiled in threadsafe mode, so
777  *      we only need to remove them in this case.
778  */
779 static void
780 destroy_ssl_system(void)
781 {
782 #ifdef ENABLE_THREAD_SAFETY
783         /* Mutex is created in initialize_ssl_system() */
784         if (pthread_mutex_lock(&ssl_config_mutex))
785                 return;
786
787         if (pq_init_crypto_lib && ssl_open_connections > 0)
788                 --ssl_open_connections;
789
790         if (pq_init_crypto_lib && ssl_open_connections == 0)
791         {
792                 /* No connections left, unregister libcrypto callbacks */
793                 CRYPTO_set_locking_callback(NULL);
794                 CRYPTO_set_id_callback(NULL);
795
796                 /*
797                  * We don't free the lock array. If we get another connection in this
798                  * process, we will just re-use it with the existing mutexes.
799                  *
800                  * This means we leak a little memory on repeated load/unload of the
801                  * library.
802                  */
803         }
804
805         pthread_mutex_unlock(&ssl_config_mutex);
806 #endif
807 }
808
809 /*
810  *      Initialize (potentially) per-connection SSL data, namely the
811  *      client certificate, private key, and trusted CA certs.
812  *
813  *      conn->ssl must already be created.      It receives the connection's client
814  *      certificate and private key.  Note however that certificates also get
815  *      loaded into the SSL_context object, and are therefore accessible to all
816  *      connections in this process.  This should be OK as long as there aren't
817  *      any hash collisions among the certs.
818  *
819  *      Returns 0 if OK, -1 on failure (with a message in conn->errorMessage).
820  */
821 static int
822 initialize_SSL(PGconn *conn)
823 {
824         struct stat buf;
825         char            homedir[MAXPGPATH];
826         char            fnbuf[MAXPGPATH];
827         char            sebuf[256];
828         bool            have_cert;
829         EVP_PKEY   *pkey = NULL;
830
831         /*
832          * We'll need the home directory if any of the relevant parameters are
833          * defaulted.
834          */
835         if (!(conn->sslcert && strlen(conn->sslcert) > 0) ||
836                 !(conn->sslkey && strlen(conn->sslkey) > 0) ||
837                 !(conn->sslrootcert && strlen(conn->sslrootcert) > 0) ||
838                 !(conn->sslcrl && strlen(conn->sslcrl) > 0))
839         {
840                 if (!pqGetHomeDirectory(homedir, sizeof(homedir)))
841                 {
842                         printfPQExpBuffer(&conn->errorMessage,
843                                                           libpq_gettext("could not get home directory to locate client certificate files\n"));
844                         return -1;
845                 }
846         }
847         else
848         {
849                 homedir[0] = '\0';
850         }
851
852         /* Read the client certificate file */
853         if (conn->sslcert && strlen(conn->sslcert) > 0)
854                 strncpy(fnbuf, conn->sslcert, sizeof(fnbuf));
855         else
856                 snprintf(fnbuf, sizeof(fnbuf), "%s/%s", homedir, USER_CERT_FILE);
857
858         if (stat(fnbuf, &buf) != 0)
859         {
860                 /*
861                  * If file is not present, just go on without a client cert; server
862                  * might or might not accept the connection.  Any other error,
863                  * however, is grounds for complaint.
864                  */
865                 if (errno != ENOENT)
866                 {
867                         printfPQExpBuffer(&conn->errorMessage,
868                            libpq_gettext("could not open certificate file \"%s\": %s\n"),
869                                                           fnbuf, pqStrerror(errno, sebuf, sizeof(sebuf)));
870                         return -1;
871                 }
872                 have_cert = false;
873         }
874         else
875         {
876                 /*
877                  * Cert file exists, so load it.  Since OpenSSL doesn't provide the
878                  * equivalent of "SSL_use_certificate_chain_file", we actually have to
879                  * load the file twice.  The first call loads any extra certs after
880                  * the first one into chain-cert storage associated with the
881                  * SSL_context.  The second call loads the first cert (only) into the
882                  * SSL object, where it will be correctly paired with the private key
883                  * we load below.  We do it this way so that each connection
884                  * understands which subject cert to present, in case different
885                  * sslcert settings are used for different connections in the same
886                  * process.
887                  */
888                 if (SSL_CTX_use_certificate_chain_file(SSL_context, fnbuf) != 1)
889                 {
890                         char       *err = SSLerrmessage();
891
892                         printfPQExpBuffer(&conn->errorMessage,
893                            libpq_gettext("could not read certificate file \"%s\": %s\n"),
894                                                           fnbuf, err);
895                         SSLerrfree(err);
896                         return -1;
897                 }
898                 if (SSL_use_certificate_file(conn->ssl, fnbuf, SSL_FILETYPE_PEM) != 1)
899                 {
900                         char       *err = SSLerrmessage();
901
902                         printfPQExpBuffer(&conn->errorMessage,
903                            libpq_gettext("could not read certificate file \"%s\": %s\n"),
904                                                           fnbuf, err);
905                         SSLerrfree(err);
906                         return -1;
907                 }
908                 /* need to load the associated private key, too */
909                 have_cert = true;
910         }
911
912         /*
913          * Read the SSL key. If a key is specified, treat it as an engine:key
914          * combination if there is colon present - we don't support files with
915          * colon in the name. The exception is if the second character is a colon,
916          * in which case it can be a Windows filename with drive specification.
917          */
918         if (have_cert && conn->sslkey && strlen(conn->sslkey) > 0)
919         {
920 #ifdef USE_SSL_ENGINE
921                 if (strchr(conn->sslkey, ':')
922 #ifdef WIN32
923                         && conn->sslkey[1] != ':'
924 #endif
925                         )
926                 {
927                         /* Colon, but not in second character, treat as engine:key */
928                         char       *engine_str = strdup(conn->sslkey);
929                         char       *engine_colon = strchr(engine_str, ':');
930
931                         *engine_colon = '\0';           /* engine_str now has engine name */
932                         engine_colon++;         /* engine_colon now has key name */
933
934                         conn->engine = ENGINE_by_id(engine_str);
935                         if (conn->engine == NULL)
936                         {
937                                 char       *err = SSLerrmessage();
938
939                                 printfPQExpBuffer(&conn->errorMessage,
940                                          libpq_gettext("could not load SSL engine \"%s\": %s\n"),
941                                                                   engine_str, err);
942                                 SSLerrfree(err);
943                                 free(engine_str);
944                                 return -1;
945                         }
946
947                         if (ENGINE_init(conn->engine) == 0)
948                         {
949                                 char       *err = SSLerrmessage();
950
951                                 printfPQExpBuffer(&conn->errorMessage,
952                                 libpq_gettext("could not initialize SSL engine \"%s\": %s\n"),
953                                                                   engine_str, err);
954                                 SSLerrfree(err);
955                                 ENGINE_free(conn->engine);
956                                 conn->engine = NULL;
957                                 free(engine_str);
958                                 return -1;
959                         }
960
961                         pkey = ENGINE_load_private_key(conn->engine, engine_colon,
962                                                                                    NULL, NULL);
963                         if (pkey == NULL)
964                         {
965                                 char       *err = SSLerrmessage();
966
967                                 printfPQExpBuffer(&conn->errorMessage,
968                                                                   libpq_gettext("could not read private SSL key \"%s\" from engine \"%s\": %s\n"),
969                                                                   engine_colon, engine_str, err);
970                                 SSLerrfree(err);
971                                 ENGINE_finish(conn->engine);
972                                 ENGINE_free(conn->engine);
973                                 conn->engine = NULL;
974                                 free(engine_str);
975                                 return -1;
976                         }
977                         if (SSL_use_PrivateKey(conn->ssl, pkey) != 1)
978                         {
979                                 char       *err = SSLerrmessage();
980
981                                 printfPQExpBuffer(&conn->errorMessage,
982                                                                   libpq_gettext("could not load private SSL key \"%s\" from engine \"%s\": %s\n"),
983                                                                   engine_colon, engine_str, err);
984                                 SSLerrfree(err);
985                                 ENGINE_finish(conn->engine);
986                                 ENGINE_free(conn->engine);
987                                 conn->engine = NULL;
988                                 free(engine_str);
989                                 return -1;
990                         }
991
992                         free(engine_str);
993
994                         fnbuf[0] = '\0';        /* indicate we're not going to load from a
995                                                                  * file */
996                 }
997                 else
998 #endif   /* USE_SSL_ENGINE */
999                 {
1000                         /* PGSSLKEY is not an engine, treat it as a filename */
1001                         strncpy(fnbuf, conn->sslkey, sizeof(fnbuf));
1002                 }
1003         }
1004         else
1005         {
1006                 /* No PGSSLKEY specified, load default file */
1007                 snprintf(fnbuf, sizeof(fnbuf), "%s/%s", homedir, USER_KEY_FILE);
1008         }
1009
1010         if (have_cert && fnbuf[0] != '\0')
1011         {
1012                 /* read the client key from file */
1013
1014                 if (stat(fnbuf, &buf) != 0)
1015                 {
1016                         printfPQExpBuffer(&conn->errorMessage,
1017                                                           libpq_gettext("certificate present, but not private key file \"%s\"\n"),
1018                                                           fnbuf);
1019                         return -1;
1020                 }
1021 #ifndef WIN32
1022                 if (!S_ISREG(buf.st_mode) || buf.st_mode & (S_IRWXG | S_IRWXO))
1023                 {
1024                         printfPQExpBuffer(&conn->errorMessage,
1025                                                           libpq_gettext("private key file \"%s\" has group or world access; permissions should be u=rw (0600) or less\n"),
1026                                                           fnbuf);
1027                         return -1;
1028                 }
1029 #endif
1030
1031                 if (SSL_use_PrivateKey_file(conn->ssl, fnbuf, SSL_FILETYPE_PEM) != 1)
1032                 {
1033                         char       *err = SSLerrmessage();
1034
1035                         printfPQExpBuffer(&conn->errorMessage,
1036                            libpq_gettext("could not load private key file \"%s\": %s\n"),
1037                                                           fnbuf, err);
1038                         SSLerrfree(err);
1039                         return -1;
1040                 }
1041         }
1042
1043         /* verify that the cert and key go together */
1044         if (have_cert &&
1045                 SSL_check_private_key(conn->ssl) != 1)
1046         {
1047                 char       *err = SSLerrmessage();
1048
1049                 printfPQExpBuffer(&conn->errorMessage,
1050                                                   libpq_gettext("certificate does not match private key file \"%s\": %s\n"),
1051                                                   fnbuf, err);
1052                 SSLerrfree(err);
1053                 return -1;
1054         }
1055
1056         /*
1057          * If the root cert file exists, load it so we can perform certificate
1058          * verification. If sslmode is "verify-full" we will also do further
1059          * verification after the connection has been completed.
1060          */
1061         if (conn->sslrootcert && strlen(conn->sslrootcert) > 0)
1062                 strncpy(fnbuf, conn->sslrootcert, sizeof(fnbuf));
1063         else
1064                 snprintf(fnbuf, sizeof(fnbuf), "%s/%s", homedir, ROOT_CERT_FILE);
1065
1066         if (stat(fnbuf, &buf) == 0)
1067         {
1068                 X509_STORE *cvstore;
1069
1070                 if (SSL_CTX_load_verify_locations(SSL_context, fnbuf, NULL) != 1)
1071                 {
1072                         char       *err = SSLerrmessage();
1073
1074                         printfPQExpBuffer(&conn->errorMessage,
1075                                                           libpq_gettext("could not read root certificate file \"%s\": %s\n"),
1076                                                           fnbuf, err);
1077                         SSLerrfree(err);
1078                         return -1;
1079                 }
1080
1081                 if ((cvstore = SSL_CTX_get_cert_store(SSL_context)) != NULL)
1082                 {
1083                         if (conn->sslcrl && strlen(conn->sslcrl) > 0)
1084                                 strncpy(fnbuf, conn->sslcrl, sizeof(fnbuf));
1085                         else
1086                                 snprintf(fnbuf, sizeof(fnbuf), "%s/%s", homedir, ROOT_CRL_FILE);
1087
1088                         /* Set the flags to check against the complete CRL chain */
1089                         if (X509_STORE_load_locations(cvstore, fnbuf, NULL) == 1)
1090                         {
1091                                 /* OpenSSL 0.96 does not support X509_V_FLAG_CRL_CHECK */
1092 #ifdef X509_V_FLAG_CRL_CHECK
1093                                 X509_STORE_set_flags(cvstore,
1094                                                   X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
1095 #else
1096                                 char       *err = SSLerrmessage();
1097
1098                                 printfPQExpBuffer(&conn->errorMessage,
1099                                                                   libpq_gettext("SSL library does not support CRL certificates (file \"%s\")\n"),
1100                                                                   fnbuf);
1101                                 SSLerrfree(err);
1102                                 return -1;
1103 #endif
1104                         }
1105                         /* if not found, silently ignore;  we do not require CRL */
1106                 }
1107
1108                 SSL_set_verify(conn->ssl, SSL_VERIFY_PEER, verify_cb);
1109         }
1110         else
1111         {
1112                 /*
1113                  * stat() failed; assume root file doesn't exist.  If sslmode is
1114                  * verify-ca or verify-full, this is an error.  Otherwise, continue
1115                  * without performing any server cert verification.
1116                  */
1117                 if (conn->sslmode[0] == 'v')    /* "verify-ca" or "verify-full" */
1118                 {
1119                         printfPQExpBuffer(&conn->errorMessage,
1120                                 libpq_gettext("root certificate file \"%s\" does not exist\n"
1121                                                           "Either provide the file or change sslmode to disable server certificate verification.\n"), fnbuf);
1122                         return -1;
1123                 }
1124         }
1125
1126         return 0;
1127 }
1128
1129 static void
1130 destroySSL(void)
1131 {
1132         destroy_ssl_system();
1133 }
1134
1135 /*
1136  *      Attempt to negotiate SSL connection.
1137  */
1138 static PostgresPollingStatusType
1139 open_client_SSL(PGconn *conn)
1140 {
1141         int                     r;
1142
1143         r = SSL_connect(conn->ssl);
1144         if (r <= 0)
1145         {
1146                 int                     err = SSL_get_error(conn->ssl, r);
1147
1148                 switch (err)
1149                 {
1150                         case SSL_ERROR_WANT_READ:
1151                                 return PGRES_POLLING_READING;
1152
1153                         case SSL_ERROR_WANT_WRITE:
1154                                 return PGRES_POLLING_WRITING;
1155
1156                         case SSL_ERROR_SYSCALL:
1157                                 {
1158                                         char            sebuf[256];
1159
1160                                         if (r == -1)
1161                                                 printfPQExpBuffer(&conn->errorMessage,
1162                                                                         libpq_gettext("SSL SYSCALL error: %s\n"),
1163                                                         SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1164                                         else
1165                                                 printfPQExpBuffer(&conn->errorMessage,
1166                                                  libpq_gettext("SSL SYSCALL error: EOF detected\n"));
1167                                         close_SSL(conn);
1168                                         return PGRES_POLLING_FAILED;
1169                                 }
1170                         case SSL_ERROR_SSL:
1171                                 {
1172                                         char       *err = SSLerrmessage();
1173
1174                                         printfPQExpBuffer(&conn->errorMessage,
1175                                                                           libpq_gettext("SSL error: %s\n"),
1176                                                                           err);
1177                                         SSLerrfree(err);
1178                                         close_SSL(conn);
1179                                         return PGRES_POLLING_FAILED;
1180                                 }
1181
1182                         default:
1183                                 printfPQExpBuffer(&conn->errorMessage,
1184                                                   libpq_gettext("unrecognized SSL error code: %d\n"),
1185                                                                   err);
1186                                 close_SSL(conn);
1187                                 return PGRES_POLLING_FAILED;
1188                 }
1189         }
1190
1191         /*
1192          * We already checked the server certificate in initialize_SSL() using
1193          * SSL_CTX_set_verify(), if root.crt exists.
1194          */
1195
1196         /* pull out server distinguished and common names */
1197         conn->peer = SSL_get_peer_certificate(conn->ssl);
1198         if (conn->peer == NULL)
1199         {
1200                 char       *err = SSLerrmessage();
1201
1202                 printfPQExpBuffer(&conn->errorMessage,
1203                                         libpq_gettext("certificate could not be obtained: %s\n"),
1204                                                   err);
1205                 SSLerrfree(err);
1206                 close_SSL(conn);
1207                 return PGRES_POLLING_FAILED;
1208         }
1209
1210         X509_NAME_oneline(X509_get_subject_name(conn->peer),
1211                                           conn->peer_dn, sizeof(conn->peer_dn));
1212         conn->peer_dn[sizeof(conn->peer_dn) - 1] = '\0';
1213
1214         r = X509_NAME_get_text_by_NID(X509_get_subject_name(conn->peer),
1215                                                                   NID_commonName, conn->peer_cn, SM_USER);
1216         conn->peer_cn[SM_USER] = '\0';          /* buffer is SM_USER+1 chars! */
1217         if (r == -1)
1218         {
1219                 /* Unable to get the CN, set it to blank so it can't be used */
1220                 conn->peer_cn[0] = '\0';
1221         }
1222         else
1223         {
1224                 /*
1225                  * Reject embedded NULLs in certificate common name to prevent attacks
1226                  * like CVE-2009-4034.
1227                  */
1228                 if (r != strlen(conn->peer_cn))
1229                 {
1230                         printfPQExpBuffer(&conn->errorMessage,
1231                                                           libpq_gettext("SSL certificate's common name contains embedded null\n"));
1232                         close_SSL(conn);
1233                         return PGRES_POLLING_FAILED;
1234                 }
1235         }
1236
1237         if (!verify_peer_name_matches_certificate(conn))
1238         {
1239                 close_SSL(conn);
1240                 return PGRES_POLLING_FAILED;
1241         }
1242
1243         /* SSL handshake is complete */
1244         return PGRES_POLLING_OK;
1245 }
1246
1247 /*
1248  *      Close SSL connection.
1249  */
1250 static void
1251 close_SSL(PGconn *conn)
1252 {
1253         if (conn->ssl)
1254         {
1255                 DECLARE_SIGPIPE_INFO(spinfo);
1256
1257                 DISABLE_SIGPIPE(conn, spinfo, (void) 0);
1258                 SSL_shutdown(conn->ssl);
1259                 SSL_free(conn->ssl);
1260                 conn->ssl = NULL;
1261                 pqsecure_destroy();
1262                 /* We have to assume we got EPIPE */
1263                 REMEMBER_EPIPE(spinfo, true);
1264                 RESTORE_SIGPIPE(conn, spinfo);
1265         }
1266
1267         if (conn->peer)
1268         {
1269                 X509_free(conn->peer);
1270                 conn->peer = NULL;
1271         }
1272
1273 #ifdef USE_SSL_ENGINE
1274         if (conn->engine)
1275         {
1276                 ENGINE_finish(conn->engine);
1277                 ENGINE_free(conn->engine);
1278                 conn->engine = NULL;
1279         }
1280 #endif
1281 }
1282
1283 /*
1284  * Obtain reason string for last SSL error
1285  *
1286  * Some caution is needed here since ERR_reason_error_string will
1287  * return NULL if it doesn't recognize the error code.  We don't
1288  * want to return NULL ever.
1289  */
1290 static char ssl_nomem[] = "out of memory allocating error description";
1291
1292 #define SSL_ERR_LEN 128
1293
1294 static char *
1295 SSLerrmessage(void)
1296 {
1297         unsigned long errcode;
1298         const char *errreason;
1299         char       *errbuf;
1300
1301         errbuf = malloc(SSL_ERR_LEN);
1302         if (!errbuf)
1303                 return ssl_nomem;
1304         errcode = ERR_get_error();
1305         if (errcode == 0)
1306         {
1307                 snprintf(errbuf, SSL_ERR_LEN, libpq_gettext("no SSL error reported"));
1308                 return errbuf;
1309         }
1310         errreason = ERR_reason_error_string(errcode);
1311         if (errreason != NULL)
1312         {
1313                 strlcpy(errbuf, errreason, SSL_ERR_LEN);
1314                 return errbuf;
1315         }
1316         snprintf(errbuf, SSL_ERR_LEN, libpq_gettext("SSL error code %lu"), errcode);
1317         return errbuf;
1318 }
1319
1320 static void
1321 SSLerrfree(char *buf)
1322 {
1323         if (buf != ssl_nomem)
1324                 free(buf);
1325 }
1326
1327 /*
1328  *      Return pointer to OpenSSL object.
1329  */
1330 void *
1331 PQgetssl(PGconn *conn)
1332 {
1333         if (!conn)
1334                 return NULL;
1335         return conn->ssl;
1336 }
1337 #else                                                   /* !USE_SSL */
1338
1339 void *
1340 PQgetssl(PGconn *conn)
1341 {
1342         return NULL;
1343 }
1344 #endif   /* USE_SSL */
1345
1346
1347 #if defined(ENABLE_THREAD_SAFETY) && !defined(WIN32)
1348
1349 /*
1350  *      Block SIGPIPE for this thread.  This prevents send()/write() from exiting
1351  *      the application.
1352  */
1353 int
1354 pq_block_sigpipe(sigset_t *osigset, bool *sigpipe_pending)
1355 {
1356         sigset_t        sigpipe_sigset;
1357         sigset_t        sigset;
1358
1359         sigemptyset(&sigpipe_sigset);
1360         sigaddset(&sigpipe_sigset, SIGPIPE);
1361
1362         /* Block SIGPIPE and save previous mask for later reset */
1363         SOCK_ERRNO_SET(pthread_sigmask(SIG_BLOCK, &sigpipe_sigset, osigset));
1364         if (SOCK_ERRNO)
1365                 return -1;
1366
1367         /* We can have a pending SIGPIPE only if it was blocked before */
1368         if (sigismember(osigset, SIGPIPE))
1369         {
1370                 /* Is there a pending SIGPIPE? */
1371                 if (sigpending(&sigset) != 0)
1372                         return -1;
1373
1374                 if (sigismember(&sigset, SIGPIPE))
1375                         *sigpipe_pending = true;
1376                 else
1377                         *sigpipe_pending = false;
1378         }
1379         else
1380                 *sigpipe_pending = false;
1381
1382         return 0;
1383 }
1384
1385 /*
1386  *      Discard any pending SIGPIPE and reset the signal mask.
1387  *
1388  * Note: we are effectively assuming here that the C library doesn't queue
1389  * up multiple SIGPIPE events.  If it did, then we'd accidentally leave
1390  * ours in the queue when an event was already pending and we got another.
1391  * As long as it doesn't queue multiple events, we're OK because the caller
1392  * can't tell the difference.
1393  *
1394  * The caller should say got_epipe = FALSE if it is certain that it
1395  * didn't get an EPIPE error; in that case we'll skip the clear operation
1396  * and things are definitely OK, queuing or no.  If it got one or might have
1397  * gotten one, pass got_epipe = TRUE.
1398  *
1399  * We do not want this to change errno, since if it did that could lose
1400  * the error code from a preceding send().      We essentially assume that if
1401  * we were able to do pq_block_sigpipe(), this can't fail.
1402  */
1403 void
1404 pq_reset_sigpipe(sigset_t *osigset, bool sigpipe_pending, bool got_epipe)
1405 {
1406         int                     save_errno = SOCK_ERRNO;
1407         int                     signo;
1408         sigset_t        sigset;
1409
1410         /* Clear SIGPIPE only if none was pending */
1411         if (got_epipe && !sigpipe_pending)
1412         {
1413                 if (sigpending(&sigset) == 0 &&
1414                         sigismember(&sigset, SIGPIPE))
1415                 {
1416                         sigset_t        sigpipe_sigset;
1417
1418                         sigemptyset(&sigpipe_sigset);
1419                         sigaddset(&sigpipe_sigset, SIGPIPE);
1420
1421                         sigwait(&sigpipe_sigset, &signo);
1422                 }
1423         }
1424
1425         /* Restore saved block mask */
1426         pthread_sigmask(SIG_SETMASK, osigset, NULL);
1427
1428         SOCK_ERRNO_SET(save_errno);
1429 }
1430
1431 #endif   /* ENABLE_THREAD_SAFETY && !WIN32 */