dir_list.cppsm 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. <%#
  2. //cppsp module to enable directory listing
  3. #include <sys/stat.h>
  4. #define TO_C_STR(in,inLen,out) char out[inLen+1];\
  5. memcpy(out,in,inLen);\
  6. out[inLen]=0;
  7. DelegateChain<void(Request&, Response&, Delegate<void()>)>::item* it;
  8. Server* server;
  9. void handleRequest(void*, Request& req, Response& resp, Delegate<void()> cb) {
  10. struct stat st;
  11. String s=server->mapPath(req.path,*req.sp);
  12. TO_C_STR(s.data(),s.length(),tmp);
  13. if(::stat(tmp,&st)>=0 && S_ISDIR(st.st_mode)) {
  14. server->handleDynamicRequest("/dir_list.cppsm",req,resp,cb);
  15. return;
  16. }
  17. (*it->prev)(req,resp,cb);
  18. }
  19. extern "C" void initModule(Server* s) {
  20. server=s;
  21. it=s->handleRequest.attach(&handleRequest);
  22. }
  23. extern "C" void deinitModule() {
  24. server->handleRequest.detach(it);
  25. }
  26. %>
  27. <!DOCTYPE HTML>
  28. <html>
  29. <head>
  30. <title>Index of <% htmlEscape(request->path,output); %></title>
  31. </head>
  32. <body>
  33. <h1 style="margin-top: 2px;">Index of <% htmlEscape(request->path,output); %></h1>
  34. <table>
  35. <tr>
  36. <th>Name</th>
  37. <th>Last modified</th>
  38. <th>Size</th>
  39. </tr>
  40. <tr>
  41. <th colspan="5"><hr /></th>
  42. </tr>
  43. <%
  44. string path=server->mapPath(request->path.toSTDString());
  45. vector<string> list;
  46. auto tmp=[&](const char* name) {
  47. list.push_back(name);
  48. };
  49. listDirectory(path.c_str(), &tmp);
  50. std::sort(list.begin(),list.end());
  51. for(int i=0;i<list.size();i++) {
  52. string name=list[i];
  53. struct stat st;
  54. char p[path.length()+name.length()+1];
  55. p[combinePath(path.c_str(),name.c_str(),p)]=0;
  56. if(stat(p,&st)<0) return;
  57. time_t rawtime=st.st_mtime;
  58. struct tm * timeinfo;
  59. char buffer[256];
  60. timeinfo = localtime (&rawtime);
  61. strftime(buffer,sizeof(buffer),"%F %r",timeinfo);
  62. %>
  63. <tr>
  64. <td>
  65. <a href="<% htmlAttributeEscape(name.c_str(),output); %><%if(S_ISDIR(st.st_mode)){%>/<%}%>">
  66. <% htmlEscape(name.c_str(),output); %><%if(S_ISDIR(st.st_mode)){%>/<%}%>
  67. </a>
  68. </td>
  69. <td align="right"><%=buffer%></td>
  70. <td align="right"><%=(int64_t)st.st_size%></td>
  71. </tr>
  72. <tr>
  73. <td></td>
  74. </tr>
  75. <%
  76. }
  77. %>
  78. </table>
  79. </body>
  80. </html>