Skip to content
This repository was archived by the owner on Aug 7, 2025. It is now read-only.

Commit bd96e69

Browse files
committed
Fetch hostname and write to *-user-data file
Fixes #57
1 parent 1ec2e49 commit bd96e69

1 file changed

Lines changed: 67 additions & 4 deletions

File tree

src/ucd-data-fetch.c

Lines changed: 67 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -233,7 +233,7 @@ static int write_lines(int out, FILE *f, size_t cl, const char *prefix)
233233
int main(int argc, char *argv[]) {
234234
int conf = -1;
235235
int sockfd;
236-
char *request, *request2;
236+
char *request, *request2, *request3;
237237
char *outpath;
238238
int n = 0;
239239

@@ -414,17 +414,80 @@ int main(int argc, char *argv[]) {
414414
}
415415
}
416416

417+
/* next, get hostname */
418+
if (!config[conf].request_hostname_path)
419+
goto user_data;
420+
421+
if (asprintf(&request2, "GET %s HTTP/1.1\r\nhost: %s \r\nConnection: keep-alive\r\n\r\n",
422+
config[conf].request_hostname_path, config[conf].ip) < 0) {
423+
FAIL("asprintf");
424+
}
425+
len = strlen(request2);
426+
427+
if (write(sockfd, request2, len) < (ssize_t)len) {
428+
close(sockfd);
429+
FAIL("write()");
430+
}
431+
432+
f = fdopen(sockfd, "r");
433+
if (!f) {
434+
close(sockfd);
435+
FAIL("fdopen()");
436+
}
437+
438+
/* parse/discard the header and body */
439+
result = parse_headers(f, &cl);
440+
if (result == 0) {
441+
/* error - exit */
442+
fclose(f);
443+
close(out);
444+
FAIL("parse_headers()");
445+
}
446+
447+
/* don't write part #2 if 404 or some non-error */
448+
if ((result != 2) && (write_lines(out, f, cl, "hostname: ") != 0)) {
449+
close(out);
450+
fclose(f);
451+
unlink(outpath);
452+
FAIL("write_lines()");
453+
}
454+
455+
/* cleanup */
456+
fclose(f);
457+
458+
/* reopen socket */
459+
sockfd = socket(AF_INET, SOCK_STREAM, 0);
460+
if (sockfd < 0) {
461+
FAIL("socket()");
462+
}
463+
464+
n = 0;
465+
for (;;) {
466+
int r = connect(sockfd, (struct sockaddr *)&server, sizeof(server));
467+
if (r == 0) {
468+
break;
469+
}
470+
if ((errno != EAGAIN) && (errno != ENETUNREACH) && (errno != ETIMEDOUT)) {
471+
FAIL("connect()");
472+
}
473+
nanosleep(&ts, NULL);
474+
if (++n > 200) { /* 10 secs */
475+
FAIL("timeout in connect()");
476+
}
477+
}
478+
479+
user_data:
417480
/* next, get user-data */
418481
if (!config[conf].request_userdata_path)
419482
goto finish;
420483

421-
if (asprintf(&request2, "GET %s HTTP/1.1\r\nhost: %s \r\nConnection: keep-alive\r\n\r\n",
484+
if (asprintf(&request3, "GET %s HTTP/1.1\r\nhost: %s \r\nConnection: keep-alive\r\n\r\n",
422485
config[conf].request_userdata_path, config[conf].ip) < 0) {
423486
FAIL("asprintf");
424487
}
425-
len = strlen(request2);
488+
len = strlen(request3);
426489

427-
if (write(sockfd, request2, len) < (ssize_t)len) {
490+
if (write(sockfd, request3, len) < (ssize_t)len) {
428491
close(sockfd);
429492
FAIL("write()");
430493
}

0 commit comments

Comments
 (0)