PolyHTTPFetcher.cpp 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  1. /*
  2. Copyright (C) 2015 by Joachim Meyer
  3. Permission is hereby granted, free of charge, to any person obtaining a copy
  4. of this software and associated documentation files (the "Software"), to deal
  5. in the Software without restriction, including without limitation the rights
  6. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  7. copies of the Software, and to permit persons to whom the Software is
  8. furnished to do so, subject to the following conditions:
  9. The above copyright notice and this permission notice shall be included in
  10. all copies or substantial portions of the Software.
  11. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  12. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  13. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  14. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  15. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  16. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  17. THE SOFTWARE.
  18. */
  19. #ifdef _WINDOWS
  20. #include <winsock2.h>
  21. #include <Ws2tcpip.h>
  22. #else
  23. #include <sys/socket.h>
  24. #include <sys/types.h>
  25. #include <netinet/in.h>
  26. #include <netdb.h>
  27. #include <unistd.h>
  28. #include <arpa/inet.h>
  29. #include <errno.h>
  30. #endif
  31. #include "PolyHTTPFetcher.h"
  32. #include "PolyLogger.h"
  33. #include "PolyCoreServices.h"
  34. #include "PolyCore.h"
  35. using namespace Polycode;
  36. HTTPFetcher::HTTPFetcher(String address, bool saveToPath, String savePath) : Threaded() {
  37. core = CoreServices::getInstance()->getCore();
  38. eventMutex = core->getEventMutex();
  39. storeInFile = saveToPath;
  40. this->savePath = savePath;
  41. this->address = address;
  42. int protocolIndex = address.find_first_of("://");
  43. if (protocolIndex != 0){
  44. protocolIndex += strlen("://");
  45. protocol = address.substr(0, protocolIndex - strlen("://"));
  46. int pathIndex = address.find_first_of("/", protocolIndex);
  47. path = address.substr(pathIndex+1, address.length());
  48. if (pathIndex != 0){
  49. host = address.substr(protocolIndex, pathIndex - protocolIndex);
  50. } else {
  51. host = address.substr(protocolIndex, address.length());
  52. }
  53. } else {
  54. int pathIndex = address.find_first_of("/");
  55. path = address.substr(pathIndex+1, address.length());
  56. if (pathIndex != 0){
  57. host = address.substr(0, pathIndex);
  58. } else {
  59. host = address;
  60. }
  61. }
  62. if (!createSocket())
  63. return;
  64. threadRunning = true;
  65. CoreServices::getInstance()->getCore()->createThread(this);
  66. }
  67. HTTPFetcher::~HTTPFetcher(){
  68. #ifdef _WINDOWS
  69. closesocket(s);
  70. #else
  71. close(s);
  72. #endif
  73. }
  74. bool HTTPFetcher::createSocket(){
  75. struct sockaddr_in server;
  76. addrinfo *result = NULL;
  77. addrinfo hints;
  78. //Create a socket
  79. #if PLATFORM == PLATFORM_WINDOWS
  80. if ((s = socket(AF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET) {
  81. Logger::log("HTTP Fetcher: Could not create socket: %d\n", WSAGetLastError());
  82. #elif PLATFORM == PLATFORM_MAC || PLATFORM == PLATFORM_UNIX
  83. if ((s = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
  84. Logger::log("HTTP Fetcher: Could not create socket: %s\n", strerror(errno));
  85. #endif
  86. return false;
  87. }
  88. memset(&hints, 0, sizeof(hints));
  89. hints.ai_family = AF_UNSPEC;
  90. hints.ai_socktype = SOCK_STREAM;
  91. hints.ai_protocol = IPPROTO_TCP;
  92. if (getaddrinfo(host.c_str(), protocol.c_str(), &hints, &result) != 0) {
  93. #if PLATFORM == PLATFORM_WINDOWS
  94. Logger::log("HTTP Fetcher: Address resolve error: %d\n", WSAGetLastError());
  95. #elif PLATFORM == PLATFORM_MAC || PLATFORM == PLATFORM_UNIX
  96. Logger::log("HTTP Fetcher: Address resolve error: %s\n", strerror(errno));
  97. #endif
  98. return false;
  99. }
  100. server.sin_addr = ((sockaddr_in*)result->ai_addr)->sin_addr;
  101. server.sin_family = AF_INET;
  102. server.sin_port = ((sockaddr_in*)result->ai_addr)->sin_port;
  103. //Connect to remote server
  104. if (connect(s, (struct sockaddr *)&server, sizeof(server)) < 0) {
  105. #if PLATFORM == PLATFORM_WINDOWS
  106. Logger::log("HTTP Fetcher: connect error code: %d\n", WSAGetLastError());
  107. #elif PLATFORM == PLATFORM_MAC || PLATFORM == PLATFORM_UNIX
  108. Logger::log("HTTP Fetcher: connect error code: %s\n", strerror(errno));
  109. #endif
  110. return false;
  111. }
  112. return true;
  113. }
  114. void HTTPFetcher::updateThread(){
  115. int protocolIndex = path.find_first_of("://");
  116. if (protocolIndex != 0){
  117. protocolIndex += strlen("://");
  118. protocol = path.substr(0, protocolIndex - strlen("://"));
  119. int pathIndex = path.find_first_of("/", protocolIndex);
  120. path = path.substr(pathIndex + 1, path.length());
  121. } else if (path.find_first_of("/") == 0) {
  122. path = path.substr(1, path.length());
  123. }
  124. //Send some data
  125. String request;
  126. if (path != "") {
  127. request = "GET /" + path + " " + String(HTTP_VERSION) + "\r\nHost: " + host + "\r\nUser-Agent: " + DEFAULT_USER_AGENT + "\r\nConnection: close\r\n\r\n";
  128. } else {
  129. request = "GET / " + String(HTTP_VERSION) + "\r\nHost: " + host + "\r\nUser-Agent: " + DEFAULT_USER_AGENT + "\r\nConnection: close\r\n\r\n";
  130. }
  131. HTTPFetcherEvent *event = new HTTPFetcherEvent();
  132. if (send(s, request.c_str(), strlen(request.c_str()), 0) < 0) {
  133. #if PLATFORM == PLATFORM_WINDOWS
  134. Logger::log("HTTP Fetcher: Send failed: %d\n", WSAGetLastError());
  135. event->errorCode = WSAGetLastError();
  136. #elif PLATFORM == PLATFORM_MAC || PLATFORM == PLATFORM_UNIX
  137. Logger::log("HTTP Fetcher: Send failed: %s\n",strerror(errno));
  138. event->errorCode = errno;
  139. #endif
  140. createSocket();
  141. dispatchEvent(event, HTTPFetcherEvent::EVENT_HTTP_ERROR);
  142. return;
  143. }
  144. char *server_reply = (char*)malloc(1);
  145. char *rec = server_reply;
  146. unsigned long recv_size = 0, totalRec = 0;
  147. do {
  148. //Receive a reply from the server
  149. #if PLATFORM == PLATFORM_WINDOWS
  150. if ((recv_size = recv(s, rec, 1, 0)) == SOCKET_ERROR) {
  151. Logger::log("HTTP Fetcher: recv failed: %d\n", WSAGetLastError());
  152. event->errorCode = WSAGetLastError();
  153. #elif PLATFORM == PLATFORM_MAC || PLATFORM == PLATFORM_UNIX
  154. if ((recv_size = recv(s, rec, DEFAULT_PAGE_BUF_SIZE, 0)) == -1) {
  155. Logger::log("HTTP Fetcher: recv failed: %s\n", strerror(errno));
  156. event->errorCode = errno;
  157. #endif
  158. dispatchEvent(event, HTTPFetcherEvent::EVENT_HTTP_ERROR);
  159. killThread();
  160. return;
  161. }
  162. totalRec += recv_size;
  163. server_reply = (char*)realloc(server_reply, totalRec + 1);
  164. rec = server_reply + totalRec;
  165. } while (recv_size != 0 && strstr(server_reply, "\r\n\r\n") == NULL);
  166. server_reply[totalRec] = '\0';
  167. event->data = server_reply;
  168. if (strlen(event->data) == 0){
  169. createSocket();
  170. return;
  171. }
  172. char *charIndex = strstr(event->data, "HTTP/");
  173. if(charIndex == NULL){
  174. killThread();
  175. return;
  176. }
  177. int i;
  178. if (sscanf(charIndex + strlen("HTTP/1.1"), "%d", &i) != 1 || i < 200 || i>299) {
  179. event->errorCode = i;
  180. dispatchEvent(event, HTTPFetcherEvent::EVENT_HTTP_ERROR);
  181. killThread();
  182. return;
  183. }
  184. charIndex = strstr(event->data, "Content-Length:");
  185. if (charIndex == NULL)
  186. charIndex = strstr(event->data, "Content-length:");
  187. if (sscanf(charIndex + strlen("content-length: "), "%d", &i) != 1) {
  188. dispatchEvent(event, HTTPFetcherEvent::EVENT_HTTP_ERROR);
  189. killThread();
  190. return;
  191. }
  192. FILE* tempFile;
  193. if (storeInFile){
  194. if (savePath == "")
  195. savePath = path;
  196. tempFile = fopen(savePath.c_str(), "wb");
  197. }
  198. free(server_reply);
  199. server_reply = (char*)malloc(DEFAULT_PAGE_BUF_SIZE);
  200. rec = server_reply;
  201. recv_size = 0, totalRec = 0;
  202. do {
  203. //Receive a reply from the server
  204. #if PLATFORM == PLATFORM_WINDOWS
  205. if ((recv_size = recv(s, rec, DEFAULT_PAGE_BUF_SIZE, 0)) == SOCKET_ERROR) {
  206. Logger::log("HTTP Fetcher: recv failed: %d\n", WSAGetLastError());
  207. event->errorCode = WSAGetLastError();
  208. #elif PLATFORM == PLATFORM_MAC || PLATFORM == PLATFORM_UNIX
  209. if ((recv_size = recv(s, rec, DEFAULT_PAGE_BUF_SIZE, 0)) == -1) {
  210. Logger::log("HTTP Fetcher: recv failed: %s\n", strerror(errno));
  211. event->errorCode = errno;
  212. #endif
  213. dispatchEvent(event, HTTPFetcherEvent::EVENT_HTTP_ERROR);
  214. killThread();
  215. return;
  216. }
  217. totalRec += recv_size;
  218. if (!storeInFile){
  219. server_reply = (char*)realloc(server_reply, totalRec + DEFAULT_PAGE_BUF_SIZE);
  220. rec = server_reply + totalRec;
  221. } else {
  222. server_reply[recv_size] = '\0';
  223. fwrite(server_reply, 1, recv_size, tempFile);
  224. }
  225. } while (recv_size !=0 && totalRec < i);
  226. if (totalRec > i){
  227. event->errorCode = HTTPFetcher::HTTPFETCHER_ERROR_WRONG_SIZE;
  228. dispatchEvent(event, HTTPFetcherEvent::EVENT_HTTP_ERROR);
  229. killThread();
  230. return;
  231. }
  232. if (storeInFile){
  233. event->storedInFile = true;
  234. event->data = (char*)malloc(sizeof(char)*(savePath.length() + 1));
  235. strcpy(event->data, savePath.c_str());
  236. fclose(tempFile);
  237. } else {
  238. event->data = server_reply;
  239. }
  240. event->contentSize = totalRec;
  241. bodyReturn = event->data;
  242. dispatchEvent(event, HTTPFetcherEvent::EVENT_HTTP_DATA_RECEIVED);
  243. killThread();
  244. }
  245. void HTTPFetcher::fetchFile(String pathToFile, bool saveToPath, String savePath){
  246. path = pathToFile;
  247. this->savePath = savePath;
  248. this->storeInFile = saveToPath;
  249. threadRunning = true;
  250. CoreServices::getInstance()->getCore()->createThread(this);
  251. }
  252. String HTTPFetcher::getData(){
  253. return this->bodyReturn;
  254. }