/*
 * (C) 2021-2022 by sysmocom - s.f.m.c. GmbH <info@sysmocom.de>
 * All Rights Reserved.
 *
 * Author: Neels Janosch Hofmeyr <nhofmeyr@sysmocom.de>
 *
 * SPDX-License-Identifier: GPL-2.0+
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

#pragma once

#include <osmocom/core/linuxlist.h>
#include <osmocom/core/hashtable.h>
#include <osmocom/core/select.h>
#include <osmocom/core/logging.h>

#include <osmocom/upf/upf_tun.h>

#define LOG_GTP_DEV(DEV, LEVEL, FMT, ARGS...) \
	LOGP(DGTP, LEVEL, "%s: " FMT, upf_gtp_dev_to_str_c(OTC_SELECT, (DEV)), ##ARGS)

struct upf_gtp_dev {
	struct llist_head entry;

	/* If true, osmo-upf created this GTP device on startup and will destroy it on program exit. If false, the user
	 * has created the device and osmo-upf will not destroy it. */
	bool created;

	char *name;
	struct {
		bool enabled;
		struct osmo_sockaddr local_addr;
		struct osmo_fd ofd;
	} gtpv0;
	struct {
		struct osmo_sockaddr local_addr;
		struct osmo_fd ofd;
	} gtpv1;
	bool sgsn_mode;

	uint32_t ifidx;

	/* list of struct upf_gtp_tunend */
	struct llist_head tunnels;
	/* hashtable of (struct upf_gtp_tunen) with key desc.access.local.teid */
	DECLARE_HASHTABLE(tunnels_by_local_f_teid, 10);
};

/* Description of a GTP encapsulation / decapsulation.
 * The active state to operate the GTP kernel module accordingly is kept in struct upf_gtp_tunend. */
struct upf_tunend {
	struct upf_tun access;
	struct {
		struct osmo_sockaddr ue_local_addr;
	} core;
};

int upf_gtp_tunend_cmp(const struct upf_tunend *a, const struct upf_tunend *b);

int upf_gtp_genl_ensure_open();
void upf_gtp_genl_close();

int upf_gtp_dev_open(const char *name, bool create_gtp_dev, const char *local_addr, bool listen_for_gtpv0,
		     bool sgsn_mode);
struct upf_gtp_dev *upf_gtp_dev_find_by_name(const char *name);
struct upf_gtp_dev *upf_gtp_dev_find_by_local_addr(const struct osmo_sockaddr *local_addr);
struct upf_gtp_dev *upf_gtp_dev_first();

int upf_gtp_dev_tunend_add(struct upf_gtp_dev *dev, const struct upf_tunend *t);
int upf_gtp_dev_tunend_del(struct upf_gtp_dev *dev, const struct upf_tunend *t);

int upf_gtp_dev_to_str_buf(char *buf, size_t buflen, const struct upf_gtp_dev *dev);
char *upf_gtp_dev_to_str_c(void *ctx, const struct upf_gtp_dev *dev);
