Subversion Repositories Mokou

Rev

Rev 8 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
5 nishi 1
/* $Id: server.c 9 2024-09-07 09:25:26Z nishi $ */
2
 
3
#include "mk_server.h"
7 nishi 4
 
8 nishi 5
#include "mk_service.h"
7 nishi 6
#include "mk_version.h"
7
#include "mk_util.h"
8
#include "mk_log.h"
9
 
10
#include <stdio.h>
11
#include <stdlib.h>
12
#include <unistd.h>
9 nishi 13
#include <poll.h>
7 nishi 14
 
15
#include <sys/types.h>
16
#include <sys/socket.h>
17
#include <sys/un.h>
18
 
19
struct sockaddr_un sun;
20
int server;
8 nishi 21
extern const char* mk_errors[];
7 nishi 22
 
23
int mk_server_init(void){
24
	remove("/tmp/mokou.sock");
25
	memset(&sun, 0, sizeof(sun));
26
	server = socket(AF_LOCAL, SOCK_STREAM, 0);
27
	if(server == -1){
28
		mk_log("Socket creation failure");
29
		return 1;
30
	}
31
	sun.sun_family = AF_LOCAL;
32
	strcpy(sun.sun_path, "/tmp/mokou.sock");
33
	if(bind(server, (struct sockaddr*)&sun, sizeof(sun)) == -1){
34
		mk_log("Bind failure");
35
		close(server);
36
		return 1;
37
	}
38
	if(listen(server, 16) == -1){
39
		mk_log("Listen failure");
40
		close(server);
41
		return 1;
42
	}
43
	return 0;
44
}
45
 
8 nishi 46
#define PROTOCOL_ERROR "EProtocol Error\n"
47
 
7 nishi 48
void mk_server_loop(void){
49
	struct sockaddr_un cun;
50
	socklen_t socklen = sizeof(cun);
8 nishi 51
	char* ver = mk_strcat3("R", mk_get_version(), "\n");
52
	char cbuf[2];
53
	cbuf[1] = 0;
54
	char* str = malloc(1);
55
	str[0] = 0;
9 nishi 56
	struct pollfd pollfds[16 + 1];
57
	pollfds[0].fd = server;
58
	pollfds[0].events = POLLIN | POLLPRI;
7 nishi 59
	while(1){
60
		mk_log("Waiting for the connection");
9 nishi 61
		int r = poll(pollfds, 16 + 1, 5000);
7 nishi 62
		int cli = accept(server, (struct sockaddr*)&cun, &socklen);
63
		send(cli, ver, strlen(ver), 0);
8 nishi 64
		while(1){
65
			if(recv(cli, cbuf, 1, 0) <= 0) break;
66
			if(cbuf[0] == '\n'){
67
				if(str[0] == 'U'){
68
					int err = mk_start_service(str + 1);
69
					if(err != 0){
70
						send(cli, "E", 1, 0);
71
						send(cli, mk_errors[err], strlen(mk_errors[err]), 0);
72
						send(cli, "\n", 1, 0);
73
					}else{
74
						send(cli, "Mok\n", 4, 0);
75
					}
76
				}else if(str[0] == 'D'){
77
					int err = mk_stop_service(str + 1);
78
					if(err != 0){
79
						send(cli, "E", 1, 0);
80
						send(cli, mk_errors[err], strlen(mk_errors[err]), 0);
81
						send(cli, "\n", 1, 0);
82
					}else{
83
						send(cli, "Mok\n", 4, 0);
84
					}
85
				}else{
86
					send(cli, PROTOCOL_ERROR, strlen(PROTOCOL_ERROR), 0);
87
				}
88
				free(str);
89
				str = malloc(1);
90
				str[0] = 0;
91
				break;
92
			}else if(cbuf[0] != '\r'){
93
				char* tmp = str;
94
				str = mk_strcat(tmp, cbuf);
95
				free(tmp);
96
			}
97
		}
7 nishi 98
		close(cli);
99
	}
100
	free(ver);
8 nishi 101
	free(ver);
7 nishi 102
}