Skip to content

Commit

Permalink
fix(api): Protects DisableConfigDir from concurrent access using mutex
Browse files Browse the repository at this point in the history
  • Loading branch information
yyoshiki41 authored and hhrutter committed Jul 25, 2023
1 parent fff3853 commit 7c02e0d
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 0 deletions.
9 changes: 9 additions & 0 deletions pkg/api/api.go
Expand Up @@ -37,6 +37,7 @@ import (
"bufio"
"io"
"os"
"sync"
"time"

"github.com/pdfcpu/pdfcpu/pkg/log"
Expand Down Expand Up @@ -160,11 +161,19 @@ func EnsureDefaultConfigAt(path string) error {
return model.EnsureDefaultConfigAt(path)
}

var (
// mutexDisableConfigDir protects DisableConfigDir from concurrent access.
// NOTE: This is not a guard for model.ConfigPath variable.
mutexDisableConfigDir sync.Mutex
)

// DisableConfigDir disables the configuration directory.
// Any needed default configuration will be loaded from configuration.go
// Since the config dir also contains the user font dir, this also limits font usage to the default core font set
// No user fonts will be available.
func DisableConfigDir() {
mutexDisableConfigDir.Lock()
defer mutexDisableConfigDir.Unlock()
// Call if you don't want to use a specific configuration
// and also do not need to use user fonts.
model.ConfigPath = "disable"
Expand Down
32 changes: 32 additions & 0 deletions pkg/api/api_test.go
@@ -0,0 +1,32 @@
package api

import (
"sync"
"testing"

"github.com/pdfcpu/pdfcpu/pkg/pdfcpu/model"
)

func TestDisableConfigDir(t *testing.T) {
t.Parallel()
DisableConfigDir()

if model.ConfigPath != "disable" {
t.Errorf("model.ConfigPath != \"disable\" (%s)", model.ConfigPath)
}
}

func TestDisableConfigDir_Parallel(t *testing.T) {
t.Parallel()

var wg sync.WaitGroup
for i := 0; i < 100; i++ {
wg.Add(1)
go func() {
defer wg.Done()
DisableConfigDir()
}()
}
wg.Wait()
t.Log("DisableConfigDir is passed")
}
4 changes: 4 additions & 0 deletions pkg/pdfcpu/model/configuration.go
Expand Up @@ -212,6 +212,10 @@ type Configuration struct {
//
// default: Ensure config dir at default location
// disable: Disable config dir usage
//
// WARNING: This is a global variable and should be safe for concurrent use.
// If you want to change disable config dir,
// call api.DisableConfigDir() that is concurrency safe instead of changing directly.
var ConfigPath string = "default"

var loadedDefaultConfig *Configuration
Expand Down

0 comments on commit 7c02e0d

Please sign in to comment.