robin/maivi
a tiny cute lua web framework
git clone https://git.robinwobin.dev/robin/maivi
6e07b35
push-srxvuswpkqxx
1const std =@import ( "std" ); 2const Io =std . Io ; 3const http =std . http ; 4const Request =http . Server . Request ; 5const Status =http . Status ; 6 7const fern =@import ( "fern" ); 8 9const handler =@import ( "handler.zig" ); 10const Connection =handler . Connection ; 11const maivi =@import ( "root.zig" ); 12 13pub fn requestHeader ( request : Request , name : [] const u8 ) ? http . Header { 14var it =request . iterateHeaders (); 15while ( it . next ()) | header | 16if ( std . mem . eql ( u8 , header . name , name )) return header ; 17return null ; 18} 19 20const SERVER_HEADER : http . Header =.{ 21. name ="server" , 22. value ="maivi" , 23}; 24 25pub fn respond ( request : * Request , buf : [] u8 , opts : struct { 26content_length : ? u64 =null , 27content_type : ContentType =. octetstream , 28status : http . Status =. ok , 29reason : ? [] const u8 =null , 30headers : [] const http . Header =& .{}, 31}) ! http . BodyWriter { 32const headers =try std . mem . concat ( maivi . allocator , http . Header , & .{ 33& .{ SERVER_HEADER }, 34& .{ opts . content_type . header ()}, 35opts . headers , 36}); 37defer maivi . allocator . free ( headers ); 38 39return try request . respondStreaming ( buf , .{ 40. content_length =opts . content_length , 41. respond_options =.{ 42. status =opts . status , 43. reason =opts . reason , 44. extra_headers =headers , 45}, 46}); 47} 48 49// u usually want to use sendfile(2) to directly stream other FDs 50// luckily zig std is awesome and already implements everything 51// b.writer.sendFileAll(file_reader: *Reader, .unlimited); 52// later on u probably wanna make it chunked too, see 53// std.http.BodyWriter.chunkedSendFile 54// for reference :3 55 56pub fn sendfile ( conn : * Connection , dir : std . Io . Dir , path : [] const u8 ) ! void { 57const request =conn . request ; 58 59const sub_path =std . mem . cutPrefix ( u8 , path , "/" ) orelse path ; 60const file =try dir . openFile ( conn . io , sub_path , .{}); 61defer file . close ( conn . io ); 62 63const stat =try file . stat ( conn . io ); 64if ( stat . kind == . directory ) return error . IsDirectory ; 65if ( stat . kind != . file ) return error . NonFile ; 66const size =stat . size ; 67 68const content_type =content_type_for_file ( path ) orelse . txt ; 69 70var wbuf : [ 0x0 ] u8 =undefined ; 71var b =try maivi . helpers . respond ( request , & wbuf , .{ 72. content_length =size , 73. content_type =content_type , 74}); 75try b . flush (); 76 77var remaining =size ; 78var offset : i64 =0 ; 79while ( remaining > 0 ) { 80const count : usize =@intCast ( @min ( remaining , 0x7ffff000 )); // ~2GiB 81const ret =std . c . sendfile ( conn . handle , file . handle , & offset , count ); 82if ( ret == - 1 ) { 83const errno =std . c . errno ( ret ); 84if ( errno == . AGAIN or errno == . INTR ) continue ; 85return error . SendFileFailed ; 86} else if ( ret == 0 ) 87return error . UnexpectedEndOfFile ; 88remaining -= @intCast ( ret ); 89} 90 91b . state = . end ; 92} 93 94/// NOTE: returns allocated memory that can optionally be freed by the caller 95pub fn redirect ( arena : std . mem . Allocator , request : * Request , uri : [] const u8 , code : ? Status ) ! [] http . Header { 96const headers =try std . mem . concat ( arena , http . Header , & .{ 97& .{ SERVER_HEADER }, 98& .{.{ . name ="location" , . value =uri }}, 99}); 100 101try request . respond ( uri , .{ 102. status =code orelse Status . found , 103. extra_headers =headers , 104}); 105 106return headers ; 107} 108 109pub fn statusFromErr ( err : anyerror ) ? Status { 110return switch ( err ) { 111error . FileNotFound =>Status . not_found , 112error . AccessDenied =>Status . forbidden , 113else =>null , 114}; 115} 116 117pub fn content_type_for_file ( path : [] const u8 ) ? ContentType { 118return . forExtension ( std . fs . path . extension ( path )); 119} 120 121pub const ContentType =enum { 122@ "3g2" , 123@ "3gp" , 124@ "7z" , 125aac , 126abw , 127apng , 128arc , 129avi , 130avif , 131azw , 132bin , 133bmp , 134bz , 135bz2 , 136cda , 137csh , 138css , 139csv , 140doc , 141docx , 142eot , 143epub , 144gif , 145gz , 146htm , 147html , 148ico , 149ics , 150jar , 151jpeg , 152jpg , 153js , 154json , 155jsonld , 156m4a , 157md , 158midi , 159mid , 160mjs , 161mp3 , 162mp4 , 163mpeg , 164mpkg , 165octetstream , 166odp , 167ods , 168odt , 169oga , 170ogv , 171ogx , 172opus , 173otf , 174, 175php , 176png , 177ppt , 178pptx , 179rar , 180rtf , 181sh , 182svg , 183tar , 184tiff , 185tif , 186tkt , 187ts , 188ttf , 189txt , 190vsd , 191wasm , 192wav , 193weba , 194webm , 195webmanifest , 196webp , 197woff , 198woff2 , 199xhtml , 200xls , 201xlsx , 202xml , 203xul , 204zip , 205 206pub fn header ( self : ContentType ) http . Header { 207return .{ 208. name ="content-type" , 209. value =self . toHeader (), 210}; 211} 212 213fn toHeader ( self : ContentType ) [] const u8 { 214return switch ( self ) { 215. @ "3g2" =>"audio/3gpp2" , 216. @ "3gp" =>"audio/3gpp" , 217. @ "7z" =>"application/x-7z-compressed" , 218. aac =>"audio/aac" , 219. abw =>"application/x-abiword" , 220. apng =>"image/apng" , 221. arc =>"application/x-freearc" , 222. avi =>"video/x-msvideo" , 223. avif =>"image/avif" , 224. azw =>"application/vnd.amazon.ebook" , 225. bin =>"application/octet-stream" , 226. bmp =>"image/bmp" , 227. bz =>"application/x-bzip" , 228. bz2 =>"application/x-bzip2" , 229. cda =>"application/x-cdf" , 230. csh =>"application/x-csh" , 231. css =>"text/css" , 232. csv =>"text/csv" , 233. doc =>"application/msword" , 234. docx =>"application/vnd.openxmlformats-officedocument.wordprocessingml.document" , 235. eot =>"application/vnd.ms-fontobject" , 236. epub =>"application/epub+zip" , 237. gif =>"image/gif" , 238. gz =>"application/x-gzip" , 239. htm , . html =>"text/html" , 240. ico =>"image/vnd.microsoft.icon" , 241. ics =>"text/calendar" , 242. jar =>"application/java-archive" , 243. jpeg , . jpg =>"image/jpeg" , 244. js =>"text/javascript" , 245. json =>"application/json" , 246. jsonld =>"application/ld+json" , 247. m4a =>"audio/mp4" , 248. md =>"text/markdown" , 249. mid , . midi =>"audio/x-midi" , 250. mjs =>"text/javascript" , 251. mp3 =>"audio/mpeg" , 252. mp4 =>"video/mp4" , 253. mpeg =>"video/mpeg" , 254. mpkg =>"application/vnd.apple.installer+xml" , 255. octetstream =>"application/octet-stream" , 256. odp =>"application/vnd.oasis.opendocument.presentation" , 257. ods =>"application/vnd.oasis.opendocument.spreadsheet" , 258. odt =>"application/vnd.oasis.opendocument.text" , 259. oga =>"audio/ogg" , 260. ogv =>"video/ogg" , 261. ogx =>"application/ogg" , 262. opus =>"audio/ogg" , 263. otf =>"font/otf" , 264. "application/pdf" , 265. php =>"application/x-httpd-php" , 266. png =>"image/png" , 267. ppt =>"application/vnd.ms-powerpoint" , 268. pptx =>"application/vnd.openxmlformats-officedocument.presentationml.presentation" , 269. rar =>"application/vnd.rar" , 270. rtf =>"application/rtf" , 271. sh =>"application/x-sh" , 272. svg =>"image/svg+xml" , 273. tar =>"application/x-tar" , 274. tif , . tiff =>"image/tiff" , 275. tkt =>"text/trinket" , 276. ts =>"video/mp2t" , 277. ttf =>"font/ttf" , 278. txt =>"text/plain" , 279. vsd =>"application/vnd.visio" , 280. wasm =>"text/wasm" , 281. wav =>"audio/wav" , 282. weba =>"audio/webm" , 283. webm =>"video/webm" , 284. webmanifest =>"application/manifest+json" , 285. webp =>"image/webp" , 286. woff =>"font/woff" , 287. woff2 =>"font/woff2" , 288. xhtml =>"application/xhtml+xml" , 289. xls =>"application/vnd.ms-excel" , 290. xlsx =>"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" , 291. xml =>"application/xml" , 292. xul =>"application/vnd.mozilla.xul+xml" , 293. zip =>"application/x-zip-compressed" , 294}; 295} 296 297pub fn forExtension ( ext : [] const u8 ) ? ContentType { 298if ( ext . len == 0 ) return null ; 299const temp =if ( ext [ 0 ] == '.' ) ext [ 1 ..] else ext ; 300if ( temp . len == 0 ) return null ; 301if ( temp . len > 5 ) return null ; 302 303var normalized : [ 5 ] u8 =undefined ; 304for ( temp , 0 ..) |c , i |{ 305normalized [ i ] = std . ascii . toLower ( c ); 306} 307 308return ContentType . map . get ( normalized [ 0 .. temp . len ]); 309} 310 311const map =std . StaticStringMap ( @This ()). initComptime (.{ 312.{ "css" , . css }, 313.{ "csv" , . csv }, 314.{ "eot" , . eot }, 315.{ "gif" , . gif }, 316.{ "gz" , . gz }, 317.{ "htm" , . html }, 318.{ "html" , . html }, 319.{ "ico" , . ico }, 320.{ "jpeg" , . jpg }, 321.{ "jpg" , . jpg }, 322.{ "js" , . js }, 323.{ "json" , . json }, 324.{ "otf" , . otf }, 325.{ "pdf" , . }, 326.{ "png" , . png }, 327.{ "svg" , . svg }, 328.{ "tar" , . tar }, 329.{ "ttf" , . ttf }, 330.{ "txt" , . txt }, 331.{ "wasm" , . wasm }, 332.{ "webp" , . webp }, 333.{ "woff" , . woff }, 334.{ "woff2" , . woff2 }, 335.{ "xml" , . xml }, 336}); 337}; 338 339pub fn read_file ( io : Io , allocator : std . mem . Allocator , dir : std . Io . Dir , path : [] const u8 ) ! [] const u8 { 340fern . debug (). ctx ( "helpers.read_file" ). str ( "path" , path ). log (); 341 342const sub_path =std . mem . cutPrefix ( u8 , path , "/" ) orelse path ; 343const file =try dir . openFile ( io , sub_path , .{}); 344defer file . close ( io ); 345 346const stat =try file . stat ( io ); 347if ( stat . kind == . directory ) return error . IsDirectory ; 348if ( stat . kind != . file ) return error . NonFile ; 349const size =stat . size ; 350 351var buf : [ 0x400 ] u8 =undefined ; 352var file_reader =file . reader ( io , & buf ); 353const reader =& file_reader . interface ; 354const contents =try reader . readAlloc ( allocator , size ); 355 356return contents ; 357} 358 359const SanitizationError =error { NoTrailingSlashes } || std . mem . Allocator . Error ; 360pub fn sanitize ( arena : std . mem . Allocator , path : [] const u8 ) ! [] u8 { 361const buf =try arena . dupe ( u8 , path ); 362const decoded =std . Uri . percentDecodeInPlace ( buf ); 363 364// redirect: no-trailing-slashes 365if ( path . len > 1 and std . mem . endsWith ( u8 , path , "/" )) return error . TrailingSlash ; 366 367// replace double slash (//) with single slash (/) 368return decoded [ 0 .. std . mem . collapseRepeatsLen ( u8 , decoded , '/' )]; 369} 370 371pub fn try_path ( conn : * Connection , dir : std . Io . Dir , path : ? [] const u8 ) ! bool { 372sendfile ( conn , dir , path orelse conn . path ) catch | err | switch ( err ) { 373error . FileNotFound =>return false , 374else =>return err , 375}; 376return true ; 377}