-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathatdate.c
478 lines (413 loc) · 14.3 KB
/
atdate.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
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
/* NTP Client - Server
* Copyright (C) 2017 Rebeca Jiménez Guillén
*
* 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 3 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/>.
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <netdb.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <errno.h>
#include <sys/wait.h>
#include <signal.h>
#include <time.h>
#define BACKLOG 10 // Max pending connections in queue
#define BUFSIZE 32 // Buffer size (TIME payload size)
#define STIME_PORT 37 // Default port for TIME protocol servers
#define SERV_PORT 6649 // Default port for atdate server
/* Time is calculated in seconds, so the count is:
* 70 years/4 = 17,5 -> 17 leap years in 70 years
* 70-17 = ((53*365)+(17*366))*24*60*60 seconds
* Total adjust time = 2208988800
*/
#define LINUX_TIMEBASE 2208988800 // January 1st, 00.00 am 1970
int sockfd, new_fd;
int is_server = 0;
/* Usage function */
void usage(){
fprintf(stderr, "usage: atdate [-h serverhost] [-p port] [-m cu|ct|s|su] [-d]\n");
exit(1);
}
/* Signal handler for Ctrl-C */
void ctrlc_handler(int sig){
if(is_server == 1){
close(sockfd);
}
printf("\n\nCtrl-C captured, exiting...\n");
printf("See you soon!\n");
exit(0);
}
/* Signal handler for ended child processes */
void sigchld_handler(int s){
while(waitpid(-1, NULL, WNOHANG) > 0);
}
/* TCP Server function */
int tcp_server(int debug){
is_server = 1;
signal(SIGCHLD, sigchld_handler);
signal(SIGINT, ctrlc_handler);
int sockfd, new_fd; // listen on sock_fd, new connection on new_fd
int port = SERV_PORT; // Port = 6649
int clientlen; // byte size of client's address
struct sockaddr_in serveraddr; // server's addr
struct sockaddr_in clientaddr; // client addr
struct hostent *hostp; // client host info
char *hostaddrp; // dotted decimal host addr string
int optval; // flag value for setsockopt
printf("TCP TIME server running in port %d\n", port);
/* socket: create the parent socket */
if(debug) printf("Creating socket for petitions\n");
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0) {
perror("ERROR opening socket");
exit(0);
}
/* setsockopt: lets s rerun the server immediately after we kill it.
* Eliminates "ERROR on binding: Address already in * use" error.
*/
optval = 1;
setsockopt(new_fd, SOL_SOCKET, SO_REUSEADDR,(const void *)&optval , sizeof(int));
/* build the server's Internet address */
if(debug) printf("Creating address\n");
bzero((char *) &serveraddr, sizeof(serveraddr));
serveraddr.sin_family = AF_INET; // IPv4
serveraddr.sin_addr.s_addr = htonl(INADDR_ANY);
serveraddr.sin_port = htons((unsigned short)port);
/* bind: associate the parent socket with a port */
if(debug) printf("Bind: Specify local address (with port)\n");
if (bind(sockfd, (struct sockaddr *) &serveraddr, sizeof(serveraddr)) < 0) {
perror("ERROR on binding");
exit(0);
}
/* listen: make this socket ready to accept connection requests */
if(debug) printf("Listen: Ready to get connections\n");
if (listen(sockfd, BACKLOG) < 0) {
perror("ERROR on listen");
exit(0);
}
/* wait for a connection request */
while(1) { // main accept() loop
clientlen = sizeof(clientaddr);
if(debug) printf("Listening for new connections...\n");
new_fd = accept(sockfd, (struct sockaddr *)&clientaddr, &clientlen);
if (new_fd == -1) {
perror("ERROR on accept");
exit(0);
}
if(debug) printf("New connection accepted\n");
/* gethostbyaddr: determine who sent the message */
if(debug) printf("getting client's address\n");
hostp = gethostbyaddr((const char *)&clientaddr.sin_addr.s_addr, sizeof(clientaddr.sin_addr.s_addr), AF_INET);
if (hostp == NULL) {
perror("ERROR on gethostbyaddr");
exit(0);
}
hostaddrp = inet_ntoa(clientaddr.sin_addr); // Net to ASCII (client addr)
if (hostaddrp == NULL) {
perror("ERROR on inet_ntoa\n");
exit(0);
}
//printf("server got connection from %s (%s)\n", hostp->h_name, hostaddrp);
if(!fork()){ // this is the child process: fork() == 0
if(debug) printf("New child process generated\n");
uint32_t time_send; // 32 bit long int
int n;
time_t own_time;
do{
if(debug) printf("Getting system time\n");
own_time = time(NULL); // Getting the server's time
if(debug) printf("Adjusting time to NTP timebase\n");
time_send = htonl(own_time + LINUX_TIMEBASE); // Adjusted
/* Sending time */
if(debug) printf("Sending...\n");
n = send(new_fd, &time_send, sizeof(uint32_t), 0);
if(n<0){
fprintf(stderr, "ERROR sending\n");
}else{
printf("Date & time correctly sent\n");
}
sleep(1); // Wait 1 second after sending new time
}while(n>0); // If n<0 -> Client closed connection
// Closed connection
if(debug) printf("Closing connection with client\n");
close(sockfd); // child doesn't need the listener
close(new_fd);
exit(0);
}
close(new_fd); // parent doesn't need this
}
return 0;
}
/* UDP Server function */
int udp_server(int debug){
is_server = 1;
signal(SIGCHLD, sigchld_handler);
signal(SIGINT, ctrlc_handler);
int port = SERV_PORT; // Port = 6649
socklen_t clientlen; // byte size of client's address
struct sockaddr_in serveraddr; // server's addr
struct sockaddr_in clientaddr; // client addr
struct hostent *hostp; // client host info
char *hostaddrp; // dotted decimal host addr string
int optval; // flag value for setsockopt
printf("UDP TIME server running in port %d\n", port);
/* socket: create the parent socket */
if(debug) printf("Creating socket for petitions\n");
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (sockfd < 0) {
perror("ERROR opening socket");
exit(0);
}
/* build the server's Internet address */
if(debug) printf("Creating address\n");
bzero((char *) &serveraddr, sizeof(serveraddr));
serveraddr.sin_family = AF_INET; // IPv4
serveraddr.sin_addr.s_addr = htonl(INADDR_ANY);
serveraddr.sin_port = htons((unsigned short)port);
/* bind: associate the parent socket with a port */
if(debug) printf("Bind: Specify local address (with port)\n");
if (bind(sockfd, (struct sockaddr *) &serveraddr, sizeof(serveraddr)) < 0) {
perror("ERROR on binding");
exit(0);
}
/* wait for a connection request */
while(1) { // main loop
clientlen = sizeof(clientaddr);
if(debug) printf("Listening for new connections...\n");
uint32_t time_send; // 32 bit long int
int n;
time_t own_time;
/* Receiving empty datagram */
char received[10];
n = recvfrom(sockfd, received, sizeof(received), 0, (struct sockaddr *)&clientaddr, &clientlen);
if( n < 0 ){
perror("ERROR receiving");
exit(0);
}else if (n == 0){
if(!fork()){
if(debug) printf("Getting system time\n");
own_time = time(NULL); // Getting the server's time
if(debug) printf("Adjusting time to NTP timebase\n");
time_send = htonl(own_time + LINUX_TIMEBASE); // Adjusted
/* Sending time */
if(debug) printf("Sending...\n");
n = sendto(sockfd, &time_send, sizeof(uint32_t), 0, (struct sockaddr *)&clientaddr, clientlen);
if(n < 0){
fprintf(stderr, "ERROR sending\n");
}else{
printf("Date & time correctly sent\n");
}
if(debug) printf("Closing connection with client\n");
close(sockfd);
exit(0);
}
}else{
if(debug) printf("Wrong type of datagram received, discarding...\n");
}
}
return 0;
}
/* TCP Client function */
int tcp_client(char *host, int port, int debug){
printf("Starting TCP\n");
int clientfd;
struct hostent *server;
struct sockaddr_in serveraddr;
uint32_t buf; // Variable to store the information received
int n;
signal(SIGINT, ctrlc_handler);
signal(SIGINT, ctrlc_handler);
/* socket: IPv4, STREAM + default protocol = TCP */
if(debug) printf("Creating socket\n");
clientfd = socket(AF_INET, SOCK_STREAM, 0);
if (clientfd < 0) {
perror("ERROR opening socket");
exit(0);
}
/* gethostbyname: get the server's DNS entry */
if(debug) printf("Getting server address\n");
server = gethostbyname(host);
if (server == NULL) {
fprintf(stderr,"ERROR, no such host: %s\n", host);
exit(0);
}
/* build the server's Internet address */
if(debug) printf("Storing server address\n");
bzero((char *) &serveraddr, sizeof(serveraddr));
serveraddr.sin_family = AF_INET;
bcopy((char *)server->h_addr, (char *)&serveraddr.sin_addr.s_addr, server->h_length);
serveraddr.sin_port = htons(port);
/* connect: create a connection with the server */
if (debug) printf("Creating connection\n");
if (connect(clientfd, (struct sockaddr *) &serveraddr, sizeof(serveraddr)) < 0) {
perror("ERROR connecting");
exit(0);
}
if(debug) printf("Waiting for server's answer\n");
/* read answer from the server */
while(1){
n = recv(clientfd, &buf, BUFSIZE, 0);
if (n < 0) {
perror("ERROR receiving");
exit(0);
}else{
if(debug) printf("Data received\n");
/* Format of date seen in:
* https://www.tutorialspoint.com/c_standard_library/c_function_strftime.htm
*/
time_t t_rcvd = ntohl(buf) - LINUX_TIMEBASE; // Adjust to linux
if(debug) printf("Adjusting time to linux timebase\n");
struct tm *final_date; // Struct tm with rcvd time
//final_date = localtime(&t_rcvd);
if(debug) printf("Formatting date\n");
char final_date_s[80]; // Buffer to store formatted string
strftime(final_date_s, 80, "%a %b %d %X %Z %Y", localtime(&t_rcvd));
/* print the server's reply */
if(debug) printf("Printing date\n");
printf("%s\n", final_date_s);
}
}
/* Close socket: ended connection */
if(debug) printf("Closing client\n");
close(clientfd);
return(0);
}
/* UDP Client function */
int udp_client(char *host, int port, int debug){
int clientfd;
struct hostent *server;
struct sockaddr_in serveraddr;
uint32_t buf; // Variable to store the information received
int n;
signal(SIGINT, ctrlc_handler);
/* socket: IPv4, DGRAM + default protocol = UDP */
if(debug) printf("Creating socket\n");
clientfd = socket(AF_INET, SOCK_DGRAM, 0);
if (clientfd < 0) {
perror("ERROR opening socket");
exit(0);
}
/* gethostbyname: get the server's DNS entry */
if(debug) printf("Getting server address\n");
server = gethostbyname(host);
if (server == NULL) {
fprintf(stderr,"ERROR, no such host: %s\n", host);
exit(0);
}
if(debug) printf("Storing server address\n");
/* build the server's Internet address */
bzero((char *) &serveraddr, sizeof(serveraddr));
serveraddr.sin_family = AF_INET;
bcopy((char *)server->h_addr, (char *)&serveraddr.sin_addr.s_addr, server->h_length);
serveraddr.sin_port = htons(port);
/* If the method "connect" is not used at this point, we'll use sendto and
* recvfrom, instead of send and recv
*/
/* connect: create a connection with the server */
if (debug) printf("Creating connection\n");
if (connect(clientfd, (struct sockaddr *) &serveraddr, sizeof(serveraddr)) < 0) {
perror("ERROR connecting");
exit(0);
}
if(debug) printf("Sending empty datagram\n");
/* Send empty message to server */
n = send(clientfd, NULL, 0, 0);
if (n < 0) {
perror("ERROR sending empty datagram");
exit(0);
}
if(debug) printf("Sent!\n");
if(debug) printf("Waiting for server's answer\n");
/* read answer from the server */
n = recv(clientfd, &buf, sizeof(buf), 0);
if (n < 0) {
perror("ERROR reading from socket");
exit(0);
}else{
if(debug) printf("Data received\n");
/* Format of date seen in:
* https://www.tutorialspoint.com/c_standard_library/c_function_strftime.htm
*/
time_t t_rcvd = ntohl(buf) - LINUX_TIMEBASE; // Adjust to linux
if(debug) printf("Adjusting time to linux timebase\n");
struct tm *final_date; // Struct tm with rcvd time
//final_date = localtime(&t_rcvd);
if(debug) printf("Formatting date\n");
char final_date_s[80]; // Buffer to store formatted string
strftime(final_date_s, 80, "%a %b %d %X %Z %Y", localtime(&t_rcvd));
/* print the server's reply */
if(debug) printf("Printing date\n");
printf("%s\n", final_date_s);
}
if(debug) printf("Closing client\n");
/* Close socket: ended connection */
close(clientfd);
return(0);
}
int main(int argc, char* const argv[]) {
int opt;
int debug = 0;
char* mode = NULL;
char* host = NULL;
int port = 37; // Default port for clients
char *str_opt;
/* Parsing command-line arguments
* Examples used from:
* https://www.gnu.org/software/libc/manual/html_node/Example-of-Getopt.html#Example-of-Getopt
*/
while((opt = getopt(argc, argv, "dh:p:m:")) != -1){
switch(opt){
case 'h':
host = optarg;
break;
case 'p':
port = atoi(optarg); // Convert input(ASCII) to int
break;
case 'm':
mode = optarg;
break;
case 'd':
debug = 1; // Debug set to true
break;
case '?':
usage();
}
}
if(mode == NULL){ // Default mode
if(debug) printf("No mode specified. Setting default mode (UDP Client)\n");
mode = "cu";
}
if((strcmp(mode,"cu") == 0) && host != NULL){
if(debug) printf("Executing UDP Client\n");
udp_client(host, port, debug);
}else if((strcmp(mode,"ct") == 0) && host != NULL){
if(debug) printf("Executing TCP Client\n");
tcp_client(host, port, debug);
}else if(strcmp(mode,"s") == 0){
if(debug) printf("Executing TCP Server\n");
tcp_server(debug);
}else if(strcmp(mode,"su") == 0){
if(debug) printf("Executing UDP Server\n");
udp_server(debug);
}else if(host == NULL){
printf("To execute Client Mode you must specify at least the option '-h'\n");
usage();
}
return 0;
}