Fix geoip download bug

This is how sing-box tries to handle downloading geoip.db file 

Senari 1
if the geoip.db file path exists then it tries to open the file and parse it. if file is empty or has invalid content it return error invalid MaxMind DB otherwise it parse the file successfully

Senari 2
if the geoip.db file path does not exist first it creates the geoip.db file but with empty content and then it tries to download the geoip.db file.if file downloaded successfully it copy the response to the to the geoip.db file but if download gets an error it return error and the geoip.db file remains with empty content and zero size so in the next run we have Senari 1 because the file path exists but we get an error because the file is empty.

Solution
so i change the order of create file to fix that problem
the file created only after the file  successfully downloaded.

Signed-off-by: johnthecoderpro <149151524+johnthecoderpro@users.noreply.github.com>
This commit is contained in:
johnthecoderpro 2023-10-30 21:12:35 +03:30 committed by 世界
parent 171e42887b
commit 0cfb14a18b
No known key found for this signature in database
GPG Key ID: CD109927C34A63C4

View File

@ -157,12 +157,6 @@ func (r *Router) downloadGeoIPDatabase(savePath string) error {
filemanager.MkdirAll(r.ctx, parentDir, 0o755)
}
saveFile, err := filemanager.Create(r.ctx, savePath)
if err != nil {
return E.Cause(err, "open output file: ", downloadURL)
}
defer saveFile.Close()
httpClient := &http.Client{
Transport: &http.Transport{
ForceAttemptHTTP2: true,
@ -182,6 +176,13 @@ func (r *Router) downloadGeoIPDatabase(savePath string) error {
return err
}
defer response.Body.Close()
saveFile, err := filemanager.Create(r.ctx, savePath)
if err != nil {
return E.Cause(err, "open output file: ", downloadURL)
}
defer saveFile.Close()
_, err = io.Copy(saveFile, response.Body)
return err
}
@ -209,12 +210,6 @@ func (r *Router) downloadGeositeDatabase(savePath string) error {
filemanager.MkdirAll(r.ctx, parentDir, 0o755)
}
saveFile, err := filemanager.Create(r.ctx, savePath)
if err != nil {
return E.Cause(err, "open output file: ", downloadURL)
}
defer saveFile.Close()
httpClient := &http.Client{
Transport: &http.Transport{
ForceAttemptHTTP2: true,
@ -234,6 +229,13 @@ func (r *Router) downloadGeositeDatabase(savePath string) error {
return err
}
defer response.Body.Close()
saveFile, err := filemanager.Create(r.ctx, savePath)
if err != nil {
return E.Cause(err, "open output file: ", downloadURL)
}
defer saveFile.Close()
_, err = io.Copy(saveFile, response.Body)
return err
}