Debian Codegraph @

terps/tads/tads3/vmnet.cpp

raw symbols SCIP
1 /* Copyright (c) 2010 by Michael J. Roberts. All Rights Reserved. */
2 /*
3 Name
4 vmnet.cpp - TADS 3 networking
5 Function
6 Implements the networking layer for TADS 3. This is used for the web
7 server configurations. This is portable code implementing high-level
8 network operations, such as an HTTP server, using the low-level socket and
9 thread API defined in osifcnet.h.
10 Notes
11
12 Modified
13 04/11/10 MJRoberts - Creation
14 */
15
16
17 #include <stdlib.h>
18 #include <string.h>
19
20 #include "t3std.h"
21 #include "os.h"
22 #include "osifcnet.h"
23 #include "vmnet.h"
24 #include "vmglob.h"
25 #include "vmtype.h"
26 #include "vmobj.h"
27 #include "vmstr.h"
28 #include "vmlst.h"
29 #include "vmisaac.h"
30 #include "sha2.h"
31 #include "vmpredef.h"
32 #include "vmhttpreq.h"
33 #include "vmglob.h"
34 #include "vmmain.h"
35 #include "vmpredef.h"
36 #include "vmerrnum.h"
37 #include "vmrun.h"
38 #include "vmfile.h"
39
40
41 /* ------------------------------------------------------------------------ */
42 /*
43 * Server manager
44 */
45 TadsServerManager::TadsServerManager()
46 {
47 /* initialize our ISAAC context */
48 ic = new isaacctx();
49 isaac_init(ic, TRUE);
50
51 /* create our mutex */
52 mutex = new OS_Mutex();
53 }
54
55 TadsServerManager::~TadsServerManager()
56 {
57 /* done with our ISAAC context */
58 delete ic;
59
60 /* done with our mutex */
61 mutex->release_ref();
62 }
63
64 /*
65 * generate a random number
66 */
67 ulong TadsServerManager::rand()
68 {
69 /* ISAAC needs protection against multi-threaded access */
70 mutex->lock();
71
72 /* get a random number */
73 ulong r = isaac_rand(ic);
74
75 /* done with the mutex */
76 mutex->unlock();
77
78 /* return the number */
79 return r;
80 }
81
82 /*
83 * Generate a random ID string
84 */
85 static inline char nybble2hex(unsigned char c)
86 {
87 c &= 0x0f;
88 return (c < 10 ? c + '0' : c - 10 + 'a');
89 }
90 char *TadsServerManager::gen_rand_id(void *obj)
91 {
92 /* set up a hashing buffer */
93 sha256_ctx s;
94 sha256_begin(&s);
95
96 /* add the current date/time to the hash */
97 os_time_t timer = os_time(0);
98 struct tm *tblock = os_localtime(&timer);
99 sha256_hash((unsigned char *)tblock, sizeof(*tblock), &s);
100
101 /* add the system timer to the hash */
102 long systime = os_get_sys_clock_ms();
103 sha256_hash((unsigned char *)&systime, sizeof(systime), &s);
104
105 /* add the object address to the hash */
106 sha256_hash((unsigned char *)obj, sizeof(obj), &s);
107
108 /* add the current stack location to the hash */
109 sha256_hash((unsigned char *)&obj, sizeof(void *), &s);
110
111 /* add some random bytes from the operating system */
112 unsigned char rbuf[128];
113 os_gen_rand_bytes(rbuf, sizeof(rbuf));
114 sha256_hash(rbuf, sizeof(rbuf), &s);
115
116 /* compute the hash */
117 unsigned char hval[32];
118 sha256_end(hval, &s);
119
120 /* convert it to hex, but just keep the low nybbles, for 32 digits */
121 char *ret = lib_alloc_str(32);
122 int i;
123 for (i = 0 ; i < 32 ; ++i)
124 ret[i] = nybble2hex(hval[i]);
125
126 /* null-terminate the string */
127 ret[i] = '\0';
128
129 /* return the allocated string */
130 return ret;
131 }
132
133
134 /* ------------------------------------------------------------------------ */
135 /*
136 * Message queue
137 */
138
139 /*
140 * wait for a message
141 */
142 int TadsMessageQueue::wait(VMG_ unsigned long timeout, TadsMessage **msgp)
143 {
144 /* assume we won't return a message */
145 *msgp = 0;
146
147 /*
148 * Wait for a message to arrive in the queue. The sender will signal
149 * our event upon posting a message. Note that our assumption that
150 * there's only one reader thread per queue means that we don't have to
151 * worry about another reader swiping the signaled message between the
152 * time the signal went off and the time we read the queue.
153 *
154 * Also stop waiting if the quit event has been signaled, or the debug
155 * event is signaled.
156 */
157 OS_Waitable *w[3];
158 int cnt = 0;
159 w[cnt++] = ev;
160
161 /* add the quit event, if present */
162 if (quit_evt != 0)
163 w[cnt++] = quit_evt;
164
165 /* add the debug break event, if present */
166 OS_Event *brkevt = 0;
167 VM_IF_DEBUGGER(if (G_debugger != 0)
168 w[cnt++] = brkevt = G_debugger->get_break_event());
169
170 /* wait for an event */
171 int ret = OS_Waitable::multi_wait(cnt, w, timeout);
172
173 /* if the message event fired, retrieve the message */
174 if (ret == OSWAIT_EVENT + 0)
175 *msgp = get();
176
177 /*
178 * always return +2 for the debug event (we'll have +1 from the
179 * multi_wait if the list doesn't have a quit event)
180 */
181 if (w[ret - OSWAIT_EVENT] == brkevt)
182 ret = OSWAIT_EVENT + 2;
183
184 /* release the debugger break event, if we got it */
185 if (brkevt != 0)
186 brkevt->release_ref();
187
188 /* return the result */
189 return ret;
190 }
191
192
193 /* ------------------------------------------------------------------------ */
194 /*
195 * Custom string object. This is a convenience class for complex string
196 * construction, which the network servers do a lot of.
197 */
198 struct NetString
199 {
200 NetString(size_t initsize) { init(initsize); }
201 NetString() { init(50); }
202
203 void init(size_t initsize)
204 {
205 buf = (char *)t3malloc(initsize);
206 buf[0] = '\0';
207 len = initsize;
208 inc = (initsize > 128 ? initsize / 2 : 128);
209 wrtidx = 0;
210 }
211
212 ~NetString()
213 {
214 if (buf != 0)
215 t3free(buf);
216 }
217
218 /* clear the buffer */
219 void clear()
220 {
221 buf[0] = '\0';
222 wrtidx = 0;
223 }
224
225 /* the buffer, its total size, and the size increment */
226 char *buf;
227 size_t len;
228 size_t inc;
229
230 /* the current buffer index */
231 size_t wrtidx;
232
233 /* reserve space for an addition 'b' bytes */
234 void reserve(size_t b)
235 {
236 if (wrtidx + b + 1 > len)
237 {
238 /* increase by the increment until big enough */
239 while (wrtidx + b + 1 > len)
240 len += inc;
241
242 /* reallocate at the increased size */
243 buf = (char *)t3realloc(buf, len);
244 }
245 }
246
247 /* append text */
248 void append(const char *txt, size_t txtlen)
249 {
250 /* make sure there's room */
251 reserve(txtlen);
252
253 /* copy the text */
254 memcpy(buf + wrtidx, txt, txtlen);
255
256 /* adjust the counters */
257 wrtidx += txtlen;
258
259 /*
260 * null terminate (but don't count it - we can overwrite it with a
261 * subsequent append)
262 */
263 buf[wrtidx] = '\0';
264 }
265
266 void append(const char *txt)
267 {
268 append(txt, strlen(txt));
269 }
270
271 /* append text to a buffer, with sprintf-style formatting */
272 void vappendf(const char *fmt, va_list argp)
273 {
274 /* calculate the amount of space we need */
275 int plen = t3vsprintf(0, 0, fmt, argp);
276
277 /* if that worked, format the data */
278 if (plen >= 0)
279 {
280 /* reserve the required space */
281 reserve(plen);
282
283 /* format the text */
284 int plen = t3vsprintf(buf + wrtidx, len - wrtidx, fmt, argp);
285
286 /* if that worked, advance the buffer pointers */
287 if (plen >= 0)
288 wrtidx += plen;
289
290 /* null-terminate at the new length in any case */
291 buf[wrtidx] = '\0';
292 }
293 }
294
295 void appendf(const char *fmt, ...)
296 {
297 va_list argp;
298
299 /* process through our va_list version */
300 va_start(argp, fmt);
301 vappendf(fmt, argp);
302 va_end(argp);
303 }
304
305 /*
306 * append text, converting plain text to valid XML by turning markup
307 * characters into entities
308 */
309 void append_xml(const char *txt)
310 {
311 const char *p, *start;
312
313 /* append in chunks as we find special characters */
314 for (p = start = txt ; *p != '\0' ; ++p)
315 {
316 static const char *xlat[] =
317 {
318 "&lt;",
319 "&gt;",
320 "&amp;"
321 };
322 static const char *specials = "<>&";
323 const char *psp = strchr(specials, *p);
324 int sp_index = (psp == 0 ? -1 : psp - specials);
325
326 /* if we're at a special character, quote it */
327 if (sp_index >= 0)
328 {
329 /* append the plain chunk up to this point */
330 if (p != start)
331 append(start, p - start);
332
333 /* append the entity version of the special character */
334 append(xlat[sp_index]);
335
336 /* the next chunk starts at the next character */
337 start = p + 1;
338 }
339 }
340
341 /* append the final chunk */
342 if (p != start)
343 append(start, p - start);
344 }
345
346 /* format then append as XML */
347 void vappendf_xml(const char *fmt, va_list argp)
348 {
349 NetString tmp(512);
350
351 /* format the message */
352 tmp.vappendf(fmt, argp);
353
354 /* append as XML */
355 append_xml(tmp.buf);
356 }
357
358 /* append text, converting plain text to URL encoding */
359 void append_urlencode(const char *txt)
360 {
361 const char *p, *start;
362
363 /* append in chunks as we find special characters */
364 for (p = start = txt ; *p != '\0' ; ++p)
365 {
366 char c = *p;
367 if (isalpha(c) || isdigit(c) || strchr("-_.", c) != 0)
368 {
369 /* it's an ordinary character - keep it as-is */
370 }
371 else
372 {
373 /* special character - quote it */
374
375 /* copy the part up to the special character */
376 if (p != start)
377 append(start, p - start);
378
379 /* append '+' for a space or a '%' encoding for others */
380 if (c == ' ')
381 append("+");
382 else
383 appendf("%%%02x", (int)(unsigned char)c);
384
385 /* the next chunk starts at the next character */
386 start = p + 1;
387 }
388 }
389
390 /* append the final chunk */
391 if (p != start)
392 append(start, p - start);
393 }
394 };
395
396
397 /* ------------------------------------------------------------------------ */
398 /*
399 * Given an XML buffer, find the end of the <?XML?> header and the start of
400 * the regular XML contents
401 */
402 const char *TadsXml::strip_xml_header(const char *buf)
403 {
404 const char *p;
405
406 /* skip any initial newlines or whitespace */
407 for (p = buf ; isspace(*p) || *p == '\n' || *p == '\r' ; ++p) ;
408
409 /* if it starts with "<?xml", find the end of the directive */
410 if (memicmp(p, "<?xml ", 6) == 0)
411 {
412 int qu;
413
414 /* scan for the matching '>' */
415 for (p += 6, qu = 0 ; *p != '\0' ; ++p)
416 {
417 /* check for quotes */
418 if (*p == '"' || *p == '\'')
419 {
420 /*
421 * if we're in a quoted section, and this is the matching
422 * close quote, leave the quoted section; if we're not in a
423 * quoted section, this is the opening quote of a quoted
424 * section
425 */
426 if (qu == 0)
427 {
428 /* we weren't in a quoted section, so now we are */
429 qu = *p;
430 }
431 else if (*p == qu)
432 {
433 /* we were in a quoted section, and it's our close quote */
434 qu = 0;
435 }
436 }
437 else if (*p == '?' && *(p+1) == '>')
438 {
439 /*
440 * It's the end of the directive. Skip the "?>" sequence
441 * and any subsequent newline characters.
442 */
443 for (p += 2 ; *p == '\n' || *p == '\r' ; ++p) ;
444
445 /*
446 * we're now at the start of the XML contents - return the
447 * current pointer
448 */
449 return p;
450 }
451 }
452 }
453
454 /*
455 * we either didn't find the start of the <?XML?> directive, or we
456 * couldn't find the end of it - in either case, we don't have a
457 * well-formed directive, so there's nothing to strip: just return the
458 * original buffer
459 */
460 return buf;
461 }
462
463 /* ------------------------------------------------------------------------ */
464 /*
465 * HTTP Server
466 */
467
468 /*
469 * construct
470 */
471 TadsListener::TadsListener(TadsListenerThread *t)
472 {
473 /* remember the thread, and note our reference */
474 thread = t;
475 t->add_ref();
476 }
477
478 TadsListener::~TadsListener()
479 {
480 /* release our referenced objects */
481 thread->release_ref();
482 }
483
484 /*
485 * launch a server
486 */
487 TadsListener *TadsListener::launch(const char *hostname, ushort portno,
488 TadsListenerThread *thread)
489 {
490 /* open the network port */
491 OS_Listener *l = new OS_Listener();
492 if (!l->open(hostname, portno))
493 {
494 /* couldn't open the port - delete the listener and return failure */
495 l->release_ref();
496 return 0;
497 }
498
499 /* put the port into non-blocking mode */
500 l->set_non_blocking();
501
502 /* hand the network port over to the thread - it assumes our reference */
503 thread->set_port(l);
504
505 /* launch the listener thread */
506 if (!thread->launch())
507 {
508 /* couldn't launch the thread - delete it and return failure */
509 thread->release_ref();
510 return 0;
511 }
512
513 /* return the new listener object */
514 return new TadsListener(thread);
515 }
516
517 /*
518 * notify the server that it's time to shut down
519 */
520 void TadsListener::shutdown()
521 {
522 /* set the 'quit' event in our thread */
523 thread->shutdown_evt->signal();
524 }
525
526
527 /* ------------------------------------------------------------------------ */
528 /*
529 * Generic listener thread base class.
530 */
531
532 /*
533 * Deletion
534 */
535 TadsListenerThread::~TadsListenerThread()
536 {
537 /* release our port, if we have one */
538 if (port != 0)
539 port->release_ref();
540
541 /* release our quit event and shutdown event */
542 quit_evt->release_ref();
543 shutdown_evt->release_ref();
544
545 /* release our mutex */
546 mutex->release_ref();
547
548 /* free the error message string */
549 lib_free_str(errmsg);
550
551 /* free the password string */
552 lib_free_str(password);
553
554 /*
555 * Release all of our server threads. Note that we don't need to
556 * protect against concurrent access here because we know that no one
557 * has a reference to this object any longer - it's the only way we can
558 * be deleted.
559 */
560 TadsServerThread *tcur, *tnxt;
561 for (tcur = servers ; tcur != 0 ; tcur = tnxt)
562 {
563 /* remember the next one, and release this one */
564 tnxt = tcur->next_server;
565 tcur->release_ref();
566 }
567 }
568
569 /*
570 * Thread main
571 */
572 void TadsListenerThread::thread_main()
573 {
574 /*
575 * keep going until we get the general application-wide 'quit' signal
576 * or our own private listener shutdown event
577 */
578 while (!quit_evt->test() && !shutdown_evt->test())
579 {
580 /*
581 * wait for a new connection request OR the quit signal, whichever
582 * comes first
583 */
584 OS_Waitable *w[] = { port, quit_evt, shutdown_evt };
585 switch (OS_Waitable::multi_wait(3, w))
586 {
587 case OSWAIT_EVENT + 0:
588 /* the port is ready - reset the event */
589 port->reset_event();
590
591 /* read connections as long as they're available */
592 for (;;)
593 {
594 /* check for a connection request */
595 OS_Socket *s = port->accept();
596
597 /* if we're out of requests, go back to waiting */
598 if (s == 0 && port->last_error() == OS_EWOULDBLOCK)
599 break;
600
601 /* check for other errors */
602 if (s == 0)
603 {
604 /* failed - flag the error and shut down */
605 errmsg = t3sprintf_alloc(
606 "Listener thread failed: error %d from accept()",
607 port->last_error());
608 shutdown_evt->signal();
609 break;
610 }
611
612 /* put the socket into non-blocking mode */
613 s->set_non_blocking();
614
615 /* create the server thread (it takes over the socket ref) */
616 TadsServerThread *st = create_server_thread(s);
617 st->thread_id = next_thread_id++;
618
619 /* launch the server thread */
620 if (!st->launch())
621 {
622 /* failed - flag the error and shut down */
623 errmsg = lib_copy_str("Listener thread failed: "
624 "couldn't launch server thread");
625 shutdown_evt->signal();
626
627 /* release our reference on the thread */
628 st->release_ref();
629
630 /* done */
631 break;
632 }
633
634 /* we're done with our reference to the thread */
635 st->release_ref();
636 }
637 break;
638
639 case OSWAIT_EVENT + 1:
640 /*
641 * The quit signal fired - the whole app is terminating.
642 * Signal our internal shutdown event and abort.
643 */
644 shutdown_evt->signal();
645 break;
646
647 case OSWAIT_EVENT + 2:
648 /* shutdown signal fired - the listener is terminating; abort */
649 break;
650 }
651 }
652
653 /* wait for our server threads to exit */
654 for (;;)
655 {
656 TadsServerThread *st;
657
658 /* get the first thread from the list */
659 mutex->lock();
660 if ((st = servers) != 0)
661 st->add_ref();
662 mutex->unlock();
663
664 /* if we're out of threads, we're done */
665 if (st == 0)
666 break;
667
668 /* wait for this thread */
669 st->wait();
670
671 /* we're done with this thread */
672 st->release_ref();
673 }
674 }
675
676 /*
677 * Add a thread to our list
678 */
679 void TadsListenerThread::add_thread(TadsServerThread *t)
680 {
681 /* protect against concurrent access */
682 mutex->lock();
683
684 /* link the thread into our list */
685 t->next_server = servers;
686 servers = t;
687
688 /* keep a reference on it */
689 t->add_ref();
690
691 /* done with concurrent access protection */
692 mutex->unlock();
693 }
694
695 /*
696 * Remove a thread from our list
697 */
698 void TadsListenerThread::remove_thread(TadsServerThread *t)
699 {
700 /* protect against concurrent access */
701 mutex->lock();
702
703 /* find the thread */
704 TadsServerThread *cur, *prv;
705 for (cur = servers, prv = 0 ; cur != 0 ;
706 prv = cur, cur = cur->next_server)
707 {
708 /* if this is the one we're looking for, unlink it */
709 if (cur == t)
710 {
711 /* unlink it from the list */
712 if (prv != 0)
713 prv->next_server = cur->next_server;
714 else
715 servers = cur->next_server;
716
717 /* release our reference on it */
718 t->release_ref();
719
720 /* we're done searching */
721 break;
722 }
723 }
724
725 /* done with concurrent access protection */
726 mutex->unlock();
727 }
728
729 /*
730 * generate a human-readable status report of my threads
731 */
732 void TadsListenerThread::list_threads(NetString *buf)
733 {
734 /* protect against concurrent access */
735 mutex->lock();
736
737 /* scan threads */
738 for (TadsServerThread *cur = servers ; cur != 0 ; cur = cur->next_server)
739 {
740 /* report on this thread */
741 StringRef *state = cur->get_state();
742 buf->appendf("Thread ID=%d (thread object=%lx): %s<br>",
743 cur->thread_id, (unsigned long)cur, state->get());
744
745 /* done with the state string */
746 state->release_ref();
747 }
748
749 /* done with concurrent access protection */
750 mutex->unlock();
751 }
752
753 /* ------------------------------------------------------------------------ */
754 /*
755 * Generic server thread base class
756 */
757
758 void TadsServerThread::thread_main()
759 {
760 /* add this thread to the listener's active server list */
761 listener->add_thread(this);
762
763 /* process requests until we encounter an error or Quit signal */
764 while (!listener->quit_evt->test()
765 && !listener->shutdown_evt->test()
766 && process_request()) ;
767
768 /* terminating - close the socket */
769 set_run_state("Closing");
770 socket->close();
771
772 /* remove myself from the listener's active server list */
773 listener->remove_thread(this);
774
775 /* set my final run state */
776 set_run_state("Terminated");
777 }
778
779 /*
780 * Read bytes from the other side. Blocks until there's at least one byte
781 * to read, then reads as many bytes into the buffer as we can without
782 * blocking further. Aborts if either the listener's "quit" or "shutdown"
783 * event is triggered.
784 */
785 long TadsServerThread::read(char *buf, size_t buflen, long minlen,
786 unsigned long timeout)
787 {
788 /* figure the ending time for the wait */
789 unsigned long t = os_get_sys_clock_ms(), t_end = t + timeout;
790
791 /* we haven't read any bytes yet */
792 long totlen = 0;
793
794 /* if the caller provided a buffer, we can't read past the buffer */
795 if (buf != 0 && minlen > (long)buflen)
796 minlen = buflen;
797
798 /* keep going until we read some data */
799 for (;;)
800 {
801 int len;
802 char ibuf[4096], *dst;
803 size_t dstlen;
804
805 /* figure the buffer destination and size to read on this round */
806 if (buf == 0)
807 {
808 /*
809 * There's no buffer, so read into our internal buffer. Tead
810 * up to the remaining minimum size, or to our available
811 * internal space, whichever is less.
812 */
813 dst = ibuf;
814 dstlen = (minlen < sizeof(ibuf) ? minlen : sizeof(ibuf));
815 }
816 else
817 {
818 /*
819 * Read into the caller's buffer, after any data we've read so
820 * far, up to the remaining buffer length.
821 */
822 dst = buf + totlen;
823 dstlen = buflen - totlen;
824 }
825
826 /* read the data */
827 set_run_state("Receiving");
828 len = socket->recv(dst, dstlen);
829
830 /* if an error occurred, check what happened */
831 if (len == OS_SOCKET_ERROR)
832 {
833 /* presume failure */
834 int ok = FALSE;
835
836 /* if this is a would-block error, wait for data to arrive */
837 if (socket->last_error() == OS_EWOULDBLOCK)
838 {
839 /*
840 * No data available - wait until we receive at least one
841 * byte, or until the 'quit' event is signaled or a timeout
842 * occurs. Figure the next timeout expiration, if we have
843 * a timeout at all.
844 */
845 if (timeout != OS_FOREVER)
846 {
847 /* if we're already past the timeout expiration, fail */
848 t = os_get_sys_clock_ms();
849 if (t > t_end)
850 return -1;
851
852 /* figure the remaining timeout interval */
853 timeout = t_end - t;
854 }
855
856 /* wait */
857 set_run_state("Waiting(receive)");
858 OS_Waitable *w[] = {
859 socket, listener->quit_evt, listener->shutdown_evt
860 };
861 if (OS_Waitable::multi_wait(3, w, timeout) == OSWAIT_EVENT + 0)
862 {
863 /* the socket is now ready - reset it and keep going */
864 socket->reset_event();
865 ok = TRUE;
866 }
867 }
868
869 /* if we didn't correct the error, give up */
870 if (!ok)
871 return -1;
872 }
873 else if (len == 0)
874 {
875 /* the socket has been closed - return failure */
876 set_run_state("Error(receiving)");
877 return -1;
878 }
879 else if (len >= minlen)
880 {
881 /* we've satisfied the request - return the bytes */
882 set_run_state("Receive completed");
883 return totlen + len;
884 }
885 else
886 {
887 /*
888 * We've read some data, but not enough to satisfy the minimum
889 * length request. Add the current chunk to the total read so
890 * far, and deduct it from the remaining minimum.
891 */
892 totlen += len;
893 minlen -= len;
894 }
895 }
896 }
897
898 /*
899 * Send data to the other side. Blocks until we send all of the data, or
900 * until the Quit event is signaled or we encounter another error. Returns
901 * true on success, false on failure.
902 */
903 int TadsServerThread::send(const char *buf, size_t len)
904 {
905 /* keep going until we satisfy the write request or run into trouble */
906 while (len != 0)
907 {
908 /* try sending */
909 set_run_state("Sending");
910 size_t cur = socket->send(buf, len);
911
912 /* check what happened */
913 if (cur == OS_SOCKET_ERROR)
914 {
915 /* error reading socket - presume failure */
916 int ok = FALSE;
917
918 /* if this is a 'would block' error, wait for the socket */
919 if (socket->last_error() == OS_EWOULDBLOCK)
920 {
921 /* wait for the socket to unblock, or for the Quit event */
922 set_run_state("Waiting(send)");
923 OS_Waitable *w[] = {
924 socket, listener->quit_evt, listener->shutdown_evt
925 };
926 if (OS_Waitable::multi_wait(3, w) == OSWAIT_EVENT + 0)
927 {
928 /* socket is ready - reset it and carry on */
929 socket->reset_event();
930 ok = TRUE;
931 }
932 }
933
934 /* if we didn't solve the problem, fail */
935 if (!ok)
936 return FALSE;
937 }
938 else
939 {
940 /* adjust the counters for the write */
941 buf += cur;
942 len -= cur;
943 }
944 }
945
946 /* we successfully sent all of the requested data */
947 set_run_state("Send completed");
948 return TRUE;
949 }
950
951
952 /* ------------------------------------------------------------------------ */
953 /*
954 * argument structure for URL parsing
955 */
956 struct url_param
957 {
958 /* argument name */
959 const char *name;
960
961 /* argument value */
962 const char *val;
963 };
964
965 struct url_param_alo: url_param
966 {
967 url_param_alo()
968 {
969 name = 0;
970 val = 0;
971 }
972
973 url_param_alo * operator =(const url_param &src)
974 {
975 name = lib_copy_str(src.name);
976 val = lib_copy_str(src.val);
977 return this;
978 }
979
980 ~url_param_alo()
981 {
982 lib_free_str((char *)name);
983 lib_free_str((char *)val);
984 }
985 };
986
987 #if 0 // not currently used
988 /* get the value of an argument */
989 static const char *get_arg_val(const char *name, const char *dflt,
990 const url_param *args, int argc)
991 {
992 int i;
993
994 /* scan for the argument name */
995 for (i = 0 ; i < argc ; ++i, ++args)
996 {
997 if (stricmp(args->name, name) == 0)
998 return args->val;
999 }
1000
1001 /* didn't find it */
1002 return dflt;
1003 }
1004 #endif
1005
1006 /* ------------------------------------------------------------------------ */
1007 /*
1008 * HTTP Listener Thread
1009 */
1010
1011 /*
1012 * construction
1013 */
1014 TadsHttpListenerThread::TadsHttpListenerThread(
1015 vm_obj_id_t srv_obj, TadsMessageQueue *q, long ulim)
1016 : TadsListenerThread(q->get_quit_evt())
1017 {
1018 /* remember the HTTPServer object that created the listener */
1019 this->srv_obj = srv_obj;
1020
1021 /* save a reference to the queue */
1022 (queue = q)->add_ref();
1023
1024 /* save the upload limit */
1025 upload_limit = ulim;
1026 }
1027
1028 /*
1029 * deletion
1030 */
1031 TadsHttpListenerThread::~TadsHttpListenerThread()
1032 {
1033 /* release our queue */
1034 queue->release_ref();
1035 }
1036
1037 /* ------------------------------------------------------------------------ */
1038 /*
1039 * HTTP Server Thread
1040 */
1041
1042 /*
1043 * Constant strings for some common HTTP status codes we report
1044 */
1045 static const char *S_http_400 = "400 Bad Request";
1046
1047 static const char *S_http_500 = "500 Internal Server Error";
1048 static const char *S_http_500_body =
1049 "<html>"
1050 "<title>500 Internal Server Error</title>"
1051 "<body>"
1052 "<h1>Internal Server Error</h1>"
1053 "</body>"
1054 "</html>";
1055
1056 static const char *S_http_503 = "503 Service Unavailable (Shutting Down)";
1057 static const char *S_http_503_quitting_body =
1058 "<html>"
1059 "<title>503 Service Unavailable</title>"
1060 "<body>"
1061 "<h1>Service Unavailable</h1>"
1062 "The server is shutting down and cannot process any more requests."
1063 "</body>"
1064 "</html>";
1065
1066 /*
1067 * Parse a space-delimited token.
1068 */
1069 static void parse_tok(char *&p, char *&tok, size_t &tok_len)
1070 {
1071 /* skip leading spaces */
1072 for ( ; isspace(*p) ; ++p) ;
1073
1074 /* the token starts here */
1075 tok = p;
1076
1077 /*
1078 * find the end of the token - it's the end of the string, or the next
1079 * whitespace or newline (CR or LF) character
1080 */
1081 for ( ; *p != '\0' && !isspace(*p) && *p != '\n' && *p != '\r' ; ++p) ;
1082
1083 /* note the length of the token */
1084 tok_len = p - tok;
1085 }
1086
1087 /*
1088 * HTTP server thread - Construction
1089 */
1090 TadsHttpServerThread::TadsHttpServerThread(
1091 TadsHttpListenerThread *l, TadsMessageQueue *q, long ulim, OS_Socket *s)
1092 : TadsServerThread(l, s)
1093 {
1094 /* keep a reference to the message queue */
1095 (queue = q)->add_ref();
1096
1097 /* remember the upload limit */
1098 upload_limit = ulim;
1099 }
1100
1101 TadsHttpServerThread::~TadsHttpServerThread()
1102 {
1103 /* done with the message queue */
1104 queue->release_ref();
1105 }
1106
1107
1108 /*
1109 * Send a simple response, with the given status code and message body. If
1110 * the mesage body is null, we'll just send the response header. Returns
1111 * true if successful, false on error.
1112 */
1113 int TadsHttpServerThread::send_simple(
1114 const char *status_code, const char *mime_type,
1115 const char *msg_body, size_t msg_len,
1116 const char *extra_headers)
1117 {
1118 char hdr[100];
1119
1120 /* send the response */
1121 t3sprintf(hdr, sizeof(hdr), "HTTP/1.1 %s\r\n", status_code);
1122 if (!send(hdr, strlen(hdr)))
1123 return FALSE;
1124
1125 /* send the extra headers */
1126 if (extra_headers != 0)
1127 send(extra_headers, strlen(extra_headers));
1128
1129 /* if there's a message body, send it, with a content-length header */
1130 if (msg_body != 0)
1131 {
1132 char buf[200];
1133
1134 /* build the cache-control and content-length header */
1135 t3sprintf(buf, sizeof(buf),
1136 "Content-Type: %s\r\n"
1137 "Content-Length: %lu\r\n"
1138 "Cache-control: no-cache\r\n"
1139 "Connection: Keep-Alive\r\n"
1140 "\r\n",
1141 mime_type, (ulong)msg_len);
1142
1143 /* send the headers, followed by the message body */
1144 if (!send(buf, strlen(buf))
1145 || !send(msg_body, msg_len))
1146 return FALSE;
1147 }
1148 else
1149 {
1150 /*
1151 * there's no body, so just send a blank line to mark the end of
1152 * the header
1153 */
1154 if (!send("\r\n", 2))
1155 return FALSE;
1156 }
1157
1158 /* success */
1159 return TRUE;
1160 }
1161
1162 /*
1163 * Read to one or two newline sequences.
1164 */
1165 int TadsHttpServerThread::read_to_nl(StringRef *dst, long ofs,
1166 int init_state, int end_state)
1167 {
1168 /* newline state: 0 \r -> 1 \n -> 2 \r -> 3 \n -> 4 */
1169 int nlstate = init_state;
1170
1171 /* keep going until we find the newline or newline pair */
1172 for (;;)
1173 {
1174 char buf[8192];
1175
1176 /* scan up to the ending offset */
1177 const char *p = dst->get() + ofs;
1178 long endofs = dst->getlen();
1179 for ( ; ofs < endofs && nlstate != end_state ; ++ofs, ++p)
1180 {
1181 if (nlstate == 2 && *p == '\r')
1182 nlstate = 3;
1183 else if (*p == '\r')
1184 nlstate = 1;
1185 else if ((nlstate == 1 || nlstate == 3) && *p == '\n')
1186 nlstate += 1;
1187 else
1188 nlstate = 0;
1189 }
1190
1191 /* if we're in the end state, we're done */
1192 if (nlstate == end_state)
1193 break;
1194
1195 /*
1196 * We didn't find the end sequence, so we need more input. Read at
1197 * least one byte with no timeout, so that we block until
1198 * something's available and then read all available bytes.
1199 */
1200 long len = read(buf, sizeof(buf), 1, OS_FOREVER);
1201 set_run_state("Processing request");
1202
1203 /* if we got the 'quit' signal, stop now */
1204 if (len < 0)
1205 return -1;
1206
1207 /* append the text to the buffer */
1208 dst->append(buf, len);
1209 }
1210
1211 /* return the buffer offset of the end of the terminating newline */
1212 return ofs;
1213 }
1214
1215
1216 /*
1217 * Process a request from our HTTP client. The main server loop calls this
1218 * when the socket has data ready to read.
1219 */
1220 int TadsHttpServerThread::process_request()
1221 {
1222 StringRef *hdrs = new StringRef(1024);
1223 TadsHttpRequestHeader *hdr_list = 0, *hdr_tail = 0;
1224 TadsHttpRequest *req = 0;
1225 char *verb;
1226 size_t verb_len;
1227 char *resource_name;
1228 size_t res_name_len;
1229 int ok = FALSE;
1230 long ofs;
1231 char *p, *hbody;
1232 StringRef *body = 0;
1233 int overflow = FALSE;
1234 long hbodylen;
1235 const char *hcl, *hte; /* content-length, transfer-encoding */
1236
1237 /*
1238 * Read the header. We read data into our buffer until we find a
1239 * double CR-LF sequence, indicating the end of the header.
1240 */
1241 if ((ofs = read_to_nl(hdrs, 0, 0, 4)) < 0)
1242 goto done;
1243
1244 /* the body, if any, starts after the double line break */
1245 hbody = hdrs->get() + ofs;
1246 hbodylen = hdrs->getlen() - ofs;
1247
1248 /* truncate the headers to the CR-LF-CR-LF sequence */
1249 hdrs->truncate(ofs - 2);
1250
1251 /*
1252 * Parse the main verb in the header - get the method and the resource
1253 * ID. The format is:
1254 *
1255 *. <space>* VERB <space>+ RESOURCE <space>+ HTTP-VERSION <CRLF>
1256 */
1257 p = hdrs->get();
1258 parse_tok(p, verb, verb_len);
1259 parse_tok(p, resource_name, res_name_len);
1260
1261 /* now parse the remaining headers */
1262 TadsHttpRequestHeader::parse_headers(hdr_list, hdr_tail, FALSE, hdrs, 0);
1263
1264 /*
1265 * Check to see if there's a message body. There is if there's a
1266 * content-length or transfer-encoding header.
1267 */
1268 hcl = hdr_list->find("content-length");
1269 hte = hdr_list->find("transfer-encoding");
1270 if (hcl != 0 || hte != 0)
1271 {
1272 /*
1273 * There's a content body. If there's a content-length field,
1274 * pre-allocate a chunk of memory, then read the number of bytes
1275 * indicated. If it's a chunked transfer, read it in pieces.
1276 */
1277 if (hcl != 0)
1278 {
1279 /* get the length */
1280 long hclval = atol(hcl);
1281
1282 /* if it's non-zero, read the content */
1283 if (hclval != 0)
1284 {
1285 /* if this exceeds the size limit, abort */
1286 if (upload_limit != 0 && hclval > upload_limit)
1287 {
1288 /* set the overflow flag, discard the input, and abort */
1289 overflow = TRUE;
1290 read(0, 0, hclval, 5000);
1291 goto done_with_upload;
1292 }
1293
1294 /* allocate the buffer; it's initially empty */
1295 body = new StringRef(hclval);
1296
1297 /* copy any portion of the body we've already read */
1298 if (hbodylen != 0)
1299 {
1300 /* limit this to the declared size */
1301 if (hbodylen > hclval)
1302 hbodylen = hclval;
1303
1304 /* copy the data */
1305 body->append(hbody, hbodylen);
1306
1307 /* deduct the remaining size */
1308 hclval -= hbodylen;
1309 }
1310
1311 /* read the body */
1312 if (hclval != 0
1313 && read(body->getend(), hclval, hclval, 5000) < 0)
1314 {
1315 send_simple(S_http_400, "text/html",
1316 "Error receiving request message body");
1317 goto done;
1318 }
1319
1320 /* set the body length */
1321 body->addlen(hclval);
1322 }
1323 }
1324 else if (stricmp(hte, "chunked") == 0)
1325 {
1326 /* set up a string buffer for the content */
1327 const long initlen = 32000;
1328 body = new StringRef(hbodylen > initlen ? hbodylen : initlen);
1329
1330 /* if we've already read some body text, copy it to the buffer */
1331 if (hbodylen != 0)
1332 body->append(hbody, hbodylen);
1333
1334 /* keep going until we reach the end marker */
1335 for (ofs = 0 ; ; )
1336 {
1337 /* read to the first newline */
1338 long nlofs = read_to_nl(body, ofs, 0, 2);
1339 if (nlofs < 0)
1340 goto done;
1341
1342 /* get the chunk length */
1343 long chunklen = strtol(body->get() + ofs, 0, 16);
1344
1345 /*
1346 * We're done with the chunk length. Move any read-ahead
1347 * content down in memory so that it directly abuts the
1348 * preceding chunk, so that when we're done we'll have the
1349 * content assembled into one contiguous piece.
1350 */
1351 long ralen = body->getlen() - nlofs;
1352 if (ralen > 0)
1353 memmove(body->get() + ofs, body->get() + nlofs,
1354 body->getlen() - nlofs);
1355
1356 /* stop at the end of the read-ahead portion */
1357 body->truncate(ofs + ralen);
1358
1359 /* if the chunk length is zero, we're done */
1360 if (chunklen == 0)
1361 break;
1362
1363 /* check if this would overflow our upload size limit */
1364 if (upload_limit != 0
1365 && !overflow
1366 && body->getlen() + chunklen > upload_limit)
1367 {
1368 /* flag the overflow, but keep reading the content */
1369 overflow = TRUE;
1370 }
1371
1372 /*
1373 * figure the remaining read size for this chunk, after any
1374 * read-ahead portion
1375 */
1376 long chunkrem = chunklen - ralen;
1377
1378 /*
1379 * if we've already overflowed, read and discard the chunk;
1380 * otherwise read it into our buffer
1381 */
1382 if (chunkrem + 2 <= 0)
1383 {
1384 /*
1385 * We've already read ahead by enough to cover the next
1386 * chunk and the newline at the end. Go in and delete
1387 * the newline (or as much of it as exists). Start by
1388 * getting the offset of the newline: it's just after
1389 * the current chunk, which starts at 'ofs' and runs
1390 * for 'chunklen'.
1391 */
1392 nlofs = ofs + chunklen;
1393
1394 /*
1395 * if we haven't yet read the full newline sequence, do
1396 * so now
1397 */
1398 if (ralen - chunklen < 2)
1399 {
1400 long nllen = 2 - (ralen - chunklen);
1401 body->ensure(nllen);
1402 if (read(body->getend(), nllen, nllen, 30000) < 0)
1403 {
1404 send_simple(S_http_400, "text/html",
1405 "Error receiving request message chunk");
1406 goto done;
1407 }
1408 }
1409
1410 /*
1411 * if there's anything after the newline, move it down
1412 * to overwrite the newline
1413 */
1414 if (ralen - chunklen > 2)
1415 {
1416 /* move the bytes */
1417 memmove(body->get() + nlofs,
1418 body->get() + nlofs + 2,
1419 ralen - chunklen - 2);
1420
1421 /* adjust the size for the closed gap */
1422 body->truncate(body->getlen() - 2);
1423 }
1424
1425 /* resume from after the newline */
1426 ofs = nlofs;
1427 }
1428 else if (overflow)
1429 {
1430 /* overflow - discard the chunk size (plus the CR-LF) */
1431 if (read(0, 0, chunkrem+2, 30000) < 0)
1432 goto done;
1433
1434 /* clear the buffer */
1435 body->truncate(0);
1436 ofs = 0;
1437 }
1438 else
1439 {
1440 /* ensure the buffer is big enough */
1441 body->ensure(chunkrem + 2);
1442
1443 /* read the chunk, plus the CR-LF that follows */
1444 if (read(body->getend(),
1445 chunkrem + 2, chunkrem + 2, 30000) < 0)
1446 {
1447 send_simple(S_http_400, "text/html",
1448 "Error receiving request message chunk");
1449 goto done;
1450 }
1451
1452 /* count the amount we just read in the buffer length */
1453 body->addlen(chunkrem + 2);
1454
1455 /* verify that the last two bytes are indeed CR-LF */
1456 if (memcmp(body->getend() - 2, "\r\n", 2) != 0)
1457 {
1458 send_simple(S_http_400, "text/html",
1459 "Error in request message chunk");
1460 goto done;
1461 }
1462
1463 /*
1464 * move past the chunk for the next read, minus the
1465 * CR-LF that follows the chunk - that isn't part of
1466 * the data, but just part of the protocol
1467 */
1468 ofs = body->getlen() - 2;
1469 body->truncate(ofs);
1470 }
1471 }
1472
1473 /*
1474 * Read to the closing blank line. We've just passed one
1475 * newline, following the '0' end length marker, so we're in
1476 * state 2. We could have either another newline following, or
1477 * "trailers" (more headers, following the content body).
1478 */
1479 long nlofs = read_to_nl(body, ofs, 2, 4);
1480 if (nlofs < 0)
1481 goto done;
1482
1483 /*
1484 * if we have more than just the closing blank line, we have
1485 * trailers - append them to the headers
1486 */
1487 if (nlofs > ofs + 2)
1488 {
1489 TadsHttpRequestHeader::parse_headers(
1490 hdr_list, hdr_tail, TRUE, body, ofs);
1491 }
1492
1493 /*
1494 * the trailers (if any) and closing newline aren't part of the
1495 * content - clip them out of the body
1496 */
1497 body->truncate(ofs);
1498 }
1499 else
1500 {
1501 /*
1502 * Other combinations of these headers are illegal. Send an
1503 * error and abort.
1504 */
1505 send_simple(S_http_400, "text/html",
1506 "<html><title>Bad Request</title>"
1507 "<h1>Bad Request</h1>"
1508 "This server does not accept the specified "
1509 "transfer-encoding.");
1510 goto done;
1511 }
1512
1513 done_with_upload:
1514 /* done with the upload - check for overflow */
1515 if (overflow)
1516 {
1517 /* release the body, if present */
1518 if (body != 0)
1519 {
1520 body->release_ref();
1521 body = 0;
1522 }
1523 }
1524 }
1525
1526 /* create a message object for the request */
1527 req = new TadsHttpRequest(
1528 this, verb, verb_len, hdrs, hdr_list, body, overflow,
1529 resource_name, res_name_len,
1530 listener->get_shutdown_evt());
1531
1532 /* we've handed over the header list to the request */
1533 hdr_list = 0;
1534
1535 /* send it to the main thread, and wait for the reply */
1536 if (queue->send(req, OS_FOREVER))
1537 {
1538 /*
1539 * success - the server will already have sent the reply, so we're
1540 * done
1541 */
1542 }
1543 else if (queue->is_quitting())
1544 {
1545 /* failed due to server shutdown */
1546 send_simple(S_http_503, "text/html", S_http_503_quitting_body);
1547 }
1548 else
1549 {
1550 /* 'send' failed - return an internal server error */
1551 send_simple(S_http_500, "text/html", S_http_500_body);
1552 }
1553
1554 /* we're done with the request */
1555 req->release_ref();
1556
1557 /* success */
1558 ok = TRUE;
1559
1560 done:
1561 /* release the message body buffer */
1562 if (body != 0)
1563 body->release_ref();
1564
1565 /* release the header buffer */
1566 hdrs->release_ref();
1567
1568 /* delete the header list */
1569 if (hdr_list != 0)
1570 delete hdr_list;
1571
1572 /* return the success/failure indication */
1573 return ok;
1574 }
1575
1576 /* ------------------------------------------------------------------------ */
1577 /*
1578 * Complete an HTTP request
1579 */
1580 void TadsHttpRequest::complete()
1581 {
1582 /*
1583 * if the client included a "connection" header with value "close",
1584 * close the socket
1585 */
1586 const char *conn = (hdr_list != 0 ? hdr_list->find("connection") : 0);
1587 if (conn != 0 && stricmp(conn, "close") == 0 && thread != 0)
1588 thread->close_socket();
1589
1590 /* mark the message queue object as completed */
1591 TadsEventMessage::complete();
1592 }
1593