handle IPv6 sources
[record-dvb] / http.c
1 #include <strings.h>
2 #include <string.h>
3 #include <stdio.h>
4 #include <stdlib.h>
5 #include <sys/types.h>
6 #include <sys/socket.h>
7 #include <netinet/in.h>
8 #include <arpa/inet.h>
9
10 #include "common.h"
11 #include "http.h"
12
13 #define BUFFSIZE 1024
14
15 int is_http(char *url)
16 {
17 if (strlen(url) < 8)
18 return 0;
19
20 if (!strncasecmp("http://",url,7))
21 return 1;
22
23 return 0;
24 }
25
26 int open_http(char *url)
27 {
28 int fd;
29 struct sockaddr_in server;
30 struct dvb_host *dvbhost = NULL;
31 char c, buffer[BUFFSIZE], *pos;
32 int lines = 0;
33
34 if(!is_http(url))
35 return -1;
36
37 dvbhost = parse(&(url[7]), "80");
38 dvbhost->socktype = SOCK_STREAM;
39
40 if (resolve(dvbhost, &server) < 0) {
41 return -1;
42 }
43
44 if ((fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0) {
45 perror("socket");
46 return -1;
47 }
48
49 if (connect(fd, (struct sockaddr*) &server, sizeof(server)) < 0) {
50 perror("connect");
51 return -1;
52 }
53
54 snprintf(buffer, BUFFSIZE-1, "GET /%s HTTP/1.0\n\n",dvbhost->location);
55 buffer[BUFFSIZE-1] = 0;
56 if (send(fd, buffer, strlen(buffer), 0) < 0) {
57 perror("send");
58 return -1;
59 }
60
61 pos = buffer;
62 while (1) {
63 if (recv(fd, &c, 1, 0) < 1) {
64 perror("recv");
65 exit(EXIT_FAILURE);
66 }
67
68 if (pos-buffer >= BUFFSIZE)
69 pos = buffer;
70
71 *(pos++) = c;
72
73 if (c == 0x0a) {
74 *(--pos) = 0;
75 if (pos-buffer > 0 && *(--pos) == 0x0d)
76 *pos = 0;
77
78 if (pos-buffer == 0)
79 break;
80
81 #ifdef DEBUG
82 printf("%d. %s (%d)\n", lines, buffer, pos-buffer);
83 #endif
84 if (lines == 0) {
85 if (strncasecmp("HTTP/", buffer, 5)) {
86 fprintf(stderr, "Wrong answer from server: %s\n", buffer);
87 return -1;
88 }
89
90 pos = buffer;
91 while (*pos != 0) {
92 if (*(pos++) == ' ') {
93 if(strncmp("200", pos, 3)) {
94 fprintf(stderr, "Wrong result-code: %s\n", buffer);
95 return -1;
96 } else {
97 break;
98 }
99 }
100
101 if (*(++pos) == 0) {
102 fprintf(stderr, "Wrong answer from server: %s\n", buffer);
103 return -1;
104 }
105 }
106 }
107
108 pos = buffer;
109 lines++;
110 }
111 }
112
113 return fd;
114 }
Impressum, Datenschutz