2
0

fopen.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547
  1. /*****************************************************************************
  2. *
  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_ .
  7. *
  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
  12. *
  13. * See the main() function at the bottom that shows an app that retrieves from
  14. * a specified url using fgets() and fread() and saves as two output files.
  15. *
  16. * Copyright (c) 2003 Simtec Electronics
  17. *
  18. * Re-implemented by Vincent Sanders <vince@kyllikki.org> with extensive
  19. * reference to original curl example code
  20. *
  21. * Redistribution and use in source and binary forms, with or without
  22. * modification, are permitted provided that the following conditions
  23. * are met:
  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.
  31. *
  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.
  42. *
  43. * This example requires libcurl 7.9.7 or later.
  44. */
  45. /* <DESC>
  46. * implements an fopen() abstraction allowing reading from URLs
  47. * </DESC>
  48. */
  49. #include <stdio.h>
  50. #include <string.h>
  51. #ifndef WIN32
  52. # include <sys/time.h>
  53. #endif
  54. #include <stdlib.h>
  55. #include <errno.h>
  56. #include <curl/curl.h>
  57. enum fcurl_type_e {
  58. CFTYPE_NONE=0,
  59. CFTYPE_FILE=1,
  60. CFTYPE_CURL=2
  61. };
  62. struct fcurl_data
  63. {
  64. enum fcurl_type_e type; /* type of handle */
  65. union {
  66. CURL *curl;
  67. FILE *file;
  68. } handle; /* handle */
  69. char *buffer; /* buffer to store cached data*/
  70. size_t buffer_len; /* currently allocated buffers length */
  71. size_t buffer_pos; /* end of data in buffer*/
  72. int still_running; /* Is background url fetch still in progress */
  73. };
  74. typedef struct fcurl_data URL_FILE;
  75. /* exported functions */
  76. URL_FILE *url_fopen(const char *url, const char *operation);
  77. int url_fclose(URL_FILE *file);
  78. int url_feof(URL_FILE *file);
  79. size_t url_fread(void *ptr, size_t size, size_t nmemb, URL_FILE *file);
  80. char *url_fgets(char *ptr, size_t size, URL_FILE *file);
  81. void url_rewind(URL_FILE *file);
  82. /* we use a global one for convenience */
  83. static CURLM *multi_handle;
  84. /* curl calls this routine to get more data */
  85. static size_t write_callback(char *buffer,
  86. size_t size,
  87. size_t nitems,
  88. void *userp)
  89. {
  90. char *newbuff;
  91. size_t rembuff;
  92. URL_FILE *url = (URL_FILE *)userp;
  93. size *= nitems;
  94. rembuff=url->buffer_len - url->buffer_pos; /* remaining space in buffer */
  95. if(size > rembuff) {
  96. /* not enough space in buffer */
  97. newbuff=realloc(url->buffer, url->buffer_len + (size - rembuff));
  98. if(newbuff==NULL) {
  99. fprintf(stderr, "callback buffer grow failed\n");
  100. size=rembuff;
  101. }
  102. else {
  103. /* realloc succeeded increase buffer size*/
  104. url->buffer_len+=size - rembuff;
  105. url->buffer=newbuff;
  106. }
  107. }
  108. memcpy(&url->buffer[url->buffer_pos], buffer, size);
  109. url->buffer_pos += size;
  110. return size;
  111. }
  112. /* use to attempt to fill the read buffer up to requested number of bytes */
  113. static int fill_buffer(URL_FILE *file, size_t want)
  114. {
  115. fd_set fdread;
  116. fd_set fdwrite;
  117. fd_set fdexcep;
  118. struct timeval timeout;
  119. int rc;
  120. CURLMcode mc; /* curl_multi_fdset() return code */
  121. /* only attempt to fill buffer if transactions still running and buffer
  122. * doesn't exceed required size already
  123. */
  124. if((!file->still_running) || (file->buffer_pos > want))
  125. return 0;
  126. /* attempt to fill buffer */
  127. do {
  128. int maxfd = -1;
  129. long curl_timeo = -1;
  130. FD_ZERO(&fdread);
  131. FD_ZERO(&fdwrite);
  132. FD_ZERO(&fdexcep);
  133. /* set a suitable timeout to fail on */
  134. timeout.tv_sec = 60; /* 1 minute */
  135. timeout.tv_usec = 0;
  136. curl_multi_timeout(multi_handle, &curl_timeo);
  137. if(curl_timeo >= 0) {
  138. timeout.tv_sec = curl_timeo / 1000;
  139. if(timeout.tv_sec > 1)
  140. timeout.tv_sec = 1;
  141. else
  142. timeout.tv_usec = (curl_timeo % 1000) * 1000;
  143. }
  144. /* get file descriptors from the transfers */
  145. mc = curl_multi_fdset(multi_handle, &fdread, &fdwrite, &fdexcep, &maxfd);
  146. if(mc != CURLM_OK) {
  147. fprintf(stderr, "curl_multi_fdset() failed, code %d.\n", mc);
  148. break;
  149. }
  150. /* On success the value of maxfd is guaranteed to be >= -1. We call
  151. select(maxfd + 1, ...); specially in case of (maxfd == -1) there are
  152. no fds ready yet so we call select(0, ...) --or Sleep() on Windows--
  153. to sleep 100ms, which is the minimum suggested value in the
  154. curl_multi_fdset() doc. */
  155. if(maxfd == -1) {
  156. #ifdef _WIN32
  157. Sleep(100);
  158. rc = 0;
  159. #else
  160. /* Portable sleep for platforms other than Windows. */
  161. struct timeval wait = { 0, 100 * 1000 }; /* 100ms */
  162. rc = select(0, NULL, NULL, NULL, &wait);
  163. #endif
  164. }
  165. else {
  166. /* Note that on some platforms 'timeout' may be modified by select().
  167. If you need access to the original value save a copy beforehand. */
  168. rc = select(maxfd+1, &fdread, &fdwrite, &fdexcep, &timeout);
  169. }
  170. switch(rc) {
  171. case -1:
  172. /* select error */
  173. break;
  174. case 0:
  175. default:
  176. /* timeout or readable/writable sockets */
  177. curl_multi_perform(multi_handle, &file->still_running);
  178. break;
  179. }
  180. } while(file->still_running && (file->buffer_pos < want));
  181. return 1;
  182. }
  183. /* use to remove want bytes from the front of a files buffer */
  184. static int use_buffer(URL_FILE *file, size_t want)
  185. {
  186. /* sort out buffer */
  187. if((file->buffer_pos - want) <=0) {
  188. /* ditch buffer - write will recreate */
  189. free(file->buffer);
  190. file->buffer=NULL;
  191. file->buffer_pos=0;
  192. file->buffer_len=0;
  193. }
  194. else {
  195. /* move rest down make it available for later */
  196. memmove(file->buffer,
  197. &file->buffer[want],
  198. (file->buffer_pos - want));
  199. file->buffer_pos -= want;
  200. }
  201. return 0;
  202. }
  203. URL_FILE *url_fopen(const char *url, const char *operation)
  204. {
  205. /* this code could check for URLs or types in the 'url' and
  206. basically use the real fopen() for standard files */
  207. URL_FILE *file;
  208. (void)operation;
  209. file = malloc(sizeof(URL_FILE));
  210. if(!file)
  211. return NULL;
  212. memset(file, 0, sizeof(URL_FILE));
  213. if((file->handle.file=fopen(url, operation)))
  214. file->type = CFTYPE_FILE; /* marked as URL */
  215. else {
  216. file->type = CFTYPE_CURL; /* marked as URL */
  217. file->handle.curl = curl_easy_init();
  218. curl_easy_setopt(file->handle.curl, CURLOPT_URL, url);
  219. curl_easy_setopt(file->handle.curl, CURLOPT_WRITEDATA, file);
  220. curl_easy_setopt(file->handle.curl, CURLOPT_VERBOSE, 0L);
  221. curl_easy_setopt(file->handle.curl, CURLOPT_WRITEFUNCTION, write_callback);
  222. if(!multi_handle)
  223. multi_handle = curl_multi_init();
  224. curl_multi_add_handle(multi_handle, file->handle.curl);
  225. /* lets start the fetch */
  226. curl_multi_perform(multi_handle, &file->still_running);
  227. if((file->buffer_pos == 0) && (!file->still_running)) {
  228. /* if still_running is 0 now, we should return NULL */
  229. /* make sure the easy handle is not in the multi handle anymore */
  230. curl_multi_remove_handle(multi_handle, file->handle.curl);
  231. /* cleanup */
  232. curl_easy_cleanup(file->handle.curl);
  233. free(file);
  234. file = NULL;
  235. }
  236. }
  237. return file;
  238. }
  239. int url_fclose(URL_FILE *file)
  240. {
  241. int ret=0;/* default is good return */
  242. switch(file->type) {
  243. case CFTYPE_FILE:
  244. ret=fclose(file->handle.file); /* passthrough */
  245. break;
  246. case CFTYPE_CURL:
  247. /* make sure the easy handle is not in the multi handle anymore */
  248. curl_multi_remove_handle(multi_handle, file->handle.curl);
  249. /* cleanup */
  250. curl_easy_cleanup(file->handle.curl);
  251. break;
  252. default: /* unknown or supported type - oh dear */
  253. ret=EOF;
  254. errno=EBADF;
  255. break;
  256. }
  257. free(file->buffer);/* free any allocated buffer space */
  258. free(file);
  259. return ret;
  260. }
  261. int url_feof(URL_FILE *file)
  262. {
  263. int ret=0;
  264. switch(file->type) {
  265. case CFTYPE_FILE:
  266. ret=feof(file->handle.file);
  267. break;
  268. case CFTYPE_CURL:
  269. if((file->buffer_pos == 0) && (!file->still_running))
  270. ret = 1;
  271. break;
  272. default: /* unknown or supported type - oh dear */
  273. ret=-1;
  274. errno=EBADF;
  275. break;
  276. }
  277. return ret;
  278. }
  279. size_t url_fread(void *ptr, size_t size, size_t nmemb, URL_FILE *file)
  280. {
  281. size_t want;
  282. switch(file->type) {
  283. case CFTYPE_FILE:
  284. want=fread(ptr, size, nmemb, file->handle.file);
  285. break;
  286. case CFTYPE_CURL:
  287. want = nmemb * size;
  288. fill_buffer(file, want);
  289. /* check if there's data in the buffer - if not fill_buffer()
  290. * either errored or EOF */
  291. if(!file->buffer_pos)
  292. return 0;
  293. /* ensure only available data is considered */
  294. if(file->buffer_pos < want)
  295. want = file->buffer_pos;
  296. /* xfer data to caller */
  297. memcpy(ptr, file->buffer, want);
  298. use_buffer(file, want);
  299. want = want / size; /* number of items */
  300. break;
  301. default: /* unknown or supported type - oh dear */
  302. want=0;
  303. errno=EBADF;
  304. break;
  305. }
  306. return want;
  307. }
  308. char *url_fgets(char *ptr, size_t size, URL_FILE *file)
  309. {
  310. size_t want = size - 1;/* always need to leave room for zero termination */
  311. size_t loop;
  312. switch(file->type) {
  313. case CFTYPE_FILE:
  314. ptr = fgets(ptr, (int)size, file->handle.file);
  315. break;
  316. case CFTYPE_CURL:
  317. fill_buffer(file, want);
  318. /* check if there's data in the buffer - if not fill either errored or
  319. * EOF */
  320. if(!file->buffer_pos)
  321. return NULL;
  322. /* ensure only available data is considered */
  323. if(file->buffer_pos < want)
  324. want = file->buffer_pos;
  325. /*buffer contains data */
  326. /* look for newline or eof */
  327. for(loop=0;loop < want;loop++) {
  328. if(file->buffer[loop] == '\n') {
  329. want=loop+1;/* include newline */
  330. break;
  331. }
  332. }
  333. /* xfer data to caller */
  334. memcpy(ptr, file->buffer, want);
  335. ptr[want]=0;/* always null terminate */
  336. use_buffer(file, want);
  337. break;
  338. default: /* unknown or supported type - oh dear */
  339. ptr=NULL;
  340. errno=EBADF;
  341. break;
  342. }
  343. return ptr;/*success */
  344. }
  345. void url_rewind(URL_FILE *file)
  346. {
  347. switch(file->type) {
  348. case CFTYPE_FILE:
  349. rewind(file->handle.file); /* passthrough */
  350. break;
  351. case CFTYPE_CURL:
  352. /* halt transaction */
  353. curl_multi_remove_handle(multi_handle, file->handle.curl);
  354. /* restart */
  355. curl_multi_add_handle(multi_handle, file->handle.curl);
  356. /* ditch buffer - write will recreate - resets stream pos*/
  357. free(file->buffer);
  358. file->buffer=NULL;
  359. file->buffer_pos=0;
  360. file->buffer_len=0;
  361. break;
  362. default: /* unknown or supported type - oh dear */
  363. break;
  364. }
  365. }
  366. #define FGETSFILE "fgets.test"
  367. #define FREADFILE "fread.test"
  368. #define REWINDFILE "rewind.test"
  369. /* Small main program to retrieve from a url using fgets and fread saving the
  370. * output to two test files (note the fgets method will corrupt binary files if
  371. * they contain 0 chars */
  372. int main(int argc, char *argv[])
  373. {
  374. URL_FILE *handle;
  375. FILE *outf;
  376. size_t nread;
  377. char buffer[256];
  378. const char *url;
  379. if(argc < 2)
  380. url="http://192.168.7.3/testfile";/* default to testurl */
  381. else
  382. url=argv[1];/* use passed url */
  383. /* copy from url line by line with fgets */
  384. outf=fopen(FGETSFILE, "wb+");
  385. if(!outf) {
  386. perror("couldn't open fgets output file\n");
  387. return 1;
  388. }
  389. handle = url_fopen(url, "r");
  390. if(!handle) {
  391. printf("couldn't url_fopen() %s\n", url);
  392. fclose(outf);
  393. return 2;
  394. }
  395. while(!url_feof(handle)) {
  396. url_fgets(buffer, sizeof(buffer), handle);
  397. fwrite(buffer, 1, strlen(buffer), outf);
  398. }
  399. url_fclose(handle);
  400. fclose(outf);
  401. /* Copy from url with fread */
  402. outf=fopen(FREADFILE, "wb+");
  403. if(!outf) {
  404. perror("couldn't open fread output file\n");
  405. return 1;
  406. }
  407. handle = url_fopen("testfile", "r");
  408. if(!handle) {
  409. printf("couldn't url_fopen() testfile\n");
  410. fclose(outf);
  411. return 2;
  412. }
  413. do {
  414. nread = url_fread(buffer, 1, sizeof(buffer), handle);
  415. fwrite(buffer, 1, nread, outf);
  416. } while(nread);
  417. url_fclose(handle);
  418. fclose(outf);
  419. /* Test rewind */
  420. outf=fopen(REWINDFILE, "wb+");
  421. if(!outf) {
  422. perror("couldn't open fread output file\n");
  423. return 1;
  424. }
  425. handle = url_fopen("testfile", "r");
  426. if(!handle) {
  427. printf("couldn't url_fopen() testfile\n");
  428. fclose(outf);
  429. return 2;
  430. }
  431. nread = url_fread(buffer, 1, sizeof(buffer), handle);
  432. fwrite(buffer, 1, nread, outf);
  433. url_rewind(handle);
  434. buffer[0]='\n';
  435. fwrite(buffer, 1, 1, outf);
  436. nread = url_fread(buffer, 1, sizeof(buffer), handle);
  437. fwrite(buffer, 1, nread, outf);
  438. url_fclose(handle);
  439. fclose(outf);
  440. return 0;/* all done */
  441. }