1 // uploader -- simplest form file uploader
2 // Copyright (C) 2018-2024 Sergey Matveev <stargrave@stargrave.org>
4 // This program is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, version 3 of the License.
8 // This program is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 // GNU General Public License for more details.
13 // You should have received a copy of the GNU General Public License
14 // along with this program. If not, see <http://www.gnu.org/licenses/>.
26 var aLongTimeAgo = time.Unix(1, 0)
28 type UCSPIAddr struct {
33 func (addr *UCSPIAddr) Network() string { return "tcp" }
35 func (addr *UCSPIAddr) String() string { return addr.ip + ":" + addr.port }
37 type UCSPIConn struct {
41 type ReadResult struct {
46 func (conn *UCSPIConn) Read(b []byte) (int, error) {
47 c := make(chan ReadResult)
49 n, err := os.Stdin.Read(b)
50 c <- ReadResult{n, err}
60 func (conn *UCSPIConn) Write(b []byte) (int, error) { return os.Stdout.Write(b) }
62 func (conn *UCSPIConn) Close() error {
63 if err := os.Stdin.Close(); err != nil {
66 return os.Stdout.Close()
69 func (conn *UCSPIConn) LocalAddr() net.Addr {
70 return &UCSPIAddr{ip: os.Getenv("TCPLOCALIP"), port: os.Getenv("TCPLOCALPORT")}
73 func (conn *UCSPIConn) RemoteAddr() net.Addr {
74 return &UCSPIAddr{ip: os.Getenv("TCPREMOTEIP"), port: os.Getenv("TCPREMOTEPORT")}
77 func (conn *UCSPIConn) SetDeadline(t time.Time) error {
78 if err := os.Stdin.SetReadDeadline(t); err != nil {
81 return os.Stdout.SetWriteDeadline(t)
84 func (conn *UCSPIConn) SetReadDeadline(t time.Time) error {
85 // An ugly hack to forcefully terminate pending read.
86 // net/http calls SetReadDeadline(aLongTimeAgo), but file
87 // descriptors are not capable to exit immediately that way.
88 if t.Equal(aLongTimeAgo) {
89 conn.eof <- struct{}{}
91 return os.Stdin.SetReadDeadline(t)
94 func (conn *UCSPIConn) SetWriteDeadline(t time.Time) error {
95 return os.Stdout.SetWriteDeadline(t)
98 type UCSPI struct{ accepted bool }
100 type UCSPIAlreadyAccepted struct{}
102 func (u UCSPIAlreadyAccepted) Error() string {
103 return "already accepted"
106 func (ucspi *UCSPI) Accept() (net.Conn, error) {
108 return nil, UCSPIAlreadyAccepted{}
110 ucspi.accepted = true
111 conn := UCSPIConn{eof: make(chan struct{}, 1)}
115 func (ucspi *UCSPI) Close() error {
119 func (ucspi *UCSPI) Addr() net.Addr {
120 return &UCSPIAddr{ip: os.Getenv("TCPLOCALIP"), port: os.Getenv("TCPLOCALPORT")}
123 func connStater(conn net.Conn, connState http.ConnState) {
127 case http.StateClosed: