/*
 * Copyright (c) 1999 Adrian Sun (asun@zoology.washington.edu)
 * Copyright (c) 1990,1993 Regents of The University of Michigan.
 * Copyright (c) 2026 Andy Lemin (@andylemin)
 * Copyright (c) 2026 Daniel Markstedt <daniel@mindani.net>
 * All Rights Reserved.  See COPYRIGHT.
 *
 * modified from main.c. this handles afp over tcp.
 */

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif /* HAVE_CONFIG_H */

#include <arpa/inet.h>
#include <errno.h>
#include <fcntl.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <signal.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/stat.h>

#include <poll.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <time.h>
#include <unistd.h>

#include <atalk/afp_util.h>
#include <atalk/compat.h>
#include <atalk/dsi.h>
#include <atalk/fce_api.h>
#include <atalk/globals.h>
#include <atalk/logger.h>
#include <atalk/netatalk_conf.h>
#include <atalk/server_ipc.h>

#ifdef WITH_SPOTLIGHT
#include <atalk/spotlight.h>
#endif

#include <atalk/util.h>
#include <atalk/uuid.h>

#include "auth.h"
#include "dircache.h"
#include "directory.h"
#include "fork.h"
#include "idle_worker.h"
#include "switch.h"

#ifndef SOL_TCP
#define SOL_TCP IPPROTO_TCP
#endif

/*!
 * We generally pass this from afp_over_dsi to all afp_* funcs, so it should already be
 * available everywhere. Unfortunately some funcs (eg acltoownermode) need acces to it
 * but are deeply nested in the function chain with the caller already without acces to it.
 * Changing this would require adding a reference to the caller which itself might be
 * called in many places (eg acltoownermode is called from accessmode).
 * The only sane way out is providing a copy of it here:
 */
AFPObj *AFPobj = NULL;

typedef struct {
    uint16_t DSIreqID;
    uint8_t  AFPcommand;
    uint32_t result;
} rc_elem_t;

/*!
 * AFP replay cache:
 * - fix sized array
 * - indexed just by taking DSIreqID mod REPLAYCACHE_SIZE
 */
static rc_elem_t replaycache[REPLAYCACHE_SIZE];

/*
 * Pending signal flags — set by async-signal-safe handlers,
 * processed in the main event loop.
 *
 * All signal handlers are kept minimal (set flag only) to avoid
 * calling non-async-signal-safe functions (malloc, syslog, LOG, etc.)
 * from signal context.  See POSIX.1-2017 §2.4.3.
 */
static volatile sig_atomic_t alarm_pending = 0;
static volatile sig_atomic_t transfer_pending = 0;
static volatile sig_atomic_t timedown_pending = 0;
static volatile sig_atomic_t getmesg_pending = 0;
/* Non-static: also checked by afp_disconnect() in auth.c */
volatile sig_atomic_t die_pending = 0;

/*!
 * @brief Self-pipe for waking poll() from signal handlers.
 *
 * Signal handlers write a single byte to sigpipe_fd[1].  The read end
 * sigpipe_fd[0] is included in the poll() set so that the main loop
 * wakes up promptly even when SA_RESTART would otherwise cause poll()
 * to be restarted transparently.
 *
 * Although POSIX says poll() is not affected by SA_RESTART, some
 * platforms (Solaris, illumos) have historically restarted it.
 * The self-pipe makes wake-up behaviour portable and deterministic.
 */
static int sigpipe_fd[2] = {-1, -1};

static void sigpipe_init(void)
{
    if (pipe(sigpipe_fd) == -1) {
        /* Fatal — without the pipe, signals cannot wake poll() reliably */
        exit(EXITERR_SYS);
    }

    /* Both ends non-blocking: write so handlers never stall,
     * read so sigpipe_drain() never blocks */
    fcntl(sigpipe_fd[0], F_SETFL,
          fcntl(sigpipe_fd[0], F_GETFL) | O_NONBLOCK);
    fcntl(sigpipe_fd[1], F_SETFL,
          fcntl(sigpipe_fd[1], F_GETFL) | O_NONBLOCK);
    fcntl(sigpipe_fd[0], F_SETFD, FD_CLOEXEC);
    fcntl(sigpipe_fd[1], F_SETFD, FD_CLOEXEC);
}

/*!
 * @brief Write a single byte to the self-pipe.
 *
 * Called from signal handlers — async-signal-safe.
 */
static void sigpipe_notify(void)
{
    int saved_errno = errno;
    char c = 1;
    (void)write(sigpipe_fd[1], &c, 1);
    errno = saved_errno;
}

/*!
 * @brief Drain all pending bytes from the self-pipe.
 *
 * Called from the main loop after poll() returns.
 */
static void sigpipe_drain(void)
{
    char buf[64];

    while (read(sigpipe_fd[0], buf, sizeof(buf)) > 0) {
        /* drain */
    }
}

static void afp_dsi_close(AFPObj *obj)
{
    DSI *dsi = obj->dsi;
    sigset_t sigs;
    /* Sets is_idle=0 — no spin. Async-signal-safe (single atomic store only).
     * Worker stops at next is_idle check. No spin needed because all
     * afp_dsi_close() paths end in exit() which terminates the worker. */
    idle_worker_stop_signal_safe();
    /* Log idle worker stats AFTER stop but BEFORE log_dircache_stat() */
    idle_worker_log_stats();
    close(obj->ipc_fd);
    obj->ipc_fd = -1;

    if (obj->hint_fd >= 0) {
        close(obj->hint_fd);
        obj->hint_fd = -1;
    }

    /* we may have been called from a signal handler caught when afpd was running
     * as uid 0, that's the wrong user for volume's prexec_close scripts if any,
     * restore our login user
     */
    if (geteuid() != obj->uid) {
        if (seteuid(obj->uid) < 0) {
            LOG(log_error, logtype_afpd, "can't seteuid(%u) back %s: uid: %u, euid: %u",
                obj->uid, strerror(errno), getuid(), geteuid());
            exit(EXITERR_SYS);
        }
    }

    close_all_vol(obj);

    if (obj->logout) {
        /* Block sigs, PAM/systemd/whoever might send us a SIG??? in (*obj->logout)() -> pam_close_session() */
        sigfillset(&sigs);
        pthread_sigmask(SIG_BLOCK, &sigs, NULL);
        (*obj->logout)();
    }

    /* Log TCP buffer sizes at session close (socket may already be closed
     * during disconnect path — check fd validity first) */
    if (dsi->socket >= 0) {
        int close_rcvbuf = 0, close_sndbuf = 0;
        socklen_t optlen = sizeof(int);
        getsockopt(dsi->socket, SOL_SOCKET, SO_RCVBUF, &close_rcvbuf, &optlen);
        optlen = sizeof(int);
        getsockopt(dsi->socket, SOL_SOCKET, SO_SNDBUF, &close_sndbuf, &optlen);
        LOG(log_info, logtype_dsi,
            "Session close TCP buffer sizes for \"%s\": "
            "rcvbuf=%d sndbuf=%d",
            obj->username, close_rcvbuf, close_sndbuf);
    }

    LOG(log_note, logtype_afpd,
        "AFP statistics: %.2f KB read, %.2f KB written via DSI",
        dsi->read_count / 1024.0, dsi->write_count / 1024.0);
    log_dircache_stat();
    dircache_rfork_shutdown();
    dsi_close(dsi);
}

/*!
 * @brief SIGTERM: Terminate the AFP session and exit.
 *
 * Wraps afp_dsi_close() + exit() with pre-flight checks and a shutdown
 * attention to notify the client.  Other call sites in this file invoke
 * afp_dsi_close() + exit() directly — a future cleanup could funnel
 * all exit paths through here.
 *
 * @param sig  signal number or EXITERR_* code; 0 for maintenance shutdown.
 */
static void afp_dsi_die(int sig)
{
    DSI *dsi = (DSI *)AFPobj->dsi;

    if (dsi->flags & DSI_RECONINPROG) {
        /* Primary reconnect succeeded, got SIGTERM from afpd parent */
        dsi->flags &= ~DSI_RECONINPROG;
        return; /* this returns to afp_disconnect */
    }

    if (dsi->flags & DSI_DISCONNECTED) {
        LOG(log_note, logtype_afpd, "Disconnected session terminating");
        exit(0);
    }

    dsi_attention(AFPobj->dsi, AFPATTN_SHUTDOWN);
    afp_dsi_close(AFPobj);

    if (sig) /* if no signal, assume dying because logins are disabled &
                don't log it (maintenance mode)*/
    {
        LOG(log_info, logtype_afpd, "Connection terminated");
    }

    if (sig == SIGTERM || sig == SIGALRM) {
        exit(0);
    } else {
        exit(sig);
    }
}

/*! SIGURG handler (primary reconnect) — async-signal-safe */
static void afp_dsi_transfer_handler(int sig _U_)
{
    transfer_pending = 1;
    sigpipe_notify();
}

/*!
 * @brief Process deferred SIGURG: primary reconnect.
 *
 * Called from the main event loop where non-signal-safe functions are permitted.
 */
static void handle_transfer_session(AFPObj *obj)
{
    uint16_t dsiID;
    int socket;
    DSI *dsi = obj->dsi;
    LOG(log_debug, logtype_afpd,
        "handle_transfer_session: got SIGURG, trying to receive session");

    if (readt(obj->ipc_fd, &dsiID, 2, 0, 2) != 2) {
        LOG(log_error, logtype_afpd,
            "handle_transfer_session: couldn't receive DSI id, goodbye");
        afp_dsi_close(obj);
        exit(EXITERR_SYS);
    }

    if ((socket = recv_fd(obj->ipc_fd, 1)) == -1) {
        LOG(log_error, logtype_afpd,
            "handle_transfer_session: couldn't receive session fd, goodbye");
        afp_dsi_close(obj);
        exit(EXITERR_SYS);
    }

    LOG(log_debug, logtype_afpd, "handle_transfer_session: received socket fd: %i",
        socket);
    dsi->proto_close(dsi);
    dsi->socket = socket;
    dsi->flags = DSI_RECONSOCKET;
    dsi->datalen = 0;
    dsi->eof = dsi->start = dsi->buffer;
    dsi->in_write = 0;
    dsi->header.dsi_requestID = dsiID;
    dsi->header.dsi_command = DSIFUNC_CMD;

    /*
     * The session transfer happens in the middle of FPDisconnect old session, thus we
     * have to send the reply now.
     */
    if (!dsi_cmdreply(dsi, AFP_OK)) {
        LOG(log_error, logtype_afpd, "dsi_cmdreply: %s", strerror(errno));
        afp_dsi_close(obj);
        exit(EXITERR_CLNT);
    }

    LOG(log_note, logtype_afpd,
        "handle_transfer_session: successful primary reconnect");
}

/* Forward declaration — defined after alarm_handler */
static void afp_dsi_die_handler(int sig);

/*! SIGUSR1 handler — async-signal-safe */
static void afp_dsi_timedown_handler(int sig _U_)
{
    timedown_pending = 1;
    sigpipe_notify();
}

/*!
 * @brief Process deferred SIGUSR1: server going down in 5 minutes.
 *
 * Called from the main event loop.
 */
static void handle_timedown(AFPObj *obj)
{
    struct sigaction	sv;
    struct itimerval	it;
    DSI *dsi = obj->dsi;
    dsi->flags |= DSI_DIE;
    /* shutdown and don't reconnect. server going down in 5 minutes. */
    setmessage("The server is going down for maintenance.");

    if (dsi_attention(obj->dsi, AFPATTN_SHUTDOWN | AFPATTN_NORECONNECT |
                      AFPATTN_MESG | AFPATTN_TIME(5)) < 0) {
        dsi->down_request = 1;
    }

    it.it_interval.tv_sec = 0;
    it.it_interval.tv_usec = 0;
    it.it_value.tv_sec = 300;
    it.it_value.tv_usec = 0;

    if (setitimer(ITIMER_REAL, &it, NULL) < 0) {
        LOG(log_error, logtype_afpd, "afp_timedown: setitimer: %s", strerror(errno));
        afp_dsi_die(EXITERR_SYS);
    }

    memset(&sv, 0, sizeof(sv));
    sv.sa_handler = afp_dsi_die_handler;
    sigemptyset(&sv.sa_mask);
    sigaddset(&sv.sa_mask, SIGHUP);
    sigaddset(&sv.sa_mask, SIGTERM);
    sv.sa_flags = SA_RESTART;

    if (sigaction(SIGALRM, &sv, NULL) < 0) {
        LOG(log_error, logtype_afpd, "afp_timedown: sigaction: %s", strerror(errno));
        afp_dsi_die(EXITERR_SYS);
    }

    /* ignore myself */
    sv.sa_handler = SIG_IGN;
    sigemptyset(&sv.sa_mask);
    sv.sa_flags = SA_RESTART;

    if (sigaction(SIGUSR1, &sv, NULL) < 0) {
        LOG(log_error, logtype_afpd, "afp_timedown: sigaction SIGUSR1: %s",
            strerror(errno));
        afp_dsi_die(EXITERR_SYS);
    }
}

/*!
 * SIGHUP: reload configuration file — async-signal-safe
 */
volatile sig_atomic_t reload_request = 0;

static void afp_dsi_reload(int sig _U_)
{
    reload_request = 1;
    sigpipe_notify();
}

/*!
 * SIGINT: enable max_debug LOGging — async-signal-safe
 */
static volatile sig_atomic_t debug_request = 0;

static void afp_dsi_debug(int sig _U_)
{
    debug_request = 1;
    sigpipe_notify();
}

/*! SIGUSR2 handler — async-signal-safe */
static void afp_dsi_getmesg_handler(int sig _U_)
{
    getmesg_pending = 1;
    sigpipe_notify();
}

/*!
 * @brief Process deferred SIGUSR2: server message.
 *
 * Called from the main event loop.
 */
static void handle_getmesg(AFPObj *obj)
{
    DSI *dsi = obj->dsi;
    dsi->msg_request = 1;

    if (dsi_attention(obj->dsi, AFPATTN_MESG | AFPATTN_TIME(5)) < 0) {
        dsi->msg_request = 2;
    }
}

/*! SIGTERM/SIGQUIT handler — async-signal-safe */
static void afp_dsi_die_handler(int sig)
{
    die_pending = sig ? sig : -1;
    sigpipe_notify();
}

/*!
 * @brief SIGALRM handler — async-signal-safe.
 *
 * Only restarts the timer (setitimer is async-signal-safe) and sets a flag.
 * All tickle/timeout logic is deferred to handle_alarm().
 */
static void alarm_handler(int sig _U_)
{
    const DSI *dsi = AFPobj->dsi;
    /* we have to restart the timer because some libraries may use alarm() */
    setitimer(ITIMER_REAL, &dsi->timer, NULL);
    alarm_pending = 1;
    sigpipe_notify();
}

/*!
 * @brief Process deferred SIGALRM: tickle/timeout management.
 *
 * Called from the main event loop where LOG/malloc/syslog are safe.
 */
static void handle_alarm(AFPObj *obj)
{
    int err;
    DSI *dsi = obj->dsi;

    /* we got some traffic from the client since the previous timer tick. */
    if (dsi->flags & DSI_DATA) {
        dsi->flags &= ~DSI_DATA;
        return;
    }

    dsi->tickle++;
    LOG(log_maxdebug, logtype_afpd,
        "alarm: tickles: %u, flags: %s|%s|%s|%s|%s|%s|%s|%s|%s",
        dsi->tickle,
        (dsi->flags & DSI_DATA) ?         "DSI_DATA" : "-",
        (dsi->flags & DSI_RUNNING) ?      "DSI_RUNNING" : "-",
        (dsi->flags & DSI_SLEEPING) ?     "DSI_SLEEPING" : "-",
        (dsi->flags & DSI_EXTSLEEP) ?     "DSI_EXTSLEEP" : "-",
        (dsi->flags & DSI_DISCONNECTED) ? "DSI_DISCONNECTED" : "-",
        (dsi->flags & DSI_DIE) ?          "DSI_DIE" : "-",
        (dsi->flags & DSI_NOREPLY) ?      "DSI_NOREPLY" : "-",
        (dsi->flags & DSI_RECONSOCKET) ?  "DSI_RECONSOCKET" : "-",
        (dsi->flags & DSI_RECONINPROG) ?  "DSI_RECONINPROG" : "-");

    if (dsi->flags & DSI_SLEEPING) {
        if (dsi->tickle > obj->options.sleep) {
            LOG(log_note, logtype_afpd, "afp_alarm: sleep time ended");
            afp_dsi_die(EXITERR_CLNT);
        }

        return;
    }

    if (dsi->flags & DSI_DISCONNECTED) {
        if (geteuid() == 0) {
            LOG(log_note, logtype_afpd,
                "afp_alarm: unauthenticated user, connection problem");
            afp_dsi_die(EXITERR_CLNT);
        }

        if (dsi->tickle > obj->options.disconnected) {
            LOG(log_error, logtype_afpd, "afp_alarm: reconnect timer expired, goodbye");
            afp_dsi_die(EXITERR_CLNT);
        }

        return;
    }

    /* if we're in the midst of processing something, don't die. */
    if (dsi->tickle >= obj->options.timeout) {
        LOG(log_error, logtype_afpd,
            "afp_alarm: child timed out, entering disconnected state");

        if (dsi_disconnect(dsi) != 0) {
            afp_dsi_die(EXITERR_CLNT);
        }

        return;
    }

    if ((err = pollvoltime(obj)) == 0) {
        LOG(log_debug, logtype_afpd, "afp_alarm: sending DSI tickle");
        err = dsi_tickle(obj->dsi);
    }

    if (err <= 0) {
        if (geteuid() == 0) {
            LOG(log_note, logtype_afpd,
                "afp_alarm: unauthenticated user, connection problem");
            afp_dsi_die(EXITERR_CLNT);
        }

        LOG(log_error, logtype_afpd,
            "afp_alarm: connection problem, entering disconnected state");

        if (dsi_disconnect(dsi) != 0) {
            afp_dsi_die(EXITERR_CLNT);
        }
    }
}

static void child_handler(int sig _U_)
{
    wait(NULL);
}

/*!
 * @brief Process all pending deferred signals.
 *
 * @returns 1 if the caller should restart the outer event loop
 *          (primary reconnect), 0 otherwise.
 *
 * @note Must be called from the main event loop, never from signal context.
 */
static int process_deferred_signals(AFPObj *obj)
{
    /* Highest priority: die (SIGTERM/SIGQUIT/SIGALRM-after-timedown) */
    if (die_pending) {
        int sig = die_pending;
        die_pending = 0;
        afp_dsi_die(sig);
        /* afp_dsi_die calls exit() — should not return */
    }

    /* Primary reconnect (SIGURG) */
    if (transfer_pending) {
        transfer_pending = 0;
        idle_worker_stop();
        handle_transfer_session(obj);
        return 1;
    }

    /* Server going down (SIGUSR1) */
    if (timedown_pending) {
        timedown_pending = 0;
        handle_timedown(obj);
    }

    /* Server message (SIGUSR2) */
    if (getmesg_pending) {
        getmesg_pending = 0;
        handle_getmesg(obj);
    }

    /* Tickle / timeout (SIGALRM) */
    if (alarm_pending) {
        alarm_pending = 0;
        handle_alarm(obj);
    }

    return 0;
}

/* -----------------
   if dsi->in_write is set attention, tickle (and close?) msg
   aren't sent. We don't care about tickle
*/
static void pending_request(DSI *dsi)
{
    /* send pending attention */

    /* read msg if any, it could be done in afp_getsrvrmesg */
    if (dsi->msg_request) {
        if (dsi->msg_request == 2) {
            /* didn't send it in signal handler */
            dsi_attention(AFPobj->dsi, AFPATTN_MESG | AFPATTN_TIME(5));
        }

        dsi->msg_request = 0;
        readmessage(AFPobj);
    }

    if (dsi->down_request) {
        dsi->down_request = 0;
        dsi_attention(AFPobj->dsi, AFPATTN_SHUTDOWN | AFPATTN_NORECONNECT |
                      AFPATTN_MESG | AFPATTN_TIME(5));
    }
}

void afp_over_dsi_sighandlers(AFPObj *obj)
{
    DSI *dsi = (DSI *) obj->dsi;
    struct sigaction action;
    memset(&action, 0, sizeof(action));
    sigfillset(&action.sa_mask);
    action.sa_flags = SA_RESTART;
    /* install SIGHUP */
    action.sa_handler = afp_dsi_reload;

    if (sigaction(SIGHUP, &action, NULL) < 0) {
        LOG(log_error, logtype_afpd, "afp_over_dsi: sigaction: %s", strerror(errno));
        afp_dsi_die(EXITERR_SYS);
    }

    /* install SIGURG */
    action.sa_handler = afp_dsi_transfer_handler;

    if (sigaction(SIGURG, &action, NULL) < 0) {
        LOG(log_error, logtype_afpd, "afp_over_dsi: sigaction: %s", strerror(errno));
        afp_dsi_die(EXITERR_SYS);
    }

    /* install SIGTERM */
    action.sa_handler = afp_dsi_die_handler;

    if (sigaction(SIGTERM, &action, NULL) < 0) {
        LOG(log_error, logtype_afpd, "afp_over_dsi: sigaction: %s", strerror(errno));
        afp_dsi_die(EXITERR_SYS);
    }

    /* install SIGQUIT */
    action.sa_handler = afp_dsi_die_handler;

    if (sigaction(SIGQUIT, &action, NULL) < 0) {
        LOG(log_error, logtype_afpd, "afp_over_dsi: sigaction: %s", strerror(errno));
        afp_dsi_die(EXITERR_SYS);
    }

    /* SIGUSR2 - server message support */
    action.sa_handler = afp_dsi_getmesg_handler;

    if (sigaction(SIGUSR2, &action, NULL) < 0) {
        LOG(log_error, logtype_afpd, "afp_over_dsi: sigaction: %s", strerror(errno));
        afp_dsi_die(EXITERR_SYS);
    }

    /*  SIGUSR1 - set down in 5 minutes  */
    action.sa_handler = afp_dsi_timedown_handler;
    action.sa_flags = SA_RESTART;

    if (sigaction(SIGUSR1, &action, NULL) < 0) {
        LOG(log_error, logtype_afpd, "afp_over_dsi: sigaction: %s", strerror(errno));
        afp_dsi_die(EXITERR_SYS);
    }

    /*  SIGINT - enable max_debug LOGging to /tmp/afpd.PID.XXXXXX */
    action.sa_handler = afp_dsi_debug;

    if (sigaction(SIGINT, &action, NULL) < 0) {
        LOG(log_error, logtype_afpd, "afp_over_dsi: sigaction: %s", strerror(errno));
        afp_dsi_die(EXITERR_SYS);
    }

#ifndef DEBUGGING
    /* SIGALRM - tickle handler */
    action.sa_handler = alarm_handler;

    if ((sigaction(SIGALRM, &action, NULL) < 0) ||
            (setitimer(ITIMER_REAL, &dsi->timer, NULL) < 0)) {
        afp_dsi_die(EXITERR_SYS);
    }

#endif /* DEBUGGING */
    /*  SIGCHLD */
    action.sa_handler = child_handler;
#ifdef SA_NOCLDWAIT
    /* this enhancement simplifies things for Solaris, it also improves performance */
    action.sa_flags |= SA_NOCLDWAIT;
#endif

    if (sigaction(SIGCHLD, &action, NULL) < 0) {
        LOG(log_error, logtype_afpd, "afp_over_dsi: sigaction: %s", strerror(errno));
        afp_dsi_die(EXITERR_SYS);
    }
}

/* -------------------------------------------
 afp over dsi. this never returns.
*/
void afp_over_dsi(AFPObj *obj)
{
    DSI *dsi = (DSI *) obj->dsi;
    int rc_idx;
    uint32_t err, cmd;
    uint8_t function;
    AFPobj = obj;
    obj->exit = afp_dsi_die;
    obj->reply = (int (*)(void *, int))dsi_cmdreply;
    obj->attention = (int (*)(void *, AFPUserBytes))dsi_attention;
    dsi->tickle = 0;
    afp_over_dsi_sighandlers(obj);

    if (dircache_init(obj->options.dircachesize) != 0) {
        afp_dsi_die(EXITERR_SYS);
    }

    /* Start idle worker thread — failure is non-fatal (synchronous fallback) */
    (void)idle_worker_init();

    /* set TCP snd/rcv buf */
    if (obj->options.tcp_rcvbuf) {
        if (setsockopt(dsi->socket,
                       SOL_SOCKET,
                       SO_RCVBUF,
                       &obj->options.tcp_rcvbuf,
                       sizeof(obj->options.tcp_rcvbuf)) != 0) {
            LOG(log_error, logtype_dsi, "afp_over_dsi: setsockopt(SO_RCVBUF): %s",
                strerror(errno));
        }
    }

    if (obj->options.tcp_sndbuf) {
        if (setsockopt(dsi->socket,
                       SOL_SOCKET,
                       SO_SNDBUF,
                       &obj->options.tcp_sndbuf,
                       sizeof(obj->options.tcp_sndbuf)) != 0) {
            LOG(log_error, logtype_dsi, "afp_over_dsi: setsockopt(SO_SNDBUF): %s",
                strerror(errno));
        }
    }

    /* Log TCP buffer sizes: configured vs actual (kernel may adjust) */
    {
        int actual_rcvbuf = 0, actual_sndbuf = 0;
        socklen_t optlen = sizeof(int);
        getsockopt(dsi->socket, SOL_SOCKET, SO_RCVBUF, &actual_rcvbuf, &optlen);
        optlen = sizeof(int);
        getsockopt(dsi->socket, SOL_SOCKET, SO_SNDBUF, &actual_sndbuf, &optlen);
        LOG(log_info, logtype_dsi,
            "Session start TCP buffer sizes: "
            "configured rcvbuf=%u sndbuf=%u, "
            "actual rcvbuf=%d sndbuf=%d",
            obj->options.tcp_rcvbuf, obj->options.tcp_sndbuf,
            actual_rcvbuf, actual_sndbuf);
    }
    /* set TCP_NODELAY */
    int flag = 1;
    setsockopt(dsi->socket, SOL_TCP, TCP_NODELAY, &flag, sizeof(flag));
    ipc_child_state(obj, DSI_RUNNING);
    /* Initialise self-pipe for signal-to-mainloop notification */
    sigpipe_init();

    /* get stuck here until the end */
    while (1) {
        while (1) {
            /* [A0] Process deferred signals before any blocking I/O */
            sigpipe_drain();

            if (process_deferred_signals(obj)) {
                goto restart_outer;
            }

            /* [A] DSI buffer check — skip poll if data buffered */
            if (dsi->start != dsi->eof) {
                break;                          /* NO idle — data ready */
            }

            /* [B] State check — disconnected/die bypass poll; sleeping must
             * still poll so deferred SIGURG reconnects can wake via self-pipe. */
            if (dsi->flags & (DSI_DISCONNECTED | DSI_DIE)) {
                if (obj->hint_fd >= 0) {
                    process_cache_hints(obj);
                }

                break;                          /* NO idle — special state */
            }

            /* [C] Setup poll fds — includes self-pipe for signal wake-up */
            struct pollfd pfds[3];
            int nfds = 0;
            pfds[nfds].fd = dsi->socket;
            pfds[nfds].events = POLLIN;
            nfds++;
            int hint_idx = -1;

            if (obj->hint_fd >= 0) {
                hint_idx = nfds;
                pfds[nfds].fd = obj->hint_fd;
                pfds[nfds].events = POLLIN;
                nfds++;
            }

            int sigpipe_idx = nfds;
            pfds[nfds].fd = sigpipe_fd[0];
            pfds[nfds].events = POLLIN;
            nfds++;
            /* Signal idle worker to start — we are about to block in poll().
             * idle_worker_start() is async-signal-safe (single atomic store) */
            idle_worker_start();
            /* [D] BLOCK IN POLL */
            int ret = poll(pfds, nfds, -1);
            /* WARNING: idle_worker_stop() must be called before ANY
             * break/continue after this point */
            idle_worker_stop();

            /* [E] poll error handling */
            if (ret < 0) {
                if (errno == EINTR) {
                    continue;
                }

                LOG(log_error, logtype_afpd, "afp_over_dsi: poll error: %s", strerror(errno));
                break;
            }

            /* [E1] Signal pipe — drain and loop back to process signals at [A0] */
            if (pfds[sigpipe_idx].revents & POLLIN) {
                sigpipe_drain();

                if (process_deferred_signals(obj)) {
                    goto restart_outer;
                }
            }

            /* [F] Hint pipe handling */
            if (hint_idx >= 0) {
                if (pfds[hint_idx].revents & POLLNVAL) {
                    LOG(log_error, logtype_afpd,
                        "afp_over_dsi: hint pipe fd %d invalid (POLLNVAL)", obj->hint_fd);
                    close(obj->hint_fd);
                    obj->hint_fd = -1;
                } else if (pfds[hint_idx].revents & (POLLIN | POLLHUP | POLLERR)) {
                    process_cache_hints(obj);
                }
            }

            /* [G] Socket error handling */
            if (pfds[0].revents & POLLNVAL) {
                LOG(log_error, logtype_afpd,
                    "afp_over_dsi: client socket fd %d invalid (POLLNVAL)", dsi->socket);
                break;
            }

            if (pfds[0].revents & (POLLHUP | POLLERR)) {
                LOG(log_debug, logtype_afpd,
                    "afp_over_dsi: client socket %s during idle wait",
                    (pfds[0].revents & POLLERR) ? "error" : "hangup");
                break;
            }

            /* [H] Client data ready */
            if (pfds[0].revents & POLLIN) {
                break;
            }

            /* [I] Only hint/signal pipe had data — loop back to poll() */
        }

        /* Blocking read on the network socket (now guaranteed to not block
         * when client data is available from poll()) */
        cmd = dsi_stream_receive(dsi);

        if (cmd == 0) {
            /* cmd == 0 is the error condition */
            if (dsi->flags & DSI_RECONSOCKET) {
                /* we just got a reconnect so we immediately try again to receive on the new fd */
                dsi->flags &= ~DSI_RECONSOCKET;
                continue;
            }

            /* A deferred SIGURG may have arrived during dsi_stream_receive */
            if (transfer_pending) {
                transfer_pending = 0;
                idle_worker_stop();
                handle_transfer_session(obj);
                continue;
            }

            /* the client sometimes logs out (afp_logout) but doesn't close the DSI session */
            if (dsi->flags & DSI_AFP_LOGGED_OUT) {
                LOG(log_note, logtype_afpd,
                    "afp_over_dsi: client logged out, terminating DSI session");
                idle_worker_shutdown();
                afp_dsi_close(obj);
                exit(0);
            }

            if (dsi->flags & DSI_RECONINPROG) {
                LOG(log_note, logtype_afpd, "afp_over_dsi: failed reconnect");
                idle_worker_shutdown();
                afp_dsi_close(obj);
                exit(0);
            }

            /* Some error on the client connection, enter disconnected state */
            if (dsi_disconnect(dsi) != 0) {
                afp_dsi_die(EXITERR_CLNT);
            }

            ipc_child_state(obj, DSI_DISCONNECTED);

            while (dsi->flags & DSI_DISCONNECTED) {
                /* gets interrupted by SIGALRM or SIGURG */
                pause();
                sigpipe_drain();

                if (process_deferred_signals(obj)) {
                    break;
                }
            }

            ipc_child_state(obj, DSI_RUNNING);
            /* continue receiving until disconnect timer expires
             * or a primary reconnect succeeds  */
            continue;
        }

        if (!(dsi->flags & DSI_EXTSLEEP) && (dsi->flags & DSI_SLEEPING)) {
            LOG(log_debug, logtype_afpd, "afp_over_dsi: got data, ending normal sleep");
            dsi->flags &= ~DSI_SLEEPING;
            dsi->tickle = 0;
            ipc_child_state(obj, DSI_RUNNING);
        }

        if (reload_request) {
            reload_request = 0;
            load_volumes(AFPobj, LV_FORCE);
        }

        /* The first SIGINT enables debugging, the next restores the config */
        if (debug_request) {
            static int debugging = 0;
            debug_request = 0;
            dircache_dump();
            uuidcache_dump();

            if (debugging) {
                if (obj->options.logconfig) {
                    setuplog(obj->options.logconfig, obj->options.logfile,
                             obj->options.log_us_timestamp);
                } else {
                    setuplog("default:note", NULL, true);
                }

                debugging = 0;
            } else {
                char logstr[MAXPATHLEN + 1];
                debugging = 1;
                snprintf(logstr, sizeof(logstr) - 1, "%s/afpd.%u.XXXXXX", tmpdir(), obj->pid);
                setuplog("default:maxdebug", logstr, true);
            }
        }

        dsi->flags |= DSI_DATA;
        dsi->tickle = 0;

        switch (cmd) {
        case DSIFUNC_CLOSE:
            LOG(log_debug, logtype_afpd, "DSI: close session request");
            idle_worker_shutdown();
            afp_dsi_close(obj);
            LOG(log_note, logtype_afpd, "done");
            exit(0);

        case DSIFUNC_TICKLE:
            /* thats no data in the sense we use it in alarm_handler */
            dsi->flags &= ~DSI_DATA;
            LOG(log_debug, logtype_afpd, "DSI: client tickle");

            /* timer is not every 30 seconds anymore, so we don't get killed on the client side. */
            if (dsi->flags & DSI_DIE) {
                dsi_tickle(dsi);
            }

            break;

        case DSIFUNC_CMD:
            function = (uint8_t) dsi->commands[0];
            /* AFP replay cache */
            rc_idx = dsi->clientID % REPLAYCACHE_SIZE;
            LOG(log_debug, logtype_dsi, "DSI request ID: %u", dsi->clientID);

            if (replaycache[rc_idx].DSIreqID == dsi->clientID
                    && replaycache[rc_idx].AFPcommand == function) {
                LOG(log_note, logtype_afpd, "AFP Replay Cache match: id: %u / cmd: %s",
                    dsi->clientID, AfpNum2name(function));
                err = replaycache[rc_idx].result;
                /* AFP replay cache end */
            } else {
                /* send off an afp command. in a couple cases, we take advantage
                 * of the fact that we're a stream-based protocol. */
                if (afp_switch[function]) {
                    dsi->datalen = DSI_DATASIZ;
                    dsi->flags |= DSI_RUNNING;
                    LOG(log_debug, logtype_afpd, "<== Start AFP command: %s",
                        AfpNum2name(function));
                    AFP_AFPFUNC_START(function, (char *)AfpNum2name(function));
                    err = (*afp_switch[function])(obj,
                                                  (char *)dsi->commands, dsi->cmdlen,
                                                  (char *)&dsi->data, &dsi->datalen);
                    AFP_AFPFUNC_DONE(function, (char *)AfpNum2name(function));
                    LOG(log_debug, logtype_afpd, "==> Finished AFP command: %s -> %s",
                        AfpNum2name(function), AfpErr2name(err));

                    if (!idle_worker_is_active()) {
                        dir_free_invalid_q();
                    }

                    dsi->flags &= ~DSI_RUNNING;
                    /* Add result to the AFP replay cache */
                    replaycache[rc_idx].DSIreqID = dsi->clientID;
                    replaycache[rc_idx].AFPcommand = function;
                    replaycache[rc_idx].result = err;
                } else {
                    LOG(log_maxdebug, logtype_afpd, "bad function %X", function);
                    dsi->datalen = 0;
                    err = AFPERR_NOOP;
                }
            }

            /* single shot toggle that gets set by dsi_readinit. */
            if (dsi->flags & DSI_NOREPLY) {
                dsi->flags &= ~DSI_NOREPLY;
                break;
            } else if (!dsi_cmdreply(dsi, err)) {
                LOG(log_error, logtype_afpd, "dsi_cmdreply(%d): %s", dsi->socket,
                    strerror(errno));

                if (dsi_disconnect(dsi) != 0) {
                    afp_dsi_die(EXITERR_CLNT);
                }
            }

            break;

        case DSIFUNC_WRITE: /* FPWrite and FPAddIcon */
            function = (uint8_t) dsi->commands[0];

            if (afp_switch[function] != NULL) {
                dsi->datalen = DSI_DATASIZ;
                dsi->flags |= DSI_RUNNING;
                LOG(log_debug, logtype_afpd, "<== Start AFP command: %s",
                    AfpNum2name(function));
                AFP_AFPFUNC_START(function, (char *)AfpNum2name(function));
                err = (*afp_switch[function])(obj,
                                              (char *)dsi->commands, dsi->cmdlen,
                                              (char *)&dsi->data, &dsi->datalen);
                AFP_AFPFUNC_DONE(function, (char *)AfpNum2name(function));
                LOG(log_debug, logtype_afpd, "==> Finished AFP command: %s -> %s",
                    AfpNum2name(function), AfpErr2name(err));
                dsi->flags &= ~DSI_RUNNING;
            } else {
                LOG(log_error, logtype_afpd, "(write) bad function %x", function);
                dsi->datalen = 0;
                err = AFPERR_NOOP;
            }

            if (!dsi_wrtreply(dsi, err)) {
                LOG(log_error, logtype_afpd, "dsi_wrtreply: %s", strerror(errno));

                if (dsi_disconnect(dsi) != 0) {
                    afp_dsi_die(EXITERR_CLNT);
                }
            }

            break;

        case DSIFUNC_ATTN: /* attention replies */
            break;

        /* error. this usually implies a mismatch of some kind
         * between server and client. if things are correct,
         * we need to flush the rest of the packet if necessary. */
        default:
            LOG(log_info, logtype_afpd, "afp_dsi: spurious command %d", cmd);
            dsi_writeinit(dsi, dsi->data, DSI_DATASIZ);
            dsi_writeflush(dsi);
            break;
        }

        pending_request(dsi);
#ifdef WITH_FCE
        fce_pending_events(obj);
#endif /* WITH_FCE */
restart_outer: ;
    }
}
