/
ssh.c
417 lines (377 loc) · 12 KB
/
ssh.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <sys/epoll.h>
#include <signal.h>
#include <pthread.h>
#include "dict.h"
#include "dict.c"
#define WORKING_THREADS_COUNT 5
//стуктура с пользовательскими данными
struct UserParams{
Dict login;
Dict fLogin;
Dict location;
};
//стуктура с параметрами потоков
struct Params{
pthread_mutex_t mutex;
pthread_cond_t condvar;
int currrent;
int end;
struct epoll_event* events;
int epollfd;
int socketfd;
struct UserParams userParams;
};
struct addrinfo* getAvilableAddresses(struct addrinfo* hints, char* port){
struct addrinfo* addresses;
int status = getaddrinfo(NULL, port, hints, &addresses);
if(status != 0){
fprintf(stderr, "getaddrinfo error: %s\n", gai_strerror(status));
return NULL;
}
return addresses;
}
int assignSocket(struct addrinfo* addresses){
int yes = 1;
int socketfd = 0;
for(struct addrinfo *address = addresses; address != NULL; address = address->ai_next){
socketfd = socket(address->ai_family, address->ai_socktype, address->ai_protocol);
if(socketfd == -1){
perror("impossible to create socket\n");
continue;
}
if(setsockopt(socketfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes)) == -1){
perror("impossible to make soket reusable\n");
continue;
}
if(bind(socketfd, address->ai_addr, address->ai_addrlen) == -1){
close(socketfd);
perror("impossible to bind socket\n");
continue;
}
return socketfd;
}
perror("socket bind error\n");
return -1;
}
//делаем сокет не блокируемым
int setNonBlock(int socketfd){
int flags = fcntl(socketfd, F_GETFL, 0);
if (fcntl(socketfd, F_SETFL, flags | O_NONBLOCK)){
perror ("impossible to make socket nonblock");
return -1;
}
return 0;
}
// добавление сокета в epoll для отслеживания событий
int addToEpoll(int epollfd, int socketfd){
struct epoll_event event;
event.data.fd = socketfd;
event.events = EPOLLIN | EPOLLET;
if (epoll_ctl(epollfd, EPOLL_CTL_ADD, socketfd, &event) == -1){
perror("failed to add descriptor to epoll");
return -1;
}
}
// прием соединения, если новых соединений нет или произошла ошибка то connectionfd == -1
int acceptConnection(int epollfd, int socketfd, struct UserParams userParams){
struct sockaddr addr;
socklen_t addrlen = sizeof addr;
int connectionfd = accept(socketfd, &addr, &addrlen);
if (connectionfd == -1){
perror ("failed to accept connection");
return -1;
}
char host[NI_MAXHOST];
char service[NI_MAXSERV];
//резервирование символьного адреса и имени сервиса
if(!getnameinfo(&addr, addrlen, host, sizeof host, service, sizeof service, NI_NUMERICHOST | NI_NUMERICSERV)){
//вывод информации о полльзователе
printf("new connection: %s:%s\n", host, service);
}
if (setNonBlock(connectionfd) == -1){
fprintf(stderr, "failed to set socket %d nonblock", connectionfd);
return -1;
}
//добавление в epol
if (addToEpoll(epollfd, connectionfd) == -1){
fprintf(stderr, "failed to add socket %d to epoll", connectionfd);
return -1;
}
dprintf(connectionfd,"Enter login: ");
//добавление пользователя в структуру
char conBuf[4];
snprintf(conBuf, 4,"%d",connectionfd);
DictInsert(userParams.login, conBuf, "");
snprintf(conBuf, 4,"%d",connectionfd);
DictInsert(userParams.fLogin, conBuf, "0");
return 0;
}
//проверка введенных пользовательских данных
int checkLogin(const char *login, char * password){
printf("Login = %s\n", login);
printf("Password = %s\n", password);
FILE *mf;
char *estr;
char str[50];
mf = fopen("registr","r");
while(1) {
estr = fgets(str,50,mf);
if (estr == NULL)
break;
if (!strcmp(str, login)){
estr = fgets(str,50,mf);
if (!strcmp(str, password)){
fclose(mf);
return 1;
}
}
else
estr = fgets(str,50,mf);
}
fclose(mf);
return 0;
}
//чтение данных, присланных пользователем
int handlerRequest(int epollfd, int connectionfd, struct UserParams userParams, pthread_mutex_t mutex){
int buffCount = 1024;
int i = 3;
char *buffer = (char*) malloc(buffCount * sizeof(char));
char conBuf[4];
ssize_t count = read(connectionfd, buffer, sizeof buffer);
char *ret;
//динамическое выделение памяти для буфера
char bufferN[buffCount];
ssize_t countN = read(connectionfd, bufferN, sizeof bufferN);
while(countN > 0){
ret = (char*)realloc(buffer,i*buffCount*sizeof(char));
if(!ret){
perror("realloc");
exit(1);
}
strcat(buffer, bufferN);
count+=countN;
i++;
countN = read(connectionfd, bufferN, sizeof bufferN);
}
switch(count){
case -1:
if (errno != EAGAIN)
perror ("failed to read data");
break;
case 0:
printf("client closed the connection");
break;
default:
snprintf(conBuf, 4,"%d",connectionfd);
//ввод логина
if(!strcmp(DictSearch(userParams.login, conBuf),"")){
if (count > 1){
char *tmpLogin = (char*) malloc(count+1);
strncpy(tmpLogin, buffer, count);
tmpLogin[count] = '\0';
DictInsert(userParams.login,conBuf,tmpLogin);
printf("%s\n", DictSearch(userParams.login, conBuf));
dprintf(connectionfd, "Enter password: ");
}
else
dprintf(connectionfd,"Enter login: ");
}
else{
//ввод пароля
if (!strcmp(DictSearch(userParams.fLogin, conBuf),"0")){
char *tmpPass=(char*) malloc(count+1);
strncpy(tmpPass, buffer, count);
tmpPass[count] = '\0';
//вызов проверки
pthread_mutex_lock(&mutex);
int check = checkLogin(DictSearch(userParams.login, conBuf), tmpPass);
pthread_mutex_unlock(&mutex);
if(check == 1){
DictDelete(userParams.fLogin,conBuf);
DictInsert(userParams.fLogin,conBuf,"1");
DictInsert(userParams.location,conBuf,"cd user_root/;");
dprintf(connectionfd, "!!Enter command: ");
}
else{
DictDelete(userParams.login,conBuf);
DictInsert(userParams.login,conBuf,"");
dprintf(connectionfd,"Enter login: ");
}
}
else{
//обработка комманд, присланных пользователем
if(!strncmp(buffer, "logout",6))
close(connectionfd);
else{
int c;
FILE *pp;
extern FILE *popen();
char* tempCd = (char*) malloc(1024*sizeof(char));
strcpy(tempCd, DictSearch(userParams.location, conBuf));
//strcat(tempCd, ";");
printf("----->%s\n",tempCd);
if ( !(pp=popen(strcat(tempCd, buffer), "r")) ){
free(tempCd);
return 1;
}
while ( (c=fgetc(pp)) != EOF ) {
putc(c, stdout);
dprintf(connectionfd,"%c",c);
fflush(pp);
}
pclose(pp);
free(tempCd);
printf("%d user command: %.*s", connectionfd, count, buffer);
dprintf(connectionfd, "Enter command: ");
}
}
}
}
free(buffer);
}
//обработка события на сокете
int handleEvent(struct epoll_event* event, int epollfd, int socketfd, struct UserParams userParams, pthread_mutex_t mutex){
if ((event->events & EPOLLERR) || (event->events & EPOLLHUP)){
printf("impossible to handle event\n");
close(event->data.fd);
return -1;
}
return socketfd == event->data.fd ?
// событие на серверном сокете
acceptConnection(epollfd, socketfd, userParams) :
// событие на сокете соединения
handlerRequest(epollfd, event->data.fd, userParams, mutex);
}
volatile sig_atomic_t done = 0;
void handleSignal(int signum){
done = 1;
}
//обработка событий потоком
void* workThread(void* p){
struct Params* params = (struct Params*) p;
printf("Wait");
pthread_mutex_lock(¶ms->mutex);
pthread_cond_wait(¶ms->condvar,¶ms->mutex);
pthread_mutex_unlock(¶ms->mutex);
printf("Hi");
int cur = malloc(sizeof(int));
while(!done)
{
int flag = 0;
pthread_mutex_lock(¶ms->mutex);
if(params->currrent < params->end){
cur = params->currrent;
params->currrent++;
flag = 1;
}
else{
//если нет новых событий
pthread_cond_wait(¶ms->condvar,¶ms->mutex);
}
pthread_mutex_unlock(¶ms->mutex);
if(flag){
printf("handling event %d of %d\n", params->currrent, params->end);
printf("%d\n",cur );
handleEvent(params->events+cur, params->epollfd, params->socketfd, params->userParams, params->mutex);
}
}
}
int main (int argc, char *argv[]){
/*int c;
FILE *pp;
extern FILE *popen();
if ( !(pp=popen("ls -l", "r")) )
return 1;
while ( (c=fgetc(pp)) != EOF ) {
putc(c, stdout);
fflush(pp);
}
pclose(pp);*/
//пользовательскике данные
struct UserParams userParams;
Dict login = DictCreate();
Dict fLogin = DictCreate();
Dict location = DictCreate();;
userParams.login = login;
userParams.fLogin = fLogin;
userParams.location = location;
//параметры адреса
printf("starting server\n");
struct addrinfo hints;
memset(&hints, 0, sizeof hints);
hints.ai_flags = AI_PASSIVE;
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
// получаение списка доступных адресов
char* port = "8080";
struct addrinfo* addresses = getAvilableAddresses(&hints, port);
if(!addresses)
return EXIT_FAILURE;
//коннект сокета
int socketfd = assignSocket(addresses);
if(!socketfd)
return EXIT_FAILURE;
if (setNonBlock(socketfd) == -1){
perror("non_block");
return EXIT_FAILURE;
}
if (listen (socketfd, SOMAXCONN) == -1){
perror ("listen");
return EXIT_FAILURE;
}
printf("listening port %s\n", port);
//создание epoll
int epollfd = epoll_create1(0);
if (epollfd == -1){
perror ("epoll_create");
return EXIT_FAILURE;
}
if (addToEpoll(epollfd, socketfd) == -1)
return EXIT_FAILURE;
//регистрация обработчика событий
signal(SIGINT, handleSignal);
int maxEventNum = 8;
struct epoll_event events[maxEventNum * sizeof(struct epoll_event)];
//заполнение параметров для потоков
struct Params params;
pthread_mutex_init(¶ms.mutex, NULL);
pthread_cond_init(¶ms.condvar, NULL);
params.end = 0;
params.currrent = 0;
params.epollfd = epollfd;
params.events = events;
params.socketfd = socketfd;
params.userParams = userParams;
pthread_t working[WORKING_THREADS_COUNT];
for(int i = 0; i<WORKING_THREADS_COUNT; i++){
pthread_create(&working[i], NULL, workThread, ¶ms);
}
//обработка событий
int timeout = -1 ;
while(!done){
if(params.currrent >= params.end){
printf("waiting new events\n");
int eventsNumber = epoll_wait(epollfd, events, maxEventNum, timeout);
params.currrent = 0;
params.end = eventsNumber;
printf("Send\n");
pthread_cond_signal(¶ms.condvar);
}
}
printf("server is going down\n");
printf("closing connections\n");
close(socketfd);
close(epollfd);
printf("done\n");
return EXIT_SUCCESS;
}