Não pode escolher mais do que 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 
 
 
 
 

463 linhas
10 KiB

  1. // Copyright (c) 2014, Google Inc.
  2. //
  3. // Permission to use, copy, modify, and/or distribute this software for any
  4. // purpose with or without fee is hereby granted, provided that the above
  5. // copyright notice and this permission notice appear in all copies.
  6. //
  7. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  8. // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  9. // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
  10. // SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  11. // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
  12. // OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
  13. // CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */
  14. package main
  15. import (
  16. "bufio"
  17. "errors"
  18. "flag"
  19. "fmt"
  20. "io"
  21. "os"
  22. "path/filepath"
  23. "sort"
  24. "strconv"
  25. "strings"
  26. "unicode"
  27. )
  28. // ssl.h reserves values 1000 and above for error codes corresponding to
  29. // alerts. If automatically assigned reason codes exceed this value, this script
  30. // will error. This must be kept in sync with SSL_AD_REASON_OFFSET in ssl.h.
  31. const reservedReasonCode = 1000
  32. var resetFlag *bool = flag.Bool("reset", false, "If true, ignore current assignments and reassign from scratch")
  33. func makeErrors(reset bool) error {
  34. dirName, err := os.Getwd()
  35. if err != nil {
  36. return err
  37. }
  38. lib := filepath.Base(dirName)
  39. headerPath, err := findHeader(lib + ".h")
  40. if err != nil {
  41. return err
  42. }
  43. sourcePath := lib + "_error.c"
  44. headerFile, err := os.Open(headerPath)
  45. if err != nil {
  46. if os.IsNotExist(err) {
  47. return fmt.Errorf("No header %s. Run in the right directory or touch the file.", headerPath)
  48. }
  49. return err
  50. }
  51. prefix := strings.ToUpper(lib)
  52. functions, reasons, err := parseHeader(prefix, headerFile)
  53. headerFile.Close()
  54. if reset {
  55. err = nil
  56. functions = make(map[string]int)
  57. // Retain any reason codes above reservedReasonCode.
  58. newReasons := make(map[string]int)
  59. for key, value := range reasons {
  60. if value >= reservedReasonCode {
  61. newReasons[key] = value
  62. }
  63. }
  64. reasons = newReasons
  65. }
  66. if err != nil {
  67. return err
  68. }
  69. dir, err := os.Open(".")
  70. if err != nil {
  71. return err
  72. }
  73. defer dir.Close()
  74. filenames, err := dir.Readdirnames(-1)
  75. if err != nil {
  76. return err
  77. }
  78. for _, name := range filenames {
  79. if !strings.HasSuffix(name, ".c") || name == sourcePath {
  80. continue
  81. }
  82. if err := addFunctionsAndReasons(functions, reasons, name, prefix); err != nil {
  83. return err
  84. }
  85. }
  86. assignNewValues(functions, -1)
  87. assignNewValues(reasons, reservedReasonCode)
  88. headerFile, err = os.Open(headerPath)
  89. if err != nil {
  90. return err
  91. }
  92. defer headerFile.Close()
  93. newHeaderFile, err := os.OpenFile(headerPath+".tmp", os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0666)
  94. if err != nil {
  95. return err
  96. }
  97. defer newHeaderFile.Close()
  98. if err := writeHeaderFile(newHeaderFile, headerFile, prefix, functions, reasons); err != nil {
  99. return err
  100. }
  101. os.Rename(headerPath+".tmp", headerPath)
  102. sourceFile, err := os.OpenFile(sourcePath, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0644)
  103. if err != nil {
  104. return err
  105. }
  106. defer sourceFile.Close()
  107. fmt.Fprintf(sourceFile, `/* Copyright (c) 2014, Google Inc.
  108. *
  109. * Permission to use, copy, modify, and/or distribute this software for any
  110. * purpose with or without fee is hereby granted, provided that the above
  111. * copyright notice and this permission notice appear in all copies.
  112. *
  113. * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  114. * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  115. * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
  116. * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  117. * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
  118. * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
  119. * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */
  120. #include <openssl/err.h>
  121. #include <openssl/%s.h>
  122. const ERR_STRING_DATA %s_error_string_data[] = {
  123. `, lib, prefix)
  124. outputStrings(sourceFile, lib, typeFunctions, functions)
  125. outputStrings(sourceFile, lib, typeReasons, reasons)
  126. sourceFile.WriteString(" {0, NULL},\n};\n")
  127. return nil
  128. }
  129. func findHeader(basename string) (path string, err error) {
  130. includeDir := filepath.Join("..", "include")
  131. fi, err := os.Stat(includeDir)
  132. if err != nil && os.IsNotExist(err) {
  133. includeDir = filepath.Join("..", includeDir)
  134. fi, err = os.Stat(includeDir)
  135. }
  136. if err != nil {
  137. return "", errors.New("cannot find path to include directory")
  138. }
  139. if !fi.IsDir() {
  140. return "", errors.New("include node is not a directory")
  141. }
  142. return filepath.Join(includeDir, "openssl", basename), nil
  143. }
  144. type assignment struct {
  145. key string
  146. value int
  147. }
  148. type assignmentsSlice []assignment
  149. func (a assignmentsSlice) Len() int {
  150. return len(a)
  151. }
  152. func (a assignmentsSlice) Less(i, j int) bool {
  153. return a[i].value < a[j].value
  154. }
  155. func (a assignmentsSlice) Swap(i, j int) {
  156. a[i], a[j] = a[j], a[i]
  157. }
  158. func outputAssignments(w io.Writer, assignments map[string]int) {
  159. var sorted assignmentsSlice
  160. for key, value := range assignments {
  161. sorted = append(sorted, assignment{key, value})
  162. }
  163. sort.Sort(sorted)
  164. for _, assignment := range sorted {
  165. fmt.Fprintf(w, "#define %s %d\n", assignment.key, assignment.value)
  166. }
  167. }
  168. func parseDefineLine(line, lib string) (typ int, key string, value int, ok bool) {
  169. if !strings.HasPrefix(line, "#define ") {
  170. return
  171. }
  172. fields := strings.Fields(line)
  173. if len(fields) != 3 {
  174. return
  175. }
  176. funcPrefix := lib + "_F_"
  177. reasonPrefix := lib + "_R_"
  178. key = fields[1]
  179. switch {
  180. case strings.HasPrefix(key, funcPrefix):
  181. typ = typeFunctions
  182. case strings.HasPrefix(key, reasonPrefix):
  183. typ = typeReasons
  184. default:
  185. return
  186. }
  187. var err error
  188. if value, err = strconv.Atoi(fields[2]); err != nil {
  189. return
  190. }
  191. ok = true
  192. return
  193. }
  194. func writeHeaderFile(w io.Writer, headerFile io.Reader, lib string, functions, reasons map[string]int) error {
  195. var last []byte
  196. var haveLast, sawDefine bool
  197. newLine := []byte("\n")
  198. scanner := bufio.NewScanner(headerFile)
  199. for scanner.Scan() {
  200. line := scanner.Text()
  201. _, _, _, ok := parseDefineLine(line, lib)
  202. if ok {
  203. sawDefine = true
  204. continue
  205. }
  206. if haveLast {
  207. w.Write(last)
  208. w.Write(newLine)
  209. }
  210. if len(line) > 0 || !sawDefine {
  211. last = []byte(line)
  212. haveLast = true
  213. } else {
  214. haveLast = false
  215. }
  216. sawDefine = false
  217. }
  218. if err := scanner.Err(); err != nil {
  219. return err
  220. }
  221. outputAssignments(w, functions)
  222. outputAssignments(w, reasons)
  223. w.Write(newLine)
  224. if haveLast {
  225. w.Write(last)
  226. w.Write(newLine)
  227. }
  228. return nil
  229. }
  230. const (
  231. typeFunctions = iota
  232. typeReasons
  233. )
  234. func outputStrings(w io.Writer, lib string, ty int, assignments map[string]int) {
  235. lib = strings.ToUpper(lib)
  236. prefixLen := len(lib + "_F_")
  237. keys := make([]string, 0, len(assignments))
  238. for key := range assignments {
  239. keys = append(keys, key)
  240. }
  241. sort.Strings(keys)
  242. for _, key := range keys {
  243. var pack string
  244. if ty == typeFunctions {
  245. pack = key + ", 0"
  246. } else {
  247. pack = "0, " + key
  248. }
  249. fmt.Fprintf(w, " {ERR_PACK(ERR_LIB_%s, %s), \"%s\"},\n", lib, pack, key[prefixLen:])
  250. }
  251. }
  252. func assignNewValues(assignments map[string]int, reserved int) {
  253. max := 99
  254. for _, value := range assignments {
  255. if reserved >= 0 && value >= reserved {
  256. continue
  257. }
  258. if value > max {
  259. max = value
  260. }
  261. }
  262. max++
  263. for key, value := range assignments {
  264. if value == -1 {
  265. if reserved >= 0 && max >= reserved {
  266. // If this happens, try passing
  267. // -reset. Otherwise bump up reservedReasonCode.
  268. panic("Automatically-assigned values exceeded limit!")
  269. }
  270. assignments[key] = max
  271. max++
  272. }
  273. }
  274. }
  275. func handleDeclareMacro(line, join, macroName string, m map[string]int) {
  276. if i := strings.Index(line, macroName); i >= 0 {
  277. contents := line[i+len(macroName):]
  278. if i := strings.Index(contents, ")"); i >= 0 {
  279. contents = contents[:i]
  280. args := strings.Split(contents, ",")
  281. for i := range args {
  282. args[i] = strings.TrimSpace(args[i])
  283. }
  284. if len(args) != 2 {
  285. panic("Bad macro line: " + line)
  286. }
  287. token := args[0] + join + args[1]
  288. if _, ok := m[token]; !ok {
  289. m[token] = -1
  290. }
  291. }
  292. }
  293. }
  294. func addFunctionsAndReasons(functions, reasons map[string]int, filename, prefix string) error {
  295. file, err := os.Open(filename)
  296. if err != nil {
  297. return err
  298. }
  299. defer file.Close()
  300. prefix += "_"
  301. reasonPrefix := prefix + "R_"
  302. var currentFunction string
  303. scanner := bufio.NewScanner(file)
  304. for scanner.Scan() {
  305. line := scanner.Text()
  306. if len(line) > 0 && unicode.IsLetter(rune(line[0])) {
  307. /* Function start */
  308. fields := strings.Fields(line)
  309. for _, field := range fields {
  310. if i := strings.Index(field, "("); i != -1 {
  311. f := field[:i]
  312. // The return type of some functions is
  313. // a macro that contains a "(".
  314. if f == "STACK_OF" {
  315. continue
  316. }
  317. currentFunction = f
  318. for len(currentFunction) > 0 && currentFunction[0] == '*' {
  319. currentFunction = currentFunction[1:]
  320. }
  321. break
  322. }
  323. }
  324. }
  325. if strings.Contains(line, "OPENSSL_PUT_ERROR(") {
  326. functionToken := prefix + "F_" + currentFunction
  327. if _, ok := functions[functionToken]; !ok {
  328. functions[functionToken] = -1
  329. }
  330. }
  331. handleDeclareMacro(line, "_R_", "OPENSSL_DECLARE_ERROR_REASON(", reasons)
  332. handleDeclareMacro(line, "_F_", "OPENSSL_DECLARE_ERROR_FUNCTION(", functions)
  333. for len(line) > 0 {
  334. i := strings.Index(line, prefix)
  335. if i == -1 {
  336. break
  337. }
  338. line = line[i:]
  339. end := strings.IndexFunc(line, func(r rune) bool {
  340. return !(r == '_' || (r >= 'A' && r <= 'Z') || (r >= '0' && r <= '9'))
  341. })
  342. if end == -1 {
  343. end = len(line)
  344. }
  345. var token string
  346. token, line = line[:end], line[end:]
  347. switch {
  348. case strings.HasPrefix(token, reasonPrefix):
  349. if _, ok := reasons[token]; !ok {
  350. reasons[token] = -1
  351. }
  352. }
  353. }
  354. }
  355. return scanner.Err()
  356. }
  357. func parseHeader(lib string, file io.Reader) (functions, reasons map[string]int, err error) {
  358. functions = make(map[string]int)
  359. reasons = make(map[string]int)
  360. scanner := bufio.NewScanner(file)
  361. for scanner.Scan() {
  362. typ, key, value, ok := parseDefineLine(scanner.Text(), lib)
  363. if !ok {
  364. continue
  365. }
  366. switch typ {
  367. case typeFunctions:
  368. functions[key] = value
  369. case typeReasons:
  370. reasons[key] = value
  371. default:
  372. panic("internal error")
  373. }
  374. }
  375. err = scanner.Err()
  376. return
  377. }
  378. func main() {
  379. flag.Parse()
  380. if err := makeErrors(*resetFlag); err != nil {
  381. fmt.Fprintf(os.Stderr, "%s\n", err)
  382. os.Exit(1)
  383. }
  384. }