Skip to content

Conversation

@maschad
Copy link
Owner

@maschad maschad commented Jun 9, 2025

The file download issue in release mode was due to inverted file transfer logic and incorrect path resolution.

The fix involved:

  • Correcting File Transfer Flow:
    • Previously, the client attempted to send files when requesting downloads, and the host tried to receive.
    • The logic in src/service/node.rs was reversed: the client now sends a file path request, then receives the file data. The host receives the request, resolves the path, and sends the file.
  • Implementing Absolute Path Resolution:
    • A absolute_path: Option<PathBuf> field was added to DirectoryItem in src/app.rs, marked with %23[serde(skip)] to prevent network serialization.
    • In src/main.rs, handle_host_mode was updated to populate this absolute_path when sharing items.
    • In src/service/node.rs, a path_mappings: HashMap<PeerId, HashMap<String, PathBuf>> was added to EventLoop.
    • The InsertDirectoryItems command handler now populates this path_mappings with absolute paths.
    • The host's incoming stream handler uses these mappings to find the actual file location when a download is requested, ensuring files are found regardless of the working directory.

These changes ensure the host correctly identifies and serves files using absolute paths, resolving the discrepancy between debug and release environments.

Summary by CodeRabbit

  • New Features
    • Enhanced file transfer protocol to support bidirectional, request-response style transfers, allowing clients to explicitly request files by path and hosts to respond with the correct file.
  • Improvements
    • Improved accuracy of file location resolution by using absolute paths during file sharing and transfer.
    • Added internal mechanisms to manage and map shared file paths for more reliable file transfers.

@coderabbitai
Copy link

coderabbitai bot commented Jun 9, 2025

Walkthrough

The changes introduce a bidirectional file transfer protocol enhancement, adding absolute path handling for shared directory items. The DirectoryItem struct now includes an optional absolute path field, and directory item creation and host-mode logic are updated to utilize absolute paths. The node service maintains peer-specific path mappings and implements a request-response file transfer protocol.

Changes

File(s) Change Summary
src/app.rs Added absolute_path: Option<PathBuf> (with #[serde(skip)]) to DirectoryItem; updated create_directory_item to initialize this field.
src/main.rs Modified host-mode logic to compute and use absolute paths for shared items; updated construction of DirectoryItem with absolute path context.
src/service/node.rs Added path_mappings to EventLoop; enhanced file transfer protocol to request files by path; updated handling of directory items and file requests using absolute paths.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant NodeService
    participant Host

    Client->>NodeService: RequestFiles (list of file paths)
    loop For each file
        NodeService->>Host: Open stream to Host
        NodeService->>Host: Send file path length + path bytes
        Host->>NodeService: Look up absolute path via path_mappings
        alt Path found
            Host->>NodeService: Stream file contents
            NodeService->>Client: Receive file (success)
        else Path not found
            Host->>NodeService: Log error, close stream
            NodeService->>Client: Mark as failed
        end
    end
    NodeService->>Client: Emit DownloadCompleted/DownloadFailed events
Loading

Poem

In the warren of bytes, a new path appears,
With absolute clarity, it now perseveres.
Rabbits map tunnels from peer to peer,
File requests hop swiftly, the routes are clear.
A hop, a skip, a transfer anew—
Sharing the carrots of data with you! 🥕

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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 generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this 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

@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 comments (1)
src/main.rs (1)

295-308: 🛠️ Refactor suggestion

Reading every file for preview on every 50 ms tick is expensive
handle_host_mode re-opens and reads up to 4 KB of every shared file each iteration, even when nothing changed. For a directory with many large files this will thrash the disk and allocate repeatedly.
Cache the preview string inside DirectoryItem (together with a hash / modified time) and rebuild only when the file actually changes.

🧹 Nitpick comments (2)
src/app.rs (2)

34-46: Addition of absolute_path looks correct but will now participate in Eq / PartialEq derives
Because the field is part of the struct, two DirectoryItems that differ only by absolute_path will be considered different. On the host side you continually rebuild the vector every 50 ms, which means absolute_path’s PathBuf instances will differ in allocation identity and sometimes in canonicalisation (e.g. after symlink-resolution).
This can trigger unnecessary UI refreshes and network traffic when you compare vectors (!=) in handle_download_mode.
If the absolute path is only an implementation detail, consider:

 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
 pub struct DirectoryItem {
@@
-    #[serde(skip)]
-    pub absolute_path: Option<PathBuf>,
+    #[serde(skip)]
+    #[compare_ignore] // <- custom derive or manual PartialEq implementation
+    pub absolute_path: Option<PathBuf>,
 }

or supply a manual PartialEq / Eq impl that ignores the field.


191-201: absolute_path is initialised to None for local filesystem listing
This is fine for the UI/client side, but any host-side code that later relies on a non-None value must remember to overwrite it. At the moment only handle_host_mode does so; if other callers re-use create_directory_item they may forget to set it and silently break downloads.
Recommend adding a helper DirectoryItem::with_absolute_path(item, path) or a dedicated constructor for the host code to avoid accidental omissions.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 5c5eebf and 2f6b3cf.

📒 Files selected for processing (3)
  • src/app.rs (2 hunks)
  • src/main.rs (2 hunks)
  • src/service/node.rs (6 hunks)
🔇 Additional comments (2)
src/main.rs (1)

268-285: Lowest-common-ancestor algorithm can misbehave for disjoint selections
If the user shares two items on different drives (/mnt/a vs C:\ on Windows) virtual_root will end up as the first path’s root because the loop stops at the first ancestor that matches, not the true LCA across all paths.
Consider using a crate such as pathdiff or implement a proper LCA that iterates over all candidates before deciding.

src/service/node.rs (1)

239-259: Path-mapping table is a clean solution
Nicely separates network-visible paths from real filesystem locations and prevents path-traversal.

Comment on lines +526 to +573
// Open a new stream for each file
match stream_control
.open_stream(peer_id, JUNKANOO_FILE_PROTOCOL)
.await
{
Ok(mut stream) => {
// Send the file request to the host
let path_bytes = file_name.as_bytes();
let path_len = u32::try_from(path_bytes.len()).unwrap();

// Send path length
if let Err(e) = stream.write_all(&path_len.to_be_bytes()).await {
tracing::error!("Failed to send path length for file '{}': {}", file_name, e);
failed_transfers.push(file_name);
continue;
}

// Send path
if let Err(e) = stream.write_all(path_bytes).await {
tracing::error!("Failed to send path for file '{}': {}", file_name, e);
failed_transfers.push(file_name);
continue;
}

// Now receive the file
let mut receiver = FileReceiver::new();
match receiver.receive_file(&mut stream).await {
Ok(received_file_name) => {
tracing::info!("Successfully received file '{}'", received_file_name);
successful_transfers.push(file_name);
}
Err(e) => {
tracing::error!(
"Failed to open stream for file '{}': {}",
"Failed to receive file '{}': {}",
file_name,
e
);
failed_transfers.push(file_name);
}
}
}

if !successful_transfers.is_empty() {
event_sender
.send(Event::DownloadCompleted(successful_transfers))
.await
.expect("Event receiver not to be dropped.");
}

if failed_transfers.is_empty() {
let _ = sender.send(Ok(Vec::new()));
} else {
let failed_files = failed_transfers.join(", ");
event_sender
.send(Event::DownloadFailed(failed_transfers))
.await
.expect("Event receiver not to be dropped.");

let _ = sender.send(Err(Box::new(std::io::Error::other(format!(
"Failed to transfer files: {failed_files}"
)))
as Box<dyn Error + Send>));
Err(e) => {
tracing::error!(
"Failed to open stream for file '{}': {}",
file_name,
e
);
failed_transfers.push(file_name);
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

No length guard when sending path length
u32::try_from(path_bytes.len()).unwrap() will panic if the path exceeds u32::MAX, and you’re sending whatever length the client chooses to the host (which must also validate).
Add the same MAX_PATH_LEN guard before conversion and return a user-visible error instead of panicking.

🤖 Prompt for AI Agents
In src/service/node.rs between lines 526 and 573, the code converts the file
path length to u32 without checking if it exceeds u32::MAX, which can cause a
panic. Add a check before the conversion to ensure the path length does not
exceed MAX_PATH_LEN, and if it does, return a user-visible error instead of
unwrapping and panicking. This prevents crashes by validating the path length
before sending it.

Comment on lines +288 to +304
let mut len_bytes = [0u8; 4];
if let Err(e) = stream.read_exact(&mut len_bytes).await {
tracing::error!("Failed to read file path length: {}", e);
drop(permit);
return;
}
Err(e) => {
tracing::error!("Failed to receive file from peer {}: {}", peer, e);
let path_len = u32::from_be_bytes(len_bytes) as usize;

let mut path_bytes = vec![0u8; path_len];
if let Err(e) = stream.read_exact(&mut path_bytes).await {
tracing::error!("Failed to read file path: {}", e);
drop(permit);
return;
}

let requested_path = match String::from_utf8(path_bytes) {
Ok(path) => path,
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Untrusted peer controls allocation size – potential DoS
path_len is read from the wire and used to allocate Vec<u8> without bounds.
A malicious peer could send 0xFFFF_FFFF, forcing a 4 GB allocation and crashing the host.

-let path_len = u32::from_be_bytes(len_bytes) as usize;
+const MAX_PATH_LEN: usize = 4096; // sane upper bound
+let path_len = u32::from_be_bytes(len_bytes) as usize;
+if path_len == 0 || path_len > MAX_PATH_LEN {
+    tracing::warn!("Rejecting request with suspicious path length {}", path_len);
+    drop(permit);
+    return;
+}

Similar validation should be applied when sending the request (request_files).

🤖 Prompt for AI Agents
In src/service/node.rs around lines 288 to 304, the code reads path_len from the
network and uses it directly to allocate a vector, which can lead to a large
allocation and potential DoS. Fix this by adding a validation step after reading
path_len to ensure it is within a reasonable maximum size before allocating the
vector. Reject or handle requests with path_len exceeding this limit gracefully.
Also, apply similar size validation when sending requests in the request_files
function to prevent oversized allocations.

@maschad maschad closed this Jun 9, 2025
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.

3 participants