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.

303 line
7.3KB

  1. package main
  2. import (
  3. "crypto/sha1"
  4. "fmt"
  5. "io"
  6. "io/ioutil"
  7. "log"
  8. "net/http"
  9. "net/http/httputil"
  10. "net/url"
  11. "os"
  12. "sort"
  13. "strconv"
  14. "strings"
  15. "time"
  16. )
  17. //apiV1Main version 1 main entry for all wechat callbacks
  18. //
  19. func apiV1Main(w http.ResponseWriter, r *http.Request) {
  20. logRequestDebug(httputil.DumpRequest(r, true))
  21. if checkSignature(r) == false {
  22. log.Println("signature of URL incorrect")
  23. w.Header().Set("Content-Type", "text/xml; charset=utf-8")
  24. w.WriteHeader(http.StatusUnauthorized)
  25. fmt.Fprintf(w, "") //empty string
  26. return
  27. }
  28. switch r.Method {
  29. case "POST":
  30. //answerWechatPostEcho(w, r)
  31. answerWechatPost(w, r)
  32. case "GET":
  33. answerInitialAuth(w, r)
  34. default:
  35. log.Println(fmt.Sprintf("FATAL: Unhandled HTTP %s", r.Method))
  36. response404Handler(w)
  37. //fmt.Fprintf(w, "Protocol Error: Expect GET or POST only")
  38. }
  39. }
  40. //
  41. //answerInitialAuth, when wechat first verify our URL for API hooks
  42. //
  43. func answerInitialAuth(w http.ResponseWriter, r *http.Request) {
  44. rq := r.URL.RawQuery
  45. m, _ := url.ParseQuery(rq)
  46. echostr, eok := m["echostr"]
  47. if checkSignature(r) && eok {
  48. fmt.Fprintf(w, echostr[0])
  49. } else {
  50. fmt.Fprintf(w, "wtf is wrong with the Internet")
  51. }
  52. }
  53. //
  54. //answerWechatPost distribute PostRequest according to xml body info
  55. func answerWechatPost(w http.ResponseWriter, r *http.Request) {
  56. in, valid := readWechatInput(r)
  57. reply := "" //nothing
  58. w.Header().Set("Content-Type", "text/xml; charset=utf-8")
  59. if !valid {
  60. log.Println("Error: Invalid Input ")
  61. } else {
  62. //put into user session based pipeline
  63. AllInMessage <- in
  64. }
  65. //read instant response
  66. reply = <-in.instantResponse
  67. in.destroy()
  68. //uncomment the followin two lines to enable echo test
  69. // state, _ := echoCommand(in.header.FromUserName, in)
  70. // reply = state.response
  71. fmt.Fprint(w, reply)
  72. }
  73. func readWechatInput(r *http.Request) (result InWechatMsg, valid bool) {
  74. body, err := ioutil.ReadAll(r.Body)
  75. if err != nil {
  76. log.Println(err)
  77. valid = false
  78. return
  79. }
  80. d := decryptToXML(string(body))
  81. if d == "" {
  82. log.Println("Cannot decode Message : \r\n" + string(body))
  83. valid = false
  84. return
  85. }
  86. valid = true
  87. fmt.Printf("decrypt as: %s\n", d)
  88. result.init()
  89. result.header = ReadCommonHeader(d)
  90. switch result.header.MsgType {
  91. case "text":
  92. result.body = ReadTextMsg(d)
  93. case "image":
  94. result.body = ReadPicMsg(d)
  95. case "voice":
  96. result.body = ReadVoiceMsg(d)
  97. case "video":
  98. result.body = ReadVideoMsg(d)
  99. case "shortvideo":
  100. result.body = ReadShortVideoMsg(d)
  101. case "location":
  102. result.body = ReadLocationMsg(d)
  103. case "link":
  104. result.body = ReadLinkMsg(d)
  105. case "event":
  106. result.body = ReadEventMsg(d)
  107. default:
  108. log.Println("Fatal: unknown incoming message type" + result.header.MsgType)
  109. valid = false
  110. }
  111. return
  112. }
  113. func answerWechatPostEcho(w http.ResponseWriter, r *http.Request) {
  114. body, _ := ioutil.ReadAll(r.Body)
  115. //fmt.Printf("get body: %s", string(body))
  116. s := ReadEncryptedMsg(string(body))
  117. //fmt.Printf("to decrypt %s", s.Encrypt)
  118. d := Decode(s.Encrypt)
  119. fmt.Printf("echo as: \r\n%s", d)
  120. e := strings.Replace(d, "ToUserName", "FDDD20170506xyzunique", 2)
  121. f := strings.Replace(e, "FromUserName", "ToUserName", 2)
  122. g := strings.Replace(f, "FDDD20170506xyzunique", "FromUserName", 2)
  123. fmt.Fprint(w, g)
  124. }
  125. //
  126. func checkSignature(r *http.Request) bool {
  127. return checkSignatureByToken(r, APIConfig.Token)
  128. }
  129. func checkSignatureByToken(r *http.Request, token string) bool {
  130. rq := r.URL.RawQuery
  131. m, _ := url.ParseQuery(rq)
  132. signature, sok := m["signature"]
  133. timestamp, tok := m["timestamp"]
  134. nonce, nok := m["nonce"]
  135. token = strings.TrimSpace(token)
  136. if sok && tok && nok && token != "" {
  137. return verifySignature(signature[0], timestamp[0], nonce[0], token)
  138. }
  139. return false
  140. }
  141. func checkCookieSignatureBytoken(r *http.Request, token string) bool {
  142. signature := ""
  143. nonce := ""
  144. timestamp := ""
  145. for _, c := range r.Cookies() {
  146. switch c.Name {
  147. case "signature":
  148. signature = c.Value
  149. case "nonce":
  150. nonce = c.Value
  151. case "timestamp":
  152. timestamp = c.Value
  153. }
  154. }
  155. if signature != "" && nonce != "" && timestamp != "" {
  156. return verifySignature(signature, timestamp, nonce, IntraAPIConfig.CRMSecrete)
  157. }
  158. return false
  159. }
  160. func verifySignature(signature, timestamp, nonce, token string) bool {
  161. if timestampTooOldStr(timestamp) {
  162. return false
  163. }
  164. return signature == calculateSignature(timestamp, nonce, token)
  165. }
  166. func calculateSignature(timestamp, nonce, token string) (signature string) {
  167. //sort token, timestamp, nonce and join them
  168. strs := []string{token, timestamp, nonce}
  169. sort.Strings(strs)
  170. s := strings.Join(strs, "")
  171. //calculate sha1
  172. h := sha1.New()
  173. h.Write([]byte(s))
  174. calculated := fmt.Sprintf("%x", h.Sum(nil))
  175. signature = calculated
  176. return
  177. }
  178. func timestampTooOldStr(timestamp string) bool {
  179. ts, err := strconv.Atoi(timestamp)
  180. if err != nil {
  181. return true
  182. }
  183. return timestampTooOld(int32(ts))
  184. }
  185. func timestampTooOld(ts int32) bool {
  186. //diff > 3min from now
  187. now := int32(time.Now().Unix())
  188. diff := now - ts
  189. if diff < 0 {
  190. diff = -diff
  191. }
  192. return diff > 180 //3 minutes, 180 seconds
  193. }
  194. // func checkSignature1() bool {
  195. // s1 := "e39de9f2e28079c01ebb4b803dfc3442b819545c"
  196. // t1 := "1492970761"
  197. // n1 := "1850971833"
  198. // token := APIConfig.Token
  199. // strs := []string{token, t1, n1}
  200. // sort.Strings(strs)
  201. // s := strings.Join(strs, "")
  202. // h := sha1.New()
  203. // h.Write([]byte(s))
  204. // us := fmt.Sprintf("%x", h.Sum(nil))
  205. // return s1 == us
  206. // }
  207. //webrootHandler sending contents to client when request "/"
  208. // essentially to prove the webserver is still alive
  209. // echo query string to the client
  210. func webrootHandler(w http.ResponseWriter, r *http.Request) {
  211. fmt.Fprintf(w, "Hi there, I love %s!", r.URL.Path[1:])
  212. rq := r.URL.RawQuery
  213. m, _ := url.ParseQuery(rq)
  214. for index, element := range m {
  215. fmt.Fprintf(w, "\n%s => %s", index, element)
  216. }
  217. logRequestDebug(httputil.DumpRequest(r, true))
  218. }
  219. func logRequestDebug(data []byte, err error) {
  220. if err == nil {
  221. fmt.Printf("%s\n\n", string(data))
  222. } else {
  223. log.Fatalf("%s\n\n", err)
  224. }
  225. }
  226. //save uploaded 'file' into temporary location
  227. func uploadHandler(w http.ResponseWriter, r *http.Request) {
  228. r.ParseMultipartForm(32 << 20) //32MB memory
  229. file, handler, err := r.FormFile("file") //form-field 'file'
  230. if err != nil {
  231. fmt.Println(err)
  232. return
  233. }
  234. defer file.Close()
  235. fmt.Fprintf(w, "%v", handler.Header)
  236. f, err := os.OpenFile("/tmp/wechat_hitxy_"+handler.Filename, os.O_WRONLY|os.O_CREATE, 0666)
  237. if err != nil {
  238. fmt.Println(err)
  239. return
  240. }
  241. defer f.Close()
  242. io.Copy(f, file)
  243. }
  244. //when user requst an attachment from our server, we get the file from CRM server and reply it back
  245. //in this way, user has no 'direct-access' to the CRM server.
  246. func crmAttachmentHandler(w http.ResponseWriter, r *http.Request) {
  247. fileID := getCrmFileID(r.URL.Path)
  248. saveAs := CRMConfig.AttachmentCache + "crm_attach_" + fileID //add prefix for easy deleting
  249. if isFileExist(saveAs) {
  250. http.ServeFile(w, r, saveAs)
  251. return
  252. }
  253. if fileID == "" {
  254. log.Println("invalid fileID")
  255. response404Handler(w)
  256. return
  257. }
  258. log.Printf("download %s => %s", fileID, saveAs)
  259. crmDownloadAttachmentAs(fileID, saveAs)
  260. if !isFileExist(saveAs) {
  261. response404Handler(w)
  262. return
  263. }
  264. http.ServeFile(w, r, saveAs)
  265. }
  266. func getCrmFileID(urlPath string) string {
  267. return strings.TrimPrefix(urlPath, "/crmfiles/")
  268. }
  269. func response404Handler(w http.ResponseWriter) {
  270. w.WriteHeader(http.StatusNotFound)
  271. fmt.Fprintf(w, "not found")
  272. }