1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <string.h>
4
5 #include <curl/curl.h>
6 #include <curl/easy.h>
7
8 #include <string>
9
10 #include "conffile.h"
11 #include "net.h"
12
13 const char* HSS_SERVER = "http://mbays.freeshell.org/kuklomenos/highScore.cgi";
14
15 // Following adapted from getinmemory.c from the libcurl distribution.
16
17 struct MemoryStruct {
18 char *memory;
19 size_t size;
20 };
21
22 static void *myrealloc(void *ptr, size_t size);
23
myrealloc(void * ptr,size_t size)24 static void *myrealloc(void *ptr, size_t size)
25 {
26 /* There might be a realloc() out there that doesn't like reallocing
27 NULL pointers, so we take care of it here */
28 if(ptr)
29 return realloc(ptr, size);
30 else
31 return malloc(size);
32 }
33
34 static size_t
WriteMemoryCallback(void * ptr,size_t size,size_t nmemb,void * data)35 WriteMemoryCallback(void *ptr, size_t size, size_t nmemb, void *data)
36 {
37 size_t realsize = size * nmemb;
38 struct MemoryStruct *mem = (struct MemoryStruct *)data;
39
40 mem->memory = (char*)myrealloc(mem->memory, mem->size + realsize + 1);
41 if (mem->memory) {
42 memcpy(&(mem->memory[mem->size]), ptr, realsize);
43 mem->size += realsize;
44 mem->memory[mem->size] = 0;
45 }
46 return realsize;
47 }
48
doHSSCommand(std::string command,std::string & response)49 hssResponseCode doHSSCommand(std::string command, std::string& response)
50 {
51 char url[128];
52 snprintf(url, 128, "%s?%s", HSS_SERVER, command.c_str());
53
54 struct MemoryStruct chunk;
55 chunk.memory=NULL; /* we expect realloc(NULL, size) to work */
56 chunk.size = 0; /* no data at this point */
57
58 CURL *curl_handle;
59
60 curl_global_init(CURL_GLOBAL_ALL);
61
62 /* init the curl session */
63 curl_handle = curl_easy_init();
64
65 /* specify URL to get */
66 curl_easy_setopt(curl_handle, CURLOPT_URL, url);
67
68 /* send all data to this function */
69 curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION, WriteMemoryCallback);
70
71 /* we pass our 'chunk' struct to the callback function */
72 curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA, (void *)&chunk);
73
74 /* some servers don't like requests that are made without a user-agent
75 field, so we provide one */
76 curl_easy_setopt(curl_handle, CURLOPT_USERAGENT, "libcurl-agent/1.0");
77
78 /* get it! */
79 curl_easy_perform(curl_handle);
80
81 response = chunk.memory;
82
83 hssResponseCode ret;
84
85 if (response.substr(0, 7) == "Error :" )
86 ret = HSS_ERROR;
87 else if (response.substr(0, 7) == "Result:" )
88 ret = HSS_SUCCESS;
89 else
90 ret = HSS_FAIL;
91
92 response = response.substr(8);
93 response.erase(response.find_first_of('\n'));
94
95 if (chunk.memory)
96 free(chunk.memory);
97
98 /* cleanup curl stuff */
99 curl_easy_cleanup(curl_handle);
100
101 curl_global_cleanup();
102
103 return ret;
104 }
105