summaryrefslogtreecommitdiffstats
path: root/kpf/src/Server.cpp
blob: 00904132da831aeb58b7fa54eccba126a85bfc8b (plain)
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
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
/*
  KPF - Public fileserver for KDE

  Copyright 2001 Rik Hemsley (rikkus) <rik@kde.org>

  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files (the "Software"), to
  deal in the Software without restriction, including without limitation the
  rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  sell copies of the Software, and to permit persons to whom the Software is
  furnished to do so, subject to the following conditions:

  The above copyright notice and this permission notice shall be included in
  all copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
  AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
  ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

#include "Defines.h"
#include "DirectoryLister.h"
#include "WebServer.h"
#include "Server.h"
#include "ServerPrivate.h"
#include "Utils.h"

#undef KPF_TRAFFIC_DEBUG

namespace KPF
{
  static const uint IncomingDataLimit = 8 * 1024;     // kB.
  static const uint Timeout           = 60 * 1000;    // seconds.
  static const uint MaxKeepAlive      = 20;           // transactions.

  Server::Server
    (
     const TQString  & dir,
     bool             followSymlinks,
     int              socket,
     WebServer        * tqparent
    )
    : TQObject(tqparent, "Server")
  {
    d = new Private;

    kpfDebug << "New server: " << d->id << endl;

    d->dir = dir;

    d->followSymlinks = followSymlinks;

    d->birth = TQDateTime::tqcurrentDateTime();

    d->socket.setSocket(socket);

    connect(&(d->socket), TQT_SIGNAL(readyRead()), this, TQT_SLOT(slotReadyRead()));

    connect
      (
       &(d->socket),
       TQT_SIGNAL(bytesWritten(int)),
       TQT_SLOT(slotBytesWritten(int))
      );

    connect
      (
       &(d->socket),
       TQT_SIGNAL(connectionClosed()),
       TQT_SLOT(slotConnectionClosed())
      );

    connect
      (
       &(d->idleTimer),
       TQT_SIGNAL(timeout()),
       TQT_SLOT(slotTimeout())
      );

    connect
      (
       &(d->readTimer),
       TQT_SIGNAL(timeout()),
       TQT_SLOT(slotRead())
      );

    // If nothing happens for a bit, cancel ourselves.

    d->idleTimer.start(Timeout, true);
  }

  Server::~Server()
  {
    delete d;
    d = 0;
  }

    void
  Server::slotReadyRead()
  {
    kpfDebug << d->id << ":slotReadyRead" << endl;

    // DoS protection.

    d->dataRead += static_cast<uint>(d->socket.bytesAvailable());

    if (d->dataRead > IncomingDataLimit)
    {
      kpfDebug
        << d->id
        << ": Read would breach limit. Assuming DoS -> finished"
        << endl;

      setFinished(NoFlush /* Don't bother flushing socket */);
      return;
    }

    // Reset idle timer.

    d->idleTimer.start(Timeout, true);

    // Read all available data to incomingLineBuffer.

    while (d->socket.canReadLine())
    {
      kpfDebug << d->id << ": socket.canReadLine" << endl;

      TQString line(d->socket.readLine().stripWhiteSpace());

#ifdef KPF_TRAFFIC_DEBUG
      kpfDebug
        << d->id
        << ": Adding line to incomingLineBuffer: "
        << line
        << endl;
#endif

      d->incomingLineBuffer.append(line);
    }

    if (!d->incomingLineBuffer.isEmpty())
    {
      kpfDebug
        << d->id
        << ": incomingLineBuffer isn't empty - calling slotRead directly"
        << endl;

      slotRead();
    }
    else
    {
      kpfDebug
        << d->id
        << ": incomingLineBuffer is empty. Nothing to do."
        << endl;
    }
  }

    void
  Server::slotRead()
  {
    kpfDebug << d->id << ": slotRead" << endl;

    if (d->incomingLineBuffer.isEmpty())
    {
      kpfDebug << d->id << ": incomingLineBuffer is empty !" << endl;
      return;
    }

    // There is data available in incomingLineBuffer.

    switch (d->state)
    {
      case WaitingForRequest:
        kpfDebug << d->id << ": I was waiting for a request" << endl;
        (void) readRequest(d->incomingLineBuffer.first());
        d->incomingLineBuffer.remove(d->incomingLineBuffer.begin());
        break;

      case WaitingForHeaders:
        kpfDebug << d->id << ": I was waiting for headers" << endl;
        readHeaders();
        break;

      case Responding:
      case Finished:
      default:
        kpfDebug << d->id << ": I was responding or finished" << endl;
        break;
    }
  }

    bool
  Server::readRequest(const TQString & line)
  {
    ++d->requestCount;

#ifdef KPF_TRAFFIC_DEBUG
    kpfDebug
      << d->id
      << ": (request #" << d->requestCount << ") readRequest: `"
      << line << "'" << endl;
#endif

    TQStringList l(TQStringList::split(' ', line));

    // A request usually looks like TQT_METHOD PATH PROTOCOL but we don't
    // require PROTOCOL - we just assume HTTP/0.9 and act accordingly.

    if (l.count() == 2)
    {
      kpfDebug << d->id << ": readRequest: HTTP/0.9 ???" << endl;
      emit(request(this));
      d->state = Responding;
      respond(400);
      emit(readyToWrite(this));
      return false;
    }

    // The Request object handles setting parsing the strings we pass it here.
    // It converts GET/HEAD/whatever to an enum, fixes up the path and
    // converts the protocol string to a number.

    d->request.setMethod    (l[0]);
    d->request.setPath      (l[1]);
    d->request.setProtocol  (l.count() == 3 ? l[2] : TQString());

    // Before we check the request, say we received it.

    emit(request(this));

    return checkRequest();
  }

    bool
  Server::checkRequest()
  {
    // We only handle TQT_METHOD of GET or HEAD.

    if (Request::Unsupported == d->request.method())
    {
      kpfDebug << d->id << ": readRequest: method unsupported" << endl;
      d->state = Responding;
      respond(501);
      emit(readyToWrite(this));
      return false;
    }

    // If there's .. or ~ in the path, we disallow. Either there's a mistake
    // or someone's trying to h@x0r us. I wouldn't have worried about ~
    // normally, because I don't do anything with it, so the resource would
    // simply not be found, but I'm worried that the TQDir/TQFile/TQFileInfo
    // stuff might try to expand it, so I'm not taking any chances.

    if (d->request.path().tqcontains("..") || d->request.path().tqcontains('~'))
    {
      kpfDebug << d->id << ": readRequest: bogus path" << endl;
      d->state = Responding;
      respond(403);
      emit(readyToWrite(this));
      return false;
    }

    if (d->request.protocol() > 1.1)
    {
      if (d->request.protocol() >= 2.0)
      {
        kpfDebug
          << d->id
          << ": readRequest: unsupported protocol major number"
          << endl;

        d->request.setProtocol(1, 1);

        d->state = Responding;
        respond(505);
        emit(readyToWrite(this));
        return false;
      }
      else
      {
        kpfDebug
          << d->id
          << ": readRequest: unsupported protocol minor number"
          << endl;

        d->request.setProtocol(1, 1);
      }
    }

    if (d->request.protocol() >= 1.0)
    {
      kpfDebug
        << d->id
        << ": readRequest: need to wait for headers now"
        << endl;

      if (d->request.protocol() > 1.0)
      {
        d->request.setPersist(true);
      }

      d->state = WaitingForHeaders;
      d->readTimer.start(0, true);
    }
    else
    {
      kpfDebug
        << d->id
        << ": readRequest: immediate response"
        << endl;

      d->state = Responding;
      prepareResponse();
      emit(readyToWrite(this));
      return true;
    }

    return true;
  }

    void
  Server::readHeaders()
  {
    kpfDebug << d->id << ": readHeaders" << endl;

    // Pop lines from front of incomingLineBuffer and add to
    // incomingHeaderLineBuffer until we reach the end of the headers, when we
    // generate a response to the request.

    while (!d->incomingLineBuffer.isEmpty())
    {
      // This would be cleaner if there was a TQValueQueue.
      // Basically we 'dequeue' the first line from incomingHeaderBuffer.

      TQString line(d->incomingLineBuffer.first());
      d->incomingLineBuffer.remove(d->incomingLineBuffer.begin());

      // Unless the line is empty, this is (in theory) a header.

      if (!line.isEmpty())
      {
        kpfDebug << d->id << ": Header line: " << line << endl;
        d->incomingHeaderLineBuffer << line;
      }
      else
      {
        kpfDebug << d->id << ": Blank line - end of headers" << endl;

        // We have a buffer filled with all the header data received.
        // First parse those headers.

        d->request.parseHeaders(d->incomingHeaderLineBuffer);

        // Clear out the buffer because we won't need to use it again
        // and leaving all that data in memory is pointless.

        d->incomingHeaderLineBuffer.clear();

        // We've parsed the headers so the next thing we do is respond.

        d->state = Responding;
        prepareResponse();

        // When the response has been prepared, we're ready to write
        // some data back into that socket.

        kpfDebug << d->id << ": Ready to write" << endl;

        emit(readyToWrite(this));

        return;
      }
    }

    // Because we haven't found an empty line and therefore parsed
    // headers + returned, we must wait for more headers.

    kpfDebug
      << d->id
      << ": readHeaders: No lines left in header buffer."
      << " Setting state to WaitingForHeaders"
      << endl;

    d->state = WaitingForHeaders;
  }

    void
  Server::prepareResponse()
  {
    // The path to the requested resource is relative to our root.

    TQString filename = d->dir + '/' + d->request.path();

    kpfDebug << d->id << ": filename: " << filename << endl;

    d->resource.setPath(d->dir, d->request.path());

    if (!d->resource.exists())
    {
      kpfDebug << d->id << ": Resource doesn't exist: %s" << filename << endl;

      // No file ? Perhaps we should give a directory listing.

      if (!(/*d->generateDirectoryListings && */ d->request.path() == "/"))
      {
        // Either index.html wasn't the file requested, or we're not supposed
        // to generated listings.

        respond(404);
        return;
      }
    }

    if (!d->followSymlinks && d->resource.symlink())
    {
      // If we're not supposed to follow symlinks and there's a symlink
      // somewhere on the path, deny.

      respond(403);
      return;
    }

    if (!d->resource.readable())
    {
      // Deny even HEAD for unreadable files.

      respond(403);
      return;
    }

//    if ((Request::Get == d->request.method()) && !d->resource.open())
    // Open resource even if we're asked for HEAD. We need to ensure
    // Content-Length is sent correctly.

    if (!d->resource.open())
    {
      // Couldn't open the file. XXX why not ?

      respond(403);
      return;
    }

    if (d->request.haveRange())
    {
      // There was a byte range specified in the request so handleRange()
      // to check that the range makes sense for the requested resource.

      kpfDebug << d->id << ": Byte range in request" << endl;

      if (!handleRange(d->request.range()))
      {
        // handleRange() takes care of sending the necessary response.
        return;
      }
    }
    else
    {
      kpfDebug
        << d->id
        << "No byte range in request."
        << endl;

      if (d->request.haveIfModifiedSince())
      {
        // If we saw an If-Modified-Since header and the resource hasn't
        // been modified since that date, we respond with '304 Not modified'

        if (toGMT(d->resource.lastModified()) <= d->request.ifModifiedSince())
        {
          kpfDebug
            << d->id
            << "Got IfModifiedSince and will respond with 304 (unmodified)"
            << endl;

          respond(304);
          // We will not serve the file, so don't the size.
        }
        else
        {
          kpfDebug
            << d->id
            << "Got IfModifiedSince and will serve whole file (modified)"
            << endl;

          // We will serve the file, so set the size.
          d->fileBytesLeft = d->resource.size();
        }
      }
      else if (d->request.haveIfUnmodifiedSince())
      {
        // As above, except the logic is reversed.

        if (toGMT(d->resource.lastModified()) > d->request.ifUnmodifiedSince())
        {
          kpfDebug 
            << d->id
            << "Got IfUnmodifiedSince and will respond with 412 (modified)"
            << endl;

          respond(412);
          // We not serve the file, so don't set the size.
        }
        else
        {
          kpfDebug
            << d->id
            << "Got IfUnmodifiedSince and will serve whole file (unmodified)"
            << endl;

          // We will serve the file, so set the size.
          d->fileBytesLeft = d->resource.size();
        }
      }
      else
      {
        // We will serve the file, so set the size.
        d->fileBytesLeft = d->resource.size();
      }
 
      // If we haven't set the response up yet, that means we are not using a
      // special response due to a modification time condition. Therefore we
      // are doing the 'usual' 200 response.

      if (0 == d->response.code())
        respond(200, d->fileBytesLeft);
    }

    kpfDebug
      << d->id
      << "Done setting up response. Code will be "
      << responseName(d->response.code())
      << endl;


    // Send some headers back to the client, but only if the protocol
    // they asked us to use is new enough to require this.

    if (d->request.protocol() >= 1.0)
    {
      writeLine("Server: kpf");
      writeLine("Date: "            + dateString());
      writeLine("Last-Modified: "   + dateString(d->resource.lastModified()));
      writeLine("Content-Type: "    + d->resource.mimeType());

      // Generate a Content-Range header if we are sending partial content.

      if (206 == d->response.code())
      {
        TQString line = "Content-Range: bytes ";

        line += TQString::number(d->request.range().first());

        line += '-';

        if (d->request.range().haveLast())
          line += TQString::number(d->request.range().last());
        else
          line += TQString::number(d->resource.size() - 1);

        line += '/';

        line += TQString::number(d->resource.size());

        writeLine(line);
      }

      writeLine("Content-Length: "  + TQString::number(d->fileBytesLeft));
    }

    if (d->requestCount >= MaxKeepAlive && d->request.protocol() >= 1.1)
    {
      // We have made many transactions on this connection. Time to
      // give up and let the client re-connect. If we don't do this,
      // they could keep this connection open indefinitely.

      writeLine("Connection: close");
    }
    else if (d->request.protocol() == 1.0)
    {
      // wget seems broken. If it sends keep-alive, it hangs waiting for
      // nothing at all. Ignore its keep-alive request.
      writeLine("Connection: close");
    }
    else if (d->request.protocol() == 1.1) {
      writeLine("Connection: keep-alive");
    }

    // End of headers so send a newline.

    if (d->request.protocol() >= 1.0)
    {
      writeLine("");
    }
  }

    bool
  Server::handleRange(const ByteRange & r)
  {
    // Here we check if the given ByteRange makes sense for the
    // requested resource.

    // Is the range just plain broken ?

    if (!r.valid())
    {
      kpfDebug << d->id << ": Invalid byte range" << endl;
      respond(416);
      return false;
    }

    // Does the range start before the end of our resource ?

    else if (r.first() > d->resource.size())
    {
      kpfDebug << d->id << ": Range starts after EOF" << endl;
      respond(416);
      return false;
    }

    // Does the range end after the end of our resource ?

    else if (r.haveLast() && r.last() > d->resource.size())
    {
      kpfDebug << d->id << ": Range end after EOF" << endl;
      respond(416);
      return false;
    }

    // Ok, in theory the range should be satisfiable ...

    else
    {
      // ... but maybe we can't seek to the start of the range.

      if (!d->resource.seek(r.first()))
      {
        kpfDebug << d->id << ": Invalid byte range (couldn't seek)" << endl;
        // Should this be 501 ?
        respond(416);
        return false;
      }

      kpfDebug << d->id << ": Ok, setting fileBytesLeft" << endl;

      // Work out how many bytes are left to send to the client. Careful
      // with the off-by-one errors here, eh ?

      if (r.haveLast())
      {
        d->fileBytesLeft = r.last() + 1 - r.first();
      }
      else
      {
        d->fileBytesLeft = d->resource.size() - r.first();
      }

      kpfDebug << d->id << ": fileBytesLeft = "
        << d->fileBytesLeft << "d" << endl;

      respond(206, d->fileBytesLeft);
    }

    return true;
  }

    void
  Server::slotBytesWritten(int i)
  {
    // Don't you just love it when people forget 'unsigned' ?

    if (i > 0)
      d->bytesWritten += i;

    emit(output(this, i));

    // Reset idle timer.
    d->idleTimer.start(Timeout, true);
  }

    void
  Server::slotConnectionClosed()
  {
    kpfDebug << d->id << ": slotConnectionClosed -> finished" << endl;
    setFinished(Flush);
  }

    void
  Server::writeLine(const TQString & line)
  {
    // Fill a buffer. We're not allowed to send anything out until our
    // controller calls write().

    TQCString s(line.utf8() + "\r\n");

    d->headerBytesLeft      += s.length();
    d->outgoingHeaderBuffer += s;
  }

    void
  Server::cancel()
  {
    kpfDebug << d->id << ": cancel -> finished" << endl;
    setFinished(NoFlush);
  }

    void
  Server::respond(uint code, ulong fileSize)
  {
    // Set the code of our Response object.

    d->response.setCode(code);

    // Request from the Response object the text that should be sent
    // back to the client.

    TQCString s(d->response.text(d->request));

    // Tell our Response object how long it will be in total (it doesn't
    // know its total size until we tell it about the resource size.)

    d->response.setSize(s.length() + fileSize);

    // Tell the world we've finished setting up our response.

    emit(response(this));

    // Add the response text to the outgoing header buffer.

    d->headerBytesLeft      += s.length();
    d->outgoingHeaderBuffer += s;
  }

    void
  Server::setFinished(FlushSelect flushSelect)
  {
    if (Finished == d->state) // Already finished.
      return;

    d->state = Finished;

    kpfDebug
      << d->id
      << ": finished("
      << (Flush == flushSelect ? "flush" : "no flush")
      << ")"
      << endl;

    if (Flush == flushSelect)
      d->socket.flush();

    d->socket.close();

    d->death = TQDateTime::tqcurrentDateTime();

    emit(finished(this));
  }

    TQHostAddress
  Server::peerAddress() const
  {
    return d->socket.peerAddress();
  }

    ulong
  Server::bytesLeft() const
  {
    // Return the combined size of the two output buffers.

    return d->headerBytesLeft + d->fileBytesLeft;
  }

    ulong
  Server::write(ulong maxBytes)
  {
    // We must be in 'Responding' state here. If not, there's a problem
    // in the code.

    if (Responding != d->state)
    {
      kpfDebug << d->id << ": write() but state != Responding -> finished";
      setFinished(Flush);
      return 0;
    }

    // If the socket has been closed (e.g. the remote end hung up)
    // then we just give up.

    if (TQSocket::Connection != d->socket.state())
    {
      kpfDebug << d->id << ": Socket closed by client -> finished" << endl;
      setFinished(Flush);
      return 0;
    }

    kpfDebug << d->id << ": Response code is " << d->response.code() << " ("
      << responseName(d->response.code()) << ")" << endl;

    ulong bytesWritten = 0;

    // Write header data.

    ulong headerBytesWritten = 0;

    if (!writeHeaderData(maxBytes, headerBytesWritten))
    {
      return 0;
    }

    maxBytes      -= headerBytesWritten;
    bytesWritten  += headerBytesWritten;

    // If we are only sending headers (response code != 2xx or request type
    // was HEAD) or we reached the end of the file we were sending, give up.

    if (d->response.code() < 200 || d->response.code() > 299)
    {
      kpfDebug << d->id << ": We are only sending headers -> finished" << endl;

      // If we're sending 'Not modified' then we don't need to drop
      // the connection just yet.

      if (d->response.code() == 304 && d->request.persist())
      {
        kpfDebug
          << d->id
          << ": 304 and persist. Not dropping connection yet."
          << endl;

        reset();
      }
      else
      {
        setFinished(Flush);
      }

      return bytesWritten;
    }

    // Just HEAD ? Ok, then if we're set to persistent mode we go back
    // and wait for another request. Otherwise we're done and can go home.

    if (Request::Head == d->request.method())
    {
      if (d->request.persist())
      {
        reset();
      }
      else
      {
        setFinished(Flush);
      }

      return bytesWritten;
    }

    // If we've written our limit then wait until next time.

    if (0 == maxBytes)
    {
      return bytesWritten;
    }

    // Write resource data.

    ulong fileBytesWritten = 0;

    // writeFileData() returns true if the op was successful and also
    // returns the number of bytes written via the second parameter.

    if (!writeFileData(maxBytes, fileBytesWritten))
    {
      return 0;
    }

    kpfDebug << "Wrote " << fileBytesWritten << " from file" << endl;

    maxBytes      -= fileBytesWritten;
    bytesWritten  += fileBytesWritten;

    // Did we finish sending the resource data ?

    if (0 == d->fileBytesLeft)
    {
      kpfDebug << d->id << ": No bytes left to write. Closing file." << endl;

      d->resource.close();

      // If we're in persistent mode, don't quit just yet.

      if (d->requestCount < MaxKeepAlive && d->request.persist())
      {
        kpfDebug
          << d->id
          << ": Request included Keep-Alive, so we set state"
          << " to WaitingForRequest and don't send finished()"
          << endl;

        reset();
      }
      else
      {
        kpfDebug
          << d->id
          << ": No keep-alive or hit MaxKeepAlive, so finished."
          << endl;

        setFinished(Flush);
      }
    }
    else
    {
      // Ok, we have some data to send over the socket. Tell the world.

      kpfDebug
        << d->id
        << "Still have data left to send."
        << endl;

      emit(readyToWrite(this));
    }

    return bytesWritten;
  }


    bool
  Server::writeHeaderData(ulong max, ulong & bytesWritten)
  {
    // Is there some header data left to write ?

    if (0 == d->headerBytesLeft)
      return true;

    // Calculate where to start reading from the buffer.

    uint headerPos =
      d->outgoingHeaderBuffer.length() - d->headerBytesLeft;

    // Calculate how many bytes we should write this session.

    uint bytesToWrite = min(d->headerBytesLeft, max);

    // Calculate how many bytes we _may_ write.

    bytesToWrite = min(bytesToWrite, d->socket.outputBufferLeft());

    // Get a pointer to the data, offset by the position we start reading.

    char * data = d->outgoingHeaderBuffer.data() + headerPos;

    // Write the data, or at least as much as the socket buffers will
    // take, and remember how much we wrote.

    int headerBytesWritten = d->socket.writeBlock(data, bytesToWrite);

    // <rant>
    //   Using -1 to signal an error is fucking evil.
    //   Return false instead or add a 'bool & ok' parameter.
    //   If you're not going to use exceptions, at least don't use
    //   crap C conventions for error handling.
    // </rant>

    if (-1 == headerBytesWritten)
    {
      // Socket error.

      kpfDebug << d->id << ": Socket error -> finished" << endl;
      setFinished(Flush);
      return false;
    }

#ifdef KPF_TRAFFIC_DEBUG
    kpfDebug
      << d->id
      << ": Wrote header data: `"
      << d->outgoingHeaderBuffer.left(headerPos)
      << "'"
      << endl;
#endif

    // Subtract the number of bytes we wrote from the number of bytes
    // left to write.

    bytesWritten        += headerBytesWritten;
    d->headerBytesLeft  -= headerBytesWritten;

    // We may be doing a long file send next, so clear the header buffer
    // because we don't need that data hanging around in memory anymore.

    if (0 == d->headerBytesLeft)
      d->outgoingHeaderBuffer.resize(0);

    return true;
  }

    bool
  Server::writeFileData(ulong maxBytes, ulong & bytesWritten)
  {
    // Nothing left in the file ?

    if (d->resource.atEnd())
    {
      d->resource.close();
      kpfDebug << d->id << ": file at end -> finished" << endl;
      setFinished(Flush);
      return false;
    }

    // Calculate how much data we may write this session.
    // If none, give up.

    uint bytesToWrite = min(d->fileBytesLeft, maxBytes);

    if (0 == bytesToWrite)
      return true;

    bytesToWrite = min(bytesToWrite, d->socket.outputBufferLeft());

    TQByteArray a(bytesToWrite);

    if (0 == bytesToWrite)
      return true;

    // Read some data (maximum = bytesToWrite) from the file.

    int fileBytesRead = d->resource.readBlock(a.data(), bytesToWrite);

    // Write that data to the socket and remember how much was actually
    // written (may be less than requested if socket buffers are full.)

    int fileBytesWritten = d->socket.writeBlock(a.data(), fileBytesRead);

    // Was there an error writing to the socket ?

    if (-1 == fileBytesWritten)
    {
      // Socket error.
      kpfDebug << d->id << ": Socket error -> finished" << endl;
      d->resource.close();
      setFinished(Flush);
      return false;
    }

#ifdef KPF_TRAFFIC_DEBUG
    kpfDebug
      << d->id
      << ": Wrote file data: `"
      << TQCString(a.data(), fileBytesWritten)
      << "'"
      << endl;
#endif

    // We should have been able to write the full amount to the socket,
    // because we tested d->socket.outputBufferLeft(). If we didn't
    // manage to write that much, either we have a bug or TQSocket does.

    if (fileBytesWritten < fileBytesRead)
    {
      kpfDebug << d->id << ": Short write !" << endl;
      d->resource.close();
      setFinished(Flush);
      return false;
    }

    // Subtract the amount of bytes written from the number left to write.

    bytesToWrite      -= fileBytesWritten;
    bytesWritten      += fileBytesWritten;
    d->fileBytesLeft  -= fileBytesWritten;

    return true;
  }

    void
  Server::slotTimeout()
  {
    kpfDebug << d->id << ": Timeout -> finished" << endl;
    setFinished(NoFlush);
  }

    Request
  Server::request() const
  {
    return d->request;
  }

    Response
  Server::response() const
  {
    return d->response;
  }

    ulong
  Server::output() const
  {
    return d->bytesWritten;
  }

    Server::State
  Server::state() const
  {
    return d->state;
  }

    TQDateTime
  Server::birth() const
  {
    return d->birth;
  }

    TQDateTime
  Server::death() const
  {
    return d->death;
  }

    void
  Server::reset()
  {
    kpfDebug << d->id << ": Resetting for another request" << endl;

    d->request  .clear();
    d->response .clear();
    d->resource .clear();

    d->state = WaitingForRequest;
    d->readTimer.start(0, true);
  }

} // End namespace KPF

#include "Server.moc"
// vim:ts=2:sw=2:tw=78:et