File: debase64.go
   1 /*
   2 The MIT License (MIT)
   3 
   4 Copyright © 2025 pacman64
   5 
   6 Permission is hereby granted, free of charge, to any person obtaining a copy of
   7 this software and associated documentation files (the “Software”), to deal
   8 in the Software without restriction, including without limitation the rights to
   9 use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
  10 of the Software, and to permit persons to whom the Software is furnished to do
  11 so, subject to the following conditions:
  12 
  13 The above copyright notice and this permission notice shall be included in all
  14 copies or substantial portions of the Software.
  15 
  16 THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  19 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  22 SOFTWARE.
  23 */
  24 
  25 /*
  26 To compile a smaller-sized command-line app, you can use the `go` command as
  27 follows:
  28 
  29 go build -ldflags "-s -w" -trimpath debase64.go
  30 */
  31 
  32 package main
  33 
  34 import (
  35     "bytes"
  36     "encoding/base64"
  37     "errors"
  38     "io"
  39     "os"
  40     "strings"
  41 )
  42 
  43 const info = `
  44 debase64 [file/data-URI...]
  45 
  46 Decode base64-encoded files and/or data-URIs.
  47 `
  48 
  49 func main() {
  50     if len(os.Args) > 2 {
  51         os.Stderr.WriteString(info[1:])
  52         os.Exit(1)
  53     }
  54 
  55     if len(os.Args) > 1 {
  56         switch os.Args[1] {
  57         case `-h`, `--h`, `-help`, `--help`:
  58             os.Stderr.WriteString(info[1:])
  59             return
  60         }
  61     }
  62 
  63     name := `-`
  64     if len(os.Args) > 1 {
  65         name = os.Args[1]
  66     }
  67 
  68     if err := run(name); err != nil {
  69         os.Stderr.WriteString("\x1b[31m")
  70         os.Stderr.WriteString(err.Error())
  71         os.Stderr.WriteString("\x1b[0m\n")
  72         os.Exit(1)
  73     }
  74 }
  75 
  76 func run(s string) error {
  77     if s == `-` {
  78         return debase64(os.Stdout, os.Stdin)
  79     }
  80 
  81     if seemsDataURI(s) {
  82         return debase64(os.Stdout, strings.NewReader(s))
  83     }
  84 
  85     f, err := os.Open(s)
  86     if err != nil {
  87         return err
  88     }
  89     defer f.Close()
  90 
  91     return debase64(os.Stdout, f)
  92 }
  93 
  94 // debase64 decodes base64 chunks explicitly, so decoding errors can be told
  95 // apart from output-writing ones
  96 func debase64(w io.Writer, r io.Reader) error {
  97     var buf [32 * 1024]byte
  98     n, err := r.Read(buf[:])
  99     if n < 1 && err == io.EOF {
 100         return nil
 101     }
 102     if err != nil {
 103         return err
 104     }
 105 
 106     start, err := skipIntroDataURI(buf[:n])
 107     if err != nil {
 108         return err
 109     }
 110 
 111     start = append([]byte(nil), start...)
 112     r = io.MultiReader(bytes.NewReader(start), r)
 113     dec := base64.NewDecoder(base64.StdEncoding, r)
 114 
 115     for {
 116         n, err := dec.Read(buf[:])
 117         if n < 1 && err == io.EOF {
 118             return nil
 119         }
 120         if err != nil {
 121             return err
 122         }
 123 
 124         if _, err := w.Write(buf[:n]); err != nil {
 125             // assume write-errors are always due to deliberately-closed
 126             // stdout pipes: ignore those errors and quit right away
 127             return nil
 128         }
 129     }
 130 }
 131 
 132 func skipIntroDataURI(chunk []byte) ([]byte, error) {
 133     if !bytes.HasPrefix(chunk, []byte(`data:`)) {
 134         return chunk, nil
 135     }
 136 
 137     start := chunk
 138     if len(start) > 64 {
 139         start = start[:64]
 140     }
 141 
 142     i := bytes.Index(start, []byte(`;base64,`))
 143     if i < 0 {
 144         return chunk, errors.New(`invalid data URI`)
 145     }
 146 
 147     return chunk[i+len(`;base64,`):], nil
 148 }
 149 
 150 func seemsDataURI(s string) bool {
 151     start := s
 152     if len(s) > 64 {
 153         start = s[:64]
 154     }
 155     return strings.HasPrefix(s, `data:`) && strings.Contains(start, `;base64,`)
 156 }