summaryrefslogtreecommitdiff
path: root/lib/HttpServ.cc
blob: 7b757a992771b5aa54c6030b19198bbd9a7a6568 (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
/*
 *  Baltisot
 *  Copyright (C) 1999-2008 Nicolas "Pixel" Noble
 *
 *  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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

#include <vector>

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "Socket.h"
#include "Action.h"
#include "HttpServ.h"
#include "Buffer.h"
#include "ReadJob.h"
#include "CopyJob.h"
#include "ChainTasks.h"
#include "Task.h"
#include "Base64.h"
#include "Domain.h"
#include "HashFunction.h"
#include "gettext.h"

#define MAXLEN 4*1024*1024

/*
 stuff we should support...
 
 Etags:
  Server: ETag: "27b42a-134-46cece08"
  Client: If-None-Match: "27b42a-146-46cecd32"
 
 Last-Modified: 
  Server: Last-Modified: Fri, 24 Aug 2007 12:24:40 GMT
  Client: If-Modified-Since: Fri, 24 Aug 2007 12:21:06 GMT
  
 Multipart stuff:

----8<-----Example-------8<--------
Content-Type: multipart/form-data; boundary=---------------------------163944935918044553841983937859
Content-Length: 377

-----------------------------163944935918044553841983937859
Content-Disposition: form-data; name="textline"


-----------------------------163944935918044553841983937859
Content-Disposition: form-data; name="datafile"; filename="tst-user-agent.txt"
Content-Type: text/plain

User-Agent: CFNetwork/129.20

-----------------------------163944935918044553841983937859--
----8<-----Example-------8<--------

*/
  
  

String endhl = "\r\n", endnl = "\n";

struct multipart_file {
      multipart_file(Buffer * _file, const String & _type, const String & _filename, const String & _varname) : file(_file), type(_type), filename(_filename), varname(_varname) { }
      ~multipart_file() { }
    Buffer * file;
    String type, filename, varname;
};

typedef std::vector<struct multipart_file> multipart_files;

class ProcessRequest : public Task {
  public:
      ProcessRequest(Action * action, const Socket & out, const String & server_name, int server_port, const String & root = "/bin/start");
      virtual ~ProcessRequest();
    virtual String GetName();
  protected:
    virtual int Do() throw (GeneralException);
  private:
    String GetMime(const String &);
    String UnMangle(const String &, int p = 0);
    bool ParseUri(String &, String &, String &, Handle *);
    void ParseVars(Handle *, int);
    void ParseMultipart(Handle *, int);
    void ShowError(Handle *);
    void SendHeads(Handle *, const String &, const String & = "", time_t = -1);
    void SendRedirect(Handle *);

    String file, domain, t, Method, Uri;
    Buffer b;
    Task * c, * a;
    Action * f;
    int len, localport;
    Action * p;
    Socket s;
    Domain * d;
    
    multipart_files m_files;
    
    String name, host, gvars, login, password, root, boundary;
    Variables * Vars, * Heads;
    bool bad, hasvars, post, multipart, content_type;
    
    HttpResponse response;
};

ProcessRequest::ProcessRequest(Action * ap, const Socket & as, const String & aname, int aport, const String & aroot) : localport(aport), p(ap), s(as), name(aname), root(aroot) {
    SetBurst();
}

ProcessRequest::~ProcessRequest() {
    std::vector<struct multipart_file>::iterator i;
    
    for (i = m_files.begin(); i != m_files.end(); i++) {
        delete i->file;
    }
}

String ProcessRequest::GetName() {
    return _("Processing HTTP request");
}

int ProcessRequest::Do() throw(GeneralException) {
    switch (current) {
    case 0:
        if (!s.IsConnected()) return TASK_DONE;

        c = new ReadJob(&s, &b);
        WaitFor(c);
	current = 1;
        Suspend(TASK_ON_HOLD);

    case 1:
        delete c;

        bad = false;

//	std::cerr << "---- Got a request from handle " << s.GetHandle() << " \n";
    
        post = ParseUri(file, domain, gvars, &b);
	
	Heads = new Variables();
	Vars = new Variables();

        len = -1;
        content_type = false;
        do {
	    int p;
    	    b >> t;
//	    std::cerr << "Read Request (n): " << t << std::endl;
	    if ((t.strstr("Content-Length: ") == 0) || (t.strstr("Content-length: ") == 0)) {
//		std::cerr << "Saw 'Content-Lenght:', reading length from '" << t.extract(16) << "'\n";
	        len = t.extract(16).to_int();
                if (len > MAXLEN)
                    len = -1;
	    }
	    if (t.strstr("Host: ") == 0) {
		host = t.extract(6);
	    }
            if (t.strstr("Authorization: Basic ") == 0) {
                int l;
                char * credentials = (char *) Base64::decode(t.extract(21), &l);
                credentials[l] = 0;
                char * p = strchr(credentials, ':');

                if (p) {
                    *p = 0;
                    login = credentials;
                    password = p + 1;
                }
                
                free(credentials);
            }
            if (t.strstr("Content-Type: application/x-www-form-urlencoded") == 0) {
                // basic post method
                multipart = false;
                content_type = true;
            }
            if (t.strstr("Content-Type: multipart/form-data; boundary=") == 0) {
                multipart = true;
                content_type = true;
                boundary = "--" + t.extract(44);
            }
	    
	    if ((p = t.strchr(':')) >= 0) {
		String s = t.extract(0, p - 1);
		s += '=';
		s += t.extract(p + 2);
		Heads->Add(s);
	    }
	} while (t.strlen());
	
//	std::cerr << "---- Processing it.\n";

        hasvars = false;

	if (post) {
	    // On a pas eu de ligne 'Content-Length' mais on a eu une méthode POST.
	    // Cela est une erreur.
	    if (len == -1) {
//		std::cerr << "Error: method POST but no Content-Length\n";
		bad = true;
	    } else {
//		std::cerr << "Got a POST request. Parsing variables. (len = " << len << ")\n";
	        // Les variables seront initialisées ici.
		hasvars = true;
	    }
            
            if (!content_type) {
                bad = true;
            }
	}

	current = 2;
	if (hasvars && len) {
	    c = new CopyJob(&s, &b, len);
	    WaitFor(c);
	    Suspend();
        } else {
	    c = 0;
	}

    case 2:
	if (gvars != "") {
	    Buffer b2;
	    b2 << gvars;
	    ParseVars(&b2, gvars.strlen());
	}
	if (hasvars && len) {
            delete c;
            if (!multipart) {
	        ParseVars(&b, len);
            } else {
                ParseMultipart(&b, len);
            }
	}
    
	printm(M_INFO, " Domain = '" + domain + "' - File = '" + file + "'\n");

        if (file == "favicon.ico") {
            domain = "/image";
        }

        regmatch_t pmatches[MAX_MATCHES];
	
        if (!bad) {
	    // Nous vérifions le domaine.
	    bad = true;
	    // Les domaines par défaut valides sont '/', '/bin' et '/image'.
	    if (domain == "/image") bad = false;
	    if (domain == "/bin") bad = false;
	    if (domain == "/") bad = false;
    	    // L'url sans domaine ni fichier est valide. (cela arrive sur certains navigateurs...)
            if (domain == "") bad = (file != "");
            if ((d = Domain::find_domain(Uri, MAX_MATCHES, pmatches))) bad = false;
	    if (bad) {
	        printm(M_INFO, _("Error: bad domain.\n"));
	    }
	}

        a = 0;

	if (bad) {
	    ShowError(&b);
	} else {
	    if (d) {
                HttpRequest request;
                request.vars = Vars;
                request.headers = Heads;
                request.uri = Uri;
                request.login = login;
                request.password = password;
		request.lip = s.GetAddr();
		request.dip = s.GetDistantAddr();
		request.lport = s.GetPort();
		request.dport = s.GetDistantPort();
                request.method = Method;
                memcpy(request.pmatches, pmatches, sizeof(regmatch_t) * MAX_MATCHES);
                d->Do(request, &response);
                a = response.BuildResponse(&s);
	    } else if (((domain == "") || (domain == "/")) && (file == "")) {
		// Si le navigateur a demandé l'URL '/', alors on renvoie une notification
		// de redirection.
		SendRedirect(&b);
	    } else if (domain == "/bin") {
		// Le domaine 'bin' est réservé aux actions. On cherche donc l'action à effectuer.
	        if ((f = p->Look4URL(file))) {
    		    SendHeads(&b, "text/html");
		    a = f->Do(Vars, Heads, &s);
		} else {
		    ShowError(&b);
	        }
	    } else if (domain == "/image") {
		// Dans tous les autres cas de domaine, on cherche le fichier dans le répertoire data.
	        // On utilise try au cas où le fichier n'existe pas et donc que le constructeur
	        // d'input renvoie une erreur.
	        try {
	    	    Handle * i = new Input(String("data/") + file);
	    	    SendHeads(&b, GetMime(file), String("Accept-Ranges: bytes") + endhl + "Content-Length: " + (unsigned long long int) i->GetSize() + endhl, i->GetModif());
		    i->SetNonBlock();
		    a = new CopyJob(i, &s);
		    printm(M_INFO, _("File found, dumping.\n"));
		}
	        catch (IOGeneral e) {
		    ShowError(&b);
		    printm(M_INFO, _("File not found, error shown.\n"));
		}
            } else {
                ShowError(&b);
            }
	}
    
	if (a) a->Stop();
    
//	std::cerr << "---- Sending header buffer.\n";
        if (!d) {
    	    c = new CopyJob(&b, &s, -1, false);
            WaitFor(c);
	    current = 3;
	    Suspend();
        }

    case 3:
        if (!d)
    	    delete c;
    
	if (a) {
//	    std::cerr << "---- Sending contents.\n";
	    a->Restart();
	    WaitFor(a);
	    current = 4;
	    Suspend();
	}

    case 4:
	if (a) delete a;
	delete Vars;
	delete Heads;
//	std::cerr << "---- End of Request.\n";
    }
    return TASK_DONE;
}

void ProcessRequest::ParseMultipart(Handle * s, int len) {
    String t, crboundary, k, v, disposition, type;
    char redo[256], r, tmp[4];
    int p, i, rl;
    bool done = false, in_headers = true, is_file = false;
    Buffer * out = 0;
    std::vector<struct multipart_file>::iterator mf_p;
    Variables * dispos_headers;
    
    crboundary = "\r\n" + boundary;
    
    redo[0] = p = 0;
    i = 1;
    while (i < crboundary.strlen()) {
        if (crboundary[i] == crboundary[p]) {
            redo[i++] = ++p;
        } else if (p > 0) {
            p = redo[p - 1];
        } else {
            redo[i++] = 0;
        }
    }

    p = 0;
    (*s) >> t;
    if (t != boundary) {
        return;
    }
    while (!done) {
        if (in_headers) {
            (*s) >> t;
            if (t != "") {
                // Content-Disposition: form-data; name="datafile"; filename="tst-user-agent.txt"
                // Content-Type: text/plain
                if (t.strstr("Content-Disposition: form-data; ") == 0) {
                    disposition = t.extract(32);
                    dispos_headers = new Variables();
                    // ****
                } else if (t.strstr("Content-Type: ") == 0) {
                    type = t.extract(14);
                } else {
                    printm(M_WARNING, "Unknown header in multipart chunk: " + t + "\n");
                }
            } else {
                in_headers = false;
                if ((type != "") && ((*dispos_headers)["filename"] != "")) {
                    is_file = true;
                    out = new Buffer();
                } else {
                    k = (*dispos_headers)["name"];
                }
            }
        } else {
            rl = 0;
            
            r = s->readU8();
            if (crboundary[p] == r) {
                p++;
                rl = 1;
            } else {
                for (i = 0; i <= p; i++) {
                    if (is_file) {
                        out->writeU8(crboundary[i]);
                    } else {
                        v += crboundary[i];
                    }
                }
                if (p > 0)
                    p = redo[p - 1];
            }
        
            if (p == crboundary.strlen()) {
                p = 0;
                tmp[0] = s->readU8();
                tmp[1] = s->readU8();
                
                if ((t[0] == 13) && (t[1] == 10)) {
                    in_headers = true;
                    
                    if (is_file) {
                        m_files.push_back(multipart_file(out, type, (*dispos_headers)["filename"], (*dispos_headers)["name"]));
                        out = 0;
                    } else {
                        Vars->Add(k + "=" + v);
                    }
                    
                    k = "";
                    v = "";
                    type = "";
                    delete dispos_headers;
                } else if ((tmp[0] == '-') && (tmp[1] == '-')) {
                    tmp[2] = s->readU8();
                    tmp[3] = s->readU8();
                    if ((tmp[2] == 13) && (tmp[3] == 10)) {                    
                        // end of streams
                        
                        if (is_file) {
                            m_files.push_back(multipart_file(out, type, (*dispos_headers)["filename"], (*dispos_headers)["name"]));
                            out = 0;
                        } else {
                            Vars->Add(k + "=" + v);
                        }
                        return;
                    } else {
                        rl = 4;
                    }
                } else {
                    rl = 2;
                }
            }
            
            for (i = 0; i < rl; i++) {
                if (is_file) {
                    out->writeU8(r);
                } else {
                    v += r;
                }
            
                r = tmp[0];
                tmp[0] = tmp[1];
                tmp[1] = tmp[2];
                tmp[2] = tmp[3];
            }
        }
    }
}

void ProcessRequest::ParseVars(Handle * s, int len) {
    String t, v;
    char conv[3], l;
    int hconv;
    bool end_of_string = false;
    ssize_t pos = 0, next;
    
    t = "";
    for (int i = 0; i < len; i++) {
	s->read(&l, 1);
	t += l;
    }
//  std::cerr << "Post variables line: '" << t << "'\n";
    
    while (!end_of_string) {
	// Les variables sont sous la forme 'var1=val1&var2=val2&val3=var3'. Donc on cherche le caractère
	// & dans la chaine POST.
	next = t.strchr('&', pos);
	if (next < 0) {
            next = t.strlen();
            end_of_string = true;
        }
	v = "";
	while (pos != next) {
	    switch (t[pos]) {
	    // Le navigateur encode les caractères spéciaux à l'aide du format %XX où XX indique
	    // la valeur hexadécimale du caractère. Nous encodons surtout les caractères
	    // ' ', '=', '%', et '/' avec cette technique.
	    case '%':
		pos++;
		conv[0] = t[pos++];
		conv[1] = t[pos++];
		conv[2] = '\0';
		sscanf(conv, "%x", &hconv);
		v += ((char) hconv);
		break;
	    // Certains navigateurs utilisent '+' pour indiquer ' ' (qui est illégal) au lieu
	    // d'utiliser %20.
	    case '+':
		v += ' ';
		pos++;
		break;
	    default:
    		v += t[pos++];
	    }
	}
//	std::cerr << "Pushing HTTP variable: " << v << std::endl;
	Vars->Add(v);
	pos++;
    }
}

/*
 * Cette fonction renverra true si la méthode est une méthode POST.
 * Les Strings domain et file seront modifiées afin de renvoyer le domaine
 * et le fichier lut. La string s doit donner la première ligne de la requète,
 * c'est à dire la méthode demandée par le client.
 */

bool ProcessRequest::ParseUri(String & file, String & domain, String & gvars, Handle * s) {
    String t;
    bool post = false;
    const char * p = 0;
    ssize_t sppos;

    *s >> t;
    printm(M_INFO, _("Read Request (1): ") + t + "\n");

    int IPos = t.strchr('?');
    
    gvars = "";
    
    if (IPos >= 0) {
	int HPos = t.strchr(' ', IPos);
	char * sdup = t.strdup(0, IPos - 1);
	gvars = t.extract(IPos + 1, HPos - 1);
	t = sdup;
	free(sdup);
    }
    
//  std::cerr << "New request: " << t << ", gvars = " << gvars << std::endl;
    
    bad = false;
    
    // p nous indiquera la position de la chaîne URL.
    switch (t[0]) {
    case 'P': /* POST? */
	if (t.extract(1, 4) == "OST ") {
    	    p = t.to_charp(5);
	    post = true;
	} else {
//	    std::cerr << "Error: unknow request.\n";
	    bad = true;
	}
        Method = "POST";
	break;
    case 'G': /* GET? */
	if (t.extract(1, 3) == "ET ") {
	    p = t.to_charp(4);
	} else {
//	    std::cerr << "Error: unknow request.\n";
	    bad = true;
	}
        Method = "GET";
	break;
    default:
//	std::cerr << "Error: unknow request.\n";
	bad = true;
        Method = "Unknown";
    }
    
    if (!bad) {
	ssize_t poshttp, posslash;
        Uri = p;
	sppos = Uri.strrchr(' ');
	Uri = Uri.extract(0, sppos - 1);
	// On enlève tout le host spécifié éventuellement dans la requete.
	if ((poshttp = Uri.strstr("http://")) > 0) {
	    Uri = Uri.to_charp(poshttp + 7);
	    posslash = Uri.strchr('/');
	    // Certains navigateurs indiqueront uniquement http://host comme URL.
	    if (posslash >= 0) {
		host = Uri.extract(0, posslash - 1);
		Uri = Uri.to_charp(posslash);
	    } else {
		host = Uri;
		Uri = "";
	    }
	}
        Uri = UnMangle(Uri);
	posslash = Uri.strrchr('/');
	file = Uri.to_charp(posslash + 1);
	if (posslash > 0) {
	    domain = Uri.extract(0, posslash - 1);
	} else {
	    domain = "";
	}
    }
    return post;
}

/*
 * Ceci sert à rediriger le navigateur vers l'url de démarrage.
 */
void ProcessRequest::SendRedirect(Handle * s) {
    *s << "HTTP/1.1 301 Moved Permanently" << endhl << 
	 "Server: " << name << endhl <<
	 "Location: http://" << host << root << endhl <<
	 "Cache-Control: no-cache" << endhl <<
	 "Connection: closed" << endhl <<
	 "Content-Type: text/html" << endhl << endhl <<
         p->GetSkinner()->Redirect("http://" + host + root);
}

/*
 * Nous envoyons les entetes de réponse HTTP.
 */

void ProcessRequest::SendHeads(Handle * s, const String & mime, const String & extra, time_t lm) {
    time_t t = time(NULL);
    struct tm * ft = gmtime(&t);
    char buf[1025];
    strftime(buf, 1024, "%a, %d %b %Y %H:%M:%S GMT", ft);
    *s << "HTTP/1.1 200 OK" << endhl <<
	  "Date: " << buf << endhl <<
	  "Server: " << name << endhl;
    if (lm >=0) {
	ft = gmtime(&lm);
	strftime(buf, 1024, "%a, %d %b %Y %H:%M:%S GMT", ft);
    }
    *s << "Last-Modified: " << buf << endhl << extra <<
	  "Connection: closed" << endhl << 
	  "Content-Type: " << mime << endhl << endhl;
}

/*
 * Affichage d'une erreur 404.
 */

void ProcessRequest::ShowError(Handle * s) {
    *s << "HTTP/1.1 404 Not Found" << endhl <<
          "Server: " << name << endhl <<    
          "Cache-Control: no-cache" << endhl <<   
          "Connection: closed" << endhl <<      
          "Content-Type: text/html" << endhl << endhl <<
          p->GetSkinner()->Error("");
}

/*
 * Sert à déterminer le type mime à partir de l'extension du fichier.
 * Par défaut, nous mettons "text/plain".
 */

String ProcessRequest::GetMime(const String & f) {
    String ext;
    size_t ppos;
    
    ppos = f.strrchr('.');
    
    if (ppos >= 0) {
	ext = f.extract(ppos + 1);
	if (ext == "jpg") return "image/jpeg";
	if (ext == "jpeg") return "image/jpeg";
	if (ext == "htm") return "text/html";
	if (ext == "html") return "text/html";
	if (ext == "gif") return "image/gif";
	if (ext == "png") return "image/png";
	if (ext == "class") return "application/octet-stream";
    }
    
    return "text/plain";
}

String ProcessRequest::UnMangle(const String & s, int p) {
    String r;
    char c1, c2, c[2] = "x";
    
    if (s.strlen() <= p)
        return "";
    
    switch (s[p]) {
    case '%':
        c1 = s[p + 1];
        c2 = s[p + 2];
        
        if ((((c1 >= '0') && (c1 <= '9')) || ((c1 >= 'A') && (c1 <= 'F')) || ((c1 >= 'a') && (c1 <= 'f'))) &&
            (((c2 >= '0') && (c2 <= '9')) || ((c2 >= 'A') && (c2 <= 'F')) || ((c2 >= 'a') && (c2 <= 'f')))) {
            if ((c1 >= '0') && (c1 <= '9')) c1 -= '0';
            if ((c2 >= '0') && (c2 <= '9')) c2 -= '0';
            if ((c1 >= 'A') && (c1 <= 'F')) c1 -= 'A' - 10;
            if ((c2 >= 'A') && (c2 <= 'F')) c2 -= 'A' - 10;
            if ((c1 >= 'a') && (c1 <= 'f')) c1 -= 'a' - 10;
            if ((c2 >= 'a') && (c2 <= 'f')) c2 -= 'a' - 10;
            c[0] = c1 * 16 + c2;
            r = c;
            p += 3;
        } else {
            r = "%";
            p++;
        }
        break;
    case '+':
        r = " ";
        p++;
        break;
    default:
        r = s[p];
        p++;
        break;
    }
    
    return r + UnMangle(s, p);
}

HttpServ::HttpServ(Action * ap, int port, const String & nname) throw (GeneralException) : root("/bin/start") {
    bool r = true;
    
    p = ap;
    name = nname;
    localport = port;
    
//  std::cerr << "Initialising Mini HTTP-Server on port " << localport << std::endl;
    
    r = Listener.SetLocal("", port);
    if (!r) {
	throw GeneralException(_("Initialisation of the Mini HTTP-Server failed: can't bind"));
    }
    
    r = Listener.Listen();
    
    if (!r) {
	throw GeneralException(_("Initialisation of the Mini HTTP-Server failed: can't listen"));
    }
    
    Listener.SetNonBlock();
    WaitFor(&Listener, W4_STICKY | W4_READING);
    
//  std::cerr << "Mini HTTP-Server '" << name << "' ready and listening for port " << port << std::endl;
}

HttpServ::~HttpServ(void) {
    Listener.close();
}

void HttpServ::SetRoot(const String & _root) {
    root = _root;
}

int HttpServ::Do() throw (GeneralException) {
    try {
	Socket s = Listener.Accept();
	s.SetNonBlock();
	new ProcessRequest(p, s, name, localport, root);
    }
    catch (GeneralException) {
    }
    return TASK_ON_HOLD;
}

String HttpServ::GetName() {
    return String("Mini HTTP-Server '") + name + "'";
}

class BuildHttpResponse : public Task {
  public:
      BuildHttpResponse(HttpResponse * _hr, Handle * _out) : hr(_hr), out(_out), file(0) { SetBurst(); }
      virtual ~BuildHttpResponse() { }
    virtual String GetName() { return "BuildHttpResponse"; }
    virtual int Do() throw (GeneralException) {
        Buffer * b;
        Handle * h;
        
        switch (current) {
        case 0:
            if (hr->Prepared()) {
                b = &hr->contents;
                current = 2;
            } else {
                if (hr->file_name != "") {
                    file = new Input(hr->file_name);
                    if (hr->last_modified < 0) {
                        hr->last_modified = file->GetModif();
                    }
                }
                b = new Buffer();
                hr->PrepareResponse(b);
                current = 1;
            }

            t = new CopyJob(b, out, -1, b != &hr->contents);
            WaitFor(t);
            Suspend(TASK_ON_HOLD);
        
        case 1:
            delete t;
            if (file) {
                h = file;
            } else {
                h = &hr->contents;
            }
            t = new CopyJob(h, out);
            WaitFor(t);
            current = 2;
            Suspend(TASK_ON_HOLD);
            
        case 2:
            delete t;
            if (file)
                delete file;
        }

        return TASK_DONE;
    }
  private:
    HttpResponse * hr;
    Handle * out;
    Input * file;
    Task * t;
};

HttpResponse::HttpResponse() : mime_type("text/html; charset=iso8859-1"), location(""), server_name("GruiK Server v0.2"), return_code(HTTP_200_OK), last_modified(time(NULL)), cache(true), already_prepared(false), builder(0) {
}

HttpResponse::~HttpResponse() {
}

Task * HttpResponse::BuildResponse(Handle * out) {
    ChainTasks::tasklist_t l;
    Task * t;
    
    t = new BuildHttpResponse(this, out);

    if (builder) {
        l.push_back(builder);
        l.push_back(t);
        t = new ChainTasks(l);
    }
    
    return t;
}

void HttpResponse::PrepareResponse(Handle * b) {
    if (already_prepared)
        return;
    
    if (!b)
        b = &contents;
    
    already_prepared = true;

    char buf[1025];

    time_t cur_time = time(NULL);
    struct tm * ft = gmtime(&cur_time);

    strftime(buf, 1024, "%a, %d %b %Y %H:%M:%S GMT", ft);
    
    (*b) << "HTTP/1.1 " << return_code << " " << code_to_string() << "\r\n"
         << "Server: " << server_name << "\r\n"
         << "Date: " << buf << "\r\n";
         
    if (!cache)
        (*b) << "Cache-Control: no-cache\r\n";
         
    (*b) << "Connection: closed\r\n"
         << "Content-Type: " << mime_type << "\r\n";
    
    
    if (location != "") {
        switch (return_code) {
        case HTTP_301_PERM_MOVED:
        case HTTP_302_FOUND:
            (*b) << "Location: " << location << "\r\n";
            break;
        case HTTP_401_UNAUTHORIZED:
            if (domain != "") {
                SHA1 h;
                String digest;
                
                h.Update(location + ":" + ((Uint64) time(0)) + ":" + domain + ":" + rand());
                digest = h.Finish();
                
                (*b) << "WWW-Authenticate: Digest realm=\"" << location << "\", domain=\"" << domain << "\", nonce=\"" << digest << "\", algorithm=\"MD5\", qop=\"auth\"\r\n";
            } else {
                (*b) << "WWW-Authenticate: Basic realm=\"" << location << "\"\r\n";
            }
            break;
        }
    }
    if (last_modified >= 0) {
	ft = gmtime(&last_modified);
	strftime(buf, 1024, "%a, %d %b %Y %H:%M:%S GMT", ft);
        (*b) << "Last-Modified: " << buf << "\r\n";
    }
    for (std::vector<std::pair<String, String> >::iterator i = cookies.begin(); i != cookies.end(); i++) {
        (*b) << "Set-Cookie: ";
        (*b) << i->first << "=" << i->second << ";";
        if (cookies_path != "")
            (*b) << "path=" << cookies_path;
        (*b) << "\r\n";
    }
    
    (*b) << "\r\n";
}

bool HttpResponse::Prepared() {
    return already_prepared;
}

String HttpResponse::code_to_string() {
    switch (return_code) {
    case HTTP_200_OK:
        return "OK";
    case HTTP_301_PERM_MOVED:
        return "Moved Permanently";
    case HTTP_302_FOUND:
        return "Found";
    case HTTP_400_BAD_REQUEST:
        return "Bad Request";
    case HTTP_401_UNAUTHORIZED:
        return "Authorization Required";
    case HTTP_403_FORBIDDEN:
        return "Forbidden";
    case HTTP_404_NOT_FOUND:
        return "Not Found";
    case HTTP_500_INTERNAL_ERROR:
        return "Internal Error";
    case HTTP_503_SERVICE_UNAVAILABLE:
        return "Service Unavailable";
    }
    return "Unknown return code " + String(return_code);
}