From 697c5335d7227f6f4d4d3a98f84a9cc836822962 Mon Sep 17 00:00:00 2001 From: maru Date: Mon, 22 Apr 2024 18:06:32 -0400 Subject: [PATCH] Prevent writing empty save files --- api/savedata/update.go | 25 +++++++++++-------------- 1 file changed, 11 insertions(+), 14 deletions(-) diff --git a/api/savedata/update.go b/api/savedata/update.go index a836c28..deb3d1a 100644 --- a/api/savedata/update.go +++ b/api/savedata/update.go @@ -29,6 +29,13 @@ func Update(uuid []byte, slot int, save any) error { var filename string var buf bytes.Buffer + zstdEncoder, err := zstd.NewWriter(&buf) + if err != nil { + return fmt.Errorf("failed to create zstd encoder: %s", err) + } + + defer zstdEncoder.Close() + switch save := save.(type) { case defs.SystemSaveData: // System if save.TrainerId == 0 && save.SecretId == 0 { @@ -46,13 +53,6 @@ func Update(uuid []byte, slot int, save any) error { filename = "system" - zstdEncoder, err := zstd.NewWriter(&buf) - if err != nil { - return fmt.Errorf("failed to create zstd encoder: %s", err) - } - - defer zstdEncoder.Close() - err = gob.NewEncoder(zstdEncoder).Encode(save) if err != nil { return fmt.Errorf("failed to serialize save: %s", err) @@ -69,13 +69,6 @@ func Update(uuid []byte, slot int, save any) error { filename += strconv.Itoa(slot) } - zstdEncoder, err := zstd.NewWriter(&buf) - if err != nil { - return fmt.Errorf("failed to create zstd encoder: %s", err) - } - - defer zstdEncoder.Close() - err = gob.NewEncoder(zstdEncoder).Encode(save) if err != nil { return fmt.Errorf("failed to serialize save: %s", err) @@ -84,6 +77,10 @@ func Update(uuid []byte, slot int, save any) error { return fmt.Errorf("invalid data type") } + if buf.Len() == 0 { + return fmt.Errorf("tried to write empty save file") + } + err = os.WriteFile(fmt.Sprintf("userdata/%x/%s.pzs", uuid, filename), buf.Bytes(), 0644) if err != nil { return fmt.Errorf("failed to write save to disk: %s", err)