File: xttpd.cc

package info (click to toggle)
xtide 2.6.4-1
  • links: PTS
  • area: main
  • in suites: sarge
  • size: 2,996 kB
  • ctags: 2,617
  • sloc: cpp: 26,266; ansic: 8,105; makefile: 152; yacc: 113; sh: 54; lex: 54
file content (1086 lines) | stat: -rw-r--r-- 28,451 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
// $Id: xttpd.cc,v 1.5 2003/02/20 15:19:56 flaterco Exp $
/*  xttpd  XTide web server.

    Copyright (C) 1998  David Flater.

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/

#include "common.hh"

// These browsers nowadays can get pretty verbose.
#define bufsize 10000

// Nasty global variables.
TideContext *context = NULL;
Dstr webmaster;
ZoneIndex zi;
int zoneinfo_doesnt_suck;

// time control modes

enum TC {	TC_ALL,		// year, month, day
		TC_YEAR,	// year
		TC_MONTH	// year, month
};

#include "purec++.hh"

static void
setup_socket (unsigned short port_number, int &s)
{
  struct sockaddr_in sin;
  struct hostent *hp;
  struct utsname foo;

  uname (&foo);
  if (!(hp = (struct hostent *) gethostbyname (foo.nodename))) {
    Dstr details ("Gethostbyname fails on own nodename!");
    barf (CANT_GET_SOCKET, details);
  }
  memset ((char *) &sin, '\0', sizeof sin);
  memcpy ((char *) &sin.sin_addr, hp->h_addr, hp->h_length);
  sin.sin_port = htons (port_number);
  sin.sin_family = hp->h_addrtype;
  sin.sin_addr.s_addr = INADDR_ANY;
  if ((s = socket (hp->h_addrtype, SOCK_STREAM, 0)) == -1) {
    Dstr details ("socket: ");
    details += strerror (errno);
    details += ".";
    barf (CANT_GET_SOCKET, details);
  }
  {
    int tmp = 1;
    if (setsockopt (s, SOL_SOCKET, SO_REUSEADDR,
	  	    (char *)&tmp, sizeof(tmp)) < 0) {
      Dstr details ("setsockopt: ");
      details += strerror (errno);
      details += ".";
      barf (CANT_GET_SOCKET, details);
    }
  }{
    struct linger li;
    li.l_onoff = 1;
    li.l_linger = 6000; // Hundredths of seconds (1 min)
    if (setsockopt (s, SOL_SOCKET, SO_LINGER,
                   (char *)&li, sizeof(struct linger)) < 0) {
      xperror ("setsockopt");
    }
  }
  if (bind (s, (struct sockaddr *)(&sin), sizeof sin) == -1) {
    if (errno == EADDRINUSE) {
      Dstr details ("Socket already in use.");
      barf (CANT_GET_SOCKET, details);
    } else {
      Dstr details ("bind: ");
      details += strerror (errno);
      details += ".";
      barf (CANT_GET_SOCKET, details);
    }
  }
  // backlog was 0, but this hung Digital Unix.  5 is the limit for BSD.
  if (listen (s, 5) == -1) {
    Dstr details ("listen: ");
    details += strerror (errno);
    details += ".";
    barf (CANT_GET_SOCKET, details);
  }

  webmaster = getenv ("XTTPD_FEEDBACK");
#ifdef webmasteraddr
  if (webmaster.isNull())
    webmaster = webmasteraddr;
#endif
  if (webmaster == "software@flaterco.com")
    webmaster = (char *)NULL;  // I can't handle the AOLers all by myself.
  if (webmaster.isNull()) {
    // Guess the local webmaster.  (Guessing the FQDN is harder!)
    webmaster = hp->h_name;
    if (webmaster.strchr('.') == -1) {
      // They deleted getdomainname()...  Now what am I supposed to do?
      Dstr domain;
      FILE *fp;
      if ((fp = fopen ("/etc/defaultdomain", "r"))) {
	domain.scan (fp);
	fclose (fp);
	webmaster += ".";
	webmaster += domain;
      } else if ((fp = fopen ("/etc/domain", "r"))) {
	domain.scan (fp);
	fclose (fp);
	webmaster += ".";
	webmaster += domain;
      } else if ((fp = fopen ("/etc/resolv.conf", "r"))) {
	Dstr buf;
	while (!(buf.getline(fp)).isNull()) {
	  buf /= domain;
	  if (domain == "domain") {
	    buf /= domain;
	    webmaster += ".";
	    webmaster += domain;
	    break;
	  }
	}
	fclose (fp);
      }
    }
    if (webmaster %= "www.")
      webmaster /= 4;
    webmaster *= "webmaster@";
  }
  webmaster *= "<a href=\"mailto:";
  webmaster += "\">";
}

static void
add_disclaimer (Dstr &foo) {
  foo += "<center><h2> NOT FOR NAVIGATION </h2></center>\n\
<blockquote>\n\
<p>This program is distributed in the hope that it will be useful, but\n\
WITHOUT ANY WARRANTY; without even the implied warranty of\n\
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.&nbsp; The author\n\
assumes no liability for damages arising from use of these predictions.&nbsp;\n\
They are not certified to be correct, and they\n\
do not incorporate the effects of tropical storms, El Ni&ntilde;o,\n\
seismic events, continental drift, or changes in global sea level.\n\
</p></blockquote>\n";
}

static void
end_page (int s, int pure = 0) {
  Dstr end_mess ("<hr>");
  if (pure)
    end_mess += "<p><img src=\"/purec++.png\" align=left hspace=25></p>";
  end_mess += "<p> <a href=\"/\">Start over</a> <br>\n";
  end_mess += "<a href=\"/index.html\">Master index</a> <br>\n";
  end_mess += "<a href=\"/zones/\">Zone index</a> <br>\n";
  end_mess += "<a href=\"http://www.flaterco.com/xtide/\">XTide software</a> <br>\n";
  end_mess += webmaster;
  end_mess += "Feedback</a> <br>\n";
  end_mess += "<a href=\"/tricks.html\">Hints and tricks</a></p>\n\
</body>\n\
</html>\n";
  write (s, end_mess.aschar(), end_mess.length());
  close (s);
  exit (0);
}

static void
unimp_barf (int s) {
  char *barf_message = "\
HTTP/1.0 501 Not Implemented\n\
MIME-version: 1.0\n\
Content-type: text/html\n\
\n\
<html>\n\
<head><title> HTTP Error </title></head>\n\
<body bgcolor=\"FFFFFF\"><h1> HTTP Error </h1>\n\
<p>So sorry!&nbsp; This server cannot satisfy your request.</p>\n";

  write (s, barf_message, strlen (barf_message));
  end_page (s);
}

static void
notfound_barf (int s) {
  char *barf_message = "\
HTTP/1.0 404 Not Found\n\
MIME-version: 1.0\n\
Content-type: text/html\n\
\n\
<html>\n\
<head><title> Not Found </title></head>\n\
<body bgcolor=\"FFFFFF\"><h1> Not Found </h1>\n\
<p>So sorry!&nbsp; This server cannot satisfy your request.</p>\n";

  write (s, barf_message, strlen (barf_message));
  end_page (s);
}

static void
toolong_barf (int s) {
  char *barf_message = "\
HTTP/1.0 413 Request Entity Too Large\n\
MIME-version: 1.0\n\
Content-type: text/html\n\
\n\
<html>\n\
<head><title> HTTP Error </title></head>\n\
<body bgcolor=\"FFFFFF\"><h1> HTTP Error </h1>\n\
<p>So sorry!&nbsp; This server cannot satisfy your request.</p>\n";

  write (s, barf_message, strlen (barf_message));
  end_page (s);
}

static void
root_page (int s) {
  Dstr root_p ("\
HTTP/1.0 200 OK\n\
MIME-version: 1.0\n\
Content-type: text/html\n\
\n\
<html>\n\
<head><title> XTide Tide Prediction Server </title></head>\n\
<body bgcolor=\"FFFFFF\"><center><h1> XTide Tide Prediction Server </h1></center>\n\
\n\
<center>\n\
<p>Copyright (C) 1998\n\
David Flater.</p>\n\
</center>\n");
  add_disclaimer (root_p);
  root_p += "<blockquote>\n\
<p>\n\
While this program is maintained by David Flater, the web site\n\
itself is not.&nbsp; Please direct feedback about problems with the web site to\n\
the local ";
  root_p += webmaster;
  root_p += "webmaster</a>.</p></blockquote>\n\
<p> XTide can provide tide predictions for thousands of places around the\n\
world, but first you have to select a location.&nbsp;\n\
There are three ways to do this.&nbsp; One\n\
way is just to enter its name here, and click on Search: </p>\n\
<p><form method=get action=\"/query\">\n\
<input name=\"location\" type=text size=\"48\">\n\
<input type=submit value=\"Search\"> <input type=reset value=\"Clear\">\n\
</form></p>\n\
\n\
<p> Your other choices are the <a href=\"/zones/\">zone index</a>, which\n\
indexes locations by time zone, and \n\
the <a href=\"index.html\">master index</a>, which is just one big list\n\
of every location supported by this server.&nbsp; The master index could be\n\
very large, so if you are on a slow connection, don't use it.</p>\n\
\n\
<p> All images shipped by this web server are in PNG format.&nbsp; Versions of\n\
Netscape or Internet Explorer older than version 4 will not be able to\n\
display them. </p>\n";

  if (!(context->stationIndex()->hfile_ids.isNull())) {
    root_p += "<p>This server is using the following versions of the XTide data files:<br>";
    root_p += context->stationIndex()->hfile_ids;
    root_p += "</p>\n";
  }

  write (s, root_p.aschar(), root_p.length());
  end_page (s);
}

static void
start_loclist (Dstr &d) {
  context->startLocListHTML (d);
}

// This differs from TideContext::listLocationHTML because we need to
// add hyperlinks.
static void
list_location (Dstr &d, StationIndex *si, unsigned long i) {
  assert (si);
  StationRef *sr = (*si)[i];
  assert (sr);
  d += "<tr><td><a href=\"/locations/";
  d += i;
  d += ".html\">";
  d += sr->name;
  d += "</a></td><td>";
  if (sr->is_reference_station())
    d += "Ref";
  else
    d += "Sub";
  d += "</td><td>";
  Dstr tempc;
  sr->coordinates.print (tempc);
  d += tempc;
  d += "</td></tr>\n";
}

static void
end_loclist (Dstr &d) {
  context->endLocListHTML (d);
}

static void
index_page (int s) {
  Dstr top_p ("\
HTTP/1.0 200 OK\n\
MIME-version: 1.0\n\
Content-type: text/html\n\
\n\
<html>\n\
<head><title> XTide Master Index </title></head>\n\
<body bgcolor=\"FFFFFF\"><center><h1> XTide Master Index </h1></center>\n\
\n\
<p>Click on any location to get tide predictions.</p>\n");
  start_loclist (top_p);
  unsigned long i;
  StationIndex *si = context->stationIndex();
  for (i=0; i<si->length(); i++) {
    list_location (top_p, si, i);
    if ((i % maxhtmltablen == 0) && (i != 0)) {
      end_loclist (top_p);
      start_loclist (top_p);
    }
  }
  end_loclist (top_p);
  write (s, top_p.aschar(), top_p.length());
  end_page (s);
}

static void
tricks (int s) {
  Dstr top_p ("\
HTTP/1.0 200 OK\n\
MIME-version: 1.0\n\
Content-type: text/html\n\
\n\
<html>\n\
<head><title> XTide hints and tricks </title></head>\n\
<body bgcolor=\"FFFFFF\"><center><h1> XTide hints and tricks </h1></center>\n\
\n\
<p> This web server uses numerically indexed URLs to load prediction\n\
pages.&nbsp; Those URLs look like this:</p>\n\
\n\
<pre>http://whatever/locations/nnn.html</pre>\n\
\n\
<p>For convenience, you can also load a prediction page with a\n\
URL of the following form: </p>\n\
\n\
<pre>http://whatever/locations/name</pre>\n\
\n\
<p>You will receive an error if the name-based lookup gives ambiguous results,\n\
but these URLs have the advantage that they do not need to change every time\n\
the tide data are updated.</p>");

  write (s, top_p.aschar(), top_p.length());
  end_page (s);
}

static void
add_time_control (enum TC type, Dstr &text, Dstr &url, unsigned y, unsigned m, unsigned d) {
  text += "<p> <form method=get action=\"";
  text += url;
  text += "\">\nYear: <select name=\"y\">\n";
  unsigned i;
  for (i=dialogfirstyear; i<=dialoglastyear; i++) {
    if (i == y)
      text += "<option selected>";
    else
      text += "<option>";
    text += i;
    text += "\n";
  }
  text += "</select>\n";

  if(type != TC_YEAR) {
    text += "Month: <select name=\"m\">\n";
    for (i=1; i<=12; i++) {
      if (i == m)
        text += "<option selected>";
      else
        text += "<option>";
      text += i;
      text += "\n";
    }
    text += "</select>\n";
  }

  if(type == TC_ALL)
  {
    text += "Day: <select name=\"d\">\n";
    for (i=1; i<=31; i++) {
      if (i == d)
        text += "<option selected>";
      else
        text += "<option>";
      text += i;
      text += "\n";
    }
    text += "</select>\n";
  }

  text += "<input type=submit value=\"Go\"></form></p>";
}

Timestamp
parse_time_control (Dstr &filename, Dstr timezone, Settings *settings,
Dstr &tc_out) {
  tc_out = (char *)NULL;
  Timestamp ret ((time_t)(time(NULL)));
  int i;
  if ((i = filename.strrchr ('?')) != -1) {
    unsigned y, m, d;
    m = d = 1;
    if ((sscanf (filename.ascharfrom(i), "?y=%u&m=%u&d=%u", &y, &m, &d)) >= 1) {
      char temp[80];
      sprintf (temp, "%4u-%02u-%02u 00:00", y, m, d);
      Dstr in_iso (temp);
      ret = Timestamp (in_iso, timezone, settings);
      tc_out = filename.ascharfrom(i);
    }
  }
  return ret;
}

static void
load_location_page(int s, Dstr &filename, unsigned long i)
{
  StationIndex *si = context->stationIndex();
  Station *st = (*si)[i]->load (context);

  Dstr top_p ("\
HTTP/1.0 200 OK\n\
MIME-version: 1.0\n\
Content-type: text/html\n\
\n\
<html>\n\
<head><title> ");

  top_p += st->name;
  top_p += "</title></head>\n<body bgcolor=\"FFFFFF\">\n<center><h1> ";
  top_p += st->name;
  top_p += " <br>\n";

  Dstr text_out, tc_out;
  Timestamp start_tm = parse_time_control (filename, st->timeZone,
    context->settings, tc_out);
  Dstr myurl ("/locations/");
  myurl += i;
  myurl += ".html";
  struct tm *starttm = start_tm.get_tm (st->timeZone, context->settings);
  unsigned y = starttm->tm_year + 1900;
  unsigned m = starttm->tm_mon + 1;
  unsigned d = starttm->tm_mday;

  if (tc_out.isNull())
    top_p += "Local time:  ";
  else
    top_p += "Requested time:  ";
#if __alpha
  Dstr mungebuf;
  start_tm.print (mungebuf, st->timeZone, context->settings);
#endif
  Dstr nowbuf;
  start_tm.print (nowbuf, st->timeZone, context->settings);
  top_p += nowbuf;
  top_p += " </h1></center>\n";

  if (!zoneinfo_doesnt_suck) {
    top_p += "<p> Warning:  this host machine is using an obsolete time zone\n\
database.&nbsp; Summer Time (Daylight Savings Time) adjustments will not be done\n\
for some locations. </p>\n";
  }

  top_p += "<p><img src=\"/graphs/";
  top_p += i;
  top_p += ".png";
  top_p += tc_out;
  top_p += "\" width=";
  top_p += context->settings->gw;
  top_p += " height=";
  top_p += context->settings->gh;
  top_p += "></p><p><pre>\n";

  context->textMode (st, start_tm, text_out);
  top_p += text_out;
  top_p += "</pre></p>\n";

  top_p += "<h2> Time Control </h2>\n";
  add_time_control (TC_ALL, top_p, myurl, y, m, d);
  top_p += "<p> Note:  predictions for some locations do not cover the\n\
full span of years.&nbsp; If your browser returns a blank page or a \"no data\"\n\
error, then the predictions that you requested are not available. </p>\n";

  top_p += "<h2> Monthly Tide Calendars </h2>\n";
  Dstr monthurl ("/calendar/month/");
  monthurl += i;
  monthurl += ".html";
  add_time_control (TC_MONTH, top_p, monthurl, y, m, d);

  top_p += "<h2> Yearly Tide Calendars </h2>\n";
  Dstr yearurl ("/calendar/year/");
  yearurl += i;
  yearurl += ".html";
  add_time_control (TC_YEAR, top_p, yearurl, y, m, d);

  add_disclaimer (top_p);
  write (s, top_p.aschar(), top_p.length());
  end_page (s, 1);
}

static void
exact_location (int s, Dstr &filename, Dstr &loc)
{
  unsigned long i, count = 0;
  long match = -1;
  StationIndex *si = context->stationIndex();
  for (i=0; i<si->length(); i++)
  {
    	if ((*si)[i]->name %= loc)
	{
		if(match == -1)
			match = i;
		else
			match = -2;
      	}
      	count++;
  }

  Dstr top_p ("\
HTTP/1.0 200 OK\n\
MIME-version: 1.0\n\
Content-type: text/html\n\
\n\
<html>\n\
<head><title> Exact Query Error </title></head>\n<body bgcolor=\"FFFFFF\">\n<center>\n\
<h1> Exact Query Error </h1></center>\n");

  switch(match)
  {
	case -1:	// no match
		top_p += "<p>No locations matched your query.</p>";
		break;

	case -2:	// more than one match
		top_p += "<p>More than one location matched your query.</p>\n";
		break;

	default:	// clear hit
  		load_location_page(s, filename, (unsigned long)match);
		return;
  }
  write (s, top_p.aschar(), top_p.length());
  end_page (s);
}

static void
badclientlocation (Dstr &filename) {
  log ("Bad client location: ", filename, LOG_NOTICE);
}

static void
rangeerror (Dstr &filename) {
  log ("Bad client location (range error): ", filename, LOG_NOTICE);
}

static void
location_page (int s, Dstr &filename) {
  unsigned long i;
  Dstr loc(filename);
  loc /= strlen("/locations/");
  if(!isdigit(loc[0]))
  {
	exact_location (s, filename, loc);
	return;
  }

  if (sscanf (loc.aschar(), "%lu.html", &i) != 1) {
    badclientlocation (filename);
    notfound_barf (s);
  }

  StationIndex *si = context->stationIndex();
  if (i >= si->length()) {
    rangeerror (filename);
    notfound_barf (s);
  }
  load_location_page(s, filename, i);
}

static void
calendar (int s, Dstr &filename) {
  unsigned long i;
  int isyear = 0;
  if (sscanf (filename.aschar(), "/calendar/month/%lu.html", &i) != 1) {
    isyear = 1;
    if (sscanf (filename.aschar(), "/calendar/year/%lu.html", &i) != 1) {
      badclientlocation (filename);
      notfound_barf (s);
    }
  }

  StationIndex *si = context->stationIndex();
  if (i >= si->length()) {
    rangeerror (filename);
    notfound_barf (s);
  }
  Station *st = (*si)[i]->load (context);

  Dstr top_p ("\
HTTP/1.0 200 OK\n\
MIME-version: 1.0\n\
Content-type: text/html\n\
\n\
<html>\n\
<head><title> ");
  top_p += st->name;
  top_p += "</title></head>\n<body bgcolor=\"FFFFFF\">\n";

  Dstr tc_out;
  Timestamp start_tm = parse_time_control (filename, st->timeZone,
    context->settings, tc_out);
  struct tm *starttm = start_tm.get_tm (st->timeZone, context->settings);
  unsigned y = starttm->tm_year + 1900;
  unsigned m = starttm->tm_mon + 1;

  Timestamp end_tm;
  {
    char temp[80];
    if (isyear)
      sprintf (temp, "%4u-01-01 00:00", y);
    else
      sprintf (temp, "%4u-%02u-01 00:00", y, m);
    start_tm = Timestamp (temp, st->timeZone, context->settings);
    if (isyear)
      sprintf (temp, "%4u-01-01 00:00", y+1);
    else
      sprintf (temp, "%4u-%02u-01 00:00", y, m+1);
    end_tm = Timestamp (temp, st->timeZone, context->settings) - Interval(1);
  }

  if (!zoneinfo_doesnt_suck) {
    top_p += "<p> Warning:  this host machine is using an obsolete time zone\n\
database.&nbsp; Summer Time (Daylight Savings Time) adjustments will not be done\n\
for some locations. </p>\n";
  }

  top_p += "<p>\n";
  Dstr text_out;
  context->calendarMode (st, start_tm, end_tm, text_out, 1, 0);
  top_p += text_out;
  top_p += "</P>\n";

  add_disclaimer (top_p);
  write (s, top_p.aschar(), top_p.length());
  end_page (s, 1);
}

static void
purecppimage (int s) {
  Dstr top_p
    ("HTTP/1.0 200 OK\nMIME-version: 1.0\nContent-type: image/png\n\n");
  write (s, top_p.aschar(), top_p.length());
  write (s, pcpp, pcpplen);
  close (s);
  exit (0);
}

static void
graphimage (int s, Dstr &filename) {
  unsigned long i;
  if (sscanf (filename.aschar(), "/graphs/%lu.png", &i) != 1) {
    badclientlocation (filename);
    notfound_barf (s);
  }

  StationIndex *si = context->stationIndex();
  if (i >= si->length()) {
    rangeerror (filename);
    notfound_barf (s);
  }
  Station *st = (*si)[i]->load (context);

  Dstr tc_out;
  Timestamp start_tm = parse_time_control (filename, st->timeZone,
    context->settings, tc_out);

  Dstr top_p
    ("HTTP/1.0 200 OK\nMIME-version: 1.0\nPragma: no-cache\nContent-type: image/png\n\n");
  write (s, top_p.aschar(), top_p.length());

  RGBGraph g (context->settings->gw, context->settings->gh, context->colors);
  g.drawTides (st, start_tm);
  png_socket = s;  // See externC.cc
  g.writeAsPNG (socket_write_data_fn);
  close (s);
  exit (0);
}

static void
zones (int s, Dstr &filename) {
  Dstr zone(filename);
  zone /= strlen("/zones/");
  Dstr title;
  ZoneIndex::dnode *dn;
  if (zone.length()) {
    dn = zi[zone];
    if (!dn) {
      log ("Bad zone: ", filename, LOG_NOTICE);
      notfound_barf (s);
    }
    title = "Zone ";
    title += zone;
  } else {
    title = "Zone Index";
    dn = zi.top;
  }

  Dstr top_p ("\
HTTP/1.0 200 OK\n\
MIME-version: 1.0\n\
Content-type: text/html\n\
\n\
<html>\n\
<head><title> ");
  top_p += title;
  top_p += "</title></head>\n<body bgcolor=\"FFFFFF\">\n<center><h1> ";
  top_p += title;
  top_p += " </h1></center>\n";

  if (dn->subzones) {
    ZoneIndex::dnode *sn;
    if (zone.length())
      sn = dn->subzones;
    else
      sn = dn;
    top_p += "\
<p> Most zones consist of a region followed by a city name.&nbsp; Choose the\n\
zone that matches the country and time zone of the location that you want.&nbsp;\n\
For example:  places on the east coast of the U.S. are in zone\n\
:America/New_York; places in New Brunswick, Canada are in zone\n\
:America/Halifax.</p><ul>\n";
    while (sn) {
      top_p += "<li><a href=\"/zones/";
      top_p += sn->name;
      top_p += "\">";
      top_p += sn->name;
      top_p += "</a></li>\n";
      sn = sn->next;
    }
    top_p += "</ul>\n";
  }
  if (dn->il) {
    top_p += "<p> Click on any location to get tide predictions. </p>\n";
    struct ZoneIndex::indexlist *ix = dn->il;
    unsigned long i = 0;
    start_loclist (top_p);
    StationIndex *si = context->stationIndex();
    while (ix) {
      list_location (top_p, si, ix->i);
      if ((i % maxhtmltablen == 0) && (i != 0)) {
        end_loclist (top_p);
        start_loclist (top_p);
      }
      ix = ix->next;
      i++;
    }
    end_loclist (top_p);
  }
  if (zone.length()) {
    Dstr upzone(filename);
    upzone -= upzone.length()-1;
    upzone -= upzone.strrchr('/')+1;
    top_p += "<p> <a href=\"";
    top_p += upzone;
    top_p += "\">Back up</a></p>\n";
  }
  write (s, top_p.aschar(), top_p.length());
  end_page (s);
}

// Remove HTTP mangling from query string.
static void
demangle (Dstr &s, int sock) {
  Dstr buf;
  unsigned i = 0;
  while (i<s.length()) {
    if (s[i] == '+') {
      buf += ' ';
      i++;
    } else if (s[i] == '%') {
      char tiny[3];
      int temp;
      i++;
      tiny[0] = s[i++];
      tiny[1] = s[i++];
      tiny[2] = '\0';
      if (sscanf (tiny, "%x", &temp) != 1) {
        log ("Really nasty URL caught in demangle....", LOG_NOTICE);
        notfound_barf (sock);
      }
      buf += (char)temp;
    } else
      buf += s[i++];
  }
  s = buf;
}

static void
query (int s, Dstr &filename) {
  Dstr locq (filename);
  locq /= strlen("/query?location=");
  demangle (locq, s);

  // Strip leading whitespace
  while (locq.length())
    if (isspace (locq[0]))
      locq /= 1;
    else
      break;

  Dstr top_p ("\
HTTP/1.0 200 OK\n\
MIME-version: 1.0\n\
Content-type: text/html\n\
\n\
<html>\n\
<head><title> Query Results </title></head>\n<body bgcolor=\"FFFFFF\">\n<center>\n\
<h1> Query Results </h1></center>\n");

  unsigned long i, count = 0;
  StationIndex *si = context->stationIndex();
  for (i=0; i<si->length(); i++) {
    if ((*si)[i]->name %= locq) {
      if (count == 0) {
        top_p += "<p>Locations matching \"";
        top_p += locq;
        top_p += "\":</p><p>\n";
        start_loclist (top_p);
      }
      list_location (top_p, si, i);
      if ((count % maxhtmltablen == 0) && (count != 0)) {
        end_loclist (top_p);
        start_loclist (top_p);
      }
      count++;
    }
  }
  if (count)
    end_loclist (top_p);
  else {
    // Try harder.
    for (i=0; i<si->length(); i++) {
      if ((*si)[i]->name.strcasestr (locq) != -1) {
	if (count == 0) {
          top_p += "<p> Regular query found no matches; using more aggressive (substring) query. </p>\n";
	  top_p += "<p>Locations matching \"";
	  top_p += locq;
	  top_p += "\":</p><p>\n";
	  start_loclist (top_p);
	}
	list_location (top_p, si, i);
	if ((count % maxhtmltablen == 0) && (count != 0)) {
	  end_loclist (top_p);
	  start_loclist (top_p);
	}
	count++;
      }
    }
    if (count)
      end_loclist (top_p);
    else
      top_p += "<p> No locations matched your query.&nbsp; However, that might\n\
just mean that something is spelled strangely in the XTide database.&nbsp; To\n\
make sure that you aren't missing a location that is actually in there,\n\
you should check the indexes linked below.</p>\n";
  }
  write (s, top_p.aschar(), top_p.length());
  end_page (s);
}

static void
log_hits (struct sockaddr *addr) {
  Dstr msg;
  switch (addr->sa_family) {
  case AF_INET:
    {
      struct sockaddr_in *u = (struct sockaddr_in *)addr;
      unsigned long a = u->sin_addr.s_addr;
      char *c =
        // Archaic SunOS syntax:
        // inet_ntoa (&a);
        inet_ntoa (u->sin_addr);
      msg = c;
      msg += "  ";
      struct hostent *hp;
      if ((hp = gethostbyaddr ((char *)(&a), sizeof a, AF_INET)) == NULL)
        msg += "(?)";
      else
        msg += hp->h_name;
    }
    break;
  default:
    msg = "Non-Internet address (?)";
  }
  log (msg, LOG_INFO);
}

static void 
robots (int s) {
  Dstr top_p ("\
HTTP/1.0 200 OK\n\
MIME-version: 1.0\n\
Content-type: text/plain\n\
\n\
User-agent: *\n\
Disallow: /\n");

  write (s, top_p.aschar(), top_p.length());
  close (s);
  exit (0);
}

static void
handle_request (struct sockaddr *addr, int s) {
  char request[bufsize+1];
  Dstr buf, command, filename;

  log_hits (addr);

  // This will truncate long requests, but we generally won't lose
  // anything that matters.
  int len = read (s, request, bufsize); // Blah, blah, blah...

  if (len >= bufsize) {
    log ("Request too long", LOG_WARNING);
    toolong_barf (s);
  }
  request[len] = '\0';
  buf = request;

#ifdef SUPER_ULTRA_VERBOSE_DEBUGGING
  log ("-------------------------\n", request, LOG_DEBUG);
#endif

  buf /= command;
  if (command != "GET") {
    log ("Bad client command: ", command, LOG_NOTICE);
    unimp_barf (s);
  }

  buf /= filename;

  if (filename == "/")
    root_page (s);
  else if (filename == "/robots.txt")
    robots (s);
  else if (filename == "/index.html")
    index_page (s);
  else if (filename == "/tricks.html")
    tricks (s);
  else if (filename == "/purec++.png")
    purecppimage (s);
  else if (filename %= "/locations/")
    location_page (s, filename);
  else if (filename %= "/graphs/")
    graphimage (s, filename);
  else if (filename %= "/zones/")
    zones (s, filename);
  else if (filename %= "/calendar/")
    calendar (s, filename);
  else if (filename %= "/query?location=")
    query (s, filename);
  else {
    log ("Client tried to get ", filename, LOG_NOTICE);
    notfound_barf (s);
  }

  exit (0);
}

static void
dont_be_root() {
  struct passwd *nb = getpwnam ("nobody");
  if (nb) {
    if (setuid (nb->pw_uid) == 0)
      return;
    else
      xperror ("setuid");
  } else
    xperror ("getpwnam");
  log ("Can't set uid to 'nobody.'  Hope that's OK....", LOG_WARNING);
}

int main (int argc, char **argv)
{
  set_daemon_mode();
  pid_t fpid = fork();
  if (fpid == -1) {
    xperror ("fork");
    exit (-1);
  }
  if (fpid)
    exit (0);

  int listen_socket, new_socket, ts;
  unsigned short portnum = 80;
  fd_set rdset;
  FD_ZERO (&rdset);

  // The port number given to xttpd is not a "proper" command line
  // setting recognized by XTide and doesn't deserve to be, so
  // if we get one we hide it to keep CommandLineSettings from
  // blowing up.

  int portnum_evade = 0;
  if (argc >= 2) {
    if (sscanf (argv[1], "%hu", &portnum) != 1)
      portnum = 80;
    else
      portnum_evade = 1;
  }

  setup_socket (portnum, listen_socket);
  dont_be_root();
  FD_SET (listen_socket, &rdset);

  Settings settings;
  {
    ConfigDefaults cd;
    UserDefaults ud;
    CommandLineSettings cls (
      portnum_evade ? argc-1 : argc,
      portnum_evade ? &(argv[1]) : argv);
    settings.supersedeBy (cd);
    settings.supersedeBy (ud);
    settings.supersedeBy (cls);
  }

  context = new TideContext (
      portnum_evade ? argc-1 : argc,
      portnum_evade ? &(argv[1]) : argv,
      new Colors (settings), &settings);
  // Build the indices.
  zi.add (context->stationIndex());
  // Avoid issuing the zoneinfo warning a million times.
  {
    Timestamp nowarn((time_t)(time(NULL)));
    zoneinfo_doesnt_suck = nowarn.zoneinfo_doesnt_suck(&settings);
  }
  log ("Accepting connections.", LOG_NOTICE);

  ts = -1;
  struct sockaddr addr;
  while (1) {
    fd_set trdset, twrset, texset;
    trdset = rdset;
    // I seem to remember that some platforms barf if you provide
    // null pointers for wrset and exset; best to be safe.
    FD_ZERO (&twrset);
    FD_ZERO (&texset);
    ts = select (listen_socket+1, &trdset, &twrset, &texset, NULL);
    if (ts > 0) {
      // Type of length is set by configure.
      acceptarg3_t length = sizeof (addr);
      if ((new_socket = accept (listen_socket, &addr, &length)) != -1) {
        if (!fork())
          handle_request (&addr, new_socket);
        close (new_socket);
      }
    }
    // Clean up zombies.
    while (waitpid (-1, NULL, WNOHANG|WUNTRACED) > 0);
  }

  exit (0);
}