Debian Codegraph @

texmf-dist/tex/luatex/luaotfload/luaotfload-diagnostics.lua

raw
1 -----------------------------------------------------------------------
2 -- FILE: luaotfload-diagnostics.lua
3 -- DESCRIPTION: part of luaotfload-tool / functionality accessible by the --diagnose option
4 -- REQUIREMENTS: luaotfload-tool.lua
5 -- AUTHOR: Philipp Gesang <[email protected]>
6 -----------------------------------------------------------------------
7
8 assert(luaotfload_module, "This is a part of luaotfload and should not be loaded independently") {
9 name = "luaotfload-diagnostics",
10 version = "3.29", --TAGVERSION
11 date = "2024-12-03", --TAGDATE
12 description = "luaotfload-tool submodule / diagnostics",
13 license = "GPL v2.0"
14 }
15
16 local names = fonts.names
17
18 local kpse = require "kpse"
19 local kpseexpand_path = kpse.expand_path
20 local kpseexpand_var = kpse.expand_var
21 local kpsefind_file = kpse.find_file
22
23 local lfs = require "lfs"
24 local lfsattributes = lfs.attributes
25 local lfsisfile = lfs.isfile
26 local lfsreadlink = lfs.readlink
27
28 local md5 = require "md5"
29 local md5sumhexa = md5.sumhexa
30
31 local ioopen = io.open
32
33 local osgetenv = os.getenv
34 local osname = os.name
35 local osremove = os.remove
36 local ostype = os.type
37 local stringformat = string.format
38 local stringlower = string.lower
39 local stringsub = string.sub
40
41 local fileisreadable = file.isreadable
42 local fileiswritable = file.iswritable
43 local filesplitpath = file.splitpath
44 local filesuffix = file.suffix
45 local ioloaddata = io.loaddata
46 local lua_of_json = utilities.json.tolua
47 local tableconcat = table.concat
48 local tablesortedkeys = table.sortedkeys
49 local tabletohash = table.tohash
50
51 local lpeg = require "lpeg"
52 local C, Cg, Ct = lpeg.C, lpeg.Cg, lpeg.Ct
53 local lpegmatch = lpeg.match
54
55 local report = luaotfload.log.report
56 local function out (...)
57 report (false, 0, "diagnose", ...)
58 end
59
60 local parsers = luaotfload.parsers
61 local stripslashes = parsers.stripslashes
62 local splitcomma = parsers.splitcomma
63
64 local function check_index (errcnt)
65
66 out "================= font names =================="
67 local namedata = names.data()
68
69 if not namedata then
70 namedata = names.load ()
71 end
72
73 local mappings = namedata.mappings
74
75 if not namedata and namedata.formats and namedata.version then
76 out "Database corrupt."
77 return errcnt + 1
78 end
79
80 out ("Database version: %.3f.", namedata.meta.version)
81 out ("Font formats indexed: %s.",
82 tableconcat (namedata.meta.formats, ", "))
83 out ("%d font files indexed.", #mappings)
84
85 local by_format = { }
86 for i = 1, #mappings do
87 local record = mappings[i]
88 local format = stringlower (filesuffix (record.filename))
89 local count = by_format[format]
90 if count then
91 by_format[format] = count + 1
92 else
93 by_format[format] = 1
94 end
95 end
96
97 local formats = tablesortedkeys (by_format)
98 for i = 1, #formats do
99 local format = formats[i]
100 out ("%20s: %5d", format, by_format[format])
101 end
102 return errcnt
103 end
104
105 local function verify_files (errcnt)
106 out "================ verify files ================="
107 local status = config.luaotfload.status
108 local hashes = status.hashes
109 local notes = status.notes
110 if not hashes or #hashes == 0 then
111 out ("FAILED: cannot read checksums from %s.", status_file)
112 return 1/0
113 elseif not notes then
114 out ("FAILED: cannot read commit metadata from %s.",
115 status_file)
116 return 1/0
117 end
118
119 out ("Luaotfload revision %s.", notes.revision)
120 out ("Committed by %s.", notes.committer)
121 out ("Timestamp %s.", notes.timestamp)
122
123 local nhashes = #hashes
124 out ("Testing %d files for integrity.", nhashes)
125 for i = 1, nhashes do
126 local fname, canonicalsum = unpack (hashes[i])
127 local location = kpsefind_file (fname)
128 or kpsefind_file (fname, "texmfscripts")
129 if not location then
130 errcnt = errcnt + 1
131 out ("FAILED: file %s missing.", fname)
132 else
133 out ("File: %s.", location)
134 local raw = ioloaddata (location)
135 if not raw then
136 errcnt = errcnt + 1
137 out ("FAILED: file %d not readable.", fname)
138 else
139 local sum = md5sumhexa (raw)
140 if sum ~= canonicalsum then
141 errcnt = errcnt + 1
142 out ("FAILED: checksum mismatch for file %s.",
143 fname)
144 out ("Expected %s.", canonicalsum)
145 out ("Got %s.", sum)
146 else
147 out ("Ok, %s passed.", fname)
148 end
149 end
150 end
151 end
152 return errcnt
153 end
154
155 local function get_tentative_attributes (file)
156 if not lfsisfile (file) then
157 local chan = ioopen (file, "w")
158 if chan then
159 chan:close ()
160 local attributes = lfsattributes (file)
161 os.remove (file)
162 return attributes
163 end
164 end
165 end
166
167 local p_permissions = Ct(Cg(Ct(C(1) * C(1) * C(1)), "u")
168 * Cg(Ct(C(1) * C(1) * C(1)), "g")
169 * Cg(Ct(C(1) * C(1) * C(1)), "o"))
170
171 local function analyze_permissions (raw)
172 return lpegmatch (p_permissions, raw)
173 end
174
175 local function get_permissions (t, location)
176 if stringsub (location, #location) == "/" then
177 --- strip trailing slashes (lfs idiosyncrasy on Win)
178 location = lpegmatch (stripslashes, location)
179 end
180 local attributes = lfsattributes (location)
181 if not attributes then
182 print""
183 print("attr", location, attributes)
184 os.exit()
185 end
186
187 if not attributes and t == "f" then
188 attributes = get_tentative_attributes (location)
189 if not attributes then
190 return false
191 end
192 end
193
194 local permissions
195
196 if fileisreadable (location) then
197 --- link handling appears to be unnecessary because
198 --- lfs.attributes() will return the information on
199 --- the link target.
200 if mode == "link" then --follow and repeat
201 location = lfsreadlink (location)
202 attributes = lfsattributes (location)
203 end
204 end
205
206 permissions = analyze_permissions (attributes.permissions)
207
208 return {
209 location = location,
210 mode = attributes.mode,
211 owner = attributes.uid, --- useless on windows
212 permissions = permissions,
213 attributes = attributes,
214 }
215 end
216
217 local function check_conformance (spec, permissions, errcnt)
218 local uid = permissions.attributes.uid
219 local gid = permissions.attributes.gid
220 local raw = permissions.attributes.permissions
221
222 out ("Owner: %d, group %d, permissions %s.", uid, gid, raw)
223 if ostype == "unix" then
224 if uid == 0 or gid == 0 then
225 out "Owned by the superuser, permission conflict likely."
226 errcnt = errcnt + 1
227 end
228 end
229
230 local user = permissions.permissions.u
231 if spec.r == true then
232 if user[1] == "r" then
233 out "Readable: ok."
234 else
235 out "Not readable: permissions need fixing."
236 errcnt = errcnt + 1
237 end
238 end
239
240 if spec.w == true then
241 if user[2] == "w"
242 or fileiswritable (permissions.location) then
243 out "Writable: ok."
244 else
245 out "Not writable: permissions need fixing."
246 errcnt = errcnt + 1
247 end
248 end
249
250 return errcnt
251 end
252
253 local function init_desired_permissions ()
254 local paths = config.luaotfload.paths
255 local compress_db = config.luaotfload.db.compress
256 return {
257 { "d", {"r","w"}, function () return caches.getwritablepath ("", "") end },
258 { "d", {"r","w"}, paths.prefix },
259 { "f", {"r","w"}, paths.index_path_lua .. (compress_db and ".gz" or "") },
260 { "f", {"r","w"}, paths.index_path_luc .. (compress_db and ".gz" or "") },
261 { "f", {"r","w"}, paths.lookup_path_lua },
262 { "f", {"r","w"}, paths.lookup_path_luc },
263 }
264 end
265
266 local function check_permissions (errcnt)
267 out [[=============== file permissions ==============]]
268 local desired_permissions = init_desired_permissions ()
269 for i = 1, #desired_permissions do
270 local t, spec, path = unpack (desired_permissions[i])
271 if type (path) == "function" then
272 path = path ()
273 end
274
275 spec = tabletohash (spec)
276
277 out ("Checking permissions of %s.", path)
278
279 local permissions = get_permissions (t, path)
280 if permissions then
281 --inspect (permissions)
282 errcnt = check_conformance (spec, permissions, errcnt)
283 else
284 errcnt = errcnt + 1
285 end
286 end
287 return errcnt
288 end
289
290 local check_upstream
291
292 if kpsefind_file ("https.lua", "lua") == nil then
293 function check_upstream (errcnt)
294 out [[============= upstream repository =============
295 WARNING: Cannot retrieve repository data.
296 Github API access requires the luasec library.
297 Grab it from <https://github.com/brunoos/luasec>
298 and retry.]]
299 return errcnt
300 end
301 else
302 --- github api stuff begin
303 local https = require "ssl.https"
304
305 local gh_api_root = [[https://api.github.com]]
306 local release_url = [[https://github.com/latex3/luaotfload/releases]]
307 local luaotfload_repo = [[latex3/luaotfload]]
308 local user_agent = [[latex3/luaotfload integrity check]]
309 local shortbytes = 8
310
311 local function gh_shortrevision (rev)
312 return stringsub (rev, 1, shortbytes)
313 end
314
315 local function gh_encode_parameters (parameters)
316 local acc = {}
317 for field, value in next, parameters do
318 --- unsafe, non-urlencoded coz it’s all ascii chars
319 acc[#acc+1] = field .. "=" .. value
320 end
321 return "?" .. tableconcat (acc, "&")
322 end
323
324 local function gh_make_url (components, parameters)
325 local url = tableconcat ({ gh_api_root,
326 unpack (components) },
327 "/")
328 if parameters then
329 url = url .. gh_encode_parameters (parameters)
330 end
331 return url
332 end
333
334 local alright = [[HTTP/1.1 200 OK]]
335
336 local function gh_api_request (...)
337 local args = {...}
338 local nargs = #args
339 local final = args[nargs]
340 local request = {
341 url = "",
342 headers = { ["user-agent"] = user_agent },
343 }
344 if type (final) == "table" then
345 args[nargs] = nil
346 request = gh_make_url (args, final)
347 else
348 request = gh_make_url (args)
349 end
350
351 out ("Requesting <%s>.", request)
352 local response, code, headers, status = https.request (request)
353 if status ~= alright then
354 out "Request failed!"
355 return false
356 end
357 return response
358 end
359
360 local function gh_api_checklimit (headers)
361 local rawlimit = gh_api_request "rate_limit"
362 local limitdata = lua_of_json (rawlimit)
363 if not limitdata and limitdata.rate then
364 out "Cannot parse API rate limit."
365 return false
366 end
367 limitdata = limitdata.rate
368
369 local limit = tonumber (limitdata.limit)
370 local left = tonumber (limitdata.remaining)
371 local reset = tonumber (limitdata.reset)
372
373 out ("%d of %d Github API requests left.", left, limit)
374 if left == 0 then
375 out ("Cannot make any more API requests.")
376 if ostype == "unix" then
377 out ("Try again later at %s.", osdate ("%F %T", reset))
378 else --- windows doesn’t C99
379 out ("Try again later at %s.",
380 osdate ("%Y-%m-%d %H:%M:%S", reset))
381 end
382 end
383 return true
384 end
385
386 local function gh_tags ()
387 out "Fetching tags from repository, please stand by."
388 local rawtags = gh_api_request ("repos",
389 luaotfload_repo,
390 "tags")
391 local taglist = lua_of_json (rawtags)
392 if not taglist or #taglist == 0 then
393 out "Cannot parse response."
394 return false
395 end
396
397 local ntags = #taglist
398 out ("Repository contains %d tags.", ntags)
399 local _idx, latest = next (taglist)
400 out ("The most recent release is %s (revision %s).",
401 latest.name,
402 gh_shortrevision (latest.commit.sha))
403 return latest
404 end
405
406 local function gh_compare (head, base)
407 if base == nil then
408 base = "HEAD"
409 end
410 out ("Fetching comparison between %s and %s, \z
411 please stand by.",
412 gh_shortrevision (head),
413 gh_shortrevision (base))
414 local comparison = base .. "..." .. head
415 local rawstatus = gh_api_request ("repos",
416 luaotfload_repo,
417 "compare",
418 comparison)
419 local status = lua_of_json (rawstatus)
420 if not status then
421 out "Cannot parse response for status request."
422 return false
423 end
424 return status
425 end
426
427 local function gh_news (since)
428 local compared = gh_compare (since)
429 if not compared then
430 return false
431 end
432 local behind_by = compared.behind_by
433 local ahead_by = compared.ahead_by
434 local status = compared.status
435 out ("Comparison state: %s.", status)
436 if behind_by > 0 then
437 out ("Your Luaotfload is %d \z
438 revisions behind upstream.",
439 behind_by)
440 return behind_by
441 elseif status == "ahead" then
442 out "Since you are obviously from the future \z
443 I assume you already know the repository state."
444 else
445 out "Everything up to date. \z
446 Luaotfload is in sync with upstream."
447 end
448 return false
449 end
450
451 local function gh_catchup (current, latest)
452 local compared = gh_compare (latest, current)
453 local ahead_by = tonumber (compared.ahead_by)
454 if ahead_by > 0 then
455 local permalink_url = compared.permalink_url
456 out ("Your Luaotfload is %d revisions \z
457 behind the most recent release.",
458 ahead_by)
459 out ("To view the commit log, visit <%s>.",
460 permalink_url)
461 out ("You can grab an up to date tarball at <%s>.",
462 release_url)
463 return true
464 else
465 out "There weren't any new releases in the meantime."
466 out "Luaotfload is up to date."
467 end
468 return false
469 end
470
471 function check_upstream (current)
472 out "============= upstream repository ============="
473 local _succ = gh_api_checklimit ()
474 local behind = gh_news (current)
475 if behind then
476 local latest = gh_tags ()
477 local _behind = gh_catchup (current,
478 latest.commit.sha,
479 latest.name)
480 end
481 end
482
483 --- trivium: diff since the first revision as pushed by Élie
484 --- in 2009
485 --- local firstrevision = "c3ccb3ee07e0a67171c24960966ae974e0dd8e98"
486 --- check_upstream (firstrevision)
487 end
488 --- github api stuff end
489
490 local function print_envvar (var)
491 local val = osgetenv (var)
492 if val then
493 out ("%20s: %q", stringformat ("$%s", var), val)
494 return val
495 else
496 out ("%20s: <unset>", stringformat ("$%s", var))
497 end
498 end
499
500 local function print_path (var)
501 local val = osgetenv (var)
502 if val then
503 local paths = filesplitpath (val)
504 if paths then
505 local npaths = #paths
506 if npaths == 1 then
507 out ("%20s: %q", stringformat ("$%s", var), val)
508 elseif npaths > 1 then
509 out ("%20s: <%d items>", stringformat ("$%s", var), npaths)
510 for i = 1, npaths do
511 out (" +: %q", paths[i])
512 end
513 else
514 out ("%20s: <empty>")
515 end
516 end
517 else
518 out ("%20s: <unset>", stringformat ("$%s", var))
519 end
520 end
521
522 local function print_kpsevar (var)
523 var = "$" .. var
524 local val = kpseexpand_var (var)
525 if val and val ~= var then
526 out ("%20s: %q", var, val)
527 return val
528 else
529 out ("%20s: <empty or unset>", var)
530 end
531 end
532
533 local function print_kpsepath (var)
534 var = "$" .. var
535 local val = kpseexpand_path (var)
536 if val and val ~= "" then
537 local paths = filesplitpath (val)
538 if paths then
539 local npaths = #paths
540 if npaths == 1 then
541 out ("%20s: %q", var, paths[1])
542 elseif npaths > 1 then
543 out ("%20s: <%d items>", var, npaths)
544 for i = 1, npaths do
545 out (" +: %q", paths[i])
546 end
547 else
548 out ("%20s: <empty>")
549 end
550 end
551 else
552 out ("%20s: <empty or unset>", var)
553 end
554 end
555
556 --- this test first if a variable is set and then expands the
557 --- paths; this is necessitated by the fact that expand-path will
558 --- return the empty string both if the variable is unset and if
559 --- the directory does not exist
560
561 local function print_kpsepathvar (var)
562 local vvar = "$" .. var
563 local val = kpseexpand_var (vvar)
564 if val and val ~= vvar then
565 out ("%20s: %q", vvar, val)
566 print_kpsepath (var)
567 else
568 out ("%20s: <empty or unset>", var)
569 end
570 end
571
572 local function check_environment (errcnt)
573 out "============ environment settings ============="
574 out ("system: %s/%s", ostype, osname)
575 if ostype == "unix" and io.popen then
576 local chan = io.popen ("uname -a", "r")
577 if chan then
578 out ("info: %s", chan:read "*all")
579 chan:close ()
580 end
581 end
582
583 out "1) *shell environment*"
584 print_envvar "SHELL"
585 print_path "PATH"
586 print_path "OSFONTDIR"
587 print_envvar "USER"
588 if ostype == "windows" then
589 print_envvar "WINDIR"
590 print_envvar "CD"
591 print_path "TEMP"
592 elseif ostype == "unix" then
593 print_envvar "HOME"
594 print_envvar "PWD"
595 print_path "TMPDIR"
596 end
597
598 out "2) *kpathsea*"
599 print_kpsepathvar "OPENTYPEFONTS"
600 print_kpsepathvar "TTFONTS"
601
602 print_kpsepathvar "TEXMFCACHE"
603 print_kpsepathvar "TEXMFVAR"
604
605 --- the expansion of these can be quite large; as they aren’t
606 --- usually essential to luaotfload, we won’t dump every single
607 --- path
608 print_kpsevar "LUAINPUTS"
609 print_kpsevar "CLUAINPUTS"
610
611 return errcnt
612 end
613
614 local anamneses = {
615 "environment",
616 "files",
617 "index",
618 "repository",
619 "permissions"
620 }
621
622 local function diagnose (job)
623 local errcnt = 0
624 local asked = job.asked_diagnostics
625 if asked == "all" or asked == "thorough" then
626 asked = tabletohash (anamneses, true)
627 else
628 asked = lpegmatch (splitcomma, asked)
629 asked = tabletohash (asked, true)
630 end
631
632 if asked.index == true then
633 errcnt = check_index (errcnt)
634 asked.index = nil
635 end
636
637 if asked.environment == true then
638 errcnt = check_environment (errcnt)
639 asked.environment = nil
640 end
641
642 if asked.files == true then
643 errcnt = verify_files (errcnt)
644 asked.files = nil
645 end
646
647 if asked.permissions == true then
648 errcnt = check_permissions (errcnt)
649 asked.permissions = nil
650 end
651
652 if asked.repository == true then
653 local status = config.luaotfload.status
654 check_upstream (status.notes.revision)
655 asked.repository = nil
656 end
657
658 local rest = next (asked)
659 if rest ~= nil then --> something unknown
660 out ("Unknown diagnostic %q.", rest)
661 end
662 if errcnt == 0 then --> success
663 out ("Everything appears to be in order, \z
664 you may sleep well.")
665 return true, false
666 end
667 out ( [[===============================================
668 WARNING
669 ===============================================
670
671 The diagnostic detected %d errors.
672
673 This version of luaotfload may have been
674 tampered with. Modified versions of the
675 luaotfload source are unsupported. Read the log
676 carefully and get a clean version from CTAN or
677 github:
678
679 × http://www.ctan.org/pkg/luaotfload
680 × https://github.com/latex3/luaotfload/releases
681
682 If you are uncertain as to how to proceed, then
683 ask on the lualatex mailing list:
684
685 http://www.tug.org/mailman/listinfo/lualatex-dev
686
687 ===============================================
688 ]], errcnt)
689 return true, false
690 end
691
692 return diagnose
693
694 -- vim:tw=71:sw=4:ts=4:expandtab