summaryrefslogtreecommitdiff
path: root/gdata/gdata-oauth1-authorizer.c
blob: 6d5fd5ec6177d459bebe9dc1915ef496673a0066 (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
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */
/*
 * GData Client
 * Copyright (C) Philip Withnall 2011 <philip@tecnocode.co.uk>
 *
 * GData Client is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * GData Client 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with GData Client.  If not, see <http://www.gnu.org/licenses/>.
 */

/**
 * SECTION:gdata-oauth1-authorizer
 * @short_description: GData OAuth 1.0 authorization interface
 * @stability: Stable
 * @include: gdata/gdata-oauth1-authorizer.h
 *
 * OAuth 1.0 has been deprecated since 2012, and OAuth 2.0 (#GDataOAuth2Authorizer) should be used instead.
 *
 * #GDataOAuth1Authorizer provides an implementation of the #GDataAuthorizer interface for authentication and authorization using the
 * <ulink type="http" url="http://code.google.com/apis/accounts/docs/OAuthForInstalledApps.html">OAuth 1.0</ulink> process,
 * which was preferred by Google until OAuth 2.0 was released — it is now
 * preferred to use #GDataOAuth2Authorizer.
 *
 * OAuth 1.0 replaces the deprecated ClientLogin process. One of the main reasons for this is to allow two-factor authentication to be supported, by
 * moving the authentication interface to a web page under Google's control.
 *
 * The OAuth 1.0 process as implemented by Google follows the <ulink type="http" url="http://tools.ietf.org/html/rfc5849">OAuth 1.0 protocol as
 * specified by IETF in RFC 5849</ulink>, with a few additions to support scopes (implemented in libgdata by #GDataAuthorizationDomains),
 * locales and custom domains. Briefly, the process is initiated by requesting an authenticated request token from the Google accounts service
 * (using gdata_oauth1_authorizer_request_authentication_uri()), going to the authentication URI for the request token, authenticating and authorizing
 * access to the desired scopes, then providing the verifier returned by Google to the Google accounts service again (using
 * gdata_oauth1_authorizer_request_authorization()) to authorize the token. This results in an access token which is attached to all future requests
 * to the online service.
 *
 * While Google supports unregistered and registered modes for OAuth 1.0 authorization, it only supports unregistered mode for installed applications.
 * Consequently, libgdata also only supports unregistered mode. For this purpose, the application name to be presented to the user on the
 * authentication page at the URI returned by gdata_oauth1_authorizer_request_authentication_uri() can be specified when constructing the
 * #GDataOAuth1Authorizer.
 *
 * As described, each authentication/authorization operation is in two parts: gdata_oauth1_authorizer_request_authentication_uri() and
 * gdata_oauth1_authorizer_request_authorization(). #GDataOAuth1Authorizer stores no state about ongoing authentication operations (i.e. ones which
 * have successfully called gdata_oauth1_authorizer_request_authentication_uri(), but are yet to successfully call
 * gdata_oauth1_authorizer_request_authorization()). Consequently, operations can be abandoned before calling
 * gdata_oauth1_authorizer_request_authorization() without problems. The only state necessary between the calls is the request token and request token
 * secret, as returned by gdata_oauth1_authorizer_request_authentication_uri() and taken as parameters to
 * gdata_oauth1_authorizer_request_authorization().
 *
 * #GDataOAuth1Authorizer natively supports authorization against multiple services in a single authorization request (unlike
 * #GDataClientLoginAuthorizer).
 *
 * Each access token is long lived, so reauthorization is rarely necessary with #GDataOAuth1Authorizer. Consequently, refreshing authorization using
 * gdata_authorizer_refresh_authorization() is not supported by #GDataOAuth1Authorizer, and will immediately return %FALSE with no error set.
 *
 * <example>
 *	<title>Authenticating Asynchronously Using OAuth 1.0</title>
 *	<programlisting>
 *	GDataSomeService *service;
 *	GDataOAuth1Authorizer *authorizer;
 *
 *	/<!-- -->* Create an authorizer and authenticate and authorize the service we're using, asynchronously. *<!-- -->/
 *	authorizer = gdata_oauth1_authorizer_new (_("My libgdata application"), GDATA_TYPE_SOME_SERVICE);
 *	gdata_oauth1_authorizer_request_authentication_uri_async (authorizer, cancellable,
 *	                                                          (GAsyncReadyCallback) request_authentication_uri_cb, user_data);
 *
 *	/<!-- -->* Create a service object and link it with the authorizer *<!-- -->/
 *	service = gdata_some_service_new (GDATA_AUTHORIZER (authorizer));
 *
 *	static void
 *	request_authentication_uri_cb (GDataOAuth1Authorizer *authorizer, GAsyncResult *async_result, gpointer user_data)
 *	{
 *		gchar *authentication_uri, *token, *token_secret, *verifier;
 *		GError *error = NULL;
 *
 *		authentication_uri = gdata_oauth1_authorizer_request_authentication_uri_finish (authorizer, async_result, &token, &token_secret,
 *		                                                                                &error);
 *
 *		if (error != NULL) {
 *			/<!-- -->* Notify the user of all errors except cancellation errors *<!-- -->/
 *			if (!g_error_matches (error, G_IO_ERROR, G_IO_ERROR_CANCELLED)) {
 *				g_error ("Requesting a token failed: %s", error->message);
 *			}
 *
 *			g_error_free (error);
 *			goto finish;
 *		}
 *
 *		/<!-- -->* (Present the page at the authentication URI to the user, either in an embedded or stand-alone web browser, and
 *		 * ask them to grant access to the application and return the verifier Google gives them.) *<!-- -->/
 *		verifier = ask_user_for_verifier (authentication_uri);
 *
 *		gdata_oauth1_authorizer_request_authorization_async (authorizer, token, token_secret, verifier, cancellable,
 *		                                                     (GAsyncReadyCallback) request_authorization_cb, user_data);
 *
 *	finish:
 *		g_free (verifier);
 *		g_free (authentication_uri);
 *		g_free (token);
 *
 *		/<!-- -->* Zero out the secret before freeing. *<!-- -->/
 *		if (token_secret != NULL) {
 *			memset (token_secret, 0, strlen (token_secret));
 *		}
 *
 *		g_free (token_secret);
 *	}
 *
 *	static void
 *	request_authorization_cb (GDataOAuth1Authorizer *authorizer, GAsyncResult *async_result, gpointer user_data)
 *	{
 *		GError *error = NULL;
 *
 *		if (gdata_oauth1_authorizer_request_authorization_finish (authorizer, async_result, &error) == FALSE) {
 *			/<!-- -->* Notify the user of all errors except cancellation errors *<!-- -->/
 *			if (!g_error_matches (error, G_IO_ERROR, G_IO_ERROR_CANCELLED)) {
 *				g_error ("Authorization failed: %s", error->message);
 *			}
 *
 *			g_error_free (error);
 *			return;
 *		}
 *
 *		/<!-- -->* (The client is now authenticated and authorized against the service.
 *		 * It can now proceed to execute queries on the service object which require the user to be authenticated.) *<!-- -->/
 *	}
 *
 *	g_object_unref (service);
 *	g_object_unref (authorizer);
 *	</programlisting>
 * </example>
 *
 * Since: 0.9.0
 */

#include <config.h>
#include <string.h>
#include <glib.h>
#include <glib/gi18n-lib.h>

#ifdef ENABLE_OAUTH1
#include <oauth.h>
#endif

#include "gdata-oauth1-authorizer.h"
#include "gdata-private.h"

#define HMAC_SHA1_LEN 20 /* bytes, raw */

static void authorizer_init (GDataAuthorizerInterface *iface);
static void dispose (GObject *object);
static void finalize (GObject *object);
static void get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec);
static void set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec);

static void process_request (GDataAuthorizer *self, GDataAuthorizationDomain *domain, SoupMessage *message);
static gboolean is_authorized_for_domain (GDataAuthorizer *self, GDataAuthorizationDomain *domain);

static void sign_message (GDataOAuth1Authorizer *self, SoupMessage *message, const gchar *token, const gchar *token_secret, GHashTable *parameters);

static void notify_proxy_uri_cb (GObject *object, GParamSpec *pspec, GDataOAuth1Authorizer *self);
static void notify_timeout_cb (GObject *gobject, GParamSpec *pspec, GObject *self);

static SoupURI *_get_proxy_uri (GDataOAuth1Authorizer *self);
static void _set_proxy_uri (GDataOAuth1Authorizer *self, SoupURI *proxy_uri);

struct _GDataOAuth1AuthorizerPrivate {
	SoupSession *session;
	SoupURI *proxy_uri; /* cached version only set if gdata_oauth1_authorizer_get_proxy_uri() is called */
	GProxyResolver *proxy_resolver;

	gchar *application_name;
	gchar *locale;

	GMutex mutex; /* mutex for token, token_secret and authorization_domains */

	/* Note: This is the access token, not the request token returned by gdata_oauth1_authorizer_request_authentication_uri().
	 * It's NULL iff the authorizer isn't authenticated. token_secret must be NULL iff token is NULL. */
	gchar *token;
	GDataSecureString token_secret; /* must be allocated by _gdata_service_secure_strdup() */

	/* Mapping from GDataAuthorizationDomain to itself; a set of domains for which ->access_token is valid. */
	GHashTable *authorization_domains;
};

enum {
	PROP_APPLICATION_NAME = 1,
	PROP_LOCALE,
	PROP_PROXY_URI,
	PROP_TIMEOUT,
	PROP_PROXY_RESOLVER,
};

G_DEFINE_TYPE_WITH_CODE (GDataOAuth1Authorizer, gdata_oauth1_authorizer, G_TYPE_OBJECT,
                         G_ADD_PRIVATE (GDataOAuth1Authorizer)
                         G_IMPLEMENT_INTERFACE (GDATA_TYPE_AUTHORIZER, authorizer_init))

static void
gdata_oauth1_authorizer_class_init (GDataOAuth1AuthorizerClass *klass)
{
	GObjectClass *gobject_class = G_OBJECT_CLASS (klass);

	gobject_class->get_property = get_property;
	gobject_class->set_property = set_property;
	gobject_class->dispose = dispose;
	gobject_class->finalize = finalize;

	/**
	 * GDataOAuth1Authorizer:application-name:
	 *
	 * The human-readable, translated application name for the client, to be presented to the user on the authentication page at the URI
	 * returned by gdata_oauth1_authorizer_request_authentication_uri().
	 *
	 * If %NULL is provided in the constructor to #GDataOAuth1Authorizer, the value returned by g_get_application_name() will be used as a
	 * fallback. Note that this may also be %NULL: in this case, the authentication page will use the application name “anonymous”.
	 *
	 * Since: 0.9.0
	 */
	g_object_class_install_property (gobject_class, PROP_APPLICATION_NAME,
	                                 g_param_spec_string ("application-name",
	                                                      "Application name", "The human-readable, translated application name for the client.",
	                                                      NULL,
	                                                      G_PARAM_CONSTRUCT_ONLY | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));

	/**
	 * GDataOAuth1Authorizer:locale:
	 *
	 * The locale to use for network requests, in Unix locale format. (e.g. "en_GB", "cs", "de_DE".) Use %NULL for the default "C" locale
	 * (typically "en_US").
	 *
	 * This locale will be used by the server-side software to localise the authentication and authorization pages at the URI returned by
	 * gdata_oauth1_authorizer_request_authentication_uri().
	 *
	 * The server-side behaviour is undefined if it doesn't support a given locale.
	 *
	 * Since: 0.9.0
	 */
	g_object_class_install_property (gobject_class, PROP_LOCALE,
	                                 g_param_spec_string ("locale",
	                                                      "Locale", "The locale to use for network requests, in Unix locale format.",
	                                                      NULL,
	                                                      G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));

	/**
	 * GDataOAuth1Authorizer:proxy-uri:
	 *
	 * The proxy URI used internally for all network requests.
	 *
	 * Since: 0.9.0
	 * Deprecated: 0.15.0: Use #GDataClientLoginAuthorizer:proxy-resolver instead, which gives more flexibility over the proxy used.
	 */
	g_object_class_install_property (gobject_class, PROP_PROXY_URI,
	                                 g_param_spec_boxed ("proxy-uri",
	                                                     "Proxy URI", "The proxy URI used internally for all network requests.",
	                                                     SOUP_TYPE_URI,
	                                                     G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));

	/**
	 * GDataOAuth1Authorizer:timeout:
	 *
	 * A timeout, in seconds, for network operations. If the timeout is exceeded, the operation will be cancelled and
	 * %GDATA_SERVICE_ERROR_NETWORK_ERROR will be returned.
	 *
	 * If the timeout is <code class="literal">0</code>, operations will never time out.
	 *
	 * Since: 0.9.0
	 */
	g_object_class_install_property (gobject_class, PROP_TIMEOUT,
	                                 g_param_spec_uint ("timeout",
	                                                    "Timeout", "A timeout, in seconds, for network operations.",
	                                                    0, G_MAXUINT, 0,
	                                                    G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));

	/**
	 * GDataOAuth1Authorizer:proxy-resolver:
	 *
	 * The #GProxyResolver used to determine a proxy URI.  Setting this will clear the #GDataOAuth1Authorizer:proxy-uri property.
	 *
	 * Since: 0.15.0
	 */
	g_object_class_install_property (gobject_class, PROP_PROXY_RESOLVER,
	                                 g_param_spec_object ("proxy-resolver",
	                                                      "Proxy Resolver", "A GProxyResolver used to determine a proxy URI.",
	                                                      G_TYPE_PROXY_RESOLVER,
	                                                      G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
}

static void
authorizer_init (GDataAuthorizerInterface *iface)
{
	iface->process_request = process_request;
	iface->is_authorized_for_domain = is_authorized_for_domain;
}

static void
gdata_oauth1_authorizer_init (GDataOAuth1Authorizer *self)
{
	self->priv = gdata_oauth1_authorizer_get_instance_private (self);

	/* Set up the authorizer's mutex */
	g_mutex_init (&(self->priv->mutex));
	self->priv->authorization_domains = g_hash_table_new_full (g_direct_hash, g_direct_equal, g_object_unref, NULL);

	/* Set up the session */
	self->priv->session = _gdata_service_build_session ();

	/* Proxy the SoupSession's proxy-uri and timeout properties */
	g_signal_connect (self->priv->session, "notify::proxy-uri", (GCallback) notify_proxy_uri_cb, self);
	g_signal_connect (self->priv->session, "notify::timeout", (GCallback) notify_timeout_cb, self);

	/* Keep our GProxyResolver synchronized with SoupSession's. */
	g_object_bind_property (self->priv->session, "proxy-resolver", self, "proxy-resolver", G_BINDING_BIDIRECTIONAL | G_BINDING_SYNC_CREATE);
}

static void
dispose (GObject *object)
{
	GDataOAuth1AuthorizerPrivate *priv = GDATA_OAUTH1_AUTHORIZER (object)->priv;

	if (priv->session != NULL)
		g_object_unref (priv->session);
	priv->session = NULL;

	g_clear_object (&priv->proxy_resolver);

	/* Chain up to the parent class */
	G_OBJECT_CLASS (gdata_oauth1_authorizer_parent_class)->dispose (object);
}

static void
finalize (GObject *object)
{
	GDataOAuth1AuthorizerPrivate *priv = GDATA_OAUTH1_AUTHORIZER (object)->priv;

	g_free (priv->application_name);
	g_free (priv->locale);

	g_hash_table_destroy (priv->authorization_domains);
	g_mutex_clear (&(priv->mutex));

	if (priv->proxy_uri != NULL) {
		soup_uri_free (priv->proxy_uri);
	}

	g_free (priv->token);
	_gdata_service_secure_strfree (priv->token_secret);

	/* Chain up to the parent class */
	G_OBJECT_CLASS (gdata_oauth1_authorizer_parent_class)->finalize (object);
}

static void
get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec)
{
	GDataOAuth1AuthorizerPrivate *priv = GDATA_OAUTH1_AUTHORIZER (object)->priv;

	switch (property_id) {
		case PROP_APPLICATION_NAME:
			g_value_set_string (value, priv->application_name);
			break;
		case PROP_LOCALE:
			g_value_set_string (value, priv->locale);
			break;
		case PROP_PROXY_URI:
			g_value_set_boxed (value, _get_proxy_uri (GDATA_OAUTH1_AUTHORIZER (object)));
			break;
		case PROP_TIMEOUT:
			g_value_set_uint (value, gdata_oauth1_authorizer_get_timeout (GDATA_OAUTH1_AUTHORIZER (object)));
			break;
		case PROP_PROXY_RESOLVER:
			g_value_set_object (value, gdata_oauth1_authorizer_get_proxy_resolver (GDATA_OAUTH1_AUTHORIZER (object)));
			break;
		default:
			/* We don't have any other property... */
			G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
			break;
	}
}

static void
set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec)
{
	GDataOAuth1AuthorizerPrivate *priv = GDATA_OAUTH1_AUTHORIZER (object)->priv;

	switch (property_id) {
		/* Construct only */
		case PROP_APPLICATION_NAME:
			priv->application_name = g_value_dup_string (value);

			/* Default to the value of g_get_application_name() */
			if (priv->application_name == NULL || *(priv->application_name) == '\0') {
				g_free (priv->application_name);
				priv->application_name = g_strdup (g_get_application_name ());
			}

			break;
		case PROP_LOCALE:
			gdata_oauth1_authorizer_set_locale (GDATA_OAUTH1_AUTHORIZER (object), g_value_get_string (value));
			break;
		case PROP_PROXY_URI:
			_set_proxy_uri (GDATA_OAUTH1_AUTHORIZER (object), g_value_get_boxed (value));
			break;
		case PROP_TIMEOUT:
			gdata_oauth1_authorizer_set_timeout (GDATA_OAUTH1_AUTHORIZER (object), g_value_get_uint (value));
			break;
		case PROP_PROXY_RESOLVER:
			gdata_oauth1_authorizer_set_proxy_resolver (GDATA_OAUTH1_AUTHORIZER (object), g_value_get_object (value));
			break;
		default:
			/* We don't have any other property... */
			G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
			break;
	}
}

static void
process_request (GDataAuthorizer *self, GDataAuthorizationDomain *domain, SoupMessage *message)
{
	GDataOAuth1AuthorizerPrivate *priv = GDATA_OAUTH1_AUTHORIZER (self)->priv;

	/* Set the authorisation header */
	g_mutex_lock (&(priv->mutex));

	/* Sanity check */
	g_assert ((priv->token == NULL) == (priv->token_secret == NULL));

	if (priv->token != NULL && g_hash_table_lookup (priv->authorization_domains, domain) != NULL) {
		sign_message (GDATA_OAUTH1_AUTHORIZER (self), message, priv->token, priv->token_secret, NULL);
	}

	g_mutex_unlock (&(priv->mutex));
}

static gboolean
is_authorized_for_domain (GDataAuthorizer *self, GDataAuthorizationDomain *domain)
{
	GDataOAuth1AuthorizerPrivate *priv = GDATA_OAUTH1_AUTHORIZER (self)->priv;
	gpointer result;
	const gchar *token;

	g_mutex_lock (&(priv->mutex));
	token = priv->token;
	result = g_hash_table_lookup (priv->authorization_domains, domain);
	g_mutex_unlock (&(priv->mutex));

	/* Sanity check */
	g_assert (result == NULL || result == domain);

	return (token != NULL && result != NULL) ? TRUE : FALSE;
}

/* Sign the message and add the Authorization header to it containing the signature.
 * NOTE: This must not lock priv->mutex, as it's called from within a critical section in process_request() and priv->mutex isn't recursive. */
static void
sign_message (GDataOAuth1Authorizer *self, SoupMessage *message, const gchar *token, const gchar *token_secret, GHashTable *parameters)
{
#ifdef ENABLE_OAUTH1
	GHashTableIter iter;
	const gchar *key, *value, *consumer_key, *consumer_secret, *signature_method;
	gsize params_length = 0;
	GList *sorted_params = NULL, *i;
	GString *query_string, *signature_base_string, *secret_string, *authorization_header;
	SoupURI *normalised_uri;
	gchar *uri, *signature, *timestamp;
	char *nonce;
	gboolean is_first = TRUE;
	gint64 time_val;
	guchar signature_buf[HMAC_SHA1_LEN];
	gsize signature_buf_len;
	GHmac *signature_hmac;

	g_return_if_fail (GDATA_IS_OAUTH1_AUTHORIZER (self));
	g_return_if_fail (SOUP_IS_MESSAGE (message));
	g_return_if_fail (token == NULL || *token != '\0');
	g_return_if_fail (token_secret == NULL || *token_secret != '\0');
	g_return_if_fail ((token == NULL) == (token_secret == NULL));

	/* Build and return a HMAC-SHA1 signature for the given SoupMessage. We always use HMAC-SHA1, since installed applications have to be
	 * unregistered (see: http://code.google.com/apis/accounts/docs/OAuth_ref.html#SigningOAuth).
	 * Reference: http://tools.ietf.org/html/rfc5849#section-3.4 */
	signature_method = "HMAC-SHA1";

	/* As described here, we use an anonymous consumer key and secret, since we're designed for installed applications:
	 * http://code.google.com/apis/accounts/docs/OAuth_ref.html#SigningOAuth */
	consumer_key = "anonymous";
	consumer_secret = "anonymous";

	/* Add various standard parameters to the list (note: this modifies the hash table belonging to the caller) */
	nonce = oauth_gen_nonce ();
	time_val = g_get_real_time () / G_USEC_PER_SEC;
	timestamp = g_strdup_printf ("%li", time_val);

	if (parameters == NULL) {
		parameters = g_hash_table_new (g_str_hash, g_str_equal);
	} else {
		g_hash_table_ref (parameters);
	}

	g_hash_table_insert (parameters, (gpointer) "oauth_signature_method", (gpointer) signature_method);
	g_hash_table_insert (parameters, (gpointer) "oauth_consumer_key", (gpointer) consumer_key);
	g_hash_table_insert (parameters, (gpointer) "oauth_nonce", nonce);
	g_hash_table_insert (parameters, (gpointer) "oauth_timestamp", timestamp);
	g_hash_table_insert (parameters, (gpointer) "oauth_version", (gpointer) "1.0");

	/* Only add the token if it's been provided */
	if (token != NULL) {
		g_hash_table_insert (parameters, (gpointer) "oauth_token", (gpointer) token);
	}

	/* Sort the parameters and build a query string, as defined here: http://tools.ietf.org/html/rfc5849#section-3.4.1.3 */
	g_hash_table_iter_init (&iter, parameters);

	while (g_hash_table_iter_next (&iter, (gpointer*) &key, (gpointer*) &value) == TRUE) {
		GString *pair = g_string_new (NULL);

		g_string_append_uri_escaped (pair, key, NULL, FALSE);
		g_string_append_c (pair, '=');
		g_string_append_uri_escaped (pair, value, NULL, FALSE);

		/* Append the pair to the list for sorting, and keep track of the total length of the strings in the list so far */
		params_length += pair->len + 1 /* sep */;
		sorted_params = g_list_prepend (sorted_params, g_string_free (pair, FALSE));
	}

	g_hash_table_unref (parameters);

	sorted_params = g_list_sort (sorted_params, (GCompareFunc) g_strcmp0);

	/* Concatenate the parameters to give the query string */
	query_string = g_string_sized_new (params_length);

	for (i = sorted_params; i != NULL; i = i->next) {
		if (is_first == FALSE) {
			g_string_append_c (query_string, '&');
		}

		g_string_append (query_string, i->data);

		g_free (i->data);
		is_first = FALSE;
	}

	g_list_free (sorted_params);

	/* Normalise the URI as described here: http://tools.ietf.org/html/rfc5849#section-3.4.1.2 */
	normalised_uri = soup_uri_copy (soup_message_get_uri (message));
	soup_uri_set_query (normalised_uri, NULL);
	soup_uri_set_fragment (normalised_uri, NULL);

	/* Append it to the signature base string */
	uri = soup_uri_to_string (normalised_uri, FALSE);

	/* Start building the signature base string as described here: http://tools.ietf.org/html/rfc5849#section-3.4.1.1 */
	signature_base_string = g_string_sized_new (4 /* method */ + 1 /* sep */ + strlen (uri) + 1 /* sep */ + params_length /* query string */);
	g_string_append_uri_escaped (signature_base_string, message->method, NULL, FALSE);
	g_string_append_c (signature_base_string, '&');
	g_string_append_uri_escaped (signature_base_string, uri, NULL, FALSE);
	g_string_append_c (signature_base_string, '&');
	g_string_append_uri_escaped (signature_base_string, query_string->str, NULL, FALSE);

	g_free (uri);
	soup_uri_free (normalised_uri);
	g_string_free (query_string, TRUE);

	/* Build the secret key to use in the HMAC */
	secret_string = g_string_new (NULL);
	g_string_append_uri_escaped (secret_string, consumer_secret, NULL, FALSE);
	g_string_append_c (secret_string, '&');

	/* Only add token_secret if it was provided */
	if (token_secret != NULL) {
		g_string_append_uri_escaped (secret_string, token_secret, NULL, FALSE);
	}

	/* Create the signature as described here: http://tools.ietf.org/html/rfc5849#section-3.4.2 */
	signature_hmac = g_hmac_new (G_CHECKSUM_SHA1, (const guchar*) secret_string->str, secret_string->len);
	g_hmac_update (signature_hmac, (const guchar*) signature_base_string->str, signature_base_string->len);

	signature_buf_len = G_N_ELEMENTS (signature_buf);
	g_hmac_get_digest (signature_hmac, signature_buf, &signature_buf_len);

	g_hmac_unref (signature_hmac);

	signature = g_base64_encode (signature_buf, signature_buf_len);

	/*g_debug ("Signing message using Signature Base String: “%s” and key “%s” using method “%s” to give signature: “%s”.",
	         signature_base_string->str, secret_string->str, signature_method, signature);*/

	/* Zero out the secret_string before freeing it, to reduce the chance of secrets hitting disk. */
	memset (secret_string->str, 0, secret_string->allocated_len);

	g_string_free (secret_string, TRUE);
	g_string_free (signature_base_string, TRUE);

	/* Build the Authorization header and append it to the message */
	authorization_header = g_string_new ("OAuth oauth_consumer_key=\"");
	g_string_append_uri_escaped (authorization_header, consumer_key, NULL, FALSE);

	/* Only add the token if it's been provided */
	if (token != NULL) {
		g_string_append (authorization_header, "\",oauth_token=\"");
		g_string_append_uri_escaped (authorization_header, token, NULL, FALSE);
	}

	g_string_append (authorization_header, "\",oauth_signature_method=\"");
	g_string_append_uri_escaped (authorization_header, signature_method, NULL, FALSE);
	g_string_append (authorization_header, "\",oauth_signature=\"");
	g_string_append_uri_escaped (authorization_header, signature, NULL, FALSE);
	g_string_append (authorization_header, "\",oauth_timestamp=\"");
	g_string_append_uri_escaped (authorization_header, timestamp, NULL, FALSE);
	g_string_append (authorization_header, "\",oauth_nonce=\"");
	g_string_append_uri_escaped (authorization_header, nonce, NULL, FALSE);
	g_string_append (authorization_header, "\",oauth_version=\"1.0\"");

	soup_message_headers_replace (message->request_headers, "Authorization", authorization_header->str);

	g_string_free (authorization_header, TRUE);
	free (signature);
	g_free (timestamp);
	free (nonce);
#endif  /* ENABLE_OAUTH1 */
}

/**
 * gdata_oauth1_authorizer_new:
 * @application_name: (allow-none): a human-readable, translated application name to use on authentication pages, or %NULL
 * @service_type: the #GType of a #GDataService subclass which the #GDataOAuth1Authorizer will be used with
 *
 * Creates a new #GDataOAuth1Authorizer.
 *
 * The #GDataAuthorizationDomains for the given @service_type (i.e. as returned by gdata_service_get_authorization_domains()) are the ones the
 * user will be requested to authorize access to on the page at the URI returned by gdata_oauth1_authorizer_request_authentication_uri().
 *
 * The given @application_name will set the value of #GDataOAuth1Authorizer:application-name and will be displayed to the user on authentication pages
 * returned by Google. If %NULL is provided, the value of g_get_application_name() will be used as a fallback.
 *
 * Return value: (transfer full): a new #GDataOAuth1Authorizer; unref with g_object_unref()
 *
 * Since: 0.9.0
 */
GDataOAuth1Authorizer *
gdata_oauth1_authorizer_new (const gchar *application_name, GType service_type)
{
	g_return_val_if_fail (g_type_is_a (service_type, GDATA_TYPE_SERVICE), NULL);

	return gdata_oauth1_authorizer_new_for_authorization_domains (application_name, gdata_service_get_authorization_domains (service_type));
}

/**
 * gdata_oauth1_authorizer_new_for_authorization_domains:
 * @application_name: (allow-none): a human-readable, translated application name to use on authentication pages, or %NULL
 * @authorization_domains: (element-type GDataAuthorizationDomain) (transfer none): a non-empty list of #GDataAuthorizationDomains to be
 * authorized against by the #GDataOAuth1Authorizer
 *
 * Creates a new #GDataOAuth1Authorizer. This function is intended to be used only when the default authorization domain list for a single
 * #GDataService, as used by gdata_oauth1_authorizer_new(), isn't suitable. For example, this could be because the #GDataOAuth1Authorizer will be used
 * with multiple #GDataService subclasses, or because the client requires a specific set of authorization domains.
 *
 * The specified #GDataAuthorizationDomains are the ones the user will be requested to authorize access to on the page at the URI returned by
 * gdata_oauth1_authorizer_request_authentication_uri().
 *
 * The given @application_name will set the value of #GDataOAuth1Authorizer:application-name and will be displayed to the user on authentication pages
 * returned by Google. If %NULL is provided, the value of g_get_application_name() will be used as a fallback.
 *
 * Return value: (transfer full): a new #GDataOAuth1Authorizer; unref with g_object_unref()
 *
 * Since: 0.9.0
 */
GDataOAuth1Authorizer *
gdata_oauth1_authorizer_new_for_authorization_domains (const gchar *application_name, GList *authorization_domains)
{
	GList *i;
	GDataOAuth1Authorizer *authorizer;

	g_return_val_if_fail (authorization_domains != NULL, NULL);

	authorizer = GDATA_OAUTH1_AUTHORIZER (g_object_new (GDATA_TYPE_OAUTH1_AUTHORIZER,
	                                                    "application-name", application_name,
	                                                    NULL));

	/* Register all the domains with the authorizer */
	for (i = authorization_domains; i != NULL; i = i->next) {
		g_return_val_if_fail (GDATA_IS_AUTHORIZATION_DOMAIN (i->data), NULL);

		/* We don't have to lock the authoriser's mutex here as no other code has seen the authoriser yet */
		g_hash_table_insert (authorizer->priv->authorization_domains, g_object_ref (GDATA_AUTHORIZATION_DOMAIN (i->data)), i->data);
	}

	return authorizer;
}

/**
 * gdata_oauth1_authorizer_request_authentication_uri:
 * @self: a #GDataOAuth1Authorizer
 * @token: (out callee-allocates): return location for the temporary credentials token returned by the authentication service; free with g_free()
 * @token_secret: (out callee-allocates): return location for the temporary credentials token secret returned by the authentication service; free with
 * g_free()
 * @cancellable: (allow-none): optional #GCancellable object, or %NULL
 * @error: a #GError, or %NULL
 *
 * Requests a fresh unauthenticated token from the Google accounts service and builds and returns the URI of an authentication page for that token.
 * This should then be presented to the user (e.g. in an embedded or stand alone web browser). The authentication page will ask the user to log in
 * using their Google account, then ask them to grant access to the #GDataAuthorizationDomains passed to the constructor of the
 * #GDataOAuth1Authorizer. If the user grants access, they will be given a verifier, which can then be passed to
 * gdata_oauth1_authorizer_request_authorization() (along with the @token and @token_secret values returned by this method) to authorize the token.
 *
 * This method can fail if the server returns an error, but this is unlikely. If it does happen, a %GDATA_SERVICE_ERROR_PROTOCOL_ERROR will be
 * raised, @token and @token_secret will be set to %NULL and %NULL will be returned.
 *
 * This method implements <ulink type="http" url="http://tools.ietf.org/html/rfc5849#section-2.1">Section 2.1</ulink> and
 * <ulink type="http" url="http://tools.ietf.org/html/rfc5849#section-2.2">Section 2.2</ulink> of the
 * <ulink type="http" url="http://tools.ietf.org/html/rfc5849">OAuth 1.0 protocol</ulink>.
 *
 * When freeing @token_secret, it's advisable to set it to all zeros first, to reduce the chance of the sensitive token being recoverable from the
 * free memory pool and (accidentally) leaked by a different part of the process. This can be achieved with the following code:
 * |[
 *	if (token_secret != NULL) {
 *		memset (token_secret, 0, strlen (token_secret));
 *		g_free (token_secret);
 *	}
 * ]|
 *
 * Return value: (transfer full): the URI of an authentication page for the user to use; free with g_free()
 *
 * Since: 0.9.0
 */
gchar *
gdata_oauth1_authorizer_request_authentication_uri (GDataOAuth1Authorizer *self, gchar **token, gchar **token_secret,
                                                    GCancellable *cancellable, GError **error)
{
#ifdef ENABLE_OAUTH1
	GDataOAuth1AuthorizerPrivate *priv;
	SoupMessage *message;
	guint status;
	gchar *request_body;
	GString *scope_string, *authentication_uri;
	GHashTable *parameters;
	GHashTableIter iter;
	gboolean is_first = TRUE;
	GDataAuthorizationDomain *domain;
	GHashTable *response_details;
	const gchar *callback_uri, *_token, *_token_secret, *callback_confirmed;
	SoupURI *_uri;
#endif

	g_return_val_if_fail (GDATA_IS_OAUTH1_AUTHORIZER (self), NULL);
	g_return_val_if_fail (token != NULL, NULL);
	g_return_val_if_fail (token_secret != NULL, NULL);
	g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), NULL);
	g_return_val_if_fail (error == NULL || *error == NULL, NULL);

#ifdef ENABLE_OAUTH1
	priv = self->priv;

	/* This implements OAuthGetRequestToken and returns the URI for OAuthAuthorizeToken, which the client must then use themselves (e.g. in an
	 * embedded web browser) to authorise the temporary credentials token. They then pass the request token and verification code they get back
	 * from that to gdata_oauth1_authorizer_request_authorization(). */

	/* We default to out-of-band callbacks */
	callback_uri = "oob";

	/* Set the output parameters to NULL in case of failure */
	*token = NULL;
	*token_secret = NULL;

	/* Build up the space-separated list of scopes we're requesting authorisation for */
	g_mutex_lock (&(priv->mutex));

	scope_string = g_string_new (NULL);
	g_hash_table_iter_init (&iter, priv->authorization_domains);

	while (g_hash_table_iter_next (&iter, (gpointer*) &domain, NULL) == TRUE) {
		if (is_first == FALSE) {
			/* Delimiter */
			g_string_append_c (scope_string, ' ');
		}

		g_string_append (scope_string, gdata_authorization_domain_get_scope (domain));

		is_first = FALSE;
	}

	g_mutex_unlock (&(priv->mutex));

	/* Build the request body and the set of parameters to be signed */
	parameters = g_hash_table_new (g_str_hash, g_str_equal);
	g_hash_table_insert (parameters, (gpointer) "scope", scope_string->str);
	g_hash_table_insert (parameters, (gpointer) "xoauth_displayname", priv->application_name);
	g_hash_table_insert (parameters, (gpointer) "oauth_callback", (gpointer) callback_uri);
	request_body = soup_form_encode_hash (parameters);

	/* Build the message */
	_uri = soup_uri_new ("https://www.google.com/accounts/OAuthGetRequestToken");
	soup_uri_set_port (_uri, _gdata_service_get_https_port ());
	message = soup_message_new_from_uri (SOUP_METHOD_POST, _uri);
	soup_uri_free (_uri);

	soup_message_set_request (message, "application/x-www-form-urlencoded", SOUP_MEMORY_TAKE, request_body, strlen (request_body));

	sign_message (self, message, NULL, NULL, parameters);

	g_hash_table_destroy (parameters);
	g_string_free (scope_string, TRUE);

	/* Send the message */
	_gdata_service_actually_send_message (priv->session, message, cancellable, error);
	status = message->status_code;

	if (status == SOUP_STATUS_CANCELLED) {
		/* Cancelled (the error has already been set) */
		g_object_unref (message);
		return NULL;
	} else if (status != SOUP_STATUS_OK) {
		/* Server returned an error. Not much we can do, since the error codes aren't documented and it shouldn't normally ever happen
		 * anyway. */
		g_set_error_literal (error, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_PROTOCOL_ERROR,
		                     _("The server rejected the temporary credentials request."));
		g_object_unref (message);

		return NULL;
	}

	g_assert (message->response_body->data != NULL);

	/* Parse the response. We expect something like:
	 *   oauth_token=ab3cd9j4ks73hf7g&oauth_token_secret=ZXhhbXBsZS5jb20&oauth_callback_confirmed=true
	 * See: http://code.google.com/apis/accounts/docs/OAuth_ref.html#RequestToken and
	 * http://tools.ietf.org/html/rfc5849#section-2.1 for details. */
	response_details = soup_form_decode (message->response_body->data);

	g_object_unref (message);

	_token = g_hash_table_lookup (response_details, "oauth_token");
	_token_secret = g_hash_table_lookup (response_details, "oauth_token_secret");
	callback_confirmed = g_hash_table_lookup (response_details, "oauth_callback_confirmed");

	/* Validate the returned values */
	if (_token == NULL || _token_secret == NULL || callback_confirmed == NULL ||
	    *_token == '\0' || *_token_secret == '\0' ||
	    strcmp (callback_confirmed, "true") != 0) {
		g_set_error_literal (error, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_PROTOCOL_ERROR,
		                     _("The server returned a malformed response."));
		g_hash_table_destroy (response_details);

		return NULL;
	}

	/* Build the authentication URI which the user will then open in a web browser and use to authenticate and authorise our application.
	 * We expect to build something like this:
	 *   https://www.google.com/accounts/OAuthAuthorizeToken?oauth_token=ab3cd9j4ks73hf7g&hd=mycollege.edu&hl=en&btmpl=mobile
	 * See: http://code.google.com/apis/accounts/docs/OAuth_ref.html#GetAuth for more details. */
	authentication_uri = g_string_new ("https://www.google.com/accounts/OAuthAuthorizeToken?oauth_token=");
	g_string_append_uri_escaped (authentication_uri, g_hash_table_lookup (response_details, "oauth_token"), NULL, TRUE);

	if (priv->locale != NULL) {
		g_string_append (authentication_uri, "&hl=");
		g_string_append_uri_escaped (authentication_uri, priv->locale, NULL, TRUE);
	}

	/* Return the token and token secret */
	*token = g_strdup (_token);
	*token_secret = g_strdup (_token_secret); /* NOTE: Ideally this would be allocated in non-pageable memory, but changing that would break API */

	g_hash_table_destroy (response_details);

	return g_string_free (authentication_uri, FALSE);
#else  /* if !ENABLE_OAUTH1 */
	*token = NULL;
	*token_secret = NULL;

	if (!g_cancellable_set_error_if_cancelled (cancellable, error))
		g_set_error_literal (error, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_UNAVAILABLE,
		                     _("OAuth 1.0 support is disabled."));

	return NULL;
#endif
}

typedef struct {
	/* All return values */
	gchar *token;
	gchar *token_secret; /* NOTE: Ideally this would be allocated in non-pageable memory, but changing that would break API */
	gchar *authentication_uri;
} RequestAuthenticationUriAsyncData;

static void
request_authentication_uri_async_data_free (RequestAuthenticationUriAsyncData *data)
{
	g_free (data->token);
	g_free (data->token_secret);
	g_free (data->authentication_uri);

	g_slice_free (RequestAuthenticationUriAsyncData, data);
}

G_DEFINE_AUTOPTR_CLEANUP_FUNC (RequestAuthenticationUriAsyncData, request_authentication_uri_async_data_free)

static void
request_authentication_uri_thread (GTask *task, gpointer source_object, gpointer task_data, GCancellable *cancellable)
{
	GDataOAuth1Authorizer *authorizer = GDATA_OAUTH1_AUTHORIZER (source_object);
	g_autoptr(RequestAuthenticationUriAsyncData) data = NULL;
	g_autoptr(GError) error = NULL;

	data = g_slice_new0 (RequestAuthenticationUriAsyncData);
	data->authentication_uri = gdata_oauth1_authorizer_request_authentication_uri (authorizer, &(data->token), &(data->token_secret),
	                                                                               cancellable, &error);

	if (error != NULL)
		g_task_return_error (task, g_steal_pointer (&error));
	else
		g_task_return_pointer (task, g_steal_pointer (&data), (GDestroyNotify) request_authentication_uri_async_data_free);
}

/**
 * gdata_oauth1_authorizer_request_authentication_uri_async:
 * @self: a #GDataOAuth1Authorizer
 * @cancellable: (allow-none): optional #GCancellable object, or %NULL
 * @callback: a #GAsyncReadyCallback to call when building the URI is finished
 * @user_data: (closure): data to pass to the @callback function
 *
 * Requests a fresh unauthenticated token from the Google accounts service and builds and returns the URI of an authentication page for that token.
 * @self is reffed when this method is called, so can safely be unreffed after this method returns.
 *
 * For more details, see gdata_oauth1_authorizer_request_authentication_uri(), which is the synchronous version of this method.
 *
 * When the operation is finished, @callback will be called. You can then call gdata_oauth1_authorizer_request_authentication_uri_finish() to get the
 * results of the operation.
 *
 * Since: 0.9.0
 */
void
gdata_oauth1_authorizer_request_authentication_uri_async (GDataOAuth1Authorizer *self, GCancellable *cancellable,
                                                          GAsyncReadyCallback callback, gpointer user_data)
{
	g_autoptr(GTask) task = NULL;

	g_return_if_fail (GDATA_IS_OAUTH1_AUTHORIZER (self));
	g_return_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable));
	g_return_if_fail (callback != NULL);

	task = g_task_new (self, cancellable, callback, user_data);
	g_task_set_source_tag (task, gdata_oauth1_authorizer_request_authentication_uri_async);
	g_task_run_in_thread (task, request_authentication_uri_thread);
}

/**
 * gdata_oauth1_authorizer_request_authentication_uri_finish:
 * @self: a #GDataOAuth1Authorizer
 * @async_result: a #GAsyncResult
 * @token: (out callee-allocates): return location for the temporary credentials token returned by the authentication service; free with g_free()
 * @token_secret: (out callee-allocates): return location for the temporary credentials token secret returned by the authentication service; free with
 * g_free()
 * @error: a #GError, or %NULL
 *
 * Finishes an asynchronous authentication URI building operation started with gdata_oauth1_authorizer_request_authentication_uri_async().
 *
 * This method can fail if the server has returned an error, but this is unlikely. If it does happen, a %GDATA_SERVICE_ERROR_PROTOCOL_ERROR will be
 * raised, @token and @token_secret will be set to %NULL and %NULL will be returned.
 *
 * When freeing @token_secret, it's advisable to set it to all zeros first, to reduce the chance of the sensitive token being recoverable from the
 * free memory pool and (accidentally) leaked by a different part of the process. This can be achieved with the following code:
 * |[
 *	if (token_secret != NULL) {
 *		memset (token_secret, 0, strlen (token_secret));
 *		g_free (token_secret);
 *	}
 * ]|
 *
 * Return value: (transfer full): the URI of an authentication page for the user to use; free with g_free()
 *
 * Since: 0.9.0
 */
gchar *
gdata_oauth1_authorizer_request_authentication_uri_finish (GDataOAuth1Authorizer *self, GAsyncResult *async_result, gchar **token,
                                                           gchar **token_secret, GError **error)
{
	g_autoptr(RequestAuthenticationUriAsyncData) data = NULL;

	g_return_val_if_fail (GDATA_IS_OAUTH1_AUTHORIZER (self), NULL);
	g_return_val_if_fail (G_IS_ASYNC_RESULT (async_result), NULL);
	g_return_val_if_fail (token != NULL, NULL);
	g_return_val_if_fail (token_secret != NULL, NULL);
	g_return_val_if_fail (error == NULL || *error == NULL, NULL);
	g_return_val_if_fail (g_task_is_valid (async_result, self), NULL);
	g_return_val_if_fail (g_async_result_is_tagged (async_result, gdata_oauth1_authorizer_request_authentication_uri_async), NULL);

	data = g_task_propagate_pointer (G_TASK (async_result), error);

	if (data == NULL) {
		/* Return the error and set all of the output parameters to NULL */
		*token = NULL;
		*token_secret = NULL;

		return NULL;
	}

	/* Success! Transfer the output to the appropriate parameters and nullify it so it doesn't get freed when the async result gets finalised */
	*token = g_steal_pointer (&data->token);
	*token_secret = g_steal_pointer (&data->token_secret);

	return g_steal_pointer (&data->authentication_uri);
}

/**
 * gdata_oauth1_authorizer_request_authorization:
 * @self: a #GDataOAuth1Authorizer
 * @token: the request token returned by gdata_oauth1_authorizer_request_authentication_uri()
 * @token_secret: the request token secret returned by gdata_oauth1_authorizer_request_authentication_uri()
 * @verifier: the verifier entered by the user from the authentication page
 * @cancellable: (allow-none): optional #GCancellable object, or %NULL
 * @error: a #GError, or %NULL
 *
 * Requests authorization of the given request @token from the Google accounts service using the given @verifier as entered by the user from the
 * authentication page at the URI returned by gdata_oauth1_authorizer_request_authentication_uri(). @token and @token_secret must be the same values
 * as were returned by gdata_oauth1_authorizer_request_authentication_uri() if it was successful.
 *
 * If the verifier is valid (i.e. the user granted access to the application and the Google accounts service has no reason to distrust the client),
 * %TRUE will be returned and any operations performed from that point onwards on #GDataServices using this #GDataAuthorizer will be
 * authorized.
 *
 * If the user denies access to the application or the Google accounts service distrusts it, a bogus verifier could be returned. In this case, %FALSE
 * will be returned and a %GDATA_SERVICE_ERROR_FORBIDDEN error will be raised.
 *
 * Note that if the user denies access to the application, it may be the case that they have no verifier to enter. In this case, the client can simply
 * not call this method. The #GDataOAuth1Authorizer stores no state for authentication operations which have succeeded in calling
 * gdata_oauth1_authorizer_request_authentication_uri() but not yet successfully called gdata_oauth1_authorizer_request_authorization().
 *
 * This method implements <ulink type="http" url="http://tools.ietf.org/html/rfc5849#section-2.3">Section 2.3</ulink> of the
 * <ulink type="http" url="http://tools.ietf.org/html/rfc5849">OAuth 1.0 protocol</ulink>.
 *
 * Return value: %TRUE if authorization was successful, %FALSE otherwise
 *
 * Since: 0.9.0
 */
gboolean
gdata_oauth1_authorizer_request_authorization (GDataOAuth1Authorizer *self, const gchar *token, const gchar *token_secret, const gchar *verifier,
                                               GCancellable *cancellable, GError **error)
{
#ifdef ENABLE_OAUTH1
	GDataOAuth1AuthorizerPrivate *priv;
	SoupMessage *message;
	guint status;
	gchar *request_body;
	GHashTable *parameters;
	GHashTable *response_details;
	const gchar *_token, *_token_secret;
	SoupURI *_uri;
#endif

	g_return_val_if_fail (GDATA_IS_OAUTH1_AUTHORIZER (self), FALSE);
	g_return_val_if_fail (token != NULL && *token != '\0', FALSE);
	g_return_val_if_fail (token_secret != NULL && *token_secret != '\0', FALSE);
	g_return_val_if_fail (verifier != NULL && *verifier != '\0', FALSE);
	g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), FALSE);
	g_return_val_if_fail (error == NULL || *error == NULL, FALSE);

#ifdef ENABLE_OAUTH1
	/* This implements OAuthGetAccessToken using the request token returned by OAuthGetRequestToken and the verification code returned by
	 * OAuthAuthorizeToken. See:
	 *  • http://code.google.com/apis/accounts/docs/OAuth_ref.html#AccessToken
	 *  • http://tools.ietf.org/html/rfc5849#section-2.3
	 */

	priv = self->priv;

	/* Build the request body and the set of parameters to be signed */
	parameters = g_hash_table_new (g_str_hash, g_str_equal);
	g_hash_table_insert (parameters, (gpointer) "oauth_verifier", (gpointer) verifier);
	request_body = soup_form_encode_hash (parameters);

	/* Build the message */
	_uri = soup_uri_new ("https://www.google.com/accounts/OAuthGetAccessToken");
	soup_uri_set_port (_uri, _gdata_service_get_https_port ());
	message = soup_message_new_from_uri (SOUP_METHOD_POST, _uri);
	soup_uri_free (_uri);
	soup_message_set_request (message, "application/x-www-form-urlencoded", SOUP_MEMORY_TAKE, request_body, strlen (request_body));

	sign_message (self, message, token, token_secret, parameters);

	g_hash_table_destroy (parameters);

	/* Send the message */
	_gdata_service_actually_send_message (priv->session, message, cancellable, error);
	status = message->status_code;

	if (status == SOUP_STATUS_CANCELLED) {
		/* Cancelled (the error has already been set) */
		g_object_unref (message);
		return FALSE;
	} else if (status != SOUP_STATUS_OK) {
		/* Server returned an error. This either means that there was a server error or, more likely, the server doesn't trust the client
		 * or the user denied authorization to the token on the authorization web page. */
		g_set_error_literal (error, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_FORBIDDEN, _("Access was denied by the user or server."));
		g_object_unref (message);

		return FALSE;
	}

	g_assert (message->response_body->data != NULL);

	/* Parse the response. We expect something like:
	 *   oauth_token=ab3cd9j4ks73hf7g&oauth_token_secret=ZXhhbXBsZS5jb20&oauth_callback_confirmed=true
	 * See: http://code.google.com/apis/accounts/docs/OAuth_ref.html#AccessToken and
	 * http://tools.ietf.org/html/rfc5849#section-2.3 for details. */
	response_details = soup_form_decode (message->response_body->data);

	/* Zero out the response body to lower the chance of it (with all the auth. tokens it contains) hitting disk or getting leaked in
	 * free memory. */
	memset ((void*) message->response_body->data, 0, message->response_body->length);

	g_object_unref (message);

	_token = g_hash_table_lookup (response_details, "oauth_token");
	_token_secret = g_hash_table_lookup (response_details, "oauth_token_secret");

	/* Validate the returned values */
	if (_token == NULL || _token_secret == NULL ||
	    *_token == '\0' || *_token_secret == '\0') {
		g_set_error_literal (error, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_PROTOCOL_ERROR, _("The server returned a malformed response."));
		g_hash_table_destroy (response_details);

		return FALSE;
	}

	/* Store the token and token secret in the authoriser */
	g_mutex_lock (&(priv->mutex));

	g_free (priv->token);
	priv->token = g_strdup (_token);

	_gdata_service_secure_strfree (priv->token_secret);
	priv->token_secret = _gdata_service_secure_strdup (_token_secret);

	g_mutex_unlock (&(priv->mutex));

	/* Zero out the secret token before freeing the hash table, to reduce the chance of it hitting disk later. */
	memset ((void*) _token_secret, 0, strlen (_token_secret));

	g_hash_table_destroy (response_details);

	return TRUE;
#else  /* if !ENABLE_OAUTH1 */
	if (!g_cancellable_set_error_if_cancelled (cancellable, error))
		g_set_error_literal (error, GDATA_SERVICE_ERROR, GDATA_SERVICE_ERROR_UNAVAILABLE,
		                     _("OAuth 1.0 support is disabled."));

	return FALSE;
#endif
}

typedef struct {
	/* Input */
	gchar *token;
	GDataSecureString token_secret; /* must be allocated by _gdata_service_secure_strdup() */
	gchar *verifier;
} RequestAuthorizationAsyncData;

static void
request_authorization_async_data_free (RequestAuthorizationAsyncData *data)
{
	g_free (data->token);
	_gdata_service_secure_strfree (data->token_secret);
	g_free (data->verifier);

	g_slice_free (RequestAuthorizationAsyncData, data);
}

static void
request_authorization_thread (GTask *task, gpointer source_object, gpointer task_data, GCancellable *cancellable)
{
	GDataOAuth1Authorizer *authorizer = GDATA_OAUTH1_AUTHORIZER (source_object);
	RequestAuthorizationAsyncData *data = task_data;
	g_autoptr(GError) error = NULL;

	if (!gdata_oauth1_authorizer_request_authorization (authorizer, data->token, data->token_secret, data->verifier, cancellable, &error))
		g_task_return_error (task, g_steal_pointer (&error));
	else
		g_task_return_boolean (task, TRUE);
}

/**
 * gdata_oauth1_authorizer_request_authorization_async:
 * @self: a #GDataOAuth1Authorizer
 * @token: the request token returned by gdata_oauth1_authorizer_request_authentication_uri()
 * @token_secret: the request token secret returned by gdata_oauth1_authorizer_request_authentication_uri()
 * @verifier: the verifier entered by the user from the authentication page
 * @cancellable: (allow-none): an optional #GCancellable, or %NULL
 * @callback: a #GAsyncReadyCallback to call when authorization is finished
 * @user_data: (closure): data to pass to the @callback function
 *
 * Requests authorization of the given request @token from the Google accounts service using the given @verifier as entered by the user.
 * @self, @token, @token_secret and @verifier are reffed/copied when this method is called, so can safely be freed after this method returns.
 *
 * For more details, see gdata_oauth1_authorizer_request_authorization(), which is the synchronous version of this method.
 *
 * When the operation is finished, @callback will be called. You can then call gdata_oauth1_authorizer_request_authorization_finish() to get the
 * results of the operation.
 *
 * Since: 0.9.0
 */
void
gdata_oauth1_authorizer_request_authorization_async (GDataOAuth1Authorizer *self, const gchar *token, const gchar *token_secret,
                                                     const gchar *verifier,
                                                     GCancellable *cancellable, GAsyncReadyCallback callback, gpointer user_data)
{
	g_autoptr(GTask) task = NULL;
	RequestAuthorizationAsyncData *data;

	g_return_if_fail (GDATA_IS_OAUTH1_AUTHORIZER (self));
	g_return_if_fail (token != NULL && *token != '\0');
	g_return_if_fail (token_secret != NULL && *token_secret != '\0');
	g_return_if_fail (verifier != NULL && *verifier != '\0');
	g_return_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable));

	data = g_slice_new (RequestAuthorizationAsyncData);
	data->token = g_strdup (token);
	data->token_secret = _gdata_service_secure_strdup (token_secret);
	data->verifier = g_strdup (verifier);

	task = g_task_new (self, cancellable, callback, user_data);
	g_task_set_source_tag (task, gdata_oauth1_authorizer_request_authorization_async);
	g_task_set_task_data (task, g_steal_pointer (&data), (GDestroyNotify) request_authorization_async_data_free);
	g_task_run_in_thread (task, request_authorization_thread);
}

/**
 * gdata_oauth1_authorizer_request_authorization_finish:
 * @self: a #GDataOAuth1Authorizer
 * @async_result: a #GAsyncResult
 * @error: a #GError, or %NULL
 *
 * Finishes an asynchronous authorization operation started with gdata_oauth1_authorizer_request_authorization_async().
 *
 * Return value: %TRUE if authorization was successful, %FALSE otherwise
 *
 * Since: 0.9.0
 */
gboolean
gdata_oauth1_authorizer_request_authorization_finish (GDataOAuth1Authorizer *self, GAsyncResult *async_result, GError **error)
{
	g_return_val_if_fail (GDATA_IS_OAUTH1_AUTHORIZER (self), FALSE);
	g_return_val_if_fail (G_IS_ASYNC_RESULT (async_result), FALSE);
	g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
	g_return_val_if_fail (g_task_is_valid (async_result, self), FALSE);
	g_return_val_if_fail (g_async_result_is_tagged (async_result, gdata_oauth1_authorizer_request_authorization_async), FALSE);

	return g_task_propagate_boolean (G_TASK (async_result), error);
}

/**
 * gdata_oauth1_authorizer_get_application_name:
 * @self: a #GDataOAuth1Authorizer
 *
 * Returns the application name being used on the authentication page at the URI returned by gdata_oauth1_authorizer_request_authentication_uri();
 * i.e. the value of #GDataOAuth1Authorizer:application-name.
 *
 * Return value: (allow-none): the application name, or %NULL if one isn't set
 *
 * Since: 0.9.0
 */
const gchar *
gdata_oauth1_authorizer_get_application_name (GDataOAuth1Authorizer *self)
{
	g_return_val_if_fail (GDATA_IS_OAUTH1_AUTHORIZER (self), NULL);
	return self->priv->application_name;
}

/**
 * gdata_oauth1_authorizer_get_locale:
 * @self: a #GDataOAuth1Authorizer
 *
 * Returns the locale currently being used for network requests, or %NULL if the locale is the default.
 *
 * Return value: (allow-none): the current locale
 *
 * Since: 0.9.0
 */
const gchar *
gdata_oauth1_authorizer_get_locale (GDataOAuth1Authorizer *self)
{
	g_return_val_if_fail (GDATA_IS_OAUTH1_AUTHORIZER (self), NULL);
	return self->priv->locale;
}

/**
 * gdata_oauth1_authorizer_set_locale:
 * @self: a #GDataOAuth1Authorizer
 * @locale: (allow-none): the new locale in Unix locale format, or %NULL for the default locale
 *
 * Set the locale used for network requests to @locale, given in standard Unix locale format. See #GDataOAuth1Authorizer:locale for more details.
 *
 * Note that while it's possible to change the locale after sending network requests (i.e. calling
 * gdata_oauth1_authorizer_request_authentication_uri() for the first time), it is unsupported, as the server-side software may behave unexpectedly.
 * The only supported use of this method is after creation of the authorizer, but before any network requests are made.
 *
 * Since: 0.9.0
 */
void
gdata_oauth1_authorizer_set_locale (GDataOAuth1Authorizer *self, const gchar *locale)
{
	g_return_if_fail (GDATA_IS_OAUTH1_AUTHORIZER (self));

	if (g_strcmp0 (locale, self->priv->locale) == 0) {
		/* Already has this value */
		return;
	}

	g_free (self->priv->locale);
	self->priv->locale = g_strdup (locale);
	g_object_notify (G_OBJECT (self), "locale");
}

static void
notify_proxy_uri_cb (GObject *gobject, GParamSpec *pspec, GDataOAuth1Authorizer *self)
{
	/* Flush our cached version */
	if (self->priv->proxy_uri != NULL) {
		soup_uri_free (self->priv->proxy_uri);
		self->priv->proxy_uri = NULL;
	}

	g_object_notify (G_OBJECT (self), "proxy-uri");
}

/* Static function which isn't deprecated so we can continue using it internally. */
static SoupURI *
_get_proxy_uri (GDataOAuth1Authorizer *self)
{
	SoupURI *proxy_uri;

	g_return_val_if_fail (GDATA_IS_OAUTH1_AUTHORIZER (self), NULL);

	/* If we have a cached version, return that */
	if (self->priv->proxy_uri != NULL) {
		return self->priv->proxy_uri;
	}

	g_object_get (self->priv->session, SOUP_SESSION_PROXY_URI, &proxy_uri, NULL);

	/* Update the cache; it takes ownership of the URI */
	self->priv->proxy_uri = proxy_uri;

	return proxy_uri;
}

/**
 * gdata_oauth1_authorizer_get_proxy_uri:
 * @self: a #GDataOAuth1Authorizer
 *
 * Gets the proxy URI on the #GDataOAuth1Authorizer's #SoupSession.
 *
 * Return value: (transfer full) (allow-none): the proxy URI, or %NULL; free with soup_uri_free()
 *
 * Since: 0.9.0
 * Deprecated: 0.15.0: Use gdata_oauth1_authorizer_get_proxy_resolver() instead, which gives more flexibility over the proxy used.
 */
SoupURI *
gdata_oauth1_authorizer_get_proxy_uri (GDataOAuth1Authorizer *self)
{
	return _get_proxy_uri (self);
}

/* Static function which isn't deprecated so we can continue using it internally. */
static void
_set_proxy_uri (GDataOAuth1Authorizer *self, SoupURI *proxy_uri)
{
	g_return_if_fail (GDATA_IS_OAUTH1_AUTHORIZER (self));

	g_object_set (self->priv->session, SOUP_SESSION_PROXY_URI, proxy_uri, NULL);

	/* Notification is handled in notify_proxy_uri_cb() which is called as a result of setting the property on the session */
}

/**
 * gdata_oauth1_authorizer_set_proxy_uri:
 * @self: a #GDataOAuth1Authorizer
 * @proxy_uri: (allow-none): the proxy URI, or %NULL
 *
 * Sets the proxy URI on the #SoupSession used internally by the #GDataOAuth1Authorizer. This forces all requests through the given proxy.
 *
 * If @proxy_uri is %NULL, no proxy will be used.
 *
 * Since: 0.9.0
 * Deprecated: 0.15.0: Use gdata_oauth1_authorizer_set_proxy_resolver() instead, which gives more flexibility over the proxy used.
 */
void
gdata_oauth1_authorizer_set_proxy_uri (GDataOAuth1Authorizer *self, SoupURI *proxy_uri)
{
	_set_proxy_uri (self, proxy_uri);
}

/**
 * gdata_oauth1_authorizer_get_proxy_resolver:
 * @self: a #GDataOAuth1Authorizer
 *
 * Gets the #GProxyResolver on the #GDataOAuth1Authorizer's #SoupSession.
 *
 * Return value: (transfer none) (allow-none): a #GProxyResolver, or %NULL
 *
 * Since: 0.15.0
 */
GProxyResolver *
gdata_oauth1_authorizer_get_proxy_resolver (GDataOAuth1Authorizer *self)
{
	g_return_val_if_fail (GDATA_IS_OAUTH1_AUTHORIZER (self), NULL);

	return self->priv->proxy_resolver;
}

/**
 * gdata_oauth1_authorizer_set_proxy_resolver:
 * @self: a #GDataOAuth1Authorizer
 * @proxy_resolver: (allow-none): a #GProxyResolver, or %NULL
 *
 * Sets the #GProxyResolver on the #SoupSession used internally by the given #GDataOAuth1Authorizer.
 *
 * Setting this will clear the #GDataOAuth1Authorizer:proxy-uri property.
 *
 * Since: 0.15.0
 */
void
gdata_oauth1_authorizer_set_proxy_resolver (GDataOAuth1Authorizer *self, GProxyResolver *proxy_resolver)
{
	g_return_if_fail (GDATA_IS_OAUTH1_AUTHORIZER (self));
	g_return_if_fail (proxy_resolver == NULL || G_IS_PROXY_RESOLVER (proxy_resolver));

	if (proxy_resolver != NULL) {
		g_object_ref (proxy_resolver);
	}

	g_clear_object (&self->priv->proxy_resolver);
	self->priv->proxy_resolver = proxy_resolver;

	g_object_notify (G_OBJECT (self), "proxy-resolver");
}

static void
notify_timeout_cb (GObject *gobject, GParamSpec *pspec, GObject *self)
{
	g_object_notify (self, "timeout");
}

/**
 * gdata_oauth1_authorizer_get_timeout:
 * @self: a #GDataOAuth1Authorizer
 *
 * Gets the #GDataOAuth1Authorizer:timeout property; the network timeout, in seconds.
 *
 * Return value: the timeout, or <code class="literal">0</code>
 *
 * Since: 0.9.0
 */
guint
gdata_oauth1_authorizer_get_timeout (GDataOAuth1Authorizer *self)
{
	guint timeout;

	g_return_val_if_fail (GDATA_IS_OAUTH1_AUTHORIZER (self), 0);

	g_object_get (self->priv->session, SOUP_SESSION_TIMEOUT, &timeout, NULL);

	return timeout;
}

/**
 * gdata_oauth1_authorizer_set_timeout:
 * @self: a #GDataOAuth1Authorizer
 * @timeout: the timeout, or <code class="literal">0</code>
 *
 * Sets the #GDataOAuth1Authorizer:timeout property; the network timeout, in seconds.
 *
 * If @timeout is <code class="literal">0</code>, network operations will never time out.
 *
 * Since: 0.9.0
 */
void
gdata_oauth1_authorizer_set_timeout (GDataOAuth1Authorizer *self, guint timeout)
{
	g_return_if_fail (GDATA_IS_OAUTH1_AUTHORIZER (self));

	if (gdata_oauth1_authorizer_get_timeout (self) == timeout) {
		/* Already has this value */
		return;
	}

	g_object_set (self->priv->session, SOUP_SESSION_TIMEOUT, timeout, NULL);

	/* Notification is handled in notify_timeout_cb() which is called as a result of setting the property on the session */
}