File: debase64.go
   1 /*
   2 The MIT License (MIT)
   3 
   4 Copyright © 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     if len(os.Args) > 2 {
  52         os.Stderr.WriteString(info[1:])
  53         os.Exit(1)
  54     }
  55 
  56     if len(os.Args) > 1 {
  57         switch os.Args[1] {
  58         case `-h`, `--h`, `-help`, `--help`:
  59             os.Stdout.WriteString(info[1:])
  60             return
  61         }
  62     }
  63 
  64     name := `-`
  65     if len(os.Args) > 1 {
  66         name = os.Args[1]
  67     }
  68 
  69     if err := run(name); err != nil {
  70         os.Stderr.WriteString(err.Error())
  71         os.Stderr.WriteString("\n")
  72         os.Exit(1)
  73     }
  74 }
  75 
  76 func run(s string) error {
  77     // bw := bufio.NewWriterSize(os.Stdout, 32*1024)
  78     // defer bw.Flush()
  79     // w := bw
  80 
  81     w := os.Stdout
  82 
  83     if s == `-` {
  84         return debase64(w, os.Stdin)
  85     }
  86 
  87     if seemsDataURI(s) {
  88         return debase64(w, strings.NewReader(s))
  89     }
  90 
  91     f, err := os.Open(s)
  92     if err != nil {
  93         return err
  94     }
  95     defer f.Close()
  96 
  97     return debase64(w, f)
  98 }
  99 
 100 // debase64 decodes base64 chunks explicitly, so decoding errors can be told
 101 // apart from output-writing ones
 102 func debase64(w io.Writer, r io.Reader) error {
 103     var buf [32 * 1024]byte
 104     n, err := r.Read(buf[:])
 105     if n < 1 && err == io.EOF {
 106         return nil
 107     }
 108     if err != nil {
 109         return err
 110     }
 111 
 112     start, err := skipIntroDataURI(buf[:n])
 113     if err != nil {
 114         return err
 115     }
 116 
 117     start = append([]byte(nil), start...)
 118     r = io.MultiReader(bytes.NewReader(start), r)
 119     dec := base64.NewDecoder(base64.StdEncoding, r)
 120     _, err = io.Copy(w, dec)
 121     return err
 122 
 123     // for {
 124     //  n, err := dec.Read(buf[:])
 125     //  if n < 1 && err == io.EOF {
 126     //      return nil
 127     //  }
 128     //  if err != nil {
 129     //      return err
 130     //  }
 131 
 132     //  if _, err := w.Write(buf[:n]); err != nil {
 133     //      // assume write-errors are always due to deliberately-closed
 134     //      // stdout pipes: ignore those errors and quit right away
 135     //      return nil
 136     //  }
 137     // }
 138 }
 139 
 140 func skipIntroDataURI(chunk []byte) ([]byte, error) {
 141     if !bytes.HasPrefix(chunk, []byte(`data:`)) {
 142         return chunk, nil
 143     }
 144 
 145     start := chunk
 146     if len(start) > 64 {
 147         start = start[:64]
 148     }
 149 
 150     i := bytes.Index(start, []byte(`;base64,`))
 151     if i < 0 {
 152         return chunk, errors.New(`invalid data URI`)
 153     }
 154 
 155     return chunk[i+len(`;base64,`):], nil
 156 }
 157 
 158 func seemsDataURI(s string) bool {
 159     start := s
 160     if len(s) > 64 {
 161         start = s[:64]
 162     }
 163     return strings.HasPrefix(s, `data:`) && strings.Contains(start, `;base64,`)
 164 }