]> git.zerfleddert.de Git - record-dvb/blob - http.c
ab798d9956f64cd55ee030d05fe45a3cd101cd29
[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 static 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 if (!dvbhost) {
38 dvbhost = parse(&(url[7]), "80");
39 dvbhost->socktype = SOCK_STREAM;
40 }
41
42 if (resolve(dvbhost, &server) < 0) {
43 return -1;
44 }
45
46 if ((fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0) {
47 perror("socket");
48 return -1;
49 }
50
51 if (connect(fd, (struct sockaddr*) &server, sizeof(server)) < 0) {
52 perror("connect");
53 return -1;
54 }
55
56 snprintf(buffer, BUFFSIZE-1, "GET /%s HTTP/1.0\n\n",dvbhost->location);
57 buffer[BUFFSIZE-1] = 0;
58 if (send(fd, buffer, strlen(buffer), 0) < 0) {
59 perror("send");
60 return -1;
61 }
62
63 pos = buffer;
64 while (1) {
65 if (recv(fd, &c, 1, 0) < 1) {
66 perror("recv");
67 exit(EXIT_FAILURE);
68 }
69
70 if (pos-buffer >= BUFFSIZE)
71 pos = buffer;
72
73 *(pos++) = c;
74
75 if (c == 0x0a) {
76 *(--pos) = 0;
77 if (pos-buffer > 0 && *(--pos) == 0x0d)
78 *pos = 0;
79
80 if (pos-buffer == 0)
81 break;
82
83 #ifdef DEBUG
84 printf("%d. %s (%d)\n", lines, buffer, pos-buffer);
85 #endif
86 if (lines == 0) {
87 if (strncasecmp("HTTP/", buffer, 5)) {
88 fprintf(stderr, "Wrong answer from server: %s\n", buffer);
89 return -1;
90 }
91
92 pos = buffer;
93 while (*pos != 0) {
94 if (*(pos++) == ' ') {
95 if(strncmp("200", pos, 3)) {
96 fprintf(stderr, "Wrong result-code: %s\n", buffer);
97 return -1;
98 } else {
99 break;
100 }
101 }
102
103 if (*(++pos) == 0) {
104 fprintf(stderr, "Wrong answer from server: %s\n", buffer);
105 return -1;
106 }
107 }
108 }
109
110 pos = buffer;
111 lines++;
112 }
113 }
114
115 return fd;
116 }
Impressum, Datenschutz