main.go 13 KB

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