summaryrefslogtreecommitdiff
path: root/libgssdp/gssdp-resource-browser.c
blob: c02a4a7cca9be6052b447ad38b947e3f4b74965f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
/* 
 * Copyright (C) 2006, 2007, 2008 OpenedHand Ltd.
 *
 * Author: Jorn Baayen <jorn@openedhand.com>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301, USA.
 */

/**
 * SECTION:gssdp-resource-browser
 * @short_description: Class handling resource discovery.
 *
 * #GSSDPResourceBrowser handles resource discovery. After creating a browser
 * and activating it, the ::resource-available and ::resource-unavailable
 * signals will be emitted whenever the availability of a resource matching the
 * specified discovery target changes. A discovery request is sent out
 * automatically when activating the browser.
 */

#include <config.h>
#include <libsoup/soup.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>

#include "gssdp-resource-browser.h"
#include "gssdp-client-private.h"
#include "gssdp-protocol.h"
#include "gssdp-marshal.h"

#define RESCAN_TIMEOUT 5 /* 5 seconds */
#define MAX_DISCOVERY_MESSAGES 3
#define DISCOVERY_FREQUENCY    500 /* 500 ms */

G_DEFINE_TYPE (GSSDPResourceBrowser,
               gssdp_resource_browser,
               G_TYPE_OBJECT);

struct _GSSDPResourceBrowserPrivate {
        GSSDPClient *client;

        char        *target;
        GRegex      *target_regex;

        gushort      mx;

        gboolean     active;

        gulong       message_received_id;

        GHashTable  *resources;
                        
        GSource     *timeout_src;
        guint        num_discovery;
        guint        version;

        GSource     *refresh_cache_src;
        GHashTable  *fresh_resources;
};

enum {
        PROP_0,
        PROP_CLIENT,
        PROP_TARGET,
        PROP_MX,
        PROP_ACTIVE
};

enum {
        RESOURCE_AVAILABLE,
        RESOURCE_UNAVAILABLE,
        LAST_SIGNAL
};

static guint signals[LAST_SIGNAL];

typedef struct {
        GSSDPResourceBrowser *resource_browser;
        char                 *usn;
        GSource              *timeout_src;
        GList                *locations;
} Resource;

/* Function prototypes */
static void
gssdp_resource_browser_set_client (GSSDPResourceBrowser *resource_browser,
                                   GSSDPClient          *client);
static void
message_received_cb              (GSSDPClient          *client,
                                  const char           *from_ip,
                                  gushort               from_port,
                                  _GSSDPMessageType     type,
                                  SoupMessageHeaders   *headers,
                                  gpointer              user_data);
static void
resource_free                    (Resource             *data);
static void
clear_cache                      (GSSDPResourceBrowser *resource_browser);
static void
send_discovery_request            (GSSDPResourceBrowser *resource_browser);
static gboolean
discovery_timeout                (gpointer              data);
static void
start_discovery                  (GSSDPResourceBrowser *resource_browser);
static void
stop_discovery                   (GSSDPResourceBrowser *resource_browser);
static gboolean
refresh_cache                    (gpointer data);
static void
resource_unavailable             (GSSDPResourceBrowser *resource_browser,
                                  SoupMessageHeaders   *headers);

static void
gssdp_resource_browser_init (GSSDPResourceBrowser *resource_browser)
{
        resource_browser->priv = G_TYPE_INSTANCE_GET_PRIVATE
                                        (resource_browser,
                                         GSSDP_TYPE_RESOURCE_BROWSER,
                                         GSSDPResourceBrowserPrivate);

        resource_browser->priv->mx = SSDP_DEFAULT_MX;

        resource_browser->priv->resources =
                g_hash_table_new_full (g_str_hash,
                                       g_str_equal,
                                       g_free,
                                       (GFreeFunc) resource_free);
}

static void
gssdp_resource_browser_get_property (GObject    *object,
                                     guint       property_id,
                                     GValue     *value,
                                     GParamSpec *pspec)
{
        GSSDPResourceBrowser *resource_browser;

        resource_browser = GSSDP_RESOURCE_BROWSER (object);

        switch (property_id) {
        case PROP_CLIENT:
                g_value_set_object
                        (value,
                         gssdp_resource_browser_get_client (resource_browser));
                break;
        case PROP_TARGET:
                g_value_set_string
                        (value,
                         gssdp_resource_browser_get_target (resource_browser));
                break;
        case PROP_MX:
                g_value_set_uint
                        (value,
                         gssdp_resource_browser_get_mx (resource_browser));
                break;
        case PROP_ACTIVE:
                g_value_set_boolean
                        (value,
                         gssdp_resource_browser_get_active (resource_browser));
                break;
        default:
                G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
                break;
        }
}

static void
gssdp_resource_browser_set_property (GObject      *object,
                                     guint         property_id,
                                     const GValue *value,
                                     GParamSpec   *pspec)
{
        GSSDPResourceBrowser *resource_browser;

        resource_browser = GSSDP_RESOURCE_BROWSER (object);

        switch (property_id) {
        case PROP_CLIENT:
                gssdp_resource_browser_set_client (resource_browser,
                                                   g_value_get_object (value));
                break;
        case PROP_TARGET:
                gssdp_resource_browser_set_target (resource_browser,
                                                   g_value_get_string (value));
                break;
        case PROP_MX:
                gssdp_resource_browser_set_mx (resource_browser,
                                               g_value_get_uint (value));
                break;
        case PROP_ACTIVE:
                gssdp_resource_browser_set_active (resource_browser,
                                                   g_value_get_boolean (value));
                break;
        default:
                G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
                break;
        }
}

static void
gssdp_resource_browser_dispose (GObject *object)
{
        GSSDPResourceBrowser *resource_browser;

        resource_browser = GSSDP_RESOURCE_BROWSER (object);

        if (resource_browser->priv->client) {
                if (g_signal_handler_is_connected
                        (resource_browser->priv->client,
                         resource_browser->priv->message_received_id)) {
                        g_signal_handler_disconnect
                                (resource_browser->priv->client,
                                 resource_browser->priv->message_received_id);
                }

                stop_discovery (resource_browser);

                g_object_unref (resource_browser->priv->client);
                resource_browser->priv->client = NULL;
        }

        clear_cache (resource_browser);

        G_OBJECT_CLASS (gssdp_resource_browser_parent_class)->dispose (object);
}

static void
gssdp_resource_browser_finalize (GObject *object)
{
        GSSDPResourceBrowser *resource_browser;

        resource_browser = GSSDP_RESOURCE_BROWSER (object);

        if (resource_browser->priv->target_regex)
                g_regex_unref (resource_browser->priv->target_regex);

        g_free (resource_browser->priv->target);

        g_hash_table_destroy (resource_browser->priv->resources);

        G_OBJECT_CLASS (gssdp_resource_browser_parent_class)->finalize (object);
}

static void
gssdp_resource_browser_class_init (GSSDPResourceBrowserClass *klass)
{
        GObjectClass *object_class;

        object_class = G_OBJECT_CLASS (klass);

        object_class->set_property = gssdp_resource_browser_set_property;
        object_class->get_property = gssdp_resource_browser_get_property;
        object_class->dispose      = gssdp_resource_browser_dispose;
        object_class->finalize     = gssdp_resource_browser_finalize;

        g_type_class_add_private (klass, sizeof (GSSDPResourceBrowserPrivate));

        /**
         * GSSDPResourceBrowser:client:
         *
         * The #GSSDPClient to use.
         **/
        g_object_class_install_property
                (object_class,
                 PROP_CLIENT,
                 g_param_spec_object
                         ("client",
                          "Client",
                          "The associated client.",
                          GSSDP_TYPE_CLIENT,
                          G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY |
                          G_PARAM_STATIC_NAME | G_PARAM_STATIC_NICK |
                          G_PARAM_STATIC_BLURB));

        /**
         * GSSDPResourceBrowser:target:
         *
         * The discovery target.
         **/
        g_object_class_install_property
                (object_class,
                 PROP_TARGET,
                 g_param_spec_string
                         ("target",
                          "Target",
                          "The discovery target.",
                          NULL,
                          G_PARAM_READWRITE |
                          G_PARAM_STATIC_NAME | G_PARAM_STATIC_NICK |
                          G_PARAM_STATIC_BLURB));

        /**
         * GSSDPResourceBrowser:mx:
         *
         * The maximum number of seconds in which to request other parties
         * to respond.
         **/
        g_object_class_install_property
                (object_class,
                 PROP_MX,
                 g_param_spec_uint
                         ("mx",
                          "MX",
                          "The maximum number of seconds in which to request "
                          "other parties to respond.",
                          1,
                          G_MAXUSHORT,
                          SSDP_DEFAULT_MX,
                          G_PARAM_READWRITE |
                          G_PARAM_STATIC_NAME | G_PARAM_STATIC_NICK |
                          G_PARAM_STATIC_BLURB));

        /**
         * GSSDPResourceBrowser:active:
         *
         * Whether this browser is active or not.
         **/
        g_object_class_install_property
                (object_class,
                 PROP_ACTIVE,
                 g_param_spec_boolean
                         ("active",
                          "Active",
                          "TRUE if the resource browser is active.",
                          FALSE,
                          G_PARAM_READWRITE |
                          G_PARAM_STATIC_NAME | G_PARAM_STATIC_NICK |
                          G_PARAM_STATIC_BLURB));

        /**
         * GSSDPResourceBrowser::resource-available:
         * @resource_browser: The #GSSDPResourceBrowser that received the
         * signal
         * @usn: The USN of the discovered resource
         * @locations: (type GList*) (transfer none) (element-type utf8): A #GList of strings describing the locations of the
         * discovered resource.
         *
         * The ::resource-available signal is emitted whenever a new resource
         * has become available.
         **/
        signals[RESOURCE_AVAILABLE] =
                g_signal_new ("resource-available",
                              GSSDP_TYPE_RESOURCE_BROWSER,
                              G_SIGNAL_RUN_LAST,
                              G_STRUCT_OFFSET (GSSDPResourceBrowserClass,
                                               resource_available),
                              NULL, NULL,
                              gssdp_marshal_VOID__STRING_POINTER,
                              G_TYPE_NONE,
                              2,
                              G_TYPE_STRING,
                              G_TYPE_POINTER);

        /**
         * GSSDPResourceBrowser::resource-unavailable:
         * @resource_browser: The #GSSDPResourceBrowser that received the
         * signal
         * @usn: The USN of the resource
         *
         * The ::resource-unavailable signal is emitted whenever a resource
         * is not available any more.
         **/
        signals[RESOURCE_UNAVAILABLE] =
                g_signal_new ("resource-unavailable",
                              GSSDP_TYPE_RESOURCE_BROWSER,
                              G_SIGNAL_RUN_LAST,
                              G_STRUCT_OFFSET (GSSDPResourceBrowserClass,
                                               resource_unavailable),
                              NULL, NULL,
                              gssdp_marshal_VOID__STRING,
                              G_TYPE_NONE,
                              1,
                              G_TYPE_STRING);
}

/**
 * gssdp_resource_browser_new:
 * @client: The #GSSDPClient to associate with
 * @target: A SSDP search target
 *
 * @target is a generic string the resource browser listens for on the SSDP
 * bus. There are several possible targets such as
 * <itemizedlist>
 *   <listitem><para>"ssdp:all" for everything</para></listitem>
 *   <listitem><para>
 *     "upnp:rootdevice" for UPnP device entry points, not caring about the
 *     device type</para></listitem>
 *   <listitem><para>The UUID of a specific device</para></listitem>
 *   <listitem><para>Device types such as
 *   "urn:schemas-upnp-org:device:MediaServer:1"</para></listitem>
 *   <listitem><para>Service types such as
 *   "urn:schemas-upnp-org:service:ContentDirectory:1"</para></listitem>
 * </itemizedlist>
 *
 * Return value: A new #GSSDPResourceBrowser object.
 **/
GSSDPResourceBrowser *
gssdp_resource_browser_new (GSSDPClient *client,
                            const char  *target)
{
        return g_object_new (GSSDP_TYPE_RESOURCE_BROWSER,
                             "client", client,
                             "target", target,
                             NULL);
}

/*
 * Sets the #GSSDPClient @resource_browser is associated with to @client
 */
static void
gssdp_resource_browser_set_client (GSSDPResourceBrowser *resource_browser,
                                   GSSDPClient          *client)
{
        g_return_if_fail (GSSDP_IS_RESOURCE_BROWSER (resource_browser));
        g_return_if_fail (GSSDP_IS_CLIENT (client));

        resource_browser->priv->client = g_object_ref (client);

        resource_browser->priv->message_received_id =
                g_signal_connect_object (resource_browser->priv->client,
                                         "message-received",
                                         G_CALLBACK (message_received_cb),
                                         resource_browser,
                                         0);

        g_object_notify (G_OBJECT (resource_browser), "client");
}

/**
 * gssdp_resource_browser_get_client:
 * @resource_browser: A #GSSDPResourceBrowser
 *
 * Returns: (transfer none): The #GSSDPClient @resource_browser is associated with.
 **/
GSSDPClient *
gssdp_resource_browser_get_client (GSSDPResourceBrowser *resource_browser)
{
        g_return_val_if_fail (GSSDP_IS_RESOURCE_BROWSER (resource_browser),
                              NULL);

        return resource_browser->priv->client;
}

/**
 * gssdp_resource_browser_set_target:
 * @resource_browser: A #GSSDPResourceBrowser
 * @target: The browser target
 *
 * Sets the browser target of @resource_browser to @target.
 **/
void
gssdp_resource_browser_set_target (GSSDPResourceBrowser *resource_browser,
                                   const char           *target)
{
        char *pattern;
        char *version;
        const char *version_pattern;
        GError *error;

        g_return_if_fail (GSSDP_IS_RESOURCE_BROWSER (resource_browser));
        g_return_if_fail (target != NULL);
        g_return_if_fail (!resource_browser->priv->active);
        
        g_free (resource_browser->priv->target);
        resource_browser->priv->target = g_strdup (target);

        if (resource_browser->priv->target_regex)
                g_regex_unref (resource_browser->priv->target_regex);

        version_pattern = "([0-9]+)";
        /* Make sure we have enough room for version pattern */
        pattern = g_strndup (target,
                             strlen (target) + strlen (version_pattern));

        version = g_strrstr (pattern, ":");
        if (version != NULL &&
            (g_strstr_len (pattern, -1, "uuid:") != pattern ||
             version != g_strstr_len (pattern, -1, ":")) &&
            g_regex_match_simple (version_pattern,
                                  version + 1,
                                  G_REGEX_ANCHORED,
                                  G_REGEX_MATCH_ANCHORED)) {
                resource_browser->priv->version = atoi (version + 1);
                strcpy (version + 1, version_pattern);
        }

        error = NULL;
        resource_browser->priv->target_regex = g_regex_new (pattern,
                                                            0,
                                                            0,
                                                            &error);
        if (error) {
                g_warning ("Error compiling regular expression '%s': %s",
                           pattern,
                           error->message);

                g_error_free (error);
        }

        g_free (pattern);
        g_object_notify (G_OBJECT (resource_browser), "target");
}

/**
 * gssdp_resource_browser_get_target:
 * @resource_browser: A #GSSDPResourceBrowser
 *
 * Return value: The browser target.
 **/
const char *
gssdp_resource_browser_get_target (GSSDPResourceBrowser *resource_browser)
{
        g_return_val_if_fail (GSSDP_IS_RESOURCE_BROWSER (resource_browser),
                              NULL);

        return resource_browser->priv->target;
}

/**
 * gssdp_resource_browser_set_mx:
 * @resource_browser: A #GSSDPResourceBrowser
 * @mx: The to be used MX value
 *
 * Sets the used MX value of @resource_browser to @mx.
 **/
void
gssdp_resource_browser_set_mx (GSSDPResourceBrowser *resource_browser,
                               gushort               mx)
{
        g_return_if_fail (GSSDP_IS_RESOURCE_BROWSER (resource_browser));

        if (resource_browser->priv->mx == mx)
                return;

        resource_browser->priv->mx = mx;
        
        g_object_notify (G_OBJECT (resource_browser), "mx");
}

/**
 * gssdp_resource_browser_get_mx:
 * @resource_browser: A #GSSDPResourceBrowser
 *
 * Return value: The used MX value.
 **/
gushort
gssdp_resource_browser_get_mx (GSSDPResourceBrowser *resource_browser)
{
        g_return_val_if_fail (GSSDP_IS_RESOURCE_BROWSER (resource_browser), 0);

        return resource_browser->priv->mx;
}

/**
 * gssdp_resource_browser_set_active:
 * @resource_browser: A #GSSDPResourceBrowser
 * @active: %TRUE to activate @resource_browser
 *
 * (De)activates @resource_browser.
 **/
void
gssdp_resource_browser_set_active (GSSDPResourceBrowser *resource_browser,
                                   gboolean              active)
{
        g_return_if_fail (GSSDP_IS_RESOURCE_BROWSER (resource_browser));

        if (resource_browser->priv->active == active)
                return;

        resource_browser->priv->active = active;

        if (active) {
                start_discovery (resource_browser);
        } else {
                stop_discovery (resource_browser);

                clear_cache (resource_browser);
        }
        
        g_object_notify (G_OBJECT (resource_browser), "active");
}

/**
 * gssdp_resource_browser_get_active:
 * @resource_browser: A #GSSDPResourceBrowser
 *
 * Return value: %TRUE if @resource_browser is active.
 **/
gboolean
gssdp_resource_browser_get_active (GSSDPResourceBrowser *resource_browser)
{
        g_return_val_if_fail (GSSDP_IS_RESOURCE_BROWSER (resource_browser), 0);

        return resource_browser->priv->active;
}

/**
 * gssdp_resource_browser_rescan:
 * @resource_browser: A #GSSDPResourceBrowser
 *
 * Begins discovery if @resource_browser is active and no discovery is
 * performed. Otherwise does nothing.
 *
 * Return value: %TRUE if rescaning has been started.
 **/
gboolean
gssdp_resource_browser_rescan (GSSDPResourceBrowser *resource_browser)
{
        g_return_val_if_fail (GSSDP_IS_RESOURCE_BROWSER (resource_browser), 0);

        if (resource_browser->priv->active &&
            resource_browser->priv->timeout_src == NULL &&
            resource_browser->priv->refresh_cache_src == NULL) {
                start_discovery (resource_browser);
                return TRUE;
        }

        return FALSE;
}

/*
 * Resource expired: Remove
 */
static gboolean
resource_expire (gpointer user_data)
{
        GSSDPResourceBrowser *resource_browser;
        Resource *resource;
        char *usn;
        char *canonical_usn;

        resource = user_data;
        resource_browser = resource->resource_browser;

        /* Steal the USN pointer from the resource as we need it for the signal
         * emission.
         */
        usn = resource->usn;
        resource->usn = NULL;

        if (resource_browser->priv->version > 0) {
                char *version;

                version = g_strrstr (usn, ":");
                canonical_usn = g_strndup (usn, version - usn);
        } else {
                canonical_usn = g_strdup (usn);
        }

        g_hash_table_remove (resource->resource_browser->priv->resources,
                             canonical_usn);

        g_signal_emit (resource_browser,
                       signals[RESOURCE_UNAVAILABLE],
                       0,
                       usn);
        g_free (usn);
        g_free (canonical_usn);

        return FALSE;
}

static void
resource_available (GSSDPResourceBrowser *resource_browser,
                    SoupMessageHeaders   *headers)
{
        const char *usn;
        const char *header;
        Resource *resource;
        gboolean was_cached;
        guint timeout;
        GList *locations;
        gboolean destroyLocations;
        GList *it1, *it2;
        char *canonical_usn;

        usn = soup_message_headers_get_one (headers, "USN");
        if (!usn)
                return; /* No USN specified */

        /* Build list of locations */
        locations = NULL;
        destroyLocations = TRUE;

        header = soup_message_headers_get_one (headers, "Location");
        if (header)
                locations = g_list_append (locations, g_strdup (header));

        header = soup_message_headers_get_one (headers, "AL");
        if (header) {
                /* Parse AL header. The format is:
                 * <uri1><uri2>... */
                const char *start, *end;
                char *uri;

                start = header;
                while ((start = strchr (start, '<'))) {
                        start += 1;
                        if (!start || !*start)
                                break;

                        end = strchr (start, '>');
                        if (!end || !*end)
                                break;

                        uri = g_strndup (start, end - start);
                        locations = g_list_append (locations, uri);

                        start = end;
                }
        }

        if (!locations)
                return; /* No location specified */

        if (resource_browser->priv->version > 0) {
                char *version;

                version = g_strrstr (usn, ":");
                canonical_usn = g_strndup (usn, version - usn);
        } else {
                canonical_usn = g_strdup (usn);
        }

        /* Get from cache, if possible */
        resource = g_hash_table_lookup (resource_browser->priv->resources,
                                        canonical_usn);
        /* Put usn into fresh resources, so this resource will not be
         * removed on cache refreshing. */
        if (resource_browser->priv->fresh_resources != NULL) {
                g_hash_table_add (resource_browser->priv->fresh_resources,
                                  g_strdup (canonical_usn));
        }

        /* If location does not match, expect that we missed bye bye packet */
        if (resource) {
                for (it1 = locations, it2 = resource->locations;
                     it1 && it2;
                     it1 = it1->next, it2 = it2->next) {
                        if (strcmp ((const char *) it1->data,
                                    (const char *) it2->data) != 0) {
                               resource_unavailable (resource_browser, headers);
                               /* Will be destroyed by resource_unavailable */
                               resource = NULL;

                               break;
                        }
                }
        }

        if (resource) {
                /* Remove old timeout */
                g_source_destroy (resource->timeout_src);

                was_cached = TRUE;
        } else {
                /* Create new Resource data structure */
                resource = g_slice_new (Resource);

                resource->resource_browser = resource_browser;
                resource->usn              = g_strdup (usn);
                resource->locations        = locations;
                destroyLocations = FALSE; /* Ownership passed to resource */
                
                g_hash_table_insert (resource_browser->priv->resources,
                                     canonical_usn,
                                     resource);
                
                was_cached = FALSE;

                /* hash-table takes ownership of this */
                canonical_usn = NULL;
        }

        if (canonical_usn != NULL)
                g_free (canonical_usn);

        /* Calculate new timeout */
        header = soup_message_headers_get_one (headers, "Cache-Control");
        if (header) {
                GSList *list;
                int res;

                res = 0;

                for (list = soup_header_parse_list (header);
                     list;
                     list = list->next) {
                        res = sscanf (list->data,
                                      "max-age = %d",
                                      &timeout);
                        if (res == 1)
                                break;
                }

                if (res != 1) {
                        g_warning ("Invalid 'Cache-Control' header. Assuming "
                                   "default max-age of %d.\n"
                                   "Header was:\n%s",
                                   SSDP_DEFAULT_MAX_AGE,
                                   header);

                        timeout = SSDP_DEFAULT_MAX_AGE;
                }

                soup_header_free_list (list);
        } else {
                const char *expires;

                expires = soup_message_headers_get_one (headers, "Expires");
                if (expires) {
                        SoupDate *soup_exp_time;
                        time_t exp_time, cur_time;

                        soup_exp_time = soup_date_new_from_string (expires);
                        exp_time = soup_date_to_time_t (soup_exp_time);
                        soup_date_free (soup_exp_time);

                        cur_time = time (NULL);

                        if (exp_time > cur_time)
                                timeout = exp_time - cur_time;
                        else {
                                g_warning ("Invalid 'Expires' header. Assuming "
                                           "default max-age of %d.\n"
                                           "Header was:\n%s",
                                           SSDP_DEFAULT_MAX_AGE,
                                           expires);

                                timeout = SSDP_DEFAULT_MAX_AGE;
                        }
                } else {
                        g_warning ("No 'Cache-Control' nor any 'Expires' "
                                   "header was specified. Assuming default "
                                   "max-age of %d.", SSDP_DEFAULT_MAX_AGE);

                        timeout = SSDP_DEFAULT_MAX_AGE;
                }
        }

        resource->timeout_src = g_timeout_source_new_seconds (timeout);
        g_source_set_callback (resource->timeout_src,
                               resource_expire,
                               resource, NULL);

        g_source_attach (resource->timeout_src,
                         g_main_context_get_thread_default ());

        g_source_unref (resource->timeout_src);

        /* Only continue with signal emission if this resource was not
         * cached already */
        if (!was_cached) {
                /* Emit signal */
                g_signal_emit (resource_browser,
                               signals[RESOURCE_AVAILABLE],
                               0,
                               usn,
                               locations);
        }
        /* Cleanup */
        if (destroyLocations)
                g_list_free_full (locations, g_free);
}

static void
resource_unavailable (GSSDPResourceBrowser *resource_browser,
                      SoupMessageHeaders   *headers)
{
        const char *usn;
        char *canonical_usn;

        usn = soup_message_headers_get_one (headers, "USN");
        if (!usn)
                return; /* No USN specified */

        if (resource_browser->priv->version > 0) {
                char *version;

                version = g_strrstr (usn, ":");
                canonical_usn = g_strndup (usn, version - usn);
        } else {
                canonical_usn = g_strdup (usn);
        }

        /* Only process if we were cached */
        if (!g_hash_table_lookup (resource_browser->priv->resources,
                                  canonical_usn))
                goto out;

        g_hash_table_remove (resource_browser->priv->resources,
                             canonical_usn);

        g_signal_emit (resource_browser,
                       signals[RESOURCE_UNAVAILABLE],
                       0,
                       usn);

out:
        g_free (canonical_usn);
}

static gboolean
check_target_compat (GSSDPResourceBrowser *resource_browser,
                     const char           *st)
{
        GMatchInfo *info;
        int         version;
        char       *tmp;

        if (strcmp (resource_browser->priv->target,
                    GSSDP_ALL_RESOURCES) == 0)
                return TRUE;

        if (!g_regex_match (resource_browser->priv->target_regex,
                            st,
                            0,
                            &info)) {
                g_match_info_free (info);

                return FALSE;
        }

        /* If there was no version to match, we're done */
        if (resource_browser->priv->version == 0) {
                g_match_info_free (info);

                return TRUE;
        }

        if (g_match_info_get_match_count (info) != 2) {
                g_match_info_free (info);

                return FALSE;
        }

        version = atoi ((tmp = g_match_info_fetch (info, 1)));
        g_free (tmp);
        g_match_info_free (info);

        if (version < 0) {
            return FALSE;
        }

        return (guint) version >= resource_browser->priv->version;
}

static void
received_discovery_response (GSSDPResourceBrowser *resource_browser,
                             SoupMessageHeaders   *headers)
{
        const char *st;

        st = soup_message_headers_get_one (headers, "ST");
        if (!st)
                return; /* No target specified */

        if (!check_target_compat (resource_browser, st))
                return; /* Target doesn't match */

        resource_available (resource_browser, headers);
}

static void
received_announcement (GSSDPResourceBrowser *resource_browser,
                       SoupMessageHeaders   *headers)
{
        const char *header;

        header = soup_message_headers_get_one (headers, "NT");
        if (!header)
                return; /* No target specified */

        if (!check_target_compat (resource_browser, header))
                return; /* Target doesn't match */

        header = soup_message_headers_get_one (headers, "NTS");
        if (!header)
                return; /* No announcement type specified */

        /* Check announcement type */
        if      (strncmp (header,
                          SSDP_ALIVE_NTS,
                          strlen (SSDP_ALIVE_NTS)) == 0)
                resource_available (resource_browser, headers);
        else if (strncmp (header,
                          SSDP_BYEBYE_NTS,
                          strlen (SSDP_BYEBYE_NTS)) == 0)
                resource_unavailable (resource_browser, headers);
}

/*
 * Received a message
 */
static void
message_received_cb (G_GNUC_UNUSED GSSDPClient *client,
                     G_GNUC_UNUSED const char  *from_ip,
                     G_GNUC_UNUSED gushort      from_port,
                     _GSSDPMessageType          type,
                     SoupMessageHeaders        *headers,
                     gpointer                   user_data)
{
        GSSDPResourceBrowser *resource_browser;

        resource_browser = GSSDP_RESOURCE_BROWSER (user_data);

        if (!resource_browser->priv->active)
                return;

        switch (type) {
        case _GSSDP_DISCOVERY_RESPONSE:
                received_discovery_response (resource_browser, headers);
                break;
        case _GSSDP_ANNOUNCEMENT:
                received_announcement (resource_browser, headers);
                break;
        case _GSSDP_DISCOVERY_REQUEST:
                /* Should not happend */
                break;
        default:
                break;
        }
}

/*
 * Free a Resource structure and its contained data
 */
static void
resource_free (Resource *resource)
{
        g_free (resource->usn);
        g_source_destroy (resource->timeout_src);
        g_list_free_full (resource->locations, g_free);
        g_slice_free (Resource, resource);
}

static gboolean
clear_cache_helper (G_GNUC_UNUSED gpointer key,
                    gpointer               value,
                    G_GNUC_UNUSED gpointer data)
{
        Resource *resource;

        resource = value;

        g_signal_emit (resource->resource_browser,
                       signals[RESOURCE_UNAVAILABLE],
                       0,
                       resource->usn);

        return TRUE;
}

/*
 * Clears the cached resources hash
 */
static void
clear_cache (GSSDPResourceBrowser *resource_browser)
{
        /* Clear cache */
        g_hash_table_foreach_remove (resource_browser->priv->resources,
                                     clear_cache_helper,
                                     NULL);
}

/* Sends discovery request */
static void
send_discovery_request (GSSDPResourceBrowser *resource_browser)
{
        char *message;

        message = g_strdup_printf (SSDP_DISCOVERY_REQUEST,
                                   resource_browser->priv->target,
                                   resource_browser->priv->mx,
                                   g_get_prgname () ? g_get_prgname () : "");

        _gssdp_client_send_message (resource_browser->priv->client,
                                    NULL,
                                    0,
                                    message,
                                    _GSSDP_DISCOVERY_REQUEST);

        g_free (message);
}

static gboolean
discovery_timeout (gpointer data)
{
        GSSDPResourceBrowser *resource_browser;

        resource_browser = GSSDP_RESOURCE_BROWSER (data);

        send_discovery_request (resource_browser);

        resource_browser->priv->num_discovery += 1;

        if (resource_browser->priv->num_discovery >= MAX_DISCOVERY_MESSAGES) {
                resource_browser->priv->timeout_src = NULL;
                resource_browser->priv->num_discovery = 0;

                /* Setup cache refreshing */
                resource_browser->priv->refresh_cache_src =
                                  g_timeout_source_new_seconds (RESCAN_TIMEOUT);
                g_source_set_callback
                                     (resource_browser->priv->refresh_cache_src,
                                      refresh_cache,
                                      resource_browser,
                                      NULL);
                g_source_attach (resource_browser->priv->refresh_cache_src,
                                 g_main_context_get_thread_default ());
                g_source_unref (resource_browser->priv->refresh_cache_src);

                return FALSE;
        } else
                return TRUE;
}

/* Starts sending discovery requests */
static void
start_discovery (GSSDPResourceBrowser *resource_browser)
{
        /* Send one now */
        send_discovery_request (resource_browser);

        /* And schedule the rest for later */
        resource_browser->priv->num_discovery = 1;
        resource_browser->priv->timeout_src =
                g_timeout_source_new (DISCOVERY_FREQUENCY);
        g_source_set_callback (resource_browser->priv->timeout_src,
                               discovery_timeout,
                               resource_browser, NULL);

        g_source_attach (resource_browser->priv->timeout_src,
                         g_main_context_get_thread_default ());

        g_source_unref (resource_browser->priv->timeout_src);

        /* Setup a set of responsive resources for cache refreshing */
        resource_browser->priv->fresh_resources = g_hash_table_new_full
                                        (g_str_hash,
                                         g_str_equal,
                                         g_free,
                                         NULL);
}

/* Stops the sending of discovery messages */
static void
stop_discovery (GSSDPResourceBrowser *resource_browser)
{
        if (resource_browser->priv->timeout_src) {
                g_source_destroy (resource_browser->priv->timeout_src);
                resource_browser->priv->timeout_src = NULL;
                resource_browser->priv->num_discovery = 0;
        }
        if (resource_browser->priv->refresh_cache_src) {
                g_source_destroy (resource_browser->priv->refresh_cache_src);
                resource_browser->priv->refresh_cache_src = NULL;
        }
        if (resource_browser->priv->fresh_resources) {
                g_hash_table_unref (resource_browser->priv->fresh_resources);
                resource_browser->priv->fresh_resources = NULL;
        }
}

static gboolean
refresh_cache_helper (gpointer key, gpointer value, gpointer data)
{
        Resource *resource;
        GHashTable *fresh_resources;

        resource = value;
        fresh_resources = data;

        if (g_hash_table_contains (fresh_resources, key))
                return FALSE;
        else {
                g_signal_emit (resource->resource_browser,
                               signals[RESOURCE_UNAVAILABLE],
                               0,
                               resource->usn);

                return TRUE;
        }
}

/* Removes non-responsive resources */
static gboolean
refresh_cache (gpointer data)
{
        GSSDPResourceBrowser *resource_browser;

        resource_browser = GSSDP_RESOURCE_BROWSER (data);
        g_hash_table_foreach_remove (resource_browser->priv->resources,
                                     refresh_cache_helper,
                                     resource_browser->priv->fresh_resources);
        g_hash_table_unref (resource_browser->priv->fresh_resources);
        resource_browser->priv->fresh_resources = NULL;
        resource_browser->priv->refresh_cache_src = NULL;

        return FALSE;
}