You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

330 lines
7.4 KiB

  1. /*
  2. The MIT License (MIT)
  3. Copyright (c) 2014-2017 DutchCoders [https://github.com/dutchcoders/]
  4. Permission is hereby granted, free of charge, to any person obtaining a copy
  5. of this software and associated documentation files (the "Software"), to deal
  6. in the Software without restriction, including without limitation the rights
  7. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. copies of the Software, and to permit persons to whom the Software is
  9. furnished to do so, subject to the following conditions:
  10. The above copyright notice and this permission notice shall be included in
  11. all copies or substantial portions of the Software.
  12. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  13. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  14. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  15. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  16. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  17. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  18. THE SOFTWARE.
  19. */
  20. package server
  21. import (
  22. "fmt"
  23. "log"
  24. "math"
  25. "net"
  26. "net/http"
  27. "net/mail"
  28. "net/url"
  29. "os"
  30. "path"
  31. "strconv"
  32. "strings"
  33. "github.com/golang/gddo/httputil/header"
  34. )
  35. func cleanTmpFile(f *os.File) {
  36. if f != nil {
  37. err := f.Close()
  38. if err != nil {
  39. log.Printf("Error closing tmpfile: %s (%s)", err, f.Name())
  40. }
  41. err = os.Remove(f.Name())
  42. if err != nil {
  43. log.Printf("Error removing tmpfile: %s (%s)", err, f.Name())
  44. }
  45. }
  46. }
  47. func sanitize(fileName string) string {
  48. return path.Clean(path.Base(fileName))
  49. }
  50. func resolveURL(r *http.Request, u *url.URL) string {
  51. r.URL.Path = ""
  52. return getURL(r).ResolveReference(u).String()
  53. }
  54. func resolveKey(key, proxyPath string) string {
  55. if strings.HasPrefix(key, "/") {
  56. key = key[1:]
  57. }
  58. if strings.HasPrefix(key, proxyPath) {
  59. key = key[len(proxyPath):]
  60. }
  61. key = strings.Replace(key, "\\", "/", -1)
  62. return key
  63. }
  64. func resolveWebAddress(r *http.Request, proxyPath string) string {
  65. rUrl := getURL(r)
  66. var webAddress string
  67. if len(proxyPath) == 0 {
  68. webAddress = fmt.Sprintf("%s://%s/",
  69. rUrl.ResolveReference(rUrl).Scheme,
  70. rUrl.ResolveReference(rUrl).Host)
  71. } else {
  72. webAddress = fmt.Sprintf("%s://%s/%s",
  73. rUrl.ResolveReference(rUrl).Scheme,
  74. rUrl.ResolveReference(rUrl).Host,
  75. proxyPath)
  76. }
  77. return webAddress
  78. }
  79. func getURL(r *http.Request) *url.URL {
  80. u, _ := url.Parse(r.URL.String())
  81. if r.TLS != nil {
  82. u.Scheme = "https"
  83. } else if proto := r.Header.Get("X-Forwarded-Proto"); proto != "" {
  84. u.Scheme = proto
  85. } else {
  86. u.Scheme = "http"
  87. }
  88. if u.Host != "" {
  89. } else if host, port, err := net.SplitHostPort(r.Host); err != nil {
  90. u.Host = r.Host
  91. } else {
  92. if port == "80" && u.Scheme == "http" {
  93. u.Host = host
  94. } else if port == "443" && u.Scheme == "https" {
  95. u.Host = host
  96. } else {
  97. u.Host = net.JoinHostPort(host, port)
  98. }
  99. }
  100. return u
  101. }
  102. func formatNumber(format string, s int64) string {
  103. return RenderFloat(format, float64(s))
  104. }
  105. var renderFloatPrecisionMultipliers = [10]float64{
  106. 1,
  107. 10,
  108. 100,
  109. 1000,
  110. 10000,
  111. 100000,
  112. 1000000,
  113. 10000000,
  114. 100000000,
  115. 1000000000,
  116. }
  117. var renderFloatPrecisionRounders = [10]float64{
  118. 0.5,
  119. 0.05,
  120. 0.005,
  121. 0.0005,
  122. 0.00005,
  123. 0.000005,
  124. 0.0000005,
  125. 0.00000005,
  126. 0.000000005,
  127. 0.0000000005,
  128. }
  129. func RenderFloat(format string, n float64) string {
  130. // Special cases:
  131. // NaN = "NaN"
  132. // +Inf = "+Infinity"
  133. // -Inf = "-Infinity"
  134. if math.IsNaN(n) {
  135. return "NaN"
  136. }
  137. if n > math.MaxFloat64 {
  138. return "Infinity"
  139. }
  140. if n < -math.MaxFloat64 {
  141. return "-Infinity"
  142. }
  143. // default format
  144. precision := 2
  145. decimalStr := "."
  146. thousandStr := ","
  147. positiveStr := ""
  148. negativeStr := "-"
  149. if len(format) > 0 {
  150. // If there is an explicit format directive,
  151. // then default values are these:
  152. precision = 9
  153. thousandStr = ""
  154. // collect indices of meaningful formatting directives
  155. formatDirectiveChars := []rune(format)
  156. formatDirectiveIndices := make([]int, 0)
  157. for i, char := range formatDirectiveChars {
  158. if char != '#' && char != '0' {
  159. formatDirectiveIndices = append(formatDirectiveIndices, i)
  160. }
  161. }
  162. if len(formatDirectiveIndices) > 0 {
  163. // Directive at index 0:
  164. // Must be a '+'
  165. // Raise an error if not the case
  166. // index: 0123456789
  167. // +0.000,000
  168. // +000,000.0
  169. // +0000.00
  170. // +0000
  171. if formatDirectiveIndices[0] == 0 {
  172. if formatDirectiveChars[formatDirectiveIndices[0]] != '+' {
  173. panic("RenderFloat(): invalid positive sign directive")
  174. }
  175. positiveStr = "+"
  176. formatDirectiveIndices = formatDirectiveIndices[1:]
  177. }
  178. // Two directives:
  179. // First is thousands separator
  180. // Raise an error if not followed by 3-digit
  181. // 0123456789
  182. // 0.000,000
  183. // 000,000.00
  184. if len(formatDirectiveIndices) == 2 {
  185. if (formatDirectiveIndices[1] - formatDirectiveIndices[0]) != 4 {
  186. panic("RenderFloat(): thousands separator directive must be followed by 3 digit-specifiers")
  187. }
  188. thousandStr = string(formatDirectiveChars[formatDirectiveIndices[0]])
  189. formatDirectiveIndices = formatDirectiveIndices[1:]
  190. }
  191. // One directive:
  192. // Directive is decimal separator
  193. // The number of digit-specifier following the separator indicates wanted precision
  194. // 0123456789
  195. // 0.00
  196. // 000,0000
  197. if len(formatDirectiveIndices) == 1 {
  198. decimalStr = string(formatDirectiveChars[formatDirectiveIndices[0]])
  199. precision = len(formatDirectiveChars) - formatDirectiveIndices[0] - 1
  200. }
  201. }
  202. }
  203. // generate sign part
  204. var signStr string
  205. if n >= 0.000000001 {
  206. signStr = positiveStr
  207. } else if n <= -0.000000001 {
  208. signStr = negativeStr
  209. n = -n
  210. } else {
  211. signStr = ""
  212. n = 0.0
  213. }
  214. // split number into integer and fractional parts
  215. intf, fracf := math.Modf(n + renderFloatPrecisionRounders[precision])
  216. // generate integer part string
  217. intStr := strconv.Itoa(int(intf))
  218. // add thousand separator if required
  219. if len(thousandStr) > 0 {
  220. for i := len(intStr); i > 3; {
  221. i -= 3
  222. intStr = intStr[:i] + thousandStr + intStr[i:]
  223. }
  224. }
  225. // no fractional part, we can leave now
  226. if precision == 0 {
  227. return signStr + intStr
  228. }
  229. // generate fractional part
  230. fracStr := strconv.Itoa(int(fracf * renderFloatPrecisionMultipliers[precision]))
  231. // may need padding
  232. if len(fracStr) < precision {
  233. fracStr = "000000000000000"[:precision-len(fracStr)] + fracStr
  234. }
  235. return signStr + intStr + decimalStr + fracStr
  236. }
  237. // Request.RemoteAddress contains port, which we want to remove i.e.:
  238. // "[::1]:58292" => "[::1]"
  239. func ipAddrFromRemoteAddr(s string) string {
  240. idx := strings.LastIndex(s, ":")
  241. if idx == -1 {
  242. return s
  243. }
  244. return s[:idx]
  245. }
  246. func getIPAddress(r *http.Request) string {
  247. hdr := r.Header
  248. hdrRealIP := hdr.Get("X-Real-Ip")
  249. hdrForwardedFor := hdr.Get("X-Forwarded-For")
  250. if hdrRealIP == "" && hdrForwardedFor == "" {
  251. return ipAddrFromRemoteAddr(r.RemoteAddr)
  252. }
  253. if hdrForwardedFor != "" {
  254. // X-Forwarded-For is potentially a list of addresses separated with ","
  255. parts := strings.Split(hdrForwardedFor, ",")
  256. for i, p := range parts {
  257. parts[i] = strings.TrimSpace(p)
  258. }
  259. // TODO: should return first non-local address
  260. return parts[0]
  261. }
  262. return hdrRealIP
  263. }
  264. func encodeRFC2047(s string) string {
  265. // use mail's rfc2047 to encode any string
  266. addr := mail.Address{
  267. Name: s,
  268. Address: "",
  269. }
  270. return strings.Trim(addr.String(), " <>")
  271. }
  272. func acceptsHTML(hdr http.Header) bool {
  273. actual := header.ParseAccept(hdr, "Accept")
  274. for _, s := range actual {
  275. if s.Value == "text/html" {
  276. return (true)
  277. }
  278. }
  279. return (false)
  280. }