tool.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package base
  5. import (
  6. "crypto/hmac"
  7. "crypto/md5"
  8. "crypto/rand"
  9. "crypto/sha1"
  10. "encoding/base64"
  11. "encoding/hex"
  12. "errors"
  13. "fmt"
  14. "hash"
  15. "html/template"
  16. "math"
  17. "regexp"
  18. "strings"
  19. "time"
  20. "github.com/Unknwon/com"
  21. "github.com/Unknwon/i18n"
  22. "github.com/gogits/gogs/modules/avatar"
  23. "github.com/gogits/gogs/modules/setting"
  24. )
  25. // Encode string to md5 hex value.
  26. func EncodeMd5(str string) string {
  27. m := md5.New()
  28. m.Write([]byte(str))
  29. return hex.EncodeToString(m.Sum(nil))
  30. }
  31. // Encode string to sha1 hex value.
  32. func EncodeSha1(str string) string {
  33. h := sha1.New()
  34. h.Write([]byte(str))
  35. return hex.EncodeToString(h.Sum(nil))
  36. }
  37. func BasicAuthDecode(encoded string) (user string, name string, err error) {
  38. var s []byte
  39. s, err = base64.StdEncoding.DecodeString(encoded)
  40. if err != nil {
  41. return user, name, err
  42. }
  43. a := strings.Split(string(s), ":")
  44. if len(a) == 2 {
  45. user, name = a[0], a[1]
  46. } else {
  47. err = errors.New("decode failed")
  48. }
  49. return user, name, err
  50. }
  51. func BasicAuthEncode(username, password string) string {
  52. return base64.StdEncoding.EncodeToString([]byte(username + ":" + password))
  53. }
  54. // GetRandomString generate random string by specify chars.
  55. func GetRandomString(n int, alphabets ...byte) string {
  56. const alphanum = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
  57. var bytes = make([]byte, n)
  58. rand.Read(bytes)
  59. for i, b := range bytes {
  60. if len(alphabets) == 0 {
  61. bytes[i] = alphanum[b%byte(len(alphanum))]
  62. } else {
  63. bytes[i] = alphabets[b%byte(len(alphabets))]
  64. }
  65. }
  66. return string(bytes)
  67. }
  68. // http://code.google.com/p/go/source/browse/pbkdf2/pbkdf2.go?repo=crypto
  69. func PBKDF2(password, salt []byte, iter, keyLen int, h func() hash.Hash) []byte {
  70. prf := hmac.New(h, password)
  71. hashLen := prf.Size()
  72. numBlocks := (keyLen + hashLen - 1) / hashLen
  73. var buf [4]byte
  74. dk := make([]byte, 0, numBlocks*hashLen)
  75. U := make([]byte, hashLen)
  76. for block := 1; block <= numBlocks; block++ {
  77. // N.B.: || means concatenation, ^ means XOR
  78. // for each block T_i = U_1 ^ U_2 ^ ... ^ U_iter
  79. // U_1 = PRF(password, salt || uint(i))
  80. prf.Reset()
  81. prf.Write(salt)
  82. buf[0] = byte(block >> 24)
  83. buf[1] = byte(block >> 16)
  84. buf[2] = byte(block >> 8)
  85. buf[3] = byte(block)
  86. prf.Write(buf[:4])
  87. dk = prf.Sum(dk)
  88. T := dk[len(dk)-hashLen:]
  89. copy(U, T)
  90. // U_n = PRF(password, U_(n-1))
  91. for n := 2; n <= iter; n++ {
  92. prf.Reset()
  93. prf.Write(U)
  94. U = U[:0]
  95. U = prf.Sum(U)
  96. for x := range U {
  97. T[x] ^= U[x]
  98. }
  99. }
  100. }
  101. return dk[:keyLen]
  102. }
  103. // verify time limit code
  104. func VerifyTimeLimitCode(data string, minutes int, code string) bool {
  105. if len(code) <= 18 {
  106. return false
  107. }
  108. // split code
  109. start := code[:12]
  110. lives := code[12:18]
  111. if d, err := com.StrTo(lives).Int(); err == nil {
  112. minutes = d
  113. }
  114. // right active code
  115. retCode := CreateTimeLimitCode(data, minutes, start)
  116. if retCode == code && minutes > 0 {
  117. // check time is expired or not
  118. before, _ := DateParse(start, "YmdHi")
  119. now := time.Now()
  120. if before.Add(time.Minute*time.Duration(minutes)).Unix() > now.Unix() {
  121. return true
  122. }
  123. }
  124. return false
  125. }
  126. const TimeLimitCodeLength = 12 + 6 + 40
  127. // create a time limit code
  128. // code format: 12 length date time string + 6 minutes string + 40 sha1 encoded string
  129. func CreateTimeLimitCode(data string, minutes int, startInf interface{}) string {
  130. format := "YmdHi"
  131. var start, end time.Time
  132. var startStr, endStr string
  133. if startInf == nil {
  134. // Use now time create code
  135. start = time.Now()
  136. startStr = DateFormat(start, format)
  137. } else {
  138. // use start string create code
  139. startStr = startInf.(string)
  140. start, _ = DateParse(startStr, format)
  141. startStr = DateFormat(start, format)
  142. }
  143. end = start.Add(time.Minute * time.Duration(minutes))
  144. endStr = DateFormat(end, format)
  145. // create sha1 encode string
  146. sh := sha1.New()
  147. sh.Write([]byte(data + setting.SecretKey + startStr + endStr + com.ToStr(minutes)))
  148. encoded := hex.EncodeToString(sh.Sum(nil))
  149. code := fmt.Sprintf("%s%06d%s", startStr, minutes, encoded)
  150. return code
  151. }
  152. // AvatarLink returns avatar link by given e-mail.
  153. func AvatarLink(email string) string {
  154. if setting.DisableGravatar {
  155. return setting.AppSubUrl + "/img/avatar_default.jpg"
  156. }
  157. gravatarHash := avatar.HashEmail(email)
  158. if setting.Service.EnableCacheAvatar {
  159. return setting.AppSubUrl + "/avatar/" + gravatarHash
  160. }
  161. return setting.GravatarSource + gravatarHash
  162. }
  163. // Seconds-based time units
  164. const (
  165. Minute = 60
  166. Hour = 60 * Minute
  167. Day = 24 * Hour
  168. Week = 7 * Day
  169. Month = 30 * Day
  170. Year = 12 * Month
  171. )
  172. func computeTimeDiff(diff int64) (int64, string) {
  173. diffStr := ""
  174. switch {
  175. case diff <= 0:
  176. diff = 0
  177. diffStr = "now"
  178. case diff < 2:
  179. diff = 0
  180. diffStr = "1 second"
  181. case diff < 1*Minute:
  182. diffStr = fmt.Sprintf("%d seconds", diff)
  183. diff = 0
  184. case diff < 2*Minute:
  185. diff -= 1 * Minute
  186. diffStr = "1 minute"
  187. case diff < 1*Hour:
  188. diffStr = fmt.Sprintf("%d minutes", diff/Minute)
  189. diff -= diff / Minute * Minute
  190. case diff < 2*Hour:
  191. diff -= 1 * Hour
  192. diffStr = "1 hour"
  193. case diff < 1*Day:
  194. diffStr = fmt.Sprintf("%d hours", diff/Hour)
  195. diff -= diff / Hour * Hour
  196. case diff < 2*Day:
  197. diff -= 1 * Day
  198. diffStr = "1 day"
  199. case diff < 1*Week:
  200. diffStr = fmt.Sprintf("%d days", diff/Day)
  201. diff -= diff / Day * Day
  202. case diff < 2*Week:
  203. diff -= 1 * Week
  204. diffStr = "1 week"
  205. case diff < 1*Month:
  206. diffStr = fmt.Sprintf("%d weeks", diff/Week)
  207. diff -= diff / Week * Week
  208. case diff < 2*Month:
  209. diff -= 1 * Month
  210. diffStr = "1 month"
  211. case diff < 1*Year:
  212. diffStr = fmt.Sprintf("%d months", diff/Month)
  213. diff -= diff / Month * Month
  214. case diff < 2*Year:
  215. diff -= 1 * Year
  216. diffStr = "1 year"
  217. default:
  218. diffStr = fmt.Sprintf("%d years", diff/Year)
  219. diff = 0
  220. }
  221. return diff, diffStr
  222. }
  223. // TimeSincePro calculates the time interval and generate full user-friendly string.
  224. func TimeSincePro(then time.Time) string {
  225. now := time.Now()
  226. diff := now.Unix() - then.Unix()
  227. if then.After(now) {
  228. return "future"
  229. }
  230. var timeStr, diffStr string
  231. for {
  232. if diff == 0 {
  233. break
  234. }
  235. diff, diffStr = computeTimeDiff(diff)
  236. timeStr += ", " + diffStr
  237. }
  238. return strings.TrimPrefix(timeStr, ", ")
  239. }
  240. func timeSince(then time.Time, lang string) string {
  241. now := time.Now()
  242. lbl := i18n.Tr(lang, "tool.ago")
  243. diff := now.Unix() - then.Unix()
  244. if then.After(now) {
  245. lbl = i18n.Tr(lang, "tool.from_now")
  246. diff = then.Unix() - now.Unix()
  247. }
  248. switch {
  249. case diff <= 0:
  250. return i18n.Tr(lang, "tool.now")
  251. case diff <= 2:
  252. return i18n.Tr(lang, "tool.1s", lbl)
  253. case diff < 1*Minute:
  254. return i18n.Tr(lang, "tool.seconds", diff, lbl)
  255. case diff < 2*Minute:
  256. return i18n.Tr(lang, "tool.1m", lbl)
  257. case diff < 1*Hour:
  258. return i18n.Tr(lang, "tool.minutes", diff/Minute, lbl)
  259. case diff < 2*Hour:
  260. return i18n.Tr(lang, "tool.1h", lbl)
  261. case diff < 1*Day:
  262. return i18n.Tr(lang, "tool.hours", diff/Hour, lbl)
  263. case diff < 2*Day:
  264. return i18n.Tr(lang, "tool.1d", lbl)
  265. case diff < 1*Week:
  266. return i18n.Tr(lang, "tool.days", diff/Day, lbl)
  267. case diff < 2*Week:
  268. return i18n.Tr(lang, "tool.1w", lbl)
  269. case diff < 1*Month:
  270. return i18n.Tr(lang, "tool.weeks", diff/Week, lbl)
  271. case diff < 2*Month:
  272. return i18n.Tr(lang, "tool.1mon", lbl)
  273. case diff < 1*Year:
  274. return i18n.Tr(lang, "tool.months", diff/Month, lbl)
  275. case diff < 2*Year:
  276. return i18n.Tr(lang, "tool.1y", lbl)
  277. default:
  278. return i18n.Tr(lang, "tool.years", diff/Year, lbl)
  279. }
  280. }
  281. // TimeSince calculates the time interval and generate user-friendly string.
  282. func TimeSince(t time.Time, lang string) template.HTML {
  283. return template.HTML(fmt.Sprintf(`<span class="time-since" title="%s">%s</span>`, t.Format(setting.TimeFormat), timeSince(t, lang)))
  284. }
  285. const (
  286. Byte = 1
  287. KByte = Byte * 1024
  288. MByte = KByte * 1024
  289. GByte = MByte * 1024
  290. TByte = GByte * 1024
  291. PByte = TByte * 1024
  292. EByte = PByte * 1024
  293. )
  294. var bytesSizeTable = map[string]uint64{
  295. "b": Byte,
  296. "kb": KByte,
  297. "mb": MByte,
  298. "gb": GByte,
  299. "tb": TByte,
  300. "pb": PByte,
  301. "eb": EByte,
  302. }
  303. func logn(n, b float64) float64 {
  304. return math.Log(n) / math.Log(b)
  305. }
  306. func humanateBytes(s uint64, base float64, sizes []string) string {
  307. if s < 10 {
  308. return fmt.Sprintf("%dB", s)
  309. }
  310. e := math.Floor(logn(float64(s), base))
  311. suffix := sizes[int(e)]
  312. val := float64(s) / math.Pow(base, math.Floor(e))
  313. f := "%.0f"
  314. if val < 10 {
  315. f = "%.1f"
  316. }
  317. return fmt.Sprintf(f+"%s", val, suffix)
  318. }
  319. // FileSize calculates the file size and generate user-friendly string.
  320. func FileSize(s int64) string {
  321. sizes := []string{"B", "KB", "MB", "GB", "TB", "PB", "EB"}
  322. return humanateBytes(uint64(s), 1024, sizes)
  323. }
  324. // Subtract deals with subtraction of all types of number.
  325. func Subtract(left interface{}, right interface{}) interface{} {
  326. var rleft, rright int64
  327. var fleft, fright float64
  328. var isInt bool = true
  329. switch left.(type) {
  330. case int:
  331. rleft = int64(left.(int))
  332. case int8:
  333. rleft = int64(left.(int8))
  334. case int16:
  335. rleft = int64(left.(int16))
  336. case int32:
  337. rleft = int64(left.(int32))
  338. case int64:
  339. rleft = left.(int64)
  340. case float32:
  341. fleft = float64(left.(float32))
  342. isInt = false
  343. case float64:
  344. fleft = left.(float64)
  345. isInt = false
  346. }
  347. switch right.(type) {
  348. case int:
  349. rright = int64(right.(int))
  350. case int8:
  351. rright = int64(right.(int8))
  352. case int16:
  353. rright = int64(right.(int16))
  354. case int32:
  355. rright = int64(right.(int32))
  356. case int64:
  357. rright = right.(int64)
  358. case float32:
  359. fright = float64(left.(float32))
  360. isInt = false
  361. case float64:
  362. fleft = left.(float64)
  363. isInt = false
  364. }
  365. if isInt {
  366. return rleft - rright
  367. } else {
  368. return fleft + float64(rleft) - (fright + float64(rright))
  369. }
  370. }
  371. // DateFormat pattern rules.
  372. var datePatterns = []string{
  373. // year
  374. "Y", "2006", // A full numeric representation of a year, 4 digits Examples: 1999 or 2003
  375. "y", "06", //A two digit representation of a year Examples: 99 or 03
  376. // month
  377. "m", "01", // Numeric representation of a month, with leading zeros 01 through 12
  378. "n", "1", // Numeric representation of a month, without leading zeros 1 through 12
  379. "M", "Jan", // A short textual representation of a month, three letters Jan through Dec
  380. "F", "January", // A full textual representation of a month, such as January or March January through December
  381. // day
  382. "d", "02", // Day of the month, 2 digits with leading zeros 01 to 31
  383. "j", "2", // Day of the month without leading zeros 1 to 31
  384. // week
  385. "D", "Mon", // A textual representation of a day, three letters Mon through Sun
  386. "l", "Monday", // A full textual representation of the day of the week Sunday through Saturday
  387. // time
  388. "g", "3", // 12-hour format of an hour without leading zeros 1 through 12
  389. "G", "15", // 24-hour format of an hour without leading zeros 0 through 23
  390. "h", "03", // 12-hour format of an hour with leading zeros 01 through 12
  391. "H", "15", // 24-hour format of an hour with leading zeros 00 through 23
  392. "a", "pm", // Lowercase Ante meridiem and Post meridiem am or pm
  393. "A", "PM", // Uppercase Ante meridiem and Post meridiem AM or PM
  394. "i", "04", // Minutes with leading zeros 00 to 59
  395. "s", "05", // Seconds, with leading zeros 00 through 59
  396. // time zone
  397. "T", "MST",
  398. "P", "-07:00",
  399. "O", "-0700",
  400. // RFC 2822
  401. "r", time.RFC1123Z,
  402. }
  403. // Parse Date use PHP time format.
  404. func DateParse(dateString, format string) (time.Time, error) {
  405. replacer := strings.NewReplacer(datePatterns...)
  406. format = replacer.Replace(format)
  407. return time.ParseInLocation(format, dateString, time.Local)
  408. }
  409. // Date takes a PHP like date func to Go's time format.
  410. func DateFormat(t time.Time, format string) string {
  411. replacer := strings.NewReplacer(datePatterns...)
  412. format = replacer.Replace(format)
  413. return t.Format(format)
  414. }
  415. type xssFilter struct {
  416. reg *regexp.Regexp
  417. repl []byte
  418. }
  419. var (
  420. whiteSpace = []byte(" ")
  421. xssFilters = []xssFilter{
  422. {regexp.MustCompile(`\ [ONon]\w*=["]*`), whiteSpace},
  423. {regexp.MustCompile(`<[SCRIPTscript]{6}`), whiteSpace},
  424. {regexp.MustCompile(`=[` + "`" + `'"]*[JAVASCRIPTjavascript \t\0&#x0D;]*:`), whiteSpace},
  425. }
  426. )
  427. // XSS goes through all the XSS filters to make user input content as safe as possible.
  428. func XSS(in []byte) []byte {
  429. for _, filter := range xssFilters {
  430. in = filter.reg.ReplaceAll(in, filter.repl)
  431. }
  432. return in
  433. }
  434. func XSSString(in string) string {
  435. return string(XSS([]byte(in)))
  436. }