Fix bug with ignored domain/dir
[gemini-php.git/.git] / server.php
1 <?php
2 /*
3  * Gemini server written in PHP by seven@0xm.net
4  * Version 0.1, Oct 2020
5 */
6
7 if(!require("config.php"))
8         die("config.php is missing.  Copy config.php.sample to config.php and customise your settings");
9 require("gemini.class.php");
10 $g = new Gemini($config);
11
12 $context = stream_context_create();
13
14 stream_context_set_option($context, 'ssl', 'local_cert', $g->certificate_file);
15 stream_context_set_option($context, 'ssl', 'passphrase', $g->certificate_passphrase);
16 stream_context_set_option($context, 'ssl', 'allow_self_signed', true);
17 stream_context_set_option($context, 'ssl', 'verify_peer', false);
18
19 $socket = stream_socket_server("tcp://{$g->ip}:{$g->port}", $errno, $errstr, STREAM_SERVER_BIND|STREAM_SERVER_LISTEN, $context);
20
21 stream_socket_enable_crypto($socket, false);
22
23 while(true) {
24         $forkedSocket = stream_socket_accept($socket, "-1", $remoteIP);
25
26         stream_set_blocking($forkedSocket, true);
27         stream_socket_enable_crypto($forkedSocket, true, STREAM_CRYPTO_METHOD_TLS_SERVER);
28         $line = fread($forkedSocket, 1024);
29         stream_set_blocking($forkedSocket, false);
30
31         $parsed_url = $g->parse_request($line);
32
33         $filepath = $g->get_filepath($parsed_url);
34
35         $status_code = $g->get_status_code($filepath);
36
37         $meta = "";
38         $filesize = 0;
39
40         if($status_code == "20") {
41                 $meta = $g->get_mime_type($filepath);
42                 $content = file_get_contents($filepath);        
43                 $filesize = filesize($filepath);
44         } else {
45                 $meta = "Not found";
46         }
47
48         $status_line = $status_code." ".$meta;
49         if($g->logging)
50                 $g->log_to_file($remoteIP,$status_code, $meta, $filepath, $filesize);
51         $status_line .= "\r\n";
52         fwrite($forkedSocket, $status_line);
53
54         if($status_code == "20") {
55                 fwrite($forkedSocket,$content);
56         }
57
58         fclose($forkedSocket);
59 }
60
61 ?>