-
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathmain.go
More file actions
277 lines (244 loc) · 10.4 KB
/
Copy pathmain.go
File metadata and controls
277 lines (244 loc) · 10.4 KB
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
package main
import (
"context"
"errors"
"fmt"
"log"
"os"
"os/signal"
"path/filepath"
"runtime/debug"
"time"
"github.com/fatih/color"
"github.com/go-pkgz/lgr"
"github.com/jessevdk/go-flags"
"github.com/umputun/weblist/server"
)
type options struct {
Listen string `short:"l" long:"listen" env:"LISTEN" default:":8080" description:"address to listen on"`
Theme string `short:"t" long:"theme" env:"THEME" default:"light" description:"theme to use (light or dark)"`
RootDir string `short:"r" long:"root" env:"ROOT_DIR" default:"." description:"root directory to serve"`
Exclude []string `short:"e" long:"exclude" env:"EXCLUDE" description:"files and directories to exclude (can be repeated)"`
Auth string `short:"a" long:"auth" env:"AUTH" description:"password for basic auth"`
AuthUser string `long:"auth-user" env:"AUTH_USER" default:"weblist" description:"username for basic auth"`
SessionSecret string `long:"session-secret" env:"SESSION_SECRET" description:"secret key for session tokens (auto-generated if not set)"`
Title string `long:"title" env:"TITLE" description:"custom title for the site (used in browser title and home)"`
HideFooter bool `short:"f" long:"hide-footer" env:"HIDE_FOOTER" description:"hide footer"`
CustomFooter string `long:"custom-footer" env:"CUSTOM_FOOTER" description:"custom footer text (can contain HTML)"`
EnableSyntaxHighlighting bool `long:"syntax-highlight" env:"SYNTAX_HIGHLIGHT" description:"enable syntax highlighting"`
EnableMultiSelect bool `long:"multi" env:"MULTI_SELECT" description:"enable multi-file selection and download"`
RecursiveMtime bool `long:"recursive-mtime" env:"RECURSIVE_MTIME" description:"directory mtime from newest file"`
InsecureCookies bool `long:"insecure-cookies" env:"INSECURE_COOKIES" description:"allow cookies without secure flag"`
SessionTTL time.Duration `long:"session-ttl" env:"SESSION_TTL" default:"24h" description:"session timeout"`
SFTP struct {
Enabled bool `long:"enabled" env:"ENABLED" description:"enable SFTP server"`
User string `long:"user" env:"USER" default:"weblist" description:"username for SFTP access"`
Address string `long:"address" env:"ADDRESS" default:":2022" description:"address to listen for SFTP connections"`
KeyFile string `long:"key" env:"KEY" default:"weblist_rsa" description:"SSH private key file path"`
Authorized string `long:"authorized" env:"AUTHORIZED" description:"public key authentication file path"`
} `group:"SFTP options" namespace:"sftp" env-namespace:"SFTP"`
Upload struct {
Enabled bool `long:"enabled" env:"ENABLED" description:"enable file upload"`
MaxSize int64 `long:"max-size" env:"MAX_SIZE" default:"64" description:"max upload size in MB"`
Overwrite bool `long:"overwrite" env:"OVERWRITE" description:"allow overwriting existing files"`
} `group:"Upload options" namespace:"upload" env-namespace:"UPLOAD"`
Branding struct {
Name string `long:"name" env:"NAME" description:"company or organization name to display in navbar"`
Color string `long:"color" env:"COLOR" description:"color for navbar (e.g. #3498db or 3498db)"`
} `group:"Branding options" namespace:"brand" env-namespace:"BRAND"`
Version bool `short:"v" long:"version" env:"VERSION" description:"show version and exit"`
Dbg bool `long:"dbg" env:"DEBUG" description:"debug mode"`
}
var opts options
var revision = "unknown" // set via ldflags -X main.revision=...
func main() {
if os.Getenv("GO_FLAGS_COMPLETION") == "" {
fmt.Printf("weblist %s\n", versionInfo())
}
p := flags.NewParser(&opts, flags.PrintErrors|flags.PassDoubleDash|flags.HelpFlag)
if _, err := p.Parse(); err != nil {
if !errors.Is(err.(*flags.Error).Type, flags.ErrHelp) {
fmt.Printf("%v", err)
}
os.Exit(1)
}
setupLog(opts.Dbg)
if opts.Version {
fmt.Printf("version: %s\n", versionInfo())
os.Exit(0)
}
// validate theme
if opts.Theme != "light" && opts.Theme != "dark" {
log.Printf("WARN: invalid theme '%s'. Using 'light' instead.", opts.Theme)
opts.Theme = "light"
}
defer func() {
if x := recover(); x != nil {
log.Printf("[WARN] run time panic:\n%v", x)
panic(x)
}
}()
ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt)
defer cancel()
if err := runServer(ctx, &opts); err != nil {
log.Printf("[FATAL] run server error: %v", err)
}
}
func runServer(ctx context.Context, opts *options) error {
// get the absolute path for root directory
absRootDir, err := filepath.Abs(opts.RootDir)
if err != nil {
return fmt.Errorf("failed to get absolute path for root directory: %w", err)
}
opts.RootDir = absRootDir
// ensure temp directory exists for multipart uploads in minimal containers (e.g., scratch).
// tries the system temp dir first, then .tmp under root dir.
if opts.Upload.Enabled {
ensureTempDir(opts.RootDir, &opts.Exclude)
}
// create OS filesystem locked to the root directory
fs := os.DirFS(opts.RootDir)
// prepare common configuration
config := server.Config{
ListenAddr: opts.Listen,
Theme: opts.Theme,
HideFooter: opts.HideFooter,
RootDir: opts.RootDir,
EnableSyntaxHighlighting: opts.EnableSyntaxHighlighting,
Version: versionInfo(),
Exclude: opts.Exclude,
Auth: opts.Auth,
AuthUser: opts.AuthUser,
SessionSecret: opts.SessionSecret,
Title: opts.Title,
CustomFooter: opts.CustomFooter,
SFTPUser: opts.SFTP.User,
SFTPAddress: opts.SFTP.Address,
SFTPKeyFile: opts.SFTP.KeyFile,
SFTPAuthorized: opts.SFTP.Authorized,
BrandName: opts.Branding.Name,
BrandColor: opts.Branding.Color,
InsecureCookies: opts.InsecureCookies,
SessionTTL: opts.SessionTTL,
EnableMultiSelect: opts.EnableMultiSelect,
RecursiveMtime: opts.RecursiveMtime,
EnableUpload: opts.Upload.Enabled,
UploadMaxSize: opts.Upload.MaxSize * 1024 * 1024, // convert MB to bytes
UploadOverwrite: opts.Upload.Overwrite,
}
// create HTTP server
srv := &server.Web{
Config: config,
FS: fs,
}
// create error channel for goroutines
errCh := make(chan error, 2)
// start HTTP server in a goroutine
go func() {
if err := srv.Run(ctx); err != nil {
errCh <- fmt.Errorf("HTTP server failed: %w", err)
}
}()
// if SFTP is enabled, start SFTP server
if opts.SFTP.Enabled && opts.SFTP.User != "" {
// for SFTP, either a password or an authorized_keys file must be provided
if opts.Auth == "" && opts.SFTP.Authorized == "" {
return fmt.Errorf("either password (-a/--auth) or authorized keys file (--sftp-authorized) is required for SFTP server")
}
sftpSrv := &server.SFTP{
Config: config,
FS: fs,
}
go func() {
if opts.SFTP.Authorized != "" {
log.Printf("[INFO] starting SFTP server on %s with username %s (public key authentication enabled)", opts.SFTP.Address, opts.SFTP.User)
} else {
log.Printf("[INFO] starting SFTP server on %s with username %s (password authentication enabled)", opts.SFTP.Address, opts.SFTP.User)
}
if err := sftpSrv.Run(ctx); err != nil {
errCh <- fmt.Errorf("SFTP server failed: %w", err)
}
}()
}
// wait for any error or context cancellation
select {
case err := <-errCh:
return err
case <-ctx.Done():
return nil
}
}
// ensureTempDir makes sure a writable temp directory exists for multipart uploads.
// in minimal containers (scratch/distroless), /tmp may not exist and the filesystem root
// may be read-only. this function tries the system temp dir and then .tmp under rootDir.
// when a fallback under rootDir is used, it is added to the exclude list to hide it from listings.
func ensureTempDir(rootDir string, exclude *[]string) {
defaultTmp := os.TempDir()
rootTmp := filepath.Join(rootDir, ".tmp")
candidates := []string{defaultTmp, rootTmp}
for _, dir := range candidates {
if dir == "" {
continue
}
if err := os.MkdirAll(dir, 0o700); err != nil {
continue
}
// verify the directory is actually writable; MkdirAll returns nil for existing read-only dirs.
// use CreateTemp to avoid predictable filenames and symlink attacks in shared dirs
probe, err := os.CreateTemp(dir, ".weblist-probe-*")
if err != nil {
continue
}
probe.Close() //nolint:gosec // closing probe file before removal
os.Remove(probe.Name()) //nolint:gosec // best-effort cleanup of zero-byte probe file
if dir != defaultTmp {
if err := os.Setenv("TMPDIR", dir); err != nil {
log.Printf("[WARN] failed to set TMPDIR to %s: %v", dir, err)
continue
}
log.Printf("[DEBUG] using %s as temp directory", dir)
}
// if we're using a fallback temp dir under rootDir (not the system default),
// exclude it from directory listings to hide upload temp files
if dir == rootTmp {
*exclude = append(*exclude, ".tmp")
}
return
}
log.Printf("[WARN] failed to create temp directory, large uploads may fail")
}
// versionInfo returns the version string. it uses the revision set via ldflags
// at build time and falls back to Go's build info for local builds.
func versionInfo() string {
if revision != "unknown" {
return revision
}
if info, ok := debug.ReadBuildInfo(); ok {
version := info.Main.Version
if version == "" {
version = "dev"
}
return version
}
return "unknown"
}
func setupLog(dbg bool, secrets ...string) {
logOpts := []lgr.Option{lgr.Msec, lgr.LevelBraces, lgr.StackTraceOnError}
if dbg {
logOpts = []lgr.Option{lgr.Debug, lgr.CallerFile, lgr.CallerFunc, lgr.Msec, lgr.LevelBraces, lgr.StackTraceOnError}
}
colorizer := lgr.Mapper{
ErrorFunc: func(s string) string { return color.New(color.FgHiRed).Sprint(s) },
WarnFunc: func(s string) string { return color.New(color.FgRed).Sprint(s) },
InfoFunc: func(s string) string { return color.New(color.FgYellow).Sprint(s) },
DebugFunc: func(s string) string { return color.New(color.FgWhite).Sprint(s) },
CallerFunc: func(s string) string { return color.New(color.FgBlue).Sprint(s) },
TimeFunc: func(s string) string { return color.New(color.FgCyan).Sprint(s) },
}
logOpts = append(logOpts, lgr.Map(colorizer))
if len(secrets) > 0 {
logOpts = append(logOpts, lgr.Secret(secrets...))
}
lgr.SetupStdLogger(logOpts...)
lgr.Setup(logOpts...)
}