-
Notifications
You must be signed in to change notification settings - Fork 0
/
lvfs.py
1592 lines (1398 loc) · 56.7 KB
/
lvfs.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/python2
# -*- coding: utf-8 -*-
#
# Copyright (C) 2015 Richard Hughes <richard@hughsie.com>
# Licensed under the GNU General Public License Version 2
import os
import hashlib
import math
import glob
import calendar
import datetime
import ConfigParser
from flask import Blueprint, session, request, flash, url_for, redirect, \
render_template, abort
import cabarchive
import appstream
from affidavit import Affidavit, NoKeyError
from db import LvfsDatabase, CursorError
from db_clients import LvfsDatabaseClients, LvfsDownloadKind
from db_eventlog import LvfsDatabaseEventlog
from db_firmware import LvfsDatabaseFirmware, LvfsFirmware, LvfsFirmwareMd
from db_users import LvfsDatabaseUsers, _password_hash
from db_cache import LvfsDatabaseCache
from inf_parser import InfParser
from backup import ensure_checkpoint
from config import DOWNLOAD_DIR, UPLOAD_DIR, CABEXTRACT_CMD, KEYRING_DIR
from util import _qa_hash
from metadata import metadata_update_qa_group, metadata_update_targets
def sizeof_fmt(num, suffix='B'):
""" Generate user-visible size """
if not type(num) in (int, long):
return "???%s???" % num
for unit in ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi']:
if abs(num) < 1024.0:
return "%3.1f%s%s" % (num, unit, suffix)
num /= 1024.0
return "%.1f%s%s" % (num, 'Yi', suffix)
def _password_check(value):
""" Check the password for suitability """
success = True
if len(value) < 8:
success = False
flash('The password is too short, the minimum is 8 characters')
if len(value) > 40:
success = False
flash('The password is too long, the maximum is 40 characters')
if value.lower() == value:
success = False
flash('The password requires at least one uppercase character')
if value.isalnum():
success = False
flash('The password requires at least one non-alphanumeric character')
return success
def _email_check(value):
""" Do a quick and dirty check on the email address """
if len(value) < 5 or value.find('@') == -1 or value.find('.') == -1:
flash('Invalid email address')
return False
return True
def _get_chart_labels_months():
""" Gets the chart labels """
now = datetime.date.today()
labels = []
offset = 0
for i in range(0, 12):
if now.month - i == 0:
offset = 1
labels.append(calendar.month_name[now.month - i - offset])
return labels
def _get_chart_labels_days():
""" Gets the chart labels """
now = datetime.date.today()
labels = []
for i in range(0, 30):
then = now - datetime.timedelta(i)
labels.append("%02i-%02i-%02i" % (then.year, then.month, then.day))
return labels
def _get_chart_labels_hours():
""" Gets the chart labels """
labels = []
for i in range(0, 24):
labels.append("%02i" % i)
return labels
def _to_javascript_array(arr):
tmp = '['
for a in arr:
if type(a) == unicode:
tmp += '"' + a + '",'
elif type(a) == long:
tmp += str(a) + ','
else:
tmp += '"' + str(a) + '",'
if len(tmp) > 1:
tmp = tmp[:-1]
tmp += ']'
return tmp
def _get_client_address():
""" Gets user IP address """
if request.headers.getlist("X-Forwarded-For"):
return request.headers.getlist("X-Forwarded-For")[0]
else:
return request.remote_addr
def _event_log(msg, is_important=False):
""" Adds an item to the event log """
username = None
qa_group = None
if 'username' in session:
username = session['username']
if not username:
username = 'anonymous'
if 'qa_group' in session:
qa_group = session['qa_group']
if not qa_group:
qa_group = 'admin'
db = LvfsDatabase(os.environ)
db_eventlog = LvfsDatabaseEventlog(db)
db_eventlog.add(msg, username, qa_group,
_get_client_address(), is_important)
def _check_session():
if not 'username' in session:
return False
if not 'qa_group' in session:
return False
if not 'qa_capability' in session:
return False
if not 'is_locked' in session:
return False
return True
def create_affidavit():
""" Create an affidavit that can be used to sign files """
db = LvfsDatabase(os.environ)
db_users = LvfsDatabaseUsers(db)
key_uid = db_users.get_signing_uid()
return Affidavit(key_uid, KEYRING_DIR)
################################################################################
lvfs = Blueprint('lvfs', __name__, url_prefix='/lvfs', template_folder='templates/lvfs')
@lvfs.errorhandler(401)
def error_permission_denied(msg=None):
""" Error handler: Permission Denied """
_event_log("Permission denied: %s" % msg, is_important=True)
flash("Permission denied: %s" % msg)
return render_template('error.html'), 401
@lvfs.errorhandler(402)
def error_internal(msg=None, errcode=402):
""" Error handler: Internal """
_event_log("Internal error: %s" % msg, is_important=True)
flash("Internal error: %s" % msg)
return render_template('error.html'), errcode
@lvfs.route('/')
def index():
"""
The main page that shows existing firmware and also allows the
user to add new firmware.
"""
if not 'username' in session:
return redirect(url_for('.login'))
return render_template('index.html')
@lvfs.route('/newaccount')
def new_account():
""" New account page for prospective vendors """
return render_template('new-account.html')
@lvfs.route('/metadata')
def metadata():
"""
Show all metadata available to this user.
"""
# security check
if not _check_session():
return redirect(url_for('.login'))
# show static lists based on QA group
qa_url = 'firmware-%s.xml.gz' % _qa_hash(session['qa_group'])
qa_disp = 'firmware-%s….xml.gz' % _qa_hash(session['qa_group'])[0:8]
return render_template('metadata.html',
qa_group=session['qa_group'],
qa_url=qa_url,
qa_desc=qa_disp)
@lvfs.route('/devicelist')
def device_list():
# add devices in stable or testing
try:
db = LvfsDatabase(os.environ)
db_firmware = LvfsDatabaseFirmware(db)
items = db_firmware.get_items()
except CursorError as e:
return error_internal(str(e))
# get a sorted list of vendors
vendors = []
for item in items:
if item.target != 'stable':
continue
vendor = item.mds[0].developer_name
if vendor in vendors:
continue
vendors.append(vendor)
html = ''
seen_guid = {}
for vendor in sorted(vendors):
html += '<h2>%s</h2>\n' % vendor
html += '<ul>\n'
for item in items:
if item.target != 'stable':
continue
for md in item.mds:
# only show correct vendor
if vendor != md.developer_name:
continue
# only show the newest version
if md.guid in seen_guid:
continue
seen_guid[md.guid] = 1
# show name and version
version = item.version_display
if not version:
version = md.version
url = '/downloads/' + item.filename
html += '<li><a href="%s">%s %s</a></li>\n' % (url, md.name, version)
html += '</ul>\n'
return render_template('devicelist.html', dyncontent=html)
@lvfs.route('/upload', methods=['GET', 'POST'])
def upload():
""" Upload a .cab file to the LVFS service """
# only accept form data
if request.method != 'POST':
return redirect(url_for('.index'))
# security check
if not _check_session():
return redirect(url_for('.login'))
# not correct parameters
if not 'target' in request.form:
return error_internal('No target')
if not 'file' in request.files:
return error_internal('No file')
# can the user upload directly to stable
if request.form['target'] in ['stable', 'testing']:
if not session['qa_capability']:
return error_permission_denied('Unable to upload to this target as not QA user')
# check size < 50Mb
fileitem = request.files['file']
if not fileitem:
return error_internal('No file object')
data = fileitem.read()
if len(data) > 50000000:
return error_internal('File too large, limit is 50Mb', 413)
if len(data) == 0:
return error_internal('File has no content')
if len(data) < 1024:
return error_internal('File too small, mimimum is 1k')
# check the file does not already exist
db = LvfsDatabase(os.environ)
db_firmware = LvfsDatabaseFirmware(db)
fwid = hashlib.sha1(data).hexdigest()
try:
item = db_firmware.get_item(fwid)
except CursorError as e:
return error_internal(str(e))
if item:
return error_internal("A firmware file with hash %s already exists" % fwid, 422)
# parse the file
arc = cabarchive.CabArchive()
try:
if os.path.exists(CABEXTRACT_CMD):
arc.set_decompressor(CABEXTRACT_CMD)
arc.parse(data)
except cabarchive.CorruptionError as e:
return error_internal('Invalid file type: %s' % str(e), 415)
except cabarchive.NotSupportedError as e:
return error_internal('The file is unsupported: %s' % str(e), 415)
# check .inf exists
fw_version_inf = None
fw_version_display_inf = None
cf = arc.find_file("*.inf")
if cf:
if cf.contents.find('FIXME') != -1:
return error_internal("The inf file was not complete; "
"Any FIXME text must be replaced with the correct values.")
# check .inf file is valid
cfg = InfParser()
cfg.read_data(cf.contents)
try:
tmp = cfg.get('Version', 'Class')
except (ConfigParser.NoOptionError, ConfigParser.NoSectionError) as e:
return error_internal('The inf file Version:Class was missing')
if not tmp == 'Firmware':
return error_internal('The inf file Version:Class was invalid')
try:
tmp = cfg.get('Version', 'ClassGuid')
except ConfigParser.NoOptionError as e:
return error_internal('The inf file Version:ClassGuid was missing')
if not tmp == '{f2e7dd72-6468-4e36-b6f1-6488f42c1b52}':
return error_internal('The inf file Version:ClassGuid was invalid')
try:
tmp = cfg.get('Version', 'DriverVer')
fw_version_display_inf = tmp.split(',')
if len(fw_version_display_inf) != 2:
return error_internal('The inf file Version:DriverVer was invalid')
except ConfigParser.NoOptionError as e:
pass
# this is optional, but if supplied must match the version in the XML
# -- also note this will not work with multi-firmware .cab files
try:
fw_version_inf = cfg.get('Firmware_AddReg', 'HKR->FirmwareVersion')
if fw_version_inf.startswith('0x'):
fw_version_inf = str(int(fw_version_inf[2:], 16))
if fw_version_inf == '0':
fw_version_inf = None
except (ConfigParser.NoOptionError, ConfigParser.NoSectionError) as e:
pass
# check metainfo exists
cfs = arc.find_files("*.metainfo.xml")
if len(cfs) == 0:
return error_internal('The firmware file had no .metadata.xml files')
# parse each MetaInfo file
apps = []
for cf in cfs:
component = appstream.Component()
try:
component.parse(str(cf.contents))
component.validate()
except appstream.ParseError as e:
return error_internal('The metadata could not be parsed: ' + str(e))
except appstream.ValidationError as e:
return error_internal('The metadata file did not validate: ' + str(e))
# check the file does not have any missing request.form
if cf.contents.find('FIXME') != -1:
return error_internal("The metadata file was not complete; "
"Any FIXME text must be replaced with the correct values.")
# check the firmware provides something
if len(component.provides) == 0:
return error_internal("The metadata file did not provide any GUID.")
if len(component.releases) == 0:
return error_internal("The metadata file did not provide any releases.")
# check the inf file matches up with the .xml file
if fw_version_inf and fw_version_inf != component.releases[0].version:
return error_internal("The inf Firmware_AddReg[HKR->FirmwareVersion] "
"'%s' did not match the metainfo.xml value '%s'."
% (fw_version_inf, component.releases[0].version))
# check the guid and version does not already exist
try:
items = db_firmware.get_items()
except CursorError as e:
return error_internal(str(e))
for item in items:
for md in item.mds:
if md.guid == component.provides[0].value and md.version == component.releases[0].version:
return error_internal("A firmware file for this version already exists", 422)
# check the ID hasn't been reused by a different GUID
for item in items:
for md in item.mds:
if md.cid == component.id and not md.guid == component.provides[0].value:
return error_internal("The %s ID has already been used by GUID %s" % (md.cid, md.guid), 422)
# add to array
apps.append(component)
# only save if we passed all tests
basename = os.path.basename(fileitem.filename)
new_filename = fwid + '-' + basename
if not os.path.exists(UPLOAD_DIR):
os.mkdir(UPLOAD_DIR)
open(os.path.join(UPLOAD_DIR, new_filename), 'wb').write(data)
# fix up the checksums and add the detached signature
for component in apps:
# ensure there's always a container checksum
release = component.releases[0]
csum = release.get_checksum_by_target('content')
if not csum:
csum = appstream.Checksum()
csum.target = 'content'
csum.filename = 'firmware.bin'
component.releases[0].add_checksum(csum)
# get the contents checksum
fw_data = arc.find_file(csum.filename)
if not fw_data:
return error_internal('No %s found in the archive' % csum.filename)
csum.kind = 'sha1'
csum.value = hashlib.sha1(fw_data.contents).hexdigest()
# set the sizes
release.size_installed = len(fw_data.contents)
release.size_download = len(data)
# add the detached signature if not already signed
sig_data = arc.find_file(csum.filename + ".asc")
if not sig_data:
try:
affidavit = create_affidavit()
except NoKeyError as e:
return error_internal('Failed to sign archive: ' + str(e))
cff = cabarchive.CabFile(fw_data.filename + '.asc',
affidavit.create(fw_data.contents))
arc.add_file(cff)
else:
# check this file is signed by something we trust
try:
affidavit = create_affidavit()
affidavit.verify(fw_data.contents)
except NoKeyError as e:
return error_internal('Failed to verify archive: ' + str(e))
# export the new archive and get the checksum
cab_data = arc.save(compressed=True)
checksum_container = hashlib.sha1(cab_data).hexdigest()
# dump to a file
if not os.path.exists(DOWNLOAD_DIR):
os.mkdir(DOWNLOAD_DIR)
fn = os.path.join(DOWNLOAD_DIR, new_filename)
open(fn, 'wb').write(cab_data)
# update database copy
db_cache = LvfsDatabaseCache(db)
db_cache.from_file(fn)
# create parent firmware object
target = request.form['target']
fwobj = LvfsFirmware()
fwobj.qa_group = session['qa_group']
fwobj.addr = _get_client_address()
fwobj.filename = new_filename
fwobj.fwid = fwid
fwobj.target = target
if fw_version_display_inf:
fwobj.version_display = fw_version_display_inf[1]
# create child metadata object for the component
for component in apps:
md = LvfsFirmwareMd()
md.fwid = fwid
md.cid = component.id
md.name = component.name
md.summary = component.summary
md.developer_name = component.developer_name
md.metadata_license = component.metadata_license
md.project_license = component.project_license
md.url_homepage = component.urls['homepage']
md.description = component.description
md.checksum_container = checksum_container
# from the provide
prov = component.provides[0]
md.guid = prov.value
# from the release
rel = component.releases[0]
md.version = rel.version
md.release_description = rel.description
md.release_timestamp = rel.timestamp
md.release_installed_size = rel.size_installed
md.release_download_size = rel.size_download
# from the content checksum
csum = component.releases[0].get_checksum_by_target('content')
md.checksum_contents = csum.value
md.filename_contents = csum.filename
fwobj.mds.append(md)
# add to database
try:
db_firmware.add(fwobj)
except CursorError as e:
return error_internal(str(e))
# set correct response code
_event_log("Uploaded file %s to %s" % (new_filename, target))
# ensure up to date
try:
filenames = []
if target != 'private':
tmp = metadata_update_qa_group(fwobj.qa_group)
filenames.extend(tmp)
if target == 'stable':
tmp = metadata_update_targets(['stable', 'testing'])
filenames.extend(tmp)
elif target == 'testing':
tmp = metadata_update_targets(['testing'])
filenames.extend(tmp)
# create detached signatures
affidavit = create_affidavit()
for filename in filenames:
affidavit.create_detached(filename)
# update database copy
db = LvfsDatabase(os.environ)
db_cache = LvfsDatabaseCache(db)
for fn in filenames:
db_cache.from_file(fn)
db_cache.from_file(fn + '.asc')
except NoKeyError as e:
return error_internal('Failed to sign metadata: ' + str(e))
except CursorError as e:
return error_internal('Failed to generate metadata: ' + str(e))
# ensure we save the latest data
ensure_checkpoint()
return redirect(url_for('.firmware_id', fwid=fwid))
@lvfs.route('/firmware')
def firmware(show_all=False):
"""
Show all previsouly uploaded firmware for this user.
"""
# security check
if not _check_session():
return redirect(url_for('.login'))
# get all firmware
try:
db = LvfsDatabase(os.environ)
db_firmware = LvfsDatabaseFirmware(db)
items = db_firmware.get_items()
except CursorError as e:
return error_internal(str(e))
# nothing!
if len(items) == 0:
html = "<p>No firmware has been uploaded to the " \
"‘%s’ QA group yet.</p>" % session['qa_group']
return render_template('firmware.html', dyncontent=html)
# group by the firmware name
names = {}
for item in items:
# admin can see everything
if session['username'] != 'admin':
if item.qa_group != session['qa_group']:
continue
name = item.mds[0].name
if not name in names:
names[name] = []
names[name].append(item)
html = "<p>"
html += "The following firmware files have been uploaded to the " \
"‘%s’ QA group. " % session['qa_group']
if not show_all:
html += "By default only one firmware per device is shown in each state. "
html += "To show all files for all devices, <a href=\"/lvfs/firmware_all\">click here</a>."
html += "</p>"
# group each thing in it's own header
for name in sorted(names):
html += "<h2>%s</h2>\n" % name
html += "<table class=\"history\">"
html += "<tr>"
html += "<th>Submitted</td>"
html += "<th>Version</td>"
html += "<th>Target</td>"
html += "<th></td>"
html += "</tr>\n"
# by default we only show the first version of each target
targets_seen = {}
for item in names[name]:
# only show one
if item.target in targets_seen:
continue
if not show_all:
targets_seen[item.target] = item
buttons = "<form method=\"get\" action=\"/lvfs/firmware/%s\">" \
"<button class=\"fixedwidth\">Details</button>" \
"</form>" % item.fwid
html += '<tr>'
html += "<td>%s</td>" % item.timestamp
if not item.version_display or item.mds[0].version == item.version_display:
html += "<td>%s</td>" % item.mds[0].version
else:
html += "<td>%s [%s]</td>" % (item.version_display, item.mds[0].version)
html += "<td>%s</td>" % item.target
html += "<td>%s</td>" % buttons
html += '</tr>\n'
html += "</table>"
return render_template('firmware.html', dyncontent=html)
@lvfs.route('/firmware_all')
def firmware_all():
return firmware(True)
@lvfs.route('/firmware/<fwid>/delete')
def firmware_delete(fwid):
""" Confirms deletion of firmware """
return render_template('firmware-delete.html', fwid=fwid), 406
@lvfs.route('/firmware/<fwid>/delete_force')
def firmware_delete_force(fwid):
""" Delete a firmware entry and also delete the file from disk """
# security check
if not _check_session():
return redirect(url_for('.login'))
# check firmware exists in database
db = LvfsDatabase(os.environ)
db_firmware = LvfsDatabaseFirmware(db)
try:
item = db_firmware.get_item(fwid)
except CursorError as e:
return error_internal(str(e))
if not item:
return error_internal("No firmware file with hash %s exists" % fwid)
if session['username'] != 'admin' and item.qa_group != session['qa_group']:
return error_permission_denied("No QA access to %s" % fwid)
# only QA users can delete once the firmware has gone stable
if not session['qa_capability'] and item.target == 'stable':
return error_permission_denied('Unable to delete stable firmware as not QA')
# delete id from database
try:
db_firmware.remove(fwid)
except CursorError as e:
return error_internal(str(e))
# remove database copy
try:
db_cache = LvfsDatabaseCache(db)
db_cache.delete(item.filename)
except CursorError as e:
return error_internal(str(e))
# delete file(s)
for loc in [UPLOAD_DIR, DOWNLOAD_DIR]:
path = os.path.join(loc, item.filename)
if os.path.exists(path):
os.remove(path)
# update everything
try:
filenames = metadata_update_qa_group(item.qa_group)
if item.target == 'stable':
tmp = metadata_update_targets(targets=['stable', 'testing'])
filenames.extend(tmp)
elif item.target == 'testing':
tmp = metadata_update_targets(targets=['testing'])
filenames.extend(tmp)
# create detached signatures
affidavit = create_affidavit()
for filename in filenames:
affidavit.create_detached(filename)
except NoKeyError as e:
return error_internal('Failed to sign metadata: ' + str(e))
except CursorError as e:
return error_internal('Failed to generate metadata: ' + str(e))
_event_log("Deleted firmware %s" % fwid)
# ensure we save the latest data
ensure_checkpoint()
return redirect(url_for('.firmware'))
@lvfs.route('/firmware/<fwid>/promote/<target>')
def firmware_promote(fwid, target):
"""
Promote or demote a firmware file from one target to another,
for example from testing to stable, or stable to testing.
"""
# security check
if not _check_session():
return redirect(url_for('.login'))
# check is QA
if not session['qa_capability']:
return error_permission_denied('Unable to promote as not QA')
# check valid
if target not in ['stable', 'testing', 'private', 'embargo']:
return error_internal("Target %s invalid" % target)
# check firmware exists in database
db = LvfsDatabase(os.environ)
db_firmware = LvfsDatabaseFirmware(db)
try:
item = db_firmware.get_item(fwid)
except CursorError as e:
return error_internal(str(e))
if session['username'] != 'admin' and item.qa_group != session['qa_group']:
return error_permission_denied("No QA access to %s" % fwid)
try:
db_firmware.set_target(fwid, target)
except CursorError as e:
return error_internal(str(e))
# set correct response code
_event_log("Moved firmware %s to %s" % (fwid, target))
# update everything
try:
filenames = metadata_update_qa_group(item.qa_group)
if target == 'stable':
tmp = metadata_update_targets(['stable', 'testing'])
filenames.extend(tmp)
elif target == 'testing':
tmp = metadata_update_targets(['testing'])
filenames.extend(tmp)
# create detached signatures
affidavit = create_affidavit()
for filename in filenames:
affidavit.create_detached(filename)
except NoKeyError as e:
return error_internal('Failed to sign metadata: ' + str(e))
except CursorError as e:
return error_internal('Failed to generate metadata: ' + str(e))
# ensure we save the latest data
ensure_checkpoint()
return redirect(url_for('.firmware_id', fwid=fwid))
@lvfs.route('/firmware/<fwid>')
def firmware_id(fwid):
""" Show firmware information """
# security check
if not _check_session():
return redirect(url_for('.login'))
# get details about the firmware
db = LvfsDatabase(os.environ)
db_firmware = LvfsDatabaseFirmware(db)
try:
item = db_firmware.get_item(fwid)
except CursorError as e:
return error_internal(str(e))
if not item:
return error_internal('No firmware matched!')
# we can only view our own firmware, unless admin
qa_group = item.qa_group
if qa_group != session['qa_group'] and session['username'] != 'admin':
return error_permission_denied('Unable to view other vendor firmware')
if not qa_group:
embargo_url = '/downloads/firmware.xml.gz'
qa_group = 'None'
else:
embargo_url = '/downloads/firmware-%s.xml.gz' % _qa_hash(qa_group)
file_uri = '/downloads/' + item.filename
buttons = ''
if session['qa_capability'] or item.target == 'private':
buttons += "<form method=\"get\" action=\"/lvfs/firmware/%s/delete\">" \
"<button class=\"fixedwidth\">Delete</button>" \
"</form>" % fwid
if session['qa_capability']:
if item.target == 'private':
buttons += "<form method=\"get\" action=\"/lvfs/firmware/%s/promote/embargo\">" \
"<button class=\"fixedwidth\">→ Embargo</button>" \
"</form>" % fwid
elif item.target == 'embargo':
buttons += "<form method=\"get\" action=\"/lvfs/firmware/%s/promote/testing\">" \
"<button class=\"fixedwidth\">→ Testing</button>" \
"</form>" % fwid
elif item.target == 'testing':
buttons += "<form method=\"get\" action=\"/lvfs/firmware/%s/promote/stable\">" \
"<button class=\"fixedwidth\">→ Stable</button>" \
"</form>" % fwid
html = '<table class="history">'
orig_filename = '-'.join(item.filename.split('-')[1:])
html += '<tr><th>Filename</th><td><a href=\"%s\">%s</a></td></tr>' % (file_uri, orig_filename)
html += '<tr><th>Current Target</th><td>%s</td></tr>' % item.target
html += '<tr><th>Submitted</th><td>%s</td></tr>' % item.timestamp
html += '<tr><th>QA Group</th><td><a href="%s">%s</a></td></tr>' % (embargo_url, qa_group)
html += '<tr><th>Uploaded from</th><td>%s</td></tr>' % item.addr
if item.version_display:
html += '<tr><th>Version (display only)</th><td>%s</td></tr>' % item.version_display
db = LvfsDatabase(os.environ)
db_clients = LvfsDatabaseClients(db)
cnt_fn = db_clients.get_firmware_count_filename(item.filename)
html += '<tr><th>Downloads</th><td>%i</td></tr>' % cnt_fn
html += '<tr><th>Actions</th><td>%s</td></tr>' % buttons
html += '</table>'
# show each component
for md in item.mds:
html += '<h2>%s</h2>' % md.name
html += '<p>%s</p>' % md.summary
html += '<table class="history">'
html += '<tr><th>ID</th><td>%s</td></tr>' % md.cid
html += '<tr><th>Device GUID</th><td><code>%s</code></td></tr>' % md.guid
html += '<tr><th>Version</th><td>%s</td></tr>' % md.version
html += '<tr><th>Installed Size</th><td>%s</td></tr>' % sizeof_fmt(md.release_installed_size)
html += '<tr><th>Download Size</th><td>%s</td></tr>' % sizeof_fmt(md.release_download_size)
html += '</table>'
# show graph
db_clients = LvfsDatabaseClients(db)
data_fw = db_clients.get_stats_for_fn(12, 30, item.filename)
html += '<h1>User Downloads</h1>'
html += '<p>This graph will only show downloads since 2015-11-02.</p>'
html += '<canvas id="metadataChartMonths" width="800" height="400"></canvas>'
html += '<script>'
html += 'var ctx = document.getElementById("metadataChartMonths").getContext("2d");'
html += 'var data = {'
html += ' labels: %s,' % _get_chart_labels_months()[::-1]
html += ' datasets: ['
html += ' {'
html += ' label: "Firmware",'
html += ' fillColor: "rgba(251,14,5,0.2)",'
html += ' strokeColor: "rgba(151,14,5,0.1)",'
html += ' pointColor: "rgba(151,14,5,0.3)",'
html += ' pointStrokeColor: "#fff",'
html += ' pointHighlightFill: "#fff",'
html += ' pointHighlightStroke: "rgba(151,187,205,1)",'
html += ' data: %s' % data_fw[::-1]
html += ' },'
html += ' ]'
html += '};'
html += 'var myLineChartMonths = new Chart(ctx).Line(data, null);'
html += '</script>'
return render_template('firmware-details.html', dyncontent=html)
@lvfs.route('/analytics')
def analytics():
""" A analytics screen to show information about users """
# security check
if not _check_session():
return redirect(url_for('.login'))
if session['username'] != 'admin':
return error_permission_denied('Unable to view analytics')
# add days
db = LvfsDatabase(os.environ)
db_clients = LvfsDatabaseClients(db)
data_md = db_clients.get_stats(30, 1, LvfsDownloadKind.METADATA)
data_fw = db_clients.get_stats(30, 1, LvfsDownloadKind.FIRMWARE)
data_asc = db_clients.get_stats(30, 1, LvfsDownloadKind.SIGNING)
html = '<h2>Metadata and Firmware Downloads (day)</h2>'
html += '<canvas id="metadataChartMonthsDays" width="800" height="400"></canvas>'
html += '<script>'
html += 'var ctx = document.getElementById("metadataChartMonthsDays").getContext("2d");'
html += 'var data = {'
html += ' labels: %s,' % _get_chart_labels_days()[::-1]
html += ' datasets: ['
html += ' {'
html += ' label: "Signing",'
html += ' fillColor: "rgba(120,120,120,0.15)",'
html += ' strokeColor: "rgba(120,120,120,0.15)",'
html += ' pointColor: "rgba(120,120,120,0.20)",'
html += ' pointStrokeColor: "#fff",'
html += ' pointHighlightFill: "#fff",'
html += ' pointHighlightStroke: "rgba(220,220,220,1)",'
html += ' data: %s' % data_asc[::-1]
html += ' },'
html += ' {'
html += ' label: "Metadata",'
html += ' fillColor: "rgba(20,120,220,0.2)",'
html += ' strokeColor: "rgba(20,120,120,0.1)",'
html += ' pointColor: "rgba(20,120,120,0.3)",'
html += ' pointStrokeColor: "#fff",'
html += ' pointHighlightFill: "#fff",'
html += ' pointHighlightStroke: "rgba(220,220,220,1)",'
html += ' data: %s' % data_md[::-1]
html += ' },'
html += ' {'
html += ' label: "Firmware",'
html += ' fillColor: "rgba(251,14,5,0.2)",'
html += ' strokeColor: "rgba(151,14,5,0.1)",'
html += ' pointColor: "rgba(151,14,5,0.3)",'
html += ' pointStrokeColor: "#fff",'
html += ' pointHighlightFill: "#fff",'
html += ' pointHighlightStroke: "rgba(151,187,205,1)",'
html += ' data: %s' % data_fw[::-1]
html += ' },'
html += ' ]'
html += '};'
html += 'var myLineChartDays = new Chart(ctx).Line(data, null);'
html += '</script>'
# add months
data_md = db_clients.get_metadata_by_month(LvfsDownloadKind.METADATA)
data_fw = db_clients.get_metadata_by_month(LvfsDownloadKind.FIRMWARE)
data_asc = db_clients.get_metadata_by_month(LvfsDownloadKind.SIGNING)
html += '<h2>Metadata and Firmware Downloads (month)</h2>'
html += '<canvas id="metadataChartMonths" width="800" height="400"></canvas>'
html += '<script>'
html += 'var ctx = document.getElementById("metadataChartMonths").getContext("2d");'
html += 'var data = {'
html += ' labels: %s,' % _get_chart_labels_months()[::-1]
html += ' datasets: ['
html += ' {'
html += ' label: "Signing",'
html += ' fillColor: "rgba(120,120,120,0.15)",'
html += ' strokeColor: "rgba(120,120,120,0.15)",'
html += ' pointColor: "rgba(120,120,120,0.20)",'
html += ' pointStrokeColor: "#fff",'
html += ' pointHighlightFill: "#fff",'
html += ' pointHighlightStroke: "rgba(220,220,220,1)",'
html += ' data: %s' % data_asc[::-1]
html += ' },'
html += ' {'
html += ' label: "Metadata",'
html += ' fillColor: "rgba(20,120,220,0.2)",'
html += ' strokeColor: "rgba(20,120,120,0.1)",'
html += ' pointColor: "rgba(20,120,120,0.3)",'
html += ' pointStrokeColor: "#fff",'
html += ' pointHighlightFill: "#fff",'
html += ' pointHighlightStroke: "rgba(220,220,220,1)",'
html += ' data: %s' % data_md[::-1]
html += ' },'
html += ' {'
html += ' label: "Firmware",'
html += ' fillColor: "rgba(251,14,5,0.2)",'
html += ' strokeColor: "rgba(151,14,5,0.1)",'
html += ' pointColor: "rgba(151,14,5,0.3)",'
html += ' pointStrokeColor: "#fff",'
html += ' pointHighlightFill: "#fff",'
html += ' pointHighlightStroke: "rgba(151,187,205,1)",'
html += ' data: %s' % data_fw[::-1]
html += ' },'
html += ' ]'
html += '};'
html += 'var myLineChartMonths = new Chart(ctx).Line(data, null);'
html += '</script>'
# add user agent
labels, data = db_clients.get_user_agent_stats()
html += '<h2>User Agents</h2>'
html += '<canvas id="metadataChartUserAgents" width="800" height="400"></canvas>'
html += '<script>'
html += 'var ctx = document.getElementById("metadataChartUserAgents").getContext("2d");'
html += 'var data = {'
html += ' labels: %s,' % _to_javascript_array(labels)
html += ' datasets: ['
html += ' {'
html += ' label: "User Agents",'
html += ' fillColor: "rgba(20,120,220,0.2)",'
html += ' strokeColor: "rgba(20,120,120,0.1)",'
html += ' pointColor: "rgba(20,120,120,0.3)",'
html += ' pointStrokeColor: "#fff",'
html += ' pointHighlightFill: "#fff",'
html += ' pointHighlightStroke: "rgba(220,220,220,1)",'
html += ' data: %s' % _to_javascript_array(data)
html += ' },'
html += ' ]'
html += '};'