Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(api): Protects DisableConfigDir from concurrent access using mutex #604

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
9 changes: 9 additions & 0 deletions pkg/api/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ import (
"bufio"
"io"
"os"
"sync"
"time"

"github.com/pdfcpu/pdfcpu/pkg/log"
Expand Down Expand Up @@ -161,11 +162,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
Original file line number Diff line number Diff line change
@@ -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
Original file line number Diff line number Diff line change
Expand Up @@ -207,6 +207,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