1 /*****************************************************************************
3 * This example source code introduces a c library buffered I/O interface to
4 * URL reads it supports fopen(), fread(), fgets(), feof(), fclose(),
5 * rewind(). Supported functions have identical prototypes to their normal c
6 * lib namesakes and are preceaded by url_ .
8 * Using this code you can replace your program's fopen() with url_fopen()
9 * and fread() with url_fread() and it become possible to read remote streams
10 * instead of (only) local files. Local files (ie those that can be directly
11 * fopened) will drop back to using the underlying clib implementations
13 * See the main() function at the bottom that shows an app that retrives from a
14 * specified url using fgets() and fread() and saves as two output files.
16 * Copyright (c) 2003 Simtec Electronics
18 * Re-implemented by Vincent Sanders <vince@kyllikki.org> with extensive
19 * reference to original curl example code
21 * Redistribution and use in source and binary forms, with or without
22 * modification, are permitted provided that the following conditions
24 * 1. Redistributions of source code must retain the above copyright
25 * notice, this list of conditions and the following disclaimer.
26 * 2. Redistributions in binary form must reproduce the above copyright
27 * notice, this list of conditions and the following disclaimer in the
28 * documentation and/or other materials provided with the distribution.
29 * 3. The name of the author may not be used to endorse or promote products
30 * derived from this software without specific prior written permission.
32 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
33 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
34 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
35 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
36 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
37 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
38 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
39 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
40 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
41 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
43 * This example requires libcurl 7.9.7 or later.
49 # include <sys/time.h>
54 #include <curl/curl.h>
64 enum fcurl_type_e type; /* type of handle */
68 } handle; /* handle */
70 char *buffer; /* buffer to store cached data*/
71 size_t buffer_len; /* currently allocated buffers length */
72 size_t buffer_pos; /* end of data in buffer*/
73 int still_running; /* Is background url fetch still in progress */
76 typedef struct fcurl_data URL_FILE;
78 /* exported functions */
79 URL_FILE *url_fopen(const char *url,const char *operation);
80 int url_fclose(URL_FILE *file);
81 int url_feof(URL_FILE *file);
82 size_t url_fread(void *ptr, size_t size, size_t nmemb, URL_FILE *file);
83 char * url_fgets(char *ptr, size_t size, URL_FILE *file);
84 void url_rewind(URL_FILE *file);
86 /* we use a global one for convenience */
89 /* curl calls this routine to get more data */
90 static size_t write_callback(char *buffer,
98 URL_FILE *url = (URL_FILE *)userp;
101 rembuff=url->buffer_len - url->buffer_pos; /* remaining space in buffer */
104 /* not enough space in buffer */
105 newbuff=realloc(url->buffer,url->buffer_len + (size - rembuff));
107 fprintf(stderr,"callback buffer grow failed\n");
111 /* realloc suceeded increase buffer size*/
112 url->buffer_len+=size - rembuff;
117 memcpy(&url->buffer[url->buffer_pos], buffer, size);
118 url->buffer_pos += size;
123 /* use to attempt to fill the read buffer up to requested number of bytes */
124 static int fill_buffer(URL_FILE *file, size_t want)
129 struct timeval timeout;
131 CURLMcode mc; /* curl_multi_fdset() return code */
133 /* only attempt to fill buffer if transactions still running and buffer
134 * doesnt exceed required size already
136 if((!file->still_running) || (file->buffer_pos > want))
139 /* attempt to fill buffer */
142 long curl_timeo = -1;
148 /* set a suitable timeout to fail on */
149 timeout.tv_sec = 60; /* 1 minute */
152 curl_multi_timeout(multi_handle, &curl_timeo);
153 if(curl_timeo >= 0) {
154 timeout.tv_sec = curl_timeo / 1000;
155 if(timeout.tv_sec > 1)
158 timeout.tv_usec = (curl_timeo % 1000) * 1000;
161 /* get file descriptors from the transfers */
162 mc = curl_multi_fdset(multi_handle, &fdread, &fdwrite, &fdexcep, &maxfd);
166 fprintf(stderr, "curl_multi_fdset() failed, code %d.\n", mc);
170 /* On success the value of maxfd is guaranteed to be >= -1. We call
171 select(maxfd + 1, ...); specially in case of (maxfd == -1) there are
172 no fds ready yet so we call select(0, ...) --or Sleep() on Windows--
173 to sleep 100ms, which is the minimum suggested value in the
174 curl_multi_fdset() doc. */
181 /* Portable sleep for platforms other than Windows. */
182 struct timeval wait = { 0, 100 * 1000 }; /* 100ms */
183 rc = select(0, NULL, NULL, NULL, &wait);
187 /* Note that on some platforms 'timeout' may be modified by select().
188 If you need access to the original value save a copy beforehand. */
189 rc = select(maxfd+1, &fdread, &fdwrite, &fdexcep, &timeout);
199 /* timeout or readable/writable sockets */
200 curl_multi_perform(multi_handle, &file->still_running);
203 } while(file->still_running && (file->buffer_pos < want));
207 /* use to remove want bytes from the front of a files buffer */
208 static int use_buffer(URL_FILE *file,int want)
210 /* sort out buffer */
211 if((file->buffer_pos - want) <=0) {
212 /* ditch buffer - write will recreate */
221 /* move rest down make it available for later */
222 memmove(file->buffer,
224 (file->buffer_pos - want));
226 file->buffer_pos -= want;
231 URL_FILE *url_fopen(const char *url,const char *operation)
233 /* this code could check for URLs or types in the 'url' and
234 basicly use the real fopen() for standard files */
239 file = malloc(sizeof(URL_FILE));
243 memset(file, 0, sizeof(URL_FILE));
245 if((file->handle.file=fopen(url,operation)))
246 file->type = CFTYPE_FILE; /* marked as URL */
249 file->type = CFTYPE_CURL; /* marked as URL */
250 file->handle.curl = curl_easy_init();
252 curl_easy_setopt(file->handle.curl, CURLOPT_URL, url);
253 curl_easy_setopt(file->handle.curl, CURLOPT_WRITEDATA, file);
254 curl_easy_setopt(file->handle.curl, CURLOPT_VERBOSE, 0L);
255 curl_easy_setopt(file->handle.curl, CURLOPT_WRITEFUNCTION, write_callback);
258 multi_handle = curl_multi_init();
260 curl_multi_add_handle(multi_handle, file->handle.curl);
262 /* lets start the fetch */
263 curl_multi_perform(multi_handle, &file->still_running);
265 if((file->buffer_pos == 0) && (!file->still_running)) {
266 /* if still_running is 0 now, we should return NULL */
268 /* make sure the easy handle is not in the multi handle anymore */
269 curl_multi_remove_handle(multi_handle, file->handle.curl);
272 curl_easy_cleanup(file->handle.curl);
282 int url_fclose(URL_FILE *file)
284 int ret=0;/* default is good return */
288 ret=fclose(file->handle.file); /* passthrough */
292 /* make sure the easy handle is not in the multi handle anymore */
293 curl_multi_remove_handle(multi_handle, file->handle.curl);
296 curl_easy_cleanup(file->handle.curl);
299 default: /* unknown or supported type - oh dear */
306 free(file->buffer);/* free any allocated buffer space */
313 int url_feof(URL_FILE *file)
319 ret=feof(file->handle.file);
323 if((file->buffer_pos == 0) && (!file->still_running))
327 default: /* unknown or supported type - oh dear */
335 size_t url_fread(void *ptr, size_t size, size_t nmemb, URL_FILE *file)
341 want=fread(ptr,size,nmemb,file->handle.file);
347 fill_buffer(file,want);
349 /* check if theres data in the buffer - if not fill_buffer()
350 * either errored or EOF */
351 if(!file->buffer_pos)
354 /* ensure only available data is considered */
355 if(file->buffer_pos < want)
356 want = file->buffer_pos;
358 /* xfer data to caller */
359 memcpy(ptr, file->buffer, want);
361 use_buffer(file,want);
363 want = want / size; /* number of items */
366 default: /* unknown or supported type - oh dear */
375 char *url_fgets(char *ptr, size_t size, URL_FILE *file)
377 size_t want = size - 1;/* always need to leave room for zero termination */
382 ptr = fgets(ptr,size,file->handle.file);
386 fill_buffer(file,want);
388 /* check if theres data in the buffer - if not fill either errored or
390 if(!file->buffer_pos)
393 /* ensure only available data is considered */
394 if(file->buffer_pos < want)
395 want = file->buffer_pos;
397 /*buffer contains data */
398 /* look for newline or eof */
399 for(loop=0;loop < want;loop++) {
400 if(file->buffer[loop] == '\n') {
401 want=loop+1;/* include newline */
406 /* xfer data to caller */
407 memcpy(ptr, file->buffer, want);
408 ptr[want]=0;/* allways null terminate */
410 use_buffer(file,want);
414 default: /* unknown or supported type - oh dear */
420 return ptr;/*success */
423 void url_rewind(URL_FILE *file)
427 rewind(file->handle.file); /* passthrough */
431 /* halt transaction */
432 curl_multi_remove_handle(multi_handle, file->handle.curl);
435 curl_multi_add_handle(multi_handle, file->handle.curl);
437 /* ditch buffer - write will recreate - resets stream pos*/
447 default: /* unknown or supported type - oh dear */
452 /* Small main program to retrive from a url using fgets and fread saving the
453 * output to two test files (note the fgets method will corrupt binary files if
454 * they contain 0 chars */
455 int main(int argc, char *argv[])
465 url="http://192.168.7.3/testfile";/* default to testurl */
467 url=argv[1];/* use passed url */
469 /* copy from url line by line with fgets */
470 outf=fopen("fgets.test","w+");
472 perror("couldn't open fgets output file\n");
476 handle = url_fopen(url, "r");
478 printf("couldn't url_fopen() %s\n", url);
483 while(!url_feof(handle)) {
484 url_fgets(buffer,sizeof(buffer),handle);
485 fwrite(buffer,1,strlen(buffer),outf);
493 /* Copy from url with fread */
494 outf=fopen("fread.test","w+");
496 perror("couldn't open fread output file\n");
500 handle = url_fopen("testfile", "r");
502 printf("couldn't url_fopen() testfile\n");
508 nread = url_fread(buffer, 1,sizeof(buffer), handle);
509 fwrite(buffer,1,nread,outf);
518 outf=fopen("rewind.test","w+");
520 perror("couldn't open fread output file\n");
524 handle = url_fopen("testfile", "r");
526 printf("couldn't url_fopen() testfile\n");
531 nread = url_fread(buffer, 1,sizeof(buffer), handle);
532 fwrite(buffer,1,nread,outf);
536 fwrite(buffer,1,1,outf);
538 nread = url_fread(buffer, 1,sizeof(buffer), handle);
539 fwrite(buffer,1,nread,outf);
547 return 0;/* all done */