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"
36 char* configFile = DEFAULT_TRANSLATOR_CONFIG_FILE;
37 char* configCtx = DEFAULT_TRANSLATOR_CONFIG_CTX;
38 char* cacheServers = DEFAULT_TRANSLATOR_CACHE_SERVERS;
40 char* routerName = NULL;
41 char* domainName = NULL;
42 int osrfConnected = 0;
43 char recipientBuf[128];
44 char contentTypeBuf[80];
46 // for development only, writes to apache error log
47 static void _dbg(char* s, ...) {
49 fprintf(stderr, "%s\n", VA_BUF);
56 transport_client* handle;
60 const char* recipient;
63 const char* remoteHost;
67 int connectOnly; // there is only 1 message, a CONNECT
68 int disconnectOnly; // there is only 1 message, a DISCONNECT
69 int connecting; // there is a connect message in this batch
70 int disconnecting; // there is a connect message in this batch
75 static const char* osrfHttpTranslatorGetConfigFile(cmd_parms *parms, void *config, const char *arg) {
76 configFile = (char*) arg;
79 static const char* osrfHttpTranslatorGetConfigFileCtx(cmd_parms *parms, void *config, const char *arg) {
80 configCtx = (char*) arg;
83 static const char* osrfHttpTranslatorGetCacheServer(cmd_parms *parms, void *config, const char *arg) {
84 cacheServers = (char*) arg;
88 /** set up the configuration handlers */
89 static const command_rec osrfHttpTranslatorCmds[] = {
90 AP_INIT_TAKE1( OSRF_TRANSLATOR_CONFIG_FILE, osrfHttpTranslatorGetConfigFile,
91 NULL, RSRC_CONF, "osrf translator config file"),
92 AP_INIT_TAKE1( OSRF_TRANSLATOR_CONFIG_CTX, osrfHttpTranslatorGetConfigFileCtx,
93 NULL, RSRC_CONF, "osrf translator config file context"),
94 AP_INIT_TAKE1( OSRF_TRANSLATOR_CACHE_SERVER, osrfHttpTranslatorGetCacheServer,
95 NULL, RSRC_CONF, "osrf translator cache server"),
100 // there can only be one, so use a global static one
101 static osrfHttpTranslator globalTranslator;
104 * Constructs a new translator object based on the current apache
105 * request_rec. Reads the request body and headers.
107 static osrfHttpTranslator* osrfNewHttpTranslator(request_rec* apreq) {
108 osrfHttpTranslator* trans = &globalTranslator;
109 trans->apreq = apreq;
111 trans->connectOnly = 0;
112 trans->disconnectOnly = 0;
113 trans->connecting = 0;
114 trans->disconnecting = 0;
115 trans->remoteHost = apreq->connection->remote_ip;
116 trans->messages = NULL;
118 /* load the message body */
119 osrfStringArray* params = apacheParseParms(apreq);
120 trans->body = apacheGetFirstParamValue(params, "osrf-msg");
121 osrfStringArrayFree(params);
123 /* load the request headers */
124 if (apr_table_get(apreq->headers_in, OSRF_HTTP_HEADER_XID)) // force our log xid to match the caller
125 osrfLogForceXid(strdup(apr_table_get(apreq->headers_in, OSRF_HTTP_HEADER_XID)));
127 trans->handle = osrfSystemGetTransportClient();
128 trans->recipient = apr_table_get(apreq->headers_in, OSRF_HTTP_HEADER_TO);
129 trans->service = apr_table_get(apreq->headers_in, OSRF_HTTP_HEADER_SERVICE);
131 const char* timeout = apr_table_get(apreq->headers_in, OSRF_HTTP_HEADER_TIMEOUT);
133 trans->timeout = atoi(timeout);
135 trans->timeout = DEFAULT_TRANSLATOR_TIMEOUT;
137 const char* multipart = apr_table_get(apreq->headers_in, OSRF_HTTP_HEADER_MULTIPART);
138 if(multipart && !strcasecmp(multipart, "true"))
139 trans->multipart = 1;
141 trans->multipart = 0;
144 snprintf(buf, sizeof(buf), "%d%ld", getpid(), time(NULL));
145 trans->delim = md5sum(buf);
147 /* Use thread if it has been passed in; otherwise, just use the delimiter */
148 trans->thread = apr_table_get(apreq->headers_in, OSRF_HTTP_HEADER_THREAD)
149 ? apr_table_get(apreq->headers_in, OSRF_HTTP_HEADER_THREAD)
150 : (const char*)trans->delim;
155 static void osrfHttpTranslatorFree(osrfHttpTranslator* trans) {
161 osrfListFree(trans->messages);
164 static void osrfHttpTranslatorDebug(osrfHttpTranslator* trans) {
165 _dbg("-----------------------------------");
166 _dbg("body = %s", trans->body);
167 _dbg("service = %s", trans->service);
168 _dbg("thread = %s", trans->thread);
169 _dbg("multipart = %d", trans->multipart);
170 _dbg("recipient = %s", trans->recipient);
174 * Determines the correct recipient address based on the requested
175 * service or recipient address.
177 static int osrfHttpTranslatorSetTo(osrfHttpTranslator* trans) {
179 jsonObject* sessionCache = NULL;
182 if(trans->recipient) {
183 osrfLogError(OSRF_LOG_MARK, "Specifying both SERVICE and TO are not allowed");
186 // service is specified, build a recipient address
187 // from the router, domain, and service
188 int size = snprintf(recipientBuf, 128, "%s@%s/%s", routerName, domainName, trans->service);
189 recipientBuf[size] = '\0';
190 osrfLogDebug(OSRF_LOG_MARK, "Set recipient to %s", recipientBuf);
191 trans->recipient = recipientBuf;
197 if(trans->recipient) {
198 sessionCache = osrfCacheGetObject(trans->thread);
201 const char* ipAddr = jsonObjectGetString(jsonObjectGetKey(sessionCache, "ip"));
202 const char* recipient = jsonObjectGetString(jsonObjectGetKey(sessionCache, "jid"));
204 // choosing a specific recipient address requires that the recipient and
205 // thread be cached on the server (so drone processes cannot be hijacked)
206 if(!strcmp(ipAddr, trans->remoteHost) && !strcmp(recipient, trans->recipient)) {
207 osrfLogDebug(OSRF_LOG_MARK, "Found cached session from host %s and recipient %s",
208 trans->remoteHost, trans->recipient);
210 trans->service = apr_pstrdup(
211 trans->apreq->pool, jsonObjectGetString(jsonObjectGetKey(sessionCache, "service")));
214 osrfLogError(OSRF_LOG_MARK,
215 "Session cache for thread %s does not match request", trans->thread);
218 osrfLogError(OSRF_LOG_MARK,
219 "attempt to send directly to %s without a session", trans->recipient);
222 osrfLogError(OSRF_LOG_MARK, "No SERVICE or RECIPIENT defined");
226 jsonObjectFree(sessionCache);
231 * Parses the request body and logs any REQUEST messages to the activity log
233 static int osrfHttpTranslatorParseRequest(osrfHttpTranslator* trans) {
235 osrfMessage* msgList[MAX_MSGS_PER_PACKET];
236 int numMsgs = osrf_message_deserialize(trans->body, msgList, MAX_MSGS_PER_PACKET);
237 osrfLogDebug(OSRF_LOG_MARK, "parsed %d opensrf messages in this packet", numMsgs);
244 if(msg->m_type == CONNECT) {
245 trans->connectOnly = 1;
246 trans->connecting = 1;
249 if(msg->m_type == DISCONNECT) {
250 trans->disconnectOnly = 1;
251 trans->disconnecting = 1;
256 // log request messages to the activity log
258 for(i = 0; i < numMsgs; i++) {
261 switch(msg->m_type) {
264 jsonObject* params = msg->_params;
265 growing_buffer* act = buffer_init(128);
266 buffer_fadd(act, "[%s] [%s] %s %s", trans->remoteHost, "", trans->service, msg->method_name);
268 jsonObject* obj = NULL;
271 while((obj = jsonObjectGetIndex(params, i++))) {
272 str = jsonObjectToJSON(obj);
274 OSRF_BUFFER_ADD(act, " ");
276 OSRF_BUFFER_ADD(act, ", ");
277 OSRF_BUFFER_ADD(act, str);
280 osrfLogActivity(OSRF_LOG_MARK, "%s", act->buf);
286 trans->connecting = 1;
290 trans->disconnecting = 1;
298 static int osrfHttpTranslatorCheckStatus(osrfHttpTranslator* trans, transport_message* msg) {
299 osrfMessage* omsgList[MAX_MSGS_PER_PACKET];
300 int numMsgs = osrf_message_deserialize(msg->body, omsgList, MAX_MSGS_PER_PACKET);
301 osrfLogDebug(OSRF_LOG_MARK, "parsed %d response messages", numMsgs);
302 if(numMsgs == 0) return 0;
304 osrfMessage* last = omsgList[numMsgs-1];
305 if(last->m_type == STATUS) {
306 if(last->status_code == OSRF_STATUS_TIMEOUT) {
307 osrfLogDebug(OSRF_LOG_MARK, "removing cached session on request timeout");
308 osrfCacheRemove(trans->thread);
311 // XXX hm, check for explicit status=COMPLETE message instead??
312 if(last->status_code != OSRF_STATUS_CONTINUE)
319 static void osrfHttpTranslatorInitHeaders(osrfHttpTranslator* trans, transport_message* msg) {
320 apr_table_set(trans->apreq->headers_out, OSRF_HTTP_HEADER_FROM, msg->sender);
321 apr_table_set(trans->apreq->headers_out, OSRF_HTTP_HEADER_THREAD, trans->thread);
322 if(trans->multipart) {
323 sprintf(contentTypeBuf, MULTIPART_CONTENT_TYPE, trans->delim);
324 contentTypeBuf[79] = '\0';
325 osrfLogDebug(OSRF_LOG_MARK, "content type %s : %s : %s", MULTIPART_CONTENT_TYPE, trans->delim, contentTypeBuf);
326 ap_set_content_type(trans->apreq, contentTypeBuf);
327 ap_rprintf(trans->apreq, "--%s\n", trans->delim);
329 ap_set_content_type(trans->apreq, JSON_CONTENT_TYPE);
334 * Cache the transaction with the JID of the backend process we are talking to
336 static void osrfHttpTranslatorCacheSession(osrfHttpTranslator* trans, const char* jid) {
337 jsonObject* cacheObj = jsonNewObject(NULL);
338 jsonObjectSetKey(cacheObj, "ip", jsonNewObject(trans->remoteHost));
339 jsonObjectSetKey(cacheObj, "jid", jsonNewObject(jid));
340 jsonObjectSetKey(cacheObj, "service", jsonNewObject(trans->service));
341 osrfCachePutObject((char*) trans->thread, cacheObj, CACHE_TIME);
346 * Writes a single chunk of multipart/x-mixed-replace content
348 static void osrfHttpTranslatorWriteChunk(osrfHttpTranslator* trans, transport_message* msg) {
349 osrfLogInternal(OSRF_LOG_MARK, "sending multipart chunk %s", msg->body);
350 ap_rprintf(trans->apreq,
351 "Content-type: %s\n\n%s\n\n", JSON_CONTENT_TYPE, msg->body);
352 //osrfLogInternal(OSRF_LOG_MARK, "Apache sending data: Content-type: %s\n\n%s\n\n", JSON_CONTENT_TYPE, msg->body);
353 if(trans->complete) {
354 ap_rprintf(trans->apreq, "--%s--\n", trans->delim);
355 //osrfLogInternal(OSRF_LOG_MARK, "Apache sending data: --%s--\n", trans->delim);
357 ap_rprintf(trans->apreq, "--%s\n", trans->delim);
358 //osrfLogInternal(OSRF_LOG_MARK, "Apache sending data: --%s\n", trans->delim);
360 ap_rflush(trans->apreq);
363 static int osrfHttpTranslatorProcess(osrfHttpTranslator* trans) {
364 if(trans->body == NULL)
365 return HTTP_BAD_REQUEST;
367 if(!osrfHttpTranslatorSetTo(trans))
368 return HTTP_BAD_REQUEST;
370 if(!osrfHttpTranslatorParseRequest(trans))
371 return HTTP_BAD_REQUEST;
373 while(client_recv(trans->handle, 0))
374 continue; // discard any old status messages in the recv queue
376 // send the message to the recipient
377 transport_message* tmsg = message_init(
378 trans->body, NULL, trans->thread, trans->recipient, NULL);
379 message_set_osrf_xid(tmsg, osrfLogGetXid());
380 client_send_message(trans->handle, tmsg);
383 if(trans->disconnectOnly) {
384 osrfLogDebug(OSRF_LOG_MARK, "exiting early on disconnect");
385 osrfCacheRemove(trans->thread);
389 // process the response from the opensrf service
391 while(!trans->complete) {
392 transport_message* msg = client_recv(trans->handle, trans->timeout);
394 if(trans->handle->error) {
395 osrfLogError(OSRF_LOG_MARK, "Transport error");
396 osrfCacheRemove(trans->thread);
397 return HTTP_INTERNAL_SERVER_ERROR;
401 return HTTP_GATEWAY_TIME_OUT;
404 osrfLogError(OSRF_LOG_MARK, "XMPP message resulted in error code %d", msg->error_code);
405 osrfCacheRemove(trans->thread);
406 return HTTP_NOT_FOUND;
409 if(!osrfHttpTranslatorCheckStatus(trans, msg))
413 osrfHttpTranslatorInitHeaders(trans, msg);
414 if(trans->connecting)
415 osrfHttpTranslatorCacheSession(trans, msg->sender);
419 if(trans->multipart) {
420 osrfHttpTranslatorWriteChunk(trans, msg);
421 if(trans->connectOnly)
425 trans->messages = osrfNewList();
426 osrfListPush(trans->messages, msg->body);
428 if(trans->complete || trans->connectOnly) {
429 growing_buffer* buf = buffer_init(128);
431 OSRF_BUFFER_ADD(buf, osrfListGetIndex(trans->messages, 0));
432 for(i = 1; i < trans->messages->size; i++) {
433 buffer_chomp(buf); // chomp off the closing array bracket
434 char* body = osrfListGetIndex(trans->messages, i);
435 char newbuf[strlen(body)];
436 sprintf(newbuf, body+1); // chomp off the opening array bracket
437 OSRF_BUFFER_ADD_CHAR(buf, ',');
438 OSRF_BUFFER_ADD(buf, newbuf);
441 ap_rputs(buf->buf, trans->apreq);
447 if(trans->disconnecting) // DISCONNECT within a multi-message batch
448 osrfCacheRemove(trans->thread);
453 static void testConnection(request_rec* r) {
454 if(!osrfConnected || !osrfSystemGetTransportClient()) {
455 osrfLogError(OSRF_LOG_MARK, "We're not connected to OpenSRF");
456 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "We're not connected to OpenSRF");
457 usleep(100000); // .1 second to prevent process die/start overload
463 static apr_status_t childExit(void* data) {
464 osrf_system_shutdown();
468 static void childInit(apr_pool_t *p, server_rec *s) {
469 if(!osrfSystemBootstrapClientResc(configFile, configCtx, "translator")) {
470 ap_log_error( APLOG_MARK, APLOG_ERR, 0, s,
471 "Unable to Bootstrap OpenSRF Client with config %s..", configFile);
475 routerName = osrfConfigGetValue(NULL, "/router_name");
476 domainName = osrfConfigGetValue(NULL, "/domain");
477 const char* servers[] = {cacheServers};
478 osrfCacheInit(servers, 1, 86400);
481 // at pool destroy time (= child exit time), cleanup
482 // XXX causes us to disconnect even for clone()'d process cleanup (as in mod_cgi)
483 //apr_pool_cleanup_register(p, NULL, childExit, apr_pool_cleanup_null);
486 static int handler(request_rec *r) {
488 if(strcmp(r->handler, MODULE_NAME)) return DECLINED;
489 if(r->header_only) return stat;
491 r->allowed |= (AP_METHOD_BIT << M_GET);
492 r->allowed |= (AP_METHOD_BIT << M_POST);
494 osrfLogSetAppname("osrf_http_translator");
498 osrfHttpTranslator* trans = osrfNewHttpTranslator(r);
500 stat = osrfHttpTranslatorProcess(trans);
501 //osrfHttpTranslatorDebug(trans);
502 osrfLogInfo(OSRF_LOG_MARK, "translator resulted in status %d", stat);
504 osrfLogWarning(OSRF_LOG_MARK, "no message body to process");
506 osrfHttpTranslatorFree(trans);
511 static void registerHooks (apr_pool_t *p) {
512 ap_hook_handler(handler, NULL, NULL, APR_HOOK_MIDDLE);
513 ap_hook_child_init(childInit, NULL, NULL, APR_HOOK_MIDDLE);
517 module AP_MODULE_DECLARE_DATA osrf_http_translator_module = {
518 STANDARD20_MODULE_STUFF,
523 osrfHttpTranslatorCmds,