]> git.0d.be Git - empathy.git/blob - libempathy/empathy-ft-handler.c
Don't destroy an hashtable owned by DBus
[empathy.git] / libempathy / empathy-ft-handler.c
1 /*
2  * empathy-ft-handler.c - Source for EmpathyFTHandler
3  * Copyright (C) 2009 Collabora Ltd.
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Lesser General Public
7  * License as published by the Free Software Foundation; either
8  * version 2.1 of the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * Lesser General Public License for more details.
14  *
15  * You should have received a copy of the GNU Lesser General Public
16  * License along with this library; if not, write to the Free Software
17  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
18  *
19  * Author: Cosimo Cecchi <cosimo.cecchi@collabora.co.uk>
20  */
21  
22 /* empathy-ft-handler.c */
23
24 #include <glib.h>
25 #include <glib/gi18n.h>
26 #include <telepathy-glib/util.h>
27
28 #include "empathy-ft-handler.h"
29 #include "empathy-tp-contact-factory.h"
30 #include "empathy-dispatcher.h"
31 #include "empathy-marshal.h"
32 #include "empathy-time.h"
33 #include "empathy-utils.h"
34
35 #define DEBUG_FLAG EMPATHY_DEBUG_FT
36 #include "empathy-debug.h"
37
38 G_DEFINE_TYPE (EmpathyFTHandler, empathy_ft_handler, G_TYPE_OBJECT)
39
40 #define GET_PRIV(obj) EMPATHY_GET_PRIV (obj, EmpathyFTHandler)
41
42 #define BUFFER_SIZE 4096
43
44 enum {
45   PROP_TP_FILE = 1,
46   PROP_G_FILE,
47   PROP_CONTACT,
48   PROP_USE_HASH
49 };
50
51 enum {
52   HASHING_STARTED,
53   HASHING_PROGRESS,
54   HASHING_DONE,
55   TRANSFER_STARTED,
56   TRANSFER_PROGRESS,
57   TRANSFER_DONE,
58   TRANSFER_ERROR,
59   LAST_SIGNAL
60 };
61
62 typedef struct {
63   GInputStream *stream;
64   GError *error;
65   guchar *buffer;
66   GChecksum *checksum;
67   gssize total_read;
68   guint64 total_bytes;
69   EmpathyFTHandler *handler;
70 } HashingData;
71
72 typedef struct {
73   EmpathyFTHandlerReadyCallback callback;
74   gpointer user_data;
75   EmpathyFTHandler *handler;
76 } CallbacksData;
77
78 /* private data */
79 typedef struct {
80   gboolean dispose_run;
81
82   GFile *gfile;
83   EmpathyTpFile *tpfile;
84   GCancellable *cancellable;
85   gboolean use_hash;
86
87   /* request for the new transfer */
88   GHashTable *request;
89
90   /* transfer properties */
91   EmpathyContact *contact;
92   gchar *content_type;
93   gchar *filename;
94   gchar *description;
95   guint64 total_bytes;
96   guint64 transferred_bytes;
97   guint64 mtime;
98   gchar *content_hash;
99   TpFileHashType content_hash_type;
100   TpFileTransferState current_state;
101
102   /* time and speed */
103   gdouble speed;
104   guint remaining_time;
105   time_t last_update_time;
106
107   gboolean is_completed;
108 } EmpathyFTHandlerPriv;
109
110 static guint signals[LAST_SIGNAL] = { 0 };
111
112 static gboolean do_hash_job_incoming (GIOSchedulerJob *job,
113     GCancellable *cancellable, gpointer user_data);
114
115 /* GObject implementations */
116 static void
117 do_get_property (GObject *object,
118                  guint property_id,
119                  GValue *value,
120                  GParamSpec *pspec)
121 {
122   EmpathyFTHandlerPriv *priv = GET_PRIV (object);
123
124   switch (property_id)
125     {
126       case PROP_CONTACT:
127         g_value_set_object (value, priv->contact);
128         break;
129       case PROP_G_FILE:
130         g_value_set_object (value, priv->gfile);
131         break;
132       case PROP_TP_FILE:
133         g_value_set_object (value, priv->tpfile);
134         break;
135       case PROP_USE_HASH:
136         g_value_set_boolean (value, priv->use_hash);
137         break;
138       default:
139         G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
140     }
141 }
142
143 static void
144 do_set_property (GObject *object,
145                  guint property_id, 
146                  const GValue *value,
147                  GParamSpec *pspec)
148 {
149   EmpathyFTHandlerPriv *priv = GET_PRIV (object);
150
151   switch (property_id)
152     {
153       case PROP_CONTACT:
154         priv->contact = g_value_dup_object (value);
155         break;
156       case PROP_G_FILE:
157         priv->gfile = g_value_dup_object (value);
158         break;
159       case PROP_TP_FILE:
160         priv->tpfile = g_value_dup_object (value);
161         break;
162       case PROP_USE_HASH:
163         priv->use_hash = g_value_get_boolean (value);
164         break;
165       default:
166         G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
167     }
168 }
169
170 static void
171 do_dispose (GObject *object)
172 {
173   EmpathyFTHandlerPriv *priv = GET_PRIV (object);
174
175   if (priv->dispose_run)
176     return;
177
178   priv->dispose_run = TRUE;
179
180   if (priv->contact) {
181     g_object_unref (priv->contact);
182     priv->contact = NULL;
183   }
184
185   if (priv->gfile) {
186     g_object_unref (priv->gfile);
187     priv->gfile = NULL;
188   }
189
190   if (priv->tpfile) {
191     empathy_tp_file_close (priv->tpfile);
192     g_object_unref (priv->tpfile);
193     priv->tpfile = NULL;
194   }
195
196   if (priv->cancellable) {
197     g_object_unref (priv->cancellable);
198     priv->cancellable = NULL;
199   }
200
201   if (priv->request != NULL)
202     {
203       g_hash_table_unref (priv->request);
204       priv->request = NULL;
205     }
206   
207   G_OBJECT_CLASS (empathy_ft_handler_parent_class)->dispose (object);
208 }
209
210 static void
211 do_finalize (GObject *object)
212 {
213   EmpathyFTHandlerPriv *priv = GET_PRIV (object);
214
215   DEBUG ("%p", object);
216
217   g_free (priv->content_type);
218   priv->content_type = NULL;
219
220   g_free (priv->filename);
221   priv->filename = NULL;
222
223   g_free (priv->description);
224   priv->description = NULL;
225
226   g_free (priv->content_hash);
227   priv->content_hash = NULL;
228
229   G_OBJECT_CLASS (empathy_ft_handler_parent_class)->finalize (object);
230 }
231
232 static void
233 empathy_ft_handler_class_init (EmpathyFTHandlerClass *klass)
234 {
235   GObjectClass *object_class = G_OBJECT_CLASS (klass);
236   GParamSpec *param_spec;
237
238   g_type_class_add_private (klass, sizeof (EmpathyFTHandlerPriv));
239
240   object_class->get_property = do_get_property;
241   object_class->set_property = do_set_property;
242   object_class->dispose = do_dispose;
243   object_class->finalize = do_finalize;
244
245   /* properties */
246   param_spec = g_param_spec_object ("contact",
247     "contact", "The remote contact",
248     EMPATHY_TYPE_CONTACT,
249     G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS | G_PARAM_CONSTRUCT_ONLY);
250   g_object_class_install_property (object_class, PROP_CONTACT, param_spec);
251
252   param_spec = g_param_spec_object ("gfile",
253     "gfile", "The GFile we're handling",
254     G_TYPE_FILE,
255     G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS);
256   g_object_class_install_property (object_class, PROP_G_FILE, param_spec);
257
258   param_spec = g_param_spec_object ("tp-file",
259     "tp-file", "The file's channel wrapper",
260     EMPATHY_TYPE_TP_FILE,
261     G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS | G_PARAM_CONSTRUCT_ONLY);
262   g_object_class_install_property (object_class, PROP_TP_FILE, param_spec);
263
264   param_spec = g_param_spec_boolean ("use-hash",
265     "use-hash", "Whether we should use checksum when sending or receiving",
266     FALSE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS);
267   g_object_class_install_property (object_class, PROP_USE_HASH, param_spec);
268
269   /* signals */
270   signals[TRANSFER_STARTED] =
271     g_signal_new ("transfer-started", G_TYPE_FROM_CLASS (klass),
272         G_SIGNAL_RUN_LAST, 0, NULL, NULL,
273         g_cclosure_marshal_VOID__OBJECT,
274         G_TYPE_NONE,
275         1, EMPATHY_TYPE_TP_FILE);
276
277   signals[TRANSFER_DONE] =
278     g_signal_new ("transfer-done", G_TYPE_FROM_CLASS (klass),
279         G_SIGNAL_RUN_LAST, 0, NULL, NULL,
280         g_cclosure_marshal_VOID__OBJECT,
281         G_TYPE_NONE,
282         1, EMPATHY_TYPE_TP_FILE);
283
284   signals[TRANSFER_ERROR] =
285     g_signal_new ("transfer-error", G_TYPE_FROM_CLASS (klass),
286         G_SIGNAL_RUN_LAST, 0, NULL, NULL,
287         g_cclosure_marshal_VOID__POINTER,
288         G_TYPE_NONE,
289         1, G_TYPE_POINTER);
290
291   signals[TRANSFER_PROGRESS] =
292     g_signal_new ("transfer-progress", G_TYPE_FROM_CLASS (klass),
293         G_SIGNAL_RUN_LAST, 0, NULL, NULL,
294         _empathy_marshal_VOID__UINT64_UINT64_UINT_DOUBLE,
295         G_TYPE_NONE,
296         4, G_TYPE_UINT64, G_TYPE_UINT64, G_TYPE_UINT, G_TYPE_DOUBLE);
297
298   signals[HASHING_STARTED] =
299     g_signal_new ("hashing-started", G_TYPE_FROM_CLASS (klass),
300         G_SIGNAL_RUN_LAST, 0, NULL, NULL,
301         g_cclosure_marshal_VOID__VOID,
302         G_TYPE_NONE, 0);
303
304   signals[HASHING_PROGRESS] =
305     g_signal_new ("hashing-progress", G_TYPE_FROM_CLASS (klass),
306         G_SIGNAL_RUN_LAST, 0, NULL, NULL,
307         _empathy_marshal_VOID__UINT64_UINT64,
308         G_TYPE_NONE,
309         2, G_TYPE_UINT64, G_TYPE_UINT64);
310
311   signals[HASHING_DONE] =
312     g_signal_new ("hashing-done", G_TYPE_FROM_CLASS (klass),
313         G_SIGNAL_RUN_LAST, 0, NULL, NULL,
314         g_cclosure_marshal_VOID__VOID,
315         G_TYPE_NONE, 0);
316 }
317
318 static void
319 empathy_ft_handler_init (EmpathyFTHandler *self)
320 {
321   EmpathyFTHandlerPriv *priv = G_TYPE_INSTANCE_GET_PRIVATE (self,
322     EMPATHY_TYPE_FT_HANDLER, EmpathyFTHandlerPriv);
323
324   self->priv = priv;
325   priv->cancellable = g_cancellable_new ();
326 }
327
328 /* private functions */
329
330 static void
331 hash_data_free (HashingData *data)
332 {
333   if (data->buffer != NULL)
334     {
335       g_free (data->buffer);
336       data->buffer = NULL;
337     }
338
339   if (data->stream != NULL)
340     {
341       g_object_unref (data->stream);
342       data->stream = NULL;
343     }
344
345   if (data->checksum != NULL)
346     {
347       g_checksum_free (data->checksum);
348       data->checksum = NULL;
349     }
350
351   if (data->error != NULL)
352     {
353       g_error_free (data->error);
354       data->error = NULL;
355     }
356   if (data->handler != NULL)
357     {
358       g_object_unref (data->handler);
359       data->handler = NULL;
360     }
361
362   g_slice_free (HashingData, data);
363 }
364
365 static GChecksumType
366 tp_file_hash_to_g_checksum (TpFileHashType type)
367 {
368   GChecksumType retval;
369
370   switch (type)
371     {
372       case TP_FILE_HASH_TYPE_MD5:
373         retval = G_CHECKSUM_MD5;
374         break;
375       case TP_FILE_HASH_TYPE_SHA1:
376         retval = G_CHECKSUM_SHA1;
377         break;
378       case TP_FILE_HASH_TYPE_SHA256:
379         retval = G_CHECKSUM_SHA256;
380         break;
381       default:
382         g_assert_not_reached ();
383         break;
384     }
385
386   return retval;
387 }
388
389 static void
390 check_hash_incoming (EmpathyFTHandler *handler)
391 {
392   HashingData *hash_data;
393   EmpathyFTHandlerPriv *priv = GET_PRIV (handler);
394
395   if (!EMP_STR_EMPTY (priv->content_hash))
396     {
397       hash_data = g_slice_new0 (HashingData);
398       hash_data->total_bytes = priv->total_bytes;
399       hash_data->handler = g_object_ref (handler);
400       hash_data->checksum = g_checksum_new
401         (tp_file_hash_to_g_checksum (priv->content_hash_type));
402
403       g_signal_emit (handler, signals[HASHING_STARTED], 0);
404
405       g_io_scheduler_push_job (do_hash_job_incoming, hash_data, NULL,
406                                G_PRIORITY_DEFAULT, priv->cancellable);
407     }
408 }
409
410 static void
411 emit_error_signal (EmpathyFTHandler *handler,
412                    const GError *error)
413 {
414   EmpathyFTHandlerPriv *priv = GET_PRIV (handler);
415
416   if (!g_cancellable_is_cancelled (priv->cancellable))
417     g_cancellable_cancel (priv->cancellable);
418
419   g_signal_emit (handler, signals[TRANSFER_ERROR], 0, error);
420 }
421
422 static void
423 ft_transfer_operation_callback (EmpathyTpFile *tp_file,
424                                 const GError *error,
425                                 gpointer user_data)
426 {
427   EmpathyFTHandler *handler = user_data;
428   EmpathyFTHandlerPriv *priv = GET_PRIV (handler);
429
430   DEBUG ("Transfer operation callback, error %p", error);
431
432   if (error != NULL)
433     {
434       emit_error_signal (handler, error);
435     }
436   else 
437     {
438       priv->is_completed = TRUE;
439       g_signal_emit (handler, signals[TRANSFER_DONE], 0, tp_file);
440
441       empathy_tp_file_close (tp_file);
442
443       if (empathy_ft_handler_is_incoming (handler) && priv->use_hash)
444         {
445           check_hash_incoming (handler);
446         }
447     }
448 }
449
450 static void
451 update_remaining_time_and_speed (EmpathyFTHandler *handler,
452                                  guint64 transferred_bytes)
453 {
454   EmpathyFTHandlerPriv *priv = GET_PRIV (handler);
455   time_t elapsed_time, current_time;
456   guint64 transferred, last_transferred_bytes;
457   gdouble speed;
458   gint remaining_time;
459
460   last_transferred_bytes = priv->transferred_bytes;
461   priv->transferred_bytes = transferred_bytes;
462
463   current_time = empathy_time_get_current ();
464   elapsed_time = current_time - priv->last_update_time;
465
466   if (elapsed_time >= 1)
467     {
468       transferred = transferred_bytes - last_transferred_bytes;
469       speed = (gdouble) transferred / (gdouble) elapsed_time;
470       remaining_time = (priv->total_bytes - transferred) / speed;
471       priv->speed = speed;
472       priv->remaining_time = remaining_time;
473       priv->last_update_time = current_time;
474     }
475 }
476
477 static void
478 ft_transfer_progress_callback (EmpathyTpFile *tp_file,
479                                guint64 transferred_bytes,
480                                gpointer user_data)
481 {
482   EmpathyFTHandler *handler = user_data;
483   EmpathyFTHandlerPriv *priv = GET_PRIV (handler);
484
485   if (empathy_ft_handler_is_cancelled (handler))
486     return;
487
488   if (transferred_bytes == 0)
489     {
490       priv->last_update_time = empathy_time_get_current ();
491       g_signal_emit (handler, signals[TRANSFER_STARTED], 0, tp_file);
492     }
493
494   if (priv->transferred_bytes != transferred_bytes)
495     {
496       update_remaining_time_and_speed (handler, transferred_bytes);
497
498       g_signal_emit (handler, signals[TRANSFER_PROGRESS], 0,
499           transferred_bytes, priv->total_bytes, priv->remaining_time,
500           priv->speed);
501     }
502 }
503
504 static void
505 ft_handler_create_channel_cb (EmpathyDispatchOperation *operation,
506                               const GError *error,
507                               gpointer user_data)
508 {
509   EmpathyFTHandler *handler = user_data;
510   EmpathyFTHandlerPriv *priv = GET_PRIV (handler);
511   GError *my_error = (GError *) error;
512
513   DEBUG ("Dispatcher create channel CB");
514
515   if (my_error == NULL)
516     {
517       g_cancellable_set_error_if_cancelled (priv->cancellable, &my_error);
518     }
519
520   if (my_error != NULL)
521     {
522       emit_error_signal (handler, my_error);
523
524       if (my_error != error)
525         g_clear_error (&my_error);
526
527       return;
528     }
529
530   priv->tpfile = g_object_ref
531       (empathy_dispatch_operation_get_channel_wrapper (operation));
532
533   empathy_tp_file_offer (priv->tpfile, priv->gfile, priv->cancellable,
534       ft_transfer_progress_callback, handler,
535       ft_transfer_operation_callback, handler);
536
537   empathy_dispatch_operation_claim (operation);
538 }
539
540 static void
541 ft_handler_push_to_dispatcher (EmpathyFTHandler *handler)
542 {
543   EmpathyDispatcher *dispatcher;
544   TpConnection *connection;
545   EmpathyFTHandlerPriv *priv = GET_PRIV (handler);
546
547   DEBUG ("Pushing request to the dispatcher");
548
549   dispatcher = empathy_dispatcher_dup_singleton ();
550   connection = empathy_contact_get_connection (priv->contact);
551
552   /* I want to own a reference to the request, and destroy it later */
553   empathy_dispatcher_create_channel (dispatcher, connection,
554       g_hash_table_ref (priv->request), ft_handler_create_channel_cb, handler);
555
556   g_object_unref (dispatcher);
557 }
558
559 static gboolean
560 ft_handler_check_if_allowed (EmpathyFTHandler *handler)
561 {
562   EmpathyDispatcher *dispatcher;
563   EmpathyFTHandlerPriv *priv = GET_PRIV (handler);
564   TpConnection *connection;
565   GStrv allowed;
566   gboolean res = TRUE;
567
568   dispatcher = empathy_dispatcher_dup_singleton ();
569   connection = empathy_contact_get_connection (priv->contact);
570
571   allowed = empathy_dispatcher_find_channel_class (dispatcher, connection,
572       TP_IFACE_CHANNEL_TYPE_FILE_TRANSFER, TP_HANDLE_TYPE_CONTACT);
573
574   if (!tp_strv_contains ((const gchar * const *) allowed,
575       TP_IFACE_CHANNEL ".TargetHandle"))
576     res = FALSE;
577
578   g_object_unref (dispatcher);
579
580   return res;
581 }
582
583 static void
584 ft_handler_populate_outgoing_request (EmpathyFTHandler *handler)
585 {
586   guint contact_handle;
587   GHashTable *request;
588   GValue *value;
589   EmpathyFTHandlerPriv *priv = GET_PRIV (handler);
590
591   request = priv->request = g_hash_table_new_full (g_str_hash, g_str_equal,
592             NULL, (GDestroyNotify) tp_g_value_slice_free);
593
594   contact_handle = empathy_contact_get_handle (priv->contact);
595
596   /* org.freedesktop.Telepathy.Channel.ChannelType */
597   value = tp_g_value_slice_new (G_TYPE_STRING);
598   g_value_set_string (value, TP_IFACE_CHANNEL_TYPE_FILE_TRANSFER);
599   g_hash_table_insert (request, TP_IFACE_CHANNEL ".ChannelType", value);
600
601   /* org.freedesktop.Telepathy.Channel.TargetHandleType */
602   value = tp_g_value_slice_new (G_TYPE_UINT);
603   g_value_set_uint (value, TP_HANDLE_TYPE_CONTACT);
604   g_hash_table_insert (request, TP_IFACE_CHANNEL ".TargetHandleType", value);
605
606   /* org.freedesktop.Telepathy.Channel.TargetHandle */
607   value = tp_g_value_slice_new (G_TYPE_UINT);
608   g_value_set_uint (value, contact_handle);
609   g_hash_table_insert (request, TP_IFACE_CHANNEL ".TargetHandle", value);
610
611   /* org.freedesktop.Telepathy.Channel.Type.FileTransfer.ContentType */
612   value = tp_g_value_slice_new (G_TYPE_STRING);
613   g_value_set_string (value, priv->content_type);
614   g_hash_table_insert (request,
615       TP_IFACE_CHANNEL_TYPE_FILE_TRANSFER ".ContentType", value);
616
617   /* org.freedesktop.Telepathy.Channel.Type.FileTransfer.Filename */
618   value = tp_g_value_slice_new (G_TYPE_STRING);
619   g_value_set_string (value, priv->filename);
620   g_hash_table_insert (request,
621       TP_IFACE_CHANNEL_TYPE_FILE_TRANSFER ".Filename", value);
622
623   /* org.freedesktop.Telepathy.Channel.Type.FileTransfer.Size */
624   value = tp_g_value_slice_new (G_TYPE_UINT64);
625   g_value_set_uint64 (value, (guint64) priv->total_bytes);
626   g_hash_table_insert (request,
627       TP_IFACE_CHANNEL_TYPE_FILE_TRANSFER ".Size", value);
628
629   /* org.freedesktop.Telepathy.Channel.Type.FileTransfer.Date */
630   value = tp_g_value_slice_new (G_TYPE_UINT64);
631   g_value_set_uint64 (value, (guint64) priv->mtime);
632   g_hash_table_insert (request,
633       TP_IFACE_CHANNEL_TYPE_FILE_TRANSFER ".Date", value);
634 }
635
636 static gboolean
637 hash_job_done (gpointer user_data)
638 {
639   HashingData *hash_data = user_data;
640   EmpathyFTHandler *handler = hash_data->handler;
641   EmpathyFTHandlerPriv *priv;
642   GError *error = NULL;
643   GValue *value;
644
645   DEBUG ("Closing stream after hashing.");
646
647   priv = GET_PRIV (handler);
648
649   if (hash_data->error != NULL)
650     {
651       error = hash_data->error;
652       goto cleanup;
653     }
654
655   DEBUG ("Got file hash %s", g_checksum_get_string (hash_data->checksum));
656
657   if (empathy_ft_handler_is_incoming (handler))
658     {
659       if (g_strcmp0 (g_checksum_get_string (hash_data->checksum),
660                      priv->content_hash))
661         {
662           DEBUG ("Hash mismatch when checking incoming handler: "
663                  "received %s, calculated %s", priv->content_hash,
664                  g_checksum_get_string (hash_data->checksum));
665
666           error = g_error_new_literal (EMPATHY_FT_ERROR_QUARK,
667               EMPATHY_FT_ERROR_HASH_MISMATCH,
668               _("The hash of the received file and the sent one do not match"));
669           goto cleanup;
670         }
671       else
672         {
673           DEBUG ("Hash verification matched, received %s, calculated %s",
674                  priv->content_hash,
675                  g_checksum_get_string (hash_data->checksum));
676         }
677     }
678   else
679     {
680       /* set the checksum in the request...
681        * org.freedesktop.Telepathy.Channel.Type.FileTransfer.ContentHash
682        */
683       value = tp_g_value_slice_new (G_TYPE_STRING);
684       g_value_set_string (value, g_checksum_get_string (hash_data->checksum));
685       g_hash_table_insert (priv->request,
686           TP_IFACE_CHANNEL_TYPE_FILE_TRANSFER ".ContentHash", value);      
687     }
688
689 cleanup:
690
691   if (error != NULL)
692     {
693       emit_error_signal (handler, error);
694       g_clear_error (&error);
695     }
696   else
697     {
698       g_signal_emit (handler, signals[HASHING_DONE], 0);
699
700       if (!empathy_ft_handler_is_incoming (handler))
701         /* the request is complete now, push it to the dispatcher */
702         ft_handler_push_to_dispatcher (handler);
703     }
704
705   hash_data_free (hash_data);
706
707   return FALSE;
708 }
709
710 static gboolean
711 emit_hashing_progress (gpointer user_data)
712 {
713   HashingData *hash_data = user_data;
714
715   g_signal_emit (hash_data->handler, signals[HASHING_PROGRESS], 0,
716       (guint64) hash_data->total_read, (guint64) hash_data->total_bytes);
717
718   return FALSE;
719 }
720
721 static gboolean
722 do_hash_job (GIOSchedulerJob *job,
723              GCancellable *cancellable,
724              gpointer user_data)
725 {
726   HashingData *hash_data = user_data;
727   gssize bytes_read;
728   EmpathyFTHandlerPriv *priv;
729   GError *error = NULL;
730
731   priv = GET_PRIV (hash_data->handler);
732
733 again:
734   if (hash_data->buffer == NULL)
735     hash_data->buffer = g_malloc0 (BUFFER_SIZE);
736
737   bytes_read = g_input_stream_read (hash_data->stream, hash_data->buffer,
738                                     BUFFER_SIZE, cancellable, &error);
739   if (error != NULL)
740     goto out;
741
742   hash_data->total_read += bytes_read;
743
744   /* we now have the chunk */
745   if (bytes_read > 0)
746     {
747       g_checksum_update (hash_data->checksum, hash_data->buffer, bytes_read);
748       g_io_scheduler_job_send_to_mainloop_async (job, emit_hashing_progress,
749           hash_data, NULL);
750
751       g_free (hash_data->buffer);
752       hash_data->buffer = NULL;
753
754       goto again;
755     }
756   else
757   {
758     g_input_stream_close (hash_data->stream, cancellable, &error);
759   }
760
761 out:
762   if (error)
763     hash_data->error = error;
764
765   g_io_scheduler_job_send_to_mainloop_async (job, hash_job_done,
766       hash_data, NULL);
767
768   return FALSE;
769 }
770
771 static gboolean
772 do_hash_job_incoming (GIOSchedulerJob *job,
773                       GCancellable *cancellable,
774                       gpointer user_data)
775 {
776   HashingData *hash_data = user_data;
777   EmpathyFTHandler *handler = hash_data->handler;
778   EmpathyFTHandlerPriv *priv = GET_PRIV (handler);
779   GError *error = NULL;
780
781   DEBUG ("checking integrity for incoming handler");
782
783   /* need to get the stream first */
784   hash_data->stream =
785     G_INPUT_STREAM (g_file_read (priv->gfile, cancellable, &error));
786
787   if (error)
788     {
789       hash_data->error = error;
790       g_io_scheduler_job_send_to_mainloop_async (job, hash_job_done,
791           hash_data, NULL);
792       return FALSE;
793     }
794
795   return do_hash_job (job, cancellable, user_data);
796 }
797
798 static void
799 ft_handler_read_async_cb (GObject *source,
800                           GAsyncResult *res,
801                           gpointer user_data)
802 {
803   GFileInputStream *stream;
804   GError *error = NULL;
805   HashingData *hash_data;
806   GValue *value;
807   EmpathyFTHandler *handler = user_data;
808   EmpathyFTHandlerPriv *priv = GET_PRIV (handler);
809
810   DEBUG ("GFile read async CB.");
811
812   stream = g_file_read_finish (priv->gfile, res, &error);
813   if (error != NULL)
814     {
815       emit_error_signal (handler, error);
816       g_clear_error (&error);
817
818       return;
819     }
820
821   hash_data = g_slice_new0 (HashingData);
822   hash_data->stream = G_INPUT_STREAM (stream);
823   hash_data->total_bytes = priv->total_bytes;
824   hash_data->handler = g_object_ref (handler);
825   /* FIXME: should look at the CM capabilities before setting the
826    * checksum type?
827    */
828   hash_data->checksum = g_checksum_new (G_CHECKSUM_MD5);
829
830   /* org.freedesktop.Telepathy.Channel.Type.FileTransfer.ContentHashType */
831   value = tp_g_value_slice_new (G_TYPE_UINT);
832   g_value_set_uint (value, TP_FILE_HASH_TYPE_MD5);
833   g_hash_table_insert (priv->request,
834       TP_IFACE_CHANNEL_TYPE_FILE_TRANSFER ".ContentHashType", value);
835
836   g_signal_emit (handler, signals[HASHING_STARTED], 0);
837
838   g_io_scheduler_push_job (do_hash_job, hash_data, NULL,
839       G_PRIORITY_DEFAULT, priv->cancellable);
840 }
841
842 static void
843 ft_handler_complete_request (EmpathyFTHandler *handler)
844
845   EmpathyFTHandlerPriv *priv = GET_PRIV (handler);
846   GError *myerr = NULL;
847
848   /* check if FT is allowed before firing up the I/O machinery */
849   if (!ft_handler_check_if_allowed (handler))
850     {
851       g_set_error_literal (&myerr, EMPATHY_FT_ERROR_QUARK,
852           EMPATHY_FT_ERROR_NOT_SUPPORTED,
853           _("File transfer not supported by remote contact"));
854
855       emit_error_signal (handler, myerr);
856       g_clear_error (&myerr);
857
858       return;
859     }
860
861   /* populate the request table with all the known properties */
862   ft_handler_populate_outgoing_request (handler);
863
864   if (priv->use_hash)
865     /* start hashing the file */
866     g_file_read_async (priv->gfile, G_PRIORITY_DEFAULT,
867         priv->cancellable, ft_handler_read_async_cb, handler);
868   else
869     /* push directly the handler to the dispatcher */
870     ft_handler_push_to_dispatcher (handler);
871 }
872
873 static void
874 callbacks_data_free (gpointer user_data)
875 {
876   CallbacksData *data = user_data;
877
878   if (data->handler)
879     g_object_unref (data->handler);
880
881   g_slice_free (CallbacksData, data);
882 }
883
884 static void
885 ft_handler_gfile_ready_cb (GObject *source,
886                            GAsyncResult *res,
887                            CallbacksData *cb_data)
888 {
889   GFileInfo *info;
890   GError *error = NULL;
891   GTimeVal mtime;
892   EmpathyFTHandlerPriv *priv = GET_PRIV (cb_data->handler);
893
894   DEBUG ("Got GFileInfo.");
895
896   info = g_file_query_info_finish (priv->gfile, res, &error);
897
898   if (error != NULL)
899     goto out;
900
901   priv->content_type = g_strdup (g_file_info_get_content_type (info));
902   priv->filename = g_strdup (g_file_info_get_display_name (info));
903   priv->total_bytes = g_file_info_get_size (info);
904   g_file_info_get_modification_time (info, &mtime);
905   priv->mtime = mtime.tv_sec;
906   priv->transferred_bytes = 0;
907   priv->description = NULL;
908
909   g_object_unref (info);
910
911 out:
912   if (error == NULL)
913     {
914       cb_data->callback (cb_data->handler, NULL, cb_data->user_data);
915     }
916   else
917     {
918       if (!g_cancellable_is_cancelled (priv->cancellable))
919         g_cancellable_cancel (priv->cancellable);
920
921       cb_data->callback (NULL, error, cb_data->user_data);
922       g_error_free (error);
923       g_object_unref (cb_data->handler);
924     }
925
926   callbacks_data_free (cb_data);
927 }
928
929 static void 
930 contact_factory_contact_cb (EmpathyTpContactFactory *factory,
931                             EmpathyContact *contact,
932                             const GError *error,
933                             gpointer user_data,
934                             GObject *weak_object)
935 {
936   CallbacksData *cb_data = user_data;
937   EmpathyFTHandler *handler = EMPATHY_FT_HANDLER (weak_object);
938   EmpathyFTHandlerPriv *priv = GET_PRIV (handler);
939
940   if (error != NULL)
941     {
942       if (!g_cancellable_is_cancelled (priv->cancellable))
943         g_cancellable_cancel (priv->cancellable);
944
945       cb_data->callback (NULL, (GError *) error, cb_data->user_data);
946       g_object_unref (handler);
947       return;
948     }
949
950   priv->contact = contact;
951
952   cb_data->callback (handler, NULL, cb_data->user_data);
953 }
954
955 static void
956 channel_get_all_properties_cb (TpProxy *proxy,
957                                GHashTable *properties,
958                                const GError *error,
959                                gpointer user_data,
960                                GObject *weak_object)
961 {
962   CallbacksData *cb_data = user_data;
963   EmpathyFTHandler *handler = EMPATHY_FT_HANDLER (weak_object);
964   EmpathyFTHandlerPriv *priv = GET_PRIV (handler);
965   EmpathyTpContactFactory *c_factory;
966   TpHandle c_handle;
967
968   if (error != NULL)
969     {
970       if (!g_cancellable_is_cancelled (priv->cancellable))
971         g_cancellable_cancel (priv->cancellable);
972
973       cb_data->callback (NULL, (GError *) error, cb_data->user_data);
974       g_object_unref (handler);
975       return;
976     }
977
978   priv->total_bytes = g_value_get_uint64 (
979       g_hash_table_lookup (properties, "Size"));
980
981   priv->transferred_bytes = g_value_get_uint64 (
982       g_hash_table_lookup (properties, "TransferredBytes"));
983
984   priv->filename = g_value_dup_string (
985       g_hash_table_lookup (properties, "Filename"));
986
987   priv->content_hash = g_value_dup_string (
988       g_hash_table_lookup (properties, "ContentHash"));
989
990   priv->content_hash_type = g_value_get_uint (
991       g_hash_table_lookup (properties, "ContentHashType"));
992
993   priv->content_type = g_value_dup_string (
994       g_hash_table_lookup (properties, "ContentType"));
995
996   priv->description = g_value_dup_string (
997       g_hash_table_lookup (properties, "Description"));
998
999   c_factory = empathy_tp_contact_factory_dup_singleton
1000       (tp_channel_borrow_connection (TP_CHANNEL (proxy)));
1001   c_handle = tp_channel_get_handle (TP_CHANNEL (proxy), NULL);
1002   empathy_tp_contact_factory_get_from_handle (c_factory, c_handle,
1003       contact_factory_contact_cb, cb_data, callbacks_data_free,
1004       G_OBJECT (handler));
1005 }
1006
1007 /* public methods */
1008
1009 void
1010 empathy_ft_handler_new_outgoing (EmpathyContact *contact,
1011                                  GFile *source,
1012                                  gboolean use_hash,
1013                                  EmpathyFTHandlerReadyCallback callback,
1014                                  gpointer user_data)
1015 {
1016   EmpathyFTHandler *handler;
1017   CallbacksData *data;
1018   EmpathyFTHandlerPriv *priv;
1019
1020   DEBUG ("New handler outgoing, use hash %s",
1021          use_hash ? "True" : "False");
1022
1023   g_return_if_fail (EMPATHY_IS_CONTACT (contact));
1024   g_return_if_fail (G_IS_FILE (source));
1025
1026   handler = g_object_new (EMPATHY_TYPE_FT_HANDLER,
1027       "contact", contact, "gfile", source, "use-hash", use_hash, NULL);
1028
1029   priv = GET_PRIV (handler);
1030
1031   data = g_slice_new0 (CallbacksData);
1032   data->callback = callback;
1033   data->user_data = user_data;
1034   data->handler = g_object_ref (handler);
1035
1036   /* start collecting info about the file */
1037   g_file_query_info_async (priv->gfile,
1038       G_FILE_ATTRIBUTE_STANDARD_DISPLAY_NAME ","
1039       G_FILE_ATTRIBUTE_STANDARD_SIZE ","
1040       G_FILE_ATTRIBUTE_STANDARD_CONTENT_TYPE ","
1041       G_FILE_ATTRIBUTE_TIME_MODIFIED,
1042       G_FILE_QUERY_INFO_NONE, G_PRIORITY_DEFAULT,
1043       NULL, (GAsyncReadyCallback) ft_handler_gfile_ready_cb, data);
1044 }
1045
1046 void
1047 empathy_ft_handler_new_incoming (EmpathyTpFile *tp_file,
1048                                  EmpathyFTHandlerReadyCallback callback,
1049                                  gpointer user_data)
1050 {
1051   EmpathyFTHandler *handler;
1052   TpChannel *channel;
1053   CallbacksData *data;
1054
1055   g_return_if_fail (EMPATHY_IS_TP_FILE (tp_file));
1056
1057   handler = g_object_new (EMPATHY_TYPE_FT_HANDLER,
1058       "tp-file", tp_file, NULL);
1059
1060   g_object_get (tp_file, "channel", &channel, NULL);
1061
1062   data = g_slice_new0 (CallbacksData);
1063   data->callback = callback;
1064   data->user_data = user_data;
1065   data->handler = g_object_ref (handler);
1066
1067   tp_cli_dbus_properties_call_get_all (channel,
1068       -1, TP_IFACE_CHANNEL_TYPE_FILE_TRANSFER,
1069       channel_get_all_properties_cb, data, NULL, G_OBJECT (handler));
1070 }
1071
1072 void
1073 empathy_ft_handler_start_transfer (EmpathyFTHandler *handler)
1074 {
1075   EmpathyFTHandlerPriv *priv;
1076
1077   g_return_if_fail (EMPATHY_IS_FT_HANDLER (handler));
1078
1079   priv = GET_PRIV (handler);
1080
1081   if (priv->tpfile == NULL)
1082     {
1083       ft_handler_complete_request (handler);
1084     }
1085   else
1086     {
1087       /* TODO: add support for resume. */
1088       empathy_tp_file_accept (priv->tpfile, 0, priv->gfile, priv->cancellable,
1089           ft_transfer_progress_callback, handler,
1090           ft_transfer_operation_callback, handler);
1091     }
1092 }
1093
1094 void
1095 empathy_ft_handler_cancel_transfer (EmpathyFTHandler *handler)
1096 {
1097   EmpathyFTHandlerPriv *priv;
1098
1099   g_return_if_fail (EMPATHY_IS_FT_HANDLER (handler));
1100
1101   priv = GET_PRIV (handler);
1102
1103   /* if we don't have an EmpathyTpFile, we are hashing, so
1104    * we can just cancel the GCancellable to stop it.
1105    */
1106   if (priv->tpfile == NULL)
1107     g_cancellable_cancel (priv->cancellable);
1108   else
1109     empathy_tp_file_cancel (priv->tpfile);
1110 }
1111
1112 void
1113 empathy_ft_handler_incoming_set_destination (EmpathyFTHandler *handler,
1114                                              GFile *destination,
1115                                              gboolean use_hash)
1116 {
1117   DEBUG ("Set incoming destination, use hash %s",
1118          use_hash ? "True" : "False");
1119
1120   g_return_if_fail (EMPATHY_IS_FT_HANDLER (handler));
1121   g_return_if_fail (G_IS_FILE (destination));
1122
1123   g_object_set (handler, "gfile", destination,
1124       "use-hash", use_hash, NULL);
1125 }
1126
1127 const char *
1128 empathy_ft_handler_get_filename (EmpathyFTHandler *handler)
1129 {
1130   EmpathyFTHandlerPriv *priv;
1131
1132   g_return_val_if_fail (EMPATHY_IS_FT_HANDLER (handler), NULL);
1133
1134   priv = GET_PRIV (handler);
1135
1136   return priv->filename;
1137 }
1138
1139 const char *
1140 empathy_ft_handler_get_content_type (EmpathyFTHandler *handler)
1141 {
1142   EmpathyFTHandlerPriv *priv;
1143
1144   g_return_val_if_fail (EMPATHY_IS_FT_HANDLER (handler), NULL);
1145
1146   priv = GET_PRIV (handler);
1147
1148   return priv->content_type;
1149 }
1150
1151 EmpathyContact *
1152 empathy_ft_handler_get_contact (EmpathyFTHandler *handler)
1153 {
1154   EmpathyFTHandlerPriv *priv;
1155
1156   g_return_val_if_fail (EMPATHY_IS_FT_HANDLER (handler), NULL);
1157
1158   priv = GET_PRIV (handler);
1159
1160   return priv->contact;
1161 }
1162
1163 GFile *
1164 empathy_ft_handler_get_gfile (EmpathyFTHandler *handler)
1165 {
1166   EmpathyFTHandlerPriv *priv;
1167
1168   g_return_val_if_fail (EMPATHY_IS_FT_HANDLER (handler), NULL);
1169
1170   priv = GET_PRIV (handler);
1171
1172   return priv->gfile;
1173 }
1174
1175 gboolean
1176 empathy_ft_handler_get_use_hash (EmpathyFTHandler *handler)
1177 {
1178   EmpathyFTHandlerPriv *priv;
1179
1180   g_return_val_if_fail (EMPATHY_IS_FT_HANDLER (handler), FALSE);
1181
1182   priv = GET_PRIV (handler);
1183
1184   return priv->use_hash;
1185 }
1186
1187 gboolean
1188 empathy_ft_handler_is_incoming (EmpathyFTHandler *handler)
1189 {
1190   EmpathyFTHandlerPriv *priv;
1191
1192   g_return_val_if_fail (EMPATHY_IS_FT_HANDLER (handler), FALSE);
1193
1194   priv = GET_PRIV (handler);
1195
1196   if (priv->tpfile == NULL)
1197     return FALSE;
1198
1199   return empathy_tp_file_is_incoming (priv->tpfile);  
1200 }
1201
1202 guint64
1203 empathy_ft_handler_get_transferred_bytes (EmpathyFTHandler *handler)
1204 {
1205   EmpathyFTHandlerPriv *priv;
1206
1207   g_return_val_if_fail (EMPATHY_IS_FT_HANDLER (handler), 0);
1208
1209   priv = GET_PRIV (handler);
1210
1211   return priv->transferred_bytes;
1212 }
1213
1214 guint64
1215 empathy_ft_handler_get_total_bytes (EmpathyFTHandler *handler)
1216 {
1217   EmpathyFTHandlerPriv *priv;
1218
1219   g_return_val_if_fail (EMPATHY_IS_FT_HANDLER (handler), 0);
1220
1221   priv = GET_PRIV (handler);
1222
1223   return priv->total_bytes;
1224 }
1225
1226 gboolean
1227 empathy_ft_handler_is_completed (EmpathyFTHandler *handler)
1228 {
1229   EmpathyFTHandlerPriv *priv;
1230
1231   g_return_val_if_fail (EMPATHY_IS_FT_HANDLER (handler), FALSE);
1232
1233   priv = GET_PRIV (handler);
1234
1235   return priv->is_completed;
1236 }
1237
1238 gboolean
1239 empathy_ft_handler_is_cancelled (EmpathyFTHandler *handler)
1240 {
1241   EmpathyFTHandlerPriv *priv;
1242
1243   g_return_val_if_fail (EMPATHY_IS_FT_HANDLER (handler), FALSE);
1244
1245   priv = GET_PRIV (handler);
1246
1247   return g_cancellable_is_cancelled (priv->cancellable);
1248 }