hce-node application  1.4.3
HCE Hierarchical Cluster Engine node application
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros
HttpParser.cpp
Go to the documentation of this file.
1 #include <HttpParser.h>
2 HttpParser::HttpParser(const char *content, size_t contentLen)
3 {
4  method = -1;
5  this->content = content;
6  this->contentLen = contentLen;
7  if(strstr(content, "GET "))
8  {
9  method = HTTP_GET;
10  parseGET();
11  }
12  else
13  {
14  if(strstr(content, "POST "))
15  {
16  method = HTTP_POST;
17  parsePOST();
18  }
19  }
20 }
21 
22 void HttpParser::parseGET()
23 {
24  const char *pos = strstr(content, "GET ");
25  size_t idx = 0;
26  if(pos)
27  {
28  pos += 4;
29  idx = pos - content;
30  while((*pos == ' ' || *pos == '\t') && idx < contentLen)
31  {
32  pos++;
33  idx++;
34  }
35  while(idx < contentLen && *pos != '?' && !delimiter(*pos))
36  {
37  pos++;
38  idx++;
39  }
40  if(*pos == '?')
41  {
42  parse(++pos);
43  }
44  }
45 }
46 
47 void HttpParser::parsePOST()
48 {
49  const char *pos = strstr(content, "\r\n\r\n");
50  if(pos)
51  {
52  pos += 4;
53  if(pos < content + contentLen)
54  {
55  parse(pos);
56  }
57  }
58 }
59 
60 void HttpParser::parse(const char *pos)
61 {
62  size_t idx = pos - content;
63  while(idx < contentLen && !delimiter(*pos))
64  {
65  Variable *var = new(std::nothrow) Variable();
66  if(!var)
67  {
68  break;
69  }
70  size_t len = 0;
71  const char *buf = pos;
72  while(*pos != '=' && idx < contentLen && !delimiter(*pos))
73  {
74  pos++;
75  idx++;
76  }
77  len = pos - buf;
78  var->name = (char*)malloc(len + 1);
79  if(!var->name)
80  {
81  break;
82  }
83  if(len)
84  {
85  memcpy(var->name, buf, len);
86  }
87  var->name[len] = '\0';
88  pos++;
89  idx++;
90  buf = pos;
91  while(*pos != '&' && idx < contentLen && !delimiter(*pos))
92  {
93  pos++;
94  idx++;
95  }
96  len = pos - buf;
97  var->value = (char*)malloc(len + 1);
98  if(!var->value)
99  {
100  break;
101  }
102  if(len)
103  {
104  memcpy(var->value, buf, len);
105  }
106  var->value[len] = '\0';
107  vars.pushDown(var);
108  if(idx < contentLen && *pos != '&')
109  {
110  break;
111  }
112  pos++;
113  idx++;
114  }
115 }
116 
118 {
119  for(unsigned long i = 0; i < vars.getCount(); i++)
120  {
121  free(vars[i]->name);
122  free(vars[i]->value);
123  delete vars[i];
124  }
125 }
126 
127 char* HttpParser::getByName(const char *var)
128 {
129  for(unsigned long i = 0; i < vars.getCount(); i++)
130  {
131  if(strcmp(vars[i]->name, var) == 0)
132  {
133  return vars[i]->value;
134  }
135  }
136  return NULL;
137 }
138 
139