+#include "iotquery.h"
+#include <string.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+#include <sys/file.h>
+#include <fcntl.h>
+#include <unistd.h>
+#include <stdlib.h>
+
+using namespace std;
+
+const char * query_str="QUERY_STRING";
+const char * uri_str="REQUEST_URI";
+const char * method_str="REQUEST_METHOD";
+const char * iotcloudroot_str="IOTCLOUD_ROOT";
+const char * length_str="CONTENT_LENGTH";
+
+IoTQuery::IoTQuery(FCGX_Request *request) :
+ request(request),
+ data(NULL),
+ directory(NULL),
+ uri(NULL),
+ query(NULL),
+ method(NULL),
+ iotcloudroot(NULL),
+ dir(NULL),
+ length(0),
+ fd(-1)
+{
+}
+
+
+IoTQuery::~IoTQuery() {
+ if (fd >= 0) {
+ close(fd);
+ }
+ if (directory)
+ delete directory;
+ if (data)
+ delete data;
+ if (dir != NULL)
+ closedir(dir);
+}
+
+void IoTQuery::processQuery() {
+ parseQuery();
+ getDirectory();
+ readData();
+
+ if (strncmp(method, "POST", 4) != 0)
+ return;
+
+ if (directory == NULL ||
+ (dir = opendir(directory)) == NULL)
+ return;
+
+ if (openMaxFile() < 0)
+ return;
+
+ flock(fd, LOCK_EX);
+
+ cout << "Content-type: text/html\r\n"
+ << "\r\n"
+ << "<html>\n"
+ << " <head>\n"
+ << " <title>Hello, World!</title>\n"
+ << " </head>\n"
+ << " <body>\n"
+ << " <h1>Hello, World!</h1>\n"
+ << " </body>\n";
+
+ cout << uri_str << " " << uri << "\n";
+ cout << query_str << " " << query << "\n";
+ cout << method_str << " " << method << "\n";
+ cout << iotcloudroot_str << " " << iotcloudroot << "\n";
+ if (data)
+ cout << "[" << data << "]";
+
+
+
+ cout << "</html>\n";
+}
+
+
+void IoTQuery::readData() {
+ if (length) {
+ data = new char[length+1];
+ memset(data, 0, length+1);
+ cin.read(data, length);
+ }
+ do {
+ char dummy;
+ cin >> dummy;
+ } while (!cin.eof());
+}
+
+
+void IoTQuery::parseQuery() {
+ uri = FCGX_GetParam(uri_str, request->envp);
+ query = FCGX_GetParam(query_str, request->envp);
+ method = FCGX_GetParam(method_str, request->envp);
+ iotcloudroot = FCGX_GetParam(iotcloudroot_str, request->envp);
+
+ char * reqlength = FCGX_GetParam(length_str, request->envp);
+ if (length) {
+ length=strtol(reqlength, NULL, 10);
+ } else {
+ length=0;
+ }
+}
+
+void IoTQuery::getDirectory() {
+ char * split = strchr((char *)uri, '?');
+ if (split == NULL)
+ return;
+ int split_len = (int) (split-uri);
+ int rootdir_len = strlen(iotcloudroot);
+ int directory_len = split_len + rootdir_len + 1;
+ directory = new char[directory_len];
+ memcpy(directory, iotcloudroot, rootdir_len);
+ memcpy(directory + rootdir_len, uri, split_len);
+ directory[directory_len]=0;
+}
+
+int IoTQuery::openMaxFile() {
+ char maxfile[]="queuesize";
+ int len=strlen(directory);
+
+ char * filename=new char[len+sizeof(maxfile)+2];
+ memcpy(filename, directory, len);
+ filename[len]='/';
+ memcpy(filename+len+1, maxfile, sizeof(maxfile));
+ filename[len+sizeof(maxfile)+1]=0;
+ fd=open(filename, O_CREAT| O_RDWR, S_IRUSR| S_IWUSR);
+ delete filename;
+ return fd;
+}