| 1 | package Yote::YapiServer; | ||
| 2 | |||
| 3 | use strict; | ||
| 4 | use warnings; | ||
| 5 | |||
| 6 | our $VERSION = '0.01'; | ||
| 7 | |||
| 8 | use IO::Socket::INET; | ||
| 9 | use File::Spec; | ||
| 10 | |||
| 11 | use Yote::SQLObjectStore; | ||
| 12 | use Yote::YapiServer::Site; | ||
| 13 | use Yote::YapiServer::Handler; | ||
| 14 | |||
| 15 | sub new { | ||
| 16 | my ($class, %args) = @_; | ||
| 17 | my $db = $args{db} // { type => 'SQLite', data_dir => $args{data_dir} // 'data' }; | ||
| 18 | return bless { | ||
| 19 | port => $args{port} // 5001, | ||
| 20 | db => $db, | ||
| 21 | root_package => $args{root_package} // 'Yote::YapiServer::Site', | ||
| 22 | lib_paths => $args{lib_paths} // [], | ||
| 23 | endpoint => $args{endpoint} // '/yapi', | ||
| 24 | max_file_size => $args{max_file_size} // 5_000_000, | ||
| 25 | webroot_dir => $args{webroot_dir} // 'www/webroot', | ||
| 26 | }, $class; | ||
| 27 | } | ||
| 28 | |||
| 29 | sub _new_store { | ||
| 30 | my ($self) = @_; | ||
| 31 | my $db = $self->{db}; | ||
| 32 | my $type = $db->{type} // 'SQLite'; | ||
| 33 | |||
| 34 | if ($type eq 'SQLite') { | ||
| 35 | my $data_dir = $db->{data_dir} // 'data'; | ||
| 36 | mkdir $data_dir unless -d $data_dir; | ||
| 37 | return Yote::SQLObjectStore->new( | ||
| 38 | 'SQLite', | ||
| 39 | BASE_DIRECTORY => $data_dir, | ||
| 40 | root_package => $self->{root_package}, | ||
| 41 | ); | ||
| 42 | } | ||
| 43 | elsif ($type eq 'MariaDB') { | ||
| 44 | return Yote::SQLObjectStore->new( | ||
| 45 | 'MariaDB', | ||
| 46 | dbname => $db->{dbname}, | ||
| 47 | username => $db->{username}, | ||
| 48 | password => $db->{password}, | ||
| 49 | root_package => $self->{root_package}, | ||
| 50 | ); | ||
| 51 | } | ||
| 52 | else { | ||
| 53 | die "Unknown db type: $type (expected SQLite or MariaDB)\n"; | ||
| 54 | } | ||
| 55 | } | ||
| 56 | |||
| 57 | sub run { | ||
| 58 | my ($self) = @_; | ||
| 59 | |||
| 60 | my $port = $self->{port}; | ||
| 61 | my $root_package = $self->{root_package}; | ||
| 62 | my $endpoint = $self->{endpoint}; | ||
| 63 | |||
| 64 | # Set Handler config | ||
| 65 | $Yote::YapiServer::Handler::max_file_size = $self->{max_file_size}; | ||
| 66 | $Yote::YapiServer::Handler::webroot_dir = $self->{webroot_dir}; | ||
| 67 | |||
| 68 | print "Initializing database ($self->{db}{type})\n"; | ||
| 69 | |||
| 70 | my $store = $self->_new_store; | ||
| 71 | |||
| 72 | # Create/update database tables by explicitly generating tables for | ||
| 73 | # known classes. The recursive reference following in | ||
| 74 | # generate_table_from_module handles dependencies automatically. | ||
| 75 | print "Creating/updating database tables...\n"; | ||
| 76 | { | ||
| 77 | my $manager = $store->get_table_manager; | ||
| 78 | my $name2table = {}; | ||
| 79 | |||
| 80 | # Load root package | ||
| 81 | my $root_file = $root_package; | ||
| 82 | $root_file =~ s/::/\//g; | ||
| 83 | require "$root_file.pm"; | ||
| 84 | |||
| 85 | # Core infrastructure tables | ||
| 86 | for my $mod ( | ||
| 87 | $root_package, | ||
| 88 | 'Yote::YapiServer::User', | ||
| 89 | 'Yote::YapiServer::Session', | ||
| 90 | 'Yote::YapiServer::File', | ||
| 91 | ) { | ||
| 92 | $manager->generate_table_from_module($name2table, $mod); | ||
| 93 | } | ||
| 94 | |||
| 95 | # Installed app tables (and their referenced classes) | ||
| 96 | if ($root_package->can('installed_apps')) { | ||
| 97 | for my $app_class (values %{$root_package->installed_apps}) { | ||
| 98 | $manager->generate_table_from_module($name2table, $app_class); | ||
| 99 | } | ||
| 100 | } | ||
| 101 | |||
| 102 | # Bootstrap: create ObjectIndex, TableDefs, TableVersions first | ||
| 103 | # (these are always needed by SQLObjectStore infrastructure) | ||
| 104 | my @sql = ( | ||
| 105 | [$manager->create_object_index_sql], | ||
| 106 | [$manager->create_table_defs_sql], | ||
| 107 | [$manager->create_table_versions_sql], | ||
| 108 | ); | ||
| 109 | # Execute CREATE TABLE IF NOT EXISTS for all application tables | ||
| 110 | for my $table_name (sort keys %$name2table) { | ||
| 111 | push @sql, [$name2table->{$table_name}]; | ||
| 112 | } | ||
| 113 | |||
| 114 | $store->start_transaction; | ||
| 115 | for my $s (@sql) { | ||
| 116 | my ($query, @qparams) = @$s; | ||
| 117 | $store->query_do($query, @qparams); | ||
| 118 | } | ||
| 119 | $store->commit_transaction; | ||
| 120 | } | ||
| 121 | |||
| 122 | # Open the store | ||
| 123 | $store->open; | ||
| 124 | |||
| 125 | # Get or create root object | ||
| 126 | my $root = $store->fetch_root; | ||
| 127 | $root->init; | ||
| 128 | $store->save; | ||
| 129 | |||
| 130 | print "Server starting on http://localhost:$port\n"; | ||
| 131 | print "Press Ctrl+C to stop.\n\n"; | ||
| 132 | |||
| 133 | # Create server socket | ||
| 134 | my $listener = IO::Socket::INET->new( | ||
| 135 | LocalAddr => '0.0.0.0', | ||
| 136 | LocalPort => $port, | ||
| 137 | Proto => 'tcp', | ||
| 138 | Listen => SOMAXCONN, | ||
| 139 | Reuse => 1, | ||
| 140 | ) or die "Cannot create socket: $!"; | ||
| 141 | |||
| 142 | # Reap zombie processes | ||
| 143 | $SIG{CHLD} = 'IGNORE'; | ||
| 144 | |||
| 145 | while (my $conn = $listener->accept) { | ||
| 146 | my $pid = fork(); | ||
| 147 | |||
| 148 | if (!defined $pid) { | ||
| 149 | warn "Fork failed: $!"; | ||
| 150 | $conn->close; | ||
| 151 | next; | ||
| 152 | } | ||
| 153 | |||
| 154 | if ($pid == 0) { | ||
| 155 | # Child process | ||
| 156 | $listener->close; | ||
| 157 | |||
| 158 | # Reconnect to database in child | ||
| 159 | my $child_store = $self->_new_store; | ||
| 160 | $child_store->open; | ||
| 161 | |||
| 162 | eval { | ||
| 163 | $self->handle_request($conn, $child_store, $endpoint); | ||
| 164 | }; | ||
| 165 | |||
| 166 | warn "Error: $@" if $@; | ||
| 167 | |||
| 168 | $conn->close; | ||
| 169 | exit(0); | ||
| 170 | } | ||
| 171 | |||
| 172 | # Parent | ||
| 173 | $conn->close; | ||
| 174 | } | ||
| 175 | } | ||
| 176 | |||
| 177 | sub handle_request { | ||
| 178 | my ($self, $conn, $store, $endpoint) = @_; | ||
| 179 | |||
| 180 | # Read request | ||
| 181 | my $request = ''; | ||
| 182 | $conn->recv($request, 65536); | ||
| 183 | |||
| 184 | return unless $request; | ||
| 185 | |||
| 186 | # Parse HTTP request | ||
| 187 | my ($headers, $body) = split(/\r\n\r\n/, $request, 2); | ||
| 188 | my @header_lines = split(/\r\n/, $headers); | ||
| 189 | my $request_line = shift @header_lines; | ||
| 190 | |||
| 191 | my ($method, $path, $version) = split(/\s+/, $request_line); | ||
| 192 | |||
| 193 | # Parse headers | ||
| 194 | my %headers; | ||
| 195 | for my $line (@header_lines) { | ||
| 196 | my ($key, $value) = split(/:\s*/, $line, 2); | ||
| 197 | $headers{lc($key)} = $value; | ||
| 198 | } | ||
| 199 | |||
| 200 | # Get client IP | ||
| 201 | my $ip = $conn->peerhost || '127.0.0.1'; | ||
| 202 | |||
| 203 | # CORS headers for all responses | ||
| 204 | my @cors = ( | ||
| 205 | 'Access-Control-Allow-Origin: *', | ||
| 206 | 'Access-Control-Allow-Methods: POST, OPTIONS', | ||
| 207 | 'Access-Control-Allow-Headers: Content-Type', | ||
| 208 | ); | ||
| 209 | |||
| 210 | # Handle OPTIONS (CORS preflight) | ||
| 211 | if ($method eq 'OPTIONS') { | ||
| 212 | my $response = "HTTP/1.1 200 OK\r\n"; | ||
| 213 | $response .= join("\r\n", @cors) . "\r\n"; | ||
| 214 | $response .= "Content-Length: 0\r\n"; | ||
| 215 | $response .= "Connection: close\r\n"; | ||
| 216 | $response .= "\r\n"; | ||
| 217 | $conn->send($response); | ||
| 218 | return; | ||
| 219 | } | ||
| 220 | |||
| 221 | # Only handle POST to endpoint | ||
| 222 | unless ($method eq 'POST' && $path eq $endpoint) { | ||
| 223 | my $not_found = '{"ok":0,"error":"Not found"}'; | ||
| 224 | my $response = "HTTP/1.1 404 Not Found\r\n"; | ||
| 225 | $response .= "Content-Type: application/json\r\n"; | ||
| 226 | $response .= "Content-Length: " . length($not_found) . "\r\n"; | ||
| 227 | $response .= join("\r\n", @cors) . "\r\n"; | ||
| 228 | $response .= "Connection: close\r\n"; | ||
| 229 | $response .= "\r\n"; | ||
| 230 | $response .= $not_found; | ||
| 231 | $conn->send($response); | ||
| 232 | return; | ||
| 233 | } | ||
| 234 | |||
| 235 | # Handle Content-Length for body — reject oversized requests | ||
| 236 | my $content_length = $headers{'content-length'} || 0; | ||
| 237 | my $max_body = $self->{max_file_size} * 2; | ||
| 238 | if ($content_length > $max_body) { | ||
| 239 | my $err = '{"ok":0,"error":"request too large"}'; | ||
| 240 | my $response = "HTTP/1.1 413 Payload Too Large\r\n"; | ||
| 241 | $response .= "Content-Type: application/json\r\n"; | ||
| 242 | $response .= "Content-Length: " . length($err) . "\r\n"; | ||
| 243 | $response .= join("\r\n", @cors) . "\r\n"; | ||
| 244 | $response .= "Connection: close\r\n"; | ||
| 245 | $response .= "\r\n"; | ||
| 246 | $response .= $err; | ||
| 247 | $conn->send($response); | ||
| 248 | return; | ||
| 249 | } | ||
| 250 | while (length($body || '') < $content_length) { | ||
| 251 | my $more; | ||
| 252 | $conn->recv($more, $content_length - length($body || '')); | ||
| 253 | last unless $more; | ||
| 254 | $body .= $more; | ||
| 255 | } | ||
| 256 | #print "[YAPI] $ip: $body\n"; | ||
| 257 | |||
| 258 | # Process request | ||
| 259 | my $result = Yote::YapiServer::Handler->handle( | ||
| 260 | store => $store, | ||
| 261 | body => $body, | ||
| 262 | ip_address => $ip, | ||
| 263 | ); | ||
| 264 | |||
| 265 | #print "[YAPI] Response: $result\n\n"; | ||
| 266 | |||
| 267 | # Send response | ||
| 268 | my $response = "HTTP/1.1 200 OK\r\n"; | ||
| 269 | $response .= "Content-Type: application/json; charset=utf-8\r\n"; | ||
| 270 | $response .= "Content-Length: " . length($result) . "\r\n"; | ||
| 271 | $response .= join("\r\n", @cors) . "\r\n"; | ||
| 272 | $response .= "Connection: close\r\n"; | ||
| 273 | $response .= "\r\n"; | ||
| 274 | $response .= $result; | ||
| 275 | |||
| 276 | $conn->send($response); | ||
| 277 | } | ||
| 278 | |||
| 279 | 1; | ||
| 280 | |||
| 281 | __END__ |