view mgw/ctrl_sock.c @ 97:9aed16c30622

mgw p2g: set M bit when restarting forwarding after no-forward
author Mychaela Falconia <falcon@freecalypso.org>
date Sun, 25 Sep 2022 20:05:02 -0800
parents f280328e7e2e
children f062c32a5116
line wrap: on
line source

/*
 * In this module we implement the logic of listening on the
 * TMGW control socket and accepting control connections.
 */

#include <sys/types.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <syslog.h>
#include <unistd.h>
#include "struct.h"
#include "select.h"

static char ctrl_socket_pathname[] = "/var/gsm/tmgw_socket";

extern void ctrl_message_handler();

void
ctrlsock_accept_handler(listener_fd)
{
	struct sockaddr_un sa;
	socklen_t sa_len;
	int conn_fd;
	struct ctrl_conn *conn;

	sa_len = sizeof sa;
	conn_fd = accept(listener_fd, (struct sockaddr *) &sa, &sa_len);
	if (conn_fd < 0) {
		syslog(LOG_CRIT, "accept on UNIX socket: %m");
		exit(1);
	}
	conn = malloc(sizeof(struct ctrl_conn));
	if (!conn) {
		syslog(LOG_CRIT, "malloc for ctrl socket conn: %m");
		close(conn_fd);
		return;
	}
	bzero(conn, sizeof(struct ctrl_conn));
	update_max_fd(conn_fd);
	FD_SET(conn_fd, &select_for_read);
	select_handlers[conn_fd] = ctrl_message_handler;
	select_data[conn_fd] = (void *) conn;
	syslog(LOG_INFO, "accepted ctrl connection");
}

create_ctrl_socket()
{
	struct sockaddr_un sa;
	unsigned sa_len;
	int fd, rc;

	fd = socket(AF_UNIX, SOCK_SEQPACKET, 0);
	if (fd < 0) {
		syslog(LOG_CRIT, "socket(AF_UNIX, SOCK_SEQPACKET, 0): %m");
		return(-1);
	}
	unlink(ctrl_socket_pathname);
	fill_sockaddr_un(ctrl_socket_pathname, &sa, &sa_len);
	rc = bind(fd, (struct sockaddr *) &sa, sa_len);
	if (rc < 0) {
		syslog(LOG_ERR, "bind to %s: %m", ctrl_socket_pathname);
		return(-1);
	}
	rc = listen(fd, 3);
	if (rc < 0) {
		syslog(LOG_CRIT, "listen on UNIX socket: %m");
		return(-1);
	}
	chmod(ctrl_socket_pathname, 0775);
	update_max_fd(fd);
	FD_SET(fd, &select_for_read);
	select_handlers[fd] = ctrlsock_accept_handler;
	return(0);
}