Make NSS database initialisation more robust, handle errors better
[platform/upstream/evolution-data-server.git] / camel / camel.c
1 /* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */
2 /*
3  *  Authors: Jeffrey Stedfast <fejj@ximian.com>
4  *           Bertrand Guiheneuf <bertrand@helixcode.com>
5  *
6  *  Copyright (C) 1999-2008 Novell, Inc. (www.novell.com)
7  *
8  *  This program is free software; you can redistribute it and/or modify
9  *  it under the terms of the GNU Lesser General Public License as published by
10  *  the Free Software Foundation; either version 2 of the License, or
11  *  (at your option) any later version.
12  *
13  *  This program is distributed in the hope that it will be useful,
14  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
15  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  *  GNU Lesser General Public License for more details.
17  *
18  *  You should have received a copy of the GNU Lesser General Public License
19  *  along with this program; if not, write to the Free Software
20  *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21  *
22  */
23
24 #ifdef HAVE_CONFIG_H
25 #include <config.h>
26 #endif
27
28 #include <signal.h>
29
30 #ifdef HAVE_NSS
31 #include <nspr.h>
32 #include <prthread.h>
33 #include "nss.h"      /* Don't use <> here or it will include the system nss.h instead */
34 #include <ssl.h>
35 #include <errno.h>
36 #endif /* HAVE_NSS */
37
38 #include <glib/gi18n-lib.h>
39
40 #include "camel.h"
41 #include "camel-certdb.h"
42 #include "camel-debug.h"
43 #include "camel-provider.h"
44 #include "camel-win32.h"
45
46 #ifdef HAVE_NSS
47 /* To protect NSS initialization and shutdown. This prevents
48    concurrent calls to shutdown() and init() by different threads */
49 PRLock *nss_initlock = NULL;
50
51 /* Whether or not Camel has initialized the NSS library. We cannot
52    unconditionally call NSS_Shutdown() if NSS was initialized by other
53    library before. This boolean ensures that we only perform a cleanup
54    if and only if Camel is the one that previously initialized NSS */
55 volatile gboolean nss_initialized = FALSE;
56 #endif
57
58 static gint initialised = FALSE;
59
60 gint camel_application_is_exiting = FALSE;
61
62 #define NSS_SYSTEM_DB "/etc/pki/nssdb"
63
64 static gint
65 nss_has_system_db(void)
66 {
67         int found = FALSE;
68 #ifndef G_OS_WIN32
69         FILE *f;
70         char buf[80];
71
72         f = fopen(NSS_SYSTEM_DB "/pkcs11.txt", "r");
73         if (!f)
74                 return FALSE;
75                 
76         /* Check whether the system NSS db is actually enabled */
77         while (fgets(buf, 80, f) && !found) {
78                 if (!strcmp(buf, "library=libnsssysinit.so\n"))
79                         found = TRUE;
80         }
81         fclose(f);
82 #endif
83         return found;
84 }
85
86 gint
87 camel_init (const gchar *configdir, gboolean nss_init)
88 {
89         CamelCertDB *certdb;
90         gchar *path;
91
92         if (initialised)
93                 return 0;
94
95         bindtextdomain (GETTEXT_PACKAGE, LOCALEDIR);
96         bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
97
98         camel_debug_init();
99
100 #ifdef HAVE_NSS
101         if (nss_init) {
102                 gchar *nss_configdir = NULL;
103                 gchar *nss_sql_configdir = NULL;
104                 SECStatus status = SECFailure;
105                 PRUint16 indx;
106
107                 if (nss_initlock == NULL) {
108                         PR_Init(PR_SYSTEM_THREAD, PR_PRIORITY_NORMAL, 10);
109                         nss_initlock = PR_NewLock();
110                 }
111                 PR_Lock (nss_initlock);
112
113                 if (NSS_IsInitialized ())
114                         goto skip_nss_init;
115
116 #ifndef G_OS_WIN32
117                 nss_configdir = g_strdup (configdir);
118 #else
119                 nss_configdir = g_win32_locale_filename_from_utf8 (configdir);
120 #endif
121
122                 if (nss_has_system_db ()) {
123                         nss_sql_configdir = g_strdup ("sql:" NSS_SYSTEM_DB );
124                 } else {
125                         /* On Windows, we use the Evolution configdir. On other
126                          * operating systems we use ~/.pki/nssdb/, which is where
127                          * the user-specific part of the "shared system db" is
128                          * stored and is what Chrome uses too.
129                          *
130                          * We have to create the configdir if it does not exist,
131                          * to prevent camel from bailing out on first run. */
132 #ifdef G_OS_WIN32
133                         g_mkdir_with_parents (configdir, 0700);
134                         nss_sql_configdir = g_strconcat ("sql:", nss_configdir, NULL);
135 #else
136                         gchar *user_nss_dir = g_build_filename ( g_get_home_dir (),
137                                                                  ".pki/nssdb", NULL );
138                         if (g_mkdir_with_parents (user_nss_dir, 0700))
139                                 g_warning("Failed to create SQL database directory %s: %s\n",
140                                           user_nss_dir, strerror(errno));
141
142                         nss_sql_configdir = g_strconcat ("sql:", user_nss_dir, NULL);
143                         g_free(user_nss_dir);
144 #endif
145                 }
146
147
148 #if NSS_VMAJOR > 3 || (NSS_VMAJOR == 3 && NSS_VMINOR >= 12)
149                 /* See: https://wiki.mozilla.org/NSS_Shared_DB,
150                  * particularly "Mode 3A".  Note that the target
151                  * directory MUST EXIST. */
152                 status = NSS_InitWithMerge (
153                         nss_sql_configdir,      /* dest dir */
154                         "", "",                 /* new DB name prefixes */
155                         SECMOD_DB,              /* secmod name */
156                         nss_configdir,          /* old DB dir */
157                         "", "",                 /* old DB name prefixes */
158                         nss_configdir,          /* unique ID for old DB */
159                         "Evolution S/MIME",     /* UI name for old DB */
160                         0);                     /* flags */
161
162                 if (status == SECFailure) {
163                         g_warning ("Failed to initialize NSS SQL database in %s: NSS error %d",
164                                    nss_sql_configdir, PORT_GetError());
165                         /* Fall back to opening the old DBM database */
166                 }
167 #endif
168                 /* Support old versions of libnss, pre-sqlite support. */
169                 if (status == SECFailure)
170                         status = NSS_InitReadWrite (nss_configdir);
171                 if (status == SECFailure) {
172                         /* Fall back to using volatile dbs? */
173                         status = NSS_NoDB_Init (nss_configdir);
174                         if (status == SECFailure) {
175                                 g_free (nss_configdir);
176                                 g_free (nss_sql_configdir);
177                                 g_warning ("Failed to initialize NSS");
178                                 PR_Unlock (nss_initlock);
179                                 return -1;
180                         }
181                 }
182
183                 nss_initialized = TRUE;
184 skip_nss_init:
185
186                 NSS_SetDomesticPolicy ();
187
188                 PR_Unlock(nss_initlock);
189
190                 /* we must enable all ciphersuites */
191                 for (indx = 0; indx < SSL_NumImplementedCiphers; indx++) {
192                         if (!SSL_IS_SSL2_CIPHER(SSL_ImplementedCiphers[indx]))
193                                 SSL_CipherPrefSetDefault (SSL_ImplementedCiphers[indx], PR_TRUE);
194                 }
195
196                 SSL_OptionSetDefault (SSL_ENABLE_SSL2, PR_TRUE);
197                 SSL_OptionSetDefault (SSL_ENABLE_SSL3, PR_TRUE);
198                 SSL_OptionSetDefault (SSL_ENABLE_TLS, PR_TRUE);
199                 SSL_OptionSetDefault (SSL_V2_COMPATIBLE_HELLO, PR_TRUE /* maybe? */);
200
201                 g_free (nss_configdir);
202                 g_free (nss_sql_configdir);
203         }
204 #endif /* HAVE_NSS */
205
206         path = g_strdup_printf ("%s/camel-cert.db", configdir);
207         certdb = camel_certdb_new ();
208         camel_certdb_set_filename (certdb, path);
209         g_free (path);
210
211         /* if we fail to load, who cares? it'll just be a volatile certdb */
212         camel_certdb_load (certdb);
213
214         /* set this certdb as the default db */
215         camel_certdb_set_default (certdb);
216
217         g_object_unref (certdb);
218
219         initialised = TRUE;
220
221         return 0;
222 }
223
224 /**
225  * camel_shutdown:
226  *
227  * Since: 2.24
228  **/
229 void
230 camel_shutdown (void)
231 {
232         CamelCertDB *certdb;
233
234         if (!initialised)
235                 return;
236
237         certdb = camel_certdb_get_default ();
238         if (certdb) {
239                 camel_certdb_save (certdb);
240                 camel_certdb_set_default (NULL);
241         }
242
243         /* These next calls must come last. */
244
245 #if defined (HAVE_NSS)
246         if (nss_initlock != NULL) {
247                 PR_Lock(nss_initlock);
248                 if (nss_initialized)
249                         NSS_Shutdown ();
250                 PR_Unlock(nss_initlock);
251         }
252 #endif /* HAVE_NSS */
253
254         initialised = FALSE;
255 }