core: use string instead of compound literal
[rofl0r-proxychains-ng.git] / src / hostsreader.c
blob42e5323e19dc4606b20edd75725c279046b6d607
1 #include <stdio.h>
2 #include <ctype.h>
3 #include <string.h>
4 #include "common.h"
6 /*
7 simple reader for /etc/hosts
8 it only supports comments, blank lines and lines consisting of an ipv4 hostname pair.
9 this is required so we can return entries from the host db without messing up the
10 non-thread-safe state of libc's gethostent().
14 struct hostsreader {
15 FILE *f;
16 char* ip, *name;
19 int hostsreader_open(struct hostsreader *ctx) {
20 if(!(ctx->f = fopen("/etc/hosts", "r"))) return 0;
21 return 1;
24 void hostsreader_close(struct hostsreader *ctx) {
25 fclose(ctx->f);
28 int hostsreader_get(struct hostsreader *ctx, char* buf, size_t bufsize) {
29 while(1) {
30 if(!fgets(buf, bufsize, ctx->f)) return 0;
31 if(*buf == '#') continue;
32 char *p = buf;
33 size_t l = bufsize;
34 ctx->ip = p;
35 while(*p && !isspace(*p) && l) {
36 p++;
37 l--;
39 if(!l || !*p || p == ctx->ip) continue;
40 *p = 0;
41 p++;
42 while(*p && isspace(*p) && l) {
43 p++;
44 l--;
46 if(!l || !*p) continue;
47 ctx->name = p;
48 while(*p && !isspace(*p) && l) {
49 p++;
50 l--;
52 if(!l || !*p) continue;
53 *p = 0;
54 if(pc_isnumericipv4(ctx->ip)) return 1;
58 char* hostsreader_get_ip_for_name(const char* name, char* buf, size_t bufsize) {
59 struct hostsreader ctx;
60 char *res = 0;
61 if(!hostsreader_open(&ctx)) return 0;
62 while(hostsreader_get(&ctx, buf, bufsize)) {
63 if(!strcmp(ctx.name, name)) {
64 res = ctx.ip;
65 break;
68 hostsreader_close(&ctx);
69 return res;
72 #include "ip_type.h"
73 #include <netinet/in.h>
74 #include <sys/socket.h>
75 #include <arpa/inet.h>
76 ip_type4 hostsreader_get_numeric_ip_for_name(const char* name) {
77 char *hres;
78 char buf[320];
79 if((hres = hostsreader_get_ip_for_name(name, buf, sizeof buf))) {
80 struct in_addr c;
81 inet_aton(hres, &c);
82 ip_type4 res;
83 memcpy(res.octet, &c.s_addr, 4);
84 return res;
85 } else return IPT4_INVALID;
88 #ifdef HOSTSREADER_TEST
89 #include "ip_type.c"
90 int main(int a, char**b) {
91 char buf[256];
92 if(a != 2) return 1;
93 char * ret = hostsreader_get_ip_for_name(b[1], buf, sizeof buf);
94 printf("%s\n", ret ? ret : "null");
96 #endif