root/src/stratcon_realtime_http.c

Revision 12ef579a4576c2d52bc65063b48858887e0669da, 16.6 kB (checked in by Theo Schlossnagle <jesus@omniti.com>, 4 years ago)

self identifying script tags, refs #229

  • Property mode set to 100644
Line 
1 /*
2  * Copyright (c) 2007, OmniTI Computer Consulting, Inc.
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions are
7  * met:
8  *
9  *     * Redistributions of source code must retain the above copyright
10  *       notice, this list of conditions and the following disclaimer.
11  *     * Redistributions in binary form must reproduce the above
12  *       copyright notice, this list of conditions and the following
13  *       disclaimer in the documentation and/or other materials provided
14  *       with the distribution.
15  *     * Neither the name OmniTI Computer Consulting, Inc. nor the names
16  *       of its contributors may be used to endorse or promote products
17  *       derived from this software without specific prior written
18  *       permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
23  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
24  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
25  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
26  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31  */
32
33 #include "noit_defines.h"
34 #include "eventer/eventer.h"
35 #include "noit_conf.h"
36 #include "utils/noit_hash.h"
37 #include "utils/noit_log.h"
38 #include "utils/noit_str.h"
39 #include "jlog/jlog.h"
40 #include "noit_jlog_listener.h"
41 #include "noit_listener.h"
42 #include "noit_http.h"
43 #include "noit_rest.h"
44 #include "noit_livestream_listener.h"
45 #include "stratcon_realtime_http.h"
46 #include "stratcon_jlog_streamer.h"
47 #include "stratcon_datastore.h"
48
49 #include <unistd.h>
50 #include <assert.h>
51 #include <errno.h>
52 #include <sys/types.h>
53 #include <sys/socket.h>
54 #ifdef HAVE_SYS_FILIO_H
55 #include <sys/filio.h>
56 #endif
57 #include <netinet/in.h>
58 #include <sys/un.h>
59 #include <arpa/inet.h>
60
61
62 typedef struct realtime_recv_ctx_t {
63   int bytes_expected;
64   int bytes_read;
65   int bytes_written;
66   int body_len;
67   char *buffer;         /* These guys are for doing partial reads */
68
69   enum {
70     REALTIME_HTTP_WANT_INITIATE = 0,
71     REALTIME_HTTP_WANT_SEND_INTERVAL = 1,
72     REALTIME_HTTP_WANT_SEND_UUID = 2,
73     REALTIME_HTTP_WANT_HEADER = 3,
74     REALTIME_HTTP_WANT_BODY = 4,
75   } state;
76   int count;            /* Number of jlog messages we need to read */
77   u_int32_t hack_inc_id;
78   noit_http_session_ctx *ctx;
79   struct realtime_tracker *rt;
80 } realtime_recv_ctx_t;
81
82 typedef struct realtime_context {
83   enum { RC_INITIAL = 0, RC_REQ_RECV, RC_INTERESTS_RESOLVED, RC_FEEDING } setup;
84   struct realtime_tracker *checklist;
85   char *document_domain;
86 } realtime_context;
87
88 static realtime_context *alloc_realtime_context(const char *domain) {
89   realtime_context *ctx;
90   ctx = calloc(sizeof(*ctx), 1);
91   ctx->document_domain = strdup(domain);
92   return ctx;
93 }
94 static void free_realtime_tracker(struct realtime_tracker *rt) {
95   if(rt->noit) free(rt->noit);
96   free(rt);
97 }
98 static void clear_realtime_context(realtime_context *rc) {
99  rc->setup = RC_INITIAL;
100   while(rc->checklist) {
101     struct realtime_tracker *tofree;
102     tofree = rc->checklist;
103     rc->checklist = tofree->next;
104     free_realtime_tracker(tofree);
105   }
106   if(rc->document_domain) free(rc->document_domain);
107   rc->document_domain = NULL;
108 }
109 int
110 stratcon_line_to_javascript(noit_http_session_ctx *ctx, char *buff,
111                             u_int32_t inc_id) {
112   char buffer[1024];
113   char *scp, *ecp, *token;
114   int len;
115   void *vcb;
116   const char *v, *cb = NULL;
117   noit_hash_table json = NOIT_HASH_EMPTY;
118   char s_inc_id[42];
119
120   snprintf(s_inc_id, sizeof(s_inc_id), "script-%08x", inc_id);
121   if(noit_hash_retrieve(&ctx->req.querystring, "cb", strlen("cb"), &vcb))
122     cb = vcb;
123   for(v = cb; v && *v; v++)
124     if(!((*v >= '0' && *v <= '9') ||
125          (*v >= 'a' && *v <= 'z') ||
126          (*v >= 'A' && *v <= 'Z') ||
127          (*v == '_') || (*v == '.'))) {
128       cb = NULL;
129       break;
130     }
131   if(!cb) cb = "window.parent.plot_iframe_data";
132
133 #define BAIL_HTTP_WRITE do { \
134   noit_hash_destroy(&json, NULL, free); \
135   noitL(noit_error, "javascript emit failed: %s:%s:%d\n", \
136         __FILE__, __FUNCTION__, __LINE__); \
137   return -1; \
138 } while(0)
139
140 #define PROCESS_NEXT_FIELD(t,l) do { \
141   if(!*scp) goto bad_row; \
142   ecp = strchr(scp, '\t'); \
143   if(!ecp) goto bad_row; \
144   t = scp; \
145   l = (ecp-scp); \
146   scp = ecp + 1; \
147 } while(0)
148 #define PROCESS_LAST_FIELD(t,l) do { \
149   if(!*scp) ecp = scp; \
150   else { \
151     ecp = scp + strlen(scp); /* Puts us at the '\0' */ \
152     if(*(ecp-1) == '\n') ecp--; /* We back up on letter if we ended in \n */ \
153   } \
154   t = scp; \
155   l = (ecp-scp); \
156 } while(0)
157
158   scp = buff;
159   PROCESS_NEXT_FIELD(token,len); /* Skip the leader */
160   if(buff[0] == 'M') {
161     noit_hash_iter iter = NOIT_HASH_ITER_ZERO;
162     const char *key;
163     int klen, i=0;
164     void *vval;
165
166 #define ra_write(a,b) if(noit_http_response_append(ctx, a, b) == noit_false) BAIL_HTTP_WRITE
167
168     snprintf(buffer, sizeof(buffer), "<script id=\"%s\">%s({", s_inc_id, cb);
169     ra_write(buffer, strlen(buffer));
170
171     while(noit_hash_next(&ctx->req.querystring, &iter, &key, &klen, &vval)) {
172       if(!strcmp(key, "cb")) continue;
173       noit_hash_store(&json, key, klen, strdup(vval ?(char *)vval : "true"));
174     }
175     /* Time */
176     noit_hash_store(&json, "script_id", 9, strdup(s_inc_id));
177     noit_hash_store(&json, "type", 4, strdup("M"));
178     PROCESS_NEXT_FIELD(token,len);
179     noit_hash_store(&json, "time", 4, noit__strndup(token, len));
180     /* UUID */
181     PROCESS_NEXT_FIELD(token,len);
182     noit_hash_store(&json, "id", 2, noit__strndup(token, len));
183     /* name */
184     PROCESS_NEXT_FIELD(token,len);
185     noit_hash_store(&json, "metric_name", 11, noit__strndup(token, len));
186     /* type */
187     PROCESS_NEXT_FIELD(token,len);
188     noit_hash_store(&json, "metric_type", 11, noit__strndup(token, len));
189     /* value */
190     PROCESS_LAST_FIELD(token,len); /* value */
191     noit_hash_store(&json, "value", 5, noit__strndup(token, len));
192
193     memset(&iter, 0, sizeof(iter));
194     while(noit_hash_next(&json, &iter, &key, &klen, &vval)) {
195       if(i++) ra_write(",", 1);
196       ra_write("'", 1);
197       ra_write(key, klen);
198       ra_write("':'", 3);
199       ra_write((char *)vval, strlen((char *)vval));
200       ra_write("'", 1);
201     }
202     snprintf(buffer, sizeof(buffer), "});</script>\n");
203     ra_write(buffer, strlen(buffer));
204
205     if(noit_http_response_flush(ctx, noit_false) == noit_false) BAIL_HTTP_WRITE;
206   }
207
208   noit_hash_destroy(&json, NULL, free);
209   return 0;
210
211  bad_row:
212   BAIL_HTTP_WRITE;
213 }
214 int
215 stratcon_realtime_uri_parse(realtime_context *rc, char *uri) {
216   int len, cnt = 0;
217   char *cp, *copy, *interest, *brk;
218   if(strncmp(uri, "/data/", 6)) return 0;
219   cp = uri + 6;
220   len = strlen(cp);
221   copy = alloca(len + 1);
222   if(!copy) return 0;
223   memcpy(copy, cp, len);
224   copy[len] = '\0';
225
226   for (interest = strtok_r(copy, "/", &brk);
227        interest;
228        interest = strtok_r(NULL, "/", &brk)) {
229     uuid_t in_uuid;
230     struct realtime_tracker *node;
231     char *interval;
232
233     interval = strchr(interest, '@');
234     if(!interval)
235       interval = "5000";
236     else
237       *interval++ = '\0';
238     if(uuid_parse(interest, in_uuid)) continue;
239     node = calloc(1, sizeof(*node));
240     node->rc = rc;
241     uuid_copy(node->checkid, in_uuid);
242     node->interval = atoi(interval);
243     node->next = rc->checklist;
244     rc->checklist = node;
245     cnt++;
246   }
247   return cnt;
248 }
249 static void
250 free_realtime_recv_ctx(void *vctx) {
251   realtime_recv_ctx_t *rrctx = vctx;
252   noit_atomic_dec32(&rrctx->ctx->ref_cnt);
253   free(rrctx);
254 }
255 #define Eread(a,b) e->opset->read(e->fd, (a), (b), &mask, e)
256 static int
257 __read_on_ctx(eventer_t e, realtime_recv_ctx_t *ctx, int *newmask) {
258   int len, mask;
259   while(ctx->bytes_read < ctx->bytes_expected) {
260     len = Eread(ctx->buffer + ctx->bytes_read,
261                 ctx->bytes_expected - ctx->bytes_read);
262     if(len < 0) {
263       *newmask = mask;
264       return -1;
265     }
266     /* if we get 0 inside SSL, and there was a real error, we
267      * will actually get a -1 here.
268      * if(len == 0) return ctx->bytes_read;
269      */
270     ctx->bytes_read += len;
271   }
272   assert(ctx->bytes_read == ctx->bytes_expected);
273   return ctx->bytes_read;
274 }
275 #define FULLREAD(e,ctx,size) do { \
276   int mask, len; \
277   if(!ctx->bytes_expected) { \
278     ctx->bytes_expected = size; \
279     if(ctx->buffer) free(ctx->buffer); \
280     ctx->buffer = malloc(size + 1); \
281     if(ctx->buffer == NULL) { \
282       noitL(noit_error, "malloc(%lu) failed.\n", (unsigned long)size + 1); \
283       goto socket_error; \
284     } \
285     ctx->buffer[size] = '\0'; \
286   } \
287   len = __read_on_ctx(e, ctx, &mask); \
288   if(len < 0) { \
289     if(errno == EAGAIN) return mask | EVENTER_EXCEPTION; \
290     noitL(noit_error, "SSL read error: %s\n", strerror(errno)); \
291     goto socket_error; \
292   } \
293   ctx->bytes_read = 0; \
294   ctx->bytes_expected = 0; \
295   if(len != size) { \
296     noitL(noit_error, "SSL short read [%d] (%d/%lu).  Reseting connection.\n", \
297           ctx->state, len, (unsigned long)size); \
298     goto socket_error; \
299   } \
300 } while(0)
301
302 int
303 stratcon_realtime_recv_handler(eventer_t e, int mask, void *closure,
304                                struct timeval *now) {
305   static u_int32_t livestream_cmd = 0;
306   noit_connection_ctx_t *nctx = closure;
307   realtime_recv_ctx_t *ctx = nctx->consumer_ctx;
308   int len;
309   u_int32_t nint;
310   char uuid_str[37];
311
312   if(!livestream_cmd) livestream_cmd = htonl(NOIT_LIVESTREAM_DATA_FEED);
313
314   if(mask & EVENTER_EXCEPTION || nctx->wants_shutdown) {
315  socket_error:
316     ctx->state = REALTIME_HTTP_WANT_INITIATE;
317     ctx->count = 0;
318     ctx->bytes_read = 0;
319     ctx->bytes_written = 0;
320     ctx->bytes_expected = 0;
321     if(ctx->buffer) free(ctx->buffer);
322     ctx->buffer = NULL;
323     noit_connection_ctx_dealloc(nctx);
324     eventer_remove_fd(e->fd);
325     e->opset->close(e->fd, &mask, e);
326     return 0;
327   }
328
329 #define full_nb_write(data, wlen) do { \
330   if(!ctx->bytes_expected) { \
331     ctx->bytes_written = 0; \
332     ctx->bytes_expected = wlen; \
333   } \
334   while(ctx->bytes_written < ctx->bytes_expected) { \
335     while(-1 == (len = e->opset->write(e->fd, ((char *)data) + ctx->bytes_written, \
336                                        ctx->bytes_expected - ctx->bytes_written, \
337                                        &mask, e)) && errno == EINTR); \
338     if(len < 0) { \
339       if(errno == EAGAIN) return mask | EVENTER_EXCEPTION; \
340       goto socket_error; \
341     } \
342     ctx->bytes_written += len; \
343   } \
344   if(ctx->bytes_written != ctx->bytes_expected) { \
345     noitL(noit_error, "short write on initiating stream [%d != %d].\n", \
346           ctx->bytes_written, ctx->bytes_expected); \
347     goto socket_error; \
348   } \
349   ctx->bytes_expected = 0; \
350 } while(0)
351
352   while(1) {
353     u_int32_t net_body_len;
354
355     switch(ctx->state) {
356       case REALTIME_HTTP_WANT_INITIATE:
357         full_nb_write(&livestream_cmd, sizeof(livestream_cmd));
358         ctx->state = REALTIME_HTTP_WANT_SEND_INTERVAL;
359       case REALTIME_HTTP_WANT_SEND_INTERVAL:
360         nint = htonl(ctx->rt->interval);
361         full_nb_write(&nint, sizeof(nint));
362         ctx->state = REALTIME_HTTP_WANT_SEND_UUID;
363       case REALTIME_HTTP_WANT_SEND_UUID:
364         uuid_unparse_lower(ctx->rt->checkid, uuid_str);
365         full_nb_write(uuid_str, 36);
366         ctx->state = REALTIME_HTTP_WANT_HEADER;
367       case REALTIME_HTTP_WANT_HEADER:
368         FULLREAD(e, ctx, sizeof(u_int32_t));
369         memcpy(&net_body_len, ctx->buffer, sizeof(u_int32_t));
370         ctx->body_len = ntohl(net_body_len);
371         free(ctx->buffer); ctx->buffer = NULL;
372         ctx->state = REALTIME_HTTP_WANT_BODY;
373         break;
374       case REALTIME_HTTP_WANT_BODY:
375         FULLREAD(e, ctx, ctx->body_len);
376         if(stratcon_line_to_javascript(ctx->ctx, ctx->buffer, ctx->hack_inc_id++)) goto socket_error;
377         free(ctx->buffer); ctx->buffer = NULL;
378         ctx->state = REALTIME_HTTP_WANT_HEADER;
379         break;
380     }
381   }
382
383 }
384
385 int
386 stratcon_realtime_http_postresolve(eventer_t e, int mask, void *closure,
387                                    struct timeval *now) {
388   noit_http_session_ctx *ctx = closure;
389   realtime_context *rc = ctx->dispatcher_closure;
390   struct realtime_tracker *node;
391
392   for(node = rc->checklist; node; node = node->next) {
393     if(node->noit) {
394       realtime_recv_ctx_t *rrctx;
395       rrctx = calloc(1, sizeof(*rrctx));
396       rrctx->ctx = ctx;
397       rrctx->rt = node;
398       stratcon_streamer_connection(NULL, node->noit,
399                                    stratcon_realtime_recv_handler,
400                                    NULL, rrctx,
401                                    free_realtime_recv_ctx);
402     }
403     else
404       noit_atomic_dec32(&ctx->ref_cnt);
405   }
406   if(ctx->ref_cnt == 1) {
407     noit_http_response_end(ctx);
408     clear_realtime_context(rc);
409     if(ctx->conn.e) eventer_trigger(ctx->conn.e, EVENTER_WRITE);
410   }
411   return 0;
412 }
413 int
414 stratcon_request_dispatcher(noit_http_session_ctx *ctx) {
415   const char *key, *value;
416   realtime_context *rc = ctx->dispatcher_closure;
417   int klen;
418   noit_hash_iter iter = NOIT_HASH_ITER_ZERO;
419   noit_http_request *req = &ctx->req;
420
421   if(rc->setup == RC_INITIAL) {
422     eventer_t completion;
423     struct realtime_tracker *node;
424     char c[1024];
425     int num_interests;
426
427     num_interests = stratcon_realtime_uri_parse(rc, ctx->req.uri_str);
428     if(num_interests == 0) {
429       noit_http_response_status_set(ctx, 404, "OK");
430       noit_http_response_option_set(ctx, NOIT_HTTP_CLOSE);
431       noit_http_response_end(ctx);
432       return 0;
433     }
434
435     noitL(noit_error, "http: %s %s %s\n",
436           req->method_str, req->uri_str, req->protocol_str);
437     while(noit_hash_next_str(&req->headers, &iter, &key, &klen, &value)) {
438       noitL(noit_error, "http: [%s: %s]\n", key, value);
439     }
440     noit_http_response_status_set(ctx, 200, "OK");
441     noit_http_response_option_set(ctx, NOIT_HTTP_CHUNKED);
442     /*noit_http_response_option_set(ctx, NOIT_HTTP_GZIP);*/
443     /*noit_http_response_option_set(ctx, NOIT_HTTP_DEFLATE);*/
444     noit_http_response_header_set(ctx, "Content-Type", "text/html");
445
446     snprintf(c, sizeof(c),
447              "<html><head><script>document.domain='%s';</script></head><body>\n",
448              rc->document_domain);
449     noit_http_response_append(ctx, c, strlen(c));
450
451     /* this dumb crap is to make some browsers happy (Safari) */
452     memset(c, ' ', sizeof(c));
453     noit_http_response_append(ctx, c, sizeof(c));
454     noit_http_response_flush(ctx, noit_false);
455
456     rc->setup = RC_REQ_RECV;
457     /* Each interest references the ctx */
458     for(node = rc->checklist; node; node = node->next) {
459       char uuid_str[UUID_STR_LEN+1];
460       noit_atomic_inc32(&ctx->ref_cnt);
461       uuid_unparse_lower(node->checkid, uuid_str);
462       noitL(noit_error, "Resolving uuid: %s\n", uuid_str);
463     }
464     completion = eventer_alloc();
465     completion->mask = EVENTER_TIMER;
466     completion->callback = stratcon_realtime_http_postresolve;
467     completion->closure = ctx;
468     gettimeofday(&completion->whence, NULL);
469     stratcon_datastore_push(DS_OP_FIND_COMPLETE, NULL, NULL,
470                             rc->checklist, completion);
471   }
472   return EVENTER_EXCEPTION;
473 }
474 int
475 stratcon_realtime_http_handler(eventer_t e, int mask, void *closure,
476                                struct timeval *now) {
477   acceptor_closure_t *ac = closure;
478   noit_http_session_ctx *http_ctx = ac->service_ctx;
479   return http_ctx->drive(e, mask, http_ctx, now);
480 }
481 static int
482 rest_stream_data(noit_http_rest_closure_t *restc,
483                  int npats, char **pats) {
484   /* We're here and want to subvert the rest system */
485   const char *document_domain = NULL;
486   noit_http_session_ctx *ctx = restc->http_ctx;
487
488   /* Rewire the handler */
489   restc->ac->service_ctx = ctx;
490
491   if(!noit_hash_retr_str(restc->ac->config,
492                          "document_domain", strlen("document_domain"),
493                          &document_domain)) {
494     noitL(noit_error, "Document domain not set!  Realtime streaming will be broken\n");
495     document_domain = "";
496   }
497   noit_http_rest_closure_free(restc);
498
499   noit_http_process_querystring(&ctx->req);
500   /* Rewire the http context */
501   ctx->conn.e->callback = stratcon_realtime_http_handler;
502   ctx->dispatcher = stratcon_request_dispatcher;
503   ctx->dispatcher_closure = alloc_realtime_context(document_domain);
504   //ctx->drive = stratcon_realtime_http_handler;
505   return stratcon_request_dispatcher(ctx);
506 }
507
508 void
509 stratcon_realtime_http_init(const char *toplevel) {
510   eventer_name_callback("stratcon_realtime_http",
511                         stratcon_realtime_http_handler);
512   assert(noit_http_rest_register(
513     "GET", "/data/",
514            "^((?:" UUID_REGEX "(?:@\\d+)?)(?:/" UUID_REGEX "(?:@\\d+)?)*)$",
515     rest_stream_data
516   ) == 0);
517 }
Note: See TracBrowser for help on using the browser.