Subversion Repositories Mokou

Rev

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