summaryrefslogtreecommitdiffstats
path: root/src/uscxml/ioprocessor/basichttp/libevent/EventIOProcessor.cpp
blob: c06c7e8202a93854857df56b9384e878e6098272 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
#include "uscxml/ioprocessor/basichttp/libevent/EventIOProcessor.h"
#include "uscxml/Message.h"
#include <iostream>
#include <event2/dns.h>
#include <event2/buffer.h>
#include <event2/keyvalq_struct.h>

#include <string.h>

#include <io/uri.hpp>
#include <glog/logging.h>

#include <netdb.h>
#include <arpa/inet.h>

namespace uscxml {
namespace io {
namespace libevent {

// see http://www.w3.org/TR/scxml/#BasicHTTPEventProcessor

EventIOProcessor::EventIOProcessor() {
}

EventIOProcessor::~EventIOProcessor() {
  _eventQueue.stop();
  EventIOServer* httpServer = EventIOServer::getInstance();
  httpServer->unregisterProcessor(this);
}

IOProcessor* EventIOProcessor::create(Interpreter* interpreter) {
  EventIOProcessor* io = new EventIOProcessor();
  io->_interpreter = interpreter;

  io->_dns = evdns_base_new(io->_eventQueue._eventLoop, 1);
  assert(io->_dns);
  assert(evdns_base_count_nameservers(io->_dns) > 0);
  
  // register at http server
  EventIOServer* httpServer = EventIOServer::getInstance();
  httpServer->registerProcessor(io);
  
  io->start();
  return io;
}

void EventIOProcessor::start() {
  _eventQueue.start();
}

void EventIOProcessor::send(SendRequest& req) {
  // I cant figure out how to copy the reference into the struct :(
  _sendData[req.sendid].req = req;
  _sendData[req.sendid].ioProcessor = this;

  if (req.delayMs > 0) {
    LOG(INFO) << "Enqueing HTTP send request";
    _eventQueue.addEvent(req.sendid, EventIOProcessor::httpMakeSendReq, req.delayMs, &_sendData[req.sendid]);
  } else {
    LOG(INFO) << "Sending HTTP send request";
    EventIOProcessor::httpMakeSendReq(&_sendData[req.sendid], req.sendid);
  }
}

void EventIOProcessor::httpMakeSendReq(void* userdata, std::string eventName) {
  SendData* sendData = ((SendData*)userdata);
  EventIOProcessor* THIS = sendData->ioProcessor;
  int err = 0;
  char uriBuf[1024];
  
  struct evhttp_uri* targetURI = evhttp_uri_parse(sendData->req.target.c_str());
  if (evhttp_uri_get_port(targetURI) == 0)
    evhttp_uri_set_port(targetURI, 80);
  const char* hostName = evhttp_uri_get_host(targetURI);

  // use synchronous dns resolving for multicast dns
  if(strlen(hostName) >= strlen(".local")) {
    if(strcmp(hostName + strlen(hostName) - strlen(".local"), ".local") == 0) {
      evhttp_uri_set_host(targetURI, EventIOServer::syncResolve(hostName).c_str());
    }
  }
  evhttp_uri_join(targetURI, uriBuf, 1024);

  LOG(INFO) << "URI for send request: " << uriBuf << std::endl;
  
  std::stringstream ssEndPoint;
  ssEndPoint << evhttp_uri_get_host(targetURI) << ":" << evhttp_uri_get_port(targetURI);
  std::string endPoint = ssEndPoint.str();

  std::stringstream ssLocalURI;
  ssLocalURI << evhttp_uri_get_path(targetURI) << evhttp_uri_get_fragment(targetURI);
  std::string localURI = ssLocalURI.str();

  if (THIS->_httpConnections.find(endPoint) == THIS->_httpConnections.end())
    THIS->_httpConnections[endPoint] = evhttp_connection_base_new(THIS->_eventQueue._eventLoop, THIS->_dns, evhttp_uri_get_host(targetURI), evhttp_uri_get_port(targetURI));

  struct evhttp_connection* httpConn = THIS->_httpConnections[endPoint];
  struct evhttp_request* httpReq = evhttp_request_new(EventIOProcessor::httpSendReqDone, userdata);
  
#if 0
  // event name
  if (sendData->req.event.size() > 0) {
    evhttp_add_header(evhttp_request_get_output_headers(httpReq), "_scxmleventname", evhttp_encode_uri(sendData->req.event.c_str()));
  }
  
  // event namelist
  if (sendData->req.namelist.size() > 0) {
    std::map<std::string, std::string>::iterator namelistIter = sendData->req.namelist.begin();
    while (namelistIter != sendData->req.namelist.end()) {
      evhttp_add_header(evhttp_request_get_output_headers(httpReq),
                        namelistIter->first.c_str(),
                        evhttp_encode_uri(namelistIter->second.c_str()));
      namelistIter++;
    }
  }
  
  // event params
  if (sendData->req.params.size() > 0) {
    std::map<std::string, std::string>::iterator paramIter = sendData->req.params.begin();
    while (paramIter != sendData->req.params.end()) {
      evhttp_add_header(evhttp_request_get_output_headers(httpReq),
                        paramIter->first.c_str(),
                        evhttp_encode_uri(paramIter->second.c_str()));
      paramIter++;
    }
  }
  
  // content
  if (sendData->req.content.size() > 0)
    evbuffer_add(evhttp_request_get_output_buffer(httpReq), sendData->req.content.c_str(), sendData->req.content.size());
#endif

  evhttp_add_header(evhttp_request_get_output_headers(httpReq), "_scxmleventstruct", evhttp_encode_uri(sendData->req.toXMLString().c_str()));

  
  THIS->_httpRequests[sendData->req.sendid] = httpReq;
  err = evhttp_make_request(httpConn,
                            httpReq,
                            EVHTTP_REQ_POST, localURI.c_str());
  if (err) {
    LOG(ERROR) << "Could not make http request to " << sendData->req.target;
  }
}

void EventIOProcessor::httpRecvReq(struct evhttp_request *req, void *arg) {
  
	const char *cmdtype;
	struct evkeyvalq *headers;
	struct evkeyval *header;
	struct evbuffer *buf;

  switch (evhttp_request_get_command(req)) {
    case EVHTTP_REQ_GET: cmdtype = "GET"; break;
    case EVHTTP_REQ_POST: cmdtype = "POST"; break;
    case EVHTTP_REQ_HEAD: cmdtype = "HEAD"; break;
    case EVHTTP_REQ_PUT: cmdtype = "PUT"; break;
    case EVHTTP_REQ_DELETE: cmdtype = "DELETE"; break;
    case EVHTTP_REQ_OPTIONS: cmdtype = "OPTIONS"; break;
    case EVHTTP_REQ_TRACE: cmdtype = "TRACE"; break;
    case EVHTTP_REQ_CONNECT: cmdtype = "CONNECT"; break;
    case EVHTTP_REQ_PATCH: cmdtype = "PATCH"; break;
    default: cmdtype = "unknown"; break;
	}

  Event reqEvent;
  reqEvent.type = Event::EXTERNAL;

  // map headers to event structure
  headers = evhttp_request_get_input_headers(req);
	for (header = headers->tqh_first; header;
       header = header->next.tqe_next) {
//    std::cout << "Header: " << header->key << std::endl;
//    std::cout << "Value: " << evhttp_decode_uri(header->value) << std::endl;
    if (boost::iequals("_scxmleventstruct", header->key)) {
      reqEvent = Event::fromXML(evhttp_decode_uri(header->value));
      break;
    } else if (boost::iequals("_scxmleventname", header->key)) {
      reqEvent.name = evhttp_decode_uri(header->value);
    } else {
      reqEvent.compound[header->key] = Data(evhttp_decode_uri(header->value), Data::VERBATIM);
    }
	}

  // get content into event
  std::string content;
	buf = evhttp_request_get_input_buffer(req);
	while (evbuffer_get_length(buf)) {
		int n;
		char cbuf[128];
		n = evbuffer_remove(buf, cbuf, sizeof(buf)-1);
		if (n > 0) {
      content.append(cbuf, n);
    }
	}
  reqEvent.compound["content"] = Data(content, Data::VERBATIM);
  
  EventIOProcessor* THIS = (EventIOProcessor*)arg;
  THIS->_interpreter->receive(reqEvent);
  
	evhttp_send_reply(req, 200, "OK", NULL);
}

void EventIOProcessor::httpSendReqDone(struct evhttp_request *req, void *cb_arg) {
  if (req) {
    LOG(INFO) << "got return code " << evhttp_request_get_response_code(req) << std::endl;
  }
}

void EventIOProcessor::invoke(InvokeRequest& req) {
  
}
void EventIOProcessor::cancel(const std::string sendId) {
  
}

EventIOServer::EventIOServer(unsigned short port) {
  _port = port;
  _base = event_base_new();
  _http = evhttp_new(_base);
  _handle = NULL;
  while((_handle = evhttp_bind_socket_with_handle(_http, INADDR_ANY, _port)) == NULL) {
    _port++;
  }
  determineAddress();
}

EventIOServer::~EventIOServer() {
}

EventIOServer* EventIOServer::_instance = NULL;
tthread::recursive_mutex EventIOServer::_instanceMutex;

EventIOServer* EventIOServer::getInstance() {
  tthread::lock_guard<tthread::recursive_mutex> lock(_instanceMutex);
  if (_instance == NULL) {
    _instance = new EventIOServer(8080);
    _instance->start();
  }
  return _instance;
}

void EventIOServer::registerProcessor(EventIOProcessor* processor) {
  EventIOServer* THIS = getInstance();
  tthread::lock_guard<tthread::recursive_mutex> lock(THIS->_mutex);
  
  /**
   * Determine path for interpreter.
   *
   * If the interpreter has a name and it is not yet taken, choose it as the path 
   * for requests. If the interpreters name path is already taken, append digits
   * until we have an available path.
   *
   * If the interpreter does not specify a name, take its sessionid.
   */
  
  std::string path = processor->_interpreter->getName();
  if (path.size() == 0) {
    path = processor->_interpreter->getSessionId();
  }
  assert(path.size() > 0);
  
  std::stringstream actualPath(path);
  int i = 1;
  while(THIS->_processors.find(actualPath.str()) != THIS->_processors.end()) {
    actualPath.str(std::string());
    actualPath.clear();
    actualPath << path << ++i;
  }
  
  std::stringstream processorURL;
  processorURL << "http://" << THIS->_address << ":" << THIS->_port << "/" << actualPath.str();
  
  THIS->_processors[actualPath.str()] = processor;
  processor->setURL(processorURL.str());
  
  evhttp_set_cb(THIS->_http, ("/" + actualPath.str()).c_str(), EventIOProcessor::httpRecvReq, processor);
//  evhttp_set_cb(THIS->_http, "/", EventIOProcessor::httpRecvReq, processor);
//  evhttp_set_gencb(THIS->_http, EventIOProcessor::httpRecvReq, NULL);
}

void EventIOServer::unregisterProcessor(EventIOProcessor* processor) {
  EventIOServer* THIS = getInstance();
  tthread::lock_guard<tthread::recursive_mutex> lock(THIS->_mutex);
  evhttp_del_cb(THIS->_http, processor->getURL().c_str());
}
  
void EventIOServer::start() {
  _isRunning = true;
  _thread = new tthread::thread(EventIOServer::run, this);
}

void EventIOServer::run(void* instance) {
  EventIOServer* THIS = (EventIOServer*)instance;
  while(THIS->_isRunning) {
    LOG(INFO) << "Dispatching HTTP Server" << std::endl;
    event_base_dispatch(THIS->_base);
  }
  LOG(INFO) << "HTTP Server stopped" << std::endl;
}

std::string EventIOServer::syncResolve(const std::string& hostname) {
  struct hostent *he;
  struct in_addr **addr_list;
  int i;

  if ( (he = gethostbyname( hostname.c_str() ) ) != NULL) {
    addr_list = (struct in_addr **) he->h_addr_list;
    for(i = 0; addr_list[i] != NULL; i++) {
      return std::string(inet_ntoa(*addr_list[i]));
    }
  }
  return "";
}
  
void EventIOServer::determineAddress() {

  char hostname[1024];
  gethostname(hostname, 1024);
  _address = std::string(hostname);
  
#if 0
  struct sockaddr_storage ss;
  evutil_socket_t fd;
  ev_socklen_t socklen = sizeof(ss);
  char addrbuf[128];

  void *inaddr;
  const char *addr;
  int got_port = -1;
  fd = evhttp_bound_socket_get_fd(_handle);
  memset(&ss, 0, sizeof(ss));
  if (getsockname(fd, (struct sockaddr *)&ss, &socklen)) {
    perror("getsockname() failed");
    return;
  }
  
  if (ss.ss_family == AF_INET) {
    got_port = ntohs(((struct sockaddr_in*)&ss)->sin_port);
    inaddr = &((struct sockaddr_in*)&ss)->sin_addr;
  } else if (ss.ss_family == AF_INET6) {
    got_port = ntohs(((struct sockaddr_in6*)&ss)->sin6_port);
    inaddr = &((struct sockaddr_in6*)&ss)->sin6_addr;
  } else {
    fprintf(stderr, "Weird address family %d\n",
            ss.ss_family);
    return;
  }
  addr = evutil_inet_ntop(ss.ss_family, inaddr, addrbuf,
                          sizeof(addrbuf));
  if (addr) {
    _address = std::string(addr);
  } else {
    fprintf(stderr, "evutil_inet_ntop failed\n");
    return;
  }
#endif
}

}
}
}