Debian Codegraph @

internal/certificatetransparency/ct-watcher.go

raw symbols SCIP
1 package certificatetransparency
2
3 import (
4 "context"
5 "errors"
6 "fmt"
7 "io"
8 "log"
9 "net/http"
10 "path/filepath"
11 "strings"
12 "sync"
13 "sync/atomic"
14 "time"
15
16 "github.com/google/trillian/client/backoff"
17
18 "github.com/d-Rickyy-b/certstream-server-go/internal/config"
19 "github.com/d-Rickyy-b/certstream-server-go/internal/metrics"
20 "github.com/d-Rickyy-b/certstream-server-go/internal/models"
21 "github.com/d-Rickyy-b/certstream-server-go/internal/web"
22
23 ct "github.com/google/certificate-transparency-go"
24 "github.com/google/certificate-transparency-go/client"
25 "github.com/google/certificate-transparency-go/jsonclient"
26 "github.com/google/certificate-transparency-go/loglist3"
27 "github.com/google/certificate-transparency-go/scanner"
28 )
29
30 var (
31 errCreatingClient = errors.New("failed to create JSON client")
32 errFetchingSTHFailed = errors.New("failed to fetch STH")
33 userAgent = fmt.Sprintf("Certstream Server v%s (github.com/d-Rickyy-b/certstream-server-go)", config.Version)
34 )
35
36 // Watcher describes a component that watches for new certificates in a CT log.
37 type Watcher struct {
38 workers []*worker
39 workersMu sync.RWMutex
40 wg sync.WaitGroup
41 context context.Context
42 certChan chan models.Entry
43 cancelFunc context.CancelFunc
44 }
45
46 // NewWatcher creates a new Watcher.
47 func NewWatcher(certChan chan models.Entry) *Watcher {
48 return &Watcher{
49 certChan: certChan,
50 }
51 }
52
53 // Start starts the watcher. This method is blocking.
54 func (w *Watcher) Start() {
55 w.context, w.cancelFunc = context.WithCancel(context.Background())
56
57 // Create new certChan if it doesn't exist yet
58 if w.certChan == nil {
59 w.certChan = make(chan models.Entry, 5000)
60 }
61
62 if config.AppConfig.General.Recovery.Enabled {
63 ctIndexFilePath, err := filepath.Abs(config.AppConfig.General.Recovery.CTIndexFile)
64 if err != nil {
65 log.Printf("Error getting absolute path for CT index file: '%s', %s\n", config.AppConfig.General.Recovery.CTIndexFile, err)
66 return
67 }
68 // Load Saved CT Indexes
69 metrics.Metrics.LoadCTIndex(ctIndexFilePath)
70 // Save CTIndexes at regular intervals
71 go metrics.Metrics.SaveCertIndexesAtInterval(time.Second*30, ctIndexFilePath) // save indexes every X seconds
72 }
73
74 // initialize the watcher with currently available logs
75 w.updateLogs()
76
77 log.Println("Started CT watcher")
78 go certHandler(w.certChan)
79 go w.watchNewLogs()
80
81 // Wait for all workers to finish
82 w.wg.Wait()
83 close(w.certChan)
84 }
85
86 // watchNewLogs monitors the ct log list for new logs and starts a worker for each new log found.
87 // This method is blocking. It can be stopped by cancelling the context.
88 func (w *Watcher) watchNewLogs() {
89 // Check for new logs once every hour
90 ticker := time.NewTicker(1 * time.Hour)
91 for {
92 select {
93 case <-ticker.C:
94 w.updateLogs()
95 case <-w.context.Done():
96 ticker.Stop()
97 return
98 }
99 }
100 }
101
102 // updateLogs checks the transparency log list for new logs and adds new workers for those to the watcher.
103 func (w *Watcher) updateLogs() {
104 // Get a list of urls of all CT logs
105 logList, err := getAllLogs()
106 if err != nil {
107 log.Println(err)
108 return
109 }
110
111 log.Println("Checking for new ct logs...")
112
113 // Track all URLs that should be monitored after reconciliation
114 monitoredURLs := make(map[string]struct{})
115 newCTs := 0
116
117 w.workersMu.Lock()
118 defer w.workersMu.Unlock()
119
120 for _, operator := range logList.Operators {
121 // Classic logs
122 for _, transparencyLog := range operator.Logs {
123 url := transparencyLog.URL
124 desc := transparencyLog.Description
125 normURL := normalizeCtlogURL(url)
126
127 if transparencyLog.State.LogStatus() == loglist3.RetiredLogStatus {
128 log.Printf("Skipping retired CT log: %s\n", normURL)
129 continue
130 }
131
132 monitoredURLs[normURL] = struct{}{}
133 if w.addLogIfNew(operator.Name, desc, url, false) {
134 newCTs++
135 }
136 }
137
138 // Tiled logs
139 for _, transparencyLog := range operator.TiledLogs {
140 url := transparencyLog.MonitoringURL
141 desc := transparencyLog.Description
142 normURL := normalizeCtlogURL(url)
143
144 if transparencyLog.State.LogStatus() == loglist3.RetiredLogStatus {
145 log.Printf("Skipping retired CT log: %s\n", normURL)
146 continue
147 }
148
149 monitoredURLs[normURL] = struct{}{}
150 if w.addLogIfNew(operator.Name, desc, url, true) {
151 newCTs++
152 }
153 }
154 }
155
156 log.Printf("New ct logs found: %d\n", newCTs)
157
158 // Optionally stop workers for logs not in the monitoredURLs set
159 if *config.AppConfig.General.DropOldLogs {
160 removed := 0
161 for _, ctWorker := range w.workers {
162 normURL := normalizeCtlogURL(ctWorker.ctURL)
163 if _, ok := monitoredURLs[normURL]; !ok {
164 log.Printf("Stopping worker. CT URL not found in LogList or retired: '%s'\n", ctWorker.ctURL)
165 ctWorker.stop()
166 removed++
167 }
168 }
169 log.Printf("Removed ct logs: %d\n", removed)
170 }
171
172 log.Printf("Currently monitored ct logs: %d\n", len(w.workers))
173 }
174
175 // addLogIfNew checks if a log is already being watched and adds it if not.
176 // Returns true if a new log was added, false otherwise.
177 func (w *Watcher) addLogIfNew(operatorName, description, url string, isTiled bool) bool {
178 normURL := normalizeCtlogURL(url)
179
180 // Check if the log is already being watched
181 for _, ctWorker := range w.workers {
182 workerURL := normalizeCtlogURL(ctWorker.ctURL)
183 if workerURL == normURL {
184 return false
185 }
186 }
187
188 // Log is not being watched, so add it
189 w.wg.Add(1)
190
191 lastCTIndex := metrics.Metrics.GetCTIndex(normURL)
192 ctWorker := worker{
193 name: description,
194 operatorName: operatorName,
195 ctURL: url,
196 entryChan: w.certChan,
197 ctIndex: lastCTIndex,
198 isTiled: isTiled,
199 }
200 w.workers = append(w.workers, &ctWorker)
201 metrics.Metrics.Init(operatorName, normURL)
202
203 // Start a goroutine for each worker
204 go func() {
205 defer w.wg.Done()
206 ctWorker.startDownloadingCerts(w.context)
207 w.discardWorker(&ctWorker)
208 }()
209
210 return true
211 }
212
213 // discardWorker removes a worker from the watcher's list of workers.
214 // This needs to be done when a worker stops.
215 func (w *Watcher) discardWorker(worker *worker) {
216 log.Println("Removing worker for CT log:", worker.ctURL)
217
218 w.workersMu.Lock()
219 defer w.workersMu.Unlock()
220
221 for i, wo := range w.workers {
222 if wo == worker {
223 w.workers = append(w.workers[:i], w.workers[i+1:]...)
224 return
225 }
226 }
227 }
228
229 // Stop stops the watcher.
230 func (w *Watcher) Stop() {
231 log.Printf("Stopping watcher\n")
232
233 if config.AppConfig.General.Recovery.Enabled {
234 // Store current CT Indexes before shutting down
235 filePath := config.AppConfig.General.Recovery.CTIndexFile
236 metrics.Metrics.SaveCertIndexes(filePath)
237 }
238
239 w.cancelFunc()
240 }
241
242 // CreateIndexFile creates a ct_index.json file based on the current STHs of all availble logs.
243 func (w *Watcher) CreateIndexFile(filePath string) error {
244 logs, err := getAllLogs()
245 if err != nil {
246 return err
247 }
248
249 w.context, w.cancelFunc = context.WithCancel(context.Background())
250 log.Println("Fetching current STH for all logs...")
251 for _, operator := range logs.Operators {
252 // Iterate over each log of the operator
253 for _, transparencyLog := range operator.Logs {
254 if transparencyLog.State.LogStatus() == loglist3.RetiredLogStatus {
255 log.Printf("Skipping retired CT log: %s\n", transparencyLog.URL)
256 continue
257 }
258
259 normalizedURL := normalizeCtlogURL(transparencyLog.URL)
260 // Check if the log is already being watched
261 metrics.Metrics.Init(operator.Name, normalizedURL)
262 log.Println("Fetching STH for", normalizedURL)
263
264 hc := http.Client{Timeout: 5 * time.Second}
265 jsonClient, e := client.New(transparencyLog.URL, &hc, jsonclient.Options{UserAgent: userAgent})
266 if e != nil {
267 log.Printf("Error creating JSON client: %s\n", e)
268 continue
269 }
270
271 sth, getSTHerr := jsonClient.GetSTH(w.context)
272 if getSTHerr != nil {
273 // TODO this can happen due to a 429 error. We should retry the request
274 log.Printf("Could not get STH for '%s': %s\n", transparencyLog.URL, getSTHerr)
275 continue
276 }
277
278 metrics.Metrics.SetCTIndex(normalizedURL, sth.TreeSize)
279 }
280 for _, transparencyLog := range operator.TiledLogs {
281 if transparencyLog.State.LogStatus() == loglist3.RetiredLogStatus {
282 log.Printf("Skipping retired CT log: %s\n", transparencyLog.MonitoringURL)
283 continue
284 }
285 // Check if the log is already being watched
286 normalizedURL := normalizeCtlogURL(transparencyLog.MonitoringURL)
287 metrics.Metrics.Init(operator.Name, normalizedURL)
288 log.Println("Fetching checkpoint for", normalizedURL)
289
290 hc := &http.Client{Timeout: 10 * time.Second}
291 checkpoint, fetchErr := FetchCheckpoint(w.context, hc, transparencyLog.MonitoringURL)
292 if fetchErr != nil {
293 log.Printf("Could not get checkpoint for '%s': %s\n", transparencyLog.MonitoringURL, fetchErr)
294 return errFetchingSTHFailed
295 }
296
297 metrics.Metrics.SetCTIndex(normalizedURL, checkpoint.Size)
298 }
299 }
300 w.cancelFunc()
301
302 metrics.Metrics.SaveCertIndexes(filePath)
303 log.Println("Index file saved to", filePath)
304
305 return nil
306 }
307
308 // A worker processes a single CT log.
309 type worker struct {
310 name string
311 operatorName string
312 ctURL string
313 entryChan chan models.Entry
314 ctIndex uint64
315 mu sync.Mutex
316 running bool
317 cancel context.CancelFunc
318 isTiled bool
319 }
320
321 // startDownloadingCerts starts downloading certificates from the CT log. This method is blocking.
322 func (w *worker) startDownloadingCerts(ctx context.Context) {
323 ctx, w.cancel = context.WithCancel(ctx)
324
325 // Normalize CT URL. We remove trailing slashes and prepend "https://" if it's not already there.
326 w.ctURL = strings.TrimRight(w.ctURL, "/")
327 if !strings.HasPrefix(w.ctURL, "https://") && !strings.HasPrefix(w.ctURL, "http://") {
328 w.ctURL = "https://" + w.ctURL
329 }
330
331 log.Printf("Initializing worker for CT log: %s\n", w.ctURL)
332 defer log.Printf("Stopping worker for CT log: %s\n", w.ctURL)
333
334 w.mu.Lock()
335 if w.running {
336 log.Printf("Worker for '%s' already running\n", w.ctURL)
337 w.mu.Unlock()
338
339 return
340 }
341
342 w.running = true
343 defer func() { w.running = false }()
344 w.mu.Unlock()
345
346 for {
347 log.Printf("Starting worker for CT log: %s\n", w.ctURL)
348
349 var workerErr error
350 if w.isTiled {
351 workerErr = w.runTiledWorker(ctx)
352 } else {
353 workerErr = w.runStandardWorker(ctx)
354 }
355
356 if workerErr != nil {
357 if errors.Is(workerErr, errFetchingSTHFailed) {
358 // TODO this could happen due to a 429 error. We should retry the request
359 log.Printf("Worker for '%s' failed - could not fetch STH\n", w.ctURL)
360 return
361 } else if errors.Is(workerErr, errCreatingClient) {
362 log.Printf("Worker for '%s' failed - could not create client\n", w.ctURL)
363 return
364 } else if strings.Contains(workerErr.Error(), "no such host") {
365 log.Printf("Worker for '%s' failed to resolve host: %s\n", w.ctURL, workerErr)
366 return
367 }
368
369 log.Printf("Worker for '%s' failed with unexpected error: %s\n", w.ctURL, workerErr)
370 }
371
372 // Check if the context was canceled
373 select {
374 case <-ctx.Done():
375 log.Printf("Context was cancelled; Stopping worker for '%s'\n", w.ctURL)
376
377 return
378 default:
379 log.Printf("Worker for '%s' sleeping for 5 seconds due to error\n", w.ctURL)
380 time.Sleep(5 * time.Second)
381 log.Printf("Restarting worker for '%s'\n", w.ctURL)
382
383 continue
384 }
385 }
386 }
387
388 func (w *worker) stop() {
389 w.mu.Lock()
390 defer w.mu.Unlock()
391
392 w.cancel()
393 }
394
395 // runStandardWorker runs the worker for a single standard CT log. This method is blocking.
396 func (w *worker) runStandardWorker(ctx context.Context) error {
397 hc := http.Client{Timeout: 30 * time.Second}
398 jsonClient, e := client.New(w.ctURL, &hc, jsonclient.Options{UserAgent: userAgent})
399 if e != nil {
400 log.Printf("Error creating JSON client: %s\n", e)
401 return errCreatingClient
402 }
403
404 // If recovery is enabled, we start at the saved index. Otherwise, we start at the latest STH.
405 recoveryEnabled := config.AppConfig.General.Recovery.Enabled
406 if !recoveryEnabled {
407 sth, getSTHerr := jsonClient.GetSTH(ctx)
408 if getSTHerr != nil {
409 // TODO this can happen due to a 429 error. We should retry the request
410 log.Printf("Could not get STH for '%s': %s\n", w.ctURL, getSTHerr)
411 return errFetchingSTHFailed
412 }
413 // Start at the latest STH to skip all the past certificates
414 w.ctIndex = sth.TreeSize
415 }
416
417 certScanner := scanner.NewScanner(jsonClient, scanner.ScannerOptions{
418 FetcherOptions: scanner.FetcherOptions{
419 BatchSize: 100,
420 ParallelFetch: 1,
421 StartIndex: int64(w.ctIndex),
422 Continuous: true,
423 },
424 Matcher: scanner.MatchAll{},
425 PrecertOnly: false,
426 NumWorkers: 1,
427 BufferSize: config.AppConfig.General.BufferSizes.CTLog,
428 })
429
430 scanErr := certScanner.Scan(ctx, w.foundCertCallback, w.foundPrecertCallback)
431 if scanErr != nil {
432 log.Println("Scan error: ", scanErr)
433 return scanErr
434 }
435
436 log.Printf("Exiting worker %s without error!\n", w.ctURL)
437
438 return nil
439 }
440
441 // runTiledWorker runs the worker for a single tiled CT log. This method is blocking.
442 func (w *worker) runTiledWorker(ctx context.Context) error {
443 hc := &http.Client{Timeout: 30 * time.Second}
444
445 // If recovery is enabled and the CT index is set, we start at the saved index. Otherwise, we start at the latest checkpoint.
446 validSavedCTIndexExists := config.AppConfig.General.Recovery.Enabled
447 if !validSavedCTIndexExists {
448 checkpoint, err := FetchCheckpoint(ctx, hc, w.ctURL)
449 if err != nil {
450 log.Printf("Could not get checkpoint for '%s': %s\n", w.ctURL, err)
451 return errFetchingSTHFailed
452 }
453 // Start at the latest checkpoint to skip all the past certificates
454 w.ctIndex = checkpoint.Size
455 }
456
457 // Initialize backoff for polling
458 pollBackoff := &backoff.Backoff{
459 Min: 1 * time.Second,
460 Max: 30 * time.Second,
461 Factor: 2,
462 Jitter: true,
463 }
464
465 // Continuous monitoring loop
466 for {
467 hadNewEntries, err := w.processTiledLogUpdates(ctx, hc)
468 if err != nil {
469 log.Printf("Error processing tiled log updates for '%s': %s\n", w.ctURL, err)
470 return err
471 }
472
473 // Reset backoff if we found new entries
474 if hadNewEntries {
475 pollBackoff.Reset()
476 }
477
478 select {
479 case <-ctx.Done():
480 return ctx.Err()
481 case <-time.After(pollBackoff.Duration()):
482 // Continue to the next iteration
483 }
484 }
485 }
486
487 // processTiledLogUpdates checks for new entries in the tiled log and processes them
488 func (w *worker) processTiledLogUpdates(ctx context.Context, hc *http.Client) (bool, error) {
489 // Fetch current checkpoint
490 checkpoint, err := FetchCheckpoint(ctx, hc, w.ctURL)
491 if err != nil {
492 return false, fmt.Errorf("fetching checkpoint: %w", err)
493 }
494
495 currentTreeSize := checkpoint.Size
496 if currentTreeSize <= w.ctIndex {
497 // No new entries
498 return false, nil
499 }
500
501 // Process entries from current index to new tree size
502 startTile := w.ctIndex / TileSize
503 endTile := currentTreeSize / TileSize
504
505 // Process complete tiles
506 for tileIndex := startTile; tileIndex < endTile; tileIndex++ {
507 if err := w.processTile(ctx, hc, tileIndex, 0); err != nil {
508 return false, fmt.Errorf("processing tile %d: %w", tileIndex, err)
509 }
510 }
511
512 // Process partial tile if exists
513 partialSize := currentTreeSize % TileSize
514 if partialSize > 0 {
515 if err := w.processTile(ctx, hc, endTile, partialSize); err != nil {
516 log.Printf("Warning: error processing partial tile %d: %s\n", endTile, err)
517 // Don't return error for partial tiles as they might be incomplete
518 }
519 }
520
521 return true, nil
522 }
523
524 // processTile processes a single tile from the tiled log.
525 // partialWidth of 0 means full tile, otherwise fetch partial tile with that width.
526 func (w *worker) processTile(ctx context.Context, hc *http.Client, tileIndex uint64, partialWidth uint64) error {
527 leaves, err := FetchTile(ctx, hc, w.ctURL, tileIndex, partialWidth)
528 if err != nil {
529 return fmt.Errorf("fetching tile: %w", err)
530 }
531
532 // Calculate the starting index for entries in this tile
533 baseIndex := tileIndex * TileSize
534
535 for i, leaf := range leaves {
536 entryIndex := baseIndex + uint64(i)
537
538 // Skip entries we've already processed
539 if entryIndex <= w.ctIndex {
540 continue
541 }
542
543 // Convert TileLeaf to RawLogEntry for compatibility with existing parsing
544 rawEntry := ConvertTileLeafToRawLogEntry(leaf, entryIndex)
545
546 // Process the entry using existing callbacks
547 switch leaf.EntryType {
548 case 0:
549 w.foundCertCallback(rawEntry)
550 case 1:
551 w.foundPrecertCallback(rawEntry)
552 default:
553 log.Printf("Unknown entry type %d in tile %d, skipping entry at index %d\n", leaf.EntryType, tileIndex, entryIndex)
554 }
555
556 // Update the index
557 w.ctIndex = entryIndex
558 }
559
560 return nil
561 }
562
563 // foundCertCallback is the callback that handles cases where new regular certs are found.
564 func (w *worker) foundCertCallback(rawEntry *ct.RawLogEntry) {
565 logType := models.SourceIsRFC6962
566 if w.isTiled {
567 logType = models.SourceIsTiled
568 }
569
570 entry, parseErr := ParseCertstreamEntry(rawEntry, w.operatorName, w.name, w.ctURL, logType)
571 if parseErr != nil {
572 log.Println("Error parsing certstream entry: ", parseErr)
573 return
574 }
575
576 entry.Data.UpdateType = "X509LogEntry"
577 w.entryChan <- entry
578
579 atomic.AddInt64(&metrics.ProcessedCerts, 1)
580 }
581
582 // foundPrecertCallback is the callback that handles cases where new precerts are found.
583 func (w *worker) foundPrecertCallback(rawEntry *ct.RawLogEntry) {
584 logType := models.SourceIsRFC6962
585 if w.isTiled {
586 logType = models.SourceIsTiled
587 }
588
589 entry, parseErr := ParseCertstreamEntry(rawEntry, w.operatorName, w.name, w.ctURL, logType)
590 if parseErr != nil {
591 log.Println("Error parsing certstream entry: ", parseErr)
592 return
593 }
594
595 entry.Data.UpdateType = "PrecertLogEntry"
596 w.entryChan <- entry
597
598 atomic.AddInt64(&metrics.ProcessedPrecerts, 1)
599 }
600
601 // certHandler takes the entries out of the entryChan channel and broadcasts them to all clients.
602 // Only a single instance of the certHandler runs per certstream server.
603 func certHandler(entryChan chan models.Entry) {
604 var processed uint64
605
606 for {
607 entry := <-entryChan
608 processed++
609
610 if processed%1000 == 0 {
611 log.Printf("Processed %d entries | Queue length: %d\n", processed, len(entryChan))
612 // Every thousandth entry, we store one certificate as example
613 web.SetExampleCert(entry)
614 }
615
616 // Run JSON encoding in the background and send the result to the clients.
617 web.ClientHandler.Broadcast <- entry
618
619 // Update metrics
620 url := entry.Data.Source.NormalizedURL
621 operator := entry.Data.Source.Operator
622 index := entry.Data.CertIndex
623
624 metrics.Metrics.Inc(operator, url, index)
625 }
626 }
627
628 // getGoogleLogList fetches the list of all CT logs from Google Chromes CT LogList.
629 func getGoogleLogList() (loglist3.LogList, error) {
630 // Download the list of all logs from ctLogInfo and decode JSON
631 resp, err := http.Get(loglist3.LogListURL)
632 if err != nil {
633 return loglist3.LogList{}, err
634 }
635 defer resp.Body.Close()
636
637 if resp.StatusCode != http.StatusOK {
638 return loglist3.LogList{}, errors.New("failed to download loglist")
639 }
640
641 bodyBytes, readErr := io.ReadAll(resp.Body)
642 if readErr != nil {
643 log.Panic(readErr)
644 }
645
646 allLogs, parseErr := loglist3.NewFromJSON(bodyBytes)
647 if parseErr != nil {
648 return loglist3.LogList{}, parseErr
649 }
650
651 return *allLogs, nil
652 }
653
654 // getAllLogs returns a list of all CT logs.
655 func getAllLogs() (loglist3.LogList, error) {
656 var allLogs loglist3.LogList
657 var err error
658
659 // Ability to disable default logs, if the user only wants to monitor custom logs.
660 if !config.AppConfig.General.DisableDefaultLogs {
661 allLogs, err = getGoogleLogList()
662 if err != nil {
663 log.Printf("Error fetching log list from Google: %s\n", err)
664 return loglist3.LogList{}, fmt.Errorf("failed to fetch log list from Google: %w", err)
665 }
666 }
667
668 // Add manually added logs from config to the allLogs list
669 // if config.AppConfig.General.AdditionalLogs == nil {
670 // return allLogs, nil
671 // }
672
673 logFound:
674 for _, additionalLog := range config.AppConfig.General.AdditionalLogs {
675 customLog := loglist3.Log{
676 URL: additionalLog.URL,
677 Description: additionalLog.Description,
678 }
679
680 operatorFound := false
681 for _, operator := range allLogs.Operators {
682 if operator.Name == additionalLog.Operator {
683 operatorFound = true
684
685 for _, ctlog := range operator.Logs {
686 if ctlog.URL == additionalLog.URL {
687 // Log already exists, skip it.
688 break logFound
689 }
690 }
691 // This works, since allLogs.Operators is a slice of pointers.
692 operator.Logs = append(operator.Logs, &customLog)
693 break
694 }
695 }
696
697 if !operatorFound {
698 newOperator := loglist3.Operator{
699 Name: additionalLog.Operator,
700 Logs: []*loglist3.Log{&customLog},
701 }
702 allLogs.Operators = append(allLogs.Operators, &newOperator)
703 }
704 }
705
706 for _, additionalLog := range config.AppConfig.General.AdditionalTiledLogs {
707 customLog := loglist3.TiledLog{
708 MonitoringURL: additionalLog.URL,
709 Description: additionalLog.Description,
710 }
711
712 operatorFound := false
713
714 tiledLogFound:
715 for _, operator := range allLogs.Operators {
716 if operator.Name == additionalLog.Operator {
717 operatorFound = true
718 for _, tl := range operator.TiledLogs {
719 if tl.MonitoringURL == additionalLog.URL {
720 // Log already exists, skip it.
721 break tiledLogFound
722 }
723 }
724 // This works, since allLogs.Operators is a slice of pointers.
725 operator.TiledLogs = append(operator.TiledLogs, &customLog)
726 break
727 }
728 }
729
730 if !operatorFound {
731 newOperator := loglist3.Operator{
732 Name: additionalLog.Operator,
733 TiledLogs: []*loglist3.TiledLog{&customLog},
734 }
735 allLogs.Operators = append(allLogs.Operators, &newOperator)
736 }
737 }
738
739 return allLogs, nil
740 }
741
742 func normalizeCtlogURL(input string) string {
743 input = strings.TrimPrefix(input, "https://")
744 input = strings.TrimPrefix(input, "http://")
745 input = strings.TrimSuffix(input, "/")
746
747 return input
748 }