-
Notifications
You must be signed in to change notification settings - Fork 212
/
gyb.py
executable file
·2918 lines (2766 loc) · 116 KB
/
gyb.py
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
#!/usr/bin/env python3
#
# Got Your Back
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""\n%s\n\nGot Your Back (GYB) is a command line tool which allows users to
backup and restore their Gmail.
For more information, see https://git.io/gyb/
"""
global __name__, __author__, __email__, __version__, __license__
__program_name__ = 'Got Your Back: Gmail Backup'
__author__ = 'Jay Lee'
__email__ = 'jay0lee@gmail.com'
__version__ = '1.82'
__license__ = 'Apache License 2.0 (https://www.apache.org/licenses/LICENSE-2.0)'
__website__ = 'jaylee.us/gyb'
__db_schema_version__ = '6'
__db_schema_min_version__ = '6' #Minimum for restore
global extra_args, options, allLabelIds, allLabels, gmail, reserved_labels, thread_msgid_map
extra_args = {'prettyPrint': False}
allLabelIds = dict()
allLabels = dict()
reserved_labels = ['inbox', 'spam', 'trash', 'unread', 'starred', 'important',
'sent', 'draft', 'chat', 'chats', 'migrated', 'todo', 'todos', 'buzz',
'bin', 'allmail', 'drafts', 'archive', 'archived', 'muted']
system_labels = ['INBOX', 'SPAM', 'TRASH', 'UNREAD', 'STARRED', 'IMPORTANT',
'SENT', 'DRAFT', 'CATEGORY_PERSONAL', 'CATEGORY_SOCIAL',
'CATEGORY_PROMOTIONS', 'CATEGORY_UPDATES', 'CATEGORY_FORUMS']
thread_msgid_map = {}
mbox_extensions = ['mbx', 'mbox', 'eml']
import argparse
from csv import DictReader
import importlib
from io import BytesIO
import sys
import os
import os.path
from importlib.metadata import version as lib_version
import ipaddress
import multiprocessing
from urllib.parse import urlencode, urlparse, parse_qs
import wsgiref.simple_server
import wsgiref.util
import time
import calendar
import random
import struct
import platform
import datetime
import socket
import sqlite3
import ssl
import email
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.utils import (format_datetime,
make_msgid)
import hashlib
import re
import string
from itertools import islice, chain
import base64
import json
import xml.etree.ElementTree as etree
from urllib.parse import urlencode
import configparser
import webbrowser
import threading
import httplib2
import google.oauth2.service_account
import google_auth_oauthlib.flow
import google_auth_httplib2
import google.oauth2.id_token
import googleapiclient
from googleapiclient.discovery import build, build_from_document, V2_DISCOVERY_URI
from googleapiclient.http import MediaIoBaseUpload, BatchHttpRequest
import googleapiclient.errors
import fmbox
import labellang
def getGYBVersion(divider="\n"):
api_client_ver = lib_version('google-api-python-client')
return ('Got Your Back %s~DIV~%s~DIV~%s - %s~DIV~Python %s.%s.%s %s-bit \
%s~DIV~google-api-client %s~DIV~%s %s' % (__version__, __website__, __author__, __email__,
sys.version_info[0], sys.version_info[1], sys.version_info[2],
struct.calcsize('P')*8, sys.version_info[3], api_client_ver, platform.platform(),
platform.machine())).replace('~DIV~', divider)
USER_AGENT = getGYBVersion(' | ')
# Override and wrap google_auth_httplib2 request methods so that the
# user-agent string is inserted into HTTP request headers.
def _request_with_user_agent(request_method):
"""Inserts the user-agent header kwargs sent to a method."""
def wrapped_request_method(self, *args, **kwargs):
if kwargs.get('headers') is not None:
if kwargs['headers'].get('user-agent'):
if USER_AGENT not in kwargs['headers']['user-agent']:
# Save the existing user-agent header and tack on the user-agent.
kwargs['headers']['user-agent'] = '%s %s' % (USER_AGENT, kwargs['headers']['user-agent'])
else:
kwargs['headers']['user-agent'] = USER_AGENT
else:
kwargs['headers'] = {'user-agent': USER_AGENT}
return request_method(self, *args, **kwargs)
return wrapped_request_method
google_auth_httplib2.Request.__call__ = _request_with_user_agent(
google_auth_httplib2.Request.__call__)
google_auth_httplib2.AuthorizedHttp.request = _request_with_user_agent(
google_auth_httplib2.AuthorizedHttp.request)
def SetupOptionParser(argv):
tls_choices = ['TLSv1_2', 'TLSv1_3']
tls_min_default = tls_choices[-1]
parser = argparse.ArgumentParser(add_help=False)
parser.add_argument('--email',
dest='email',
help='Full email address of user or group to act against')
action_choices = ['backup','backup-chat', 'restore', 'restore-group', 'restore-mbox',
'count', 'purge', 'purge-labels', 'print-labels', 'estimate', 'quota', 'reindex', 'revoke',
'split-mbox', 'create-project', 'delete-projects', 'check-service-account', 'create-label']
parser.add_argument('--action',
choices=action_choices,
dest='action',
default='backup',
help='Action to perform. Default is backup.')
parser.add_argument('--search',
dest='gmail_search',
default='-is:chat',
help='Optional: On backup, estimate, count and purge, Gmail search to \
scope operation against')
parser.add_argument('--local-folder',
dest='local_folder',
help='Optional: On backup, restore, estimate, local folder to use. \
Default is GYB-GMail-Backup-<email>',
default='XXXuse-email-addressXXX')
parser.add_argument('--label-restored',
action='append',
dest='label_restored',
help='Optional: On restore, all messages will additionally receive \
this label. For example, "--label_restored gyb-restored" will label all \
uploaded messages with a gyb-restored label.',
default=[])
parser.add_argument('--label-prefix',
action='append',
dest='label_prefix',
help='Optional: On restore, all labels will additionally receive \
this prefix label. For example, "--label-prefix gyb-archive" will become main label of all \
uploaded labels with a gyb-archive label. \
ATTENTION - This is not compatible with --label-strip \
ATTENTION - this will also create one INBOX and SENT specific label',
default=[])
parser.add_argument('--strip-labels',
dest='strip_labels',
action='store_true',
default=False,
help='Optional: On restore and restore-mbox, strip existing labels from \
messages except for those explicitly declared with the --label-restored \
parameter.')
parser.add_argument('--vault',
action='store_true',
default=None,
dest='vault',
help='Optional: On restore and restore-mbox, restored messages will not be\
visible in user\'s Gmail but are subject to Vault discovery/retention.')
parser.add_argument('--service-account',
action='store_true',
dest='service_account',
help='Google Workspace only. Use OAuth 2.0 Service \
Account to authenticate.')
parser.add_argument('--use-admin',
dest='use_admin',
help='Optional: On restore-group, authenticate as this admin user.')
parser.add_argument('--spam-trash',
dest='spamtrash',
action='store_true',
help='Optional: Include Spam and Trash folders in backup, estimate and count actions. This is always enabled for purge.')
parser.add_argument('--batch-size',
dest='batch_size',
metavar='{1 - 100}',
type=int,
choices=list(range(1,101)),
default=0, # default of 0 means use per action default
help='Optional: Sets the number of operations to perform at once.')
parser.add_argument('--noresume',
action='store_true',
help='Optional: On restores, start from beginning. Default is to resume \
where last restore left off.')
parser.add_argument('--fast-incremental',
dest='refresh',
action='store_false',
default=True,
help='Optional: On backup, skips refreshing labels for existing message')
parser.add_argument('--debug',
action='store_true',
dest='debug',
help='Turn on verbose debugging and connection information \
(troubleshooting)')
parser.add_argument('--memory-limit',
dest='memory_limit',
type=int,
default=0,
help='Limit in megabytes batch requests allow. Prevents memory issues.')
if tls_choices:
parser.add_argument('--tls-min-version',
dest='tls_min_version',
default=tls_min_default,
choices=tls_choices,
help='Set minimum version of TLS HTTPS connections require. Default is TLSv1_3')
parser.add_argument('--tls-max-version',
dest='tls_max_version',
default=None,
choices=tls_choices,
help='Set maximum version of TLS HTTPS connections use. Default is no max')
parser.add_argument('--ca-file',
dest='ca_file',
default=None,
help='specify a certificate authority to use for validating HTTPS hosts.')
parser.add_argument('--extra-reserved-labels',
dest='extra_reserved_labels',
nargs='+',
help='extra labels that should be treated as reserved.')
parser.add_argument('--extra-system-labels',
dest='extra_system_labels',
nargs='+',
help='extra labels that should be treated as system labels.')
parser.add_argument('--config-folder',
dest='config_folder',
help='Optional: Alternate folder to store config and credentials',
default=getProgPath())
parser.add_argument('--cleanup',
action='store_true',
dest='cleanup',
help='Attempt to cleanup Message-Id, From and Date headers on restore to avoid issues. MAKES PERMANENT CHANGES TO RESTORED MESSAGES.')
now_date_header = email.utils.formatdate(localtime=True)
parser.add_argument('--cleanup-date',
dest='cleanup_date',
help=f'Date header to use if --cleanup is specified and IF message date header is missing or is not parsable. Format should look like "{now_date_header}". Defaults to now.',
default=now_date_header)
default_cleanup_from = 'GYB Restore <gyb-restore@gyb-restore.local>'
parser.add_argument('--cleanup-from',
dest='cleanup_from',
help=f'From header to use if --cleanup is specified and IF message from header is missing or not parasable. Default is "{default_cleanup_from}". Use a similar format.',
default=default_cleanup_from)
parser.add_argument('--version',
action='store_true',
dest='version',
help='print GYB version and quit')
parser.add_argument('--short-version',
action='store_true',
dest='shortversion',
help='Just print version and quit')
parser.add_argument('--help',
action='help',
help='Display this message.')
return parser.parse_args(argv)
# from:
# https://developers.google.com/gmail/api/reference/quota
# https://developers.google.com/admin-sdk/groups-migration/v1/reference/archive/insert
GOOGLEQUOTAS = {
"groupsmigration.archive.insert": 1,
"gmail.users.labels.create": 5,
"gmail.users.labels.delete": 5,
"gmail.users.labels.list": 1,
"gmail.users.messages.batchDelete": 50,
"gmail.users.messages.get": 5,
"gmail.users.messages.import": 25,
"gmail.users.messages.insert": 25,
"gmail.users.messages.list": 5,
}
def getQuota(method):
"""
Blocks until it has obtained enough tokens for the given method.
Parameters:
method (googleapiclient.http.HttpRequest | googleapiclient.http.BatchHttpRequest):
a method API request that needs quota prior to sending.
"""
if isinstance(method, BatchHttpRequest):
method_ids = [m.methodId for m in method._requests.values()]
else:
method_ids = [method.methodId]
for m in method_ids:
try:
bucket_name = m.split(".")[0]
bucket = buckets[bucket_name]
except KeyError:
# the base API group does not have quota support
continue
except IndexError:
systemErrorExit(1, "empty method ID")
bucket.get(m)
class QuotaBucket:
"""
basic token bucket for Google's rate limiting.
https://developers.google.com/gmail/api/reference/quota
https://developers.google.com/admin-sdk/groups-migration/v1/reference/archive/insert
"""
def __init__(self, size, interval, refill_size):
"""
Parameters:
size (int): how many total tokens the bucket can hold. It will start with this many.
interval (float): How many seconds between refilling the bucket.
refill_size (int): How many tokens to add during each refill.
"""
self.size = size
self.interval = interval
self.refill_size = refill_size
self.tokens = size
self.lock = threading.Lock()
self.fill_event = threading.Event()
self.set_timer()
def set_timer(self):
t = threading.Timer(self.interval, self.fill)
t.daemon = True
t.start()
def fill(self):
self.set_timer()
with self.lock:
self.tokens = min(self.size, self.tokens + self.refill_size)
self.fill_event.set()
self.fill_event = threading.Event()
def get(self, method):
"""
Blocks until it has obtained enough tokens for the given method.
Parameters:
method (str): name of the API method to be called
"""
try:
needed = GOOGLEQUOTAS[method]
except KeyError:
systemErrorExit(1, "missing quota data for method: " + method)
while True:
my_event = None
with self.lock:
self.tokens -= needed
if self.tokens >= 0:
return
needed = abs(self.tokens)
self.tokens = 0
my_event = self.fill_event
# wait for the next fill to happen
my_event.wait()
# Bucket names are the first segment of the method ID. Start here if you need
# to add rate limiting for an API group. Then add methods to the GOOGLEQUOTAS
# dictionary above.
buckets = {
"gmail": QuotaBucket(250, 0.5, 125),
"groupsmigration": QuotaBucket(10, 1, 10),
}
def getProgPath():
if os.environ.get('STATICX_PROG_PATH', False):
# StaticX static executable
return os.path.dirname(os.environ['STATICX_PROG_PATH'])
elif getattr(sys, 'frozen', False):
# PyInstaller exe
return os.path.dirname(sys.executable)
else:
# Source code
return os.path.dirname(os.path.realpath(__file__))
def getValidOauth2TxtCredentials(force_refresh=False):
"""Gets OAuth2 credentials which are guaranteed to be fresh and valid."""
credentials = getOauth2TxtStorageCredentials()
if (credentials and credentials.expired) or force_refresh:
retries = 3
for n in range(1, retries+1):
try:
req = google_auth_httplib2.Request(_createHttpObj())
credentials.refresh(req)
writeCredentials(credentials)
break
except google.auth.exceptions.RefreshError as e:
systemErrorExit(18, str(e))
except (google.auth.exceptions.TransportError, httplib2.ServerNotFoundError, RuntimeError) as e:
if n != retries:
waitOnFailure(n, retries, str(e))
continue
systemErrorExit(4, str(e))
elif credentials is None or not credentials.valid:
requestOAuthAccess()
credentials = getOauth2TxtStorageCredentials()
return credentials
def getOauth2TxtStorageCredentials():
auth_as = options.use_admin if options.use_admin else options.email
cfgFile = os.path.join(options.config_folder, '%s.cfg' % auth_as)
oauth_string = readFile(cfgFile, continueOnError=True, displayError=False)
if not oauth_string:
return
oauth_data = json.loads(oauth_string)
oauth_data['type'] = 'authorized_user'
if os.environ.get('GOOGLE_API_CLIENT_CERTIFICATE') and \
os.environ.get('GOOGLE_API_CLIENT_PRIVATE_KEY'):
oauth_data['token_uri'] = 'https://oauth2.mtls.googleapis.com/token'
else:
oauth_data['token_uri'] = 'https://oauth2.googleapis.com/token'
google.oauth2.credentials._GOOGLE_OAUTH2_TOKEN_ENDPOINT = oauth_data['token_uri']
creds = google.oauth2.credentials.Credentials.from_authorized_user_info(oauth_data)
creds.token = oauth_data.get('token', oauth_data.get('auth_token', ''))
creds._id_token = oauth_data.get('id_token_jwt', oauth_data.get('id_token', None))
token_expiry = oauth_data.get('token_expiry', '1970-01-01T00:00:01Z')
creds.expiry = datetime.datetime.strptime(token_expiry, '%Y-%m-%dT%H:%M:%SZ')
return creds
def getOAuthClientIDAndSecret():
"""Retrieves the OAuth client ID and client secret from JSON."""
MISSING_CLIENT_SECRETS_MESSAGE = """Please configure a project
To make GYB run you will need to populate the client_secrets.json file. Try
running:
%s --action create-project --email %s
""" % (sys.argv[0], options.email)
filename = os.path.join(options.config_folder, 'client_secrets.json')
cs_data = readFile(filename, continueOnError=True, displayError=True)
if not cs_data:
systemErrorExit(14, MISSING_CLIENT_SECRETS_MESSAGE)
try:
cs_json = json.loads(cs_data)
client_id = cs_json['installed']['client_id']
# chop off .apps.googleusercontent.com suffix as it's not needed
# and we need to keep things short for the Auth URL.
client_id = re.sub(r'\.apps\.googleusercontent\.com$', '', client_id)
client_secret = cs_json['installed']['client_secret']
except (ValueError, IndexError, KeyError):
systemErrorExit(3, 'the format of your client secrets file:\n\n%s\n\n'
'is incorrect. Please recreate the file.' % filename)
return (client_id, client_secret)
def requestOAuthAccess():
auth_as = options.use_admin if options.use_admin else options.email
credentials = getOauth2TxtStorageCredentials()
if credentials and credentials.valid:
return
client_id, client_secret = getOAuthClientIDAndSecret()
possible_scopes = ['https://www.googleapis.com/auth/gmail.modify', # Gmail modify
'https://www.googleapis.com/auth/gmail.readonly', # Gmail readonly
'https://www.googleapis.com/auth/gmail.insert https://www.googleapis.com/auth/gmail.labels', # insert and labels
'https://mail.google.com/', # Gmail Full Access
'', # No Gmail
'https://www.googleapis.com/auth/apps.groups.migration', # Groups Archive Restore
'https://www.googleapis.com/auth/drive.appdata'] # Drive app config (used for quota)
selected_scopes = [' ', ' ', ' ', '*', ' ', '*', '*']
menu = '''Select the actions you wish GYB to be able to perform for %s
[%s] 0) Gmail Backup And Restore - read/write mailbox access
[%s] 1) Gmail Backup Only - read-only mailbox access
[%s] 2) Gmail Restore Only - write-only mailbox access and label management
[%s] 3) Gmail Full Access - read/write mailbox access and message purge
[%s] 4) No Gmail Access
[%s] 5) Groups Restore - write to Google Workspace Groups Archive
[%s] 6) Storage Quota - Drive app config scope used for --action quota
7) Continue
'''
os.system(['clear', 'cls'][os.name == 'nt'])
while True:
selection = input(menu % tuple([auth_as]+selected_scopes))
try:
if int(selection) > -1 and int(selection) <= 6:
if selected_scopes[int(selection)] == ' ':
selected_scopes[int(selection)] = '*'
if int(selection) > -1 and int(selection) <= 4:
for i in range(0,5):
if i == int(selection):
continue
selected_scopes[i] = ' '
else:
selected_scopes[int(selection)] = ' '
elif selection == '7':
at_least_one = False
for i in range(0, len(selected_scopes)):
if selected_scopes[i] in ['*',]:
if i == 4:
continue
at_least_one = True
if at_least_one:
break
else:
os.system(['clear', 'cls'][os.name == 'nt'])
print("YOU MUST SELECT AT LEAST ONE SCOPE!\n")
continue
else:
os.system(['clear', 'cls'][os.name == 'nt'])
print('NOT A VALID SELECTION!\n')
continue
os.system(['clear', 'cls'][os.name == 'nt'])
except ValueError:
os.system(['clear', 'cls'][os.name == 'nt'])
print('NOT A VALID SELECTION!\n')
continue
scopes = ['email',]
for i in range(0, len(selected_scopes)):
if selected_scopes[i] == '*':
scopes.append(possible_scopes[i])
credentials = _run_oauth_flow(client_id, client_secret, scopes, access_type='offline', login_hint=auth_as)
writeCredentials(credentials)
def writeCredentials(creds):
auth_as = options.use_admin if options.use_admin else options.email
cfgFile = os.path.join(options.config_folder, '%s.cfg' % auth_as)
creds_data = {
'token': creds.token,
'refresh_token': creds.refresh_token,
'token_uri': creds.token_uri,
'client_id': creds.client_id,
'client_secret': creds.client_secret,
'id_token': creds.id_token,
'token_expiry': creds.expiry.strftime('%Y-%m-%dT%H:%M:%SZ'),
}
expected_iss = ['https://accounts.google.com', 'accounts.google.com']
if _getValueFromOAuth('iss', creds) not in expected_iss:
systemErrorExit(13, 'Wrong OAuth 2.0 credentials issuer. Got %s, expected one of %s' % (_getValueFromOAuth('iss', creds), ', '.join(expected_iss)))
creds_data['decoded_id_token'] = _decodeIdToken(creds)
data = json.dumps(creds_data, indent=2, sort_keys=True)
writeFile(cfgFile, data)
def _decodeIdToken(credentials=None):
credentials = credentials if credentials is not None else getValidOauth2TxtCredentials()
httpc = google_auth_httplib2.Request(_createHttpObj())
return google.oauth2.id_token.verify_oauth2_token(
credentials.id_token,
httpc,
clock_skew_in_seconds=10)
def _getValueFromOAuth(field, credentials=None):
id_token = _decodeIdToken(credentials)
return id_token.get(field, 'Unknown')
#
# Read a file
#
def readFile(filename, mode='r', continueOnError=False, displayError=True, encoding=None):
try:
if filename != '-':
if not encoding:
with open(os.path.expanduser(filename), mode) as f:
return f.read()
with codecs.open(os.path.expanduser(filename), mode, encoding) as f:
content = f.read()
# codecs does not strip UTF-8 BOM (ef:bb:bf) so we must
if not content.startswith(codecs.BOM_UTF8):
return content
return content[3:]
return unicode(sys.stdin.read())
except IOError as e:
if continueOnError:
if displayError:
sys.stderr.write(str(e))
return None
systemErrorExit(6, e)
except (LookupError, UnicodeDecodeError, UnicodeError) as e:
systemErrorExit(2, str(e))
def doGYBCheckForUpdates(forceCheck=False, debug=False):
def _LatestVersionNotAvailable():
if forceCheck:
systemErrorExit(4, 'GYB Latest Version information not available')
last_update_check_file = os.path.join(options.config_folder, 'lastcheck.txt')
current_version = __version__
now_time = calendar.timegm(time.gmtime())
check_url = 'https://api.github.com/repos/jay0lee/got-your-back/releases' # includes pre-releases
if not forceCheck:
last_check_time_str = readFile(last_update_check_file, continueOnError=True, displayError=False)
last_check_time = int(last_check_time_str) if last_check_time_str and last_check_time_str.isdigit() else 0
if last_check_time > now_time-604800:
return
check_url = check_url + '/latest' # latest full release
headers = {'Accept': 'application/vnd.github.v3.text+json',
'User-Agent': getGYBVersion(' | ')}
anonhttpc = _createHttpObj()
try:
(_, c) = anonhttpc.request(check_url, 'GET', headers=headers)
try:
release_data = json.loads(c.decode('utf-8'))
except ValueError:
_LatestVersionNotAvailable()
return
if isinstance(release_data, list):
release_data = release_data[0] # only care about latest release
if not isinstance(release_data, dict) or 'tag_name' not in release_data:
_LatestVersionNotAvailable()
return
latest_version = release_data['tag_name']
if latest_version[0].lower() == 'v':
latest_version = latest_version[1:]
if forceCheck or (latest_version > current_version):
print('Version Check:\n Current: {0}\n Latest: {1}'.format(current_version, latest_version))
if latest_version <= current_version:
writeFile(last_update_check_file, str(now_time), continueOnError=True, displayError=forceCheck)
return
announcement = release_data.get('body_text', 'No details about this release')
sys.stderr.write('\nGYB %s release notes:\n\n' % latest_version)
sys.stderr.write(announcement)
try:
print('\n\nHit CTRL+C to visit the GYB website and download the latest release or wait 15 seconds to continue with this boring old version. GYB won\'t bother you with this announcement for 1 week or you can create a file named noupdatecheck.txt in the same location as gyb.py or gyb.exe and GYB won\'t ever check for updates.')
time.sleep(15)
except KeyboardInterrupt:
webbrowser.open(release_data['html_url'])
print('GYB exiting for update...')
sys.exit(0)
writeFile(last_update_check_file, str(now_time), continueOnError=True, displayError=forceCheck)
return
except (httplib2.HttpLib2Error, httplib2.ServerNotFoundError):
return
def getAPIVer(api):
if api == 'oauth2':
return 'v2'
elif api == 'gmail':
return 'v1'
elif api == 'groupsmigration':
return 'v1'
elif api == 'drive':
return 'v2'
return 'v1'
def getAPIScope(api):
if api == 'gmail':
return ['https://mail.google.com/']
elif api == 'groupsmigration':
return ['https://www.googleapis.com/auth/apps.groups.migration']
elif api == 'drive':
return ['https://www.googleapis.com/auth/drive.appdata']
def get_cert_files():
return (os.environ.get('GOOGLE_API_CLIENT_CERTIFICATE'),
os.environ.get('GOOGLE_API_CLIENT_PRIVATE_KEY'),
None)
def getClientOptions():
client_options = {}
if os.environ.get('GOOGLE_API_CLIENT_CERTIFICATE') and \
os.environ.get('GOOGLE_API_CLIENT_PRIVATE_KEY'):
client_options['client_encrypted_cert_source'] = get_cert_files
return client_options
def buildGAPIObject(api, httpc=None):
if not httpc:
credentials = getValidOauth2TxtCredentials()
httpc = google_auth_httplib2.AuthorizedHttp(credentials, _createHttpObj())
if options.debug:
extra_args['prettyPrint'] = True
if os.path.isfile(os.path.join(options.config_folder, 'extra-args.txt')):
config = configparser.ConfigParser()
config.optionxform = str
config.read(os.path.join(options.config_folder, 'extra-args.txt'))
extra_args.update(dict(config.items('extra-args')))
version = getAPIVer(api)
client_options = getClientOptions()
try:
service = build(
api,
version,
http=httpc,
cache_discovery=False,
client_options=client_options,
static_discovery=False)
except googleapiclient.errors.UnknownApiNameOrVersion:
disc_file = os.path.join(options.config_folder, f'{api}-{version}.json')
if os.path.isfile(disc_file):
with open(disc_file, 'r') as f:
discovery = f.read()
service = build_from_document(discovery,
http=httpc)
else:
print('No online discovery doc and %s does not exist locally'
% disc_file)
raise
if os.environ.get('GOOGLE_API_CLIENT_CERTIFICATE') and \
os.environ.get('GOOGLE_API_CLIENT_PRIVATE_KEY'):
root_url = service._rootDesc.get('rootUrl')
mtls_root_url = service._rootDesc.get('mtlsRootUrl')
if not mtls_root_url:
if api == 'oauth2':
# OA2 API is broken on mTLS, just use regular host
mtls_root_url = root_url
else:
mtls_root_url = re.sub(r'googleapis\.com',
'mtls.googleapis.com',
root_url)
base_url = service._rootDesc.get('baseUrl')
base_url_suffix = base_url.replace(root_url, '')
mtls_base_url = f'{mtls_root_url}{base_url_suffix}'
# force TLS URLs
service._rootDesc['baseUrl'] = mtls_base_url
service._rootDesc['rootUrl'] = mtls_root_url
service._baseUrl = mtls_base_url
# rebuild functions like batch with TLS URL
service._add_basic_methods(
service._resourceDesc,
service._rootDesc,
service._schema)
return service
def buildGAPIServiceObject(api, soft_errors=False):
global extra_args
auth_as = options.use_admin if options.use_admin else options.email
scopes = getAPIScope(api)
credentials = getSvcAcctCredentials(scopes, auth_as)
if options.debug:
extra_args['prettyPrint'] = True
if os.path.isfile(os.path.join(options.config_folder, 'extra-args.txt')):
config = configparser.ConfigParser()
config.optionxform = str
ex_args_file = os.path.join(options.config_folder, 'extra-args.txt')
config.read(ex_args_file)
extra_args.update(dict(config.items('extra-args')))
httpc = _createHttpObj()
request = google_auth_httplib2.Request(httpc)
credentials.refresh(request)
version = getAPIVer(api)
client_options = getClientOptions()
try:
service = build(
api,
version,
http=httpc,
cache_discovery=False,
client_options=client_options,
static_discovery=False)
service._http = google_auth_httplib2.AuthorizedHttp(credentials, http=httpc)
return service
except (httplib2.ServerNotFoundError, RuntimeError) as e:
systemErrorExit(4, e)
except google.auth.exceptions.RefreshError as e:
if isinstance(e.args, tuple):
e = e.args[0]
systemErrorExit(5, e)
def _backoff(n, retries, reason):
wait_on_fail = (2 ** n) if (2 ** n) < 60 else 60
randomness = float(random.randint(1,1000)) / 1000
wait_on_fail += randomness
if n > 3:
sys.stderr.write('\nTemp error %s. Backing off %s seconds...'
% (reason, int(wait_on_fail)))
time.sleep(wait_on_fail)
if n > 3:
sys.stderr.write('attempt %s/%s\n' % (n+1, retries))
def callGAPI(service, function, soft_errors=False, throw_reasons=[], retry_reasons=[], **kwargs):
retries = 10
parameters = kwargs.copy()
parameters.update(extra_args)
for n in range(1, retries+1):
try:
if function:
method = getattr(service, function)(**parameters)
else:
method = service
getQuota(method)
return method.execute()
except googleapiclient.errors.MediaUploadSizeError as e:
sys.stderr.write('\nERROR: %s' % (e))
if soft_errors:
sys.stderr.write(' - Giving up.\n')
return
else:
sys.exit(int(http_status))
except (OSError,
socket.timeout,
socket.gaierror,
ssl.SSLEOFError,
httplib2.error.ServerNotFoundError) as e:
_backoff(n, retries, e)
continue
except googleapiclient.errors.HttpError as e:
try:
error = json.loads(e.content.decode('utf-8'))
reason = error['error']['errors'][0]['reason']
http_status = error['error']['code']
message = error['error']['errors'][0]['message']
except (KeyError, json.decoder.JSONDecodeError):
http_status = int(e.resp['status'])
reason = http_status
message = e.content
if reason in throw_reasons:
raise
if n != retries and (http_status >= 500 or
reason in ['rateLimitExceeded', 'userRateLimitExceeded', 'backendError'] or
reason in retry_reasons):
_backoff(n, retries, reason)
continue
sys.stderr.write('\n%s: %s - %s\n' % (http_status, message, reason))
if soft_errors:
sys.stderr.write(' - Giving up.\n')
return
else:
sys.exit(int(http_status))
except google.auth.exceptions.RefreshError as e:
sys.stderr.write('Error: Authentication Token Error - %s' % e)
sys.exit(403)
def callGAPIpages(service, function, items='items',
nextPageToken='nextPageToken', page_message=None, message_attribute=None,
**kwargs):
pageToken = None
all_pages = list()
total_items = 0
while True:
this_page = callGAPI(service, function,
pageToken=pageToken, **kwargs)
if not this_page:
this_page = {items: []}
try:
page_items = len(this_page[items])
except KeyError:
page_items = 0
total_items += page_items
if page_message:
show_message = page_message
try:
show_message = show_message.replace('%%num_items%%', str(page_items))
except (IndexError, KeyError):
show_message = show_message.replace('%%num_items%%', '0')
try:
show_message = show_message.replace('%%total_items%%',
str(total_items))
except (IndexError, KeyError):
show_message = show_message.replace('%%total_items%%', '0')
if message_attribute:
try:
show_message = show_message.replace('%%first_item%%',
str(this_page[items][0][message_attribute]))
show_message = show_message.replace('%%last_item%%',
str(this_page[items][-1][message_attribute]))
except (IndexError, KeyError):
show_message = show_message.replace('%%first_item%%', '')
show_message = show_message.replace('%%last_item%%', '')
rewrite_line(show_message)
try:
all_pages += this_page[items]
pageToken = this_page[nextPageToken]
if pageToken == '':
return all_pages
except (IndexError, KeyError):
if page_message:
sys.stderr.write('\n')
return all_pages
VALIDEMAIL_PATTERN = re.compile(r'^[^@]+@[^@]+\.[^@]+$')
def getValidateLoginHint(login_hint):
if login_hint:
login_hint = login_hint.strip()
if VALIDEMAIL_PATTERN.match(login_hint):
return login_hint
while True:
login_hint = input('\nWhat is your Google Workspace admin email address? ').strip()
if VALIDEMAIL_PATTERN.match(login_hint):
return login_hint
print('Error: that is not a valid email address')
def percentage(part, whole):
return '{0:.2f}'.format(100 * float(part)/float(whole))
def shorten_url(long_url):
simplehttp = _createHttpObj(timeout=10)
url_shortnr = 'https://gyb-shortn.jaylee.us/create'
headers = {'Content-Type': 'application/json',
'User-Agent': getGYBVersion(' | ')}
try:
resp, content = simplehttp.request(url_shortnr, 'POST',
f'{{"long_url": "{long_url}"}}', headers=headers)
except Exception as e:
return long_url
if resp.status != 200:
return long_url
try:
return json.loads(content).get('short_url', long_url)
except Exception as e:
print(content)
return long_url
def _localhost_to_ip():
'''returns IPv4 or IPv6 loopback address which localhost resolves to.
If localhost does not resolve to valid loopback IP address then returns
127.0.0.1'''
# TODO gethostbyname() will only ever return ipv4
# find a way to support IPv6 here and get preferred IP
# note that IPv6 may be broken on some systems also :-(
# for now IPv4 should do.
local_ip = socket.gethostbyname('localhost')
local_ipaddress = ipaddress.ip_address(local_ip)
ip4_local_range = ipaddress.ip_network('127.0.0.0/8')
ip6_local_range = ipaddress.ip_network('::1/128')
if local_ipaddress not in ip4_local_range and \
local_ipaddress not in ip6_local_range:
local_ip = '127.0.0.1'
return local_ip
def _wait_for_http_client(d):
wsgi_app = google_auth_oauthlib.flow._RedirectWSGIApp(MESSAGE_LOCAL_SERVER_SUCCESS)
wsgiref.simple_server.WSGIServer.allow_reuse_address = False
# Convert hostn to IP since apparently binding to the IP
# reduces odds of firewall blocking us
local_ip = _localhost_to_ip()
for port in range(8080, 8099):
try:
local_server = wsgiref.simple_server.make_server(
local_ip,
port,
wsgi_app,
handler_class=wsgiref.simple_server.WSGIRequestHandler
)
break
except OSError:
pass
redirect_uri_format = (
"http://{}:{}/" if d['trailing_slash'] else "http://{}:{}"
)
# provide redirect_uri to main process so it can formulate auth_url
d['redirect_uri'] = redirect_uri_format.format(*local_server.server_address)
# wait until main process provides auth_url
# so we can open it in web browser.
while 'auth_url' not in d:
time.sleep(0.1)
if d['open_browser']:
webbrowser.open(d['auth_url'], new=1, autoraise=True)
local_server.handle_request()
authorization_response = wsgi_app.last_request_uri.replace("http", "https")
d['code'] = authorization_response
local_server.server_close()
def _wait_for_user_input(d):
sys.stdin = open(0)
code = input(MESSAGE_CONSOLE_AUTHORIZATION_CODE)
d['code'] = code
MESSAGE_CONSOLE_AUTHORIZATION_PROMPT = '''\nGo to the following link in your browser:
\n\t{url}\n
IMPORTANT: If you get a browser error that the site can't be reached AFTER you
click the Allow button, copy the URL from the browser where the error occurred
and paste that here instead.
'''
MESSAGE_CONSOLE_AUTHORIZATION_CODE = 'Enter verification code or browser URL: '
MESSAGE_LOCAL_SERVER_SUCCESS = ('The authentication flow has completed. You may'
' close this browser window and return to GYB.')
MESSAGE_AUTHENTICATION_COMPLETE = ('\nThe authentication flow has completed.\n')
class ShortURLFlow(google_auth_oauthlib.flow.InstalledAppFlow):
def authorization_url(self, **kwargs):
long_url, state = super(ShortURLFlow, self).authorization_url(**kwargs)
short_url = shorten_url(long_url)
return short_url, state
def run_dual(self,
use_console_flow,
authorization_prompt_message='',