]> Sergey Matveev's repositories - tofuproxy.git/blob - cmd/ungzip/main.go
0895aa576fece023266ad4c6fa67a695488aea98
[tofuproxy.git] / cmd / ungzip / main.go
1 /*
2 tofuproxy -- flexible HTTP/WARC proxy with TLS certificates management
3 Copyright (C) 2021 Sergey Matveev <stargrave@stargrave.org>
4
5 This program is free software: you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation, version 3 of the License.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 GNU General Public License for more details.
13
14 You should have received a copy of the GNU General Public License
15 along with this program.  If not, see <http://www.gnu.org/licenses/>.
16 */
17
18 package main
19
20 import (
21         "bufio"
22         "compress/gzip"
23         "fmt"
24         "io"
25         "log"
26         "os"
27 )
28
29 type CountableReader struct {
30         *bufio.Reader
31         n int64
32 }
33
34 func (r *CountableReader) ReadByte() (b byte, err error) {
35         b, err = r.Reader.ReadByte()
36         if err == nil {
37                 r.n++
38         }
39         return b, err
40 }
41
42 func (r *CountableReader) Read(p []byte) (n int, err error) {
43         n, err = r.Reader.Read(p)
44         r.n += int64(n)
45         return
46 }
47
48 func main() {
49         log.SetFlags(log.Lshortfile)
50         fdOff := os.NewFile(3, "fdOff")
51         br := bufio.NewReader(os.Stdin)
52         cr := &CountableReader{Reader: br}
53         bw := bufio.NewWriter(os.Stdout)
54         z, err := gzip.NewReader(cr)
55         if err != nil {
56                 log.Fatalln(err)
57         }
58         z.Multistream(false)
59         var offset, offsetPrev int64
60         for {
61                 written, err := io.Copy(bw, z)
62                 if err != nil {
63                         log.Fatalln(err)
64                 }
65                 offset = cr.n
66                 if fdOff != nil {
67                         fmt.Fprintf(fdOff, "%d\t%d\n", offset-offsetPrev, written)
68                 }
69                 offsetPrev = offset
70                 err = z.Reset(cr)
71                 if err != nil {
72                         if err == io.EOF {
73                                 break
74                         }
75                         log.Fatalln(err)
76                 }
77                 z.Multistream(false)
78         }
79 }