-
Notifications
You must be signed in to change notification settings - Fork 3
/
magan.c
1738 lines (1461 loc) · 45.9 KB
/
magan.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
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* ----------------------------------------------------------------------------
magan : a DoH server
Copyright (C) 2021 Evuraan, <evuraan@gmail.com>
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 <https://www.gnu.org/licenses/>.
* ----------------------------------------------------------------------------
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#include <pthread.h>
#include <assert.h>
#include <time.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <curl/curl.h>
#include <stdint.h>
#include <fcntl.h>
#include <endian.h>
#include <json-c/json.h>
#include <getopt.h>
#include <stdarg.h>
#include <sys/epoll.h>
#define bufsize 8192
#define ONE_K 1024
#define PORT 53
#define UDP_THREADS 4
#define EPOLL_MAXEVENTS 10
#define CACHE_MAX_ITEMS 100
#define CACHE_STALE 5*60 // seconds
#define VAL1 1331
#define VAL2 441
#define DISABLE_CACHE 0
struct udp_sender_thread_thingy {
int server_socket;
char *buffer;
struct sockaddr_in remoteaddr;
int addrlen;
int cut_here;
};
#pragma pack(push, 1)
struct tcp {
uint16_t length;
};
#pragma pack(pop)
struct reply {
size_t sendSize;
char *sendThis;
};
#pragma pack(push, 1)
struct dns_header {
uint16_t id;
#if __BYTE_ORDER == __BIG_ENDIAN
uint16_t qr:1;
uint16_t opcode:4;
uint16_t aa:1;
uint16_t tc:1;
uint16_t rd:1;
uint16_t ra:1;
uint16_t zero:3;
uint16_t rcode:4;
#elif __BYTE_ORDER == __LITTLE_ENDIAN
uint16_t rd:1;
uint16_t tc:1;
uint16_t aa:1;
uint16_t opcode:4;
uint16_t qr:1;
uint16_t rcode:4;
uint16_t zero:3;
/*
uint16_t cd :1; // Checking Disabled (DNSSEC only; disables checking at the receiving server)
uint16_t ad :1; // Authenticated Data (for DNSSEC only; indicates that the data was authenticated)
uint16_t z :1; // Reserved for future use Must be zero in all queries
*/
uint16_t ra:1;
#else
#error "Adjust your <bits/endian.h> defines"
#endif
uint16_t qdcount; /* question count */
uint16_t ancount; /* Answer record count */
uint16_t nscount; /* Name Server (Autority Record) Count */
uint16_t arcount; /* Additional Record Count */
};
#pragma pack(pop)
#pragma pack(push, 1)
struct dns_question {
uint16_t type;
uint16_t class;
};
#pragma pack(pop)
#pragma pack(push, 1)
struct dns_rr {
uint16_t type;
uint16_t class;
uint32_t ttl;
uint16_t rdlength;
};
#pragma pack(pop)
struct Node {
CURL *handle;
pthread_mutex_t *NodeMutex;
int TimeStamp;
struct curl_slist *slist;
int TimeDelta;
int Count;
int UsageFlag;
char *myslist_text;
struct MemoryStruct *Chunky;
struct Node *Next;
};
struct LinkedList {
struct Node *HeadNode;
struct Node *TailNode;
int LLSize;
};
struct MemoryStruct {
char *memory;
size_t size;
};
struct cacheStruct {
int key;
int epoch;
size_t len;
char hit[bufsize];
};
// all them global variables
static struct LinkedList *Roller;
static struct Node *UseThisNode = 0;
char resolv_this[] = "dns.google.com";
char use_ns[] = "8.8.8.8";
static char holdmine[bufsize] = { 0 };
static int flashed = 0;
const int ttl_max = 597;
curl_version_info_data *curl_version_data;
char getter_url[] = "https://dns.google.com/";
int pid;
char Name[] = "Magan";
char Version[] = "Magan/3.0a";
int LISTEN_PORT = 53;
int debug = 0;
pthread_t udpWorkers[UDP_THREADS] = { 0 };
int udpPipe[2] = { 0 };
struct cacheStruct cache[CACHE_MAX_ITEMS] = { 0 };
char dot[] = ".";
int sockfd = 0;
int epollFD = 0;
struct epoll_event epevent = { 0 };
struct epoll_event events[EPOLL_MAXEVENTS] = { 0 };
pthread_mutex_t cacheMutex = PTHREAD_MUTEX_INITIALIZER;
//prototypes here
char *getCacheEntry(char *url);
int doCurlStuff(char *url, char *json_buffer);
struct cacheStruct *cacheLookup(char *url);
struct cacheStruct *findValidHash(int key);
int get_hash(char *input);
void *udp_listener_thread(void *vargp);
int WriteMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp);
void read_back(char *label_in, int len, char *buffer);
void *tcp_listener(void *vargp);
void get_reply(char *request, int PROTO, struct reply *reply, int cut_here);
int get_random();
void convert(char *dns, char *host);
void do_lookup(char *resolv_this_input, char *dns_server_input, int Query_Type, char *hold_here);
void setup_holdmine();
char *get_currentTime();
int PopulateList(struct LinkedList *Roller, int slot);
void Prep_HANDLE(struct Node *Node);
int WriteMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp);
struct Node *get_CURLHANDLE();
void findNthWord(char *line_in, int n, char *word);
void init();
void show_usage();
void *send_udp_response(void *vargp);
int debug_print(char *format, ...);
int print(char *format, ...);
void *udpWorker(void *vargp);
int acceptNewConn();
//int populateCache(char *url, char *memory, int *chunkSize);
int populateCache(char *url, char *memory, uint chunkSize);
void handleTCPClient(int newSock);
int insertCacheEntry(struct cacheStruct *placeHere, char *memory, uint * chunkSize, int *keyPtr);
int main(int argc, char *argv[]) {
pid = getpid();
int c = 1;
print("%s Copyright (C) 2021 Evuraan <evuraan@gmail.com>\n", Version);
print("This program comes with ABSOLUTELY NO WARRANTY.\n");
while (c) {
static struct option long_options[] = {
{"port", required_argument, NULL, 'p'},
{"artist", required_argument, NULL, 'a'},
{"help", no_argument, NULL, 'h'},
{"debug", no_argument, NULL, 'd'},
{"version", no_argument, NULL, 'v'},
{NULL, 0, NULL, 0}
};
int option_index = 0;
c = getopt_long(argc, argv, "p:hvd", long_options, &option_index);
if (c == -1) {
break;
}
switch (c) {
case 'p':
;
char *ptr_alt_port;
LISTEN_PORT = strtod(optarg, &(ptr_alt_port));
if ((LISTEN_PORT <= 0) || (LISTEN_PORT > 65535)) {
fprintf(stderr, "%s %s[%d]: Invalid alternate port, exiting.\n", get_currentTime(), Name, pid);
return 1;
}
break;
case 'h':
case '?':
show_usage();
return 1;
break;
case 'd':
debug++;
debug_print("Debug set\n");
break;
case 'v':
printf("Version: %s\n", Version);
return 1;
break;
default:
printf("?? getopt returned character code 0%o ??\n", c);
show_usage();
return 1;
break;
}
}
printf("%s %s[%d]: Listening on port: %d\n", get_currentTime(), Name, pid, LISTEN_PORT);
pthread_t udp, tcp = { 0 };
//tcp listener
int tcp_rc = pthread_create(&tcp, NULL, tcp_listener, NULL);
assert(tcp_rc == 0);
//udp_listener();
int udp_rc = pthread_create(&udp, NULL, udp_listener_thread, NULL);
assert(udp_rc == 0);
usleep(50);
// launch udp thread workers
// init udp Pipes:
if (pipe(udpPipe) < 0) {
perror("pipe err\n");
exit(1);
}
// spawn worker threads:
int rc, worker = 0;
for (int i = 0; i < (UDP_THREADS - 1); i++) {
debug_print("Launching udp worker: %d\n", worker++);
rc = pthread_create(&udpWorkers[i], 0, udpWorker, 0);
if (rc) {
printf("Failed launching worker: %d\n", i);
}
}
// become the last udp worker, instead of idling around:
debug_print("Launching udp worker: %d\n", worker++);
udpWorker(0);
pthread_join(udp, NULL);
return 0;
}
void show_usage() {
printf("Usage: \n");
printf(" -h --help print this usage and exit\n");
printf(" -p --port alternate port to listen\n");
printf(" -d --debug show debug info\n");
printf(" -v --version print version information and exit\n");
_exit(1);
}
void *udpWorker(void *vargp) {
(void)vargp;
pthread_t tid = pthread_self();
debug_print("[%s] worker %ld\n", __func__, tid);
int n = 0;
uintptr_t ptrAsInt = 0;
struct udp_sender_thread_thingy *udp_sender_thread_thingy = 0;
while (1) {
udp_sender_thread_thingy = 0;
ptrAsInt = 0;
n = read(udpPipe[0], &ptrAsInt, sizeof(ptrAsInt));
if (!n) {
perror("worker read\n");
continue;
}
if (!ptrAsInt) {
perror("ptrAsInt null\n");
continue;
}
udp_sender_thread_thingy = (struct udp_sender_thread_thingy *)ptrAsInt;
send_udp_response(udp_sender_thread_thingy);
debug_print("[%s] answered by worker thread %ld\n", __func__, tid);
}
}
void init() {
setbuf(stdout, NULL);
char looking_for[8] = "https";
if (memcmp(getter_url, looking_for, strnlen(looking_for, 8)) == 0) {
// reasonably fair assumption to make in Dec 2019:
snprintf(holdmine, ONE_K, "%s", "dns.google.com:443:8.8.4.4");
setup_holdmine();
} else {
printf("Non https url, skipping setup_holdmine()\n");
}
Roller = calloc(1, sizeof(*Roller));
curl_version_data = curl_version_info(CURLVERSION_NOW);
#if LIBCURL_VERSION_NUM >= 0x073800
if (curl_version_data->version_num >= 0x073800) {
CURLsslset result;
result = curl_global_sslset((curl_sslbackend) 1, NULL, NULL);
assert(result == CURLSSLSET_OK);
} else {
//printf("%s %s[%d]: Note: libcurl does not support CURLSSLBACKEND_OPENSSL et al\n", get_currentTime(), Name, pid);
}
#else
#warning "libcurl version too old to set CURLSSLBACKEND_OPENSSL"
//printf("%s %s[%d]: Note: libcurl does not support CURLSSLBACKEND_OPENSSL et al\n", get_currentTime(), Name, pid);
#endif
curl_global_init(CURL_GLOBAL_ALL);
PopulateList(Roller, 4);
print("Ready..\n");
}
void *udp_listener_thread(void *vargp) {
(void)vargp;
int PROTO = SOCK_DGRAM;
int server_socket = socket(AF_INET, PROTO, 0);
if (server_socket < 0) {
fprintf(stderr, "socket error");
return NULL;
}
//bind
struct sockaddr_in myaddr = { 0 };
struct sockaddr_in remoteaddr = { 0 };
uint addrlen = sizeof(remoteaddr);
myaddr.sin_family = AF_INET;
myaddr.sin_addr.s_addr = INADDR_ANY;
myaddr.sin_port = htons(LISTEN_PORT);
if (bind(server_socket, (struct sockaddr *)&myaddr, sizeof(myaddr)) < 0) {
fprintf(stderr, "bind error\n");
perror("Failed at udp bind");
_exit(1);
return NULL;
}
init();
// any allocations for the while True loop should happen out here
uint recvlen = 0;
uintptr_t ptrAsInt = 0;
int n = 0;
while (1) {
n = 0;
recvlen = 0;
struct udp_sender_thread_thingy *udp_sender_thread_thingy = calloc(2, sizeof(struct udp_sender_thread_thingy));
udp_sender_thread_thingy->addrlen = addrlen;
udp_sender_thread_thingy->server_socket = server_socket;
char *buffer = calloc(bufsize, sizeof(*buffer));
recvlen = recvfrom(server_socket, buffer, bufsize, 0, (struct sockaddr *)&remoteaddr, &addrlen);
debug_print("UDP Recvd %d bytes\n", recvlen);
udp_sender_thread_thingy->buffer = buffer;
udp_sender_thread_thingy->remoteaddr = remoteaddr;
udp_sender_thread_thingy->cut_here = recvlen;
ptrAsInt = (uintptr_t) udp_sender_thread_thingy;
n = write(udpPipe[1], &ptrAsInt, sizeof(ptrAsInt));
if (n) {
debug_print("Sent %d bytes to workers PTr: %lu\n", n, ptrAsInt);
} else {
perror("Dispatch fail\n");
//exit(1);
free(udp_sender_thread_thingy->buffer);
free(udp_sender_thread_thingy);
}
}
pthread_exit(NULL);
}
void *send_udp_response(void *vargp) {
struct timeval start, end = { 0 };
long secs_used, micros_used;
gettimeofday(&start, NULL);
struct udp_sender_thread_thingy *udp_sender_thread_thingy = (struct udp_sender_thread_thingy *)vargp;
int PROTO = SOCK_DGRAM;
struct reply reply = { 0 };
reply.sendSize = 0;
char sendThis[bufsize] = { 0 };
reply.sendThis = sendThis;
get_reply(udp_sender_thread_thingy->buffer, PROTO, &reply, udp_sender_thread_thingy->cut_here);
int sendlen = sendto(udp_sender_thread_thingy->server_socket, reply.sendThis, reply.sendSize, 0, (struct sockaddr *)&udp_sender_thread_thingy->remoteaddr, udp_sender_thread_thingy->addrlen);
gettimeofday(&end, NULL);
secs_used = (end.tv_sec - start.tv_sec);
micros_used = ((secs_used * 1000000) + end.tv_usec) - (start.tv_usec);
free(udp_sender_thread_thingy->buffer);
free(udp_sender_thread_thingy);
debug_print("%s %s[%d]: udp sendlen: %d bytes, took %lu microseconds\n", get_currentTime(), Name, pid, sendlen, micros_used);
return 0;
}
void *tcp_listener(void *vargp) {
(void)vargp;
int PROTO = SOCK_STREAM;
// Create socket first
sockfd = socket(AF_INET, PROTO, 0);
if (sockfd < 0) {
perror("socket error\n");
return NULL;
}
/* Second: Set socket options */
int optval = 1;
int sockopt_int = setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval));
if (sockopt_int < 0) {
perror("Failed at setsockopt");
return NULL;
}
/* Third: Bind to the port */
/* int bind(int sockfd, const struct sockaddr *addr, socklen_t addrlen); */
struct sockaddr_in address = { 0 };
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons(LISTEN_PORT);
int bind_int = bind(sockfd, (struct sockaddr *)&address, sizeof(address));
if (bind_int < 0) {
perror("Failed at bind");
_exit(1);
return NULL;
}
/* Fourth : Listen
Mark sockfd as passive - so it can accept incoming connections
*/
if (listen(sockfd, 200) < 0) {
perror("Failed at listen");
return NULL;
}
// and then give every thing over to epoll to perform C10K magic!
// epoll_create
if ((epollFD = epoll_create(1)) < 0) {
perror("epoll_create failed");
exit(1);
}
epevent.events = EPOLLIN;
epevent.data.fd = sockfd;
if (epoll_ctl(epollFD, EPOLL_CTL_ADD, sockfd, &epevent) < 0) {
perror("epoll_ctl failed");
exit(1);
}
int eventCount = 0;
while ((eventCount = epoll_wait(epollFD, events, EPOLL_MAXEVENTS, -1)) > 0) {
for (int i = 0; i < eventCount; i++) {
if (events[i].events & EPOLLERR || events[i].events & EPOLLRDHUP || events[i].events & EPOLLHUP) {
print("Closing: %d\n", events[i].data.fd);
close(events[i].data.fd);
} else if (events[i].events & EPOLLIN) {
// incoming
if (events[i].data.fd == sockfd) {
// new connection - try accepting this.
if (acceptNewConn() < 0) {
perror("Error accepting new client");
}
} else {
// Client is sending a req.
handleTCPClient(events[i].data.fd);
}
}
}
}
return 0;
}
int acceptNewConn() {
struct sockaddr_in address = { 0 };
int addrlen = sizeof(address);
int clientSock = accept(sockfd, (struct sockaddr *)&address, (socklen_t *) & addrlen);
if (debug > 0) {
char somebuff[bufsize] = { 0 };
inet_ntop(AF_INET, &address.sin_addr, somebuff, INET_ADDRSTRLEN);
debug_print("[%s] Connection from %s, port %d\n", __func__, somebuff, ntohs(address.sin_port));
}
if (clientSock) {
struct epoll_event epevent = { 0 };
epevent.events = EPOLLIN | EPOLLRDHUP;
epevent.data.fd = clientSock;
if (epoll_ctl(epollFD, EPOLL_CTL_ADD, clientSock, &epevent) < 0) {
perror("epoll_ctl failed accepting from a new client");
shutdown(clientSock, SHUT_RDWR);
close(clientSock);
return -1;
} else {
debug_print("[%s] Added new connection %d to epoll\n", __func__, clientSock);
}
}
return 0;
}
void handleTCPClient(int newSock) {
if (!newSock) {
return;
}
char ReadThis[bufsize] = { 0 };
char sendThis[bufsize] = { 0 };
struct timeval start, end = { 0 };
gettimeofday(&start, 0);
int n = read(newSock, ReadThis, bufsize);
if (n <= 0) {
return;
}
debug_print("TCP Recvd %d bytes\n", n);
long secs_used, micros_used = 0;
struct reply replyThing = {.sendSize = 0,.sendThis = sendThis };
get_reply(ReadThis, SOCK_STREAM, &replyThing, n);
int sendlen = send(newSock, replyThing.sendThis, replyThing.sendSize, 0);
gettimeofday(&end, NULL);
secs_used = (end.tv_sec - start.tv_sec);
micros_used = ((secs_used * 1000000) + end.tv_usec) - (start.tv_usec);
debug_print("%s %s[%d]: tcp sendlen: %d bytes, took %lu microseconds\n", get_currentTime(), Name, pid, sendlen, micros_used);
}
void read_back(char *label_in, int len, char *buffer) {
char label[ONE_K] = { 0 };
if (len > ONE_K) {
len = ONE_K;
}
memcpy(&label, label_in, len);
char *we_made = buffer;
int labelVal = 0;
for (int i = 1; i < len; i++) {
labelVal = (int)label[i];
if (labelVal == 192) {
break;
} else if (label[i] < 45) {
we_made[i - 1] = '.';
} else if ((labelVal >= 40) && (labelVal < 192)) {
we_made[i - 1] = label[i];
} else {
we_made[i - 1] = 46;
}
}
return;
}
// request is bufsize long
void get_reply(char *request, int PROTO, struct reply *reply, int cut_here) {
char *r = request;
char *tcbuf = request; // to send the tc goody if needed later
struct tcp tcp = { 0 };
uint16_t somenu = 0;
if (PROTO == SOCK_STREAM) {
//puts("Inching tcp header");
memcpy(&somenu, r, sizeof(somenu));
r += sizeof(tcp);
}
struct dns_header header = { 0 };
memcpy(&header, r, sizeof(header));
if ((header.opcode > 0) || (header.rcode > 0) || (ntohs(header.qdcount) != 1) || (ntohs(header.arcount) > 10) || (ntohs(header.nscount) > 10)) {
printf("%s %s[%d]: Bad Query, QueryId: %d - outta here!\n", get_currentTime(), Name, pid, ntohs(header.id));
reply->sendSize = 12; // just to mess with, send back some junk from our side too..
return;
}
r += sizeof(header);
char *Question_start = r;
int nlen = bufsize - (r - request);
if (nlen < 0) {
return;
}
//int end = find_null(r);
int end = strnlen(r, nlen);
char question[ONE_K] = { 0 };
memcpy(&question, r, ONE_K);
char readable[4096] = { 0 };
read_back(question, end, readable);
//printf("Question: %s\n", readable);
end = strnlen(question, ONE_K);
r += end + 1;
struct dns_question dns_question = { 0 };
memcpy(&dns_question, r, sizeof(dns_question));
uint16_t queType = ntohs(dns_question.type);
int Question_Size = end + 1 + sizeof(dns_question);
char Question[bufsize] = { 0 };
memcpy(&Question, Question_start, Question_Size);
//printf("for lols, question is %s\n", Question);
//--------------------------------------------------------------------------------------------------------------------------//
char *R = reply->sendThis;
int rcode = 0;
struct dns_header reply_header = { 0 };
memcpy(&reply_header, &header, sizeof(header)); // copy header from request,
// deduce url to go for:
char url[bufsize] = { 0 };
char *pointTo = readable;
if ((queType == 2) && (!strnlen(readable, 10))) {
// a recursive query.
pointTo = dot;
}
snprintf(url, bufsize, "%sresolve?name=%s&type=%d", getter_url, pointTo, queType);
debug_print("Url: %s\n", url);
char *json_buffer = 0;
char awkward[bufsize] = { 0 };
int gotData = 0;
json_buffer = getCacheEntry(url);
if (!json_buffer) {
if (doCurlStuff(url, awkward)) {
json_buffer = awkward;
gotData++;
}
} else {
debug_print("Cache hit for %s\n", url);
gotData++;
}
if (!json_buffer) {
// this may need an rcode 5, pivots on gotData below.
json_buffer = awkward;
}
if (gotData) {
rcode = 0;
reply_header.rcode = rcode;
reply_header.ancount = 0;
reply_header.arcount = 0;
reply_header.nscount = 0;
reply_header.qr = 1;
reply_header.ra = 1;
} else {
rcode = 5;
reply_header.rcode = 5;
reply_header.ancount = htons(0);
reply_header.arcount = 0;
reply_header.nscount = 0;
reply_header.qr = 1;
}
struct json_object *parsed_json_a, *parsed_json_b;
struct json_object *Question_json;
struct json_object *TC;
struct json_object *AD;
struct json_object *Answers; // Answers - plural
struct json_object *answer; // holds the answer (singular) from Answers
struct json_object *Comment;
struct json_object *RA;
struct json_object *CD;
struct json_object *Status;
struct json_object *RD;
parsed_json_a = json_tokener_parse(json_buffer);
json_object_object_get_ex(parsed_json_a, "Question", &Question_json);
json_object_object_get_ex(parsed_json_a, "TC", &TC);
json_object_object_get_ex(parsed_json_a, "AD", &AD);
json_object_object_get_ex(parsed_json_a, "Answer", &Answers);
json_object_object_get_ex(parsed_json_a, "Comment", &Comment);
json_object_object_get_ex(parsed_json_a, "RA", &RA);
json_object_object_get_ex(parsed_json_a, "CD", &CD);
json_object_object_get_ex(parsed_json_a, "Status", &Status);
json_object_object_get_ex(parsed_json_a, "RD", &RD);
if (Answers == NULL) {
reply_header.rcode = json_object_get_int(Status);
debug_print("ancount 0 for %s, rcode is %d\n", readable, reply_header.rcode);
reply_header.ancount = 0;
// put changed header this into reply
memcpy(R, &reply_header, sizeof(reply_header)); // <<<
R += sizeof(reply_header);
//copy over Question to response,
memcpy(R, &Question, Question_Size); // <<<
debug_print("Question_Size is %d\n", Question_Size);
//R += Question_Size;
reply->sendSize = sizeof(reply_header) + Question_Size;
} else if (json_object_get_int(Status) != 0) {
debug_print("Status is 0, Send rcode 2 or 5\n");
reply_header.rcode = 2;
// put changed header this into reply
memcpy(R, &reply_header, sizeof(reply_header)); // <<<
R += sizeof(reply_header);
//copy over Question to response,
memcpy(R, &Question, Question_Size); // <<<
R += Question_Size;
memcpy(R, &question, end); // <<<
R += (end + 1);
reply->sendSize = sizeof(reply_header) + Question_Size + end + 1;
} else {
size_t answer_count, i;
reply_header.aa = 1;
answer_count = json_object_array_length(Answers);
//printf("we got %lu answers\n", answer_count);
reply_header.ancount = htons(answer_count);
// put changed header this into reply
memcpy(R, &reply_header, sizeof(reply_header)); // <<<
R += sizeof(reply_header);
/*
|###[ DNS Question Record ]###
| qname = 'www.cnn.com.'
| qtype = A
| qclass = IN // Question Size
*/
//copy over Question to response,
memcpy(R, Question, Question_Size); // <<<
R += Question_Size;
memcpy(R, question, end); // <<<
reply->sendSize = sizeof(reply_header) + Question_Size;
// int Question_Size = end + 1 + sizeof(dns_question) ;
for (i = 0; i < answer_count; i++) {
//printf("iter %ld \n " ,i);
answer = json_object_array_get_idx(Answers, i);
//printf(" We are here.. %lu : %s\n", i,json_object_get_string(answer) );
parsed_json_b = json_tokener_parse(json_object_get_string(answer));
struct json_object *name;
struct json_object *type;
struct json_object *TTL;
struct json_object *data;
json_object_object_get_ex(parsed_json_b, "name", &name);
json_object_object_get_ex(parsed_json_b, "type", &type);
json_object_object_get_ex(parsed_json_b, "TTL", &TTL);
json_object_object_get_ex(parsed_json_b, "data", &data);
int answer_type = json_object_get_int(type);
char con_ns[bufsize] = { 0 };
// general protection:
int dataLen = json_object_get_string_len(name);
if (!dataLen || dataLen > ONE_K) {
continue;
}
char *interim_buf = (char *)json_object_get_string(name);
convert(con_ns, interim_buf);
int end_here = strnlen(con_ns, bufsize);
memcpy(R, con_ns, end_here);
R += end_here + 1;
reply->sendSize += end_here + 1;
// general protection:
dataLen = json_object_get_string_len(data);
if (!dataLen || dataLen > ONE_K) {
continue;
}
if ((answer_type == 2) || (answer_type == 5) || (answer_type == 12)) {
memset(con_ns, 0, bufsize);
char *mehu = (char *)json_object_get_string(data);
convert(con_ns, mehu);
int nslen = strnlen(con_ns, bufsize) + 1;
struct dns_rr dns_rr = { 0 };
dns_rr.type = htons(answer_type);
dns_rr.class = htons(1);
dns_rr.ttl = htonl(json_object_get_int(TTL));
dns_rr.rdlength = htons(nslen);
memcpy(R, &dns_rr, sizeof(dns_rr));
R += sizeof(dns_rr);
reply->sendSize += sizeof(dns_rr);
memcpy(R, con_ns, nslen);
reply->sendSize += nslen;
R += nslen;
} else if ((answer_type == 99) || (answer_type == 16)) {
memset(con_ns, 0, bufsize);
int watermark = 255;
char *mehu = (char *)json_object_get_string(data);
int len = dataLen;
char *mehu_ptr = mehu;
char *con_ns_ptr = con_ns;
if (len <= watermark) {
con_ns[0] = len;
for (int i = 0; i < len; i++) {
con_ns[i + 1] = mehu[i];
}
} else {
int x = len / watermark;
int this_slice_len = 0;
for (int i = 0; i < (x + 1); i++) {
char mytemp[bufsize] = { 0 };
char *mytemp_ptr = mytemp;
if (i == 0) {
// this slice is watermark long
this_slice_len = watermark;
} else {
// could this be another ginormous slice?
int mehu_ptr_len = strnlen(mehu_ptr, ONE_K);
if (mehu_ptr_len >= watermark) {
this_slice_len = watermark;
} else {
this_slice_len = mehu_ptr_len;
}
}
mytemp[0] = this_slice_len;
mytemp_ptr += 1;
memcpy(mytemp_ptr, mehu_ptr, this_slice_len);
mytemp_ptr += this_slice_len;
mehu_ptr += this_slice_len;
memcpy(con_ns_ptr, mytemp, (1 + this_slice_len));
con_ns_ptr += (1 + this_slice_len);
}
}
int nslen = strnlen(con_ns, bufsize);
struct dns_rr dns_rr = { 0 };
dns_rr.type = htons(answer_type);
dns_rr.class = htons(1);
dns_rr.ttl = htonl(json_object_get_int(TTL));
dns_rr.rdlength = htons(nslen);
memcpy(R, &dns_rr, sizeof(dns_rr));
R += sizeof(dns_rr);
reply->sendSize += sizeof(dns_rr);
memcpy(R, con_ns, nslen);
reply->sendSize += nslen;
R += nslen;
} else if (answer_type == 15) {
char *mehu = (char *)json_object_get_string(data);
memset(con_ns, 0, bufsize);
char scratch_text[ONE_K] = { 0 };
findNthWord(mehu, 0, scratch_text);
debug_print("prio scratch; %s\n", scratch_text);
char *ptr;
int priority_int = strtod(scratch_text, &(ptr));
uint16_t priority = htons(priority_int);
memset(scratch_text, 0, ONE_K);
findNthWord(mehu, 1, scratch_text);
convert(con_ns, scratch_text);
int rdlen = sizeof(priority) + strnlen(con_ns, bufsize) + 1;
struct dns_rr dns_rr = { 0 };
dns_rr.type = htons(answer_type);
dns_rr.class = htons(1);
dns_rr.ttl = htonl(json_object_get_int(TTL));
dns_rr.rdlength = htons(rdlen);
memcpy(R, &dns_rr, sizeof(dns_rr));
R += sizeof(dns_rr);
memcpy(R, &priority, sizeof(priority));
R += sizeof(priority);
memcpy(R, con_ns, strnlen(con_ns, bufsize) + 1);
R += strnlen(con_ns, bufsize) + 1;
reply->sendSize += rdlen + sizeof(dns_rr);
} else if (answer_type == 28) {
//memset(con_ns, 0 , ONE_K); // we don't need it here
char *mehu = (char *)json_object_get_string(data);
struct sockaddr_in6 sa2 = { 0 };
inet_pton(AF_INET6, mehu, &(sa2.sin6_addr));
struct dns_rr dns_rr = { 0 };
dns_rr.type = htons(answer_type);
dns_rr.class = htons(1);
dns_rr.ttl = htonl(json_object_get_int(TTL));
dns_rr.rdlength = htons(sizeof(sa2.sin6_addr));
memcpy(R, &dns_rr, sizeof(dns_rr));
R += sizeof(dns_rr);
memcpy(R, &sa2.sin6_addr, sizeof(sa2.sin6_addr));
R += sizeof(sa2.sin6_addr);
reply->sendSize += sizeof(sa2.sin6_addr) + sizeof(dns_rr);
} else if (answer_type == 1) {
//memset(con_ns, 0 , ONE_K);
char *mehu = (char *)json_object_get_string(data);
struct sockaddr_in sa = { 0 };
inet_pton(AF_INET, mehu, &(sa.sin_addr));
struct dns_rr dns_rr = { 0 };
dns_rr.type = htons(answer_type);
dns_rr.class = htons(1);
dns_rr.ttl = htonl(json_object_get_int(TTL));
dns_rr.rdlength = htons(sizeof(sa.sin_addr));
memcpy(R, &dns_rr, sizeof(dns_rr));