* Partially fixes NB#83671, fixes several reference leaks and remove passwords in...
[modest] / src / modest-utils.c
1 /* Copyright (c) 2007, Nokia Corporation
2  * All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions are
6  * met:
7  *
8  * * Redistributions of source code must retain the above copyright
9  *   notice, this list of conditions and the following disclaimer.
10  * * Redistributions in binary form must reproduce the above copyright
11  *   notice, this list of conditions and the following disclaimer in the
12  *   documentation and/or other materials provided with the distribution.
13  * * Neither the name of the Nokia Corporation nor the names of its
14  *   contributors may be used to endorse or promote products derived from
15  *   this software without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
18  * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
19  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
20  * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
21  * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
22  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
23  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
24  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
25  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
26  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
27  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28  */
29
30 #include <glib.h>
31 #include <glib/gstdio.h>
32 #include <errno.h>
33 #include <string.h> /* for strlen */
34 #include <modest-runtime.h>
35 #include <libgnomevfs/gnome-vfs.h>
36 #include <tny-fs-stream.h>
37 #include <tny-camel-account.h>
38 #include <tny-status.h>
39 #include <tny-camel-transport-account.h>
40 #include <tny-camel-imap-store-account.h>
41 #include <tny-camel-pop-store-account.h>
42
43 #include <modest-defs.h>
44 #include "modest-utils.h"
45 #include "modest-platform.h"
46 #include <modest-local-folder-info.h>
47
48 GQuark
49 modest_utils_get_supported_secure_authentication_error_quark (void)
50 {
51         return g_quark_from_static_string("modest-utils-get-supported-secure-authentication-error-quark");
52 }
53
54 gboolean 
55 modest_utils_folder_writable (const gchar *filename)
56 {
57         g_return_val_if_fail (filename, FALSE);
58
59         if (!filename)
60                 return FALSE;
61         
62         if (g_strncasecmp (filename, "obex", 4) != 0) {
63                 GnomeVFSFileInfo *folder_info;
64                 gchar *folder;
65                 folder = g_path_get_dirname (filename);
66                 folder_info = gnome_vfs_file_info_new ();
67                 gnome_vfs_get_file_info (folder, folder_info,
68                                          GNOME_VFS_FILE_INFO_GET_ACCESS_RIGHTS);
69                 g_free (folder);
70                 if (!((folder_info->permissions & GNOME_VFS_PERM_ACCESS_WRITABLE) ||
71                       (folder_info->permissions & GNOME_VFS_PERM_USER_WRITE))) {
72                         return FALSE;
73                 }
74                 gnome_vfs_file_info_unref (folder_info);
75         }
76         return TRUE;
77 }
78
79 gboolean 
80 modest_utils_file_exists (const gchar *filename)
81 {
82         GnomeVFSURI *uri = NULL;
83         gboolean result = FALSE;
84
85         g_return_val_if_fail (filename, FALSE);
86         
87         uri = gnome_vfs_uri_new (filename);
88         if (uri) {
89                 result = gnome_vfs_uri_exists (uri);
90                 gnome_vfs_uri_unref (uri);
91         }
92         return result;
93 }
94
95 TnyFsStream *
96 modest_utils_create_temp_stream (const gchar *orig_name, const gchar *hash_base, gchar **path)
97 {
98         gint fd;
99         gchar *filepath = NULL;
100         gchar *tmpdir;
101         guint hash_number;
102
103         /* hmmm... maybe we need a modest_text_utils_validate_file_name? */
104         g_return_val_if_fail (orig_name && strlen(orig_name) != 0, NULL);
105
106         if (strlen(orig_name) > 200) {
107                 g_warning ("%s: filename too long ('%s')",
108                            __FUNCTION__, orig_name);
109                 return NULL;
110         }
111         
112         if (g_strstr_len (orig_name, strlen(orig_name), "/") != NULL) {
113                 g_warning ("%s: filename contains '/' character(s) (%s)",
114                            __FUNCTION__, orig_name);
115                 return NULL;
116         }
117                 
118         /* make a random subdir under /tmp or /var/tmp */
119         if (hash_base != NULL) {
120                 hash_number = g_str_hash (hash_base);
121         } else {
122                 hash_number = (guint) random ();
123         }
124         tmpdir = g_strdup_printf ("%s/%u", g_get_tmp_dir (), hash_number);
125         if ((g_access (tmpdir, R_OK) == -1) && (g_mkdir (tmpdir, 0755) == -1)) {
126                 g_warning ("%s: failed to create dir '%s': %s",
127                            __FUNCTION__, tmpdir, g_strerror(errno));
128                 g_free (tmpdir);
129                 return NULL;
130         }
131
132         filepath = g_strconcat (tmpdir, "/", orig_name, NULL);
133         /* don't overwrite if it already exists, even if it is writable */
134         if (modest_utils_file_exists (filepath)) {
135                 if (path!=NULL) {
136                         *path = filepath;
137                 } else {
138                         g_free (filepath);
139                 }
140                 g_free (tmpdir);
141                 return NULL;
142         } else {
143                 /* try to write the file there */
144                 fd = g_open (filepath, O_CREAT|O_WRONLY|O_TRUNC, 0644);
145                 if (fd == -1) {
146                         g_warning ("%s: failed to create '%s': %s",
147                                         __FUNCTION__, filepath, g_strerror(errno));                     
148                         g_free (filepath);
149                         g_free (tmpdir);
150                         return NULL;
151                 }
152         }
153
154         g_free (tmpdir);
155
156         if (path)
157                 *path = filepath;
158
159         return TNY_FS_STREAM (tny_fs_stream_new (fd));
160 }
161
162 typedef struct 
163 {
164         gboolean cancel;
165         GList *result;
166         GtkWidget* dialog;
167         GtkWidget* progress;
168         GError* error;
169 } ModestGetSupportedAuthInfo;
170
171 static void on_camel_account_get_supported_secure_authentication_status (
172         GObject *self, TnyStatus *status, gpointer user_data)
173 {
174         /*ModestGetSupportedAuthInfo* info = (ModestGetSupportedAuthInfo*) user_data;*/
175 }
176
177 static gboolean
178 on_idle_secure_auth_finished (gpointer user_data)
179 {
180         ModestGetSupportedAuthInfo *info = (ModestGetSupportedAuthInfo*)user_data;
181         /* Operation has finished, close the dialog. Control continues after
182          * gtk_dialog_run in modest_utils_get_supported_secure_authentication_methods() */
183
184         /* This is a GDK lock because we are an idle callback and
185          * the code below is or does Gtk+ code */
186
187         gdk_threads_enter(); /* CHECKED */
188         gtk_dialog_response (GTK_DIALOG (info->dialog), GTK_RESPONSE_ACCEPT);
189         gdk_threads_leave(); /* CHECKED */
190
191         return FALSE;
192 }
193
194 static void
195 on_camel_account_get_supported_secure_authentication (TnyCamelAccount *self, gboolean cancelled,
196         TnyList *auth_types, GError *err, gpointer user_data)
197 {
198         g_return_if_fail (TNY_IS_CAMEL_ACCOUNT(self));
199         g_return_if_fail (TNY_IS_LIST(auth_types));
200         
201         ModestGetSupportedAuthInfo *info = (ModestGetSupportedAuthInfo*)user_data;
202         g_return_if_fail (info);
203         
204
205         /* Free everything if the actual action was canceled */
206         if (info->cancel) {
207                 /* The operation was canceled and the ownership of the info given to us
208                  * so that we could still check the cancel flag. */
209                 g_slice_free (ModestGetSupportedAuthInfo, info);
210                 info = NULL;
211         }
212         else
213         {
214                 if (err) {
215                         if (info->error) {
216                                 g_error_free (info->error);
217                                 info->error = NULL;
218                         }
219                         
220                         info->error = g_error_copy (err);
221                 }
222
223                 if (!auth_types) {
224                         g_warning ("DEBUG: %s: auth_types is NULL.\n", __FUNCTION__);
225                 }
226                 else if (tny_list_get_length(auth_types) == 0) 
227                         g_warning ("DEBUG: %s: auth_types is an empty TnyList.\n", __FUNCTION__);
228                 else {
229                         ModestPairList* pairs = modest_protocol_info_get_auth_protocol_pair_list ();
230   
231                         /* Get the enum value for the strings: */
232                         GList *result = NULL;
233                         TnyIterator* iter = tny_list_create_iterator(auth_types);
234                         while (!tny_iterator_is_done(iter)) {
235                                 TnyPair *pair = TNY_PAIR(tny_iterator_get_current(iter));
236                                 const gchar *auth_name = NULL;
237                                 if (pair) {
238                                         auth_name = tny_pair_get_name(pair);
239                                         g_object_unref (pair);
240                                         pair = NULL;
241                                 }
242
243                                 printf("DEBUG: %s: auth_name=%s\n", __FUNCTION__, auth_name);
244
245                                 ModestAuthProtocol proto = modest_protocol_info_get_auth_protocol (auth_name);
246                                 if(proto != MODEST_PROTOCOL_AUTH_NONE)
247                                                 result = g_list_prepend(result, GINT_TO_POINTER(proto));
248
249                                 tny_iterator_next(iter);
250                         }
251                         g_object_unref (iter);
252
253                         modest_pair_list_free (pairs);
254         
255                         info->result = result;
256                 }
257
258                 printf("DEBUG: finished\n");
259                                 
260                 /* Close the dialog in a main thread */
261                 g_idle_add(on_idle_secure_auth_finished, info);
262         }
263 }
264
265 static void
266 on_secure_auth_cancel(GtkWidget* dialog, int response, gpointer user_data)
267 {
268         g_return_if_fail (GTK_IS_WIDGET(dialog));
269         
270         if(response == GTK_RESPONSE_REJECT || response == GTK_RESPONSE_DELETE_EVENT) {
271                 ModestGetSupportedAuthInfo *info = (ModestGetSupportedAuthInfo*)user_data;
272                 g_return_if_fail(info);
273                 /* This gives the ownership of the info to the worker thread. */
274                 info->result = NULL;
275                 info->cancel = TRUE;
276         }
277 }
278 typedef struct {
279         GtkProgressBar *progress;
280         gboolean not_finished;
281 } KeepPulsing;
282
283 static gboolean
284 keep_pulsing (gpointer user_data)
285 {
286         KeepPulsing *info = (KeepPulsing *) user_data;
287         
288         gtk_progress_bar_pulse (info->progress);
289
290         if (!info->not_finished) {
291                 g_object_unref (info->progress);
292                 g_slice_free (KeepPulsing, info);
293                 return FALSE;
294         }
295         
296         return TRUE;
297 }
298
299 GList*
300 modest_utils_get_supported_secure_authentication_methods (ModestTransportStoreProtocol proto, 
301         const gchar* hostname, gint port, const gchar* username, GtkWindow *parent_window, GError** error)
302 {
303         g_return_val_if_fail (proto != MODEST_PROTOCOL_TRANSPORT_STORE_UNKNOWN, NULL);
304         
305         /* We need a connection to get the capabilities; */
306         if (!modest_platform_connect_and_wait (GTK_WINDOW (parent_window), NULL))
307                 return NULL;
308          
309         /*
310         result = g_list_append (result, GINT_TO_POINTER (MODEST_PROTOCOL_AUTH_CRAMMD5));
311         */
312         
313         /* Create a TnyCamelAccount so we can use 
314          * tny_camel_account_get_supported_secure_authentication(): */
315         TnyAccount * tny_account = NULL;
316         switch (proto) {
317         case MODEST_PROTOCOL_TRANSPORT_SENDMAIL:
318         case MODEST_PROTOCOL_TRANSPORT_SMTP:
319                 tny_account = TNY_ACCOUNT(tny_camel_transport_account_new ()); break;
320         case MODEST_PROTOCOL_STORE_POP:
321                 tny_account = TNY_ACCOUNT(tny_camel_pop_store_account_new ()); break;
322         case MODEST_PROTOCOL_STORE_IMAP:
323                 tny_account = TNY_ACCOUNT(tny_camel_imap_store_account_new ()); break;
324         case MODEST_PROTOCOL_STORE_MAILDIR:
325         case MODEST_PROTOCOL_STORE_MBOX:
326                 tny_account = TNY_ACCOUNT(tny_camel_store_account_new()); break;
327         default:
328                 tny_account = NULL;
329         }
330
331         
332         if (!tny_account) {
333                 g_printerr ("%s could not create tny account.", __FUNCTION__);
334                 return NULL;
335         }
336         
337         /* Set proto, so that the prepare_func() vfunc will work when we call 
338          * set_session(): */
339          /* TODO: Why isn't this done in account_new()? */
340         tny_account_set_proto (tny_account,
341                                modest_protocol_info_get_transport_store_protocol_name(proto));
342
343         tny_account_set_hostname (tny_account, hostname);
344         /* Required for POP, at least */
345         tny_account_set_user (tny_account, username);
346                                
347         if(port > 0)
348                 tny_account_set_port (tny_account, port);
349                 
350         /* Set the session for the account, so we can use it: */
351         ModestTnyAccountStore *account_store = modest_runtime_get_account_store ();
352         TnySessionCamel *session = 
353                 modest_tny_account_store_get_session (TNY_ACCOUNT_STORE (account_store));
354         g_return_val_if_fail (session, NULL);
355         tny_camel_account_set_session (TNY_CAMEL_ACCOUNT(tny_account), session);
356         
357         
358         /* Ask camel to ask the server, asynchronously: */
359         ModestGetSupportedAuthInfo *info = g_slice_new (ModestGetSupportedAuthInfo);
360         info->result = NULL;
361         info->cancel = FALSE;
362         info->error = NULL;
363         info->progress = gtk_progress_bar_new();
364         /* TODO: Need logical_ID for the title: */
365         info->dialog = gtk_dialog_new_with_buttons(" ",
366                                                    parent_window, GTK_DIALOG_MODAL,
367                                                    _("mcen_bd_dialog_cancel"),
368                                                    GTK_RESPONSE_REJECT,
369                                                    NULL);
370         //gtk_window_set_default_size(GTK_WINDOW(info->dialog), 300, 100);
371         
372         g_signal_connect(G_OBJECT(info->dialog), "response", G_CALLBACK(on_secure_auth_cancel), info);
373         
374         gtk_container_add(GTK_CONTAINER(GTK_DIALOG(info->dialog)->vbox),
375                           gtk_label_new(_("emev_ni_checking_supported_auth_methods")));
376         gtk_container_add(GTK_CONTAINER(GTK_DIALOG(info->dialog)->vbox), info->progress);
377         gtk_widget_show_all(info->dialog);
378
379         KeepPulsing *pi = g_slice_new (KeepPulsing);
380         pi->progress = (GtkProgressBar *) g_object_ref (info->progress);
381         pi->not_finished = TRUE;
382         
383         /* Starts the pulsing of the progressbar */
384         g_timeout_add (500, keep_pulsing, pi);
385         
386         printf ("DEBUG: %s: STARTING.\n", __FUNCTION__);
387         
388         tny_camel_account_get_supported_secure_authentication (
389                 TNY_CAMEL_ACCOUNT (tny_account),
390                 on_camel_account_get_supported_secure_authentication,
391                 on_camel_account_get_supported_secure_authentication_status,
392                 info);
393
394         gtk_dialog_run (GTK_DIALOG (info->dialog));
395         
396         pi->not_finished = FALSE;
397         /* pi is freed in the timeout itself to avoid a GCond here */
398         
399         gtk_widget_destroy(info->dialog);
400                         
401         GList *result = info->result;
402         if (!info->cancel)
403         {
404                 if (info->error) {
405                         gchar * debug_url_string = tny_account_get_url_string  (tny_account);
406                         g_warning ("DEBUG: %s:\n  error: %s\n  account url: %s", __FUNCTION__, info->error->message, 
407                                 debug_url_string);
408                         g_free (debug_url_string);
409                         
410                         g_propagate_error(error, info->error);
411                         info->error = NULL;
412                 }
413
414                 g_slice_free (ModestGetSupportedAuthInfo, info);
415                 info = NULL;
416         }
417         else
418         {
419                 // Tell the caller that the operation was canceled so it can
420                 // make a difference
421                 g_set_error(error,
422                             modest_utils_get_supported_secure_authentication_error_quark(),
423                             MODEST_UTILS_GET_SUPPORTED_SECURE_AUTHENTICATION_ERROR_CANCELED,
424                             "User has canceled query");
425         }
426
427         return result;
428 }
429
430 void 
431 modest_utils_show_dialog_and_forget (GtkWindow *parent_window, 
432                                      GtkDialog *dialog)
433 {
434         g_return_if_fail (GTK_IS_WINDOW(parent_window));
435         g_return_if_fail (GTK_IS_DIALOG(dialog));
436
437         gtk_window_set_transient_for (GTK_WINDOW (dialog), parent_window);
438         
439         /* Destroy the dialog when it is closed: */
440         g_signal_connect_swapped (dialog, 
441                                   "response", 
442                                   G_CALLBACK (gtk_widget_destroy), 
443                                   dialog);
444
445         gtk_widget_show (GTK_WIDGET (dialog));
446 }
447
448 void
449 modest_utils_toggle_action_set_active_block_notify (GtkToggleAction *action, gboolean value)
450 {
451         GSList *proxies = NULL;
452
453         g_return_if_fail (GTK_IS_TOGGLE_ACTION (action));
454
455         for (proxies = gtk_action_get_proxies (GTK_ACTION (action));
456              proxies != NULL; proxies = g_slist_next (proxies)) {
457                 GtkWidget *widget = (GtkWidget *) proxies->data;
458                 gtk_action_block_activate_from (GTK_ACTION (action), widget);
459         }
460
461         gtk_toggle_action_set_active (action, value);
462
463         for (proxies = gtk_action_get_proxies (GTK_ACTION (action));
464              proxies != NULL; proxies = g_slist_next (proxies)) {
465                 GtkWidget *widget = (GtkWidget *) proxies->data;
466                 gtk_action_unblock_activate_from (GTK_ACTION (action), widget);
467         }
468
469 }
470
471
472 gint 
473 modest_list_index (TnyList *list, GObject *object)
474 {
475         TnyIterator *iter;
476         gint index = 0;
477
478         g_return_val_if_fail (TNY_IS_LIST(list), -1);
479         g_return_val_if_fail (G_IS_OBJECT(object), -1);
480         
481         iter = tny_list_create_iterator (list);
482         while (!tny_iterator_is_done (iter)) {
483                 GObject *current = tny_iterator_get_current (iter);
484
485                 g_object_unref (current);
486                 if (current == object)
487                         break;
488
489                 tny_iterator_next (iter);
490                 index++;
491         }
492
493         if (tny_iterator_is_done (iter))
494                 index = -1;
495         g_object_unref (iter);
496         return index;
497 }
498
499 guint64 
500 modest_folder_available_space (const gchar *maildir_path)
501 {
502         gchar *folder;
503         gchar *uri_string;
504         GnomeVFSURI *uri;
505         GnomeVFSFileSize size;
506
507         folder = modest_local_folder_info_get_maildir_path (maildir_path);
508         uri_string = gnome_vfs_get_uri_from_local_path (folder);
509         uri = gnome_vfs_uri_new (uri_string);
510         g_free (folder);
511         g_free (uri_string);
512
513         if (uri) {
514                 if (gnome_vfs_get_volume_free_space (uri, &size) != GNOME_VFS_OK)
515                         size = -1;
516                 gnome_vfs_uri_unref (uri);
517         } else {
518                 size = -1;
519         }
520
521         return (guint64) size;
522 }