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