aboutsummaryrefslogtreecommitdiff
path: root/captain/web.f90
blob: eedb25413c5471269030365a1598a5a796d092d2 (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
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
! Copyright (c) 2021 Approximatrix, LLC <support@approximatrix.com>
!
! 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 shall be used for Good, not Evil.
!
! 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 OR COPYRIGHT HOLDERS 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.

module web
implicit none

    private
    
    public :: handle_request

    integer, parameter::REQUEST_UNKNOWN = 0
    integer, parameter::REQUEST_GET  = 1
    integer, parameter::REQUEST_POST = 2

contains

    function method()
    use utilities, only: toupper
    implicit none
    
        integer::method
        character(4)::method_text
    
        call get_environment_variable("REQUEST_METHOD", method_text)
        call toupper(method_text)
        if(trim(method_text) == "GET") then
            method = REQUEST_GET
        else if(method_text == "POST") then
            method = REQUEST_POST
        else
            method = REQUEST_UNKNOWN
        end if
        
    end function method

    subroutine echo_error_stdout(error_code)
    implicit none
    
        integer, intent(in)::error_code
    
        Print *, "<html><head><title>Falling...</title></head><body><p>An Error Occurred:"
        Print *, error_code
        Print *, "</p></body></html>"
        
    end subroutine echo_error_stdout
    
    subroutine handle_basic_template_components(req, page)
    use server_response
    use page_template
    use captain_db
    use config
    implicit none
    
        class(request), intent(in)::req
        type(template), intent(inout)::page
        character(len=128)::username
    
        call page%assign('project', project)
        call page%assign('base_url', req%server)
        
        if(req%is_authenticated_user()) then
        
            call page%assign('user_link_page', "profile")
            call get_session_username_db(req%token, username)
            call page%assign('user_link_text', achar(240)//achar(159)//achar(152)//achar(128)//" "//trim(username))
        
        else
        
            call page%assign('user_link_page', "login")
            call page%assign('user_link_text', "Login")
        
        end if
    
    end subroutine handle_basic_template_components
    
    subroutine build_request_object(req)
    use server_response, only:http_request
    use logging
    implicit none
    
        type(http_request), intent(out)::req
        character(len=:), allocatable::url, script_name, cookie, server_name, fullurl
        character(len=4)::method
        integer::url_size, cookie_size, sn_size
        character(len=5)::server_port

        call get_environment_variable("REQUEST_URI", length=url_size)
        allocate(character(len=url_size)::url)
        call get_environment_variable("REQUEST_URI", url)
        
        call get_environment_variable("SCRIPT_NAME", length=sn_size)
        allocate(character(len=sn_size)::script_name)
        call get_environment_variable("SCRIPT_NAME", script_name)
        
        call get_environment_variable("SERVER_NAME", length=sn_size)
        allocate(character(len=sn_size)::server_name)
        call get_environment_variable("SERVER_NAME", server_name)

        call get_environment_variable("SERVER_PORT", server_port)
        
        call get_environment_variable("REQUEST_METHOD", method)
        
        call get_environment_variable("HTTP_COOKIE", length=cookie_size)
        if(cookie_size > 0) then
            allocate(character(len=cookie_size) :: cookie)
            call get_environment_variable("HTTP_COOKIE", cookie)
            call write_log("COOKIE="//cookie, LOG_DEBUG)
        end if

        ! If we're in CGI mode, treat the "server" as the script name
        call write_log("URL IS "//trim(url), level=LOG_DEBUG)
        call write_log("SE IS "//trim(script_name), level=LOG_DEBUG)
        
        ! We don't actually use this fabircated URL, but it is helpful for debugging
        ! whatever the hell is going on when the request object is built...
        allocate(character(len=(len_trim(server_name) + len_trim(url) + 7)) :: fullurl)
        fullurl = "http://"//trim(server_name)//":"//trim(server_port)//trim(url)
        call write_log("FULL URL WOULD BE "//trim(fullurl), level=LOG_DEBUG)
        
        if(allocated(cookie)) then
            call req%init(url, server_explicit=script_name, protocol_explicit="http", method=method, cookiestring=cookie)
            deallocate(cookie)
        else
            call req%init(url, server_explicit=script_name, protocol_explicit="http", method=method)
        end if
        
        deallocate(url)
        deallocate(script_name)
        deallocate(server_name)
        
    end subroutine build_request_object
    
    function html_link(link, label) result(res)
    use request_utils, only: build_link
    implicit none
        
        character(*), intent(in)::link, label
        character(len=:), pointer::res
        
        res => build_link(link, label, .false.)
    
    end function html_link

    function generate_one_instuction_html(req) result(res)
    use captain_db
    use server_response
    use request_utils, only: get_player_status_utf8, render_jobs_links, generate_simple_pager
    use config, only: global_permissions
    implicit none
    
        type(request)::req
        character(len=:), pointer::res
        integer::id_from_req
        
        character(128)::instruction_name
        type(job), dimension(:), pointer::jobs
        integer, dimension(:), pointer::players
        character(len=PLAYER_NAME_LENGTH), dimension(:), pointer::all_players
        integer::i, j, n_jobs, n_players, nsize, job_start_index
        
        character(len=:), pointer::job_link_text, one_link, pager
        character(1)::nl = new_line(' ')    
        character(PLAYER_NAME_LENGTH)::player_name
        character(4)::player_status
        
        i = index(req%page, ".html")
        instruction_name = req%page(1:i-1)
        id_from_req = get_instruction_id(trim(instruction_name))
        
        jobs => get_jobs_for_instruction(id_from_req)
        
        if(associated(jobs)) then
        
            if(associated(req%query_string)) then
                read(req%query_string, *, iostat=j) job_start_index
                if(j /= 0) then
                    job_start_index = 1
                end if
            else
                job_start_index = 1
            end if
    
            n_jobs = size(jobs)
            job_link_text => render_jobs_links(jobs, gemini_mode=.false., &
                link_prefix="../", startindex=job_start_index, &
                stopindex=min(job_start_index+4, n_jobs))
                
        else
            
            job_start_index = 0
            n_jobs = 0
            job_link_text => null()
            
        end if

        players => get_instruction_players(id_from_req)
        if(associated(players)) then
            n_players = size(players)
        else
            n_players = 0
        end if

        nsize = 1024
        if(n_jobs > 0) then
            nsize = nsize + len_trim(job_link_text)
        end if
        if(n_players > 0) then
            nsize = nsize + n_players*(2*PLAYER_NAME_LENGTH+64)
        end if

        nsize = nsize + get_player_count()*(2*PLAYER_NAME_LENGTH+64)

        allocate(character(len=nsize) :: res)

        res = "<h2>"//trim(instruction_name)//"</h2>"
        
        if(req%auth_level >= global_permissions%get("view-raw-instructions")) then
            one_link => html_link(trim(instruction_name)//".json", &
                                 "View Raw")
            res = trim(res)//nl//"<p><em>"//one_link//"</em></p>"
            deallocate(one_link)
        end if
        
        if(n_players == 0) then
            res = trim(res)//nl//"<p>No players currently can run these instructions</p>"
            
        else if(req%auth_level >= global_permissions%get("launch-job")) then
            res = trim(res)//nl//"<h3>Launch Now</h3>"//nl//"<ul>"
            
            do i = 1, n_players
                call get_player_name(players(i), player_name)
                player_status = get_player_status_utf8(players(i))
                one_link => html_link(req%page//"?launch="//trim(player_name), &
                                     trim(player_status)//" "//trim(player_name))
                
                res = trim(res)//nl//"<li>"//trim(one_link)//"</li>"
                
            end do
            
            res = trim(res)//nl//"</ul>"
        end if
        
        res = trim(res)//nl//"<h3>Jobs</h3>"
        if(n_jobs == 0) then
            res = trim(res)//nl//"None Yet"
        else
        
            pager => generate_simple_pager(job_start_index, job_start_index + 4, 5, n_jobs, req%page,.false.)
            
            res = trim(res)//nl//job_link_text
            
            if(associated(pager)) then
                res = trim(res)//nl//pager
                deallocate(pager)
            end if
            
            deallocate(job_link_text)
            
        end if
        
        if(req%auth_level >= global_permissions%get("assign-instructions")) then
            all_players => get_player_names()
            if(associated(all_players)) then
                res = trim(res)//nl//"<h3>Assign</h3>"//nl//"<p>Assign a player to these instructions</p>"//nl//"<ul>"
                do i = 1, size(all_players)
                    if(n_players > 0) then
                        j = get_player_id(all_players(i))
                        if(any(j == players)) then
                            cycle
                        end if
                    end if
                    
                    one_link => html_link(req%page//"?assign="//trim(all_players(i)), &
                                          trim(all_players(i)))
                    
                    res = trim(res)//nl//"<li>"//one_link//"</li>"
                    deallocate(one_link)
                end do
                res = trim(res)//nl//"</ul>"
                deallocate(all_players)
            end if
            
            if(n_players > 0) then
                 res = trim(res)//nl//"<h3>Remove</h3>"//nl//"<p>Remove a player from these instructions</p>"//nl//"<ul>"
                 do i = 1, n_players
                    call get_player_name(players(i), player_name)
                    
                    one_link => html_link(req%page//"?remove="//trim(player_name), &
                                          trim(player_name))
                                          
                    res = trim(res)//nl//"<li>"//one_link//"</li>"
                    deallocate(one_link)
                end do
                res = trim(res)//nl//"</ul>"
            end if
        end if
        
    end function generate_one_instuction_html

    function generate_instructions_html(req) result(res)
    use captain_db
    use server_response, only:request
    use config, only: global_permissions
    implicit none
    
        type(request)::req
        character(len=:), pointer::res
        character(len=PLAYER_NAME_LENGTH), dimension(:), pointer::instruction_names
        integer::n, i, nsize

        character(len=:), pointer::one_player, scanlink
        
        n = get_instructions_count()
        
        if(n == 0) then
        
            allocate(character(len=1024) :: res)
            res = "None Yet"
            
        else
        
            instruction_names => get_instruction_names()
            nsize = 1024
            do i = 1, size(instruction_names)
                nsize = nsize + 16 + 2*len_trim(instruction_names(i))
            end do
            
            allocate(character(len=nsize) :: res)
            res = "<h2>Instructions</h2>"//new_line(' ')//"<ul>"
            
            do i = 1, n
                one_player => html_link("instructions/"//trim(instruction_names(i))//".html", &
                                        trim(instruction_names(i)))
                res = trim(res)//new_line(' ')//"<li>"//trim(one_player)//"</li>"
                deallocate(one_player)
            end do
            
            res = trim(res)//new_line(' ')//"</ul>"
            
            deallocate(instruction_names)
        
        end if
        
        if(req%auth_level >= global_permissions%get("scan-instructions")) then
            res = trim(res)//new_line(' ')//"<h2>Management</h2>"
            
            scanlink => html_link(req%page//"?scan", "Scan for instructions now")
            res = trim(res)//new_line(' ')//"<p>"//scanlink//"</p>"
            deallocate(scanlink)
        end if
    
    end function generate_instructions_html
    
    function generate_groups_html(req) result(res)
    use captain_db
    use server_response, only:request
    use config, only: global_permissions
    implicit none
    
        type(request)::req
        character(len=:), pointer::res
        integer, dimension(:), pointer::groups
        character(128)::one_group
        integer::n, i

        character(len=:), pointer::one_link
        
        n = get_group_count_db()

        if(n == 0) then
        
            allocate(character(len=1024) :: res)
            res = "None Yet"
            
        else
        
            allocate(character(len=(n*(256+64) + 384)) :: res)
        
            res = "<h2>Groups</h2>"//new_line(' ')//"<ul>"
        
            groups => get_groups_db()
            do i=1, n
                call get_group_name_db(groups(i), one_group)
                one_link => html_link("groups/"//trim(one_group)//".html", &
                                      trim(one_group))
                
                res = trim(res)//new_line(' ')//"<li>"//trim(one_link)//"</li>"
                deallocate(one_link)
            end do
            
            res = trim(res)//new_line(' ')//"</ul>"
            deallocate(groups)
        
        end if
        
        if(req%auth_level >= global_permissions%get("add-groups")) then
            res = trim(res)//new_line(' ')//"<h2>Management</h2>"
            
            res = trim(res)//new_line(' ')// &
            '<form action="groups/add.html" method="POST"><label for="name">Name:</label>'// &
            '<input name="name" id="name" /><input type="submit" value="Add"/></form>'
        end if
    
    end function generate_groups_html
    
    function generate_one_group_html(req) result(res)
    use captain_db
    use server_response, only:request
    use request_utils
    use query_utilities
    use logging
    use remote_launch, only: launch_group
    use config, only: global_permissions
    implicit none
    
        type(request)::req
        character(len=:), pointer::res
        
        type(query)::q
        
        character(128)::group_name, instruction_name, player_name
        integer::id
        
        type(group_entry), dimension(:), pointer::entries
        type(work_pair), dimension(:), pointer::all_entries
        character(len=:), pointer::one_link, delete_link, play_link, qreq
        
        character(128)::launch_msg
        
        integer::i, j, n_instructions_group, n_instructions_total
        
        call req%path_component(2, group_name)
        i = index(group_name, ".html")
        group_name(i:128) = ' '
        
        id = get_group_id_db(trim(group_name))
        entries => null()
        all_entries => null()
        
        launch_msg = " "
        
        if(associated(req%query_string)) then
            
            call q%init(req%query_string)
            qreq => q%get_value("add")
            
            if(associated(qreq) .and. req%auth_level >= global_permissions%get("add-groups")) then
                
                call write_log("ADD: "//trim(qreq))
                
                i = index(qreq, ',')
                player_name = qreq(i+1:len_trim(qreq))
                instruction_name = qreq(1:i-1)
                
                i = get_instruction_id(trim(instruction_name))
                j = get_player_id(trim(player_name))
                
                call add_entry_to_group_db(id, i, j)

            else
            
                qreq => q%get_value("delete")
            
                if(associated(qreq) .and. req%auth_level >= global_permissions%get("modify-groups")) then
            
                    i = index(qreq, ',')
                    player_name = qreq(i+1:len(qreq))
                    instruction_name = qreq(1:i-1)
                    
                    i = get_instruction_id(trim(instruction_name))
                    j = get_player_id(trim(player_name))
                    
                    call remove_entry_from_group_db(id, i, j)

                else if(trim(req%query_string) == "launch" .and. req%auth_level >= global_permissions%get("launch-job")) then
                
                    call launch_group(id)
                    write(launch_msg, '(I4, 1X, A13)') get_group_entries_count_db(id), "jobs launched"
                    
                else if(trim(req%query_string) == "destroy" .and. req%auth_level >= global_permissions%get("modify-groups")) then
                
                    call delete_group_db(id)
                    
                end if
                
            end if
            
            call q%destroy()
            
        end if
        
        n_instructions_group = get_group_entries_count_db(id)
        n_instructions_total = get_available_count_db()
        
        allocate(character( len=(n_instructions_total*384 + 512) ) :: res)
        
        res = "<h2>"//trim(group_name)//"</h2>"
        
        if(n_instructions_group == 0) then
            
            res = trim(res)//new_line(' ')//"<p><em>Contains no instructions.</em></p>"
            
        else
        
            if(len_trim(launch_msg) > 0) then
                res = trim(res)//new_line(' ')//'<p><strong>'//trim(launch_msg)//'</strong></p>'
            else
                res = trim(res)//new_line(' ')//'<p><a href="'//req%page//'?launch">&#x1f680; Launch Now</a></p>'
            end if
            
            res = trim(res)//new_line(' ')//"<h3>Work to Be Performed</h3>"//new_line(' ')//"<ul>"
            
            entries => get_group_entries_db(id)
            do i = 1, n_instructions_group
            
                call get_instruction_name(entries(i)%instruction, instruction_name)
                call get_player_name(entries(i)%player, player_name)
            
                one_link => html_link("../instructions/"//trim(instruction_name)//".html", trim(instruction_name))
                play_link => html_link("../players/"//trim(player_name)//".html", trim(player_name))
                
                
                res = trim(res)//new_line(' ')//"<li>"//one_link//" on "//play_link
                
                if(req%auth_level >= global_permissions%get("modify-groups")) then
                    delete_link => html_link(trim(group_name)//".html?delete="// &
                                             trim(instruction_name)//","//trim(player_name), &
                                             "<em>Remove</em>")
                    res = trim(res)//" - "//delete_link
                    deallocate(delete_link)
                end if
                
                res = trim(res)//"</li>"
            
                deallocate(one_link)
                deallocate(play_link)
            
            end do
            
            res = trim(res)//new_line(' ')//"</ul>"
            
        end if
        
        if(n_instructions_total > 0 .and. req%auth_level >= global_permissions%get("modify-groups")) then
        
            res = trim(res)//new_line(' ')//"<h3>Add Instructions</h3>"
            
            all_entries => get_available_work_pairs_db()
            if(associated(all_entries)) then
            
                res = trim(res)//new_line(' ')//'<form action="'//trim(group_name)//'.html" method="GET">'// &
                    '<label for="add">Instruction:</label>'//new_line(' ')// &
                    '<select name="add" id="add">'
                
                do i=1,n_instructions_total
                
                    if(associated(entries)) then
                        if(any(entries%player == all_entries(i)%player .AND. &
                               entries%instruction == all_entries(i)%instruction) )  &
                        then
                            cycle
                        end if
                    end if
        
                    call get_instruction_name(all_entries(i)%instruction, instruction_name)
                    call get_player_name(all_entries(i)%player, player_name)
                    res = trim(res)//new_line(' ')//'<option value="'//trim(instruction_name)//","//trim(player_name)//'">'// &
                          trim(instruction_name)//" on "//trim(player_name)//"</option>"
                        
                end do
                
                res = trim(res)//new_line(' ')//'</select>'//'<input type="submit" value="Add"/></form>'
            end if
        end if
        
        if(req%auth_level >= global_permissions%get("modify-groups")) then
            res = trim(res)//new_line(' ')//'<h3>Destroy This Group</h3>'//new_line(' ')// &
                  '<p><a href="'//req%page//'?destroy">&#x1f4a3; Destroy</a></p>'//new_line(' ')// &
                  '<p><em>This operation will not destroy any instructions</em></p>'
        end if
        
    end function generate_one_group_html

    function generate_players_html(req) result(res)
    use captain_db
    use request_utils, only: get_status_utf8
    use server_response, only: request
    use config, only: global_permissions
    implicit none
        
        type(request), intent(in)::req
    
        character(len=:), pointer::res
        character(len=PLAYER_NAME_LENGTH), dimension(:), pointer::players
        integer::n, i, nsize, pid

        character(4)::player_status
        character(len=:), pointer::one_player
        
        n = get_player_count()
        if(n == 0) then
        
            allocate(character(len=1024) :: res)
            
            res = "None Yet"
            
        else

            players => get_player_names()
            
            nsize = 1024
            do i = 1, size(players)
                nsize = nsize + 16 + 2*len_trim(players(i))
            end do
            
            allocate(character(len=nsize) :: res)
            res = "<h2>Existing Players</h2>"//new_line(' ')//"<ul>"
            
            do i = 1, n
            
                pid = get_player_id(players(i))
                if(is_player_online(pid)) then
                    if(is_player_busy(pid)) then
                        player_status = get_status_utf8(PLAYER_STATUS_BUSY)
                    else
                        player_status = get_status_utf8(PLAYER_STATUS_IDLE)
                    end if
                else
                    player_status = get_status_utf8(PLAYER_STATUS_OFFLINE)
                end if
            
                one_player => html_link("players/"//trim(players(i))//".html", &
                                       trim(player_status)//" "//trim(players(i)))
                res = trim(res)//new_line(' ')//"<li>"//trim(one_player)//"</li>"
                deallocate(one_player)
            end do
            
            res = trim(res)//new_line(' ')//"</ul>"
            deallocate(players)
        end if
        
        if(req%auth_level >= global_permissions%get("add-players")) then
            res = trim(res)//new_line(' ')//"<h2>Management</h2>"// &
            new_line(' ')//'<form action="players/add.html" method="POST"><label for="name">Name:</label>'// &
            '<input name="name" id="name" /><input type="submit" value="Add"/></form>'
        end if
        
    end function generate_players_html

    function generate_one_player_html(req) result(res)
    use captain_db
    use server_response
    use request_utils
    use config, only: global_permissions
    implicit none

        type(request), intent(in)::req
        character(len=:), pointer::res
        
        character(len=PLAYER_NAME_LENGTH)::player_name, instruction_name
        character(len=:), pointer::one_link
        integer::i, n, pid
        integer, dimension(8)::values
        integer, dimension(:), pointer::instruction_ids
        
        character(len=64)::dateconvert
        
        call req%last_component(player_name)
        i = index(player_name, '.html')
        player_name = player_name(1:i-1)
        pid = get_player_id(trim(player_name))
        
        n = get_instructions_count(player=pid)
        allocate(character(len=(2*n*PLAYER_NAME_LENGTH + 1024)) :: res)
        
        res = "<h2>"//trim(player_name)
        if(is_player_online(pid)) then
            res = trim(res)//" - Online</h2>"
        else
            res = trim(res)//" - Offline</h2>"
        end if
        
        ! Last checkin
        call get_last_checkin_time(pid, values)
        write(dateconvert, '(I4,A1,I0.2,A1,I0.2,3X,I2,A1,I0.2,A1,I0.2)') &
            values(1), '-', values(2), '-', values(3), &
            values(5), ':', values(6), ':', values(7)
        
        res = trim(res)//new_line(' ')//'<p><em>Last Checkin: <strong>'//trim(dateconvert)//&
              '</strong></em></p>'
        
        ! List of instructions
        res = trim(res)//new_line(' ')//"<h3>Instructions for "//trim(player_name)//"</h3>"
        instruction_ids => get_instruction_ids(player=pid)
        if(associated(instruction_ids)) then
            res = trim(res)//new_line(' ')//"<ul>"
            do i = 1, n
                call get_instruction_name(instruction_ids(i), instruction_name)
                one_link => html_link("../instructions/"//trim(instruction_name)//".html", trim(instruction_name))
                res = trim(res)//new_line(' ')//"    <li>"//one_link//"</li>"
                deallocate(one_link)
            end do
            res = trim(res)//new_line(' ')//"</ul>"
            deallocate(instruction_ids)
        else
            res = trim(res)//"<p>None Yet</p>"
        end if
        
        if(req%auth_level >= global_permissions%get("modify-players")) then
            ! Token assignment
            res = trim(res)//new_line(' ')//"<h3>Security</h3>"//new_line(' ')//"<p>"
            
            if(player_has_token_db(trim(player_name))) then
                res = trim(res)//"Player currently has a token assigned."
            else
                res = trim(res)//"<em>Player is insecure!  Please assign a token!</em>"
            end if
            
            res = trim(res)//"</p>"
            
            res = trim(res)//new_line(' ')// &
                  '<form action="assign_token.html" method="POST">'//new_line(' ')// &
                  '<label for="token">Token:</label>'// &
                  '<input name="token" id="token" />'//new_line(' ')// &
                  '<input type="hidden" name="player" id="player" value="'//trim(player_name)//'"/>'//new_line(' ')// &
                  '<input type="submit" value="Set"/></form>'
        end if
        
    end function generate_one_player_html

    function generate_one_job_html(req) result(res)
    use captain_db
    use config
    use server_response
    use special_filenames, only: get_task_result_static_filename
    use request_utils, only: get_status_utf8, get_player_link => player_link, &
                             get_instruction_link => instruction_link
    implicit none
    
        type(request), intent(in)::req
        character(len=:), pointer::res
        
        character(4)::status
        integer::i, j, job_id
        type(job)::one_job
        
        character(1)::nl = new_line(' ')
        
        type(task), dimension(:), pointer::tasks
        character(32)::task_text, job_text, task_type
        character(len=:), pointer::task_results_filename, one_link, local_task_results_filename
        character(len=:), pointer::player_link, instruction_link
        
        character(len=FILENAME_NAME_LENGTH), dimension(:), pointer::releases
        logical::file_exists
        
        res => null()
    
        ! Ugh, all this nonsense
        call req%last_component(job_text)
        j = index(job_text, ".", back=.true.)
        job_text(j:len(job_text)) = " "
        read(job_text, '(I8)') job_id
        one_job = get_job(job_id)
        
        if(one_job%id >= 0) then
            allocate(character(len=1024) :: res)
            
            status = get_status_utf8(one_job%status)
            res = "<h2>Status - "//status//"</h2>"
            
            player_link => get_player_link(one_job%player, .FALSE., prefix="..")
            if(associated(player_link)) then
                res = trim(res)//nl//nl//"<p><em>Running on "//player_link//nl// &
                      "Last update at: "//one_job%time//"</em></p>"
                deallocate(player_link)
            end if
            
            instruction_link => get_instruction_link(one_job%instruction, .FALSE., prefix="..")
            if(associated(instruction_link)) then
                res = trim(res)//nl//"<p><em>Executing: "//instruction_link//"</em></p>"
                deallocate(instruction_link)
            end if
            
            res = trim(res)//nl//nl//"<h3>Task Results</h3>"
            
            tasks => get_job_tasks(job_id)
            if(associated(tasks)) then
                res = trim(res)//nl//"<ul>"
                do i = 1, size(tasks)
                    status = get_status_utf8(tasks(i)%status)
                    task_results_filename => get_task_result_static_filename(one_job%id, i, no_path=.true.)
                    local_task_results_filename => get_task_result_static_filename(one_job%id, i, no_path=.false.)
                    inquire(file=local_task_results_filename, exist=file_exists)
                    
                    write(task_text, '(I8)') i
                    
                    if(file_exists) then
                        one_link => html_link("../results/"//task_results_filename, &
                                              trim(status)//" - Task "//trim(adjustl(task_text)))
                    
                        res = trim(res)//nl//"    <li>"//trim(one_link)
                        deallocate(one_link)
                    else
                        res = trim(res)//nl//"    <li>"// &
                              trim(status)//" - Task "//trim(adjustl(task_text))
                    end if
                    
                    if(get_task_type(job_id, i, task_type)) then
                        res = trim(res)//" ("//trim(task_type)//")"
                    end if
                    
                    res =  trim(res)//"</li>"
                    deallocate(local_task_results_filename)
                    deallocate(task_results_filename)
                end do
                res = trim(res)//nl//"</ul>"
                deallocate(tasks)
            else
                res = trim(res)//nl//nl//"<p><strong>None reported yet</strong></p>"
            end if
            
            if(get_job_upload_count_by_category_db(job_id, "releases") > 0 .and. &
               req%auth_level >= global_permissions%get("access-releases"))  &
            then
            
                res = trim(res)//nl//"<h3>Releases</h3>"//nl//"<ul>"
                releases => get_job_uploads_by_category_db(job_id, "releases")
                do i = 1, size(releases)
                    
                    one_link => html_link("../releases/"//trim(releases(i)), &
                                          trim(releases(i)))
                    
                    res = trim(res)//nl//"    <li>"//trim(one_link)//"</li>"
                
                end do
            
                res = trim(res)//nl//"</ul>"
            
            end if
            
        else
        
            allocate(character(len=64) :: res) 
            write(res, '(A20, 1X, I5)') "No record of:", job_id
            
        end if
    
    end function generate_one_job_html

    function generate_releases_html(req) result(res)
    use utilities
    use server_response
    use config
    implicit none
    
        type(request), intent(in)::req
        character(len=:), pointer::res
        character(len=DIR_LIST_STRING_LENGTH), dimension(:), pointer::directories
        character(len=DIR_LIST_STRING_LENGTH), dimension(:), pointer::files
        
        character(1024)::public_path, local_path, subpath
        integer::allocation_size, i
        character(1)::nl = new_line(' ')
        character(4)::folder_icon = char(240)//char(159)//char(147)//char(129)
        character(len=:), pointer::one_link
        
        if(.not. associated(req%query_string)) then
            public_path = "/releases"
            local_path = release_dir
        else if(len_trim(req%query_string) == 0) then
            public_path = "/releases"
            local_path = release_dir
        else
            call combine_paths("/releases", req%query_string, public_path)
            call combine_paths(release_dir, req%query_string, local_path)
        end if
        
        res => null()
        
        ! Auth check
        if(req%auth_level < global_permissions%get("access-releases")) then
            allocate(character(len=64)::res)
            if(req%auth_level == 0) then
                res = "Login required."
            else
                res = "Unacceptable permissions"
            end if
            return
        end if
        
        ! Easy safety check - no relative paths
        if(index(local_path, '..') > 0) then
            allocate(character(len=64)::res)
            res = "None Found"
            return
        end if
        
        directories => get_directories_in_directory(local_path)
        files => get_files_in_directory(local_path)
        
        allocation_size = 1024
        if(associated(directories)) then
            allocation_size = allocation_size + 2 * size(directories) * (DIR_LIST_STRING_LENGTH+32)
        end if
        if(associated(files)) then
            allocation_size = allocation_size + 2 * size(files) * (DIR_LIST_STRING_LENGTH+32)
        end if
        allocate(character(len=allocation_size) :: res)
        res = "<h2>Listing for "//trim(public_path)//"</h2>"//nl//"<ul>"
        
        ! Add an "Up" link
        if(trim(public_path) /= "/releases") then
            i = index(req%query_string, "/", back=.true.)
            if(i > 0) then
                one_link => html_link("releases.html?"//req%query_string(1:(i-1)), "Up a directory")
            else
                one_link => html_link("releases.html", "Up a directory")
            end if
            res = trim(res)//nl//"<li>"//one_link//"</li>"
            deallocate(one_link)
        end if
        
        if(associated(directories)) then
            
            do i = 1, size(directories)
            
                if(associated(req%query_string)) then
                    call combine_paths(req%query_string, trim(directories(i)), subpath)
                else
                    subpath = trim(directories(i))
                end if

                one_link => html_link("releases.html?"//trim(subpath), folder_icon//" "//trim(directories(i)))
                res = trim(res)//nl//"<li>"//one_link//"</li>"
                deallocate(one_link)
                
            end do
            
            deallocate(directories)
            
        end if
        
        if(associated(files)) then
        
            do i = 1, size(files)
                call combine_paths(public_path(2:len_trim(public_path)), trim(files(i)), subpath)
                one_link => html_link(trim(subpath), trim(files(i)))
                res = trim(res)//nl//"<li>"//one_link//"</li>"
                deallocate(one_link)
            end do
            
            deallocate(files)
            
        end if
            
        res = trim(res)//nl//"</ul>"
            
    end function generate_releases_html
    
    function generate_jobs_html(req) result(res)
    use captain_db
    use server_response
    use request_utils, only: render_jobs_links, generate_simple_pager
    use logging
    implicit none
    
        type(request)::req
        character(len=:), pointer::res
        type(job), dimension(:), pointer::jobs
        integer::n, nsize
        integer::i_start_jobs, ierr
        
        character(len=:), pointer::linklist, pager
        
        n = get_jobs_count()
        if(n == 0) then
        
            allocate(character(len=1024) :: res)
            
            res = "None Yet"
            
        else
            if(associated(req%query_string)) then
                read(req%query_string, *, iostat=ierr) i_start_jobs
            else
                ierr = -1
            end if
            
            if(ierr /= 0) then
                i_start_jobs = 1
            end if
        
            jobs => get_jobs()
        
            ! 15 per page
            nsize = 15*(2*PLAYER_NAME_LENGTH + 64) + 1024
            allocate(character(len=nsize) :: res)

            res = " "
            
            linklist => render_jobs_links(jobs, i_start_jobs, min(i_start_jobs+14, n), .false.)
            res = trim(res)//new_line(' ')//trim(linklist)
            
            ! Pagers
            pager => generate_simple_pager(i_start_jobs, min(i_start_jobs+14, n), 15, n, req%page, .false.)
            if(associated(pager)) then
                res = trim(res)//new_line(' ')//pager
                deallocate(pager)
            end if
            
            deallocate(linklist)
        
        end if
        
    end function generate_jobs_html

    function request_templated(req) result(resp)
    use page_template
    use config, only: template_filepath, project
    use logging
    use server_response, only:request, response
    use http_codes, only: HTTP_CODE_SUCCESS, HTTP_CODE_NOTFOUND
    use request_utils, only: get_job_page_title, handle_instruction_command
    use captain_db, only: scan_instructions_for_db, get_session_username_db, destroy_session_db
    use utilities, only: build_date
    implicit none
    
        class(request), intent(in)::req
        type(response)::resp
        
        character(64)::template_to_use
        character(1024)::template_file
        type(template)::page
        character(64)::first
        
        character(len=:), pointer::contents
        character(128)::job_page_title, username
        
        integer::i
        logical::authenticated
        
        authenticated = req%is_authenticated_user()
        
        if(trim(req%location) == "/" .or. &
           trim(req%location) == "/index.html" .or. &
           trim(req%location) == "/home.html") &
        then
        
            template_to_use = "home.html"
            
        else if(trim(req%location) == "/about.html") then
        
            template_to_use = "about.html"
        
        else if(trim(req%location) == "/login.html") then
        
            if(authenticated) then
                template_to_use = "redirect.html"
            else
                template_to_use = "login.html"
            end if
        
        else if(trim(req%location) == "/profile.html") then
        
            if(authenticated) then
                template_to_use = "profile.html"
            else
                template_to_use = "redirect.html"
            end if
        
        else if(trim(req%location) == "/logout.html") then
            
            template_to_use = "redirect.html"

        else if(index(req%location, "/instructions/") == 1 .and. associated(req%query_string)) then

            template_to_use = "redirect.html"
            
        else
        
            template_to_use = "index.html"
            
        end if
        
        call template_filepath(template_to_use, template_file)
        call write_log("Template base path is: "//trim(template_file), LOG_DEBUG)
        call page%init(trim(template_file))
        
        ! Initialize with success
        resp%code = HTTP_CODE_SUCCESS
        
        call req%path_component(1, first)
        
        if(trim(req%location) == "/" .or. trim(req%location) == "/index.html" .or. trim(req%location) == "/home.html") then
        
            call page%assign('title', 'Home')
            
        else if(trim(req%location) == "/releases.html") then
        
            call page%assign('title', 'Releases')
            contents => generate_releases_html(req)
            call page%assign('contents', contents)
        
        else if(trim(req%location) == "/jobs.html") then
        
            call page%assign('title', 'Jobs')
            contents => generate_jobs_html(req)
            call page%assign('contents', contents)
        
        else if(trim(req%location) == "/players.html") then
        
            call page%assign('title', 'Players')
            contents => generate_players_html(req)
            call page%assign('contents', contents)
            
        else if(req%location(1:9) == '/players/') then
            
            call req%last_component(job_page_title)
            i = index(job_page_title, '.', back=.true.)
            
            call page%assign('title', job_page_title(1:i-1))
            contents => generate_one_player_html(req)
            call page%assign('contents', contents)
        
        else if(trim(req%location) == "/about.html") then
        
            call page%assign('title', 'About')
            call page%assign('build_date', build_date())
            
        else if(trim(req%location) == "/instructions.html") then
            
            if(associated(req%query_string) ) then
                if(trim(req%query_string) == "scan") then
                    call scan_instructions_for_db()
                end if
            end if
            
            call page%assign('title', 'Build Instructions')
            contents => generate_instructions_html(req)
            call page%assign('contents', contents)
            
        else if(trim(first) == "instructions") then
            
            if(associated(req%query_string)) then
                call handle_instruction_command(req)
                call page%assign('title', 'Command Received')
                call page%assign('destination', req%location(2:))
            else
                call page%assign('title', 'Build Instructions')
                contents => generate_one_instuction_html(req)
                call page%assign('contents', contents)
            end if
            
        else if(trim(first) == "jobs") then
            
            call get_job_page_title(req, job_page_title)
            call page%assign('title', trim(job_page_title))
            contents => generate_one_job_html(req)
            call page%assign('contents', contents)
        
        else if(trim(req%location) == "/groups.html") then
        
            call page%assign('title', 'Instruction Groups')
            contents => generate_groups_html(req)
            call page%assign('contents', contents)
        
        else if(trim(first) == "groups") then
        
            call page%assign('title', 'Instruction Group')
            contents => generate_one_group_html(req)
            call page%assign('contents', contents)
        
        else if(trim(first) == "login.html") then
        
            call page%assign('title', 'Login')
            if(authenticated) then
                call page%assign('destination', 'home.html')
            else 
                if(associated(req%q%get_value("failed"))) then
                    call page%assign('login_message', "Login Failed.")
                end if
            end if
        
        else if(trim(first) == "profile.html") then
        
            call page%assign('title', 'User Profile')
            if(authenticated) then
                call get_session_username_db(req%token, username)
                call page%assign('username', username)
            else
                call page%assign('destination', 'login.html')
            end if
            
        else if(trim(first) == "logout.html") then
            
            call page%assign('title', 'Logout')
            call page%assign('destination', 'home.html')
            if(authenticated) then
                call destroy_session_db(req%token)
            end if
        
        else
        
            call page%assign('title', 'Not Found')
            resp%code = HTTP_CODE_NOTFOUND
            
        end if
        
        call handle_basic_template_components(req, page)
        
        call write_log("Rendering page for "//req%location)
        call page%render()

        call write_log("Finalizing response", LOG_INFO)
        resp%temporary_file = .true.
        resp%body_filename => page%output_filename
        resp%body_mimetype = "text/html"
        
    end function request_templated
    
    function handle_post(req) result(resp)
    use captain_db, only: add_player_db, add_group_db, update_player_token_db, create_user_session_db, &
                          validate_user_db
    use page_template
    use config, only: template_filepath, global_permissions
    use logging
    use server_response, only:http_request, response
    use http_post_utilities
    use query_utilities, only: query
    use http_codes
    implicit none
    
        type(http_request), intent(in)::req
        type(response)::resp
        type(query)::posted
        
        character(1024)::template_file
        type(template)::page
        
        character(64)::category, second
    
        posted = read_post_contents()
        call write_log("Post Contents: "//posted%full, LOG_DEBUG)
        
        if(posted%component_count() > 0) then
        
            ! We will immediately redirect after the command is handled
            call template_filepath("redirect.html", template_file)
            call page%init(trim(template_file))
            
            ! Handle based on category
            call req%path_component(1, category)
            if(trim(category) == "players") then
                call req%path_component(2, second)
                
                ! Add a player
                if(trim(second) == "add.html" .and. req%auth_level >= global_permissions%get("add-players")) then
                
                    call add_player_db(posted%get_value("name"))
                    call page%assign('destination', 'players.html')
    
                else if(trim(second) == "assign_token.html" .and. req%auth_level >= global_permissions%get("modify-players")) then
                
                    call update_player_token_db(posted%get_value("player"), posted%get_value("token"))
                    call page%assign('destination', "players/"//posted%get_value("player")//".html")
    
                end if
            
            else if(trim(category) == "groups") then
            
                call req%path_component(2, second)
                
                ! Add a group
                if(trim(second) == "add.html" .and. req%auth_level >= global_permissions%get("add-groups")) then
                
                    call add_group_db(posted%get_value("name"))
                    call page%assign('destination', 'groups.html')
    
                end if
                
            else if(trim(category) == "login.html") then
            
                ! Determine if logged in
                if(validate_user_db(posted%get_value("username"), posted%get_value("password"))) then
                    call resp%set_cookie("token", create_user_session_db(posted%get_value("username")))
                    call page%assign('destination', "home.html")
                else
                    call page%assign('destination', "login.html?failed=1")
                end if
            
            end if
            
            ! Handle the template
            call handle_basic_template_components(req, page)
            call page%render()

            call write_log("Finalizing response", LOG_INFO)
            resp%temporary_file = .true.
            resp%body_filename => page%output_filename
            resp%body_mimetype = "text/html"
            resp%code = HTTP_CODE_SUCCESS
            
            call posted%destroy()
            
        else
        
            resp%code = HTTP_CODE_FAILURE
        
        end if

    end function handle_post

    subroutine handle_request()
    use server_response, only:http_request, response
    use logging
    use request_utils
    use http_codes
    use http, only: write_response_headers, write_redirect
    use iso_fortran_env, only: output_unit
    use utilities, only: echo_file_stdout
    implicit none
    
        type(http_request)::req
        type(response)::resp
        integer::response_size
        
        character(64)::logresponse
        
        call build_request_object(req)
        
        if(is_request_static(req)) then
            call write_log("Req static", LOG_INFO)
            resp = request_static(req)
    
        else if(req%is_post()) then
            call write_log("POST operation", LOG_INFO)
            resp = handle_post(req)
    
        else 
            call write_log("Req template", LOG_INFO)
            resp = request_templated(req)
    
        end if
        
        ! Perform the response
        call write_log("Publishing response", LOG_INFO)
        
        write(logresponse, *) "Response code is: ", resp%code
        call write_log(trim(logresponse), LOG_INFO)
        
        select case(resp%code)
            case(HTTP_CODE_REDIRECT)
                call write_redirect(output_unit, resp%code, trim(resp%url))
                
            case(HTTP_CODE_SUCCESS)
                inquire(file=resp%body_filename, size=response_size)
                if(associated(resp%cookiecmd)) then
                    call write_response_headers(output_unit, resp%code, response_size, trim(resp%body_mimetype), resp%cookiecmd)
                else
                    call write_response_headers(output_unit, resp%code, response_size, trim(resp%body_mimetype))
                end if
                call echo_file_stdout(resp%body_filename)
                
            case default
                call write_log("Failure reported for location: "//trim(req%location), LOG_NORMAL)
                call echo_error_stdout(resp%code)
            ! Need some more...
            
        end select
        
        call write_log("Cleanup", LOG_INFO)
        
        call resp%destroy()
        call req%destroy()
    
        call write_log("Exit handler", LOG_INFO)
    
    end subroutine handle_request

end module web