~ubuntu-geoip-team/ubuntu-geoip/trunk

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
/*
A GeoClue provider to use the Ubuntu GeoIP web service

Copyright 2010 Canonical Ltd.

Authors:
    Ted Gould <ted@canonical.com>

This program is free software: you can redistribute it and/or modify it 
under the terms of the GNU General Public License version 3, as published 
by the Free Software Foundation.

This program is distributed in the hope that it will be useful, but 
WITHOUT ANY WARRANTY; without even the implied warranties of 
MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR 
PURPOSE.  See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along 
with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include <math.h>
#include <stdlib.h>
#include <glib.h>

#include "ubuntu-geoip-provider.h"

/* GeoClue */
#include <geoclue/gc-iface-position.h>
#include <geoclue/gc-iface-address.h>

/* Soup */
#include <libsoup/soup-gnome.h>

/* Network Manager */
#include <nm-client.h>

#define REQUEUE_MIN_SEC   15
#define REQUEUE_MAX_SEC   (60 * 60)
#define REQUEUE_SCALE     2

#define GEOIP_URL         "geoip-url"

typedef enum _MarkupField MarkupField;
enum _MarkupField {
	/* Address */
	MARKUP_FIELD_COUNTRY_CODE,
	MARKUP_FIELD_COUNTRY_NAME,
	MARKUP_FIELD_REGION_NAME,
	MARKUP_FIELD_CITY,
	MARKUP_FIELD_POSTAL_CODE,
	MARKUP_FIELD_TIMEZONE,
	/* Position */
	MARKUP_FIELD_LONGITUDE,
	MARKUP_FIELD_LATITUDE,
	/* End of list */
	MARKUP_FIELD_CNT
};

typedef struct _MarkupData MarkupData;
struct _MarkupData {
	UbuntuGeoipProvider * provider;
	MarkupField field;

	gboolean position_changed;
	gboolean address_changed;

	gboolean valid_header;
};

struct _UbuntuGeoipProviderPrivate
{
	SoupSession * soup;
	NMClient * client;
	GSettings * settings;

	/* Markup thingies */
	GMarkupParseContext * context;
	MarkupData markup_data;

	/* Position Variables */
	double latitude;
	double longitude;

	/* Address variables */
	gchar * country_code;
	gchar * country_name;
	gchar * region_name;
	gchar * city;
	gchar * postal_code;
	gchar * timezone;

	/* State variables */
	NMState network_state;
	gboolean gotdata;

	/* Requeue variables */
	guint requeue_source;
	guint requeue_time;
};

#define UBUNTU_GEOIP_PROVIDER_GET_PRIVATE(o) \
(G_TYPE_INSTANCE_GET_PRIVATE ((o), UBUNTU_GEOIP_PROVIDER_TYPE, UbuntuGeoipProviderPrivate))

static gchar * test_data = NULL;
static GMainLoop * mainloop = NULL;
static const gchar * field_names[MARKUP_FIELD_CNT] = {
	"CountryCode",
	"CountryName",
	"RegionName",
	"City",
	"ZipPostalCode",
	"TimeZone",
	"Longitude",
	"Latitude"
};

static void ubuntu_geoip_provider_class_init (UbuntuGeoipProviderClass *klass);
static void ubuntu_geoip_provider_init       (UbuntuGeoipProvider *self);
static void ubuntu_geoip_provider_dispose    (GObject *object);
static void ubuntu_geoip_provider_finalize   (GObject *object);
static void gc_shutdown                      (GcProvider *provider);
static gboolean get_status                   (GcIfaceGeoclue *geoclue,
                                              GeoclueStatus  *status,
                                              GError        **error);
static void position_iface_init              (GcIfacePositionClass *iface);
static void address_iface_init               (GcIfaceAddressClass *iface);
static void send_message                     (UbuntuGeoipProvider *provider);
static void queue_message                    (UbuntuGeoipProvider * provider);
static void nm_state_change                  (NMClient *client,
                                              const GParamSpec *pspec,
                                              gpointer user_data);
static gboolean get_address                  (GcIfaceAddress *gc,
                                              int *timestamp,
                                              GHashTable **address,
                                              GeoclueAccuracy **accuracy,
                                              GError **error);
static void markup_start                     (GMarkupParseContext * context,
                                              const gchar * element_name,
                                              const gchar ** attribute_names,
                                              const gchar ** attribute_values,
                                              gpointer user_data,
                                              GError ** error);
static void markup_end                       (GMarkupParseContext * context,
                                              const gchar * element_name,
                                              gpointer user_data,
                                              GError ** error);
static void markup_text                      (GMarkupParseContext * context,
                                              const gchar * text,
                                              gsize text_len,
                                              gpointer user_data,
                                              GError ** error);
static void url_changed                      (GSettings * settings,
                                              char * key,
                                              gpointer user_data);
static gboolean parse_xml_data               (UbuntuGeoipProvider * provider,
                                              const gchar * xml,
                                              const gint length);
static gboolean use_test_data                (gpointer user_data);

static GMarkupParser parser_struct = {
	start_element: markup_start,
	end_element: markup_end,
	text: markup_text,
	passthrough: NULL,
	error: NULL
};

G_DEFINE_TYPE_WITH_CODE (UbuntuGeoipProvider, ubuntu_geoip_provider, GC_TYPE_PROVIDER,
                         G_IMPLEMENT_INTERFACE (GC_TYPE_IFACE_POSITION, position_iface_init)
                         G_IMPLEMENT_INTERFACE (GC_TYPE_IFACE_ADDRESS,  address_iface_init)
                         );

/* Discuss our relationship with other classes */
static void
ubuntu_geoip_provider_class_init (UbuntuGeoipProviderClass *klass)
{
	GObjectClass *object_class = G_OBJECT_CLASS (klass);

	g_type_class_add_private (klass, sizeof (UbuntuGeoipProviderPrivate));

	object_class->dispose = ubuntu_geoip_provider_dispose;
	object_class->finalize = ubuntu_geoip_provider_finalize;

	GcProviderClass * gc_class = GC_PROVIDER_CLASS(klass);

	gc_class->get_status = get_status;
	gc_class->shutdown = gc_shutdown;

	return;
}

/* Check to see if a schema exists */
static gboolean
settings_schema_exists (const gchar * schema)
{
	const gchar * const * schemas = g_settings_list_schemas();
	int i;

	for (i = 0; schemas[i] != NULL; i++) {
		if (g_strcmp0(schemas[i], schema) == 0) {
			return TRUE;
		}
	}

	return FALSE;
}

/* Make everything consistent */
static void
ubuntu_geoip_provider_init (UbuntuGeoipProvider *self)
{
	self->priv = UBUNTU_GEOIP_PROVIDER_GET_PRIVATE(self);

	/* Init */
	self->priv->soup = NULL;
	self->priv->client = NULL;
	self->priv->settings = NULL;

	self->priv->latitude = 0.0;
	self->priv->longitude = 0.0;
	self->priv->network_state = NM_STATE_UNKNOWN;
	self->priv->gotdata = FALSE;

	self->priv->country_code = NULL;
	self->priv->country_name = NULL;
	self->priv->region_name = NULL;
	self->priv->city = NULL;
	self->priv->postal_code = NULL;
	self->priv->timezone = NULL;

	self->priv->context = NULL;
	self->priv->markup_data.provider = self;
	self->priv->markup_data.field = MARKUP_FIELD_CNT;

	self->priv->requeue_source = 0;
	self->priv->requeue_time = REQUEUE_MIN_SEC;

	/* Build Parser */
	self->priv->context = g_markup_parse_context_new(&parser_struct, 0, &self->priv->markup_data, NULL);

	/* Set up settings */
	if (settings_schema_exists("com.ubuntu.geoip")) {
		self->priv->settings = g_settings_new("com.ubuntu.geoip");
		g_signal_connect(G_OBJECT(self->priv->settings), "changed::" GEOIP_URL, G_CALLBACK(url_changed), self);
	}

	/* Allocate */
	if (test_data == NULL) {
		self->priv->soup = soup_session_async_new();
		soup_session_add_feature_by_type(self->priv->soup, soup_proxy_resolver_gnome_get_type());
		self->priv->client = nm_client_new();
		g_signal_connect(G_OBJECT(self->priv->client), "notify::" NM_CLIENT_STATE, G_CALLBACK(nm_state_change), self);

		/* Check things out */
		nm_state_change(self->priv->client, NULL, self);
	} else {
		self->priv->network_state = NM_STATE_CONNECTED_GLOBAL;
		g_idle_add(use_test_data, self);
	}

	gc_provider_set_details (GC_PROVIDER (self),
	                         "org.freedesktop.Geoclue.Providers.UbuntuGeoIP",
	                         "/org/freedesktop/Geoclue/Providers/UbuntuGeoIP",
	                         "Ubuntu GeoIP",
	                         "Provides location using IP and the Ubuntu IP Geolocation Service");

	return;
}

/* Loose references */
static void
ubuntu_geoip_provider_dispose (GObject *object)
{
	UbuntuGeoipProvider * provider = UBUNTU_GEOIP_PROVIDER(object);

	if (provider->priv->requeue_source != 0) {
		g_source_remove(provider->priv->requeue_source);
		provider->priv->requeue_source = 0;
	}

	if (provider->priv->soup != NULL) {
		g_object_unref(provider->priv->soup);
		provider->priv->soup = NULL;
	}

	if (provider->priv->client != NULL) {
		g_object_unref(provider->priv->client);
		provider->priv->client = NULL;
	}

	if (provider->priv->context != NULL) {
		g_object_unref(provider->priv->context);
		provider->priv->context = NULL;
	}

	if (provider->priv->settings != NULL) {
		g_object_unref(provider->priv->settings);
		provider->priv->settings = NULL;
	}

	G_OBJECT_CLASS (ubuntu_geoip_provider_parent_class)->dispose (object);
	return;
}

/* Free Memory */
static void
ubuntu_geoip_provider_finalize (GObject *object)
{
	UbuntuGeoipProvider * provider = UBUNTU_GEOIP_PROVIDER(object);

	if (provider->priv->country_code != NULL) {
		g_free(provider->priv->country_code);
		provider->priv->country_code = NULL;
	}

	if (provider->priv->country_name != NULL) {
		g_free(provider->priv->country_name);
		provider->priv->country_name = NULL;
	}

	if (provider->priv->region_name != NULL) {
		g_free(provider->priv->region_name);
		provider->priv->region_name = NULL;
	}

	if (provider->priv->city != NULL) {
		g_free(provider->priv->city);
		provider->priv->city = NULL;
	}

	if (provider->priv->postal_code != NULL) {
		g_free(provider->priv->postal_code);
		provider->priv->postal_code = NULL;
	}

	if (provider->priv->timezone != NULL) {
		g_free(provider->priv->timezone);
		provider->priv->timezone = NULL;
	}


	G_OBJECT_CLASS (ubuntu_geoip_provider_parent_class)->finalize (object);
	return;
}

/* Function to load the test data and pass it into the parser */
static gboolean
use_test_data (gpointer user_data)
{
	g_return_val_if_fail(IS_UBUNTU_GEOIP_PROVIDER(user_data), FALSE);
	g_return_val_if_fail(test_data != NULL, FALSE);

	gchar * data = NULL;
	gsize length = 0;

	if (g_file_test(test_data, G_FILE_TEST_EXISTS)) {
		GError * error = NULL;

		g_file_get_contents(test_data, &data, &length, &error);

		if (error != NULL) {
			g_warning("Unable to read test data '%s': %s", test_data, error->message);
			g_error_free(error);
		}
	}

	if (data != NULL) {
		parse_xml_data(UBUNTU_GEOIP_PROVIDER(user_data), data, length);

		g_free(data);
	}

	return FALSE;
}

/* Something could change our URL settings, if so we need to respond
   and start getting the new data */
static void
url_changed (GSettings * settings, char * key, gpointer user_data)
{
	UbuntuGeoipProvider *provider = UBUNTU_GEOIP_PROVIDER(user_data);
	g_return_if_fail(provider != NULL);

	/* If we've got a network connection we care, otherwise we don't
	   have a reason to use the new URL */
	if (provider->priv->network_state == NM_STATE_CONNECTED_GLOBAL) {
		provider->priv->gotdata = FALSE;
		gc_iface_geoclue_emit_status_changed(GC_IFACE_GEOCLUE(provider), GEOCLUE_STATUS_ACQUIRING);
		send_message(provider);
	}

	return;
}

/* Respond to a request to shutdown from the GeoClue provider
   interface. */
static void
gc_shutdown (GcProvider *provider)
{
	g_debug("Shutdown by provider");
	g_main_loop_quit(mainloop);
	return;
}

/* Get teh status of our position */
static gboolean
get_status (GcIfaceGeoclue *geoclue, GeoclueStatus * status, GError ** error)
{
	UbuntuGeoipProvider *provider = UBUNTU_GEOIP_PROVIDER(geoclue);
	g_return_val_if_fail(provider != NULL, FALSE);

	if (provider->priv->network_state != NM_STATE_CONNECTED_GLOBAL &&
		provider->priv->network_state != NM_STATE_CONNECTING) {
		*status = GEOCLUE_STATUS_UNAVAILABLE;
	} else if (provider->priv->network_state == NM_STATE_CONNECTING) {
		*status = GEOCLUE_STATUS_ACQUIRING;
	} else if (provider->priv->gotdata == FALSE) {
		*status = GEOCLUE_STATUS_ACQUIRING;
	} else {
		*status = GEOCLUE_STATUS_AVAILABLE;
	}

	return TRUE;
}

/* Figure out how accurate we are based on the information we have */
GeoclueAccuracy *
position_accuracy_build (UbuntuGeoipProvider * provider)
{
	GeoclueAccuracy * accuracy = geoclue_accuracy_new (GEOCLUE_ACCURACY_LEVEL_NONE, 0.0, 0.0);

	/* We're basically making fixed point values at the 10K location */
	gint fixed_alat = abs(provider->priv->latitude * 10000.0);
	gint fixed_alon = abs(provider->priv->longitude * 10000.0);

	/* Basically what we're doing here is checking the rounding.  If we're
	   rounding to an even value... it's roughly a country. */
	if ((fixed_alat % 100000) > 0 || (fixed_alon % 100000) > 0) { /* 1.0 accuracy */
		geoclue_accuracy_set_details(accuracy, GEOCLUE_ACCURACY_LEVEL_COUNTRY, 0.0, 0.0);

		if ((fixed_alat % 10000) > 0 || (fixed_alon % 10000) > 0) { /* 0.1 accuracy */
			geoclue_accuracy_set_details(accuracy, GEOCLUE_ACCURACY_LEVEL_REGION, 0.0, 0.0);

			if ((fixed_alat % 1000) > 0 || (fixed_alon % 1000) > 0) { /* 0.01 accuracy */
				geoclue_accuracy_set_details(accuracy, GEOCLUE_ACCURACY_LEVEL_LOCALITY, 0.0, 0.0);
			}
		}
	}

	return accuracy;
}

/* Get the current position as we see it. */
static gboolean
get_position (GcIfacePosition *gc, GeocluePositionFields * fields, int * timestamp, double *latitude, double *longitude, double *altitude, GeoclueAccuracy **accuracy, GError **error)
{
	UbuntuGeoipProvider *provider = UBUNTU_GEOIP_PROVIDER(gc);
	g_return_val_if_fail(provider != NULL, FALSE);

	*timestamp = time (NULL);

	if (provider->priv->gotdata == FALSE) {
		*fields = GEOCLUE_POSITION_FIELDS_NONE;
		*accuracy = geoclue_accuracy_new (GEOCLUE_ACCURACY_LEVEL_NONE, 0.0, 0.0);
	} else {
		*fields = GEOCLUE_POSITION_FIELDS_LATITUDE | GEOCLUE_POSITION_FIELDS_LONGITUDE;
		*latitude = provider->priv->latitude;
		*longitude = provider->priv->longitude;
		*accuracy = position_accuracy_build(provider);
	}

	return TRUE;
}

/* Bring up the position interface */
static void
position_iface_init (GcIfacePositionClass *iface)
{
	iface->get_position = get_position;
	return;
}

/* Figure out how accurate we are based on the information we have */
GeoclueAccuracy *
address_accuracy_build (UbuntuGeoipProvider * provider)
{
	GeoclueAccuracy * accuracy = geoclue_accuracy_new (GEOCLUE_ACCURACY_LEVEL_NONE, 0.0, 0.0);

	if (provider->priv->country_name != NULL || provider->priv->country_code != NULL) {
		geoclue_accuracy_set_details(accuracy, GEOCLUE_ACCURACY_LEVEL_COUNTRY, 0.0, 0.0);
	}

	if (provider->priv->region_name != NULL) {
		geoclue_accuracy_set_details(accuracy, GEOCLUE_ACCURACY_LEVEL_REGION, 0.0, 0.0);
	}

	if (provider->priv->city != NULL || provider->priv->postal_code != NULL) {
		geoclue_accuracy_set_details(accuracy, GEOCLUE_ACCURACY_LEVEL_LOCALITY, 0.0, 0.0);
	}

	return accuracy;
}

/* Put the details into the hash table correctly */
static void
address_details_build (UbuntuGeoipProvider * provider, GHashTable * details)
{
	if (provider->priv->country_code != NULL) {
		geoclue_address_details_insert(details, GEOCLUE_ADDRESS_KEY_COUNTRYCODE, provider->priv->country_code);
	}

	if (provider->priv->country_name != NULL) {
		geoclue_address_details_insert(details, GEOCLUE_ADDRESS_KEY_COUNTRY, provider->priv->country_name);
	}

	if (provider->priv->region_name != NULL) {
		geoclue_address_details_insert(details, GEOCLUE_ADDRESS_KEY_REGION, provider->priv->region_name);
	}

	if (provider->priv->city != NULL) {
		geoclue_address_details_insert(details, GEOCLUE_ADDRESS_KEY_LOCALITY, provider->priv->city);
	}

	if (provider->priv->postal_code != NULL) {
		geoclue_address_details_insert(details, GEOCLUE_ADDRESS_KEY_POSTALCODE, provider->priv->postal_code);
	}

	if (provider->priv->timezone != NULL) {
		geoclue_address_details_insert(details, "timezone", provider->priv->timezone);
	}

	return;
}

/* Get the address as we have it */
static gboolean
get_address (GcIfaceAddress *gc, int *timestamp, GHashTable **address, GeoclueAccuracy **accuracy, GError **error)
{
	UbuntuGeoipProvider *provider = UBUNTU_GEOIP_PROVIDER(gc);
	g_return_val_if_fail(provider != NULL, FALSE);

	*timestamp = time (NULL);

	if (provider->priv->gotdata == FALSE) {
		*address = geoclue_address_details_new();
		*accuracy = geoclue_accuracy_new (GEOCLUE_ACCURACY_LEVEL_NONE, 0.0, 0.0);
	} else {
		*address = geoclue_address_details_new();
		address_details_build(provider, *address);
		*accuracy = address_accuracy_build(provider);
	}

	return TRUE;
}

/* Bring up the address interface */
static void
address_iface_init (GcIfaceAddressClass *iface)
{
	iface->get_address = get_address;
	return;
}

/* Take the XML data we got from the internet and turn it into
   something useful */
static gboolean
parse_xml_data (UbuntuGeoipProvider * provider, const gchar * xml, const gint length)
{
	g_return_val_if_fail(xml != NULL, FALSE);
	g_return_val_if_fail(length > 10, FALSE);

	provider->priv->markup_data.position_changed = FALSE;
	provider->priv->markup_data.address_changed = FALSE;
	provider->priv->markup_data.valid_header = FALSE;

	/* Parse through the data using the markup functions already setup in
	   the context */
	if (g_markup_parse_context_parse(provider->priv->context, xml, length, NULL) == FALSE) {
		g_warning("Unable to parse the data from the geoip provider");

		/* Once we've broken a context, clear it for next time */
		g_clear_object(&provider->priv->context);
		provider->priv->context = g_markup_parse_context_new(&parser_struct, 0, &provider->priv->markup_data, NULL);

		return FALSE;
	}

	/* The parser won't check the format, this field ensures we got
	   a format that we expect */
	if (!provider->priv->markup_data.valid_header) {
		g_warning("We didn't get valid XML, that's not cool.");
		return FALSE;
	}

	/* We only need to emit a state change if we're switching from
	   not having data to having it */
	gboolean emit = FALSE;
	if (provider->priv->gotdata == FALSE) {
		emit = TRUE;
	}
	provider->priv->gotdata = TRUE;

	/* If the position changed, update that */
	if (provider->priv->markup_data.position_changed) {
		g_debug("New position:");
		g_debug("Latitude:  %f", provider->priv->latitude);
		g_debug("Longitude: %f", provider->priv->longitude);

		GeoclueAccuracy * accuracy = position_accuracy_build(provider);
		gc_iface_position_emit_position_changed(GC_IFACE_POSITION(provider), 
		                                        GEOCLUE_POSITION_FIELDS_LATITUDE | GEOCLUE_POSITION_FIELDS_LONGITUDE,
		                                        time(NULL),
		                                        provider->priv->latitude,
		                                        provider->priv->longitude,
		                                        0, /* Altitude */
		                                        accuracy);

		geoclue_accuracy_free(accuracy);
	}

	/* If the address changed, update that */
	if (provider->priv->markup_data.address_changed) {
		GeoclueAccuracy * accuracy = address_accuracy_build(provider);
		GHashTable * address = geoclue_address_details_new();

		address_details_build(provider, address);

		gc_iface_address_emit_address_changed(GC_IFACE_ADDRESS(provider), 
		                                        time(NULL),
		                                        address,
		                                        accuracy);

		g_hash_table_destroy(address);
		geoclue_accuracy_free(accuracy);
	}

	/* Now emit our status */
	if (emit) {
		g_debug("Emitting Available");
		gc_iface_geoclue_emit_status_changed(GC_IFACE_GEOCLUE(provider), GEOCLUE_STATUS_AVAILABLE);
	}

	return TRUE;
}

/* Called when the message is finished in its response */
static void
message_finished (SoupMessage * message, gpointer user_data)
{
	UbuntuGeoipProvider *provider = UBUNTU_GEOIP_PROVIDER(user_data);
	g_return_if_fail(provider != NULL);

	g_debug("Message Finished");

	guint statuscode = 0;
	g_object_get(G_OBJECT(message), SOUP_MESSAGE_STATUS_CODE, &statuscode, NULL);
	if (statuscode != 200) {
		g_warning("Unable to connect to geoip service, status: %d", statuscode);
		queue_message(provider);
		return;
	}

	if (parse_xml_data(provider, message->response_body->data, message->response_body->length)) {
		/* If we got something valid, reset our progressive backoff */
		provider->priv->requeue_time = REQUEUE_MIN_SEC;
	} else {
		/* If we got junk, try again later */
		queue_message(provider);
	}

	return;
}

/* Called when the message is entirely complete */
static void
message_complete (SoupSession * session, SoupMessage * message, gpointer user_data)
{
	UbuntuGeoipProvider *provider = UBUNTU_GEOIP_PROVIDER(user_data);
	g_return_if_fail(provider != NULL);

	g_debug("Message Complete");
	return;
}

/* Handle events that can be errors */
static void
message_network_event (SoupMessage * message, GSocketClientEvent event, GIOStream * connection, gpointer user_data)
{
	UbuntuGeoipProvider *provider = UBUNTU_GEOIP_PROVIDER(user_data);
	g_return_if_fail(provider != NULL);

	if (event == G_SOCKET_CLIENT_COMPLETE && connection == NULL) {
		/* This is the error condition */
		g_warning("Network connection error");
		queue_message(provider);
	}

	return;
}

/* Sends the message to the GeoIP service and sets up some
   callbacks for fun */
static void
send_message (UbuntuGeoipProvider *provider)
{
	g_return_if_fail(provider->priv->soup != NULL);

	/* Insure that we reset our timeout as we're fulfilling it */
	if (provider->priv->requeue_source != 0) {
		g_source_remove(provider->priv->requeue_source);
		provider->priv->requeue_source = 0;
	}

	/* Grab the URL from the settings if we have it */
	gchar * url = NULL;
	if (provider->priv->settings != NULL) {
		url = g_settings_get_string(provider->priv->settings, GEOIP_URL);
	} else {
		url = g_strdup("http://geoip.ubuntu.com/lookup");
	}
	g_debug("Using GeoIP URL: %s", url);

	/* Build the message to send */
	SoupMessage * message = soup_message_new("GET", url);
	g_signal_connect(G_OBJECT(message), "finished", G_CALLBACK(message_finished), provider);
	g_signal_connect(G_OBJECT(message), "network-event", G_CALLBACK(message_network_event), provider);

	g_free(url);
	url = NULL;

	/* Ask SOUP to hit the interwebs for us */
	soup_session_queue_message(provider->priv->soup, message,
	                           message_complete, provider);

	return;
}

/* It's now time to send the delayed message */
static gboolean
queue_message_timeout (gpointer user_data)
{
	UbuntuGeoipProvider * provider = UBUNTU_GEOIP_PROVIDER(user_data);
	g_return_val_if_fail(provider != NULL, FALSE);

	provider->priv->requeue_source = 0;

	send_message(provider);
	return FALSE;
}

/* Queue up a timeout to send a message */
static void
queue_message (UbuntuGeoipProvider * provider)
{
	if (provider->priv->requeue_source != 0) {
		return;
	}

	g_debug("Queuing up new message");
	provider->priv->requeue_time *= REQUEUE_SCALE;
	if (provider->priv->requeue_time > REQUEUE_MAX_SEC) {
		provider->priv->requeue_time = REQUEUE_MAX_SEC;
	}

	provider->priv->requeue_source = g_timeout_add_seconds(provider->priv->requeue_time, queue_message_timeout, provider);

	return;
}

/* Change the position to be zero and emit it if it changed */
static void
clear_position (UbuntuGeoipProvider * provider)
{
	if (provider->priv->latitude == 0.0 && provider->priv->longitude == 0.0) {
		/* We didn't have any data */
		return;
	}

	provider->priv->latitude = 0.0;
	provider->priv->longitude = 0.0;

	g_debug("Position Cleared");

	GeoclueAccuracy * accuracy = geoclue_accuracy_new (GEOCLUE_ACCURACY_LEVEL_NONE, 0.0, 0.0);
	gc_iface_position_emit_position_changed(GC_IFACE_POSITION(provider), 
	                                        time(NULL),
	                                        GEOCLUE_POSITION_FIELDS_NONE,
	                                        provider->priv->latitude,
	                                        provider->priv->longitude,
	                                        0, /* Altitude */
	                                        accuracy);

	geoclue_accuracy_free(accuracy);

	return;
}

/* Change the address to be clear and emit it if it changed */
static void
clear_address (UbuntuGeoipProvider * provider)
{
	if (provider->priv->country_code == NULL &&
			provider->priv->country_name == NULL &&
			provider->priv->region_name == NULL &&
			provider->priv->city == NULL &&
			provider->priv->postal_code == NULL &&
			provider->priv->timezone == NULL) {
		/* We don't have any data to clear */
		return;
	}

	if (provider->priv->country_code != NULL) {
		g_free(provider->priv->country_code);
		provider->priv->country_code = NULL;
	}

	if (provider->priv->country_name != NULL) {
		g_free(provider->priv->country_name);
		provider->priv->country_name = NULL;
	}

	if (provider->priv->region_name != NULL) {
		g_free(provider->priv->region_name);
		provider->priv->region_name = NULL;
	}

	if (provider->priv->city != NULL) {
		g_free(provider->priv->city);
		provider->priv->city = NULL;
	}

	if (provider->priv->postal_code != NULL) {
		g_free(provider->priv->postal_code);
		provider->priv->postal_code = NULL;
	}

	if (provider->priv->timezone != NULL) {
		g_free(provider->priv->timezone);
		provider->priv->timezone = NULL;
	}

	g_debug("Address Cleared");

	GHashTable * address = geoclue_address_details_new();
	GeoclueAccuracy * accuracy = geoclue_accuracy_new (GEOCLUE_ACCURACY_LEVEL_NONE, 0.0, 0.0);

	gc_iface_address_emit_address_changed(GC_IFACE_ADDRESS(provider), 
	                                        time(NULL),
	                                        address,
	                                        accuracy);

	geoclue_accuracy_free(accuracy);
	g_hash_table_unref(address);

	return;
}

/* Callback for when the Network Manger state changes */
static void
nm_state_change (NMClient *client, const GParamSpec *pspec, gpointer user_data)
{
	UbuntuGeoipProvider *provider = UBUNTU_GEOIP_PROVIDER(user_data);
	g_return_if_fail(provider != NULL);

	NMState state = nm_client_get_state (provider->priv->client);

	if (provider->priv->network_state != state) {
		/* Either way we want to refresh */
		provider->priv->gotdata = FALSE;
		provider->priv->network_state = state;

		clear_position(provider);
		clear_address(provider);

		if (state == NM_STATE_CONNECTED_GLOBAL) {
			g_debug("Network connected");
			gc_iface_geoclue_emit_status_changed(GC_IFACE_GEOCLUE(provider), GEOCLUE_STATUS_ACQUIRING);
			send_message(provider);
		} else if (state == NM_STATE_CONNECTING) {
			g_debug("Network connecting");
			gc_iface_geoclue_emit_status_changed(GC_IFACE_GEOCLUE(provider), GEOCLUE_STATUS_ACQUIRING);
		} else {
			g_debug("Network lost");
			gc_iface_geoclue_emit_status_changed(GC_IFACE_GEOCLUE(provider), GEOCLUE_STATUS_UNAVAILABLE);
		}
	}

	return;
}

/* Handle the start of tags */
static void
markup_start (GMarkupParseContext * context, const gchar * element_name, const gchar ** attribute_names, const gchar ** attribute_values, gpointer user_data, GError ** error)
{
	MarkupData * markup_data = (MarkupData *)user_data;

	if (markup_data->valid_header == FALSE) {
		if (g_strcmp0(element_name, "Response") == 0) {
			markup_data->valid_header = TRUE;
			markup_data->field = MARKUP_FIELD_CNT;
		}
		return;
	}

	if (markup_data->field != MARKUP_FIELD_CNT) {
		g_warning("New start tag without clearing old one.");
	}

	int i;
	for (i = 0; i < MARKUP_FIELD_CNT; i++) {
		if (g_strcmp0(field_names[i], element_name) == 0) {
			break;
		}
	}

	markup_data->field = i;

	return;
}

/* Look at teh end of tags */
static void
markup_end (GMarkupParseContext * context, const gchar * element_name, gpointer user_data, GError ** error)
{
	MarkupData * markup_data = (MarkupData *)user_data;
	markup_data->field = MARKUP_FIELD_CNT;
	return;
}

/* Handle the text inside a tag */
static void
markup_text (GMarkupParseContext * context, const gchar * text, gsize text_len, gpointer user_data, GError ** error)
{
	MarkupData * markup_data = (MarkupData *)user_data;
	gchar ** field = NULL;
	double * val = NULL;

	if (markup_data->valid_header == FALSE) {
		return;
	}

	if (text_len == 0) {
		/* Null strings aren't interesting to us */
		return;
	}

	/* Decode the enum into an offset */
	switch (markup_data->field) {
	case MARKUP_FIELD_COUNTRY_CODE:
		field = &(markup_data->provider->priv->country_code);
		break;
	case MARKUP_FIELD_COUNTRY_NAME:
		field = &(markup_data->provider->priv->country_name);
		break;
	case MARKUP_FIELD_REGION_NAME:
		field = &(markup_data->provider->priv->region_name);
		break;
	case MARKUP_FIELD_CITY:
		field = &(markup_data->provider->priv->city);
		break;
	case MARKUP_FIELD_POSTAL_CODE:
		field = &(markup_data->provider->priv->postal_code);
		break;
	case MARKUP_FIELD_TIMEZONE:
		field = &(markup_data->provider->priv->timezone);
		break;
	case MARKUP_FIELD_LATITUDE:
		val = &(markup_data->provider->priv->latitude);
		break;
	case MARKUP_FIELD_LONGITUDE:
		val = &(markup_data->provider->priv->longitude);
		break;
	case MARKUP_FIELD_CNT:
	default:
		break;
	}

	/* Make the text null terminated */
	gchar * newstr = g_memdup(text, text_len + 1);
	if (newstr != NULL) {
		newstr[text_len] = '\0';
	}

	if (g_strcmp0(newstr, "None") == 0) {
		g_free(newstr);
		return;
	}

	/* If we've got a string field, let's deal with that */
	if (field != NULL && newstr != NULL) {
		/* We've got new data? */
		if (g_strcmp0(*field, newstr) != 0) {
			if (*field != NULL) {
				g_free(*field);
				*field = NULL;
			}
			*field = newstr;
			newstr = NULL; /* Steal the memory */
			markup_data->address_changed = TRUE;
		}
	}

	/* We got a double field let's do that */
	if (val != NULL && newstr != NULL) {
		gdouble newval = strtod(newstr, NULL);
		if (newval != *val) {
			*val = newval;
			markup_data->position_changed = TRUE;
		}
	}

	/* Free the allocated memory */
	if (newstr != NULL) {
		g_free(newstr);
	}

	return;
}

static void
sigterm_graceful_exit (int signal)
{
	g_warning("SIGTERM recieved");
	g_main_loop_quit(mainloop);
	return;
}

static GOptionEntry general_options[] = {
	{"test-data",  0,  0,  G_OPTION_ARG_FILENAME,  &test_data,  "Path to test data to use instead of getting it from the network", "XML Data File"},
	{NULL}
};

/* Function to start everything */
int
main (int argc, char * argv[])
{
	GError * error = NULL;
	GOptionContext * context;

#ifndef GLIB_VERSION_2_36
	g_type_init();
#endif

	context = g_option_context_new("- Get the location of the machine using GeoIP and report it through GeoClue");

	g_option_context_add_main_entries(context, general_options, "dbus-runner");

	if (!g_option_context_parse(context, &argc, &argv, &error)) {
		g_print("option parsing failed: %s\n", error->message);
		g_error_free(error);
		return 1;
	}

	UbuntuGeoipProvider * provider = g_object_new(UBUNTU_GEOIP_PROVIDER_TYPE, NULL);
	g_return_val_if_fail(provider != NULL, 1);

	mainloop = g_main_loop_new(NULL, TRUE);

	signal(SIGTERM, sigterm_graceful_exit);

	g_main_loop_run(mainloop);

	g_main_loop_unref(mainloop);
	g_object_unref(provider);

	return 0;
}