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