1
0

FileCache.cpp 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. #include "FileCache.h"
  2. #include "hscope.h"
  3. #include "httpdef.h" // for http_content_type_str_by_suffix
  4. #include "http_page.h" //make_index_of_page
  5. file_cache_t* FileCache::Open(const char* filepath, void* ctx) {
  6. std::lock_guard<std::mutex> locker(mutex_);
  7. file_cache_t* fc = Get(filepath);
  8. bool modified = false;
  9. if (fc) {
  10. time_t tt;
  11. time(&tt);
  12. if (tt - fc->stat_time > file_stat_interval) {
  13. time_t mtime = fc->st.st_mtime;
  14. stat(filepath, &fc->st);
  15. fc->stat_time = tt;
  16. fc->stat_cnt++;
  17. if (mtime != fc->st.st_mtime) {
  18. modified = true;
  19. fc->stat_cnt = 1;
  20. }
  21. }
  22. }
  23. if (fc == NULL || modified) {
  24. int fd = open(filepath, O_RDONLY);
  25. if (fd < 0) {
  26. return NULL;
  27. }
  28. defer(close(fd);)
  29. if (fc == NULL) {
  30. struct stat st;
  31. fstat(fd, &st);
  32. if (S_ISREG(st.st_mode) ||
  33. (S_ISDIR(st.st_mode) &&
  34. filepath[strlen(filepath)-1] == '/')) {
  35. fc = new file_cache_t;
  36. //fc->filepath = filepath;
  37. fc->st = st;
  38. time(&fc->open_time);
  39. fc->stat_time = fc->open_time;
  40. fc->stat_cnt = 1;
  41. cached_files[filepath] = fc;
  42. }
  43. else {
  44. return NULL;
  45. }
  46. }
  47. if (S_ISREG(fc->st.st_mode)) {
  48. // FILE
  49. fc->resize_buf(fc->st.st_size);
  50. read(fd, fc->filebuf.base, fc->filebuf.len);
  51. const char* suffix = strrchr(filepath, '.');
  52. if (suffix) {
  53. fc->content_type = http_content_type_str_by_suffix(++suffix);
  54. }
  55. }
  56. else if (S_ISDIR(fc->st.st_mode)) {
  57. // DIR
  58. std::string page;
  59. make_index_of_page(filepath, page, (const char*)ctx);
  60. fc->resize_buf(page.size());
  61. memcpy(fc->filebuf.base, page.c_str(), page.size());
  62. fc->content_type = http_content_type_str(TEXT_HTML);
  63. }
  64. time_t tt = fc->st.st_mtime;
  65. strftime(fc->last_modified, sizeof(fc->last_modified), "%a, %d %b %Y %H:%M:%S GMT", gmtime(&tt));
  66. snprintf(fc->etag, sizeof(fc->etag), "\"%zx-%zx\"", fc->st.st_mtime, fc->st.st_size);
  67. }
  68. return fc;
  69. }
  70. int FileCache::Close(const char* filepath) {
  71. std::lock_guard<std::mutex> locker(mutex_);
  72. auto iter = cached_files.find(filepath);
  73. if (iter != cached_files.end()) {
  74. delete iter->second;
  75. iter = cached_files.erase(iter);
  76. return 0;
  77. }
  78. return -1;
  79. }
  80. file_cache_t* FileCache::Get(const char* filepath) {
  81. auto iter = cached_files.find(filepath);
  82. if (iter != cached_files.end()) {
  83. return iter->second;
  84. }
  85. return NULL;
  86. }