]> git.donarmstrong.com Git - samtools.git/blob - knetfile.c
* samtools-0.1.5-3 (r393)
[samtools.git] / knetfile.c
1 #include <time.h>
2 #include <stdio.h>
3 #include <netdb.h>
4 #include <ctype.h>
5 #include <stdlib.h>
6 #include <string.h>
7 #include <unistd.h>
8 #include <sys/types.h>
9 #include <arpa/inet.h>
10 #include <sys/socket.h>
11 #include "knetfile.h"
12
13 static int socket_wait(int fd, int is_read)
14 {
15         fd_set fds, *fdr = 0, *fdw = 0;
16         struct timeval tv;
17         int ret;
18         tv.tv_sec = 5; tv.tv_usec = 0; // 5 seconds time out
19         FD_ZERO(&fds);
20         FD_SET(fd, &fds);
21         if (is_read) fdr = &fds;
22         else fdw = &fds;
23         ret = select(fd+1, fdr, fdw, 0, &tv);
24         if (ret == -1) perror("select");
25         return ret;
26 }
27
28 static int socket_connect(const char *host, const char *port)
29 {
30 #define __err_connect(func) do { perror(func); freeaddrinfo(res); return -1; } while (0)
31
32         int on = 1, fd;
33         struct linger lng = { 0, 0 };
34         struct addrinfo hints, *res;
35         memset(&hints, 0, sizeof(struct addrinfo));
36         hints.ai_family = AF_UNSPEC;
37         hints.ai_socktype = SOCK_STREAM;
38         if (getaddrinfo(host, port, &hints, &res) != 0) __err_connect("getaddrinfo");
39         if ((fd = socket(res->ai_family, res->ai_socktype, res->ai_protocol)) == -1) __err_connect("socket");
40         if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) == -1) __err_connect("setsockopt");
41         if (setsockopt(fd, SOL_SOCKET, SO_LINGER, &lng, sizeof(lng)) == -1) __err_connect("setsockopt");
42         if (connect(fd, res->ai_addr, res->ai_addrlen) != 0) __err_connect("connect");
43         freeaddrinfo(res);
44         return fd;
45 }
46
47 static off_t my_read(int fd, void *buf, off_t len)
48 {
49         off_t rest = len, curr, l = 0;
50         while (rest) {
51                 if (socket_wait(fd, 1) <= 0) break; // socket is not ready for reading
52                 curr = read(fd, buf + l, rest);
53                 if (curr == 0) break;
54                 l += curr; rest -= curr;
55         }
56         return l;
57 }
58
59 /*************************
60  * FTP specific routines *
61  *************************/
62
63 static int kftp_get_response(knetFile *ftp)
64 {
65         unsigned char c;
66         int n = 0;
67         char *p;
68         if (socket_wait(ftp->ctrl_fd, 1) <= 0) return 0;
69         while (read(ftp->ctrl_fd, &c, 1)) { // FIXME: this is *VERY BAD* for unbuffered I/O
70                 //fputc(c, stderr);
71                 if (n >= ftp->max_response) {
72                         ftp->max_response = ftp->max_response? ftp->max_response<<1 : 256;
73                         ftp->response = realloc(ftp->response, ftp->max_response);
74                 }
75                 ftp->response[n++] = c;
76                 if (c == '\n') {
77                         if (n >= 4 && isdigit(ftp->response[0]) && isdigit(ftp->response[1]) && isdigit(ftp->response[2])
78                                 && ftp->response[3] != '-') break;
79                         n = 0;
80                         continue;
81                 }
82         }
83         if (n < 2) return -1;
84         ftp->response[n-2] = 0;
85         return strtol(ftp->response, &p, 0);
86 }
87
88 static int kftp_send_cmd(knetFile *ftp, const char *cmd, int is_get)
89 {
90         if (socket_wait(ftp->ctrl_fd, 0) <= 0) return -1; // socket is not ready for writing
91         write(ftp->ctrl_fd, cmd, strlen(cmd));
92         return is_get? kftp_get_response(ftp) : 0;
93 }
94
95 static int kftp_pasv_prep(knetFile *ftp)
96 {
97         char *p;
98         int v[6];
99         kftp_send_cmd(ftp, "PASV\r\n", 1);
100         for (p = ftp->response; *p && *p != '('; ++p);
101         if (*p != '(') return -1;
102         ++p;
103         sscanf(p, "%d,%d,%d,%d,%d,%d", &v[0], &v[1], &v[2], &v[3], &v[4], &v[5]);
104         memcpy(ftp->pasv_ip, v, 4 * sizeof(int));
105         ftp->pasv_port = (v[4]<<8&0xff00) + v[5];
106         return 0;
107 }
108
109
110 static int kftp_pasv_connect(knetFile *ftp)
111 {
112         char host[80], port[10];
113         if (ftp->pasv_port == 0) {
114                 fprintf(stderr, "[kftp_pasv_connect] kftp_pasv_prep() is not called before hand.\n");
115                 return -1;
116         }
117         sprintf(host, "%d.%d.%d.%d", ftp->pasv_ip[0], ftp->pasv_ip[1], ftp->pasv_ip[2], ftp->pasv_ip[3]);
118         sprintf(port, "%d", ftp->pasv_port);
119         ftp->fd = socket_connect(host, port);
120         if (ftp->fd == -1) return -1;
121         return 0;
122 }
123
124 int kftp_connect(knetFile *ftp)
125 {
126         ftp->ctrl_fd = socket_connect(ftp->host, "ftp");
127         if (ftp->ctrl_fd == -1) return -1;
128         kftp_get_response(ftp);
129         kftp_send_cmd(ftp, "USER anonymous\r\n", 1);
130         kftp_send_cmd(ftp, "PASS kftp@\r\n", 1);
131         kftp_send_cmd(ftp, "TYPE I\r\n", 1);
132         return 0;
133 }
134
135 int kftp_reconnect(knetFile *ftp)
136 {
137         if (ftp->ctrl_fd >= 0) {
138                 close(ftp->ctrl_fd);
139                 ftp->ctrl_fd = -1;
140         }
141         close(ftp->fd);
142         return kftp_connect(ftp);
143 }
144
145 // initialize ->type, ->host and ->retr
146 knetFile *kftp_parse_url(const char *fn, const char *mode)
147 {
148         knetFile *fp;
149         char *p;
150         int l;
151         if (strstr(fn, "ftp://") != fn) return 0;
152         for (p = (char*)fn + 6; *p && *p != '/'; ++p);
153         if (*p != '/') return 0;
154         l = p - fn - 6;
155         fp = calloc(1, sizeof(knetFile));
156         fp->type = KNF_TYPE_FTP;
157         fp->fd = -1;
158         fp->host = calloc(l + 1, 1);
159         if (strchr(mode, 'c')) fp->no_reconnect = 1;
160         strncpy(fp->host, fn + 6, l);
161         fp->retr = calloc(strlen(p) + 8, 1);
162         sprintf(fp->retr, "RETR %s\r\n", p);
163         fp->seek_offset = -1;
164         return fp;
165 }
166 // place ->fd at offset off
167 int kftp_connect_file(knetFile *fp)
168 {
169         int ret;
170         if (fp->fd >= 0) {
171                 close(fp->fd);
172                 if (fp->no_reconnect) kftp_get_response(fp);
173         }
174         kftp_pasv_prep(fp);
175         if (fp->offset) {
176                 char tmp[32];
177                 sprintf(tmp, "REST %lld\r\n", (long long)fp->offset);
178                 kftp_send_cmd(fp, tmp, 1);
179         }
180         kftp_send_cmd(fp, fp->retr, 0);
181         kftp_pasv_connect(fp);
182         ret = kftp_get_response(fp);
183         if (ret != 150) {
184                 fprintf(stderr, "[kftp_connect_file] %s\n", fp->response);
185                 close(fp->fd);
186                 fp->fd = -1;
187                 return -1;
188         }
189         fp->is_ready = 1;
190         return 0;
191 }
192
193 /**************************
194  * HTTP specific routines *
195  **************************/
196
197 knetFile *khttp_parse_url(const char *fn, const char *mode)
198 {
199         knetFile *fp;
200         char *p;
201         int l;
202         if (strstr(fn, "http://") != fn) return 0;
203         for (p = (char*)fn + 7; *p && *p != '/'; ++p);
204         l = p - fn - 7;
205         fp = calloc(1, sizeof(knetFile));
206         fp->type = KNF_TYPE_HTTP;
207         fp->fd = fp->ctrl_fd = -1;
208         fp->host = calloc(l + 1, 1);
209         if (strchr(mode, 'c')) fp->no_reconnect = 1;
210         strncpy(fp->host, fn + 7, l);
211         l = strlen(fn);
212         fp->path = calloc(strlen(p) + 2, 1);
213         strcpy(fp->path, *p? p : "/");
214         fp->seek_offset = -1;
215         return fp;
216 }
217
218 int khttp_connect_file(knetFile *fp)
219 {
220         int ret, l = 0;
221         char *buf, *p;
222         if (fp->fd >= 0) close(fp->fd);
223         fp->fd = socket_connect(fp->host, "http");
224         buf = calloc(0x10000, 1); // FIXME: I am lazy... But in principle, 64KB should be large enough.
225         l += sprintf(buf + l, "GET %s HTTP/1.0\r\nHost: %s\r\n", fp->path, fp->host);
226         if (fp->offset)
227                 l += sprintf(buf + l, "Range: bytes=%lld-\r\n", (long long)fp->offset);
228         l += sprintf(buf + l, "\r\n");
229         write(fp->fd, buf, l);
230         l = 0;
231         while (read(fp->fd, buf + l, 1)) { // read HTTP header; FIXME: bad efficiency
232                 if (buf[l] == '\n' && l >= 3)
233                         if (strncmp(buf + l - 3, "\r\n\r\n", 4) == 0) break;
234                 ++l;
235         }
236         buf[l] = 0;
237         if (l < 14) { // prematured header
238                 close(fp->fd);
239                 fp->fd = -1;
240                 return -1;
241         }
242         ret = strtol(buf + 8, &p, 0); // HTTP return code
243         if (ret == 200 && fp->offset) { // 200 (complete result); then skip beginning of the file
244                 off_t rest = fp->offset;
245                 while (rest) {
246                         off_t l = rest < 0x10000? rest : 0x10000;
247                         rest -= my_read(fp->fd, buf, l);
248                 }
249         } else if (ret != 206 && ret != 200) {
250                 free(buf);
251                 fprintf(stderr, "[khttp_connect_file] fail to open file (HTTP code: %d).\n", ret);
252                 close(fp->fd);
253                 fp->fd = -1;
254                 return -1;
255         }
256         free(buf);
257         fp->is_ready = 1;
258         return 0;
259 }
260
261 /********************
262  * Generic routines *
263  ********************/
264
265 knetFile *knet_open(const char *fn, const char *mode)
266 {
267         knetFile *fp = 0;
268         if (mode[0] != 'r') {
269                 fprintf(stderr, "[kftp_open] only mode \"r\" is supported.\n");
270                 return 0;
271         }
272         if (strstr(fn, "ftp://") == fn) {
273                 fp = kftp_parse_url(fn, mode);
274                 if (fp == 0) return 0;
275                 if (kftp_connect(fp) == -1) {
276                         knet_close(fp);
277                         return 0;
278                 }
279                 kftp_connect_file(fp);
280         } else if (strstr(fn, "http://") == fn) {
281                 fp = khttp_parse_url(fn, mode);
282                 if (fp == 0) return 0;
283                 khttp_connect_file(fp);
284         } else { // local file
285                 int fd = open(fn, O_RDONLY);
286                 if (fd == -1) {
287                         perror("open");
288                         return 0;
289                 }
290                 fp = (knetFile*)calloc(1, sizeof(knetFile));
291                 fp->type = KNF_TYPE_LOCAL;
292                 fp->fd = fd;
293                 fp->ctrl_fd = -1;
294         }
295         if (fp && fp->fd < 0) {
296                 knet_close(fp);
297                 return 0;
298         }
299         return fp;
300 }
301
302 knetFile *knet_dopen(int fd, const char *mode)
303 {
304         knetFile *fp = (knetFile*)calloc(1, sizeof(knetFile));
305         fp->type = KNF_TYPE_LOCAL;
306         fp->fd = fd;
307         return fp;
308 }
309
310 off_t knet_read(knetFile *fp, void *buf, off_t len)
311 {
312         off_t l = 0;
313         if (fp->fd < 0) return 0;
314         if (fp->type == KNF_TYPE_FTP) {
315                 if (fp->is_ready == 0) {
316                         if (!fp->no_reconnect) kftp_reconnect(fp);
317                         kftp_connect_file(fp);
318                 }
319         } else if (fp->type == KNF_TYPE_HTTP) {
320                 if (fp->is_ready == 0)
321                         khttp_connect_file(fp);
322         }
323         l = my_read(fp->fd, buf, len);
324         fp->offset += l;
325         return l;
326 }
327
328 int knet_seek(knetFile *fp, off_t off, int whence)
329 {
330         if (whence == SEEK_SET && off == fp->offset) return 0;
331         if (fp->type == KNF_TYPE_LOCAL) {
332                 if (lseek(fp->fd, off, whence) == -1) {
333                         perror("lseek");
334                         return -1;
335                 }
336                 fp->offset = off;
337                 return 0;
338         } else if (fp->type == KNF_TYPE_FTP || fp->type == KNF_TYPE_HTTP) {
339                 if (whence != SEEK_SET) { // FIXME: we can surely allow SEEK_CUR and SEEK_END in future
340                         fprintf(stderr, "[knet_seek] only SEEK_SET is supported for FTP/HTTP. Offset is unchanged.\n");
341                         return -1;
342                 }
343                 fp->offset = off;
344                 fp->is_ready = 0;
345                 return 0;
346         }
347         return -1;
348 }
349
350 int knet_close(knetFile *fp)
351 {
352         if (fp == 0) return 0;
353         if (fp->ctrl_fd >= 0) close(fp->ctrl_fd);
354         if (fp->fd >= 0) close(fp->fd);
355         free(fp->response); free(fp->retr); free(fp->host); free(fp->path);
356         free(fp);
357         return 0;
358 }
359
360 #ifdef KNETFILE_MAIN
361 int main(void)
362 {
363         char *buf;
364         knetFile *fp;
365         int type = 4, l;
366         buf = calloc(0x100000, 1);
367         if (type == 0) {
368                 fp = knet_open("knetfile.c", "r");
369                 knet_seek(fp, 1000, SEEK_SET);
370         } else if (type == 1) { // NCBI FTP, large file
371                 fp = knet_open("ftp://ftp.ncbi.nih.gov/1000genomes/ftp/data/NA12878/alignment/NA12878.chrom6.SLX.SRP000032.2009_06.bam", "r");
372                 knet_seek(fp, 2500000000ll, SEEK_SET);
373                 l = knet_read(fp, buf, 255);
374         } else if (type == 2) {
375                 fp = knet_open("ftp://ftp.sanger.ac.uk/pub4/treefam/tmp/index.shtml", "r");
376                 knet_seek(fp, 1000, SEEK_SET);
377         } else if (type == 3) {
378                 fp = knet_open("http://www.sanger.ac.uk/Users/lh3/index.shtml", "r");
379                 knet_seek(fp, 1000, SEEK_SET);
380         } else if (type == 4) {
381                 fp = knet_open("http://www.sanger.ac.uk/Users/lh3/ex1.bam", "r");
382                 knet_read(fp, buf, 10000);
383                 knet_seek(fp, 20000, SEEK_SET);
384                 knet_seek(fp, 10000, SEEK_SET);
385                 l = knet_read(fp, buf+10000, 10000000) + 10000;
386         }
387         if (type != 4 && type != 1) {
388                 knet_read(fp, buf, 255);
389                 buf[255] = 0;
390                 printf("%s\n", buf);
391         } else write(fileno(stdout), buf, l);
392         knet_close(fp);
393         free(buf);
394         return 0;
395 }
396 #endif