-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathserver.py
More file actions
2553 lines (2257 loc) · 101 KB
/
Copy pathserver.py
File metadata and controls
2553 lines (2257 loc) · 101 KB
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
import datetime as _dt
import hashlib
import io
import json
import logging
import math
import os
import re
import shutil
import struct
import subprocess
import tempfile
import threading
import time
import uuid
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from typing import Dict, Optional, Tuple
from urllib.parse import parse_qs, unquote, urlsplit, urlunsplit
import fitz # PyMuPDF
import requests
from dotenv import load_dotenv
from PIL import Image, ImageColor, ImageOps
logger = logging.getLogger("ipp")
_PROCESS_STARTED_MONOTONIC = time.monotonic()
_MAX_TARGET_PIXELS = 100_000_000
_BUILT_IN_MEDIA_PROFILES = (
{
"media_id": "open-paper-l-13.3-inch",
"display_name": "Open Paper L (13.3 inch)",
"width": 1200,
"height": 1600,
"media_diagonal_inches": 13.3,
"fit": "contain",
"auto_rotate": False,
"background": "#ffffff",
},
{
"media_id": "openpaper-7-7.3-inch",
"display_name": "OpenPaper 7 (7.3 inch)",
"width": 480,
"height": 800,
"media_diagonal_inches": 7.3,
"fit": "contain",
"auto_rotate": False,
"background": "#ffffff",
},
)
_JOB_LAYOUT_FIELDS = (
"media",
"media-key",
"media-size-name",
"media-x-dimension",
"media-y-dimension",
"orientation-requested",
)
_STANDARD_MEDIA_MARGIN = 300 # 3 mm, expressed in hundredths of a millimetre
def _utc_timestamp_compact() -> str:
return _dt.datetime.now(_dt.UTC).strftime("%Y%m%dT%H%M%SZ")
def _resolve_endpoint_template(endpoint: str, paper_id: str) -> str:
if not endpoint or not paper_id:
return endpoint
# Support a few common placeholder styles.
placeholders = ("<paperId>", "{PAPER_ID}", "{paper_id}")
if any(p in endpoint for p in placeholders):
return (
endpoint.replace("<paperId>", paper_id)
.replace("{PAPER_ID}", paper_id)
.replace("{paper_id}", paper_id)
)
# If no placeholder is present, treat POST_ENDPOINT as a base URL and
# append the paper_id as the final path segment.
parts = urlsplit(endpoint)
existing_path = parts.path or ""
normalized_existing = existing_path.rstrip("/")
candidate_path = normalized_existing + "/" + paper_id
# Avoid double-appending if it's already present.
if normalized_existing.endswith("/" + paper_id) or normalized_existing == paper_id:
candidate_path = existing_path
return urlunsplit((parts.scheme, parts.netloc, candidate_path, parts.query, parts.fragment))
def _split_ipp_path_and_overrides(raw_path: str, ipp_base_path: str) -> Tuple[Optional[str], Dict[str, str], str]:
"""Return (path_only, overrides, safe_path_for_logs).
Accepts:
- /ipp/print
- /ipp/print?paper_id=123&auth_value=TOKEN
- /ipp/print/123
- /ipp/print/123/TOKEN
- /ipp/print/job/<id> (from Create-Job job-uri)
"""
parts = urlsplit(raw_path)
path_only = parts.path or ""
if path_only != ipp_base_path and not path_only.startswith(ipp_base_path.rstrip("/") + "/"):
return None, {}, raw_path
qs = parse_qs(parts.query or "", keep_blank_values=True)
def _first(qname: str) -> str:
values = qs.get(qname)
if not values:
return ""
return (values[0] or "").strip()
overrides: Dict[str, str] = {}
# Query params (preferred)
# Note: accept both snake_case and a few historical/alternate spellings.
# Some systems refer to these as PAPER_ID / AUTH_VALUE (waitlist-style).
paper_id_q = _first("paper_id") or _first("paperId") or _first("paper") or _first("PAPER_ID")
auth_value_q = _first("auth_value") or _first("token") or _first("auth") or _first("AUTH_VALUE")
if paper_id_q:
overrides["paper_id"] = paper_id_q
if auth_value_q:
overrides["auth_value"] = auth_value_q
# Optional path segments after the base path.
remainder = path_only[len(ipp_base_path) :]
remainder = remainder.lstrip("/")
if remainder and not remainder.startswith("job/"):
segs = [unquote(s) for s in remainder.split("/") if s]
if segs and "paper_id" not in overrides:
overrides["paper_id"] = segs[0].strip()
if len(segs) >= 2 and "auth_value" not in overrides:
overrides["auth_value"] = segs[1].strip()
# Redact secrets in logs (never log auth_value/token). The second custom
# path segment carries the API credential, so it must be redacted too.
safe_path_only = path_only
if remainder and not remainder.startswith("job/"):
raw_segments = [segment for segment in remainder.split("/") if segment]
if len(raw_segments) >= 2:
safe_segments = [raw_segments[0], "<redacted>", *raw_segments[2:]]
safe_path_only = ipp_base_path.rstrip("/") + "/" + "/".join(safe_segments)
safe_query_parts = []
for k, v in qs.items():
lk = k.lower()
if lk in {"auth_value", "token", "auth"}:
safe_query_parts.append(f"{k}=<redacted>")
else:
safe_query_parts.append(f"{k}={v[0] if v else ''}")
safe_query = "&".join(safe_query_parts)
safe_path_for_logs = safe_path_only + (("?" + safe_query) if safe_query else "")
return path_only, overrides, safe_path_for_logs
def _ipp_uri_resource(uri: str) -> str:
"""Return the path/query portion of an IPP URI, or an empty string."""
if not uri:
return ""
parts = urlsplit(uri)
path = parts.path or ""
if not path:
return ""
return path + (("?" + parts.query) if parts.query else "")
def _overrides_from_ipp_uri(uri: str, ipp_base_path: str) -> Dict[str, str]:
resource = _ipp_uri_resource(uri)
if not resource:
return {}
_, overrides, _ = _split_ipp_path_and_overrides(resource, ipp_base_path)
return overrides
def _merge_overrides(primary: Dict[str, str], fallback: Dict[str, str]) -> Dict[str, str]:
merged = dict(primary)
for key in ("paper_id", "auth_value"):
if not (merged.get(key) or "").strip():
value = (fallback.get(key) or "").strip()
if value:
merged[key] = value
return merged
def _redact_http_request_line(request_line: str, ipp_base_path: str) -> str:
parts = request_line.split(" ", 2)
if len(parts) < 2:
return request_line
path_only, _, safe_path = _split_ipp_path_and_overrides(parts[1], ipp_base_path)
if path_only is None:
return request_line
parts[1] = safe_path
return " ".join(parts)
def _external_ipp_uri(headers, request_path: str, ipp_base_path: str, ipp_printer_uri: str = "") -> str:
"""Build the canonical externally reachable URI returned to IPP clients.
Reverse proxies terminate TLS, while the application itself sees plain HTTP.
Windows can also POST to the conventional base path while retaining the full
configured resource in the IPP printer-uri attribute, so prefer the resource
that contains per-printer routing information.
"""
forwarded_proto = (headers.get("X-Forwarded-Proto") or "").split(",", 1)[0].strip().lower()
scheme = "ipps" if forwarded_proto in {"https", "ipps"} else "ipp"
host = (
(headers.get("X-Forwarded-Host") or "").split(",", 1)[0].strip()
or (headers.get("Host") or "").strip()
or "127.0.0.1"
)
request_resource = _ipp_uri_resource(request_path) or ipp_base_path
ipp_resource = _ipp_uri_resource(ipp_printer_uri)
def _valid(resource: str) -> bool:
path = urlsplit(resource).path or ""
base = ipp_base_path.rstrip("/")
return path == ipp_base_path or path.startswith(base + "/")
resource = request_resource if _valid(request_resource) else ipp_base_path
if _valid(ipp_resource):
_, request_overrides, _ = _split_ipp_path_and_overrides(resource, ipp_base_path)
_, ipp_overrides, _ = _split_ipp_path_and_overrides(ipp_resource, ipp_base_path)
if ipp_overrides and not request_overrides:
resource = ipp_resource
return f"{scheme}://{host}{resource}"
def _env_int(name: str, default: int) -> int:
value = os.getenv(name)
if value is None or value == "":
return default
return int(value)
def _env_str(name: str, default: str) -> str:
value = os.getenv(name)
if value is None or value == "":
return default
return value
def _env_bool(name: str, default: bool) -> bool:
value = os.getenv(name)
if value is None or value == "":
return default
return value.strip().lower() in {"1", "true", "yes", "on"}
def _parse_target_profiles(raw: str) -> Dict[str, Dict[str, object]]:
"""Parse and validate per-paper output profiles from JSON."""
if not (raw or "").strip():
return {}
try:
decoded = json.loads(raw)
except json.JSONDecodeError as exc:
raise ValueError(f"IPP_TARGET_PROFILES must be valid JSON: {exc}") from exc
if not isinstance(decoded, dict):
raise ValueError("IPP_TARGET_PROFILES must be a JSON object keyed by paper ID")
profiles: Dict[str, Dict[str, object]] = {}
for raw_paper_id, raw_profile in decoded.items():
paper_id = str(raw_paper_id).strip()
if not paper_id:
raise ValueError("IPP_TARGET_PROFILES contains an empty paper ID")
if not isinstance(raw_profile, dict):
raise ValueError(f"Target profile {paper_id!r} must be a JSON object")
raw_width = raw_profile.get("width")
raw_height = raw_profile.get("height")
if isinstance(raw_width, bool) or isinstance(raw_height, bool):
raise ValueError(f"Target profile {paper_id!r} width/height must be integers")
try:
width = int(raw_width)
height = int(raw_height)
except (TypeError, ValueError) as exc:
raise ValueError(f"Target profile {paper_id!r} width/height must be integers") from exc
if width <= 0 or height <= 0:
raise ValueError(f"Target profile {paper_id!r} width/height must be positive")
if width > 20_000 or height > 20_000 or width * height > _MAX_TARGET_PIXELS:
raise ValueError(f"Target profile {paper_id!r} dimensions are too large")
fit = str(raw_profile.get("fit", "contain")).strip().lower()
if fit not in {"contain", "cover", "stretch"}:
raise ValueError(f"Target profile {paper_id!r} fit must be contain, cover, or stretch")
auto_rotate = raw_profile.get("auto_rotate", False)
if not isinstance(auto_rotate, bool):
raise ValueError(f"Target profile {paper_id!r} auto_rotate must be true or false")
background = str(raw_profile.get("background", "#ffffff")).strip()
try:
background_rgb = ImageColor.getrgb(background)
except ValueError as exc:
raise ValueError(f"Target profile {paper_id!r} has an invalid background color") from exc
if len(background_rgb) != 3:
raise ValueError(f"Target profile {paper_id!r} background must be an opaque color")
profiles[paper_id] = {
"width": width,
"height": height,
"fit": fit,
"auto_rotate": auto_rotate,
"background": background,
}
return profiles
def _target_profile_for_paper_id(
profiles: Dict[str, Dict[str, object]], paper_id: str
) -> Optional[Dict[str, object]]:
profile = profiles.get((paper_id or "").strip()) or profiles.get("*")
return dict(profile) if profile else None
def _target_media_definition(profile: Dict[str, object], dpi: int) -> Tuple[str, list[Tuple[str, int, object]]]:
width = int(profile["width"])
height = int(profile["height"])
diagonal_inches = float(profile.get("media_diagonal_inches") or 0)
if diagonal_inches > 0:
scale = diagonal_inches * 2540 / math.hypot(width, height)
width_hundredths_mm = max(1, round(width * scale))
height_hundredths_mm = max(1, round(height * scale))
else:
effective_dpi = max(1, int(dpi))
width_hundredths_mm = max(1, round(width * 2540 / effective_dpi))
height_hundredths_mm = max(1, round(height * 2540 / effective_dpi))
width_mm = width_hundredths_mm / 100
height_mm = height_hundredths_mm / 100
raw_media_id = str(profile.get("media_id") or f"{width}x{height}").strip().lower()
media_id = re.sub(r"[^a-z0-9.-]+", "-", raw_media_id).strip("-") or f"{width}x{height}"
media_name = f"custom_{media_id}_{width_mm:.2f}x{height_mm:.2f}mm"
return media_name, [
("x-dimension", VT_INTEGER, width_hundredths_mm),
("y-dimension", VT_INTEGER, height_hundredths_mm),
]
def _selectable_target_profiles(
default_profile: Optional[Dict[str, object]] = None,
) -> list[Dict[str, object]]:
base_profiles = [dict(profile) for profile in _BUILT_IN_MEDIA_PROFILES]
if default_profile:
default_size = (int(default_profile["width"]), int(default_profile["height"]))
for index, profile in enumerate(base_profiles):
if (int(profile["width"]), int(profile["height"])) == default_size:
merged = dict(profile)
merged.update(default_profile)
base_profiles[index] = merged
base_profiles.insert(0, base_profiles.pop(index))
break
else:
custom = dict(default_profile)
custom.setdefault("display_name", f"{default_size[0]}×{default_size[1]}")
base_profiles.insert(0, custom)
profiles: list[Dict[str, object]] = []
for base in base_profiles:
base_media_id = str(base.get("media_id") or f"{base['width']}x{base['height']}")
base_display_name = str(
base.get("display_name") or f"{base['width']}×{base['height']}"
)
standard = dict(base)
standard["borderless"] = False
standard["media_margin"] = _STANDARD_MEDIA_MARGIN
profiles.append(standard)
borderless = dict(base)
borderless["borderless"] = True
borderless["media_margin"] = 0
borderless["media_id"] = f"{base_media_id}.borderless"
borderless["display_name"] = f"{base_display_name} – Randlos"
profiles.append(borderless)
return profiles
def _target_profile_for_job(
meta: Dict[str, str],
dpi: int,
default_profile: Optional[Dict[str, object]] = None,
) -> Dict[str, object]:
profiles = _selectable_target_profiles(default_profile)
selected_names = {
(meta.get(field) or "").strip().lower()
for field in ("media", "media-key", "media-size-name")
if (meta.get(field) or "").strip()
}
if selected_names:
for profile in profiles:
media_name, _ = _target_media_definition(profile, dpi)
if media_name.lower() in selected_names:
return dict(profile)
try:
selected_size = (
int(meta.get("media-x-dimension") or "0"),
int(meta.get("media-y-dimension") or "0"),
)
except ValueError:
selected_size = (0, 0)
if selected_size != (0, 0):
for profile in profiles:
_, size = _target_media_definition(profile, dpi)
profile_size = (int(size[0][2]), int(size[1][2]))
if profile_size == selected_size:
return dict(profile)
return dict(profiles[0])
def _job_layout_context(meta: Dict[str, str]) -> Dict[str, str]:
return {
field: meta[field]
for field in _JOB_LAYOUT_FIELDS
if (meta.get(field) or "").strip()
}
def _stored_job_context(overrides: Dict[str, str]) -> Dict[str, str]:
context = {
"paper_id": (overrides.get("paper_id") or "").strip(),
"auth_value": (overrides.get("auth_value") or "").strip(),
}
context.update(_job_layout_context(overrides))
return context
def _redacted_headers(headers) -> Dict[str, str]:
out: Dict[str, str] = {}
for k, v in headers.items():
lk = k.lower()
if lk in {"authorization", "cookie", "x-api-key", "x-ipp-token"}:
out[k] = "<redacted>"
else:
out[k] = v
return out
def _document_debug_fields(document: bytes) -> Dict[str, object]:
tail_window = document[-1024:] if len(document) > 1024 else document
return {
"bytes": len(document),
"sha256": hashlib.sha256(document).hexdigest() if document else "",
"first16": document[:16].hex(),
"last16": document[-16:].hex() if document else "",
"has_pdf_header": document.startswith(b"%PDF"),
"has_ps_header": document.startswith(b"%!PS"),
"has_pdf_eof": b"%%EOF" in tail_window,
"has_startxref": b"startxref" in tail_window,
}
def _log_document_diagnostics(prefix: str, document: bytes) -> None:
info = _document_debug_fields(document)
logger.debug(
"%s bytes=%s sha256=%s first16=%s last16=%s pdf_header=%s ps_header=%s pdf_eof=%s startxref=%s",
prefix,
info["bytes"],
info["sha256"],
info["first16"],
info["last16"],
info["has_pdf_header"],
info["has_ps_header"],
info["has_pdf_eof"],
info["has_startxref"],
)
def _log_pdf_state(prefix: str, doc, pdf_bytes: bytes) -> None:
metadata = getattr(doc, "metadata", None) or {}
logger.debug(
"%s page_count=%s needs_pass=%s is_encrypted=%s producer=%s title=%s",
prefix,
getattr(doc, "page_count", None),
bool(getattr(doc, "needs_pass", False)),
bool(getattr(doc, "is_encrypted", False)),
(metadata.get("producer") or "")[:120],
(metadata.get("title") or "")[:120],
)
_log_document_diagnostics(f"{prefix} bytes", pdf_bytes)
def _ghostscript_command() -> str:
return shutil.which("gs") or shutil.which("ghostscript") or ""
def _pwg_raster_converter_command() -> str:
candidates = (
shutil.which("rastertopdf"),
"/usr/lib/cups/filter/rastertopdf",
"/usr/libexec/cups/filter/rastertopdf",
shutil.which("rastertotiff"),
"/usr/lib/cups/filter/rastertotiff",
"/usr/libexec/cups/filter/rastertotiff",
)
for candidate in candidates:
if candidate and Path(candidate).is_file() and os.access(candidate, os.X_OK):
return candidate
return ""
def _supported_document_formats() -> list[str]:
formats = ["application/pdf", "image/jpeg"]
if _pwg_raster_converter_command():
formats.append("image/pwg-raster")
if _ghostscript_command():
formats.extend(["application/postscript", "application/vnd.cups-postscript"])
return formats
def _detect_document_kind(document: bytes, meta: Dict[str, str]) -> str:
if document.startswith(b"%PDF"):
return "pdf"
if document.startswith(b"%!PS"):
return "postscript"
if document.startswith((b"RaS2", b"RaS3", b"RaS4")):
return "pwg-raster"
if document.startswith(b"\xff\xd8\xff"):
return "jpeg"
if document.startswith(b"\x89PNG\r\n\x1a\n"):
return "png"
declared_format = (meta.get("document-format", "") or "").strip().lower()
if declared_format == "application/pdf":
return "pdf"
if declared_format in {"application/postscript", "application/vnd.cups-postscript"}:
return "postscript"
if declared_format == "image/pwg-raster":
return "pwg-raster"
if declared_format in {"image/jpeg", "image/jpg"}:
return "jpeg"
if declared_format == "image/png":
return "png"
return "unknown"
def render_image_to_pngs(image_bytes: bytes, filetype: str) -> Tuple[int, Dict[int, bytes]]:
doc = fitz.open(stream=image_bytes, filetype=filetype)
try:
total = doc.page_count
if total <= 0:
raise ValueError(f"{filetype.upper()} payload contains zero pages")
pages: Dict[int, bytes] = {}
for index in range(total):
pix = doc.load_page(index).get_pixmap(alpha=False)
pages[index + 1] = pix.tobytes("png")
return total, pages
finally:
doc.close()
def render_pwg_raster_to_pngs(raster_bytes: bytes, dpi: int, job_name: str = "") -> Tuple[int, Dict[int, bytes]]:
converter = _pwg_raster_converter_command()
if not converter:
raise ValueError(
"PWG Raster payload received but rastertopdf/rastertotiff is not installed; "
"install cups-filters-core-drivers"
)
with tempfile.TemporaryDirectory(prefix="ipp-pwg-raster-") as temp_dir:
input_path = Path(temp_dir) / "input.pwg"
input_path.write_bytes(raster_bytes)
result = subprocess.run(
[converter, "1", "paperlesspaper", job_name or "IPP job", "1", "", str(input_path)],
capture_output=True,
check=False,
)
if result.returncode != 0 or not result.stdout:
details = (result.stderr or b"PWG Raster conversion failed").decode("utf-8", errors="replace").strip()
raise ValueError(f"Failed to convert PWG Raster payload: {details}")
converter_name = Path(converter).name.lower()
if converter_name == "rastertopdf":
return render_pdf_to_pngs(result.stdout, dpi=dpi)
return render_image_to_pngs(result.stdout, "tiff")
def render_postscript_to_pngs(document: bytes, dpi: int) -> Tuple[int, Dict[int, bytes]]:
gs_command = _ghostscript_command()
if not gs_command:
raise ValueError(
"PostScript payload received but Ghostscript is not installed; install Ghostscript to accept Generic IPP/PostScript printer output"
)
with tempfile.TemporaryDirectory(prefix="ipp-postscript-") as temp_dir:
input_path = Path(temp_dir) / "input.ps"
output_pattern = Path(temp_dir) / "page-%04d.png"
input_path.write_bytes(document)
result = subprocess.run(
[
gs_command,
"-q",
"-dSAFER",
"-dBATCH",
"-dNOPAUSE",
"-sDEVICE=png16m",
f"-r{dpi}",
f"-sOutputFile={output_pattern}",
str(input_path),
],
capture_output=True,
text=True,
check=False,
)
output_files = sorted(Path(temp_dir).glob("page-*.png"))
if result.returncode != 0 or not output_files:
details = (result.stderr or result.stdout or "Ghostscript conversion failed").strip()
raise ValueError(f"Failed to render PostScript payload: {details}")
pages: Dict[int, bytes] = {}
for index, output_file in enumerate(output_files, start=1):
pages[index] = output_file.read_bytes()
return len(output_files), pages
def _op_name(operation_id: int) -> str:
return {
IPP_OP_PRINT_JOB: "Print-Job",
IPP_OP_VALIDATE_JOB: "Validate-Job",
IPP_OP_CREATE_JOB: "Create-Job",
IPP_OP_SEND_DOCUMENT: "Send-Document",
IPP_OP_CANCEL_JOB: "Cancel-Job",
IPP_OP_GET_JOB_ATTRIBUTES: "Get-Job-Attributes",
IPP_OP_GET_JOBS: "Get-Jobs",
IPP_OP_GET_PRINTER_ATTRIBUTES: "Get-Printer-Attributes",
IPP_OP_CANCEL_MY_JOBS: "Cancel-My-Jobs",
IPP_OP_CLOSE_JOB: "Close-Job",
IPP_OP_IDENTIFY_PRINTER: "Identify-Printer",
}.get(operation_id, f"op-0x{operation_id:04x}")
def _read_exact(rfile, n: int) -> bytes:
data = rfile.read(n)
if data is None:
return b""
return data
def _read_chunked_body(rfile, max_bytes: int) -> bytes:
body = bytearray()
chunk_count = 0
while True:
# chunk-size line (hex) optionally followed by extensions
line = rfile.readline(65536)
if not line:
raise ValueError("Incomplete chunked body: missing terminating chunk")
line = line.strip()
if b";" in line:
line = line.split(b";", 1)[0]
try:
chunk_size = int(line.decode("ascii", errors="ignore") or "0", 16)
except ValueError:
raise ValueError("Invalid chunk size")
if chunk_size == 0:
# consume trailer headers until CRLF
while True:
trailer = rfile.readline(65536)
if not trailer or trailer in {b"\r\n", b"\n"}:
break
logger.debug("Finished chunked request body: chunks=%d total_bytes=%d", chunk_count, len(body))
break
if len(body) + chunk_size > max_bytes:
raise ValueError("Chunked body exceeds limit")
chunk_count += 1
body += _read_exact(rfile, chunk_size)
# consume CRLF
chunk_ending = rfile.readline(3)
if chunk_ending not in {b"\r\n", b"\n"}:
raise ValueError("Invalid chunk terminator")
return bytes(body)
DELIMITER_TAGS = {
0x01, # operation-attributes-tag
0x02, # job-attributes-tag
0x03, # end-of-attributes-tag
0x04, # printer-attributes-tag
0x05, # unsupported-attributes-tag
}
IPP_OP_PRINT_JOB = 0x0002
IPP_OP_VALIDATE_JOB = 0x0004
IPP_OP_CREATE_JOB = 0x0005
IPP_OP_SEND_DOCUMENT = 0x0006
IPP_OP_CANCEL_JOB = 0x0008
IPP_OP_GET_JOB_ATTRIBUTES = 0x0009
IPP_OP_GET_JOBS = 0x000A
IPP_OP_GET_PRINTER_ATTRIBUTES = 0x000B
IPP_OP_CANCEL_MY_JOBS = 0x0039
IPP_OP_CLOSE_JOB = 0x003B
IPP_OP_IDENTIFY_PRINTER = 0x003C
IPP_STATUS_SUCCESSFUL_OK = 0x0000
IPP_STATUS_CLIENT_ERROR_BAD_REQUEST = 0x0400
IPP_STATUS_CLIENT_ERROR_NOT_POSSIBLE = 0x0404
IPP_STATUS_SERVER_ERROR_OPERATION_NOT_SUPPORTED = 0x0501
IPP_STATUS_SERVER_ERROR_VERSION_NOT_SUPPORTED = 0x0503
TAG_OPERATION_ATTRIBUTES = 0x01
TAG_PRINTER_ATTRIBUTES = 0x04
TAG_END_OF_ATTRIBUTES = 0x03
VT_TEXT_WITHOUT_LANGUAGE = 0x41
VT_NAME_WITHOUT_LANGUAGE = 0x42
VT_KEYWORD = 0x44
VT_URI = 0x45
VT_CHARSET = 0x47
VT_NATURAL_LANGUAGE = 0x48
VT_MIME_MEDIA_TYPE = 0x49
VT_BOOLEAN = 0x22
VT_INTEGER = 0x21
VT_ENUM = 0x23
VT_OCTET_STRING = 0x30
VT_DATETIME = 0x31
VT_RESOLUTION = 0x32
VT_RANGE_OF_INTEGER = 0x33
VT_BEGIN_COLLECTION = 0x34
VT_END_COLLECTION = 0x37
VT_URI_SCHEME = 0x46
VT_MEMBER_ATTR_NAME = 0x4A
def _ipp_attr(tag: int, name: str, value: bytes) -> bytes:
name_b = name.encode("utf-8")
return bytes([tag]) + struct.pack(">H", len(name_b)) + name_b + struct.pack(">H", len(value)) + value
def _ipp_attr_str(tag: int, name: str, value: str) -> bytes:
return _ipp_attr(tag, name, value.encode("utf-8"))
def _ipp_attr_bool(name: str, value: bool) -> bytes:
return _ipp_attr(VT_BOOLEAN, name, b"\x01" if value else b"\x00")
def _ipp_attr_i32(tag: int, name: str, value: int) -> bytes:
return _ipp_attr(tag, name, struct.pack(">i", int(value)))
def _ipp_attr_i32_set(tag: int, name: str, values: list[int]) -> bytes:
if not values:
return b""
out = bytearray()
first = True
for v in values:
if first:
out += _ipp_attr(tag, name, struct.pack(">i", int(v)))
first = False
else:
# additional value: name-length = 0
out += bytes([tag]) + struct.pack(">H", 0) + struct.pack(">H", 4) + struct.pack(">i", int(v))
return bytes(out)
def _ipp_attr_range(name: str, lower: int, upper: int) -> bytes:
return _ipp_attr(VT_RANGE_OF_INTEGER, name, struct.pack(">ii", int(lower), int(upper)))
def _ipp_attr_resolution(name: str, xdpi: int, ydpi: int, units: int = 3) -> bytes:
return _ipp_attr(VT_RESOLUTION, name, struct.pack(">iiB", int(xdpi), int(ydpi), int(units)))
def _ipp_attr_datetime(name: str, value: _dt.datetime) -> bytes:
current = value.astimezone(_dt.UTC)
encoded = struct.pack(
">HBBBBBBcBB",
current.year,
current.month,
current.day,
current.hour,
current.minute,
current.second,
0,
b"+",
0,
0,
)
return _ipp_attr(VT_DATETIME, name, encoded)
def _ipp_collection(name: str, members: list[Tuple[str, int, object]]) -> bytes:
out = bytearray(_ipp_attr(VT_BEGIN_COLLECTION, name, b""))
for member_name, tag, value in members:
out += _ipp_attr(VT_MEMBER_ATTR_NAME, "", member_name.encode("utf-8"))
if tag == VT_BEGIN_COLLECTION:
out += _ipp_collection("", value) # type: ignore[arg-type]
elif isinstance(value, int):
out += _ipp_attr(tag, "", struct.pack(">i", value))
elif isinstance(value, bytes):
out += _ipp_attr(tag, "", value)
else:
out += _ipp_attr(tag, "", str(value).encode("utf-8"))
out += _ipp_attr(VT_END_COLLECTION, "", b"")
return bytes(out)
def _ipp_collection_set(name: str, collections: list[list[Tuple[str, int, object]]]) -> bytes:
out = bytearray()
for index, members in enumerate(collections):
out += _ipp_collection(name if index == 0 else "", members)
return bytes(out)
def _ipp_attr_str_set(tag: int, name: str, values: list[str]) -> bytes:
if not values:
return b""
out = bytearray()
first = True
for v in values:
value_b = (v or "").encode("utf-8")
if first:
out += _ipp_attr(tag, name, value_b)
first = False
else:
# additional value: name-length = 0
out += bytes([tag]) + struct.pack(">H", 0) + struct.pack(">H", len(value_b)) + value_b
return bytes(out)
def build_ipp_response(status_code: int, request_id: int, attribute_bytes: bytes) -> bytes:
return build_ipp_response_with_version(1, 1, status_code, request_id, attribute_bytes)
def build_ipp_response_with_version(
version_major: int,
version_minor: int,
status_code: int,
request_id: int,
attribute_bytes: bytes,
) -> bytes:
response = bytearray()
response += bytes([version_major & 0xFF, version_minor & 0xFF])
response += struct.pack(">H", status_code)
response += struct.pack(">I", request_id)
response += attribute_bytes
response += bytes([TAG_END_OF_ATTRIBUTES])
return bytes(response)
def build_get_printer_attributes_response(
host_header: str,
ipp_path: str,
*,
scheme: str = "ipp",
printer_uri: str = "",
requested_attributes: Optional[list[str]] = None,
render_dpi: int = 150,
target_profile: Optional[Dict[str, object]] = None,
) -> bytes:
host = host_header or "127.0.0.1"
canonical_uri = printer_uri or f"{scheme}://{host}{ipp_path}"
security = "tls" if canonical_uri.lower().startswith("ipps://") else "none"
http_scheme = "https" if security == "tls" else "http"
info_uri = f"{http_scheme}://{host}/"
printer_uuid = uuid.uuid5(uuid.NAMESPACE_URL, canonical_uri)
up_time = max(1, int(time.monotonic() - _PROCESS_STARTED_MONOTONIC))
now = _dt.datetime.now(_dt.UTC)
formats = _supported_document_formats()
supports_pwg = "image/pwg-raster" in formats
default_format = "image/pwg-raster" if supports_pwg else "application/pdf"
selectable_profiles = _selectable_target_profiles(target_profile)
media_definitions = [
(*_target_media_definition(profile, render_dpi), profile)
for profile in selectable_profiles
]
default_media_name, default_media_size, _ = media_definitions[0]
printer_info = "paperlesspaper virtual IPP printer for Open Paper displays"
def media_col(
size: list[Tuple[str, int, object]],
media_name: str,
profile: Dict[str, object],
) -> list[Tuple[str, int, object]]:
margin = int(profile.get("media_margin", 0))
return [
("media-size", VT_BEGIN_COLLECTION, size),
("media-bottom-margin", VT_INTEGER, margin),
("media-left-margin", VT_INTEGER, margin),
("media-right-margin", VT_INTEGER, margin),
("media-top-margin", VT_INTEGER, margin),
("media-source", VT_KEYWORD, "auto"),
("media-type", VT_KEYWORD, "stationery"),
("media-key", VT_KEYWORD, media_name),
(
"media-info",
VT_TEXT_WITHOUT_LANGUAGE,
str(profile.get("display_name") or f"{profile['width']}×{profile['height']}"),
),
("media-size-name", VT_KEYWORD, media_name),
]
attributes: list[Tuple[str, bytes]] = []
def add(name: str, encoded: bytes) -> None:
attributes.append((name, encoded))
add("printer-uri-supported", _ipp_attr_str(VT_URI, "printer-uri-supported", canonical_uri))
add("uri-authentication-supported", _ipp_attr_str(VT_KEYWORD, "uri-authentication-supported", "none"))
add("uri-security-supported", _ipp_attr_str(VT_KEYWORD, "uri-security-supported", security))
add("printer-name", _ipp_attr_str(VT_NAME_WITHOUT_LANGUAGE, "printer-name", "paperlesspaper"))
add("printer-info", _ipp_attr_str(VT_TEXT_WITHOUT_LANGUAGE, "printer-info", printer_info))
add("printer-location", _ipp_attr_str(VT_TEXT_WITHOUT_LANGUAGE, "printer-location", "Cloud"))
add("printer-geo-location", _ipp_attr_str(VT_URI, "printer-geo-location", "geo:0,0"))
add("printer-make-and-model", _ipp_attr_str(VT_TEXT_WITHOUT_LANGUAGE, "printer-make-and-model", "paperlesspaper IPP Printer"))
add("printer-more-info", _ipp_attr_str(VT_URI, "printer-more-info", info_uri))
add("printer-icons", _ipp_attr_str(VT_URI, "printer-icons", f"{info_uri.rstrip('/')}/favicon.ico"))
add("printer-uuid", _ipp_attr_str(VT_URI, "printer-uuid", f"urn:uuid:{printer_uuid}"))
add(
"printer-device-id",
_ipp_attr_str(
VT_TEXT_WITHOUT_LANGUAGE,
"printer-device-id",
"MFG:paperlesspaper;MDL:Virtual IPP Printer;CMD:PDF,PWG-Raster,JPEG,POSTSCRIPT;",
),
)
add("ipp-versions-supported", _ipp_attr_str_set(VT_KEYWORD, "ipp-versions-supported", ["1.1", "2.0"]))
if supports_pwg:
add("ipp-features-supported", _ipp_attr_str(VT_KEYWORD, "ipp-features-supported", "ipp-everywhere"))
add(
"operations-supported",
_ipp_attr_i32_set(
VT_ENUM,
"operations-supported",
[
IPP_OP_PRINT_JOB,
IPP_OP_VALIDATE_JOB,
IPP_OP_CREATE_JOB,
IPP_OP_SEND_DOCUMENT,
IPP_OP_CANCEL_JOB,
IPP_OP_GET_JOB_ATTRIBUTES,
IPP_OP_GET_JOBS,
IPP_OP_GET_PRINTER_ATTRIBUTES,
IPP_OP_CANCEL_MY_JOBS,
IPP_OP_CLOSE_JOB,
IPP_OP_IDENTIFY_PRINTER,
],
),
)
add("charset-configured", _ipp_attr_str(VT_CHARSET, "charset-configured", "utf-8"))
add("charset-supported", _ipp_attr_str(VT_CHARSET, "charset-supported", "utf-8"))
add("natural-language-configured", _ipp_attr_str(VT_NATURAL_LANGUAGE, "natural-language-configured", "en"))
add("generated-natural-language-supported", _ipp_attr_str(VT_NATURAL_LANGUAGE, "generated-natural-language-supported", "en"))
add("printer-is-accepting-jobs", _ipp_attr_bool("printer-is-accepting-jobs", True))
add("printer-state", _ipp_attr_i32(VT_ENUM, "printer-state", 3))
add("printer-state-reasons", _ipp_attr_str(VT_KEYWORD, "printer-state-reasons", "none"))
add("queued-job-count", _ipp_attr_i32(VT_INTEGER, "queued-job-count", 0))
add("printer-up-time", _ipp_attr_i32(VT_INTEGER, "printer-up-time", up_time))
add("printer-config-change-time", _ipp_attr_i32(VT_INTEGER, "printer-config-change-time", 0))
add("printer-config-change-date-time", _ipp_attr_datetime("printer-config-change-date-time", now))
add("printer-state-change-time", _ipp_attr_i32(VT_INTEGER, "printer-state-change-time", 0))
add("printer-state-change-date-time", _ipp_attr_datetime("printer-state-change-date-time", now))
add("document-format-default", _ipp_attr_str(VT_MIME_MEDIA_TYPE, "document-format-default", default_format))
add("document-format-supported", _ipp_attr_str_set(VT_MIME_MEDIA_TYPE, "document-format-supported", formats))
add("compression-supported", _ipp_attr_str(VT_KEYWORD, "compression-supported", "none"))
add("pdl-override-supported", _ipp_attr_str(VT_KEYWORD, "pdl-override-supported", "attempted"))
add("printer-get-attributes-supported", _ipp_attr_str(VT_KEYWORD, "printer-get-attributes-supported", "document-format"))
add("job-ids-supported", _ipp_attr_bool("job-ids-supported", True))
add("multiple-document-jobs-supported", _ipp_attr_bool("multiple-document-jobs-supported", False))
add("multiple-operation-time-out", _ipp_attr_i32(VT_INTEGER, "multiple-operation-time-out", 30))
add("multiple-operation-time-out-action", _ipp_attr_str(VT_KEYWORD, "multiple-operation-time-out-action", "process-job"))
add("overrides-supported", _ipp_attr_str_set(VT_KEYWORD, "overrides-supported", ["document-number", "pages"]))
add("which-jobs-supported", _ipp_attr_str_set(VT_KEYWORD, "which-jobs-supported", ["completed", "not-completed", "all"]))
add("preferred-attributes-supported", _ipp_attr_bool("preferred-attributes-supported", False))
add(
"job-creation-attributes-supported",
_ipp_attr_str_set(
VT_KEYWORD,
"job-creation-attributes-supported",
[
"copies",
"finishings",
"ipp-attribute-fidelity",
"job-name",
"media",
"media-col",
"orientation-requested",
"output-bin",
"page-ranges",
"print-color-mode",
"print-quality",
"printer-resolution",
"requesting-user-name",
"sides",
],
),
)
add("copies-default", _ipp_attr_i32(VT_INTEGER, "copies-default", 1))
add("copies-supported", _ipp_attr_range("copies-supported", 1, 1))