]> git.evergreen-ils.org Git - OpenSRF.git/blob - src/gateway/osrf_http_translator.c
fixed broken call to sizeof(). replaced ap_rvputs with more appropriate ap_rprintf...
[OpenSRF.git] / src / gateway / osrf_http_translator.c
1 #include <sys/time.h>
2 #include <sys/resource.h>
3 #include <unistd.h>
4 #include <strings.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>
11
12 #define MODULE_NAME "osrf_http_translator_module"
13 #define TRANSLATOR_CONFIG_FILE "OSRFTranslatorConfig"
14 #define TRANSLATOR_CONFIG_CTX "OSRFTranslatorConfigContext"
15 #define TRANSLATOR_CACHE_SERVER "OSRFTranslatorCacheServer"
16 #define DEFAULT_TRANSLATOR_CONFIG_CTX "gateway"
17 #define DEFAULT_TRANSLATOR_CONFIG_FILE "/openils/conf/opensrf_core.xml"
18 #define DEFAULT_TRANSLATOR_TIMEOUT 1200
19
20 #define MULTIPART_CONTENT_TYPE "multipart/x-mixed-replace;boundary=\"%s\""
21 #define JSON_CONTENT_TYPE "text/plain"
22 #define CACHE_TIME 300
23
24 #define OSRF_HTTP_HEADER_TO "X-OpenSRF-to"
25 #define OSRF_HTTP_HEADER_XID "X-OpenSRF-xid"
26 #define OSRF_HTTP_HEADER_FROM "X-OpenSRF-from"
27 #define OSRF_HTTP_HEADER_THREAD "X-OpenSRF-thread"
28 #define OSRF_HTTP_HEADER_TIMEOUT "X-OpenSRF-timeout"
29 #define OSRF_HTTP_HEADER_SERVICE "X-OpenSRF-service"
30 #define OSRF_HTTP_HEADER_MULTIPART "X-OpenSRF-multipart"
31 #define MAX_MSGS_PER_PACKET 256
32
33 char* configFile = DEFAULT_TRANSLATOR_CONFIG_FILE;
34 char* configCtx = DEFAULT_TRANSLATOR_CONFIG_CTX;
35 char* routerName = NULL;
36 char* domainName = NULL;
37 int osrfConnected = 0;
38 char recipientBuf[128];
39
40 // for development only, writes to apache error log
41 static void _dbg(char* s, ...) {
42     VA_LIST_TO_STRING(s);
43     fprintf(stderr, "%s\n", VA_BUF);
44     fflush(stderr);
45 }
46
47 // Translator struct
48 typedef struct {
49     request_rec* apreq;
50     transport_client* handle;
51     osrfList* messages;
52     char* body;
53     char* delim;
54     const char* recipient;
55     const char* service;
56     const char* thread;
57     const char* remoteHost;
58     int complete;
59     int timeout;
60     int multipart;
61     int connectOnly;
62     int disconnectOnly;
63     int localXid;
64 } osrfHttpTranslator;
65
66 /*
67  * Constructs a new translator object based on the current apache 
68  * request_rec.  Reads the request body and headers.
69  */
70 static osrfHttpTranslator* osrfNewHttpTranslator(request_rec* apreq) {
71     osrfHttpTranslator* trans;
72     OSRF_MALLOC(trans, sizeof(osrfHttpTranslator));
73     trans->apreq = apreq;
74     trans->complete = 0;
75     trans->connectOnly = 0;
76     trans->disconnectOnly = 0;
77     trans->remoteHost = apreq->connection->remote_ip;
78     trans->messages = NULL;
79
80     /* load the message body */
81         osrfStringArray* params = apacheParseParms(apreq);
82     trans->body = apacheGetFirstParamValue(params, "osrf-msg");
83     osrfStringArrayFree(params);
84
85     /* load the request headers */
86     if (apr_table_get(apreq->headers_in, OSRF_HTTP_HEADER_XID) ) {
87         trans->localXid = 0;
88     } else {
89         trans->localXid = 1;
90     }
91
92     trans->handle = osrfSystemGetTransportClient();
93     trans->recipient = apr_table_get(apreq->headers_in, OSRF_HTTP_HEADER_TO);
94     trans->service = apr_table_get(apreq->headers_in, OSRF_HTTP_HEADER_SERVICE);
95     trans->thread = apr_table_get(apreq->headers_in, OSRF_HTTP_HEADER_THREAD); /* XXX create thread if necessary */
96
97     const char* timeout = apr_table_get(apreq->headers_in, OSRF_HTTP_HEADER_TIMEOUT);
98     if(timeout) 
99         trans->timeout = atoi(timeout);
100     else 
101         trans->timeout = DEFAULT_TRANSLATOR_TIMEOUT;
102
103     const char* multipart = apr_table_get(apreq->headers_in, OSRF_HTTP_HEADER_MULTIPART);
104     if(multipart && !strcasecmp(multipart, "true"))
105         trans->multipart = 1;
106     else
107         trans->multipart = 0;
108
109     char buf[32];
110     snprintf(buf, sizeof(buf), "%d%ld", getpid(), time(NULL));
111     trans->delim = md5sum(buf);
112
113     return trans;
114 }
115
116 static void osrfHttpTranslatorFree(osrfHttpTranslator* trans) {
117     if(!trans) return;
118     if(trans->body)
119         free(trans->body);
120     if(trans->delim)
121         free(trans->delim);
122     osrfListFree(trans->messages);
123     free(trans);
124 }
125
126 static void osrfHttpTranslatorDebug(osrfHttpTranslator* trans) {
127     _dbg("-----------------------------------");
128     _dbg("body = %s", trans->body);
129     _dbg("service = %s", trans->service);
130     _dbg("thread = %s", trans->thread);
131     _dbg("multipart = %d", trans->multipart);
132     _dbg("recipient = %s", trans->recipient);
133 }
134
135 /**
136  * Determines the correct recipient address based on the requested 
137  * service or recipient address.  
138  */
139 static int osrfHttpTranslatorSetTo(osrfHttpTranslator* trans) {
140     int stat = 0;
141     jsonObject* sessionCache = NULL;
142
143     if(trans->service) {
144         if(trans->recipient) {
145             osrfLogError(OSRF_LOG_MARK, "Specifying both SERVICE and TO are not allowed");
146
147         } else {
148             // service is specified, build a recipient address 
149             // from the router, domain, and service
150             int size = snprintf(recipientBuf, 128, "%s@%s/%s", routerName, domainName, trans->service);
151             recipientBuf[size] = '\0';
152             osrfLogDebug(OSRF_LOG_MARK, "Set recipient to %s", recipientBuf);
153             trans->recipient = recipientBuf;
154             stat = 1;
155         }
156
157     } else {
158
159         if(trans->recipient) {
160             sessionCache = osrfCacheGetObject(trans->thread);
161
162             if(sessionCache) {
163                 char* ipAddr = jsonObjectGetString(jsonObjectGetKey(sessionCache, "ip"));
164                 char* recipient = jsonObjectGetString(jsonObjectGetKey(sessionCache, "jid"));
165
166                 // choosing a specific recipient address requires that the recipient and 
167                 // thread be cached on the server (so drone processes cannot be hijacked)
168                 if(!strcmp(ipAddr, trans->remoteHost) && !strcmp(recipient, trans->recipient)) {
169                     osrfLogDebug(OSRF_LOG_MARK, "Found cached session from host %s and recipient %s", 
170                         trans->remoteHost, trans->recipient);
171                     stat = 1;
172                     trans->service = jsonObjectGetString(jsonObjectGetKey(sessionCache, "service"));
173
174                 } else {
175                     osrfLogError(OSRF_LOG_MARK, 
176                         "Session cache for thread %s does not match request", trans->thread);
177                 }
178             }  else {
179                 osrfLogError(OSRF_LOG_MARK, 
180                     "attempt to send directly to %s without a session", trans->recipient);
181             }
182         } else {
183             osrfLogError(OSRF_LOG_MARK, "No SERVICE or RECIPIENT defined");
184         } 
185     }
186
187     jsonObjectFree(sessionCache);
188     return stat;
189 }
190
191 /**
192  * Parses the request body and logs any REQUEST messages to the activity log
193  */
194 static int osrfHttpTranslatorParseRequest(osrfHttpTranslator* trans) {
195     osrfMessage* msg;
196     osrfMessage* msgList[MAX_MSGS_PER_PACKET];
197     int numMsgs = osrf_message_deserialize(trans->body, msgList, MAX_MSGS_PER_PACKET);
198     osrfLogDebug(OSRF_LOG_MARK, "parsed %d opensrf messages in this packet", numMsgs);
199
200     if(numMsgs == 0)
201         return 0;
202
203     if(numMsgs == 1) {
204         msg = msgList[0];
205         if(msg->m_type == CONNECT) {
206             trans->connectOnly = 1;
207             return 1;
208         }
209         if(msg->m_type == DISCONNECT) {
210             trans->disconnectOnly = 1;
211             return 1;
212         }
213     }
214
215     // log request messages to the activity log
216     int i;
217     for(i = 0; i < numMsgs; i++) {
218         msg = msgList[i];
219         if(msg->m_type == REQUEST) {
220
221             jsonObject* params = msg->_params;
222             growing_buffer* act = buffer_init(128);     
223             buffer_fadd(act, "[%s] [%s] %s %s", trans->remoteHost, "", trans->service, msg->method_name);
224
225             char* str; 
226             int i = 0;
227             while((str = jsonObjectGetString(jsonObjectGetIndex(params, i++)))) {
228                 if( i == 1 )
229                     OSRF_BUFFER_ADD(act, " ");
230                 else 
231                     OSRF_BUFFER_ADD(act, ", ");
232                 OSRF_BUFFER_ADD(act, str);
233             }
234             osrfLogActivity(OSRF_LOG_MARK, act->buf);
235             buffer_free(act);
236         }
237     }
238
239     return 1;
240 }
241
242 static int osrfHttpTranslatorCheckStatus(osrfHttpTranslator* trans, transport_message* msg) {
243     osrfMessage* omsgList[MAX_MSGS_PER_PACKET];
244     int numMsgs = osrf_message_deserialize(msg->body, omsgList, MAX_MSGS_PER_PACKET);
245     osrfLogDebug(OSRF_LOG_MARK, "parsed %d response messages", numMsgs);
246     if(numMsgs == 0) return 0;
247
248     osrfMessage* last = omsgList[numMsgs-1];
249     if(last->m_type == STATUS) {
250         if(last->status_code == OSRF_STATUS_TIMEOUT) {
251             osrfLogDebug(OSRF_LOG_MARK, "removing cached session on request timeout");
252             osrfCacheRemove(trans->thread);
253             return 0;
254         }
255         // XXX hm, check for explicit status=COMPLETE message instead??
256         if(last->status_code != OSRF_STATUS_CONTINUE)
257             trans->complete = 1;
258     }
259
260     return 1;
261 }
262
263 static void osrfHttpTranslatorInitHeaders(osrfHttpTranslator* trans, transport_message* msg) {
264     apr_table_set(trans->apreq->headers_out, OSRF_HTTP_HEADER_FROM, msg->sender);
265     apr_table_set(trans->apreq->headers_out, OSRF_HTTP_HEADER_THREAD, trans->thread);
266     if(trans->multipart) {
267         char buf[strlen(MULTIPART_CONTENT_TYPE) + strlen(trans->delim) + 1];
268         sprintf(buf, MULTIPART_CONTENT_TYPE, trans->delim);
269             ap_set_content_type(trans->apreq, buf);
270         ap_rprintf(trans->apreq, "--%s\n", trans->delim);
271     } else {
272             ap_set_content_type(trans->apreq, JSON_CONTENT_TYPE);
273     }
274 }
275
276 static void osrfHttpTranslatorCacheSession(osrfHttpTranslator* trans) {
277     jsonObject* cacheObj = jsonNewObject(NULL);
278     jsonObjectSetKey(cacheObj, "ip", jsonNewObject(trans->remoteHost));
279     jsonObjectSetKey(cacheObj, "jid", jsonNewObject(trans->recipient));
280     jsonObjectSetKey(cacheObj, "service", jsonNewObject(trans->service));
281     osrfCachePutObject((char*) trans->thread, cacheObj, CACHE_TIME);
282 }
283
284            
285 /**
286  * Writes a single chunk of multipart/x-mixed-replace content
287  */
288 static void osrfHttpTranslatorWriteChunk(osrfHttpTranslator* trans, transport_message* msg) {
289     ap_rprintf(trans->apreq, 
290         "Content-type: %s\n\n%s\n\n", JSON_CONTENT_TYPE, msg->body);
291     if(trans->complete)
292         ap_rprintf(trans->apreq, "--%s--\n", trans->delim);
293     else
294         ap_rprintf(trans->apreq, "--%s\n", trans->delim);
295     ap_rflush(trans->apreq);
296 }
297
298 static int osrfHttpTranslatorProcess(osrfHttpTranslator* trans) {
299     if(trans->body == NULL)
300         return HTTP_BAD_REQUEST;
301
302     if(!osrfHttpTranslatorSetTo(trans))
303         return HTTP_BAD_REQUEST;
304
305     if(!osrfHttpTranslatorParseRequest(trans))
306         return HTTP_BAD_REQUEST;
307
308     while(client_recv(trans->handle, 0))
309         continue; // discard any old status messages in the recv queue
310
311     // send the message to the recipient
312     transport_message* tmsg = message_init(
313         trans->body, NULL, trans->thread, trans->recipient, NULL);
314     client_send_message(trans->handle, tmsg);
315     message_free(tmsg); 
316
317     if(trans->disconnectOnly) {
318         osrfLogDebug(OSRF_LOG_MARK, "exiting early on disconnect");
319         return OK;
320     }
321
322     // process the response from the opensrf service
323     int firstWrite = 1;
324     while(!trans->complete) {
325         transport_message* msg = client_recv(trans->handle, trans->timeout);
326
327         if(trans->handle->error) {
328             osrfLogError(OSRF_LOG_MARK, "Transport error");
329             return HTTP_NOT_FOUND;
330         }
331
332         if(msg == NULL)
333             return HTTP_GATEWAY_TIME_OUT;
334
335         if(msg->is_error) {
336             osrfLogError(OSRF_LOG_MARK, "XMPP message resulted in error code %d", msg->error_code);
337             return HTTP_NOT_FOUND;
338         }
339
340         if(!osrfHttpTranslatorCheckStatus(trans, msg))
341             continue;
342
343         if(firstWrite) {
344             osrfHttpTranslatorInitHeaders(trans, msg);
345             osrfHttpTranslatorCacheSession(trans);
346             firstWrite = 0;
347         }
348
349         if(trans->multipart) {
350             osrfHttpTranslatorWriteChunk(trans, msg);
351             if(trans->connectOnly)
352                 break;
353         } else {
354             if(!trans->messages)
355                 trans->messages = osrfNewList();
356             osrfListPush(trans->messages, msg->body);
357
358             if(trans->complete || trans->connectOnly) {
359                 growing_buffer* buf = buffer_init(128);
360                 int i;
361                 OSRF_BUFFER_ADD(buf, osrfListGetIndex(trans->messages, 0));
362                 for(i = 1; i < trans->messages->size; i++) {
363                     // yay! string mangling
364                 }
365             }
366         }
367     }
368
369     return OK;
370 }
371
372 static void testConnection(request_rec* r) {
373         if(!osrfConnected || !osrfSystemGetTransportClient()) {
374         osrfLogError(OSRF_LOG_MARK, "We're not connected to OpenSRF");
375                 ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "We're not connected to OpenSRF");
376                 usleep(100000); // .1 second to prevent process die/start overload
377                 exit(1);
378         }
379 }
380
381 // it's dead, Jim
382 static apr_status_t childExit(void* data) {
383     osrf_system_shutdown();
384     return OK;
385 }
386
387 static void childInit(apr_pool_t *p, server_rec *s) {
388         if(!osrfSystemBootstrapClientResc(configFile, configCtx, "translator")) {
389                 ap_log_error( APLOG_MARK, APLOG_ERR, 0, s, 
390                         "Unable to Bootstrap OpenSRF Client with config %s..", configFile);
391                 return;
392         }
393
394     routerName = osrfConfigGetValue(NULL, "/router_name");
395     domainName = osrfConfigGetValue(NULL, "/domain");
396     // ---------------------
397     // XXX initialize the cache from the Apache settings
398     const char* servers[] = {"127.0.0.1:11211"};
399     osrfCacheInit(servers, 1, 86400);
400     // ---------------------
401         osrfConnected = 1;
402
403     // at pool destroy time (= child exit time), cleanup
404     apr_pool_cleanup_register(p, NULL, childExit, NULL);
405 }
406
407 static int handler(request_rec *r) {
408     int stat = OK;
409         if(strcmp(r->handler, MODULE_NAME)) return DECLINED;
410     if(r->header_only) return stat;
411
412         r->allowed |= (AP_METHOD_BIT << M_GET);
413         r->allowed |= (AP_METHOD_BIT << M_POST);
414
415         osrfLogSetAppname("osrf_http_translator");
416     testConnection(r);
417
418     osrfHttpTranslator* trans = osrfNewHttpTranslator(r);
419     if(trans->body) {
420         stat = osrfHttpTranslatorProcess(trans);
421         osrfHttpTranslatorDebug(trans);
422         osrfLogInfo(OSRF_LOG_MARK, "translator resulted in status %d", stat);
423     } else {
424         osrfLogWarning(OSRF_LOG_MARK, "no message body to process");
425     }
426     osrfHttpTranslatorFree(trans);
427         return stat;
428 }
429
430
431 static void registerHooks (apr_pool_t *p) {
432         ap_hook_handler(handler, NULL, NULL, APR_HOOK_MIDDLE);
433         ap_hook_child_init(childInit, NULL, NULL, APR_HOOK_MIDDLE);
434 }
435
436
437 module AP_MODULE_DECLARE_DATA osrf_http_translator_module = {
438         STANDARD20_MODULE_STUFF,
439     NULL,
440         NULL,
441     NULL,
442         NULL,
443     NULL,
444         registerHooks,
445 };
446
447
448
449