package controller import ( "encoding/json" "fmt" "github.com/gin-gonic/gin" "hy2xs-admin/model/constant" "hy2xs-admin/model/dto" "hy2xs-admin/model/vo" "hy2xs-admin/service" "hy2xs-admin/util" "time" ) func LogSystem(c *gin.Context) { logSystemDto, err := validateField(c, dto.LogDto{}) if err != nil { return } exists := util.Exists(constant.SystemLogPath) logSystemVos := make([]vo.LogSystemVo, 0) if !exists { vo.Success(logSystemVos, c) return } numLine := 0 if logSystemDto.NumLine != nil && *logSystemDto.NumLine > 0 { numLine = *logSystemDto.NumLine } logLines, total, err := util.ReadLinesFromBottom(constant.SystemLogPath, numLine) if err != nil { vo.Fail("Unable to read log file", c) return } for _, line := range logLines { if line == "" { continue } logSystemVo := vo.LogSystemVo{} err := json.Unmarshal([]byte(line), &logSystemVo) if err != nil { vo.Fail("Unable to unmarshal log data", c) continue } // Собственный журнал санитизируется так же, как чужой. // // Раньше через SanitizeLogText проходил только журнал Hysteria: он // «чужой», а свой мы якобы контролируем. Контроль этот держался на // внимательности — ровно до logrus.Warnf с паролем администратора в // dao/sqlite.go. Санитайз здесь стоит не вместо аккуратности в местах // записи, а на случай следующего такого места. logSystemVo.Msg = service.SanitizeLogText(logSystemVo.Msg) logSystemVos = append(logSystemVos, logSystemVo) } vo.Success(vo.LogSystemPage[vo.LogSystemVo]{ LogSystemVos: logSystemVos, Total: int64(total), }, c) } func LogHysteria2(c *gin.Context) { logSystemDto, err := validateField(c, dto.LogDto{}) if err != nil { return } logHysteria2Vos := make([]vo.LogHysteria2Vo, 0) numLine := 0 if logSystemDto.NumLine != nil && *logSystemDto.NumLine > 0 { numLine = *logSystemDto.NumLine } logHysteria2Vos, total, err := service.ReadHysteriaJournalLogs(numLine) if err != nil { vo.Fail("Unable to read hysteria journal logs", c) return } vo.Success(vo.LogSystemPage[vo.LogHysteria2Vo]{ LogSystemVos: logHysteria2Vos, Total: int64(total), }, c) } func ExportLog(c *gin.Context) { logExportDto, err := validateField(c, dto.LogExportDto{}) if err != nil { return } var fileName string if *logExportDto.Option == 0 { fileName = fmt.Sprintf("hy2xs-admin-%s.log", time.Now().Format("20060102150405")) // Журнал админки отдаётся санитизированным, а не файлом «как есть». // // Раньше здесь стоял c.File(constant.SystemLogPath): оператор скачивал // сырой /var/log/hy2xs/hy2xs-admin.log. Журнал Hysteria при этом // проходил через SanitizeLogText — то есть чужому журналу продукт не // доверял, а своему доверял. Асимметрия ничем не обоснована: файл в // обоих случаях покидает сервер и пересылается в переписке. output, exportErr := service.ExportAdminLog() if exportErr != nil { vo.Fail("log file not exist", c) return } c.Header("Content-Type", "text/plain; charset=utf-8") c.Header("Content-Transfer-Encoding", "binary") c.Header("Content-Disposition", fmt.Sprintf("attachment; filename=%s", fileName)) c.Data(200, "text/plain; charset=utf-8", []byte(output)) return } else if *logExportDto.Option == 1 { fileName = fmt.Sprintf("hysteria2-%s.log", time.Now().Format("20060102150405")) output, exportErr := service.ExportHysteriaJournalLogs(5000) if exportErr != nil { vo.Fail("failed to export hysteria journal logs", c) return } c.Header("Content-Type", "text/plain; charset=utf-8") c.Header("Content-Transfer-Encoding", "binary") c.Header("Content-Disposition", fmt.Sprintf("attachment; filename=%s", fileName)) c.Data(200, "text/plain; charset=utf-8", []byte(output)) return } // Обе ветки выше завершаются return. Сюда попадает только неизвестное // значение option, и это отказ, а не отдача пустого файла: раньше здесь // оставался путь с пустым filePath, который сводился к тому же сообщению // окольной дорогой. vo.Fail("unsupported log export option", c) }