#469·haven

[Resource Leak] FileOutputStream not closed in MonitorActivity.initMonitor()

Author: CyberSecurity-NCCCreated Dec 23, 2025Updated Dec 23, 2025

Summary

The method initMonitor() in MonitorActivity creates a FileOutputStream to write the .nomedia file but fails to close it. This results in a file descriptor (FD) leak every time the monitoring service is initialized.

  • Affected File: src/main/java/org/havenapp/main/MonitorActivity.java
  • Method: private void initMonitor()
  • Lines: 358-361

Impact

  • Resource Leak: The anonymous FileOutputStream instance is never explicitly closed. While the Garbage Collector may eventually reclaim it, relying on finalization is unpredictable.
  • Stability: If initMonitor() is called repeatedly (e.g., multiple start/stop monitoring cycles), leaked file descriptors can accumulate, potentially leading to "Too many open files" errors or stability issues on resource-constrained devices.

Severity: Medium (Recurring leak on specific user actions).

Code Analysis

Current Implementation:

java
try {
    File fileImageDir = new File(Environment.getExternalStorageDirectory(), preferences.getDefaultMediaStoragePath());
    fileImageDir.mkdirs();
    // ISSUE: Anonymous FileOutputStream is created and written to, but never closed.
    new FileOutputStream(new File(fileImageDir, ".nomedia")).write(0);
} catch (IOException e) {
    Log.e("Monitor", "unable to init media storage directory", e);
}

Suggested Fix

Using try-with-resources to ensure the stream is explicitly closed is recommended. Additionally, checking if the file already exists can avoid unnecessary I/O operations.

Suggestion:

java
try {
    File fileImageDir = new File(Environment.getExternalStorageDirectory(), preferences.getDefaultMediaStoragePath());
    if (!fileImageDir.exists()) {
        fileImageDir.mkdirs();
    }
    
    File noMedia = new File(fileImageDir, ".nomedia");
    // Fix: Use try-with-resources to ensure the stream is closed
    try (FileOutputStream fos = new FileOutputStream(noMedia)) {
        fos.write(0);
    }
} catch (IOException e) {
    Log.e("Monitor", "unable to init media storage directory", e);
}

Context & Acknowledgement:

This issue was identified during our academic research on Java resource management. We have manually verified this finding.

Thank you for maintaining haven! We hope this report helps.