summaryrefslogtreecommitdiff
path: root/client/src/leap/soledad/client/__init__.py
blob: 116a59e450ba9f0bbe717fac4fd36623bcc3c2c4 (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
# -*- coding: utf-8 -*-
# __init__.py
# Copyright (C) 2013, 2014 LEAP
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program 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 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/>.
"""
Soledad - Synchronization Of Locally Encrypted Data Among Devices.

Soledad is the part of LEAP that manages storage and synchronization of
application data. It is built on top of U1DB reference Python API and
implements (1) a SQLCipher backend for local storage in the client, (2) a
SyncTarget that encrypts data before syncing, and (3) a CouchDB backend for
remote storage in the server side.
"""
import binascii
import errno
import httplib
import logging
import multiprocessing
import os
import socket
import sqlite3
import ssl
import urlparse
import hmac

#from functools import partial
from hashlib import sha256
from threading import Lock
from collections import defaultdict

try:
    import cchardet as chardet
except ImportError:
    import chardet

from taskthread import TimerTask
from u1db.remote import http_client
from u1db.remote.ssl_match_hostname import match_hostname

import scrypt
import simplejson as json

from leap.common.config import get_path_prefix
from leap.soledad.common import SHARED_DB_NAME
from leap.soledad.common.errors import (
    InvalidTokenError,
    NotLockedError,
    AlreadyLockedError,
    LockTimedOutError,
)
from leap.soledad.common.crypto import (
    MacMethods,
    UnknownMacMethod,
    WrongMac,
    MAC_KEY,
    MAC_METHOD_KEY,
)

#
# Signaling function
#

SOLEDAD_CREATING_KEYS = 'Creating keys...'
SOLEDAD_DONE_CREATING_KEYS = 'Done creating keys.'
SOLEDAD_DOWNLOADING_KEYS = 'Downloading keys...'
SOLEDAD_DONE_DOWNLOADING_KEYS = 'Done downloading keys.'
SOLEDAD_UPLOADING_KEYS = 'Uploading keys...'
SOLEDAD_DONE_UPLOADING_KEYS = 'Done uploading keys.'
SOLEDAD_NEW_DATA_TO_SYNC = 'New data available.'
SOLEDAD_DONE_DATA_SYNC = 'Done data sync.'

# we want to use leap.common.events to emits signals, if it is available.
try:
    from leap.common import events
    from leap.common.events import signal
    SOLEDAD_CREATING_KEYS = events.events_pb2.SOLEDAD_CREATING_KEYS
    SOLEDAD_DONE_CREATING_KEYS = events.events_pb2.SOLEDAD_DONE_CREATING_KEYS
    SOLEDAD_DOWNLOADING_KEYS = events.events_pb2.SOLEDAD_DOWNLOADING_KEYS
    SOLEDAD_DONE_DOWNLOADING_KEYS = \
        events.events_pb2.SOLEDAD_DONE_DOWNLOADING_KEYS
    SOLEDAD_UPLOADING_KEYS = events.events_pb2.SOLEDAD_UPLOADING_KEYS
    SOLEDAD_DONE_UPLOADING_KEYS = \
        events.events_pb2.SOLEDAD_DONE_UPLOADING_KEYS
    SOLEDAD_NEW_DATA_TO_SYNC = events.events_pb2.SOLEDAD_NEW_DATA_TO_SYNC
    SOLEDAD_DONE_DATA_SYNC = events.events_pb2.SOLEDAD_DONE_DATA_SYNC

except ImportError:
    # we define a fake signaling function and fake signal constants that will
    # allow for logging signaling attempts in case leap.common.events is not
    # available.

    def signal(signal, content=""):
        logger.info("Would signal: %s - %s." % (str(signal), content))


from leap.soledad.common import soledad_assert, soledad_assert_type
from leap.soledad.common.document import SoledadDocument
from leap.soledad.client.crypto import SoledadCrypto
from leap.soledad.client.crypto import SyncEncrypterPool, SyncDecrypterPool
from leap.soledad.client.shared_db import SoledadSharedDatabase
from leap.soledad.client.sqlcipher import open as sqlcipher_open
from leap.soledad.client.sqlcipher import SQLCipherDatabase
from leap.soledad.client.target import SoledadSyncTarget


logger = logging.getLogger(name=__name__)


#
# Constants
#

SOLEDAD_CERT = None
"""
Path to the certificate file used to certify the SSL connection between
Soledad client and server.
"""


#
# Soledad: local encrypted storage and remote encrypted sync.
#

class NoStorageSecret(Exception):
    """
    Raised when trying to use a storage secret but none is available.
    """
    pass


class PassphraseTooShort(Exception):
    """
    Raised when trying to change the passphrase but the provided passphrase is
    too short.
    """


class BootstrapSequenceError(Exception):
    """
    Raised when an attempt to generate a secret and store it in a recovery
    documents on server failed.
    """


class Soledad(object):
    """
    Soledad provides encrypted data storage and sync.

    A Soledad instance is used to store and retrieve data in a local encrypted
    database and synchronize this database with Soledad server.

    This class is also responsible for bootstrapping users' account by
    creating cryptographic secrets and/or storing/fetching them on Soledad
    server.

    Soledad uses C{leap.common.events} to signal events. The possible events
    to be signaled are:

        SOLEDAD_CREATING_KEYS: emitted during bootstrap sequence when key
            generation starts.
        SOLEDAD_DONE_CREATING_KEYS: emitted during bootstrap sequence when key
            generation finishes.
        SOLEDAD_UPLOADING_KEYS: emitted during bootstrap sequence when soledad
            starts sending keys to server.
        SOLEDAD_DONE_UPLOADING_KEYS: emitted during bootstrap sequence when
            soledad finishes sending keys to server.
        SOLEDAD_DOWNLOADING_KEYS: emitted during bootstrap sequence when
            soledad starts to retrieve keys from server.
        SOLEDAD_DONE_DOWNLOADING_KEYS: emitted during bootstrap sequence when
            soledad finishes downloading keys from server.
        SOLEDAD_NEW_DATA_TO_SYNC: emitted upon call to C{need_sync()} when
          there's indeed new data to be synchronized between local database
          replica and server's replica.
        SOLEDAD_DONE_DATA_SYNC: emitted inside C{sync()} method when it has
            finished synchronizing with remote replica.
    """

    LOCAL_DATABASE_FILE_NAME = 'soledad.u1db'
    """
    The name of the local SQLCipher U1DB database file.
    """

    LOCAL_SYMMETRIC_SYNC_FILE_NAME = 'sync.u1db'
    """
    The name of the local symmetrically encrypted documents to
    sync database file.
    """

    STORAGE_SECRETS_FILE_NAME = "soledad.json"
    """
    The name of the file where the storage secrets will be stored.
    """

    GENERATED_SECRET_LENGTH = 1024
    """
    The length of the generated secret used to derive keys for symmetric
    encryption for local and remote storage.
    """

    LOCAL_STORAGE_SECRET_LENGTH = 512
    """
    The length of the secret used to derive a passphrase for the SQLCipher
    database.
    """

    REMOTE_STORAGE_SECRET_LENGTH = \
        GENERATED_SECRET_LENGTH - LOCAL_STORAGE_SECRET_LENGTH
    """
    The length of the secret used to derive an encryption key and a MAC auth
    key for remote storage.
    """

    SALT_LENGTH = 64
    """
    The length of the salt used to derive the key for the storage secret
    encryption.
    """

    MINIMUM_PASSPHRASE_LENGTH = 6
    """
    The minimum length for a passphrase. The passphrase length is only checked
    when the user changes her passphrase, not when she instantiates Soledad.
    """

    IV_SEPARATOR = ":"
    """
    A separator used for storing the encryption initial value prepended to the
    ciphertext.
    """

    UUID_KEY = 'uuid'
    STORAGE_SECRETS_KEY = 'storage_secrets'
    SECRET_KEY = 'secret'
    CIPHER_KEY = 'cipher'
    LENGTH_KEY = 'length'
    KDF_KEY = 'kdf'
    KDF_SALT_KEY = 'kdf_salt'
    KDF_LENGTH_KEY = 'kdf_length'
    KDF_SCRYPT = 'scrypt'
    CIPHER_AES256 = 'aes256'
    """
    Keys used to access storage secrets in recovery documents.
    """

    DEFAULT_PREFIX = os.path.join(get_path_prefix(), 'leap', 'soledad')
    """
    Prefix for default values for path.
    """

    syncing_lock = defaultdict(Lock)
    encrypting_lock = Lock()
    """
    A dictionary that hold locks which avoid multiple sync attempts from the
    same database replica.
    """

    def __init__(self, uuid, passphrase, secrets_path, local_db_path,
                 server_url, cert_file,
                 auth_token=None, secret_id=None):
        """
        Initialize configuration, cryptographic keys and dbs.

        :param uuid: User's uuid.
        :type uuid: str

        :param passphrase: The passphrase for locking and unlocking encryption
                           secrets for local and remote storage.
        :type passphrase: unicode

        :param secrets_path: Path for storing encrypted key used for
                             symmetric encryption.
        :type secrets_path: str

        :param local_db_path: Path for local encrypted storage db.
        :type local_db_path: str

        :param server_url: URL for Soledad server. This is used either to sync
                           with the user's remote db and to interact with the
                           shared recovery database.
        :type server_url: str

        :param cert_file: Path to the certificate of the ca used
                          to validate the SSL certificate used by the remote
                          soledad server.
        :type cert_file: str
        :param auth_token: Authorization token for accessing remote databases.
        :type auth_token: str

        :raise BootstrapSequenceError: Raised when the secret generation and
                                       storage on server sequence has failed
                                       for some reason.
        """
        # get config params
        self._uuid = uuid
        soledad_assert_type(passphrase, unicode)
        self._passphrase = passphrase
        # init crypto variables
        self._secrets = {}
        self._secret_id = secret_id

        # init config (possibly with default values)
        sync_db_path = "%s-sync" % local_db_path
        self._init_config(secrets_path, local_db_path, server_url,
                          sync_db_path)

        self._set_token(auth_token)
        self._shared_db_instance = None
        # configure SSL certificate
        global SOLEDAD_CERT
        SOLEDAD_CERT = cert_file
        # initiate bootstrap sequence
        self._bootstrap()  # might raise BootstrapSequenceError()

        # initialize syncing queue encryption pool
        self._sync_enc_pool = SyncEncrypterPool(self._crypto, self._sync_db)
        self._sync_watcher = TimerTask(self._encrypt_syncing_docs, delay=10)
        self._sync_watcher.start()

    def _init_config(self, secrets_path, local_db_path, server_url,
                     local_sync_path):
        """
        Initialize configuration using default values for missing params.
        """
        # initialize secrets_path
        self._secrets_path = secrets_path
        if self._secrets_path is None:
            self._secrets_path = os.path.join(
                self.DEFAULT_PREFIX, self.STORAGE_SECRETS_FILE_NAME)
        # initialize local_db_path
        self._local_db_path = local_db_path
        if self._local_db_path is None:
            self._local_db_path = os.path.join(
                self.DEFAULT_PREFIX, self.LOCAL_DATABASE_FILE_NAME)
        # initialize server_url
        self._server_url = server_url
        soledad_assert(
            self._server_url is not None,
            'Missing URL for Soledad server.')
        # initialize local_sync_path
        self._local_sync_path = local_sync_path
        print "INITIALIZING SYNC DB ---->", local_sync_path
        if self._local_sync_path is None:
            self._local_sync_path = os.path.join(
                self.DEFAULT_PREFIX, self.LOCAL_SYMMETRIC_SYNC_FILE_NAME)

    #
    # initialization/destruction methods
    #

    def _get_or_gen_crypto_secrets(self):
        """
        Retrieves or generates the crypto secrets.

        Might raise BootstrapSequenceError
        """
        doc = self._get_secrets_from_shared_db()

        if doc:
            logger.info(
                'Found cryptographic secrets in shared recovery '
                'database.')
            _, mac = self.import_recovery_document(doc.content)
            if mac is False:
                self.put_secrets_in_shared_db()
            self._store_secrets()  # save new secrets in local file
            if self._secret_id is None:
                self._set_secret_id(self._secrets.items()[0][0])
        else:
            # STAGE 3 - there are no secrets in server also, so
            # generate a secret and store it in remote db.
            logger.info(
                'No cryptographic secrets found, creating new '
                ' secrets...')
            self._set_secret_id(self._gen_secret())
            try:
                self._put_secrets_in_shared_db()
            except Exception as ex:
                # storing generated secret in shared db failed for
                # some reason, so we erase the generated secret and
                # raise.
                try:
                    os.unlink(self._secrets_path)
                except OSError as e:
                    if e.errno != errno.ENOENT:  # no such file or directory
                        logger.exception(e)
                logger.exception(ex)
                raise BootstrapSequenceError(
                    'Could not store generated secret in the shared '
                    'database, bailing out...')

    def _bootstrap(self):
        """
        Bootstrap local Soledad instance.

        Soledad Client bootstrap is the following sequence of stages:

        * stage 0 - local environment setup.
            - directory initialization.
            - crypto submodule initialization
        * stage 1 - local secret loading:
            - if secrets exist locally, load them.
        * stage 2 - remote secret loading:
            - else, if secrets exist in server, download them.
        * stage 3 - secret generation:
            - else, generate a new secret and store in server.
        * stage 4 - database initialization.

        This method decides which bootstrap stages have already been performed
        and performs the missing ones in order.

        :raise BootstrapSequenceError: Raised when the secret generation and
            storage on server sequence has failed for some reason.
        """
        # STAGE 0  - local environment setup
        self._init_dirs()
        self._crypto = SoledadCrypto(self)

        secrets_problem = None

        # STAGE 1 - verify if secrets exist locally
        if not self._has_secret():  # try to load from local storage.

            # STAGE 2 - there are no secrets in local storage, so try to fetch
            # encrypted secrets from server.
            logger.info(
                'Trying to fetch cryptographic secrets from shared recovery '
                'database...')

            # --- start of atomic operation in shared db ---

            # obtain lock on shared db
            token = timeout = None
            try:
                token, timeout = self._shared_db.lock()
            except AlreadyLockedError:
                raise BootstrapSequenceError('Database is already locked.')
            except LockTimedOutError:
                raise BootstrapSequenceError('Lock operation timed out.')

            try:
                self._get_or_gen_crypto_secrets()
            except Exception as e:
                secrets_problem = e

            # release the lock on shared db
            try:
                self._shared_db.unlock(token)
            except NotLockedError:
                # for some reason the lock expired. Despite that, secret
                # loading or generation/storage must have been executed
                # successfully, so we pass.
                pass
            except InvalidTokenError:
                # here, our lock has not only expired but also some other
                # client application has obtained a new lock and is currently
                # doing its thing in the shared database. Using the same
                # reasoning as above, we assume everything went smooth and
                # pass.
                pass
            except Exception as e:
                logger.error("Unhandled exception when unlocking shared "
                             "database.")
                logger.exception(e)

            # --- end of atomic operation in shared db ---

        # STAGE 4 - local database initialization
        if secrets_problem is None:
            self._init_db()
        else:
            raise secrets_problem

        # STAGE 5 - local sync documents and queue initialization
        self._init_sync_db()

    def _init_dirs(self):
        """
        Create work directories.

        :raise OSError: in case file exists and is not a dir.
        """
        paths = map(
            lambda x: os.path.dirname(x),
            [self._local_db_path, self._secrets_path])
        for path in paths:
            try:
                if not os.path.isdir(path):
                    logger.info('Creating directory: %s.' % path)
                os.makedirs(path)
            except OSError as exc:
                if exc.errno == errno.EEXIST and os.path.isdir(path):
                    pass
                else:
                    raise

    def _init_db(self):
        """
        Initialize the U1DB SQLCipher database for local storage.

        Currently, Soledad uses the default SQLCipher cipher, i.e.
        'aes-256-cbc'. We use scrypt to derive a 256-bit encryption key and
        uses the 'raw PRAGMA key' format to handle the key to SQLCipher.

        The first C{self.REMOTE_STORAGE_SECRET_LENGTH} bytes of the storage
        secret are used for remote storage encryption. We use the next
        C{self.LOCAL_STORAGE_SECRET} bytes to derive a key for local storage.
        From these bytes, the first C{self.SALT_LENGTH} are used as the salt
        and the rest as the password for the scrypt hashing.
        """
        # salt indexes
        salt_start = self.REMOTE_STORAGE_SECRET_LENGTH
        salt_end = salt_start + self.SALT_LENGTH
        # password indexes
        pwd_start = salt_end
        pwd_end = salt_start + self.LOCAL_STORAGE_SECRET_LENGTH
        # calculate the key for local encryption
        secret = self._get_storage_secret()
        key = scrypt.hash(
            secret[pwd_start:pwd_end],  # the password
            secret[salt_start:salt_end],  # the salt
            buflen=32,  # we need a key with 256 bits (32 bytes)
        )

        self._db = sqlcipher_open(
            self._local_db_path,
            binascii.b2a_hex(key),  # sqlcipher only accepts the hex version
            create=True,
            document_factory=SoledadDocument,
            crypto=self._crypto,
            raw_key=True)

    def _init_sync_db(self):
        """
        Initialize the Symmetrically-Encrypted document to be synced database,
        and the queue to communicate with subprocess workers.
        """
        self._sync_db = sqlite3.connect(self._local_sync_path,
                                        check_same_thread=False)
        self._create_sync_db()
        self._sync_queue = multiprocessing.Queue()

    def _create_sync_db(self):
        """
        Create local sync documents db if needed.
        """
        encr = SyncEncrypterPool
        decr = SyncDecrypterPool
        sql_encr = ("CREATE TABLE IF NOT EXISTS %s (%s)" % (
            encr.TABLE_NAME, encr.FIELD_NAMES))
        sql_decr = ("CREATE TABLE IF NOT EXISTS %s (%s)" % (
            decr.TABLE_NAME, decr.FIELD_NAMES))

        c = self._sync_db.cursor()
        c.execute(sql_encr)
        c.execute(sql_decr)
        self._sync_db.commit()

    def close(self):
        """
        Close underlying U1DB database.
        """
        if hasattr(self, '_db') and isinstance(
                self._db,
                SQLCipherDatabase):
            self._db.close()

    def __del__(self):
        """
        Make sure local database is closed when object is destroyed.
        """
        # Watch out! We have no guarantees  that this is properly called.
        self.close()

    #
    # Management of secret for symmetric encryption.
    #

    def _get_storage_secret(self):
        """
        Return the storage secret.

        Storage secret is encrypted before being stored. This method decrypts
        and returns the stored secret.

        :return: The storage secret.
        :rtype: str
        """
        # calculate the encryption key
        key = scrypt.hash(
            self._passphrase_as_string(),
            # the salt is stored base64 encoded
            binascii.a2b_base64(
                self._secrets[self._secret_id][self.KDF_SALT_KEY]),
            buflen=32,  # we need a key with 256 bits (32 bytes).
        )
        # recover the initial value and ciphertext
        iv, ciphertext = self._secrets[self._secret_id][self.SECRET_KEY].split(
            self.IV_SEPARATOR, 1)
        ciphertext = binascii.a2b_base64(ciphertext)
        return self._crypto.decrypt_sym(ciphertext, key, iv=iv)

    def _set_secret_id(self, secret_id):
        """
        Define the id of the storage secret to be used.

        This method will also replace the secret in the crypto object.
        """
        self._secret_id = secret_id

    def _load_secrets(self):
        """
        Load storage secrets from local file.
        """
        # does the file exist in disk?
        if not os.path.isfile(self._secrets_path):
            raise IOError('File does not exist: %s' % self._secrets_path)
        # read storage secrets from file
        content = None
        with open(self._secrets_path, 'r') as f:
            content = json.loads(f.read())
        _, mac = self.import_recovery_document(content)
        if mac is False:
            self._store_secrets()
            self._put_secrets_in_shared_db()
        # choose first secret if no secret_id was given
        if self._secret_id is None:
            self._set_secret_id(self._secrets.items()[0][0])

    def _has_secret(self):
        """
        Return whether there is a storage secret available for use or not.

        :return: Whether there's a storage secret for symmetric encryption.
        :rtype: bool
        """
        if self._secret_id is None or self._secret_id not in self._secrets:
            try:
                self._load_secrets()  # try to load from disk
            except IOError, e:
                logger.warning('IOError: %s' % str(e))
        try:
            self._get_storage_secret()
            return True
        except Exception:
            return False

    def _gen_secret(self):
        """
        Generate a secret for symmetric encryption and store in a local
        encrypted file.

        This method emits the following signals:

            * SOLEDAD_CREATING_KEYS
            * SOLEDAD_DONE_CREATING_KEYS

        A secret has the following structure:

            {
                '<secret_id>': {
                        'kdf': 'scrypt',
                        'kdf_salt': '<b64 repr of salt>'
                        'kdf_length': <key length>
                        'cipher': 'aes256',
                        'length': <secret length>,
                        'secret': '<encrypted b64 repr of storage_secret>',
                }
            }

        :return: The id of the generated secret.
        :rtype: str
        """
        signal(SOLEDAD_CREATING_KEYS, self._uuid)
        # generate random secret
        secret = os.urandom(self.GENERATED_SECRET_LENGTH)
        secret_id = sha256(secret).hexdigest()
        # generate random salt
        salt = os.urandom(self.SALT_LENGTH)
        # get a 256-bit key
        key = scrypt.hash(self._passphrase_as_string(), salt, buflen=32)
        iv, ciphertext = self._crypto.encrypt_sym(secret, key)
        self._secrets[secret_id] = {
            # leap.soledad.crypto submodule uses AES256 for symmetric
            # encryption.
            self.KDF_KEY: self.KDF_SCRYPT,
            self.KDF_SALT_KEY: binascii.b2a_base64(salt),
            self.KDF_LENGTH_KEY: len(key),
            self.CIPHER_KEY: self.CIPHER_AES256,
            self.LENGTH_KEY: len(secret),
            self.SECRET_KEY: '%s%s%s' % (
                str(iv), self.IV_SEPARATOR, binascii.b2a_base64(ciphertext)),
        }
        self._store_secrets()
        signal(SOLEDAD_DONE_CREATING_KEYS, self._uuid)
        return secret_id

    def _store_secrets(self):
        """
        Store secrets in C{Soledad.STORAGE_SECRETS_FILE_PATH}.
        """
        with open(self._secrets_path, 'w') as f:
            f.write(
                json.dumps(
                    self.export_recovery_document()))

    def change_passphrase(self, new_passphrase):
        """
        Change the passphrase that encrypts the storage secret.

        :param new_passphrase: The new passphrase.
        :type new_passphrase: unicode

        :raise NoStorageSecret: Raised if there's no storage secret available.
        """
        # maybe we want to add more checks to guarantee passphrase is
        # reasonable?
        soledad_assert_type(new_passphrase, unicode)
        if len(new_passphrase) < self.MINIMUM_PASSPHRASE_LENGTH:
            raise PassphraseTooShort(
                'Passphrase must be at least %d characters long!' %
                self.MINIMUM_PASSPHRASE_LENGTH)
        # ensure there's a secret for which the passphrase will be changed.
        if not self._has_secret():
            raise NoStorageSecret()
        secret = self._get_storage_secret()
        # generate random salt
        new_salt = os.urandom(self.SALT_LENGTH)
        # get a 256-bit key
        key = scrypt.hash(new_passphrase.encode('utf-8'), new_salt, buflen=32)
        iv, ciphertext = self._crypto.encrypt_sym(secret, key)
        # XXX update all secrets in the dict
        self._secrets[self._secret_id] = {
            # leap.soledad.crypto submodule uses AES256 for symmetric
            # encryption.
            self.KDF_KEY: self.KDF_SCRYPT,  # TODO: remove hard coded kdf
            self.KDF_SALT_KEY: binascii.b2a_base64(new_salt),
            self.KDF_LENGTH_KEY: len(key),
            self.CIPHER_KEY: self.CIPHER_AES256,
            self.LENGTH_KEY: len(secret),
            self.SECRET_KEY: '%s%s%s' % (
                str(iv), self.IV_SEPARATOR, binascii.b2a_base64(ciphertext)),
        }
        self._passphrase = new_passphrase
        self._store_secrets()
        self._put_secrets_in_shared_db()

    #
    # General crypto utility methods.
    #

    @property
    def _shared_db(self):
        """
        Return an instance of the shared recovery database object.

        :return: The shared database.
        :rtype: SoledadSharedDatabase
        """
        if self._shared_db_instance is None:
            self._shared_db_instance = SoledadSharedDatabase.open_database(
                urlparse.urljoin(self.server_url, SHARED_DB_NAME),
                self._uuid,
                False,  # db should exist at this point.
                creds=self._creds)
        return self._shared_db_instance

    def _shared_db_doc_id(self):
        """
        Calculate the doc_id of the document in the shared db that stores key
        material.

        :return: the hash
        :rtype: str
        """
        return sha256('%s%s' %
                     (self._passphrase_as_string(), self.uuid)).hexdigest()

    def _get_secrets_from_shared_db(self):
        """
        Retrieve the document with encrypted key material from the shared
        database.

        :return: a document with encrypted key material in its contents
        :rtype: SoledadDocument
        """
        signal(SOLEDAD_DOWNLOADING_KEYS, self._uuid)
        db = self._shared_db
        if not db:
            logger.warning('No shared db found')
            return
        doc = db.get_doc(self._shared_db_doc_id())
        signal(SOLEDAD_DONE_DOWNLOADING_KEYS, self._uuid)
        return doc

    def _put_secrets_in_shared_db(self):
        """
        Assert local keys are the same as shared db's ones.

        Try to fetch keys from shared recovery database. If they already exist
        in the remote db, assert that that data is the same as local data.
        Otherwise, upload keys to shared recovery database.
        """
        soledad_assert(
            self._has_secret(),
            'Tried to send keys to server but they don\'t exist in local '
            'storage.')
        # try to get secrets doc from server, otherwise create it
        doc = self._get_secrets_from_shared_db()
        if doc is None:
            doc = SoledadDocument(
                doc_id=self._shared_db_doc_id())
        # fill doc with encrypted secrets
        doc.content = self.export_recovery_document()
        # upload secrets to server
        signal(SOLEDAD_UPLOADING_KEYS, self._uuid)
        db = self._shared_db
        if not db:
            logger.warning('No shared db found')
            return
        db.put_doc(doc)
        signal(SOLEDAD_DONE_UPLOADING_KEYS, self._uuid)

    #
    # Document storage, retrieval and sync.
    #

    def put_doc(self, doc):
        """
        Update a document in the local encrypted database.

        ============================== WARNING ==============================
        This method converts the document's contents to unicode in-place. This
        means that after calling C{put_doc(doc)}, the contents of the
        document, i.e. C{doc.content}, might be different from before the
        call.
        ============================== WARNING ==============================

        :param doc: the document to update
        :type doc: SoledadDocument

        :return: the new revision identifier for the document
        :rtype: str
        """
        doc.content = self._convert_to_unicode(doc.content)
        new_rev = self._db.put_doc(doc)
        # enqueue the modified document for symmetric encryption before sync
        self._sync_queue.put_nowait(doc)
        return new_rev

    def delete_doc(self, doc):
        """
        Delete a document from the local encrypted database.

        :param doc: the document to delete
        :type doc: SoledadDocument

        :return: the new revision identifier for the document
        :rtype: str
        """
        return self._db.delete_doc(doc)

    def get_doc(self, doc_id, include_deleted=False):
        """
        Retrieve a document from the local encrypted database.

        :param doc_id: the unique document identifier
        :type doc_id: str
        :param include_deleted: if True, deleted documents will be
                                returned with empty content; otherwise asking
                                for a deleted document will return None
        :type include_deleted: bool

        :return: the document object or None
        :rtype: SoledadDocument
        """
        return self._db.get_doc(doc_id, include_deleted=include_deleted)

    def get_docs(self, doc_ids, check_for_conflicts=True,
                 include_deleted=False):
        """
        Get the content for many documents.

        :param doc_ids: a list of document identifiers
        :type doc_ids: list
        :param check_for_conflicts: if set False, then the conflict check will
            be skipped, and 'None' will be returned instead of True/False
        :type check_for_conflicts: bool

        :return: iterable giving the Document object for each document id
            in matching doc_ids order.
        :rtype: generator
        """
        return self._db.get_docs(
            doc_ids, check_for_conflicts=check_for_conflicts,
            include_deleted=include_deleted)

    def get_all_docs(self, include_deleted=False):
        """Get the JSON content for all documents in the database.

        :param include_deleted: If set to True, deleted documents will be
                                returned with empty content. Otherwise deleted
                                documents will not be included in the results.
        :return: (generation, [Document])
                 The current generation of the database, followed by a list of
                 all the documents in the database.
        """
        return self._db.get_all_docs(include_deleted)

    def _convert_to_unicode(self, content):
        """
        Converts content to unicode (or all the strings in content)

        NOTE: Even though this method supports any type, it will
        currently ignore contents of lists, tuple or any other
        iterable than dict. We don't need support for these at the
        moment

        :param content: content to convert
        :type content: object

        :rtype: object
        """
        if isinstance(content, unicode):
            return content
        elif isinstance(content, str):
            result = chardet.detect(content)
            default = "utf-8"
            encoding = result["encoding"] or default
            try:
                content = content.decode(encoding)
            except UnicodeError as e:
                logger.error("Unicode error: {0!r}. Using 'replace'".format(e))
                content = content.decode(encoding, 'replace')
            return content
        else:
            if isinstance(content, dict):
                for key in content.keys():
                    content[key] = self._convert_to_unicode(content[key])
        return content

    def create_doc(self, content, doc_id=None):
        """
        Create a new document in the local encrypted database.

        :param content: the contents of the new document
        :type content: dict
        :param doc_id: an optional identifier specifying the document id
        :type doc_id: str

        :return: the new document
        :rtype: SoledadDocument
        """
        doc = self._db.create_doc(
            self._convert_to_unicode(content), doc_id=doc_id)
        # enqueue the modified document for symmetric encryption before sync
        self._sync_queue.put_nowait(doc)
        return doc

    def create_doc_from_json(self, json, doc_id=None):
        """
        Create a new document.

        You can optionally specify the document identifier, but the document
        must not already exist. See 'put_doc' if you want to override an
        existing document.
        If the database specifies a maximum document size and the document
        exceeds it, create will fail and raise a DocumentTooBig exception.

        :param json: The JSON document string
        :type json: str
        :param doc_id: An optional identifier specifying the document id.
        :type doc_id:
        :return: The new cocument
        :rtype: SoledadDocument
        """
        doc = self._db.create_doc_from_json(json, doc_id=doc_id)
        # enqueue the modified document for encryption before sync
        self._sync_queue.put_nowait(doc)
        return doc

    def create_index(self, index_name, *index_expressions):
        """
        Create an named index, which can then be queried for future lookups.
        Creating an index which already exists is not an error, and is cheap.
        Creating an index which does not match the index_expressions of the
        existing index is an error.
        Creating an index will block until the expressions have been evaluated
        and the index generated.

        :param index_name: A unique name which can be used as a key prefix
        :type index_name: str
        :param index_expressions: index expressions defining the index
                                  information.
        :type index_expressions: dict

            Examples:

            "fieldname", or "fieldname.subfieldname" to index alphabetically
            sorted on the contents of a field.

            "number(fieldname, width)", "lower(fieldname)"
        """
        if self._db:
            return self._db.create_index(
                index_name, *index_expressions)

    def delete_index(self, index_name):
        """
        Remove a named index.

        :param index_name: The name of the index we are removing
        :type index_name: str
        """
        if self._db:
            return self._db.delete_index(index_name)

    def list_indexes(self):
        """
        List the definitions of all known indexes.

        :return: A list of [('index-name', ['field', 'field2'])] definitions.
        :rtype: list
        """
        if self._db:
            return self._db.list_indexes()

    def get_from_index(self, index_name, *key_values):
        """
        Return documents that match the keys supplied.

        You must supply exactly the same number of values as have been defined
        in the index. It is possible to do a prefix match by using '*' to
        indicate a wildcard match. You can only supply '*' to trailing entries,
        (eg 'val', '*', '*' is allowed, but '*', 'val', 'val' is not.)
        It is also possible to append a '*' to the last supplied value (eg
        'val*', '*', '*' or 'val', 'val*', '*', but not 'val*', 'val', '*')

        :param index_name: The index to query
        :type index_name: str
        :param key_values: values to match. eg, if you have
                           an index with 3 fields then you would have:
                           get_from_index(index_name, val1, val2, val3)
        :type key_values: tuple
        :return: List of [Document]
        :rtype: list
        """
        if self._db:
            return self._db.get_from_index(index_name, *key_values)

    def get_count_from_index(self, index_name, *key_values):
        """
        Return the count of the documents that match the keys and
        values supplied.

        :param index_name: The index to query
        :type index_name: str
        :param key_values: values to match. eg, if you have
                           an index with 3 fields then you would have:
                           get_from_index(index_name, val1, val2, val3)
        :type key_values: tuple
        :return: count.
        :rtype: int
        """
        if self._db:
            return self._db.get_count_from_index(index_name, *key_values)

    def get_range_from_index(self, index_name, start_value, end_value):
        """
        Return documents that fall within the specified range.

        Both ends of the range are inclusive. For both start_value and
        end_value, one must supply exactly the same number of values as have
        been defined in the index, or pass None. In case of a single column
        index, a string is accepted as an alternative for a tuple with a single
        value. It is possible to do a prefix match by using '*' to indicate
        a wildcard match. You can only supply '*' to trailing entries, (eg
        'val', '*', '*' is allowed, but '*', 'val', 'val' is not.) It is also
        possible to append a '*' to the last supplied value (eg 'val*', '*',
        '*' or 'val', 'val*', '*', but not 'val*', 'val', '*')

        :param index_name: The index to query
        :type index_name: str
        :param start_values: tuples of values that define the lower bound of
            the range. eg, if you have an index with 3 fields then you would
            have: (val1, val2, val3)
        :type start_values: tuple
        :param end_values: tuples of values that define the upper bound of the
            range. eg, if you have an index with 3 fields then you would have:
            (val1, val2, val3)
        :type end_values: tuple
        :return: List of [Document]
        :rtype: list
        """
        if self._db:
            return self._db.get_range_from_index(
                index_name, start_value, end_value)

    def get_index_keys(self, index_name):
        """
        Return all keys under which documents are indexed in this index.

        :param index_name: The index to query
        :type index_name: str
        :return: [] A list of tuples of indexed keys.
        :rtype: list
        """
        if self._db:
            return self._db.get_index_keys(index_name)

    def get_doc_conflicts(self, doc_id):
        """
        Get the list of conflicts for the given document.

        :param doc_id: the document id
        :type doc_id: str

        :return: a list of the document entries that are conflicted
        :rtype: list
        """
        if self._db:
            return self._db.get_doc_conflicts(doc_id)

    def resolve_doc(self, doc, conflicted_doc_revs):
        """
        Mark a document as no longer conflicted.

        :param doc: a document with the new content to be inserted.
        :type doc: SoledadDocument
        :param conflicted_doc_revs: a list of revisions that the new content
                                    supersedes.
        :type conflicted_doc_revs: list
        """
        if self._db:
            return self._db.resolve_doc(doc, conflicted_doc_revs)

    def sync(self, decrypt_inline=False):
        """
        Synchronize the local encrypted replica with a remote replica.

        This method blocks until a syncing lock is acquired, so there are no
        attempts of concurrent syncs from the same client replica.

        :param url: the url of the target replica to sync with
        :type url: str

        :param decrypt_inline: Whether to do the decryption of received
                               messages inline or not.
        :type decrypt_inline: bool

        :return: The local generation before the synchronisation was
                 performed.
        :rtype: str
        """
        print "SYNC: inline? ", decrypt_inline
        local_gen = None
        if self._db:
            # acquire lock before attempt to sync
            replica_uid = self._db._get_replica_uid()
            logger.debug("REPLICA UID: %s", replica_uid)
            lock = Soledad.syncing_lock[replica_uid]
            # optional wait flag used to avoid blocking
            if not lock.acquire(False):
                logger.debug('Already syncing... Skipping!')
                return
            else:
                print "CLIENT syncing..."
                try:
                    local_gen = self._db.sync(
                        urlparse.urljoin(
                            self.server_url, 'user-%s' % self._uuid),
                        creds=self._creds, autocreate=True,
                        decrypt_inline=decrypt_inline)
                    signal(SOLEDAD_DONE_DATA_SYNC, self._uuid)
                except Exception as exc:
                    logger.error("error during soledad sync")
                    logger.exception(exc)
                finally:
                    lock.release()
                    if local_gen is not None:
                        print "CLIENT synced!!!", local_gen
                        return local_gen

    def need_sync(self, url):
        """
        Return if local db replica differs from remote url's replica.

        :param url: The remote replica to compare with local replica.
        :type url: str

        :return: Whether remote replica and local replica differ.
        :rtype: bool
        """
        target = SoledadSyncTarget(url, creds=self._creds, crypto=self._crypto)
        info = target.get_sync_info(self._db._get_replica_uid())
        # compare source generation with target's last known source generation
        if self._db._get_generation() != info[4]:
            signal(SOLEDAD_NEW_DATA_TO_SYNC, self._uuid)
            return True
        return False

    def _set_token(self, token):
        """
        Set the authentication token for remote database access.

        Build the credentials dictionary with the following format:

            self._{
                'token': {
                    'uuid': '<uuid>'
                    'token': '<token>'
            }

        :param token: The authentication token.
        :type token: str
        """
        self._creds = {
            'token': {
                'uuid': self._uuid,
                'token': token,
            }
        }

    def _get_token(self):
        """
        Return current token from credentials dictionary.
        """
        return self._creds['token']['token']

    token = property(_get_token, _set_token, doc='The authentication Token.')

    #
    # Recovery document export and import methods
    #

    def export_recovery_document(self):
        """
        Export the storage secrets.

        A recovery document has the following structure:

            {
                'storage_secrets': {
                    '<storage_secret id>': {
                        'kdf': 'scrypt',
                        'kdf_salt': '<b64 repr of salt>'
                        'kdf_length': <key length>
                        'cipher': 'aes256',
                        'length': <secret length>,
                        'secret': '<encrypted storage_secret>',
                    },
                },
                'kdf': 'scrypt',
                'kdf_salt': '<b64 repr of salt>',
                'kdf_length: <key length>,
                '_mac_method': 'hmac',
                '_mac': '<mac>'
            }

        Note that multiple storage secrets might be stored in one recovery
        document. This method will also calculate a MAC of a string
        representation of the secrets dictionary.

        :return: The recovery document.
        :rtype: dict
        """
        # create salt and key for calculating MAC
        salt = os.urandom(self.SALT_LENGTH)
        key = scrypt.hash(self._passphrase_as_string(), salt, buflen=32)
        data = {
            self.STORAGE_SECRETS_KEY: self._secrets,
            self.KDF_KEY: self.KDF_SCRYPT,
            self.KDF_SALT_KEY: binascii.b2a_base64(salt),
            self.KDF_LENGTH_KEY: len(key),
            MAC_METHOD_KEY: MacMethods.HMAC,
            MAC_KEY: hmac.new(
                key,
                json.dumps(self._secrets),
                sha256).hexdigest(),
        }
        return data

    def import_recovery_document(self, data):
        """
        Import storage secrets for symmetric encryption and uuid (if present)
        from a recovery document.

        Note that this method does not store the imported data on disk. For
        that, use C{self._store_secrets()}.

        :param data: The recovery document.
        :type data: dict

        :return: A tuple containing the number of imported secrets and whether
                 there was MAC informationa available for authenticating.
        :rtype: (int, bool)
        """
        soledad_assert(self.STORAGE_SECRETS_KEY in data)
        # check mac of the recovery document
        #mac_auth = False  # XXX ?
        mac = None
        if MAC_KEY in data:
            soledad_assert(data[MAC_KEY] is not None)
            soledad_assert(MAC_METHOD_KEY in data)
            soledad_assert(self.KDF_KEY in data)
            soledad_assert(self.KDF_SALT_KEY in data)
            soledad_assert(self.KDF_LENGTH_KEY in data)
            if data[MAC_METHOD_KEY] == MacMethods.HMAC:
                key = scrypt.hash(
                    self._passphrase_as_string(),
                    binascii.a2b_base64(data[self.KDF_SALT_KEY]),
                    buflen=32)
                mac = hmac.new(
                    key,
                    json.dumps(data[self.STORAGE_SECRETS_KEY]),
                    sha256).hexdigest()
            else:
                raise UnknownMacMethod('Unknown MAC method: %s.' %
                                       data[MAC_METHOD_KEY])
            if mac != data[MAC_KEY]:
                raise WrongMac('Could not authenticate recovery document\'s '
                               'contents.')
            #mac_auth = True  # XXX ?
        # include secrets in the secret pool.
        secrets = 0
        for secret_id, secret_data in data[self.STORAGE_SECRETS_KEY].items():
            if secret_id not in self._secrets:
                secrets += 1
                self._secrets[secret_id] = secret_data
        return secrets, mac

    #
    # Setters/getters
    #

    def _get_uuid(self):
        return self._uuid

    uuid = property(_get_uuid, doc='The user uuid.')

    def _get_secret_id(self):
        return self._secret_id

    secret_id = property(
        _get_secret_id,
        doc='The active secret id.')

    def _get_secrets_path(self):
        return self._secrets_path

    secrets_path = property(
        _get_secrets_path,
        doc='The path for the file containing the encrypted symmetric secret.')

    def _get_local_db_path(self):
        return self._local_db_path

    local_db_path = property(
        _get_local_db_path,
        doc='The path for the local database replica.')

    def _get_server_url(self):
        return self._server_url

    server_url = property(
        _get_server_url,
        doc='The URL of the Soledad server.')

    storage_secret = property(
        _get_storage_secret,
        doc='The secret used for symmetric encryption.')

    def _get_passphrase(self):
        return self._passphrase

    passphrase = property(
        _get_passphrase,
        doc='The passphrase for locking and unlocking encryption secrets for '
            'local and remote storage.')

    def _passphrase_as_string(self):
        return self._passphrase.encode('utf-8')

    #
    # Symmetric encryption of syncing docs
    #

    def _encrypt_syncing_docs(self):
        """
        Process the syncing queue and send the documents there
        to be encrypted in the sync db. They will be read by the
        SoledadSyncTarget during the sync_exchange.

        Called periodical from the TimerTask self._sync_watcher.
        """
        lock = self.encrypting_lock
        # optional wait flag used to avoid blocking
        if not lock.acquire(False):
            return
        else:
            queue = self._sync_queue
            try:
                while not queue.empty():
                    doc = queue.get_nowait()
                    self._sync_enc_pool.encrypt_doc(doc)
            except Exception as exc:
                logger.error("Error while  encrypting docs to sync")
                logger.exception(exc)
            finally:
                lock.release()


#-----------------------------------------------------------------------------
# Monkey patching u1db to be able to provide a custom SSL cert
#-----------------------------------------------------------------------------

# We need a more reasonable timeout (in seconds)
SOLEDAD_TIMEOUT = 120


class VerifiedHTTPSConnection(httplib.HTTPSConnection):
    """
    HTTPSConnection verifying server side certificates.
    """
    # derived from httplib.py

    def connect(self):
        """
        Connect to a host on a given (SSL) port.
        """
        try:
            source = self.source_address
            sock = socket.create_connection((self.host, self.port),
                                            SOLEDAD_TIMEOUT, source)
        except AttributeError:
            # source_address was introduced in 2.7
            sock = socket.create_connection((self.host, self.port),
                                            SOLEDAD_TIMEOUT)
        if self._tunnel_host:
            self.sock = sock
            self._tunnel()

        self.sock = ssl.wrap_socket(sock,
                                    ca_certs=SOLEDAD_CERT,
                                    cert_reqs=ssl.CERT_REQUIRED)
        match_hostname(self.sock.getpeercert(), self.host)


old__VerifiedHTTPSConnection = http_client._VerifiedHTTPSConnection
http_client._VerifiedHTTPSConnection = VerifiedHTTPSConnection


__all__ = ['soledad_assert', 'Soledad']

from ._version import get_versions
__version__ = get_versions()['version']
del get_versions