2 #include <sys/resource.h>
5 #include "apachetools.h"
6 #include <opensrf/osrf_app_session.h>
7 #include <opensrf/osrf_system.h>
8 #include <opensrf/osrfConfig.h>
9 #include <opensrf/osrf_json.h>
10 #include <opensrf/osrf_cache.h>
12 #define MODULE_NAME "osrf_http_translator_module"
13 #define OSRF_TRANSLATOR_CONFIG_FILE "OSRFTranslatorConfig"
14 #define OSRF_TRANSLATOR_CONFIG_CTX "OSRFTranslatorConfigContext"
15 #define OSRF_TRANSLATOR_CACHE_SERVER "OSRFTranslatorCacheServer"
17 #define DEFAULT_TRANSLATOR_CONFIG_CTX "gateway"
18 #define DEFAULT_TRANSLATOR_CONFIG_FILE "/openils/conf/opensrf_core.xml"
19 #define DEFAULT_TRANSLATOR_TIMEOUT 1200
20 #define DEFAULT_TRANSLATOR_CACHE_SERVERS "127.0.0.1:11211"
22 #define MULTIPART_CONTENT_TYPE "multipart/x-mixed-replace;boundary=\"%s\""
23 #define JSON_CONTENT_TYPE "text/plain"
24 #define MAX_MSGS_PER_PACKET 256
25 #define CACHE_TIME 300
27 #define OSRF_HTTP_HEADER_TO "X-OpenSRF-to"
28 #define OSRF_HTTP_HEADER_XID "X-OpenSRF-xid"
29 #define OSRF_HTTP_HEADER_FROM "X-OpenSRF-from"
30 #define OSRF_HTTP_HEADER_THREAD "X-OpenSRF-thread"
31 #define OSRF_HTTP_HEADER_TIMEOUT "X-OpenSRF-timeout"
32 #define OSRF_HTTP_HEADER_SERVICE "X-OpenSRF-service"
33 #define OSRF_HTTP_HEADER_MULTIPART "X-OpenSRF-multipart"
35 char* configFile = DEFAULT_TRANSLATOR_CONFIG_FILE;
36 char* configCtx = DEFAULT_TRANSLATOR_CONFIG_CTX;
37 char* cacheServers = DEFAULT_TRANSLATOR_CACHE_SERVERS;
39 char* routerName = NULL;
40 char* domainName = NULL;
41 int osrfConnected = 0;
42 char recipientBuf[128];
43 char contentTypeBuf[80];
45 // for development only, writes to apache error log
46 static void _dbg(char* s, ...) {
48 fprintf(stderr, "%s\n", VA_BUF);
55 transport_client* handle;
59 const char* recipient;
62 const char* remoteHost;
72 static const char* osrfHttpTranslatorGetConfigFile(cmd_parms *parms, void *config, const char *arg) {
73 configFile = (char*) arg;
76 static const char* osrfHttpTranslatorGetConfigFileCtx(cmd_parms *parms, void *config, const char *arg) {
77 configCtx = (char*) arg;
80 static const char* osrfHttpTranslatorGetCacheServer(cmd_parms *parms, void *config, const char *arg) {
81 cacheServers = (char*) arg;
85 /** set up the configuratoin handlers */
86 static const command_rec osrf_json_gateway_cmds[] = {
87 AP_INIT_TAKE1( OSRF_TRANSLATOR_CONFIG_FILE, osrfHttpTranslatorGetConfigFile,
88 NULL, RSRC_CONF, "osrf translator config file"),
89 AP_INIT_TAKE1( OSRF_TRANSLATOR_CONFIG_CTX, osrfHttpTranslatorGetConfigFileCtx,
90 NULL, RSRC_CONF, "osrf translator config file context"),
91 AP_INIT_TAKE1( OSRF_TRANSLATOR_CACHE_SERVER, osrfHttpTranslatorGetCacheServer,
92 NULL, RSRC_CONF, "osrf translator cache server"),
97 // there can only be one, so use a global static one
98 static osrfHttpTranslator globalTranslator;
101 * Constructs a new translator object based on the current apache
102 * request_rec. Reads the request body and headers.
104 static osrfHttpTranslator* osrfNewHttpTranslator(request_rec* apreq) {
105 osrfHttpTranslator* trans = &globalTranslator;
106 trans->apreq = apreq;
108 trans->connectOnly = 0;
109 trans->disconnectOnly = 0;
110 trans->remoteHost = apreq->connection->remote_ip;
111 trans->messages = NULL;
113 /* load the message body */
114 osrfStringArray* params = apacheParseParms(apreq);
115 trans->body = apacheGetFirstParamValue(params, "osrf-msg");
116 osrfStringArrayFree(params);
118 /* load the request headers */
119 if (apr_table_get(apreq->headers_in, OSRF_HTTP_HEADER_XID)) // force our log xid to match the caller
120 osrfLogForceXid(strdup(apr_table_get(apreq->headers_in, OSRF_HTTP_HEADER_XID)));
122 trans->handle = osrfSystemGetTransportClient();
123 trans->recipient = apr_table_get(apreq->headers_in, OSRF_HTTP_HEADER_TO);
124 trans->service = apr_table_get(apreq->headers_in, OSRF_HTTP_HEADER_SERVICE);
125 trans->thread = apr_table_get(apreq->headers_in, OSRF_HTTP_HEADER_THREAD); /* XXX create thread if necessary */
127 const char* timeout = apr_table_get(apreq->headers_in, OSRF_HTTP_HEADER_TIMEOUT);
129 trans->timeout = atoi(timeout);
131 trans->timeout = DEFAULT_TRANSLATOR_TIMEOUT;
133 const char* multipart = apr_table_get(apreq->headers_in, OSRF_HTTP_HEADER_MULTIPART);
134 if(multipart && !strcasecmp(multipart, "true"))
135 trans->multipart = 1;
137 trans->multipart = 0;
140 snprintf(buf, sizeof(buf), "%d%ld", getpid(), time(NULL));
141 trans->delim = md5sum(buf);
146 static void osrfHttpTranslatorFree(osrfHttpTranslator* trans) {
152 osrfListFree(trans->messages);
155 static void osrfHttpTranslatorDebug(osrfHttpTranslator* trans) {
156 _dbg("-----------------------------------");
157 _dbg("body = %s", trans->body);
158 _dbg("service = %s", trans->service);
159 _dbg("thread = %s", trans->thread);
160 _dbg("multipart = %d", trans->multipart);
161 _dbg("recipient = %s", trans->recipient);
165 * Determines the correct recipient address based on the requested
166 * service or recipient address.
168 static int osrfHttpTranslatorSetTo(osrfHttpTranslator* trans) {
170 jsonObject* sessionCache = NULL;
173 if(trans->recipient) {
174 osrfLogError(OSRF_LOG_MARK, "Specifying both SERVICE and TO are not allowed");
177 // service is specified, build a recipient address
178 // from the router, domain, and service
179 int size = snprintf(recipientBuf, 128, "%s@%s/%s", routerName, domainName, trans->service);
180 recipientBuf[size] = '\0';
181 osrfLogDebug(OSRF_LOG_MARK, "Set recipient to %s", recipientBuf);
182 trans->recipient = recipientBuf;
188 if(trans->recipient) {
189 sessionCache = osrfCacheGetObject(trans->thread);
192 char* ipAddr = jsonObjectGetString(jsonObjectGetKey(sessionCache, "ip"));
193 char* recipient = jsonObjectGetString(jsonObjectGetKey(sessionCache, "jid"));
195 // choosing a specific recipient address requires that the recipient and
196 // thread be cached on the server (so drone processes cannot be hijacked)
197 if(!strcmp(ipAddr, trans->remoteHost) && !strcmp(recipient, trans->recipient)) {
198 osrfLogDebug(OSRF_LOG_MARK, "Found cached session from host %s and recipient %s",
199 trans->remoteHost, trans->recipient);
201 trans->service = jsonObjectGetString(jsonObjectGetKey(sessionCache, "service"));
204 osrfLogError(OSRF_LOG_MARK,
205 "Session cache for thread %s does not match request", trans->thread);
208 osrfLogError(OSRF_LOG_MARK,
209 "attempt to send directly to %s without a session", trans->recipient);
212 osrfLogError(OSRF_LOG_MARK, "No SERVICE or RECIPIENT defined");
216 jsonObjectFree(sessionCache);
221 * Parses the request body and logs any REQUEST messages to the activity log
223 static int osrfHttpTranslatorParseRequest(osrfHttpTranslator* trans) {
225 osrfMessage* msgList[MAX_MSGS_PER_PACKET];
226 int numMsgs = osrf_message_deserialize(trans->body, msgList, MAX_MSGS_PER_PACKET);
227 osrfLogDebug(OSRF_LOG_MARK, "parsed %d opensrf messages in this packet", numMsgs);
234 if(msg->m_type == CONNECT) {
235 trans->connectOnly = 1;
238 if(msg->m_type == DISCONNECT) {
239 trans->disconnectOnly = 1;
244 // log request messages to the activity log
246 for(i = 0; i < numMsgs; i++) {
248 if(msg->m_type == REQUEST) {
250 jsonObject* params = msg->_params;
251 growing_buffer* act = buffer_init(128);
252 buffer_fadd(act, "[%s] [%s] %s %s", trans->remoteHost, "", trans->service, msg->method_name);
256 while((str = jsonObjectGetString(jsonObjectGetIndex(params, i++)))) {
258 OSRF_BUFFER_ADD(act, " ");
260 OSRF_BUFFER_ADD(act, ", ");
261 OSRF_BUFFER_ADD(act, str);
263 osrfLogActivity(OSRF_LOG_MARK, act->buf);
271 static int osrfHttpTranslatorCheckStatus(osrfHttpTranslator* trans, transport_message* msg) {
272 osrfMessage* omsgList[MAX_MSGS_PER_PACKET];
273 int numMsgs = osrf_message_deserialize(msg->body, omsgList, MAX_MSGS_PER_PACKET);
274 osrfLogDebug(OSRF_LOG_MARK, "parsed %d response messages", numMsgs);
275 if(numMsgs == 0) return 0;
277 osrfMessage* last = omsgList[numMsgs-1];
278 if(last->m_type == STATUS) {
279 if(last->status_code == OSRF_STATUS_TIMEOUT) {
280 osrfLogDebug(OSRF_LOG_MARK, "removing cached session on request timeout");
281 osrfCacheRemove(trans->thread);
284 // XXX hm, check for explicit status=COMPLETE message instead??
285 if(last->status_code != OSRF_STATUS_CONTINUE)
292 static void osrfHttpTranslatorInitHeaders(osrfHttpTranslator* trans, transport_message* msg) {
293 apr_table_set(trans->apreq->headers_out, OSRF_HTTP_HEADER_FROM, msg->sender);
294 apr_table_set(trans->apreq->headers_out, OSRF_HTTP_HEADER_THREAD, trans->thread);
295 if(trans->multipart) {
296 sprintf(contentTypeBuf, MULTIPART_CONTENT_TYPE, trans->delim);
297 contentTypeBuf[79] = '\0';
298 osrfLogDebug(OSRF_LOG_MARK, "content type %s : %s : %s", MULTIPART_CONTENT_TYPE, trans->delim, contentTypeBuf);
299 ap_set_content_type(trans->apreq, contentTypeBuf);
300 ap_rprintf(trans->apreq, "--%s\n", trans->delim);
302 ap_set_content_type(trans->apreq, JSON_CONTENT_TYPE);
306 static void osrfHttpTranslatorCacheSession(osrfHttpTranslator* trans) {
307 jsonObject* cacheObj = jsonNewObject(NULL);
308 jsonObjectSetKey(cacheObj, "ip", jsonNewObject(trans->remoteHost));
309 jsonObjectSetKey(cacheObj, "jid", jsonNewObject(trans->recipient));
310 jsonObjectSetKey(cacheObj, "service", jsonNewObject(trans->service));
311 osrfCachePutObject((char*) trans->thread, cacheObj, CACHE_TIME);
316 * Writes a single chunk of multipart/x-mixed-replace content
318 static void osrfHttpTranslatorWriteChunk(osrfHttpTranslator* trans, transport_message* msg) {
319 ap_rprintf(trans->apreq,
320 "Content-type: %s\n\n%s\n\n", JSON_CONTENT_TYPE, msg->body);
321 //osrfLogInternal(OSRF_LOG_MARK, "Apache sending data: Content-type: %s\n\n%s\n\n", JSON_CONTENT_TYPE, msg->body);
322 if(trans->complete) {
323 ap_rprintf(trans->apreq, "--%s--\n", trans->delim);
324 //osrfLogInternal(OSRF_LOG_MARK, "Apache sending data: --%s--\n", trans->delim);
326 ap_rprintf(trans->apreq, "--%s\n", trans->delim);
327 //osrfLogInternal(OSRF_LOG_MARK, "Apache sending data: --%s\n", trans->delim);
329 ap_rflush(trans->apreq);
332 static int osrfHttpTranslatorProcess(osrfHttpTranslator* trans) {
333 if(trans->body == NULL)
334 return HTTP_BAD_REQUEST;
336 if(!osrfHttpTranslatorSetTo(trans))
337 return HTTP_BAD_REQUEST;
339 if(!osrfHttpTranslatorParseRequest(trans))
340 return HTTP_BAD_REQUEST;
342 while(client_recv(trans->handle, 0))
343 continue; // discard any old status messages in the recv queue
345 // send the message to the recipient
346 transport_message* tmsg = message_init(
347 trans->body, NULL, trans->thread, trans->recipient, NULL);
348 message_set_osrf_xid(tmsg, osrfLogGetXid());
349 client_send_message(trans->handle, tmsg);
352 if(trans->disconnectOnly) {
353 osrfLogDebug(OSRF_LOG_MARK, "exiting early on disconnect");
357 // process the response from the opensrf service
359 while(!trans->complete) {
360 transport_message* msg = client_recv(trans->handle, trans->timeout);
362 if(trans->handle->error) {
363 osrfLogError(OSRF_LOG_MARK, "Transport error");
364 return HTTP_INTERNAL_SERVER_ERROR;
368 return HTTP_GATEWAY_TIME_OUT;
371 osrfLogError(OSRF_LOG_MARK, "XMPP message resulted in error code %d", msg->error_code);
372 return HTTP_NOT_FOUND;
375 if(!osrfHttpTranslatorCheckStatus(trans, msg))
379 osrfHttpTranslatorInitHeaders(trans, msg);
380 osrfHttpTranslatorCacheSession(trans);
384 if(trans->multipart) {
385 osrfHttpTranslatorWriteChunk(trans, msg);
386 if(trans->connectOnly)
390 trans->messages = osrfNewList();
391 osrfListPush(trans->messages, msg->body);
393 if(trans->complete || trans->connectOnly) {
394 growing_buffer* buf = buffer_init(128);
396 OSRF_BUFFER_ADD(buf, osrfListGetIndex(trans->messages, 0));
397 for(i = 1; i < trans->messages->size; i++) {
398 buffer_chomp(buf); // chomp off the closing array bracket
399 char* body = osrfListGetIndex(trans->messages, i);
400 char newbuf[strlen(body)];
401 sprintf(newbuf, body+1); // chomp off the opening array bracket
402 OSRF_BUFFER_ADD_CHAR(buf, ',');
403 OSRF_BUFFER_ADD(buf, newbuf);
406 ap_rputs(buf->buf, trans->apreq);
415 static void testConnection(request_rec* r) {
416 if(!osrfConnected || !osrfSystemGetTransportClient()) {
417 osrfLogError(OSRF_LOG_MARK, "We're not connected to OpenSRF");
418 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "We're not connected to OpenSRF");
419 usleep(100000); // .1 second to prevent process die/start overload
425 static apr_status_t childExit(void* data) {
426 osrf_system_shutdown();
430 static void childInit(apr_pool_t *p, server_rec *s) {
431 if(!osrfSystemBootstrapClientResc(configFile, configCtx, "translator")) {
432 ap_log_error( APLOG_MARK, APLOG_ERR, 0, s,
433 "Unable to Bootstrap OpenSRF Client with config %s..", configFile);
437 routerName = osrfConfigGetValue(NULL, "/router_name");
438 domainName = osrfConfigGetValue(NULL, "/domain");
439 const char* servers[] = {cacheServers};
440 osrfCacheInit(servers, 1, 86400);
443 // at pool destroy time (= child exit time), cleanup
444 // XXX causes us to disconnect even for clone()'d process cleanup (as in mod_cgi)
445 //apr_pool_cleanup_register(p, NULL, childExit, apr_pool_cleanup_null);
448 static int handler(request_rec *r) {
450 if(strcmp(r->handler, MODULE_NAME)) return DECLINED;
451 if(r->header_only) return stat;
453 r->allowed |= (AP_METHOD_BIT << M_GET);
454 r->allowed |= (AP_METHOD_BIT << M_POST);
456 osrfLogSetAppname("osrf_http_translator");
459 osrfHttpTranslator* trans = osrfNewHttpTranslator(r);
462 stat = osrfHttpTranslatorProcess(trans);
463 //osrfHttpTranslatorDebug(trans);
464 osrfLogInfo(OSRF_LOG_MARK, "translator resulted in status %d", stat);
466 osrfLogWarning(OSRF_LOG_MARK, "no message body to process");
468 osrfHttpTranslatorFree(trans);
473 static void registerHooks (apr_pool_t *p) {
474 ap_hook_handler(handler, NULL, NULL, APR_HOOK_MIDDLE);
475 ap_hook_child_init(childInit, NULL, NULL, APR_HOOK_MIDDLE);
479 module AP_MODULE_DECLARE_DATA osrf_http_translator_module = {
480 STANDARD20_MODULE_STUFF,