File: debase64.go
   1 /*
   2 The MIT License (MIT)
   3 
   4 Copyright © 2020-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 Single-file source-code for debase64.
  27 
  28 To compile a smaller-sized command-line app, you can use the `go` command as
  29 follows:
  30 
  31 go build -ldflags "-s -w" -trimpath debase64.go
  32 */
  33 
  34 package main
  35 
  36 import (
  37     "bytes"
  38     "encoding/base64"
  39     "errors"
  40     "io"
  41     "os"
  42     "strings"
  43 )
  44 
  45 const info = `
  46 debase64 [file/data-URI...]
  47 
  48 Decode base64-encoded files and/or data-URIs.
  49 `
  50 
  51 func main() {
  52     if len(os.Args) > 2 {
  53         os.Stderr.WriteString(info[1:])
  54         os.Exit(1)
  55     }
  56 
  57     if len(os.Args) > 1 {
  58         switch os.Args[1] {
  59         case `-h`, `--h`, `-help`, `--help`:
  60             os.Stderr.WriteString(info[1:])
  61             return
  62         }
  63     }
  64 
  65     name := `-`
  66     if len(os.Args) > 1 {
  67         name = os.Args[1]
  68     }
  69 
  70     if err := run(name); err != nil {
  71         os.Stderr.WriteString("\x1b[31m")
  72         os.Stderr.WriteString(err.Error())
  73         os.Stderr.WriteString("\x1b[0m\n")
  74         os.Exit(1)
  75     }
  76 }
  77 
  78 func run(s string) error {
  79     if s == `-` {
  80         return debase64(os.Stdout, os.Stdin)
  81     }
  82 
  83     if seemsDataURI(s) {
  84         return debase64(os.Stdout, strings.NewReader(s))
  85     }
  86 
  87     f, err := os.Open(s)
  88     if err != nil {
  89         return err
  90     }
  91     defer f.Close()
  92 
  93     return debase64(os.Stdout, f)
  94 }
  95 
  96 // debase64 decodes base64 chunks explicitly, so decoding errors can be told
  97 // apart from output-writing ones
  98 func debase64(w io.Writer, r io.Reader) error {
  99     var buf [16 * 1024]byte
 100     n, err := r.Read(buf[:])
 101     if n < 1 && err == io.EOF {
 102         return nil
 103     }
 104     if err != nil {
 105         return err
 106     }
 107 
 108     start, err := skipIntroDataURI(buf[:n])
 109     if err != nil {
 110         return err
 111     }
 112 
 113     start = append([]byte(nil), start...)
 114     r = io.MultiReader(bytes.NewReader(start), r)
 115     dec := base64.NewDecoder(base64.StdEncoding, r)
 116 
 117     for {
 118         n, err := dec.Read(buf[:])
 119         if n < 1 && err == io.EOF {
 120             return nil
 121         }
 122         if err != nil {
 123             return err
 124         }
 125 
 126         if _, err := w.Write(buf[:n]); err != nil {
 127             // assume write-errors are always due to deliberately-closed
 128             // stdout pipes: ignore those errors and quit right away
 129             return nil
 130         }
 131     }
 132 }
 133 
 134 func skipIntroDataURI(chunk []byte) ([]byte, error) {
 135     if !bytes.HasPrefix(chunk, []byte(`data:`)) {
 136         return chunk, nil
 137     }
 138 
 139     start := chunk
 140     if len(start) > 64 {
 141         start = start[:64]
 142     }
 143 
 144     i := bytes.Index(start, []byte(`;base64,`))
 145     if i < 0 {
 146         return chunk, errors.New(`invalid data URI`)
 147     }
 148 
 149     return chunk[i+len(`;base64,`):], nil
 150 }
 151 
 152 func seemsDataURI(s string) bool {
 153     start := s
 154     if len(s) > 64 {
 155         start = s[:64]
 156     }
 157     return strings.HasPrefix(s, `data:`) && strings.Contains(start, `;base64,`)
 158 }