main.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  1. package main
  2. /*
  3. * 本检测工具基于SCD文档管理系统第二版本开发
  4. * 本版本中引入了crc校验及ccd提取外部程序,该程序由C++编写,在部署时需要根据目标机器进行源码编译。其源程序在scdcrc目录下,编译时可参考目录的编译说明。
  5. * 本版本中引入了java开发的xml校验(根据xsd校验)外部程序,该程序由java编写,在部署时需要在目标机器上安装jdk1.8。务必(!!!)并将操作系统安装或者设置为中文语言,设置命令如下:
  6. * 1:全局配置修改。vi /etc/sysconfig/i18n 输入LANG="zh_CN.UTF-8"或者LANG="en_US.UTF-8",执行source /etc/sysconfig/i18n,重启电脑生效
  7. * 2:临时修改。export LANG="zh_CN.UTF-8" 或者 export LANG="en_US.UTF-8"
  8. * 3: 查看liunx系统当前语言。命令: echo $LANG
  9. */
  10. // ***************** 重新生成api接口文档,终端运行生成命令:bee run -gendoc=true -downdoc=true ***************
  11. // ***************** 如果生成swagger文档时失败,可运行:bee generate docs生成,可查看详情生成过程 ***************
  12. // ***************** 其他异常问题可尝试执行:swag init ***************
  13. // @title SCD检测工具API
  14. // @version 1.0.0
  15. // @description SCD文档管理系统接口文档。本文档仅用于本项目的前端接口说明
  16. // @termsOfService http://swagger.io/terms/
  17. // @contact.name liling
  18. // @contact.url http://www.swagger.io/support
  19. // @contact.email 3116246@qq.com
  20. // @license.name none
  21. // @license.url -
  22. // @host localhost:9527
  23. // @BasePath /api
  24. // @securityDefinitions.token token AUTH
  25. import (
  26. "bytes"
  27. "crypto/md5"
  28. "encoding/binary"
  29. "encoding/hex"
  30. "flag"
  31. "fmt"
  32. "io"
  33. "io/fs"
  34. "net"
  35. "net/http"
  36. "net/url"
  37. "os"
  38. "os/exec"
  39. "path/filepath"
  40. "scd_check_tools/arrayex"
  41. "scd_check_tools/conf"
  42. _ "scd_check_tools/conf"
  43. "scd_check_tools/db"
  44. "scd_check_tools/email"
  45. "scd_check_tools/global"
  46. "scd_check_tools/logger"
  47. "scd_check_tools/models/bo"
  48. "scd_check_tools/models/enum"
  49. "scd_check_tools/monitor"
  50. "scd_check_tools/sms"
  51. "scd_check_tools/test"
  52. "scd_check_tools/upgrade"
  53. "syscall"
  54. //"regexp"
  55. "runtime"
  56. "scd_check_tools/mqtt"
  57. "scd_check_tools/tools"
  58. "sort"
  59. "strconv"
  60. "strings"
  61. "time"
  62. "github.com/astaxie/beego"
  63. //"github.com/astaxie/beego/logs"
  64. "github.com/astaxie/beego/context"
  65. _ "scd_check_tools/routers"
  66. //"github.com/shopspring/decimal"
  67. _ "scd_check_tools/docs"
  68. _ "scd_check_tools/models/enum"
  69. "github.com/pkg/browser"
  70. )
  71. var (
  72. cpunum = runtime.NumCPU() - 1
  73. )
  74. var (
  75. openBrowser = flag.Bool("open", true, "Open browser automatically")
  76. )
  77. func main() {
  78. runtime.GOMAXPROCS(cpunum)
  79. flag.Parse()
  80. logger.Logger.Init()
  81. logger.Logger.Println(tools.NowTime() + " 当前操作系统:" + string(runtime.GOOS) + " " + runtime.GOARCH)
  82. conf.LoadAppConf()
  83. dbtype := tools.IsEmpty(conf.GlobalConfig["dbtype"])
  84. runmode := tools.IsEmpty(conf.GlobalConfig["runmode"])
  85. if runmode == "" {
  86. runmode = "dev"
  87. }
  88. if dbtype == "" || dbtype == "mysql" {
  89. db.ConnDB("conf/mysql-" + runmode + ".cnf")
  90. } else if dbtype == "sqlite" {
  91. db.ConnSqlite("conf/db.cnf")
  92. }
  93. //new(test.UnitTest).TestIntAddrParse("RPIT/GOINGGIO1.SPCSO1.stVal")
  94. //new(test.UnitTest).TestDoiNameRex("(断路器)&(跳|合|闸){1,}&(位置)", "断路器跳闸位置")
  95. //new(test.UnitTest).TestDoiNameRex("(测量|计量)&(电流.*C)|(C.*电流)|(IC1)", "测量电流C相")
  96. go mqtt.Start()
  97. if runmode == "dev" {
  98. //自动生成接口权限定义
  99. new(ApiDoc).Run()
  100. }
  101. new(ApiDoc).CacheApiDoc()
  102. bo.LoadSysParam()
  103. //缓存系统代码定义
  104. bo.LoadAndCacheGlobalCode()
  105. monitor.StartDataMonitor()
  106. monitor.StartSystem()
  107. new(bo.TaskMgr).ChangeErr2Normal()
  108. //初始化短信对象
  109. smspf := conf.GlobalConfig["sms.platform"]
  110. if smspf != "" {
  111. smsSend := sms.GetSmsInstance(smspf)
  112. smsSend.AppId = conf.GlobalConfig["sms."+smspf+".appid"]
  113. smsSend.AppKey = conf.GlobalConfig["sms."+smspf+".appkey"]
  114. smsSend.SignName = conf.GlobalConfig["sms.signname"]
  115. }
  116. //启动邮件发送对象
  117. email.EmailConfig.Load()
  118. //发送邮件调用参考:
  119. //err := new(email.Send).SendEmail("3116246@qq.com", "测试", "这是邮件发送测试")
  120. logger.Logger.Println("****** 当前程序运行版本:" + upgrade.GetVersion() + " 运行端口:" + conf.GlobalConfig["appport"] + " 运行环境:" + runmode + " ******")
  121. logger.Logger.Println("如果需要重新生成api接口文档,终端运行生成命令:bee run -gendoc=true -downdoc=true")
  122. go test.Start("")
  123. go func() {
  124. //将生成的swagger文件复制到web目录下
  125. dirchar := string(os.PathSeparator)
  126. swaggerdir, err := os.Stat("." + dirchar + "swagger")
  127. if os.IsNotExist(err) {
  128. //项目中没有启用swagger时,不处理
  129. return
  130. }
  131. if swaggerdir.IsDir() {
  132. filepath.Walk("."+dirchar+"swagger", func(pathitem string, info fs.FileInfo, err error) error {
  133. if info.IsDir() {
  134. return nil
  135. }
  136. src, _ := os.Open(pathitem)
  137. defer src.Close()
  138. dst, _ := os.Create("." + dirchar + "static" + dirchar + "swagger" + dirchar + info.Name())
  139. defer dst.Close()
  140. io.Copy(dst, src)
  141. return nil
  142. })
  143. }
  144. }()
  145. if string(runtime.GOOS) == "windows" {
  146. if runmode == "prod" {
  147. go func() {
  148. killcmd := exec.Command("taskkill.exe", "/f", "/im", "Web2Cs.exe")
  149. killcmd.Start()
  150. //先杀掉残留的Web2Cs.exe进程
  151. time.Sleep(1 * time.Second)
  152. //dir, _ := filepath.Abs(filepath.Dir(os.Args[0]))
  153. //cmd := exec.Command("cmd.exe", "/c", "start "+dir+"/static/pc/Web2Cs.exe")
  154. //cmd.Start()
  155. //隐藏CMD窗口
  156. //如果编译的非windows版本,需要注释下面的代码
  157. kernel32 := syscall.NewLazyDLL("kernel32.dll")
  158. user32 := syscall.NewLazyDLL("user32.dll")
  159. getConsoleWindow := kernel32.NewProc("GetConsoleWindow")
  160. hideWin := user32.NewProc("ShowWindowAsync")
  161. winHander, _, err := getConsoleWindow.Call()
  162. if winHander == 0 {
  163. logger.Logger.Error(err)
  164. return
  165. }
  166. code, _, err := hideWin.Call(winHander, 0)
  167. if code != 1 {
  168. logger.Logger.Error(err)
  169. return
  170. }
  171. }()
  172. //检查Web2Cs.exe是否运行中,未运行时退出当前程序
  173. go func() {
  174. /*
  175. for {
  176. time.Sleep(3 * time.Second)
  177. param := []string{"/C", "wmic process list brief| findstr Web2Cs.exe"}
  178. cmd := exec.Command("cmd", param...)
  179. var stdout, stderr bytes.Buffer
  180. cmd.Stdout = &stdout
  181. cmd.Stderr = &stderr
  182. err := cmd.Run()
  183. if err != nil {
  184. logger.Logger.Error(err)
  185. }
  186. resultOut, _ := string(stdout.Bytes()), string(stderr.Bytes())
  187. if strings.ReplaceAll(resultOut, " ", "") == "" {
  188. break
  189. }
  190. }
  191. os.Exit(0)
  192. */
  193. }()
  194. }
  195. }
  196. if conf.GlobalConfig["appport"] != "" {
  197. go bo.CheckSystemUser()
  198. beego.SetLevel(beego.LevelDebug)
  199. //beego.SetLogger(logs.AdapterFile, "{\"filename\": \"beego_log.log\"}")
  200. beego.SetStaticPath("/", "static/index.html")
  201. beego.SetStaticPath("/login", "static/index.html")
  202. //beego.SetStaticPath("/logout", "static/login.html")
  203. beego.InsertFilter("/*", beego.BeforeRouter, AuthFilter)
  204. if *openBrowser {
  205. go func() {
  206. time.Sleep(100 * time.Millisecond)
  207. browser.OpenURL("http://127.0.0.1:" + conf.GlobalConfig["appport"])
  208. }()
  209. }
  210. beego.Run(":" + conf.GlobalConfig["appport"])
  211. }
  212. }
  213. func BytesToInt(bys []byte) int {
  214. bytebuff := bytes.NewBuffer(bys)
  215. var data int64
  216. binary.Read(bytebuff, binary.BigEndian, &data)
  217. return int(data)
  218. }
  219. var staticFile = ".css,.html,.js,.png,.jpg,.gif,.svg,.ico,.ttf,.eot,.woff,.woff2,.map"
  220. var AuthFilter = func(ctx *context.Context) {
  221. //fmt.Println(ctx.Request.URL.Path)
  222. ps := strings.Split(ctx.Request.URL.Path, ".")
  223. if strings.Index(staticFile, "."+ps[len(ps)-1]) > -1 {
  224. http.ServeFile(ctx.ResponseWriter, ctx.Request, "static/"+ctx.Request.URL.Path)
  225. return
  226. }
  227. ip := ctx.Request.Header.Get("X-Real-IP")
  228. if net.ParseIP(ip) == nil {
  229. ips := ctx.Request.Header.Get("X-Forward-For")
  230. for _, i := range strings.Split(ips, ",") {
  231. if net.ParseIP(i) != nil {
  232. ip = i
  233. break
  234. }
  235. }
  236. if ip == "" {
  237. ip, _, _ = net.SplitHostPort(ctx.Request.RemoteAddr)
  238. }
  239. }
  240. if ip != "" {
  241. //当前IP是否需要检查访问授权,默认为需要
  242. isCheckThisIP := true
  243. if _, exist := global.AccessedIps.Load(ip); exist {
  244. //IP已经访问过系统,则无需检查
  245. isCheckThisIP = false
  246. }
  247. if isCheckThisIP && global.AllowAccessIps != "*" {
  248. //判断当前客户端是否在允许范围内
  249. ips := strings.Split(global.AllowAccessIps, ",")
  250. allowLogin := false
  251. for _, iplimt := range ips {
  252. if iplimt == ip {
  253. allowLogin = true
  254. break
  255. }
  256. tmppos := strings.Index(iplimt, ".*")
  257. if tmppos > 1 {
  258. //ip段
  259. if len(ip) < tmppos {
  260. continue
  261. }
  262. if ip[:tmppos] == iplimt[:tmppos] {
  263. allowLogin = true
  264. break
  265. }
  266. }
  267. }
  268. if !allowLogin {
  269. userInfo := map[string]interface{}{}
  270. userInfo["ip"] = ip
  271. userInfo["name"] = "系统内置访问控制"
  272. new(bo.SystemLog).Fail(enum.AuditType_Client, enum.LogType_commit, enum.OptEventType_System, enum.OptEventLevel_Hight, fmt.Sprintf("未授权终端(IP:%s)尝试访问系统被拦截", ip), userInfo)
  273. //c.Data["json"] = c.WarpError("系统限制:未授权的访问!")
  274. //c.ServeJSON()
  275. ctx.Redirect(430, "/static/430.html")
  276. return
  277. }
  278. }
  279. //将IP缓存到允许队列中,如果更改了允许访问的IP配置时,需要重新初始化该队列
  280. global.AccessedIps.Store(ip, 1)
  281. }
  282. u, err := url.Parse(strings.ReplaceAll(ctx.Request.RequestURI, "//", "/"))
  283. if err != nil {
  284. ctx.Redirect(500, "/error")
  285. return
  286. }
  287. uri := strings.ToLower(u.Path)
  288. if uri == "/api/logout" || uri == "/api/version" || uri == "/api/keep-alive" || arrayex.IndexOf(global.NoAuthRouter, uri) > -1 {
  289. return
  290. }
  291. var token string
  292. token = ctx.Request.Header.Get("Authorization")
  293. if token == "" {
  294. logger.Logger.Println("接口" + ctx.Request.RequestURI + "token标识缺失")
  295. ctx.ResponseWriter.WriteHeader(401)
  296. return
  297. }
  298. token = strings.ReplaceAll(strings.ReplaceAll(token, "Bearer ", ""), " ", "")
  299. if token == "" {
  300. logger.Logger.Println("接口" + ctx.Request.RequestURI + "token标识无效")
  301. ctx.ResponseWriter.WriteHeader(401)
  302. return
  303. }
  304. //校验该token有没有当前接口的访问权限
  305. if !bo.HasApiAccess(token, uri) {
  306. logger.Logger.Println("接口" + ctx.Request.RequestURI + "不能被token:" + token + "访问")
  307. ctx.ResponseWriter.WriteHeader(401)
  308. return
  309. }
  310. nonce := ctx.Request.Header.Get("auth_nonce")
  311. //判断是不是特殊的token(后台layui接口不能校验)
  312. if strings.HasPrefix(nonce, "police-s-admin-") && len(nonce) == 26 {
  313. return
  314. }
  315. //验证请求时间戳和随机数,防数据重放
  316. tim := ctx.Request.Header.Get("auth_time")
  317. if tim == "" {
  318. logger.Logger.Println("接口" + ctx.Request.RequestURI + " auth_time标识缺失")
  319. ctx.ResponseWriter.WriteHeader(401)
  320. //ctx.Redirect(301, "/login")
  321. return
  322. }
  323. nowhaomiao := time.Now().Unix()
  324. tim2 := tim[0:10]
  325. timint, er := strconv.Atoi(tim2)
  326. //接口请求有效时长为2秒内
  327. //log.Println(fmt.Sprintf("now:%d tim:%d", nowhaomiao, timint))
  328. if er != nil || (int(nowhaomiao)-timint) > 4 {
  329. logger.Logger.Println("接口" + ctx.Request.RequestURI + "请求超时。" + tim2 + ":" + strconv.Itoa(int(nowhaomiao)))
  330. ctx.ResponseWriter.WriteHeader(401)
  331. //ctx.Redirect(301, "/login")
  332. return
  333. }
  334. if nonce == "" {
  335. logger.Logger.Println("接口" + ctx.Request.RequestURI + " auth_nonce标识缺失")
  336. ctx.ResponseWriter.WriteHeader(401)
  337. //ctx.Redirect(301, "/login")
  338. return
  339. }
  340. kv, has := global.GoCahce.Get(nonce)
  341. if has == true || kv != nil {
  342. logger.Logger.Println("接口" + ctx.Request.RequestURI + " auth_nonce已存在,本次请求可能是接口重放攻击")
  343. ctx.ResponseWriter.WriteHeader(401)
  344. //ctx.Redirect(301, "/login")
  345. return
  346. }
  347. sign := ctx.Request.Header.Get("sign")
  348. if sign == "" {
  349. logger.Logger.Println("接口" + ctx.Request.RequestURI + "签名缺失")
  350. ctx.ResponseWriter.WriteHeader(401)
  351. //ctx.Redirect(301, "/login")
  352. return
  353. }
  354. //获取请求的所有参数,并进行签名对比,防数据篡改
  355. signParalist := map[string]string{"auth_time": tim, "auth_nonce": nonce}
  356. reqPara1 := ctx.Request.URL.Query()
  357. for k, _ := range reqPara1 {
  358. signParalist[(k)] = tools.IsEmpty(reqPara1[k][0])
  359. }
  360. if ctx.Request.MultipartForm == nil || len(ctx.Request.MultipartForm.File) == 0 {
  361. reqPara2 := ctx.Request.PostForm
  362. for k, _ := range reqPara2 {
  363. signParalist[(k)] = tools.IsEmpty(reqPara2[k][0])
  364. }
  365. }
  366. var entiy []string
  367. var keys []string
  368. for key := range signParalist {
  369. keys = append(keys, (key))
  370. }
  371. sort.Stable(sort.StringSlice(keys))
  372. for _, name := range keys {
  373. /*tmpStr := url.QueryEscape(signParalist[name])
  374. tmpStr = strings.ReplaceAll(tmpStr, "%28", "(")
  375. tmpStr = strings.ReplaceAll(tmpStr, "%29", ")")*/
  376. entiy = append(entiy, name+"="+signParalist[name])
  377. }
  378. newParalist := strings.Join(entiy, "&") // + token
  379. h := md5.New()
  380. h.Write([]byte(newParalist))
  381. cipherStr := h.Sum(nil)
  382. signstr := hex.EncodeToString(cipherStr) // 输出加密结果
  383. if sign != signstr {
  384. logger.Logger.Println("接口" + ctx.Request.RequestURI + "签名不一致,请检查参数值中是否有特殊字符。原始签名:" + sign + " 后台签名:" + signstr)
  385. logger.Logger.Println("接口" + ctx.Request.RequestURI + "签名参数:")
  386. logger.Logger.Println(newParalist)
  387. ctx.ResponseWriter.WriteHeader(401)
  388. //ctx.Redirect(401, "/login")
  389. return
  390. }
  391. //请求验证全部通过,更新session
  392. err = bo.UpdateSession(token)
  393. if err != nil {
  394. if uri != "/login" {
  395. logger.Logger.Error("接口" + ctx.Request.RequestURI + " token已过期:" + token)
  396. ctx.ResponseWriter.WriteHeader(401)
  397. //ctx.Redirect(401, "/login")
  398. }
  399. return
  400. }
  401. //3秒过期的随机数
  402. global.GoCahce.Set(nonce, nonce, 3*time.Second)
  403. }