File: debase64.go
   1 /*
   2 The MIT License (MIT)
   3 
   4 Copyright (c) 2026 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     "bufio"
  36     "bytes"
  37     "encoding/base64"
  38     "errors"
  39     "io"
  40     "os"
  41     "strings"
  42 )
  43 
  44 const info = `
  45 debase64 [file/data-URI...]
  46 
  47 Decode base64-encoded files and/or data-URIs.
  48 `
  49 
  50 func main() {
  51     args := os.Args[1:]
  52 
  53     if len(args) > 0 {
  54         switch args[0] {
  55         case `-h`, `--h`, `-help`, `--help`:
  56             os.Stdout.WriteString(info[1:])
  57             return
  58 
  59         case `--`:
  60             args = args[1:]
  61         }
  62     }
  63 
  64     if len(args) > 1 {
  65         os.Stderr.WriteString(info[1:])
  66         os.Exit(1)
  67     }
  68 
  69     name := `-`
  70     if len(args) == 1 {
  71         name = args[0]
  72     }
  73 
  74     if err := run(name); err != nil {
  75         os.Stderr.WriteString(err.Error())
  76         os.Stderr.WriteString("\n")
  77         os.Exit(1)
  78     }
  79 }
  80 
  81 func run(s string) error {
  82     bw := bufio.NewWriterSize(os.Stdout, 32*1024)
  83     defer bw.Flush()
  84     w := bw
  85 
  86     if s == `-` {
  87         return debase64(w, os.Stdin)
  88     }
  89 
  90     if seemsDataURI(s) {
  91         return debase64(w, strings.NewReader(s))
  92     }
  93 
  94     f, err := os.Open(s)
  95     if err != nil {
  96         return err
  97     }
  98     defer f.Close()
  99 
 100     return debase64(w, f)
 101 }
 102 
 103 // debase64 decodes base64 chunks explicitly, so decoding errors can be told
 104 // apart from output-writing ones
 105 func debase64(w io.Writer, r io.Reader) error {
 106     br := bufio.NewReaderSize(r, 32*1024)
 107     start, err := br.Peek(64)
 108     if err != nil && err != io.EOF {
 109         return err
 110     }
 111 
 112     skip, err := skipIntroDataURI(start)
 113     if err != nil {
 114         return err
 115     }
 116 
 117     if skip > 0 {
 118         br.Discard(skip)
 119     }
 120 
 121     dec := base64.NewDecoder(base64.StdEncoding, br)
 122     _, err = io.Copy(w, dec)
 123     return err
 124 }
 125 
 126 func skipIntroDataURI(chunk []byte) (skip int, err error) {
 127     if bytes.HasPrefix(chunk, []byte{0xef, 0xbb, 0xbf}) {
 128         chunk = chunk[3:]
 129         skip += 3
 130     }
 131 
 132     if !bytes.HasPrefix(chunk, []byte(`data:`)) {
 133         return skip, nil
 134     }
 135 
 136     start := chunk
 137     if len(start) > 64 {
 138         start = start[:64]
 139     }
 140 
 141     i := bytes.Index(start, []byte(`;base64,`))
 142     if i < 0 {
 143         return skip, errors.New(`invalid data URI`)
 144     }
 145 
 146     skip += i + len(`;base64,`)
 147     return skip, 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 }