Added bug 90185 to changelog
[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-account-mgr-helpers.h"
47 #include "modest-text-utils.h"
48 #include <modest-local-folder-info.h>
49
50 GQuark
51 modest_utils_get_supported_secure_authentication_error_quark (void)
52 {
53         return g_quark_from_static_string("modest-utils-get-supported-secure-authentication-error-quark");
54 }
55
56 gboolean 
57 modest_utils_folder_writable (const gchar *filename)
58 {
59         g_return_val_if_fail (filename, FALSE);
60
61         if (!filename)
62                 return FALSE;
63         
64         if (g_strncasecmp (filename, "obex", 4) != 0) {
65                 GnomeVFSFileInfo *folder_info;
66                 gchar *folder;
67                 folder = g_path_get_dirname (filename);
68                 folder_info = gnome_vfs_file_info_new ();
69                 gnome_vfs_get_file_info (folder, folder_info,
70                                          GNOME_VFS_FILE_INFO_GET_ACCESS_RIGHTS);
71                 g_free (folder);
72                 if (!((folder_info->permissions & GNOME_VFS_PERM_ACCESS_WRITABLE) ||
73                       (folder_info->permissions & GNOME_VFS_PERM_USER_WRITE))) {
74                         return FALSE;
75                 }
76                 gnome_vfs_file_info_unref (folder_info);
77         }
78         return TRUE;
79 }
80
81 gboolean 
82 modest_utils_file_exists (const gchar *filename)
83 {
84         GnomeVFSURI *uri = NULL;
85         gboolean result = FALSE;
86
87         g_return_val_if_fail (filename, FALSE);
88         
89         uri = gnome_vfs_uri_new (filename);
90         if (uri) {
91                 result = gnome_vfs_uri_exists (uri);
92                 gnome_vfs_uri_unref (uri);
93         }
94         return result;
95 }
96
97 TnyFsStream *
98 modest_utils_create_temp_stream (const gchar *orig_name, const gchar *hash_base, gchar **path)
99 {
100         gint fd;
101         gchar *filepath = NULL;
102         gchar *tmpdir;
103         guint hash_number;
104
105         /* hmmm... maybe we need a modest_text_utils_validate_file_name? */
106         g_return_val_if_fail (orig_name && strlen(orig_name) != 0, NULL);
107
108         if (strlen(orig_name) > 200) {
109                 g_warning ("%s: filename too long ('%s')",
110                            __FUNCTION__, orig_name);
111                 return NULL;
112         }
113
114         if (g_strstr_len (orig_name, strlen(orig_name), "/") != NULL) {
115                 g_warning ("%s: filename contains '/' character(s) (%s)",
116                            __FUNCTION__, orig_name);
117                 return NULL;
118         }
119
120         /* make a random subdir under /tmp or /var/tmp */
121         if (hash_base != NULL) {
122                 hash_number = g_str_hash (hash_base);
123         } else {
124                 hash_number = (guint) random ();
125         }
126         tmpdir = g_strdup_printf ("%s/%u", g_get_tmp_dir (), hash_number);
127         if ((g_access (tmpdir, R_OK) == -1) && (g_mkdir (tmpdir, 0755) == -1)) {
128                 g_warning ("%s: failed to create dir '%s': %s",
129                            __FUNCTION__, tmpdir, g_strerror(errno));
130                 g_free (tmpdir);
131                 return NULL;
132         }
133
134         filepath = g_strconcat (tmpdir, "/", orig_name, NULL);
135         /* don't overwrite if it already exists, even if it is writable */
136         if (modest_utils_file_exists (filepath)) {
137                 if (path!=NULL) {
138                         *path = filepath;
139                 } else {
140                         g_free (filepath);
141                 }
142                 g_free (tmpdir);
143                 return NULL;
144         } else {
145                 /* try to write the file there */
146                 fd = g_open (filepath, O_CREAT|O_WRONLY|O_TRUNC, 0644);
147                 if (fd == -1) {
148                         g_warning ("%s: failed to create '%s': %s",
149                                         __FUNCTION__, filepath, g_strerror(errno));
150                         g_free (filepath);
151                         g_free (tmpdir);
152                         return NULL;
153                 }
154         }
155
156         g_free (tmpdir);
157
158         if (path)
159                 *path = filepath;
160
161         return TNY_FS_STREAM (tny_fs_stream_new (fd));
162 }
163
164 typedef struct 
165 {
166         gboolean cancel;
167         GList *result;
168         GtkWidget* dialog;
169         GtkWidget* progress;
170         GError* error;
171 } ModestGetSupportedAuthInfo;
172
173 static void on_camel_account_get_supported_secure_authentication_status (
174         GObject *self, TnyStatus *status, gpointer user_data)
175 {
176         /*ModestGetSupportedAuthInfo* info = (ModestGetSupportedAuthInfo*) user_data;*/
177 }
178
179 static gboolean
180 on_idle_secure_auth_finished (gpointer user_data)
181 {
182         ModestGetSupportedAuthInfo *info = (ModestGetSupportedAuthInfo*)user_data;
183         /* Operation has finished, close the dialog. Control continues after
184          * gtk_dialog_run in modest_utils_get_supported_secure_authentication_methods() */
185
186         /* This is a GDK lock because we are an idle callback and
187          * the code below is or does Gtk+ code */
188
189         gdk_threads_enter(); /* CHECKED */
190         gtk_dialog_response (GTK_DIALOG (info->dialog), GTK_RESPONSE_ACCEPT);
191         gdk_threads_leave(); /* CHECKED */
192
193         return FALSE;
194 }
195
196 static void
197 on_camel_account_get_supported_secure_authentication (TnyCamelAccount *self, gboolean cancelled,
198         TnyList *auth_types, GError *err, gpointer user_data)
199 {
200         g_return_if_fail (TNY_IS_CAMEL_ACCOUNT(self));
201         g_return_if_fail (TNY_IS_LIST(auth_types));
202         
203         ModestGetSupportedAuthInfo *info = (ModestGetSupportedAuthInfo*)user_data;
204         g_return_if_fail (info);
205         
206
207         /* Free everything if the actual action was canceled */
208         if (info->cancel) {
209                 /* The operation was canceled and the ownership of the info given to us
210                  * so that we could still check the cancel flag. */
211                 g_slice_free (ModestGetSupportedAuthInfo, info);
212                 info = NULL;
213         }
214         else
215         {
216                 if (err) {
217                         if (info->error) {
218                                 g_error_free (info->error);
219                                 info->error = NULL;
220                         }
221                         
222                         info->error = g_error_copy (err);
223                 }
224
225                 if (!auth_types) {
226                         g_warning ("DEBUG: %s: auth_types is NULL.\n", __FUNCTION__);
227                 }
228                 else if (tny_list_get_length(auth_types) == 0) 
229                         g_warning ("DEBUG: %s: auth_types is an empty TnyList.\n", __FUNCTION__);
230                 else {
231                         ModestPairList* pairs = modest_protocol_info_get_auth_protocol_pair_list ();
232   
233                         /* Get the enum value for the strings: */
234                         GList *result = NULL;
235                         TnyIterator* iter = tny_list_create_iterator(auth_types);
236                         while (!tny_iterator_is_done(iter)) {
237                                 TnyPair *pair = TNY_PAIR(tny_iterator_get_current(iter));
238                                 const gchar *auth_name = NULL;
239                                 if (pair) {
240                                         auth_name = tny_pair_get_name(pair);
241                                         g_object_unref (pair);
242                                         pair = NULL;
243                                 }
244
245                                 printf("DEBUG: %s: auth_name=%s\n", __FUNCTION__, auth_name);
246
247                                 ModestAuthProtocol proto = modest_protocol_info_get_auth_protocol (auth_name);
248                                 if(proto != MODEST_PROTOCOL_AUTH_NONE)
249                                                 result = g_list_prepend(result, GINT_TO_POINTER(proto));
250
251                                 tny_iterator_next(iter);
252                         }
253                         g_object_unref (iter);
254
255                         modest_pair_list_free (pairs);
256         
257                         info->result = result;
258                 }
259
260                 printf("DEBUG: finished\n");
261                                 
262                 /* Close the dialog in a main thread */
263                 g_idle_add(on_idle_secure_auth_finished, info);
264         }
265 }
266
267 static void
268 on_secure_auth_cancel(GtkWidget* dialog, int response, gpointer user_data)
269 {
270         g_return_if_fail (GTK_IS_WIDGET(dialog));
271         
272         if(response == GTK_RESPONSE_REJECT || response == GTK_RESPONSE_DELETE_EVENT) {
273                 ModestGetSupportedAuthInfo *info = (ModestGetSupportedAuthInfo*)user_data;
274                 g_return_if_fail(info);
275                 /* This gives the ownership of the info to the worker thread. */
276                 info->result = NULL;
277                 info->cancel = TRUE;
278         }
279 }
280 typedef struct {
281         GtkProgressBar *progress;
282         gboolean not_finished;
283 } KeepPulsing;
284
285 static gboolean
286 keep_pulsing (gpointer user_data)
287 {
288         KeepPulsing *info = (KeepPulsing *) user_data;
289         
290         gtk_progress_bar_pulse (info->progress);
291
292         if (!info->not_finished) {
293                 g_object_unref (info->progress);
294                 g_slice_free (KeepPulsing, info);
295                 return FALSE;
296         }
297         
298         return TRUE;
299 }
300
301 GList*
302 modest_utils_get_supported_secure_authentication_methods (ModestTransportStoreProtocol proto, 
303         const gchar* hostname, gint port, const gchar* username, GtkWindow *parent_window, GError** error)
304 {
305         g_return_val_if_fail (proto != MODEST_PROTOCOL_TRANSPORT_STORE_UNKNOWN, NULL);
306         
307         /* We need a connection to get the capabilities; */
308         if (!modest_platform_connect_and_wait (GTK_WINDOW (parent_window), NULL))
309                 return NULL;
310          
311         /*
312         result = g_list_append (result, GINT_TO_POINTER (MODEST_PROTOCOL_AUTH_CRAMMD5));
313         */
314         
315         /* Create a TnyCamelAccount so we can use 
316          * tny_camel_account_get_supported_secure_authentication(): */
317         TnyAccount * tny_account = NULL;
318         switch (proto) {
319         case MODEST_PROTOCOL_TRANSPORT_SENDMAIL:
320         case MODEST_PROTOCOL_TRANSPORT_SMTP:
321                 tny_account = TNY_ACCOUNT(tny_camel_transport_account_new ()); break;
322         case MODEST_PROTOCOL_STORE_POP:
323                 tny_account = TNY_ACCOUNT(tny_camel_pop_store_account_new ()); break;
324         case MODEST_PROTOCOL_STORE_IMAP:
325                 tny_account = TNY_ACCOUNT(tny_camel_imap_store_account_new ()); break;
326         case MODEST_PROTOCOL_STORE_MAILDIR:
327         case MODEST_PROTOCOL_STORE_MBOX:
328                 tny_account = TNY_ACCOUNT(tny_camel_store_account_new()); break;
329         default:
330                 tny_account = NULL;
331         }
332
333         
334         if (!tny_account) {
335                 g_printerr ("%s could not create tny account.", __FUNCTION__);
336                 return NULL;
337         }
338         
339         /* Set proto, so that the prepare_func() vfunc will work when we call 
340          * set_session(): */
341          /* TODO: Why isn't this done in account_new()? */
342         tny_account_set_proto (tny_account,
343                                modest_protocol_info_get_transport_store_protocol_name(proto));
344
345         tny_account_set_hostname (tny_account, hostname);
346         /* Required for POP, at least */
347         tny_account_set_user (tny_account, username);
348                                
349         if(port > 0)
350                 tny_account_set_port (tny_account, port);
351                 
352         /* Set the session for the account, so we can use it: */
353         ModestTnyAccountStore *account_store = modest_runtime_get_account_store ();
354         TnySessionCamel *session = 
355                 modest_tny_account_store_get_session (TNY_ACCOUNT_STORE (account_store));
356         g_return_val_if_fail (session, NULL);
357         tny_camel_account_set_session (TNY_CAMEL_ACCOUNT(tny_account), session);
358         
359         
360         /* Ask camel to ask the server, asynchronously: */
361         ModestGetSupportedAuthInfo *info = g_slice_new (ModestGetSupportedAuthInfo);
362         info->result = NULL;
363         info->cancel = FALSE;
364         info->error = NULL;
365         info->progress = gtk_progress_bar_new();
366
367         /* FIXME: the title (first arg) here is empty; there should be 'accountwizard_fi_authentication', 
368          *  but that does not exist yet; see bug #82487. so, for now, we simply leave it empty
369          */
370         info->dialog = gtk_dialog_new_with_buttons(" ", 
371                                                    parent_window, GTK_DIALOG_MODAL,
372                                                    _("mcen_bd_dialog_cancel"),
373                                                    GTK_RESPONSE_REJECT,
374                                                    NULL);
375         //gtk_window_set_default_size(GTK_WINDOW(info->dialog), 300, 100);
376         
377         g_signal_connect(G_OBJECT(info->dialog), "response", G_CALLBACK(on_secure_auth_cancel), info);
378         
379         gtk_container_add(GTK_CONTAINER(GTK_DIALOG(info->dialog)->vbox),
380                           gtk_label_new(_("emev_ni_checking_supported_auth_methods")));
381         gtk_container_add(GTK_CONTAINER(GTK_DIALOG(info->dialog)->vbox), info->progress);
382         gtk_widget_show_all(info->dialog);
383
384         KeepPulsing *pi = g_slice_new (KeepPulsing);
385         pi->progress = (GtkProgressBar *) g_object_ref (info->progress);
386         pi->not_finished = TRUE;
387         
388         /* Starts the pulsing of the progressbar */
389         g_timeout_add (500, keep_pulsing, pi);
390         
391         printf ("DEBUG: %s: STARTING.\n", __FUNCTION__);
392         
393         tny_camel_account_get_supported_secure_authentication (
394                 TNY_CAMEL_ACCOUNT (tny_account),
395                 on_camel_account_get_supported_secure_authentication,
396                 on_camel_account_get_supported_secure_authentication_status,
397                 info);
398
399         gtk_dialog_run (GTK_DIALOG (info->dialog));
400         
401         pi->not_finished = FALSE;
402         /* pi is freed in the timeout itself to avoid a GCond here */
403         
404         gtk_widget_destroy(info->dialog);
405                         
406         GList *result = info->result;
407         if (!info->cancel)
408         {
409                 if (info->error) {
410                         gchar * debug_url_string = tny_account_get_url_string  (tny_account);
411                         g_warning ("DEBUG: %s:\n  error: %s\n  account url: %s", __FUNCTION__, info->error->message, 
412                                 debug_url_string);
413                         g_free (debug_url_string);
414                         
415                         g_propagate_error(error, info->error);
416                         info->error = NULL;
417                 }
418
419                 g_slice_free (ModestGetSupportedAuthInfo, info);
420                 info = NULL;
421         }
422         else
423         {
424                 // Tell the caller that the operation was canceled so it can
425                 // make a difference
426                 g_set_error(error,
427                             modest_utils_get_supported_secure_authentication_error_quark(),
428                             MODEST_UTILS_GET_SUPPORTED_SECURE_AUTHENTICATION_ERROR_CANCELED,
429                             "User has canceled query");
430         }
431
432         return result;
433 }
434
435 void 
436 modest_utils_show_dialog_and_forget (GtkWindow *parent_window, 
437                                      GtkDialog *dialog)
438 {
439         g_return_if_fail (GTK_IS_WINDOW(parent_window));
440         g_return_if_fail (GTK_IS_DIALOG(dialog));
441
442         gtk_window_set_transient_for (GTK_WINDOW (dialog), parent_window);
443         
444         /* Destroy the dialog when it is closed: */
445         g_signal_connect_swapped (dialog, 
446                                   "response", 
447                                   G_CALLBACK (gtk_widget_destroy), 
448                                   dialog);
449
450         gtk_widget_show (GTK_WIDGET (dialog));
451 }
452
453 void
454 modest_utils_toggle_action_set_active_block_notify (GtkToggleAction *action, gboolean value)
455 {
456         GSList *proxies = NULL;
457
458         g_return_if_fail (GTK_IS_TOGGLE_ACTION (action));
459
460         for (proxies = gtk_action_get_proxies (GTK_ACTION (action));
461              proxies != NULL; proxies = g_slist_next (proxies)) {
462                 GtkWidget *widget = (GtkWidget *) proxies->data;
463                 gtk_action_block_activate_from (GTK_ACTION (action), widget);
464         }
465
466         gtk_toggle_action_set_active (action, value);
467
468         for (proxies = gtk_action_get_proxies (GTK_ACTION (action));
469              proxies != NULL; proxies = g_slist_next (proxies)) {
470                 GtkWidget *widget = (GtkWidget *) proxies->data;
471                 gtk_action_unblock_activate_from (GTK_ACTION (action), widget);
472         }
473
474 }
475
476
477 gint 
478 modest_list_index (TnyList *list, GObject *object)
479 {
480         TnyIterator *iter;
481         gint index = 0;
482
483         g_return_val_if_fail (TNY_IS_LIST(list), -1);
484         g_return_val_if_fail (G_IS_OBJECT(object), -1);
485         
486         iter = tny_list_create_iterator (list);
487         while (!tny_iterator_is_done (iter)) {
488                 GObject *current = tny_iterator_get_current (iter);
489
490                 g_object_unref (current);
491                 if (current == object)
492                         break;
493
494                 tny_iterator_next (iter);
495                 index++;
496         }
497
498         if (tny_iterator_is_done (iter))
499                 index = -1;
500         g_object_unref (iter);
501         return index;
502 }
503
504 guint64 
505 modest_utils_get_available_space (const gchar *maildir_path)
506 {
507         gchar *folder;
508         gchar *uri_string;
509         GnomeVFSURI *uri;
510         GnomeVFSFileSize size;
511
512         folder = modest_local_folder_info_get_maildir_path (maildir_path);
513         uri_string = gnome_vfs_get_uri_from_local_path (folder);
514         uri = gnome_vfs_uri_new (uri_string);
515         g_free (folder);
516         g_free (uri_string);
517
518         if (uri) {
519                 if (gnome_vfs_get_volume_free_space (uri, &size) != GNOME_VFS_OK)
520                         size = 0;
521                 gnome_vfs_uri_unref (uri);
522         } else {
523                 size = 0;
524         }
525
526         return (guint64) size;
527 }
528
529 gchar *
530 modest_utils_get_account_name_from_recipient (const gchar *from_header)
531 {
532         gchar *account_name = NULL;
533         ModestAccountMgr *mgr = NULL;
534         GSList *accounts = NULL, *node = NULL;
535
536         g_return_val_if_fail (from_header, NULL);
537
538         mgr = modest_runtime_get_account_mgr ();
539         accounts = modest_account_mgr_account_names (mgr, TRUE);
540                 
541         for (node = accounts; node != NULL; node = g_slist_next (node)) {
542                 gchar *from = 
543                         modest_account_mgr_get_from_string (mgr, node->data);
544                         
545                 if (from) {
546                         gchar *from_email = 
547                                 modest_text_utils_get_email_address (from);
548                                 
549                         if (from_email) {
550                                 if (!modest_text_utils_utf8_strcmp (from_header, from_email, TRUE)) {
551                                         account_name = g_strdup (node->data);
552                                         g_free (from);
553                                         g_free (from_email);
554                                         break;
555                                 }
556                                 g_free (from_email);
557                         }
558                         g_free (from);
559                 }
560         }
561         g_slist_foreach (accounts, (GFunc) g_free, NULL);
562         g_slist_free (accounts);
563
564         return account_name;
565 }