#include "netlinkmonitor.h"
#include <QFile>
#include <QDebug>
#include <QDateTime>

static volatile bool need_exit = false;

class NetLinkMonitorPrivate
{
public:
    NetLinkMonitorPrivate(NetLinkMonitor *parent):
        q_ptr(parent)
    {

    }

    QStringList monitorBinarys;
    QMap<int, QString> softPids;

    NetLinkMonitor *q_ptr;
    Q_DECLARE_PUBLIC(NetLinkMonitor)
};

NetLinkMonitor::NetLinkMonitor(const QList<SoftwareFilter> filters, QObject *parent):
    QThread(parent),
    dd_ptr(new NetLinkMonitorPrivate(this))
{
    Q_D(NetLinkMonitor);
    for (auto &filter : filters) {
        d->monitorBinarys.append(filter.binaryFilters);
    }
}

NetLinkMonitor::~NetLinkMonitor()
{

}

int NetLinkMonitor::nl_connect()
{
    int rc;
    int nl_sock;
    struct sockaddr_nl sa_nl;

    nl_sock = socket(PF_NETLINK, SOCK_DGRAM, NETLINK_CONNECTOR);
    if (nl_sock == -1) {
        perror("socket");
        return -1;
    }

    sa_nl.nl_family = AF_NETLINK;
    sa_nl.nl_groups = CN_IDX_PROC;
    sa_nl.nl_pid = getpid();

    rc = bind(nl_sock, (struct sockaddr *)&sa_nl, sizeof(sa_nl));
    if (rc == -1) {
        perror("bind");
        close(nl_sock);
        return -1;
    }

    return nl_sock;
}

int NetLinkMonitor::set_proc_ev_listen(int nl_sock, bool enable)
{
    int rc;
    struct __attribute__((aligned(NLMSG_ALIGNTO))) {
        struct nlmsghdr nl_hdr;
        struct __attribute__((__packed__)) {
            struct cn_msg cn_msg;
            enum proc_cn_mcast_op cn_mcast;
        };
    } nlcn_msg;

    memset(&nlcn_msg, 0, sizeof(nlcn_msg));
    nlcn_msg.nl_hdr.nlmsg_len = sizeof(nlcn_msg);
    nlcn_msg.nl_hdr.nlmsg_pid = getpid();
    nlcn_msg.nl_hdr.nlmsg_type = NLMSG_DONE;

    nlcn_msg.cn_msg.id.idx = CN_IDX_PROC;
    nlcn_msg.cn_msg.id.val = CN_VAL_PROC;
    nlcn_msg.cn_msg.len = sizeof(enum proc_cn_mcast_op);

    nlcn_msg.cn_mcast = enable ? PROC_CN_MCAST_LISTEN : PROC_CN_MCAST_IGNORE;

    rc = send(nl_sock, &nlcn_msg, sizeof(nlcn_msg), 0);
    if (rc == -1) {
        perror("netlink send");
        return -1;
    }

    return 0;
}

int NetLinkMonitor::handle_proc_ev(int nl_sock)
{
    Q_D(NetLinkMonitor);
    int rc;
    struct __attribute__((aligned(NLMSG_ALIGNTO))) {
        struct nlmsghdr nl_hdr;
        struct __attribute__((__packed__)) {
            struct cn_msg cn_msg;
            struct proc_event proc_ev;
        };
    } nlcn_msg;

    while (!need_exit) {
        rc = recv(nl_sock, &nlcn_msg, sizeof(nlcn_msg), 0);
        if (rc == 0) {
            /* shutdown? */
            return 0;
        } else if (rc == -1) {
            if (errno == EINTR) { continue; }
            perror("netlink recv");
            return -1;
        }
        switch (nlcn_msg.proc_ev.what) {
        case proc_event::what::PROC_EVENT_NONE:
            printf("set mcast listen ok\n");
            break;
        case proc_event::what::PROC_EVENT_EXEC: {
//                printf("exec: tid=%d pid=%d\n",
//                        nlcn_msg.proc_ev.event_data.exec.process_pid,
//                        nlcn_msg.proc_ev.event_data.exec.process_tgid);
            int pid = nlcn_msg.proc_ev.event_data.exec.process_pid;
            QString cmd = QString("/proc/%1/cmdline").arg(QString::number(pid));
            QFile f(cmd);
            if (f.open(QIODevice::ReadOnly)) {
                QString cmdline = f.readAll();
                if (d->monitorBinarys.contains(cmdline)) {
                    d->softPids.insert(pid, cmdline);
                    Q_EMIT softwareStarted(pid, cmdline, QDateTime::currentDateTime().toMSecsSinceEpoch());
                }
            }
            f.close();
            break;
        }
        case proc_event::what::PROC_EVENT_EXIT: {
//                printf("exit: tid=%d pid=%d exit_code=%d\n",
//                        nlcn_msg.proc_ev.event_data.exit.process_pid,
//                        nlcn_msg.proc_ev.event_data.exit.process_tgid,
//                        nlcn_msg.proc_ev.event_data.exit.exit_code);
            int pid = nlcn_msg.proc_ev.event_data.exit.process_pid;
            if (d->softPids.contains(pid)) {
                Q_EMIT softwareStoped(pid, d->softPids.value(pid), QDateTime::currentDateTime().toMSecsSinceEpoch());
            }
            break;
        }
        default:
            break;
        }
    }

    return 0;
}

void NetLinkMonitor::monitor()
{
    int nl_sock;
    int rc = EXIT_SUCCESS;

//    signal(SIGINT, on_sigint);
//    siginterrupt(SIGINT, true);

    nl_sock = nl_connect();
    if (nl_sock == -1) {
        return;
    }
//      exit(EXIT_FAILURE);

    rc = set_proc_ev_listen(nl_sock, true);
    if (rc == -1) {
//      rc = EXIT_FAILURE;
        goto out;
    }

    rc = handle_proc_ev(nl_sock);
    if (rc == -1) {
        rc = EXIT_FAILURE;
        goto out;
    }

    set_proc_ev_listen(nl_sock, false);

out:
    close(nl_sock);
}

void NetLinkMonitor::run()
{
    monitor();
}
