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

Prevent file handles from leaking on failed open. #67

Merged
merged 2 commits into from
Apr 1, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion webcam.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,14 +35,21 @@ type Control struct {
// Checks if device is a v4l2 device and if it is
// capable to stream video
func Open(path string) (*Webcam, error) {

handle, err := unix.Open(path, unix.O_RDONLY|unix.O_NONBLOCK, 0666)
if err != nil {
return nil, err
}
if handle < 0 {
return nil, fmt.Errorf("failed to open %v", path)
}
// At this point the handle is valid and must be return or closed
success := false // If this is not set true prior to function exit we assume error and close the handle
defer func() {
if !success {
// Since the handle is not returned on error we must close it or leak
unix.Close(handle)
}
}()
fd := uintptr(handle)

supportsVideoCapture, supportsVideoStreaming, err := checkCapabilities(fd)
Expand All @@ -63,6 +70,7 @@ func Open(path string) (*Webcam, error) {
w.fd = fd
w.bufcount = 256
w.pollFds = []unix.PollFd{{Fd: int32(fd), Events: unix.POLLIN}}
success = true
return w, nil
}

Expand Down