diff --git a/cmd/poster/parsing.go b/cmd/poster/parsing.go index 76f51ff..30e011b 100644 --- a/cmd/poster/parsing.go +++ b/cmd/poster/parsing.go @@ -3,11 +3,13 @@ package main import ( "encoding/json" "fmt" + "io" "log" "os" "path/filepath" "github.com/adcondev/poster/internal/load" + "github.com/adcondev/poster/pkg/constants" "github.com/adcondev/poster/pkg/document/schema" ) @@ -26,11 +28,34 @@ func loadJSON(filePath string) ([]byte, error) { return nil, fmt.Errorf("security check failed: %w", err) } - // Read file - data, err := os.ReadFile(securePath) //nolint:gosec + // Read file securely + file, err := os.Open(securePath) //nolint:gosec if err != nil { return nil, err } + defer func() { + _ = file.Close() + }() + + // Check file size + fi, err := file.Stat() + if err != nil { + return nil, fmt.Errorf("failed to stat file: %w", err) + } + if fi.Size() > int64(constants.MaxJSONSize) { + return nil, fmt.Errorf("file too large: %d bytes (max %d bytes)", fi.Size(), constants.MaxJSONSize) + } + + // Read with limit reader to prevent TOCTOU issues if file grows + reader := io.LimitReader(file, int64(constants.MaxJSONSize)+1) + data, err := io.ReadAll(reader) + if err != nil { + return nil, err + } + + if len(data) > constants.MaxJSONSize { + return nil, fmt.Errorf("file too large (exceeded %d bytes during read)", constants.MaxJSONSize) + } // Validate JSON var temp interface{} @@ -41,7 +66,28 @@ func loadJSON(filePath string) ([]byte, error) { return data, nil } +func validateJSON(filePath string) error { + data, err := loadJSON(filePath) + if err != nil { + return err + } + + var doc schema.Document + if err := json.Unmarshal(data, &doc); err != nil { + return fmt.Errorf("invalid JSON: %w", err) + } + + if err := doc.Validate(); err != nil { + return fmt.Errorf("invalid document: %w", err) + } + + return validateDocument(&doc) +} + func validateDocument(doc *schema.Document) error { + if err := doc.Validate(); err != nil { + return fmt.Errorf("invalid document: %w", err) + } fmt.Println("=== Document Validation ===") fmt.Printf("Version: %s\n", doc.Version) fmt.Printf("Profile: %s (%dmm)\n", doc.Profile.Model, doc.Profile.PaperWidth) diff --git a/cmd/poster/parsing_test.go b/cmd/poster/parsing_test.go new file mode 100644 index 0000000..d702216 --- /dev/null +++ b/cmd/poster/parsing_test.go @@ -0,0 +1,192 @@ +package main + +import ( + "encoding/json" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/adcondev/poster/pkg/constants" + "github.com/adcondev/poster/pkg/document/schema" +) + +const validDocContent = `{ + "version": "1.0", + "profile": { + "model": "POS-80" + }, + "commands": [ + { + "type": "text", + "data": {"text": "data"} + } + ] +}` + +func TestLoadJSON_SizeLimit(t *testing.T) { + tempDir, err := os.MkdirTemp("", "poster_test") + if err != nil { + t.Fatalf("Failed to create temp dir: %v", err) + } + t.Cleanup(func() { + _ = os.RemoveAll(tempDir) + }) + + // Case 1: File within limit + smallFile := filepath.Join(tempDir, "small.json") + if err := os.WriteFile(smallFile, []byte(validDocContent), 0600); err != nil { + t.Fatalf("Failed to write small file: %v", err) + } + + _, err = loadJSON(smallFile) + if err != nil { + t.Errorf("Expected no error for small file, got: %v", err) + } + + // Case 2: File exceeding limit + largeFile := filepath.Join(tempDir, "large.json") + f, err := os.Create(filepath.Clean(largeFile)) + if err != nil { + t.Fatalf("Failed to create large file: %v", err) + } + + // Write slightly more than MaxJSONSize (11MB) + chunk := make([]byte, 1024*1024) + for i := range chunk { + chunk[i] = ' ' + } + + for i := 0; i < 11; i++ { + if _, err := f.Write(chunk); err != nil { + _ = f.Close() + t.Fatalf("Failed to write to large file: %v", err) + } + } + if _, err := f.Write([]byte(validDocContent)); err != nil { + _ = f.Close() + t.Fatalf("Failed to write end of large file: %v", err) + } + _ = f.Close() + + _, err = loadJSON(largeFile) + if err == nil { + t.Error("Expected error for large file, got nil") + } else if !strings.Contains(err.Error(), "file too large") { + t.Errorf("Expected 'file too large' error, got: %v", err) + } +} + +func TestLoadJSON_ExactLimit(t *testing.T) { + tempDir, err := os.MkdirTemp("", "poster_test_exact") + if err != nil { + t.Fatalf("Failed to create temp dir: %v", err) + } + t.Cleanup(func() { + _ = os.RemoveAll(tempDir) + }) + + exactFile := filepath.Join(tempDir, "exact.json") + f, err := os.Create(filepath.Clean(exactFile)) + if err != nil { + t.Fatalf("Failed to create exact file: %v", err) + } + + targetSize := constants.MaxJSONSize + validBytes := []byte(validDocContent) + if _, err := f.Write(validBytes); err != nil { + _ = f.Close() + t.Fatalf("Failed to write valid doc prefix: %v", err) + } + + chunkSize := 1024 * 1024 + chunk := make([]byte, chunkSize) + for i := range chunk { + chunk[i] = ' ' + } + + remaining := targetSize - len(validBytes) + for remaining > 0 { + toWrite := remaining + if toWrite > chunkSize { + toWrite = chunkSize + } + if _, err := f.Write(chunk[:toWrite]); err != nil { + _ = f.Close() + t.Fatalf("Failed to write exact file padding: %v", err) + } + remaining -= toWrite + } + _ = f.Close() + + info, err := os.Stat(exactFile) + if err != nil { + t.Fatalf("Failed to stat exact file: %v", err) + } + if info.Size() != int64(constants.MaxJSONSize) { + t.Fatalf("Created file size %d, expected %d", info.Size(), constants.MaxJSONSize) + } + + data, err := loadJSON(exactFile) + if err != nil { + t.Fatalf("Expected no error for exact size file, got: %v", err) + } + + var doc schema.Document + if err := json.Unmarshal(data, &doc); err != nil { + t.Fatalf("Failed to unmarshal exact size file JSON: %v", err) + } + if err := doc.Validate(); err != nil { + t.Errorf("Document in exact size file failed doc.Validate(): %v", err) + } +} + +func TestValidateJSON(t *testing.T) { + tempDir, err := os.MkdirTemp("", "poster_validate_test") + if err != nil { + t.Fatalf("Failed to create temp dir: %v", err) + } + t.Cleanup(func() { + _ = os.RemoveAll(tempDir) + }) + + t.Run("Valid document passes validation", func(t *testing.T) { + filePath := filepath.Join(tempDir, "valid.json") + if err := os.WriteFile(filePath, []byte(validDocContent), 0600); err != nil { + t.Fatalf("Failed to write test file: %v", err) + } + + if err := validateJSON(filePath); err != nil { + t.Errorf("Expected valid document to pass validateJSON, got: %v", err) + } + }) + + t.Run("Invalid document schema fails validation", func(t *testing.T) { + invalidDoc := `{"commands": [{"type": "text", "data": {"text": "hello"}}]}` + filePath := filepath.Join(tempDir, "invalid_schema.json") + if err := os.WriteFile(filePath, []byte(invalidDoc), 0600); err != nil { + t.Fatalf("Failed to write test file: %v", err) + } + + err := validateJSON(filePath) + if err == nil { + t.Error("Expected error for invalid document schema, got nil") + } else if !strings.Contains(err.Error(), "invalid document") { + t.Errorf("Expected 'invalid document' error, got: %v", err) + } + }) + + t.Run("Invalid JSON syntax fails validation", func(t *testing.T) { + filePath := filepath.Join(tempDir, "invalid_syntax.json") + if err := os.WriteFile(filePath, []byte(`{not valid json}`), 0600); err != nil { + t.Fatalf("Failed to write test file: %v", err) + } + + err := validateJSON(filePath) + if err == nil { + t.Error("Expected error for invalid syntax, got nil") + } else if !strings.Contains(err.Error(), "invalid JSON") { + t.Errorf("Expected 'invalid JSON' error, got: %v", err) + } + }) +} diff --git a/internal/testutils/byte_helpers.go b/internal/testutils/byte_helpers.go index 99b121b..fdd48f0 100644 --- a/internal/testutils/byte_helpers.go +++ b/internal/testutils/byte_helpers.go @@ -31,6 +31,12 @@ func RepeatByte(length int, value byte) []byte { return result } +// GenerateString creates a string of specified length filled with value +func GenerateString(length int, value byte) string { + return string(RepeatByte(length, value)) +} + + // ============================================================================ // Command Builders // ============================================================================ diff --git a/pkg/commands/print/print_test.go b/pkg/commands/print/print_test.go index 8a3f48b..562f271 100644 --- a/pkg/commands/print/print_test.go +++ b/pkg/commands/print/print_test.go @@ -5,6 +5,7 @@ import ( "errors" "testing" + "github.com/adcondev/poster/internal/testutils" "github.com/adcondev/poster/pkg/commands/print" "github.com/adcondev/poster/pkg/commands/shared" ) @@ -106,12 +107,8 @@ func TestCommands_Text(t *testing.T) { wantErr: true, }, { - name: "buffer overflow", - // FIXME: change anonymous func to utils helpers - text: func() string { - overflow := make([]byte, shared.MaxBuf+1) - return string(overflow) - }(), + name: "buffer overflow", + text: testutils.GenerateString(shared.MaxBuf+1, 0), want: nil, wantErr: true, }, diff --git a/pkg/constants/constants.go b/pkg/constants/constants.go index 7dabe82..ebc4110 100644 --- a/pkg/constants/constants.go +++ b/pkg/constants/constants.go @@ -425,3 +425,13 @@ const ( // TopMarginMultiplier is used to calculate initial top margin TopMarginMultiplier = 2 ) + +// ============================================================================ +// File Size Constants +// ============================================================================ + +const ( + // MaxJSONSize is the maximum size in bytes for a JSON document (10MB) + MaxJSONSize = 10 * 1024 * 1024 +) + diff --git a/pkg/document/executor/image_handler.go b/pkg/document/executor/image_handler.go index b1a2e9e..33082b2 100644 --- a/pkg/document/executor/image_handler.go +++ b/pkg/document/executor/image_handler.go @@ -38,6 +38,13 @@ func (e *Executor) handleImage(printer service.PrinterActions, data json.RawMess opts.PixelWidth = constants.DefaultImagePixelWidth } + if prof := printer.GetProfile(); prof != nil && prof.DotsPerLine > 0 { + opts.MaxWidth = prof.DotsPerLine + if opts.PixelWidth > opts.MaxWidth { + opts.PixelWidth = opts.MaxWidth + } + } + if opts.Threshold == 0 { opts.Threshold = constants.DefaultImageThreshold } diff --git a/pkg/emulator/emulator_engine.go b/pkg/emulator/emulator_engine.go index 1a8e2da..3a9e1bc 100644 --- a/pkg/emulator/emulator_engine.go +++ b/pkg/emulator/emulator_engine.go @@ -5,7 +5,6 @@ import ( "image" "image/png" "io" - "log" "strings" "github.com/adcondev/poster/pkg/constants" @@ -54,19 +53,8 @@ func NewEngine(config Config) (*Engine, error) { fonts := NewFontManager() // Try to load embedded fonts, fall back to bitmap if not available - errA := fonts.LoadFont("A", "JetBrainsMono-ExtraBold.ttf", constants.FontAWidth, constants.FontAHeight) - errB := fonts.LoadFont("B", "JetBrainsMono-Bold.ttf", constants.FontBWidth, constants.FontBHeight) - if errA != nil { - log.Printf("[Emulator] Warning: Font A failed to load: %v (using fallback)", errA) - } - if errB != nil { - log.Printf("[Emulator] Warning: Font B failed to load: %v (using fallback)", errB) - } - - // Log if using fallback - if fonts.UseFallback() { - log.Printf("[Emulator] Using bitmap fallback renderer") - } + _ = fonts.LoadFont("A", "JetBrainsMono-ExtraBold.ttf", constants.FontAWidth, constants.FontAHeight) + _ = fonts.LoadFont("B", "JetBrainsMono-Bold.ttf", constants.FontBWidth, constants.FontBHeight) // Create printer state state := NewPrinterState(config.PaperPxWidth) @@ -109,9 +97,6 @@ func (e *Engine) Reset() { e.textRenderer = NewTextRenderer(e.canvas, e.fonts, e.state) e.basicRenderer = NewBasicRenderer(e.canvas, e.fonts, e.state) e.imageRenderer = NewImageRenderer(e.canvas, e.state) - if e.debug { - log.Printf("[Emulator] Engine reset to initial state") - } } // ============================================================================ @@ -157,9 +142,6 @@ func (e *Engine) SetAlign(align string) { default: e.state.Align = constants.Left.String() } - if e.debug { - log.Printf("[Emulator] Alignment set to: %s", e.state.Align) - } } // AlignLeft sets left alignment @@ -180,9 +162,6 @@ func (e *Engine) AlignRight() { // SetBold enables or disables bold text func (e *Engine) SetBold(enabled bool) { e.state.IsBold = enabled - if e.debug { - log.Printf("[Emulator] Bold mode set to: %v", enabled) - } } // SetUnderline sets underline mode (0=off, 1=single, 2=double) @@ -194,17 +173,11 @@ func (e *Engine) SetUnderline(mode int) { mode = 2 } e.state.IsUnderline = mode - if e.debug { - log.Printf("[Emulator] Underline mode set to: %d", mode) - } } // SetInverse enables or disables inverse mode (white on black) func (e *Engine) SetInverse(enabled bool) { e.state.IsInverse = enabled - if e.debug { - log.Printf("[Emulator] Inverse mode set to: %v", enabled) - } } // SetFont sets the current font ("A" or "B") @@ -219,9 +192,6 @@ func (e *Engine) SetFont(name string) { } else { e.state.FontName = "A" } - if e.debug { - log.Printf("[Emulator] Font set to: %s", e.state.FontName) - } } // SetSize sets character size multipliers (1-8 for both width and height). @@ -255,14 +225,6 @@ func (e *Engine) SetSize(width, height int) { extraHeight := metrics.GlyphHeight * (e.state.ScaleH - oldScaleH) e.state.CursorY += extraHeight e.canvas.UpdateMaxY(e.state.CursorY) - - if e.debug { - log.Printf("[Emulator] Auto-adjusted cursor by %.1f pixels for scale change", extraHeight) - } - } - - if e.debug { - log.Printf("[Emulator] Character size set to: width=%d, height=%d", width, height) } } @@ -289,17 +251,11 @@ func (e *Engine) Separator(char string, length int) { // Cut renders a cut line (visual indicator) func (e *Engine) Cut(partial bool) { e.basicRenderer.RenderCut(partial) - if e.debug { - log.Printf("[Emulator] Cut rendered: partial=%v", partial) - } } // HorizontalLine renders a solid horizontal line func (e *Engine) HorizontalLine(thickness int) { e.basicRenderer.RenderHorizontalLine(thickness) - if e.debug { - log.Printf("[Emulator] Horizontal line rendered: thickness=%d", thickness) - } } // ============================================================================ @@ -349,9 +305,6 @@ func (e *Engine) Render() image.Image { func (e *Engine) RenderWithInfo() RenderResult { img := e.canvas.Crop() bounds := img.Bounds() - if e.debug { - log.Printf("[Emulator] Rendered image size: %dx%d", bounds.Dx(), bounds.Dy()) - } return RenderResult{ Image: img, Width: bounds.Dx(), @@ -362,9 +315,6 @@ func (e *Engine) RenderWithInfo() RenderResult { // WritePNG writes the rendered image as PNG to the writer func (e *Engine) WritePNG(w io.Writer) error { img := e.Render() - if e.debug { - log.Printf("[Emulator] Writing PNG output (%dx%d)", img.Bounds().Dx(), img.Bounds().Dy()) - } return png.Encode(w, img) } @@ -380,11 +330,7 @@ func (e *Engine) State() PrinterState { // CharsPerLine returns the number of characters that fit on a line with current font func (e *Engine) CharsPerLine() int { metrics := e.fonts.GetMetrics(e.state.FontName) - chars := e.state.CharsPerLine(metrics.GlyphWidth) - if e.debug { - log.Printf("[Emulator] CharsPerLine: %d (Font: %s, CharWidth: %.2f)", chars, e.state.FontName, metrics.GlyphWidth) - } - return chars + return e.state.CharsPerLine(metrics.GlyphWidth) } // =========================================================================== diff --git a/pkg/emulator/fonts.go b/pkg/emulator/fonts.go index 1680473..da810b9 100644 --- a/pkg/emulator/fonts.go +++ b/pkg/emulator/fonts.go @@ -5,8 +5,8 @@ import ( "image" "image/color" "image/draw" - "log" "math" + "sync" "golang.org/x/image/font" "golang.org/x/image/font/opentype" @@ -34,9 +34,9 @@ type ScaledFont struct { // FontManager handles font loading and scaling for thermal printer emulation type FontManager struct { - fonts map[string]*ScaledFont - // FIXME: he scaledFaces map is accessed from multiple methods without synchronization. + fonts map[string]*ScaledFont scaledFaces map[string]font.Face // Cache: "fontName_scaleW_scaleH" -> face + mu sync.RWMutex useFallback bool } @@ -53,14 +53,12 @@ func NewFontManager() *FontManager { func (fm *FontManager) LoadFont(name, filename string, targetWidth, targetHeight float64) error { ttfData, err := emfonts.LoadFontData(filename) if err != nil { - log.Printf("[FontManager] ERROR: Failed to load font data for '%s': %v", name, err) fm.useFallback = true return fmt.Errorf("loading font data: %w", err) } f, err := opentype.Parse(ttfData) if err != nil { - log.Printf("[FontManager] ERROR: Failed to parse TTF for '%s': %v", name, err) fm.useFallback = true return fmt.Errorf("parsing ttf: %w", err) } @@ -84,6 +82,7 @@ func (fm *FontManager) LoadFont(name, filename string, targetWidth, targetHeight // Use 'M' as reference for width in monospace advance, ok := face.GlyphAdvance('M') if !ok { + _ = face.Close() continue } @@ -98,13 +97,17 @@ func (fm *FontManager) LoadFont(name, filename string, targetWidth, targetHeight if totalDiff < minDiff { minDiff = totalDiff + if bestFace != nil { + _ = bestFace.Close() + } bestFace = face + } else { + _ = face.Close() } } // Accept if we found ANY face (we'll use target metrics for spacing) if bestFace == nil { - log.Printf("[FontManager] ERROR: Could not create any font face for '%s'", name) fm.useFallback = true return fmt.Errorf("could not fit font %s to dimensions %.2fx%.2f", filename, targetWidth, targetHeight) } @@ -124,7 +127,9 @@ func (fm *FontManager) LoadFont(name, filename string, targetWidth, targetHeight // Pre-cache the 1x1 scale for this font cacheKey := fmt.Sprintf("%s_1.0_1.0", name) + fm.mu.Lock() fm.scaledFaces[cacheKey] = bestFace + fm.mu.Unlock() return nil } @@ -179,9 +184,12 @@ func (fm *FontManager) GetOrCreateScaledFace(fontName string, scaleW, scaleH flo key := fmt.Sprintf("%s_%.1f_%.1f", fontName, scaleW, scaleH) // Check cache first + fm.mu.RLock() if face, ok := fm.scaledFaces[key]; ok { + fm.mu.RUnlock() return face, nil } + fm.mu.RUnlock() // Get the base font sf, err := fm.GetFont(fontName) @@ -189,6 +197,17 @@ func (fm *FontManager) GetOrCreateScaledFace(fontName string, scaleW, scaleH flo return nil, err } + if scaleW == 1.0 && scaleH == 1.0 && sf.face != nil { + fm.mu.Lock() + if face, ok := fm.scaledFaces[key]; ok { + fm.mu.Unlock() + return face, nil + } + fm.scaledFaces[key] = sf.face + fm.mu.Unlock() + return sf.face, nil + } + // Calculate target height for the scaled font // Use the larger scale factor to determine the font size scaleFactor := scaleH @@ -224,7 +243,12 @@ func (fm *FontManager) GetOrCreateScaledFace(fontName string, scaleW, scaleH flo diff := math.Abs(currentHeight - targetHeight) if diff < minDiff { minDiff = diff + if bestFace != nil { + _ = bestFace.Close() + } bestFace = face + } else { + _ = face.Close() } // Early exit if we found a very close match @@ -238,8 +262,15 @@ func (fm *FontManager) GetOrCreateScaledFace(fontName string, scaleW, scaleH flo } // Cache the result + fm.mu.Lock() + // Double check cache in case another goroutine populated it + if face, ok := fm.scaledFaces[key]; ok { + fm.mu.Unlock() + _ = bestFace.Close() + return face, nil + } fm.scaledFaces[key] = bestFace - log.Printf("[FontManager] Created and cached scaled face: %s at %.1fx%.1f", fontName, scaleW, scaleH) + fm.mu.Unlock() return bestFace, nil } @@ -338,10 +369,25 @@ func (fm *FontManager) drawFallbackCharScaled(dst draw.Image, char rune, x, y, w } } -// FIXME: ClearScaledFaceCache recreates the map but doesn't close the existing font.Face resources. - // ClearScaledFaceCache clears the cached scaled font faces // Useful when resetting the engine or changing fonts func (fm *FontManager) ClearScaledFaceCache() { + fm.mu.Lock() + defer fm.mu.Unlock() + + baseFaces := make(map[font.Face]struct{}, len(fm.fonts)) + for _, sf := range fm.fonts { + if sf != nil && sf.face != nil { + baseFaces[sf.face] = struct{}{} + } + } + + for _, face := range fm.scaledFaces { + if face != nil { + if _, isBase := baseFaces[face]; !isBase { + _ = face.Close() + } + } + } fm.scaledFaces = make(map[string]font.Face) } diff --git a/pkg/emulator/fonts/embed.go b/pkg/emulator/fonts/embed.go index f2fafac..1cbbf60 100644 --- a/pkg/emulator/fonts/embed.go +++ b/pkg/emulator/fonts/embed.go @@ -4,7 +4,6 @@ package fonts import ( "embed" "fmt" - "log" ) // Note: Place your .ttf files in this directory. @@ -54,20 +53,7 @@ func ListFonts() []string { return fonts } -// DiagnoseEmbedding prints diagnostic info about embedded fonts +// DiagnoseEmbedding checks the embedded fonts directory. func DiagnoseEmbedding() { - entries, err := fs.ReadDir(".") - if err != nil { - log.Printf("[fonts] ERROR reading embed directory: %v", err) - return - } - log.Printf("[fonts] Found %d entries in embedded filesystem:", len(entries)) - for _, entry := range entries { - info, _ := entry.Info() - if info != nil { - log.Printf("[fonts] - %s (%d bytes)", entry.Name(), info.Size()) - } else { - log.Printf("[fonts] - %s (size unknown)", entry.Name()) - } - } + _, _ = fs.ReadDir(".") } diff --git a/pkg/emulator/fonts_test.go b/pkg/emulator/fonts_test.go new file mode 100644 index 0000000..be8fa8e --- /dev/null +++ b/pkg/emulator/fonts_test.go @@ -0,0 +1,90 @@ +package emulator + +import ( + "sync" + "testing" + + "golang.org/x/image/math/fixed" +) + +// TestScaledFacesRace verifies that accessing scaledFaces from multiple goroutines +// does not cause a data race. +func TestScaledFacesRace(t *testing.T) { + fm := NewFontManager() + + // Load a font first (assuming JetBrainsMono-Regular.ttf is available in embedded fs) + // We use a dummy target size. + err := fm.LoadFont("testfont", "JetBrainsMono-Regular.ttf", 12, 24) + if err != nil { + t.Skipf("Skipping test because font loading failed (likely missing embedded font): %v", err) + } + + var wg sync.WaitGroup + // Spawn multiple goroutines to access GetOrCreateScaledFace + for i := 0; i < 20; i++ { + wg.Add(1) + go func(i int) { + defer wg.Done() + // Use different scales to trigger writes to the map + scale := float64(i%5) + 1.0 + _, _ = fm.GetOrCreateScaledFace("testfont", scale, scale) + }(i) + } + + // Concurrently clear the cache to stress test locking + wg.Add(1) + go func() { + defer wg.Done() + for i := 0; i < 5; i++ { + fm.ClearScaledFaceCache() + } + }() + + wg.Wait() +} + +// TestClearScaledFaceCachePreservesBaseFace verifies that ClearScaledFaceCache +// does not close the base font face. +func TestClearScaledFaceCachePreservesBaseFace(t *testing.T) { + fm := NewFontManager() + err := fm.LoadFont("testfont", "JetBrainsMono-Regular.ttf", 12, 24) + if err != nil { + t.Fatalf("LoadFont failed: %v", err) + } + + // Generate a scaled face + face2x, err := fm.GetOrCreateScaledFace("testfont", 2.0, 2.0) + if err != nil { + t.Fatalf("GetOrCreateScaledFace failed: %v", err) + } + if face2x == nil { + t.Fatal("expected non-nil face2x") + } + + // Clear cache + fm.ClearScaledFaceCache() + + // Base font face must still be valid and usable + sf, err := fm.GetFont("testfont") + if err != nil { + t.Fatalf("GetFont failed: %v", err) + } + if sf.face == nil { + t.Fatal("expected non-nil sf.face") + } + + // Calling Glyph on sf.face must succeed + _, _, _, _, ok := sf.face.Glyph(fixed.Point26_6{}, 'A') + if !ok { + t.Fatal("expected glyph for 'A' to be found in base face") + } + + // Re-fetching 1.0x1.0 scaled face should succeed + face1x, err := fm.GetOrCreateScaledFace("testfont", 1.0, 1.0) + if err != nil { + t.Fatalf("GetOrCreateScaledFace(1.0, 1.0) failed: %v", err) + } + if face1x == nil { + t.Fatal("expected non-nil face1x") + } +} diff --git a/pkg/emulator/state.go b/pkg/emulator/state.go index 2774e2e..97c9f4b 100644 --- a/pkg/emulator/state.go +++ b/pkg/emulator/state.go @@ -1,8 +1,6 @@ package emulator import ( - "log" - "github.com/adcondev/poster/pkg/constants" ) @@ -97,14 +95,12 @@ func (s *PrinterState) SetSize(w, h float64) { s.ScaleH = clampScale(h, "height") } -// clampScale clamps a scale value to valid range and logs warnings -func clampScale(value float64, name string) float64 { +// clampScale clamps a scale value to valid range +func clampScale(value float64, _ string) float64 { if value < constants.MinScale { - log.Printf("[Emulator] Warning: Character %s scale %.2f too small, clamping to %.1f", name, value, constants.MinScale) return constants.MinScale } if value > constants.MaxScale { - log.Printf("[Emulator] Warning: Character %s scale %.2f too large, clamping to %.1f", name, value, constants.MaxScale) return constants.MaxScale } return value diff --git a/pkg/graphics/bitmap.go b/pkg/graphics/bitmap.go index ae60eba..fc0858a 100644 --- a/pkg/graphics/bitmap.go +++ b/pkg/graphics/bitmap.go @@ -32,6 +32,7 @@ func (m *MonochromeBitmap) SetPixel(x, y int, black bool) { } byteIndex := y*m.bytesPerRow + x/8 + // Safe: x is non-negative (checked above) so x%8 is [0,7], result is positive. bitIndex := uint(7 - (x % 8)) if black { @@ -48,6 +49,7 @@ func (m *MonochromeBitmap) GetPixel(x, y int) bool { } byteIndex := y*m.bytesPerRow + x/8 + // Safe: x is non-negative (checked above) so x%8 is [0,7], result is positive. bitIndex := uint(7 - (x % 8)) return (m.data[byteIndex] & (1 << bitIndex)) != 0 diff --git a/pkg/graphics/graph_engine.go b/pkg/graphics/graph_engine.go index a5aa4f8..91f0416 100644 --- a/pkg/graphics/graph_engine.go +++ b/pkg/graphics/graph_engine.go @@ -52,6 +52,7 @@ var ScaleMap = map[constants.Scaling]ScaleMode{ // ImgOptions configures the graphics processing pipeline type ImgOptions struct { PixelWidth int // Target width in pixels + MaxWidth int // Maximum width in pixels Threshold uint8 // Threshold for black/white (0-255) Dithering DitherMode // Processing algorithm Scaling ScaleMode // Up/Down Scale algorithm @@ -63,6 +64,7 @@ type ImgOptions struct { func DefaultOptions() *ImgOptions { return &ImgOptions{ PixelWidth: constants.DefaultImagePixelWidth, + MaxWidth: constants.PaperPxWidth80mm, Threshold: constants.DefaultImageThreshold, Dithering: DitherMap[constants.Atkinson.String()], Scaling: ScaleMap[constants.Bilinear], @@ -116,8 +118,10 @@ func (p *Pipeline) Process(img image.Image) (*MonochromeBitmap, error) { // resize scales (up or down) the image to target width maintaining aspect ratio func (p *Pipeline) resize(img image.Image) image.Image { - // TODO: ImgOption should have a MaxWidth to cap resizing based on ticket size. - maxWidth := constants.PaperPxWidth80mm + maxWidth := p.opts.MaxWidth + if maxWidth <= 0 { + maxWidth = constants.PaperPxWidth80mm + } if p.opts.PixelWidth > maxWidth { p.opts.PixelWidth = maxWidth } @@ -140,14 +144,60 @@ func (p *Pipeline) applyThreshold(gray *image.Gray) *MonochromeBitmap { bounds := gray.Bounds() width, height := bounds.Dx(), bounds.Dy() mono := NewMonochromeBitmap(width, height) + if width <= 0 || height <= 0 { + return mono + } + + threshold := p.opts.Threshold + bytesPerRow := mono.bytesPerRow + fullBytes := width / 8 + remBits := width % 8 + + bitMasks := [8]byte{0x80, 0x40, 0x20, 0x10, 0x08, 0x04, 0x02, 0x01} for y := 0; y < height; y++ { - for x := 0; x < width; x++ { - pixel := gray.GrayAt(x, y).Y - // Set pixel to black (true) if below threshold - if pixel < p.opts.Threshold { - mono.SetPixel(x, y, true) + srcRowOffset := gray.PixOffset(bounds.Min.X, bounds.Min.Y+y) + dstRowOffset := y * bytesPerRow + + for byteIdx := 0; byteIdx < fullBytes; byteIdx++ { + var b byte + srcX := srcRowOffset + byteIdx*8 + if gray.Pix[srcX] < threshold { + b |= 0x80 + } + if gray.Pix[srcX+1] < threshold { + b |= 0x40 + } + if gray.Pix[srcX+2] < threshold { + b |= 0x20 + } + if gray.Pix[srcX+3] < threshold { + b |= 0x10 + } + if gray.Pix[srcX+4] < threshold { + b |= 0x08 + } + if gray.Pix[srcX+5] < threshold { + b |= 0x04 + } + if gray.Pix[srcX+6] < threshold { + b |= 0x02 + } + if gray.Pix[srcX+7] < threshold { + b |= 0x01 + } + mono.data[dstRowOffset+byteIdx] = b + } + + if remBits > 0 { + var b byte + srcX := srcRowOffset + fullBytes*8 + for bit := 0; bit < remBits; bit++ { + if gray.Pix[srcX+bit] < threshold { + b |= bitMasks[bit] + } } + mono.data[dstRowOffset+fullBytes] = b } } diff --git a/pkg/graphics/processing.go b/pkg/graphics/processing.go index 9b978eb..db894ef 100644 --- a/pkg/graphics/processing.go +++ b/pkg/graphics/processing.go @@ -27,6 +27,10 @@ func DefaultResizeOptions(paperWidth int) *ResizeOptions { } } +// MaxImagePixelHeight is the maximum allowed height for a processed image to prevent +// excessive memory allocation (DoS). 32000 pixels is approx 4 meters at 203 DPI. +const MaxImagePixelHeight = 32000 + // ResizeImage scales an image to the target width while optionally preserving aspect ratio. func ResizeImage(img image.Image, opts *ResizeOptions) image.Image { if img == nil { @@ -58,6 +62,11 @@ func ResizeImage(img image.Image, opts *ResizeOptions) image.Image { targetH = (srcH * targetW) / srcW } + // Safety check: Clamp height to prevent OOM + if targetH > MaxImagePixelHeight { + targetH = MaxImagePixelHeight + } + // Create destination image dst := image.NewRGBA(image.Rect(0, 0, targetW, targetH)) diff --git a/pkg/graphics/processing_security_test.go b/pkg/graphics/processing_security_test.go new file mode 100644 index 0000000..e84e8bb --- /dev/null +++ b/pkg/graphics/processing_security_test.go @@ -0,0 +1,49 @@ +package graphics_test + +import ( + "image" + "image/color" + "testing" + + "github.com/adcondev/poster/pkg/graphics" +) + +// HugeImage is a mock image that reports huge dimensions but doesn't store data. +type HugeImage struct { + W, H int +} + +func (m *HugeImage) ColorModel() color.Model { return color.RGBAModel } +func (m *HugeImage) Bounds() image.Rectangle { return image.Rect(0, 0, m.W, m.H) } +func (m *HugeImage) At(_, _ int) color.Color { return color.RGBA{0, 0, 0, 255} } + +func TestResizeImage_DoS_Vulnerability(t *testing.T) { + // Setup: srcW=10, srcH=1200, targetW=500. + // targetH would be (1200 * 500) / 10 = 60,000 without cap. + // With cap, it should be graphics.MaxImagePixelHeight (32000). + + src := &HugeImage{W: 10, H: 1200} + opts := &graphics.ResizeOptions{ + TargetWidth: 500, + MaxWidth: 576, + PreserveAspect: true, + Scaling: graphics.BiLinear, + } + + res := graphics.ResizeImage(src, opts) + + if res == nil { + t.Fatal("ResizeImage returned nil") + } + + bounds := res.Bounds() + t.Logf("Result bounds: %v", bounds) + + if bounds.Dy() > graphics.MaxImagePixelHeight { + t.Errorf("Result height %d exceeds MaxImagePixelHeight %d", bounds.Dy(), graphics.MaxImagePixelHeight) + } + + if bounds.Dy() != graphics.MaxImagePixelHeight { + t.Errorf("Expected result height to be capped at %d, got %d", graphics.MaxImagePixelHeight, bounds.Dy()) + } +} diff --git a/pkg/service/printer_service.go b/pkg/service/printer_service.go index ed0cf00..6d78866 100644 --- a/pkg/service/printer_service.go +++ b/pkg/service/printer_service.go @@ -4,6 +4,7 @@ package service import ( "fmt" + "github.com/adcondev/poster/internal/calculate" "github.com/adcondev/poster/pkg/commands/character" "github.com/adcondev/poster/pkg/commands/mechanismcontrol" "github.com/adcondev/poster/pkg/composer" @@ -49,10 +50,14 @@ func NewPrinter(proto *composer.EscposProtocol, prof *profile.Escpos, conn conne func (p *Printer) Initialize() error { // TODO: Add profile-specific initialization if needed var ct []byte + var err error if p.Profile.IsSupported(p.Profile.CodeTable) { - ct, _ = p.Protocol.Character.SelectCharacterCodeTable(p.Profile.CodeTable) + ct, err = p.Protocol.Character.SelectCharacterCodeTable(p.Profile.CodeTable) } else { - ct, _ = p.Protocol.Character.SelectCharacterCodeTable(character.WPC1252) + ct, err = p.Protocol.Character.SelectCharacterCodeTable(character.WPC1252) + } + if err != nil { + return fmt.Errorf("select code table: %w", err) } init := append(p.Protocol.InitializePrinter(), ct...) @@ -242,13 +247,19 @@ func (p *Printer) InverseOff() error { // FullFeedAndCut performs a full paper cut func (p *Printer) FullFeedAndCut(lines byte) error { - cmd, _ := p.Protocol.MechanismControl.FeedAndCutPaper(mechanismcontrol.FeedCutFull, lines) + cmd, err := p.Protocol.MechanismControl.FeedAndCutPaper(mechanismcontrol.FeedCutFull, lines) + if err != nil { + return fmt.Errorf("feed and cut paper: %w", err) + } return p.Write(cmd) } // PartialFeedAndCut performs a partial paper cut func (p *Printer) PartialFeedAndCut(lines byte) error { - cmd, _ := p.Protocol.MechanismControl.FeedAndCutPaper(mechanismcontrol.FeedCutPartial, lines) + cmd, err := p.Protocol.MechanismControl.FeedAndCutPaper(mechanismcontrol.FeedCutPartial, lines) + if err != nil { + return fmt.Errorf("feed and cut paper: %w", err) + } return p.Write(cmd) } @@ -320,21 +331,38 @@ func (p *Printer) SetCodeTable(codeTable character.CodeTable) error { // QR Code Printing Methods // ============================================================================ +// calculateMaxPixelWidth calculates the maximum printable pixel width based on printer profile. +func (p *Printer) calculateMaxPixelWidth() int { + if p.Profile.DotsPerLine > 0 { + return p.Profile.DotsPerLine + } + + if p.Profile.PrintWidth > 0 && p.Profile.DPI > 0 { + return calculate.MmToDots(float64(p.Profile.PrintWidth), p.Profile.DPI) + } + + if p.Profile.PaperWidth > 0 && p.Profile.DPI > 0 { + var printWidthMm float64 + if p.Profile.PaperWidth >= 78 { // ~80mm + printWidthMm = 72.0 + } else { // ~58mm or smaller + printWidthMm = 48.0 + } + return calculate.MmToDots(printWidthMm, p.Profile.DPI) + } + + return constants.PaperPxWidth80mm +} + // PrintQR imprime un QR con detección automática y fallback func (p *Printer) PrintQR(data string, qropts *graphics.QrOptions) error { + maxWidth := p.calculateMaxPixelWidth() if qropts == nil { - // TODO: Automatic options based on profile (DPI and Paper PixelWidth config to calculate Dots Per Line) qropts = graphics.DefaultQROptions() + qropts.MaxPixelWidth = maxWidth } - switch p.Profile.PaperWidth { - case constants.Paper58mm: - qropts.MaxPixelWidth = constants.PaperPxWidth58mm - case constants.Paper80mm: - qropts.MaxPixelWidth = constants.PaperPxWidth80mm - default: - qropts.MaxPixelWidth = constants.PaperPxWidth58mm - } + qropts.MaxPixelWidth = maxWidth // Use native ESC/POS QR only when supported AND neither logo nor circle_shape is requested qropts.Qr = graphics.QrInfo{} @@ -342,7 +370,8 @@ func (p *Printer) PrintQR(data string, qropts *graphics.QrOptions) error { qropts.Logo = graphics.LogoInfo{} } - if p.Profile.HasQR && qropts.LogoData == "" && qropts.Logo.Image == nil && !qropts.CircleShape { + useNativeQR := p.Profile.HasQR && qropts.LogoData == "" && qropts.Logo.Image == nil && !qropts.CircleShape + if useNativeQR { err := p.printQRNative(data, qropts) if err == nil { return nil diff --git a/pkg/service/qr_test.go b/pkg/service/qr_test.go new file mode 100644 index 0000000..44cc9b0 --- /dev/null +++ b/pkg/service/qr_test.go @@ -0,0 +1,276 @@ +package service + +import ( + "bytes" + "testing" + + "github.com/adcondev/poster/pkg/composer" + "github.com/adcondev/poster/pkg/constants" + "github.com/adcondev/poster/pkg/graphics" + "github.com/adcondev/poster/pkg/profile" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +type mockConnector struct { + buffer bytes.Buffer +} + +func (m *mockConnector) Write(p []byte) (n int, err error) { + return m.buffer.Write(p) +} + +func (m *mockConnector) Close() error { + return nil +} + +func TestCalculateMaxPixelWidth(t *testing.T) { + tests := []struct { + name string + profile profile.Escpos + expected int + }{ + { + name: "Profile with DotsPerLine set (80mm standard)", + profile: profile.Escpos{ + PaperWidth: 80, + DPI: 203, + DotsPerLine: 576, + }, + expected: 576, + }, + { + name: "Profile with DotsPerLine set (58mm standard)", + profile: profile.Escpos{ + PaperWidth: 58, + DPI: 203, + DotsPerLine: 384, + }, + expected: 384, + }, + { + name: "High DPI profile with DotsPerLine", + profile: profile.Escpos{ + PaperWidth: 80, + DPI: 300, + DotsPerLine: 944, + }, + expected: 944, + }, + { + name: "Profile without DotsPerLine (calculated from PrintWidth)", + profile: profile.Escpos{ + PaperWidth: 80, + DPI: 203, + PrintWidth: 72, + }, + expected: 575, // 72 * 203 / 25.4 = 575.4 -> 575 + }, + { + name: "Profile without DotsPerLine or PrintWidth (calc from 80mm PaperWidth)", + profile: profile.Escpos{ + PaperWidth: 80, + DPI: 203, + }, + expected: 575, // 72mm assumed * 203 / 25.4 + }, + { + name: "Profile without DotsPerLine or PrintWidth (calc from 58mm PaperWidth)", + profile: profile.Escpos{ + PaperWidth: 58, + DPI: 203, + }, + expected: 383, // 48mm assumed * 203 / 25.4 = 383.6 -> 383 + }, + { + name: "Profile with no dimension information (fallback to 80mm default)", + profile: profile.Escpos{}, + expected: constants.PaperPxWidth80mm, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + conn := &mockConnector{} + proto := composer.NewEscpos() + prof := tt.profile + + printer, err := NewPrinter(proto, &prof, conn) + require.NoError(t, err) + + actual := printer.calculateMaxPixelWidth() + assert.Equal(t, tt.expected, actual) + }) + } +} + +func TestPrintQR_AutomaticOptions(t *testing.T) { + tests := []struct { + name string + profile profile.Escpos + inputOpts *graphics.QrOptions + expectedMaxWidth int + }{ + { + name: "Standard 80mm 203dpi profile", + profile: profile.Escpos{ + PaperWidth: 80, + DPI: 203, + DotsPerLine: 576, + HasQR: true, + }, + inputOpts: &graphics.QrOptions{Model: 1}, + expectedMaxWidth: 576, + }, + { + name: "Standard 58mm 203dpi profile", + profile: profile.Escpos{ + PaperWidth: 58, + DPI: 203, + DotsPerLine: 384, + HasQR: true, + }, + inputOpts: &graphics.QrOptions{Model: 1}, + expectedMaxWidth: 384, + }, + { + name: "High DPI 80mm profile (300dpi)", + profile: profile.Escpos{ + PaperWidth: 80, + DPI: 300, + DotsPerLine: 944, + HasQR: true, + }, + inputOpts: &graphics.QrOptions{Model: 1}, + expectedMaxWidth: 944, + }, + { + name: "Profile without DotsPerLine (calc from PrintWidth)", + profile: profile.Escpos{ + PaperWidth: 80, + DPI: 203, + PrintWidth: 72, + HasQR: true, + }, + inputOpts: &graphics.QrOptions{Model: 1}, + expectedMaxWidth: 575, + }, + { + name: "Profile without DotsPerLine or PrintWidth (calc from PaperWidth)", + profile: profile.Escpos{ + PaperWidth: 80, + DPI: 203, + HasQR: true, + }, + inputOpts: &graphics.QrOptions{Model: 1}, + expectedMaxWidth: 575, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + conn := &mockConnector{} + proto := composer.NewEscpos() + prof := tt.profile + + printer, err := NewPrinter(proto, &prof, conn) + require.NoError(t, err) + + err = printer.PrintQR("https://example.com", tt.inputOpts) + assert.NoError(t, err) + assert.Equal(t, tt.expectedMaxWidth, tt.inputOpts.MaxPixelWidth) + }) + } +} + +func TestPrintQR_NativeVsFallback(t *testing.T) { + nativeQRHeader := []byte{0x1D, 0x28, 0x6B} + rasterBitImageHeader := []byte{0x1D, 0x76, 0x30} + + t.Run("Native QR used when HasQR is true and no logo/circle", func(t *testing.T) { + conn := &mockConnector{} + proto := composer.NewEscpos() + prof := profile.Escpos{ + PaperWidth: 80, + DPI: 203, + DotsPerLine: 576, + HasQR: true, + } + + printer, err := NewPrinter(proto, &prof, conn) + require.NoError(t, err) + + opts := graphics.DefaultQROptions() + err = printer.PrintQR("https://example.com", opts) + assert.NoError(t, err) + + buf := conn.buffer.Bytes() + assert.True(t, bytes.Contains(buf, nativeQRHeader), "expected native QR commands in buffer") + assert.False(t, bytes.Contains(buf, rasterBitImageHeader), "raster bit image commands should not be emitted") + }) + + t.Run("Software fallback used when HasQR is false", func(t *testing.T) { + conn := &mockConnector{} + proto := composer.NewEscpos() + prof := profile.Escpos{ + PaperWidth: 80, + DPI: 203, + DotsPerLine: 576, + HasQR: false, + } + + printer, err := NewPrinter(proto, &prof, conn) + require.NoError(t, err) + + opts := graphics.DefaultQROptions() + err = printer.PrintQR("https://example.com", opts) + assert.NoError(t, err) + + buf := conn.buffer.Bytes() + assert.False(t, bytes.Contains(buf, nativeQRHeader), "native QR commands should not be emitted when HasQR is false") + assert.True(t, bytes.Contains(buf, rasterBitImageHeader), "expected raster bit image commands in fallback") + }) + + t.Run("Software fallback used when CircleShape is true even with HasQR", func(t *testing.T) { + conn := &mockConnector{} + proto := composer.NewEscpos() + prof := profile.Escpos{ + PaperWidth: 80, + DPI: 203, + DotsPerLine: 576, + HasQR: true, + } + + printer, err := NewPrinter(proto, &prof, conn) + require.NoError(t, err) + + opts := graphics.DefaultQROptions() + opts.CircleShape = true + err = printer.PrintQR("https://example.com", opts) + assert.NoError(t, err) + + buf := conn.buffer.Bytes() + assert.False(t, bytes.Contains(buf, nativeQRHeader), "native QR commands should not be emitted when CircleShape is true") + assert.True(t, bytes.Contains(buf, rasterBitImageHeader), "expected raster bit image commands in circle shape fallback") + }) + + t.Run("Default options when nil qropts passed", func(t *testing.T) { + conn := &mockConnector{} + proto := composer.NewEscpos() + prof := profile.Escpos{ + PaperWidth: 80, + DPI: 203, + DotsPerLine: 576, + HasQR: true, + } + + printer, err := NewPrinter(proto, &prof, conn) + require.NoError(t, err) + + err = printer.PrintQR("https://example.com", nil) + assert.NoError(t, err) + + buf := conn.buffer.Bytes() + assert.True(t, bytes.Contains(buf, nativeQRHeader), "expected native QR commands for nil options with HasQR") + }) +}