fix(chat): use traversal-resistant file api
This commit is contained in:
parent
164795e39a
commit
e50ce446a3
2 changed files with 40 additions and 24 deletions
|
|
@ -79,26 +79,36 @@ func getCachedProfileImage(avatarHash discord.Hash, url string) (string, error)
|
|||
return "", err
|
||||
}
|
||||
|
||||
path = filepath.Join(path, avatarHash+".png")
|
||||
if _, err := os.Stat(path); err == nil {
|
||||
return path, nil
|
||||
}
|
||||
|
||||
file, err := os.Create(path)
|
||||
root, err := os.OpenRoot(path)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to open avatars dir: %w", err)
|
||||
}
|
||||
defer root.Close()
|
||||
|
||||
filename := avatarHash + ".png"
|
||||
_, err = root.Stat(filename)
|
||||
switch {
|
||||
case err == nil:
|
||||
return filepath.Join(path, filename), nil
|
||||
case os.IsNotExist(err):
|
||||
file, err := root.Create(filename)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
resp, err := http.Get(url)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if _, err := io.Copy(file, resp.Body); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return file.Name(), nil
|
||||
default:
|
||||
return "", err
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
resp, err := http.Get(url)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if _, err := io.Copy(file, resp.Body); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return path, nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1202,10 +1202,16 @@ func (ml *messagesList) openAttachment(attachment discord.Attachment) {
|
|||
return
|
||||
}
|
||||
|
||||
path = filepath.Join(path, attachment.Filename)
|
||||
file, err := os.Create(path)
|
||||
root, err := os.OpenRoot(path)
|
||||
if err != nil {
|
||||
slog.Error("failed to create attachment file", "err", err, "path", path)
|
||||
slog.Error("failed to open attachments dir", "err", err, "path", path)
|
||||
return
|
||||
}
|
||||
defer root.Close()
|
||||
|
||||
file, err := root.Create(attachment.Filename)
|
||||
if err != nil {
|
||||
slog.Error("failed to create attachment file", "err", err, "filename", attachment.Filename)
|
||||
return
|
||||
}
|
||||
defer file.Close()
|
||||
|
|
@ -1215,8 +1221,8 @@ func (ml *messagesList) openAttachment(attachment discord.Attachment) {
|
|||
return
|
||||
}
|
||||
|
||||
if err := open.Start(path); err != nil {
|
||||
slog.Error("failed to open attachment file", "err", err, "path", path)
|
||||
if err := open.Start(file.Name()); err != nil {
|
||||
slog.Error("failed to open attachment file", "err", err, "path", file.Name())
|
||||
return
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue