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 Missing dll failure #1763

Merged
merged 2 commits into from
Dec 2, 2024
Merged

Fix Missing dll failure #1763

merged 2 commits into from
Dec 2, 2024

Conversation

vlabo
Copy link
Member

@vlabo vlabo commented Dec 2, 2024

Summary by CodeRabbit

  • New Features

    • Enhanced error handling for DNS monitor flushing process in connection management.
    • Improved identification and handling of connections to captive portals.
    • Introduced an event manager for initialization events in the OSIntegration module.
  • Bug Fixes

    • Added checks for ETW session initialization in various components to prevent operations on uninitialized sessions.
  • Documentation

    • Minor adjustments to comments and documentation for improved readability and maintainability.
  • Refactor

    • Introduced dedicated session initialization functions to streamline error handling and control flow.
    • Updated method signatures and field types to use pointers for improved memory management.

Copy link
Contributor

coderabbitai bot commented Dec 2, 2024

📝 Walkthrough
📝 Walkthrough

Walkthrough

The pull request introduces several modifications across multiple files, primarily focusing on the ETWSession struct and its methods within the dnsmonitor package. Key changes include altering field types to pointers, enhancing error handling, and restructuring functions for better clarity and robustness. The initializeSessions function is introduced to streamline session initialization, while the DLL loading process is improved with dynamic error handling. These updates collectively enhance the control flow and reliability of the DNS monitoring functionality.

Changes

File Path Change Summary
service/firewall/interception/dnsmonitor/etwlink_windows.go - Updated ETWSession struct field i from integration.ETWFunctions to *integration.ETWFunctions.
- Modified NewSession method to accept a pointer.
- Added nil checks in FlushTrace and DestroySession methods.
service/firewall/interception/dnsmonitor/eventlistener_windows.go - Restructured newListener function to call initializeSessions for ETW session setup.
- Introduced initializeSessions function for centralized session initialization.
- Updated flush method for session initialization check.
service/integration/etw_windows.go - Changed return type of initializeETW from ETWFunctions to *ETWFunctions.
- Adjusted instantiation of ETWFunctions to use a pointer.
service/integration/integration_windows.go - Updated OSSpecific struct's etwFunctions field to *ETWFunctions.
- Enhanced DLL loading error handling in Initialize method with a callback for retries.
- Introduced loadDLL method for DLL loading logic.
service/integration/module.go - Removed states field from OSIntegration struct.
- Added OnInitializedEvent field for event management.
service/network/connection.go - Updated GatherConnectionInfo method to handle errors from the DNS monitor flushing process.
- Refined logic for determining domain and DNS context of connections.

Possibly related PRs

  • Fix deadlocks and process username issue #1738: The changes in this PR involve modifications to error handling and logging, which may relate to the enhanced error handling introduced in the main PR for the ETWSession struct and its methods.

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Outside diff range and nitpick comments (2)
service/firewall/interception/dnsmonitor/etwlink_windows.go (1)

Cleanup is needed in error path to prevent resource leak

The verification confirms that CreateState allocates memory that must be freed by DestroySession. From the DLL source code:

// PM_ETWCreateState allocates memory for the state and initializes the config for the session. PM_ETWDestroySession must be called to avoid leaks.

While the finalizer helps prevent leaks in the normal path, we should explicitly clean up in the error path to ensure immediate resource release:

err := etwSession.i.InitializeSession(etwSession.state)
if err != nil {
+    _ = etwSession.i.DestroySession(etwSession.state)
    return nil, fmt.Errorf("failed to initialize session: %q", err)
}
🔗 Analysis chain

Line range hint 44-56: Verify cleanup in error paths

While the finalizer helps prevent memory leaks, we should ensure proper cleanup in error paths. Currently, if InitializeSession fails, we might leak the state created by CreateState.

Let's check for similar patterns in the codebase:

Consider adding cleanup in the error path:

 err := etwSession.i.InitializeSession(etwSession.state)
 if err != nil {
+    _ = etwSession.i.DestroySession(etwSession.state)
     return nil, fmt.Errorf("failed to initialize session: %q", err)
 }
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for CreateState/DestroySession pairs
rg -B 5 -A 5 "CreateState|DestroySession"

Length of output: 13257

service/network/connection.go (1)

553-557: Consider improving error handling logic.

While the addition of error handling for Flush() is good, the current implementation breaks the retry loop on any error. Consider whether some errors might be temporary and worth retrying.

-					err = module.instance.DNSMonitor().Flush()
-					if err != nil {
-						// Error flushing, dont try again.
-						break
-					}
+					if err = module.instance.DNSMonitor().Flush(); err != nil {
+						// Log the error but continue retrying
+						log.Tracer(pkt.Ctx()).Debugf("network: failed to flush DNS monitor: %v", err)
+						continue
+					}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between ef0995b and 4f8417d.

📒 Files selected for processing (6)
  • service/firewall/interception/dnsmonitor/etwlink_windows.go (5 hunks)
  • service/firewall/interception/dnsmonitor/eventlistener_windows.go (1 hunks)
  • service/integration/etw_windows.go (1 hunks)
  • service/integration/integration_windows.go (2 hunks)
  • service/integration/module.go (2 hunks)
  • service/network/connection.go (1 hunks)
🔇 Additional comments (8)
service/integration/module.go (1)

12-12: LGTM! Good improvement to event handling

The switch from StateMgr to EventMgr provides better reactive handling of initialization events, which aligns well with the PR's goal of improving DLL failure handling. The initialization in the constructor is properly done.

Also applies to: 24-26

service/integration/integration_windows.go (2)

Line range hint 44-64: LGTM! Well-structured DLL loading with proper error handling

The new loadDLL function properly:

  • Finds the DLL path using platform-specific logic
  • Handles loading errors with descriptive messages
  • Initializes ETW functions
  • Notifies listeners of successful initialization

76-79: LGTM! Type consistency improvement

The pointer return type for GetETWInterface maintains consistency with the field type change and improves null safety.

service/firewall/interception/dnsmonitor/etwlink_windows.go (2)

26-29: LGTM! Good defensive programming with nil check

The nil check for etwInterface prevents potential crashes and provides a clear error message.


71-74: LGTM! Consistent nil checks across methods

The addition of nil checks in both FlushTrace and DestroySession methods maintains consistency and prevents potential crashes.

Also applies to: 93-95

service/firewall/interception/dnsmonitor/eventlistener_windows.go (2)

27-38: LGTM! Well-structured error handling for DLL loading.

The implementation properly handles the case of missing DLL by:

  1. Attempting to initialize sessions
  2. If initialization fails, registering a callback to retry when the DLL is loaded
  3. Using proper error propagation

41-51: LGTM! Clean separation of concerns.

The new initializeSessions function nicely encapsulates the session initialization logic, making the code more maintainable and easier to test.

service/integration/etw_windows.go (1)

22-23: LGTM! Improved pointer semantics.

The change to return *ETWFunctions instead of value type is appropriate for struct types and maintains consistency with the rest of the codebase.

Comment on lines 22 to 49
// Try to load dll
err := i.loadDLL()
if err != nil {
log.Errorf("integration: failed to load dll: %s", err)

// listen for event from the updater and try to load again if any.
i.instance.Updates().EventResourcesUpdated.AddCallback("core-dll-loader", func(wc *mgr.WorkerCtx, s struct{}) (cancel bool, err error) {
err = i.loadDLL()
if err != nil {
log.Errorf("integration: failed to load dll: %s", err)
} else {
log.Info("integration: initialize successful after updater event")
}
return false, nil
})

} else {
log.Info("integration: initialize successful")
}
return nil
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codebase verification

Race condition concern is valid and needs synchronization

The verification confirms the race condition concern. There are multiple paths that can trigger DLL loading:

  • Initial loading during Initialize()
  • Callback from EventResourcesUpdated
  • No synchronization mechanism exists to prevent concurrent loading attempts

This could lead to:

  • Multiple simultaneous DLL loading attempts
  • Race conditions when accessing i.os.dll and i.os.etwFunctions
  • Potential resource leaks if a new DLL is loaded while the old one is still in use

Recommendations:

  • Add a mutex to protect the DLL loading operation
  • Ensure proper cleanup of existing DLL before loading a new one
  • Consider adding a state check to prevent redundant loading attempts
🔗 Analysis chain

Consider potential race condition in error handling

In the error path, we register a callback that might attempt to load the DLL concurrently with other initialization attempts. Consider adding synchronization to prevent multiple simultaneous loading attempts.

Let's verify if there are other places in the codebase that might trigger concurrent loading:


Let me gather more information about potential concurrent access to the DLL loading functionality.


Let me check one more aspect to understand if there's any mutex or synchronization mechanism already in place.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for other potential DLL loading triggers
rg -A 5 "loadDLL|LoadDLL" 

Length of output: 2259


Script:

#!/bin/bash
# Search for initialization and usage of OSIntegration to understand concurrent access patterns
ast-grep --pattern 'type OSIntegration struct {
  $$$
}'

# Also search for any calls to initialize the integration
rg -A 3 "NewOSIntegration|OSIntegration.*Initialize"

Length of output: 1564


Script:

#!/bin/bash
# Search for any synchronization mechanisms in the integration package
rg -A 3 "sync\.|Mutex|RWMutex|Lock|Unlock" service/integration/

# Also check the complete implementation of loadDLL
ast-grep --pattern 'func (i *OSIntegration) loadDLL() error {
  $$$
}'

Length of output: 1699

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Outside diff range and nitpick comments (3)
service/integration/integration_windows.go (1)

Line range hint 51-71: Consider additional error handling in loadDLL

While the function handles basic errors, there are a few improvements to consider:

  1. The DLL release in case of ETW initialization failure
  2. The state cleanup if notification fails

Apply this improvement:

 func (i *OSIntegration) loadDLL() error {
     // Find path to the dll.
     file, err := updates.GetPlatformFile("dll/portmaster-core.dll")
     if err != nil {
         return err
     }
     // Load the DLL.
     i.os.dll, err = windows.LoadDLL(file.Path())
     if err != nil {
         return fmt.Errorf("failed to load dll: %q", err)
     }
+    
+    // Use defer for cleanup in case of initialization failure
+    var initialized bool
+    defer func() {
+        if !initialized && i.os.dll != nil {
+            _ = i.os.dll.Release()
+            i.os.dll = nil
+        }
+    }()
 
     // Enumerate all needed dll functions.
     i.os.etwFunctions, err = initializeETW(i.os.dll)
     if err != nil {
         return err
     }
 
     // Notify listeners
     i.OnInitializedEvent.Submit(struct{}{})
+    initialized = true
 
     return nil
 }
service/firewall/interception/dnsmonitor/etwlink_windows.go (1)

71-74: Consider consolidating duplicate nil checks

The nil check for l.i is duplicated in both FlushTrace and DestroySession. Consider extracting to a helper method.

+func (l *ETWSession) checkInitialized() error {
+    if l.i == nil {
+        return fmt.Errorf("session not initialized")
+    }
+    return nil
+}

 func (l *ETWSession) FlushTrace() error {
-    if l.i == nil {
-        return fmt.Errorf("session not initialized")
-    }
+    if err := l.checkInitialized(); err != nil {
+        return err
+    }
     // ... rest of the code

 func (l *ETWSession) DestroySession() error {
-    if l.i == nil {
-        return fmt.Errorf("session not initialized")
-    }
+    if err := l.checkInitialized(); err != nil {
+        return err
+    }
     // ... rest of the code

Also applies to: 93-95

service/firewall/interception/dnsmonitor/eventlistener_windows.go (1)

55-57: Consistent error message style

The error message "etw not initialized" should follow the package prefix pattern used elsewhere.

 func (l *Listener) flush() error {
     if l.etw == nil {
-        return fmt.Errorf("etw not initialized")
+        return fmt.Errorf("dnsmonitor: ETW session not initialized")
     }
     return l.etw.FlushTrace()
 }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 4f8417d and ed2338f.

📒 Files selected for processing (4)
  • service/firewall/interception/dnsmonitor/etwlink_windows.go (5 hunks)
  • service/firewall/interception/dnsmonitor/eventlistener_windows.go (1 hunks)
  • service/integration/integration_windows.go (2 hunks)
  • service/network/connection.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • service/network/connection.go
🔇 Additional comments (3)
service/integration/integration_windows.go (2)

28-43: Synchronization improvement addresses race condition

The added mutex properly addresses the previously identified race condition concern by preventing concurrent DLL loading attempts in the callback.


83-86: Consider thread safety for GetETWInterface

The function accesses i.os.etwFunctions without synchronization. While pointer reads are atomic, consider adding RLock if the pointer can be modified concurrently.

Let's verify if there are concurrent modifications to etwFunctions:

Consider adding read lock:

 func (i *OSIntegration) GetETWInterface() *ETWFunctions {
+    i.mu.RLock()
+    defer i.mu.RUnlock()
     return i.os.etwFunctions
 }
service/firewall/interception/dnsmonitor/etwlink_windows.go (1)

26-29: Proper nil check for ETW interface

Good addition of the nil check for etwInterface parameter. This prevents potential panic and provides clear error message.

Comment on lines +27 to 37
err := initializeSessions(module, listener)
if err != nil {
return nil, err
// Listen for event if the dll has been loaded
module.instance.OSIntegration().OnInitializedEvent.AddCallback("loader-listener", func(wc *mgr.WorkerCtx, s struct{}) (cancel bool, err error) {
err = initializeSessions(module, listener)
if err != nil {
return false, err
}
return true, nil
})
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Consider error logging in initialization callback

The callback silently returns errors which might make debugging difficult.

 module.instance.OSIntegration().OnInitializedEvent.AddCallback("loader-listener", func(wc *mgr.WorkerCtx, s struct{}) (cancel bool, err error) {
     err = initializeSessions(module, listener)
     if err != nil {
+        log.Errorf("dnsmonitor: failed to initialize sessions after DLL load: %v", err)
         return false, err
     }
     return true, nil
 })
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
err := initializeSessions(module, listener)
if err != nil {
return nil, err
// Listen for event if the dll has been loaded
module.instance.OSIntegration().OnInitializedEvent.AddCallback("loader-listener", func(wc *mgr.WorkerCtx, s struct{}) (cancel bool, err error) {
err = initializeSessions(module, listener)
if err != nil {
return false, err
}
return true, nil
})
}
err := initializeSessions(module, listener)
if err != nil {
// Listen for event if the dll has been loaded
module.instance.OSIntegration().OnInitializedEvent.AddCallback("loader-listener", func(wc *mgr.WorkerCtx, s struct{}) (cancel bool, err error) {
err = initializeSessions(module, listener)
if err != nil {
log.Errorf("dnsmonitor: failed to initialize sessions after DLL load: %v", err)
return false, err
}
return true, nil
})
}

Comment on lines +41 to +51
func initializeSessions(module *DNSMonitor, listener *Listener) error {
var err error
listener.etw, err = NewSession(module.instance.OSIntegration().GetETWInterface(), listener.processEvent)
if err != nil {
return err
}
// Start listener
module.mgr.Go("etw-dns-event-listener", func(w *mgr.WorkerCtx) error {
return listener.etw.StartTrace()
})

return listener, nil
return nil
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Consider cleanup on initialization failure

If StartTrace fails in the worker, the ETW session remains initialized. Consider adding cleanup.

 func initializeSessions(module *DNSMonitor, listener *Listener) error {
     var err error
     listener.etw, err = NewSession(module.instance.OSIntegration().GetETWInterface(), listener.processEvent)
     if err != nil {
         return err
     }
+    
+    initialized := make(chan error, 1)
     // Start listener
     module.mgr.Go("etw-dns-event-listener", func(w *mgr.WorkerCtx) error {
-        return listener.etw.StartTrace()
+        if err := listener.etw.StartTrace(); err != nil {
+            initialized <- err
+            return err
+        }
+        initialized <- nil
+        return nil
     })
+    
+    // Wait for initialization
+    if err := <-initialized; err != nil {
+        _ = listener.etw.DestroySession()
+        listener.etw = nil
+        return fmt.Errorf("failed to start trace: %w", err)
+    }
     return nil
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
func initializeSessions(module *DNSMonitor, listener *Listener) error {
var err error
listener.etw, err = NewSession(module.instance.OSIntegration().GetETWInterface(), listener.processEvent)
if err != nil {
return err
}
// Start listener
module.mgr.Go("etw-dns-event-listener", func(w *mgr.WorkerCtx) error {
return listener.etw.StartTrace()
})
return listener, nil
return nil
func initializeSessions(module *DNSMonitor, listener *Listener) error {
var err error
listener.etw, err = NewSession(module.instance.OSIntegration().GetETWInterface(), listener.processEvent)
if err != nil {
return err
}
initialized := make(chan error, 1)
// Start listener
module.mgr.Go("etw-dns-event-listener", func(w *mgr.WorkerCtx) error {
if err := listener.etw.StartTrace(); err != nil {
initialized <- err
return err
}
initialized <- nil
return nil
})
// Wait for initialization
if err := <-initialized; err != nil {
_ = listener.etw.DestroySession()
listener.etw = nil
return fmt.Errorf("failed to start trace: %w", err)
}
return nil
}

@dhaavi dhaavi merged commit 6e173e3 into develop Dec 2, 2024
6 checks passed
@dhaavi dhaavi deleted the fix/missing-dll-failure branch December 2, 2024 14:23
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants