fopen.c 13 KB

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