Skip to content

Commit c1cc78c

Browse files
committed
fix: prevent deadlock from happening
reported in #91
1 parent f17d7fd commit c1cc78c

1 file changed

Lines changed: 14 additions & 7 deletions

File tree

internal/certificatetransparency/logmetrics.go

Lines changed: 14 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -168,20 +168,27 @@ func (m *LogMetrics) SetCTIndex(url string, index uint64) {
168168

169169
// LoadCTIndex loads the last cert index processed for each CT url if it exists.
170170
func (m *LogMetrics) LoadCTIndex(ctIndexFilePath string) {
171+
log.Println("Loading CT indexes from file: ", ctIndexFilePath)
172+
171173
m.mutex.Lock()
172174
defer m.mutex.Unlock()
173175

174176
bytes, readErr := os.ReadFile(ctIndexFilePath)
175177
if readErr != nil {
176178
// Create the file if it doesn't exist
177179
if os.IsNotExist(readErr) {
178-
err := createCTIndexFile(ctIndexFilePath, m)
180+
log.Println("CT index file does not exist, creating a new one...")
181+
if m.index == nil {
182+
m.index = make(CTCertIndex)
183+
}
184+
err := m.createCTIndexFile(ctIndexFilePath)
179185
if err != nil {
180186
log.Printf("Error creating CT index file: '%s'\n", ctIndexFilePath)
181187
log.Panicln(err)
182188
}
189+
bytes = []byte("{}")
183190
} else {
184-
// If the file exists but we can't read it, log the error and panic
191+
// If the file exists, but we can't read it, log the error and panic
185192
log.Panicln(readErr)
186193
}
187194
}
@@ -195,10 +202,7 @@ func (m *LogMetrics) LoadCTIndex(ctIndexFilePath string) {
195202
log.Println("Successfully loaded saved CT indexes")
196203
}
197204

198-
func createCTIndexFile(ctIndexFilePath string, m *LogMetrics) error {
199-
m.mutex.RLock()
200-
defer m.mutex.RUnlock()
201-
205+
func (m *LogMetrics) createCTIndexFile(ctIndexFilePath string) error {
202206
log.Printf("Specified CT index file does not exist: '%s'\n", ctIndexFilePath)
203207
log.Println("Creating CT index file now!")
204208

@@ -207,7 +211,11 @@ func createCTIndexFile(ctIndexFilePath string, m *LogMetrics) error {
207211
log.Printf("Error creating CT index file: '%s'\n", ctIndexFilePath)
208212
log.Panicln(createErr)
209213
}
214+
defer file.Close()
210215

216+
if m.index == nil {
217+
m.index = make(CTCertIndex)
218+
}
211219
bytes, marshalErr := json.Marshal(m.index)
212220
if marshalErr != nil {
213221
return marshalErr
@@ -217,7 +225,6 @@ func createCTIndexFile(ctIndexFilePath string, m *LogMetrics) error {
217225
log.Printf("Error writing to CT index file: '%s'\n", ctIndexFilePath)
218226
log.Panicln(writeErr)
219227
}
220-
file.Close()
221228

222229
return nil
223230
}

0 commit comments

Comments
 (0)