-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdeppa.go
424 lines (384 loc) · 12.7 KB
/
deppa.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
/**
* This file is part of Deppa.
* Copyright (C) 2021 Emily <[email protected]>
*
* Deppa is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Deppa is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Deppa. If not, see <https://www.gnu.org/licenses/>.
**/
package main
import (
"bufio"
"flag"
"fmt"
"io"
"io/ioutil"
"net"
"os"
"os/exec"
"os/user"
"runtime"
"strconv"
"strings"
"syscall"
)
type DeppaSettings struct {
hostname string
port int
portString string
dir string
disableGobj bool
manualGCInterval int
userId uint32
groupId uint32
}
func existsAndIsDir(path string) (bool, bool, error) {
info, err := os.Stat(path)
if err == nil {
if info.IsDir() {
return true, true, nil
} else {
return true, false, nil
}
}
if os.IsNotExist(err) {
return false, false, nil
}
return false, false, err
}
func ErrorResponse(message string) string {
/* return an error response */
return "3" + message + "\tfake\t(NULL)\t0\r\n.\r\n"
}
func handleConnection(conn net.Conn, opts DeppaSettings) {
/* handle incoming requests, parse magic string and call handler */
defer conn.Close()
buf := bufio.NewReader(conn)
req, toobig, err := buf.ReadLine()
if err != nil {
fmt.Fprint(conn, ErrorResponse("Invalid request: cannot read magic string"))
return
}
if toobig {
fmt.Fprint(conn, ErrorResponse("Invalid request: magic string too big"))
return
}
fmt.Printf("%v: %s", conn.RemoteAddr(), req)
handleBasicRequest(string(req), conn, opts)
}
func handleBasicRequest(request string, conn net.Conn, opts DeppaSettings) {
/* find request type */
if strings.Contains(request, "../") || strings.Contains(request, "/..") {
fmt.Fprint(conn, ErrorResponse("Invalid request: \"../\" and \"/..\" are not allowed in magic string"))
}
fmt.Printf("\t%s/%s\n", opts.dir, request)
if request == "" {
handleDirectoryListingRequest(request, conn, opts)
} else if request[len(request) - 1] == '/' {
handleDirectoryListingRequest(request, conn, opts)
} else {
handleFileDisplayRequest(request, conn, opts)
}
}
func handleDirectoryListingRequest(request string, conn net.Conn, opts DeppaSettings) {
files, err := ioutil.ReadDir(opts.dir + "/" + request)
if err != nil {
fmt.Println(opts.dir + "/" + request)
fmt.Fprint(conn, ErrorResponse("Invalid request: cannot read target dir"))
}
reverse := false
footer := false
header := false
use_index := false
var resplines []string
var index_fname string
for _, file := range files {
if file.Name()[0] == '.' {
if file.Name() == ".reverse" {
reverse = true
} else if file.Name() == ".header" {
header = true
} else if file.Name() == ".footer" {
footer = true
}
continue
} else if strings.HasPrefix(file.Name(), "index") && !strings.HasSuffix(file.Name(), ".html") {
use_index = true
index_fname = file.Name()
break
}
var respline string
if file.IsDir() || strings.HasSuffix(file.Name(), ".md") || strings.HasSuffix(file.Name(), ".gm") {
respline = "1" + file.Name() + "\t" + request + file.Name() + "\t" + opts.hostname + "\t" + opts.portString + "\r\n"
} else if strings.HasSuffix(file.Name(), ".gobj") || strings.HasSuffix(file.Name(), ".txt") {
respline = "0" + file.Name() + "\t" + request + file.Name() + "\t" + opts.hostname + "\t" + opts.portString + "\r\n"
} else if strings.HasSuffix(file.Name(), ".ogg") || strings.HasSuffix(file.Name(), ".opus") || strings.HasSuffix(file.Name(), ".flac") || strings.HasSuffix(file.Name(), ".mp3") || strings.HasSuffix(file.Name(), ".wav") {
respline = "s" + file.Name() + "\t" + request + file.Name() + "\t" + opts.hostname + "\t" + opts.portString + "\r\n"
} else if strings.HasSuffix(file.Name(), ".pdf") || strings.HasSuffix(file.Name(), ".doc") || strings.HasSuffix(file.Name(), ".docx") {
respline = "d" + file.Name() + "\t" + request + file.Name() + "\t" + opts.hostname + "\t" + opts.portString + "\r\n"
} else {
respline = "9" + file.Name() + "\t" + request + file.Name() + "\t" + opts.hostname + "\t" + opts.portString + "\r\n"
}
resplines = append(resplines, respline)
}
if use_index {
handleFileDisplayRequest(request + "/" + index_fname, conn, opts)
} else {
if header {
SendPlainFile(opts.dir + "/" + request + "/.header", conn)
}
if reverse {
for i := len(resplines) - 1; i >= 0; i-- {
fmt.Fprint(conn, resplines[i])
}
} else {
for _, entry := range resplines {
fmt.Fprint(conn, entry)
}
}
if footer {
SendPlainFile(opts.dir + "/" + request + "/.footer", conn)
}
fmt.Fprint(conn, ".\r\n")
}
}
func handleFileDisplayRequest(request string, conn net.Conn, opts DeppaSettings) {
exist, isdir, err := existsAndIsDir(opts.dir + "/" + request)
if !exist || err != nil {
fmt.Fprint(conn, ErrorResponse("Not found"))
} else if isdir {
handleDirectoryListingRequest(request + "/", conn, opts)
}
if strings.HasSuffix(request, ".md") {
SendHeaderIfStandaloneAndExists(request, conn, opts, true)
SendMarkdownFile(opts.dir + "/" + request, conn, opts, request)
SendFooterIfStandaloneAndExists(request, conn, opts, true)
} else if strings.HasSuffix(request, ".gm") {
SendHeaderIfStandaloneAndExists(request, conn, opts, true)
SendFile(opts.dir + "/" + request, conn)
SendFooterIfStandaloneAndExists(request, conn, opts, true)
} else if strings.HasSuffix(request, ".gobj") {
if !opts.disableGobj {
SendHeaderIfStandaloneAndExists(request, conn, opts, false)
// out, err := exec.Command(opts.dir + "/" + request).Output()
cmd := exec.Command(opts.dir + "/" + request)
cmd.SysProcAttr = &syscall.SysProcAttr{}
cmd.SysProcAttr.Credential = &syscall.Credential{Uid: opts.userId, Gid: opts.groupId}
out, err := cmd.Output()
if err != nil {
fmt.Fprint(conn, ErrorResponse("error executing script"))
return
}
conn.Write(out)
SendFooterIfStandaloneAndExists(request, conn, opts, false)
} else {
fmt.Fprint(conn, ErrorResponse("Not found"))
fmt.Println("script execution requested, but --disable-gobj flag passed")
}
} else if strings.HasSuffix(request, ".txt") {
SendHeaderIfStandaloneAndExists(request, conn, opts, false)
SendFile(opts.dir + "/" + request, conn)
SendFooterIfStandaloneAndExists(request, conn, opts, false)
} else {
SendFile(opts.dir + "/" + request, conn)
return
}
fmt.Fprint(conn, ".\r\n")
}
func SendHeaderIfStandaloneAndExists(request string, conn net.Conn, opts DeppaSettings, listing bool) {
pathParts := strings.Split(request, "/")
var path string
if len(pathParts) == 1 {
path = ""
} else {
path = strings.Join(pathParts[:len(pathParts) - 1], "/")
}
exist, isdir, err := existsAndIsDir(opts.dir + "/" + path + "/.header")
if exist && !isdir && err == nil {
if listing {
SendPlainFile(opts.dir + "/" + path + "/.header", conn)
} else {
SendFile(opts.dir + "/" + path + "/.header", conn)
}
}
}
func SendFooterIfStandaloneAndExists(request string, conn net.Conn, opts DeppaSettings, listing bool) {
pathParts := strings.Split(request, "/")
var path string
if len(pathParts) == 1 {
path = ""
} else {
path = strings.Join(pathParts[:len(pathParts) - 1], "/")
}
exist, isdir, err := existsAndIsDir(opts.dir + "/" + path + "/.footer")
if exist && !isdir && err == nil {
if listing {
SendPlainFile(opts.dir + "/" + path + "/.footer", conn)
} else {
SendFile(opts.dir + "/" + path + "/.footer", conn)
}
}
}
func SendFile(path string, conn net.Conn) {
file, err := os.Open(path)
if err != nil {
fmt.Fprint(conn, ErrorResponse("Not found"))
return
}
defer file.Close()
_, err = io.Copy(conn, file)
if err != nil {
return
}
}
func SendMarkdownFile(path string, conn net.Conn, opts DeppaSettings, request string) {
file, err := os.Open(path)
if err != nil {
fmt.Fprint(conn, ErrorResponse("Not found"))
return
}
defer file.Close()
var content string
scan := bufio.NewScanner(file)
for scan.Scan() {
currentline := scan.Text()
if strings.HasPrefix(currentline, "[") {
sections := strings.Split(currentline, "]")
sections[0] = sections[0][1:]
sections[1] = sections[1][1:len(sections[1]) - 1]
if strings.HasPrefix(sections[1], "http") || strings.HasSuffix(sections[1], ".html") {
content += "h" + sections[0] + "\t/URL:" + sections[1] + "\t" + opts.hostname + "\t" + opts.portString + "\r\n"
} else {
if sections[1][0] != '/' {
pathParts := strings.Split(request, "/")
if len(pathParts) == 1 {
request = ""
} else {
request = strings.Join(pathParts[:len(pathParts) - 1], "/") + "/"
}
sections[1] = request + sections[1]
}
if strings.HasSuffix(sections[1], "/") || strings.HasSuffix(sections[1], ".md") || strings.HasSuffix(sections[1], ".gm") {
content += "1" + sections[0] + "\t" + sections[1] + "\t" + opts.hostname + "\t" + opts.portString + "\r\n"
} else if strings.HasSuffix(sections[1], ".gobj") || strings.HasSuffix(sections[1], ".txt") {
content += "0" + sections[0] + "\t" + sections[1] + "\t" + opts.hostname + "\t" + opts.portString + "\r\n"
} else {
content += "9" + sections[0] + "\t" + sections[1] + "\t" + opts.hostname + "\t" + opts.portString + "\r\n"
}
}
} else if strings.HasPrefix(currentline, "![") {
sections := strings.Split(currentline, "]")
sections[0] = sections[0][1:]
sections[1] = sections[1][1:len(sections[1]) - 1]
content += "I" + sections[0] + "\t" + sections[1] + "\t" + opts.hostname + "\t" + opts.portString + "\r\n"
} else {
content += "i" + currentline + "\tfake\t(NULL)\t0\r\n"
}
}
if scan.Err() != nil {
fmt.Fprint(conn, ErrorResponse("Read error"))
return
}
fmt.Fprint(conn, content)
}
func SendPlainFile(path string, conn net.Conn) {
file, err := os.Open(path)
if err != nil {
fmt.Fprint(conn, ErrorResponse("Not found"))
return
}
defer file.Close()
var content string
scan := bufio.NewScanner(file)
for scan.Scan() {
content += "i" + scan.Text() + "\tfake\t(NULL)\t0\r\n"
}
if scan.Err() != nil {
fmt.Fprint(conn, ErrorResponse("Read error"))
return
}
fmt.Fprint(conn, content)
}
func RunServer(opts DeppaSettings) {
/* init socket */
ln, err := net.Listen("tcp", opts.hostname + ":" + opts.portString)
if err != nil {
fmt.Printf("error: could not listen on socket. exiting. (%v)\n", err)
return
}
fmt.Println("listening on " + opts.hostname + ":" + opts.portString)
gcCountdown := 0
/* listen forever */
for {
conn, err := ln.Accept()
if err != nil {
fmt.Printf("error: could not accept connection (%v)\n", err)
}
go handleConnection(conn, opts)
gcCountdown++
if gcCountdown == opts.manualGCInterval {
fmt.Println("\n-= RUNNING GC NOW! =-\n")
runtime.GC()
gcCountdown = 0
}
}
}
func main() {
/* determine hostname */
default_hostname, err := os.Hostname()
if err != nil {
fmt.Printf("error: could not fetch default hostname, defaulting to 0.0.0.0 (%v)\n", err)
default_hostname = "0.0.0.0"
}
/* parse flags */
version := flag.Bool("v", false, "print program version and exit")
hostname := flag.String("h", default_hostname, "hostname to listen on")
port := flag.Int("p", 70, "port to listen on")
dir := flag.String("d", ".", "directory to serve files from")
disableGobj := flag.Bool("disable-gobj", false, "disables execution of .gobj files when given")
gcInterval := flag.Int("gc-interval", 1024, "number of requests after which the garbage collector should trigger")
dropUid := flag.String("gobj-user", "nobody", "user to run gobjs as")
dropGid := flag.String("gobj-group", "nogroup", "group to run gobjs as")
flag.Parse()
if *version {
fmt.Println("deppa 1.1")
os.Exit(0)
}
var userId uint32 = 0
var groupId uint32 = 0
if !(*disableGobj) {
usr, err := user.Lookup(*dropUid)
if err != nil {
fmt.Printf("user.Lookup: %v\n", err)
os.Exit(1)
}
uid, err := strconv.Atoi(usr.Uid)
if err != nil {
fmt.Printf("user.Lookup.Uid.Atoi: %v\n", err)
os.Exit(1)
}
userId = uint32(uid)
group, err := user.LookupGroup(*dropGid)
if err != nil {
fmt.Printf("user.LookupGroup: %v\n", err)
os.Exit(1)
}
gid, err := strconv.Atoi(group.Gid)
if err != nil {
fmt.Printf("user.LookupGroup.Gid.Atoi: %v\n", err)
os.Exit(1)
}
groupId = uint32(gid)
}
opts := DeppaSettings { *hostname, *port, strconv.Itoa(*port), *dir, *disableGobj, *gcInterval, userId, groupId }
RunServer(opts)
}