Skip to content

Dev Docs Components AFPD

Andy Lemin edited this page Aug 16, 2025 · 2 revisions

WIP - ALL LINKS IN THIS WIKI STRUCTURE ARE CURRENTLY BROKEN DURING WIKI MIGRATION

THESE ARE COMMUNITY DOCS

AFP Daemon (afpd)

Overview

The afpd daemon is the core component of Netatalk that implements the Apple Filing Protocol (AFP) server functionality. It handles client connections, processes AFP commands, manages file operations, and coordinates with other system components to provide native Mac file sharing services.

Implementation Files

  • etc/afpd/main.c - Main daemon entry point and process management
  • etc/afpd/afp_config.c - Configuration parsing and initialization
  • etc/afpd/afp_options.c - Command-line option processing
  • etc/afpd/messages.c - Server message and attention handling
  • etc/afpd/status.c - Server status and capability reporting

Architecture

Process Model

afpd uses a master-worker process architecture:

  • Master Process: Listens for incoming connections and manages worker processes
  • Worker Processes: Handle individual client sessions (one process per connection)
  • Connection Multiplexing: Uses event-driven I/O for efficient connection handling
graph TB
    subgraph "afpd Master Process"
        A[Connection Listener]
        B[Process Manager]
        C[Configuration Handler]
    end
    
    subgraph "Worker Processes"
        D[Client Session 1]
        E[Client Session 2]
        F[Client Session N]
    end
    
    subgraph "Shared Resources"
        G[Volume Configuration]
        H[Authentication Modules]
        I[CNID Database]
    end
    
    A --> D
    A --> E
    A --> F
    B --> D
    B --> E
    B --> F
    C --> G
    D --> H
    D --> I
Loading

Core Components

1. Network Layer

  • DSI Protocol Handler: Manages AFP over TCP/IP connections
  • ASP Protocol Handler: Manages AFP over AppleTalk connections
  • Connection State Management: Tracks session state and cleanup
  • Protocol Multiplexing: Supports both DSI and ASP simultaneously

Implementation Files:

  • etc/afpd/afp_dsi.c - DSI protocol handler and TCP/IP connection management
  • etc/afpd/afp_asp.c - ASP protocol handler and AppleTalk connection management
  • libatalk/dsi/ - DSI protocol implementation library
  • libatalk/asp/ - ASP protocol implementation library

2. AFP Command Processor

  • Command Dispatch: Routes AFP commands to appropriate handlers
  • Request Validation: Validates command parameters and permissions
  • Response Generation: Formats and sends AFP responses
  • Error Handling: Manages AFP error codes and recovery

Implementation Files:

  • etc/afpd/switch.c - Main AFP command dispatcher and routing
  • etc/afpd/afp_util.c - Common AFP utilities and helper functions
  • include/atalk/afp.h - AFP protocol definitions and constants

3. Authentication System

  • UAM Integration: Loads and manages User Authentication Modules
  • Session Management: Maintains authenticated user sessions
  • Access Control: Enforces volume and file-level permissions
  • Security Context: Manages user identity and group membership

Implementation Files:

  • etc/afpd/auth.c - Authentication handling and session management
  • etc/afpd/uam.c - User Authentication Module loading and interface
  • etc/uams/ - Authentication module implementations (DHX, DHX2, PAM, etc.)
  • include/atalk/uam.h - UAM interface definitions

4. Volume Manager

  • Volume Discovery: Enumerates available volumes for clients
  • Mount Management: Handles volume mounting and unmounting
  • Permission Checking: Validates user access to volumes
  • Configuration Integration: Applies volume-specific settings

Implementation Files:

  • etc/afpd/volume.c - Volume management and configuration
  • etc/afpd/enumerate.c - Volume enumeration and discovery
  • etc/afpd/afp_vols.c - Volume-specific AFP operations
  • libatalk/util/volinfo.c - Volume information utilities

5. File Operations

  • File Access: Implements AFP file operations (open, read, write, close)
  • Directory Operations: Handles directory creation, enumeration, deletion
  • Fork Management: Manages data and resource forks
  • Metadata Handling: Processes file attributes and extended metadata

Implementation Files:

  • etc/afpd/file.c - File operations and fork management
  • etc/afpd/filedir.c - File and directory parameter handling
  • etc/afpd/fork.c - Fork management and I/O operations
  • etc/afpd/ofork.c - Open fork tracking and management
  • etc/afpd/desktop.c - Desktop database and file type handling

6. Directory Cache

  • Performance Optimization: Caches frequently accessed directory information
  • CNID Integration: Coordinates with CNID system for file identification
  • Cache Invalidation: Maintains cache consistency with filesystem changes
  • Memory Management: Efficient cache storage and cleanup

Implementation Files:

  • etc/afpd/directory.c - Directory operations and caching
  • etc/afpd/hash.c - Hash table implementation for directory cache
  • libatalk/util/bstring.c - String utilities for path handling

Key Data Structures

Implementation Files

  • include/atalk/afp.h - Core AFP data structure definitions
  • include/atalk/volume.h - Volume structure definitions
  • include/atalk/directory.h - Directory cache structure definitions
  • etc/afpd/globals.h - Global variables and configuration structures

AFPObj Structure

The main AFP object that maintains session state:

typedef struct AFPObj {
    void *handle;               // Protocol-specific handle (DSI/ASP)
    char *username;             // Authenticated username
    char *password;             // User password (temporary)
    struct AFPVolume *volumes;  // Available volumes
    struct auth_methods *auth;  // Authentication methods
    
    // Protocol information
    int proto;                  // AFPPROTO_DSI or AFPPROTO_ASP
    AFPUserBytes (*attention)();// Attention handler
    
    // Configuration
    struct afp_options *options;// Server options
    struct AFPConfig *config;   // Configuration data
    
    // Runtime state
    uid_t uid;                  // User ID
    gid_t gid;                  // Group ID
    time_t time;               // Current time
    int logfd;                 // Log file descriptor
} AFPObj;

Volume Structure

Represents a shared volume:

struct vol {
    struct vol *v_next;         // Next volume in list
    char *v_localname;          // Local filesystem path
    char *v_name;               // AFP volume name
    char *v_password;           // Volume password
    
    // Volume attributes
    uint16_t v_flags;           // Volume flags
    mode_t v_perm;              // Default permissions
    mode_t v_dperm;             // Default directory permissions
    
    // CNID information
    struct _cnid_module *v_cdb; // CNID database handle
    
    // Extended attributes
    char *v_cnidscheme;         // CNID scheme
    char *v_dbpath;             // Database path
    
    // Spotlight support
    int v_qfd;                  // Query file descriptor
};

Directory Entry Cache

Optimizes directory operations:

struct dir {
    struct dir *d_parent;       // Parent directory
    struct dir *d_child;        // First child directory
    struct dir *d_next;         // Next sibling directory
    
    char *d_m_name;             // Mac filename
    char *d_u_name;             // Unix filename
    
    cnid_t d_did;               // Directory ID (CNID)
    dev_t d_dev;                // Device number
    ino_t d_inode;              // Inode number
    
    time_t d_ctime;             // Creation time
    time_t d_mtime;             // Modification time
    
    uint16_t d_rights;          // Access rights cache
    struct dir *d_fullpath;     // Full path cache
};

AFP Command Implementation

Implementation Files

  • etc/afpd/afp_*.c - Individual AFP command implementations
  • etc/afpd/catsearch.c - Catalog search implementation
  • etc/afpd/extattrs.c - Extended attributes handling
  • etc/afpd/unix.c - Unix-specific file operations

Command Processing Flow

sequenceDiagram
    participant Client as Mac Client
    participant DSI as DSI Handler
    participant Switch as Command Switch
    participant Handler as AFP Handler
    participant Volume as Volume Manager
    participant CNID as CNID System
    
    Client->>DSI: AFP Command (FPOpenVol)
    DSI->>Switch: Parse command
    Switch->>Handler: Route to handler
    Handler->>Volume: Validate volume access
    Volume->>CNID: Initialize CNID DB
    CNID-->>Volume: Database ready
    Volume-->>Handler: Volume opened
    Handler-->>Switch: Success response
    Switch-->>DSI: Format response
    DSI-->>Client: AFP Response
Loading

Key AFP Commands

Session Management

  • FPLogin: User authentication and session establishment
  • FPLoginExt: Extended authentication with additional options
  • FPLogout: Session termination and cleanup
  • FPGetUserInfo: Retrieve user information and capabilities

Volume Operations

  • FPGetSrvrParms: Get server parameters and volume list
  • FPOpenVol: Open volume for access
  • FPCloseVol: Close volume and cleanup resources
  • FPGetVolParms: Get volume parameters and statistics

File Operations

  • FPCreateFile: Create new file with specified parameters
  • FPOpenFork: Open file fork (data or resource)
  • FPCloseFork: Close file fork and flush data
  • FPRead: Read data from file fork
  • FPWrite: Write data to file fork
  • FPDelete: Delete file or directory

Directory Operations

  • FPCreateDir: Create new directory
  • FPEnumerate: Enumerate directory contents
  • FPGetFileDirParms: Get file/directory parameters
  • FPSetFileDirParms: Set file/directory parameters
  • FPCatSearch: Search for files matching criteria

Integration Points

Implementation Files

  • libatalk/cnid/ - CNID database interface implementations
  • etc/cnid_dbd/cnid_metad.c - CNID metadata daemon interface
  • etc/afpd/spotlight.c - Spotlight search integration
  • libatalk/compat/ - Platform compatibility layer

CNID Database Integration

// CNID operations in afpd
cnid_t cnid_add(struct cnid_db *cdb, 
                const struct stat *st,
                cnid_t did, 
                const char *name, 
                size_t len, 
                char *hint);

cnid_t cnid_get(struct cnid_db *cdb, 
                cnid_t did, 
                const char *name, 
                size_t len);

int cnid_update(struct cnid_db *cdb, 
                cnid_t id, 
                const struct stat *st,
                cnid_t did, 
                const char *name, 
                size_t len);

Authentication Module Interface

// UAM registration and usage
struct uam_export {
    int uam_setup;
    int uam_checkuser;
    int uam_login;
    int uam_logincont;
    int uam_logout;
};

// UAM module loading
void *uam_load(const char *path, const char *name);
struct uam_export *uam_attach(void *handle, const char *name);

Volume Configuration

// Volume initialization
struct vol *getvolbyvid(const uint16_t vid);
struct vol *getvolbypath(const char *path);
int load_volumes(struct AFPObj *obj);
void unload_volumes(struct AFPObj *obj);

Performance Optimizations

Implementation Files

  • etc/afpd/afp_zeroconf.c - Zero-configuration networking optimizations
  • libatalk/util/server_child.c - Process pool management
  • libatalk/util/queue.h - Queue data structures for performance
  • etc/afpd/afp_avahi.c - Service discovery optimizations

Connection Management

  • Connection Pooling: Reuse worker processes for multiple sessions
  • Keep-Alive Handling: Efficient idle connection management
  • Resource Limits: Configurable connection and memory limits
  • Load Balancing: Even distribution of connections across workers

I/O Optimizations

  • Sendfile Support: Zero-copy file transfers where supported
  • Asynchronous I/O: Non-blocking I/O operations via libevent
  • Buffer Management: Efficient memory usage for large transfers
  • Read-Ahead Caching: Anticipate sequential file access patterns

Directory Caching

  • LRU Cache: Least Recently Used eviction policy
  • Path Resolution Cache: Speed up repeated path lookups
  • Stat Cache: Cache filesystem metadata
  • Negative Caching: Cache "file not found" results

Configuration Options

Implementation Files

  • etc/afpd/afp_config.c - Configuration file parsing
  • etc/afpd/afp_options.c - Command-line and runtime options
  • etc/netatalk/netatalk.c - Global configuration management
  • libatalk/util/cnid_open.c - CNID configuration handling

Network Configuration

  • Listen Addresses: Specify binding addresses and ports
  • Protocol Support: Enable/disable DSI and ASP protocols
  • Connection Limits: Maximum concurrent connections
  • Timeout Settings: Various protocol timeouts

Authentication Configuration

  • UAM Modules: Specify available authentication methods
  • Guest Access: Enable/disable anonymous access
  • Password Policies: Password complexity requirements
  • Session Timeouts: Idle session timeout values

Volume Configuration

  • Volume Definitions: Specify shared directories
  • Access Controls: Per-volume permission settings
  • Features: Enable/disable volume-specific features
  • Quotas: Volume size and file count limits

Debugging and Monitoring

Implementation Files

  • libatalk/util/logger.c - Logging system implementation
  • etc/afpd/status.c - Server status reporting
  • etc/afpd/afp_util.c - Debugging utilities and helpers
  • bin/afpstats/afpstats.c - AFP statistics collection tool
  • contrib/debugging/ - Additional debugging tools and scripts

Log Categories

  • Connection Events: Client connect/disconnect
  • Authentication: Login attempts and failures
  • File Operations: File access and modifications
  • Error Conditions: Protocol and system errors
  • Performance: Timing and throughput metrics

Diagnostic Tools

  • Status Commands: Check daemon status and statistics
  • Configuration Dump: Display active configuration
  • Connection List: Show active client sessions
  • Performance Counters: I/O and protocol statistics

Common Issues

  • Connection Refused: Network configuration problems
  • Authentication Failures: UAM or credential issues
  • Permission Denied: Filesystem or AFP access problems
  • Performance Issues: I/O bottlenecks or resource limits

The afpd daemon serves as the foundation of Netatalk's AFP functionality, providing a robust and efficient implementation of the Apple Filing Protocol while maintaining compatibility across different Mac generations and network configurations.

Clone this wiki locally