Debian Codegraph @

extensions/Scribunto/includes/Engines/LuaStandalone/MWServer.lua

raw symbols SCIP
1 MWServer = {}
2
3 --- Create a new MWServer object
4 function MWServer:new( interpreterId, intSize )
5 interpreterId = tonumber( interpreterId )
6 if not interpreterId then
7 error( "bad argument #1 to 'MWServer:new' (must be a number or convertible to a number)", 2 )
8 end
9 intSize = tonumber( intSize )
10 if intSize ~= 4 and intSize ~= 8 then
11 error( "bad argument #2 to 'MWServer:new' (must be 4 or 8)", 2 )
12 end
13
14 obj = {
15 interpreterId = interpreterId,
16 nextChunkId = 1,
17 chunks = {},
18 xchunks = {},
19 protectedFunctions = {},
20 protectedEnvironments = {},
21 baseEnv = {}
22 }
23 if intSize == 4 then
24 obj.intMax = 2147483648
25 obj.intKeyMax = 2147483648
26 else
27 -- Lua can't represent most larger integers, so they may as well be sent to PHP as floats.
28 obj.intMax = 9007199254740992
29 obj.intKeyMax = 9223372036854775807
30 end
31 setmetatable( obj, self )
32 self.__index = self
33
34 obj:init()
35
36 return obj
37 end
38
39 --- Initialise a new MWServer object
40 function MWServer:init()
41 self.baseEnv = self:newEnvironment()
42 for funcName, func in pairs( self ) do
43 if type(func) == 'function' then
44 self.protectedFunctions[func] = true
45 end
46 end
47 self.protectedEnvironments[_G] = true
48 end
49
50 --- Serve requests until exit is requested
51 function MWServer:execute()
52 self:dispatch( nil )
53 self:debug( 'MWServer:execute: returning' )
54 end
55
56 -- Convert a multiple-return-value or a ... into a count and a table
57 function MWServer:listToCountAndTable( ... )
58 return select( '#', ... ), { ... }
59 end
60
61 --- Call a PHP function
62 -- Raise an error if the PHP handler requests it. May return any number
63 -- of values.
64 --
65 -- @param id The function ID, specified by a registerLibrary message
66 -- @param nargs Count of function arguments
67 -- @param args The function arguments
68 -- @return The return values from the PHP function
69 function MWServer:call( id, nargs, args )
70 local result = self:dispatch( {
71 op = 'call',
72 id = id,
73 nargs = nargs,
74 args = args
75 } )
76 if result.op == 'return' then
77 return unpack( result.values, 1, result.nvalues )
78 elseif result.op == 'error' then
79 -- Raise an error in the actual user code that called the function
80 -- The level is 3 since our immediate caller is a closure
81 error( result.value, 3 )
82 else
83 self:internalError( 'MWServer:call: unexpected result op' )
84 end
85 end
86
87 --- Handle a "call" message from PHP. Call the relevant function.
88 --
89 -- @param message The message from PHP
90 -- @return A response message to send back to PHP
91 function MWServer:handleCall( message )
92 if not self.chunks[message.id] then
93 return {
94 op = 'error',
95 value = 'function id ' .. message.id .. ' does not exist'
96 }
97 end
98
99 local n, result = self:listToCountAndTable( xpcall(
100 function ()
101 return self.chunks[message.id]( unpack( message.args, 1, message.nargs ) )
102 end,
103 function ( err )
104 return MWServer:attachTrace( err )
105 end
106 ) )
107
108 if result[1] then
109 -- table.remove( result, 1 ) renumbers from 2 to #result. But #result
110 -- is not necessarily "right" if result contains nils.
111 result = { unpack( result, 2, n ) }
112 return {
113 op = 'return',
114 nvalues = n - 1,
115 values = result
116 }
117 else
118 if result[2].value and result[2].trace then
119 return {
120 op = 'error',
121 value = result[2].value,
122 trace = result[2].trace,
123 }
124 else
125 return {
126 op = 'error',
127 value = result[2]
128 }
129 end
130 end
131 end
132
133 --- The xpcall() error handler for handleCall(). Modifies the error object
134 -- to include a structured backtrace
135 --
136 -- @param err The error object
137 -- @return The new error object
138 function MWServer:attachTrace( err )
139 return {
140 value = err,
141 trace = self:getStructuredTrace( 2 )
142 }
143 end
144
145 --- Handle a "loadString" message from PHP.
146 -- Load the function and return a chunk ID.
147 --
148 -- @param message The message from PHP
149 -- @return A response message to send back to PHP
150 function MWServer:handleLoadString( message )
151 if string.find( message.text, '\27Lua', 1, true ) then
152 return {
153 op = 'error',
154 value = 'cannot load code with a Lua binary chunk marker escape sequence in it'
155 }
156 end
157 local chunk, errorMsg = loadstring( message.text, message.chunkName )
158 if chunk then
159 setfenv( chunk, self.baseEnv )
160 local id = self:addChunk( chunk )
161 return {
162 op = 'return',
163 nvalues = 1,
164 values = {id}
165 }
166 else
167 return {
168 op = 'error',
169 value = errorMsg
170 }
171 end
172 end
173
174 --- Add a function value to the list of tracked chunks and return its associated ID.
175 -- Adding a chunk allows it to be referred to in messages from PHP.
176 --
177 -- @param chunk The function value
178 -- @return The chunk ID
179 function MWServer:addChunk( chunk )
180 local id = self.nextChunkId
181 self.nextChunkId = id + 1
182 self.chunks[id] = chunk
183 self.xchunks[chunk] = id
184 return id
185 end
186
187 --- Handle a "cleanupChunks" message from PHP.
188 -- Remove any chunks no longer referenced by PHP code.
189 --
190 -- @param message The message from PHP
191 -- @return A response message to send back to PHP
192 function MWServer:handleCleanupChunks( message )
193 for id, chunk in pairs( self.chunks ) do
194 if not message.ids[id] then
195 self.chunks[id] = nil
196 self.xchunks[chunk] = nil
197 end
198 end
199
200 return {
201 op = 'return',
202 nvalues = 0,
203 values = {}
204 }
205 end
206
207 --- Handle a "registerLibrary" message from PHP.
208 -- Add the relevant functions to the base environment.
209 --
210 -- @param message The message from PHP
211 -- @return The response message
212 function MWServer:handleRegisterLibrary( message )
213 local startPos = 1
214 local component
215 if not self.baseEnv[message.name] then
216 self.baseEnv[message.name] = {}
217 end
218 local t = self.baseEnv[message.name]
219
220 for name, id in pairs( message.functions ) do
221 t[name] = function( ... )
222 return self:call( id, self:listToCountAndTable( ... ) )
223 end
224 -- Protect the function against setfenv()
225 self.protectedFunctions[t[name]] = true
226 end
227
228 return {
229 op = 'return',
230 nvalues = 0,
231 values = {}
232 }
233 end
234
235 --- Handle a "wrapPhpFunction" message from PHP.
236 -- Create an anonymous function
237 --
238 -- @param message The message from PHP
239 -- @return The response message
240 function MWServer:handleWrapPhpFunction( message )
241 local id = message.id
242 local func = function( ... )
243 return self:call( id, self:listToCountAndTable( ... ) )
244 end
245 -- Protect the function against setfenv()
246 self.protectedFunctions[func] = true
247
248 return {
249 op = 'return',
250 nvalues = 1,
251 values = { func }
252 }
253 end
254
255 --- Handle a "getStatus" message from PHP
256 --
257 -- @param message The request message
258 -- @return The response message
259 function MWServer:handleGetStatus( message )
260 local nullRet = {
261 op = 'return',
262 nvalues = 0,
263 values = {}
264 }
265 local file = io.open( '/proc/self/stat' )
266 if not file then
267 return nullRet
268 end
269 local s = file:read('*a')
270 file:close()
271 local t = {}
272 for token in string.gmatch(s, '[^ ]+') do
273 t[#t + 1] = token
274 end
275 if #t < 22 then
276 return nullRet
277 end
278 return {
279 op = 'return',
280 nvalues = 1,
281 values = {{
282 pid = tonumber(t[1]),
283 time = tonumber(t[14]) + tonumber(t[15]) + tonumber(t[16]) + tonumber(t[17]),
284 vsize = tonumber(t[23]),
285 }}
286 }
287 end
288
289 --- The main request/response loop
290 --
291 -- Send a request message and return its matching reply message. Handle any
292 -- intervening requests (i.e. re-entrant calls) by dispatching them to the
293 -- relevant handler function.
294 --
295 -- The request message may optionally be omitted, to listen for request messages
296 -- without first sending a request of its own. Such a dispatch() call will
297 -- continue running until termination is requested by PHP. Typically, PHP does
298 -- this with a SIGTERM signal.
299 --
300 -- @param msgToPhp The message to send to PHP. Optional.
301 -- @return The matching response message
302 function MWServer:dispatch( msgToPhp )
303 if msgToPhp then
304 self:sendMessage( msgToPhp, 'call' )
305 end
306 while true do
307 local msgFromPhp = self:receiveMessage()
308 local msgToPhp
309 local op = msgFromPhp.op
310 if op == 'return' or op == 'error' then
311 return msgFromPhp
312 elseif op == 'call' then
313 msgToPhp = self:handleCall( msgFromPhp )
314 self:sendMessage( msgToPhp, 'reply' )
315 elseif op == 'loadString' then
316 msgToPhp = self:handleLoadString( msgFromPhp )
317 self:sendMessage( msgToPhp, 'reply' )
318 elseif op == 'registerLibrary' then
319 msgToPhp = self:handleRegisterLibrary( msgFromPhp )
320 self:sendMessage( msgToPhp, 'reply' )
321 elseif op == 'wrapPhpFunction' then
322 msgToPhp = self:handleWrapPhpFunction( msgFromPhp )
323 self:sendMessage( msgToPhp, 'reply' )
324 elseif op == 'cleanupChunks' then
325 msgToPhp = self:handleCleanupChunks( msgFromPhp )
326 self:sendMessage( msgToPhp, 'reply' )
327 elseif op == 'getStatus' then
328 msgToPhp = self:handleGetStatus( msgFromPhp )
329 self:sendMessage( msgToPhp, 'reply' )
330 elseif op == 'quit' then
331 self:debug( 'MWServer:dispatch: quit message received' )
332 os.exit(0)
333 elseif op == 'testquit' then
334 self:debug( 'MWServer:dispatch: testquit message received' )
335 os.exit(42)
336 else
337 self:internalError( "Invalid message operation" )
338 end
339 end
340 end
341
342 --- Write a message to the debug output stream.
343 -- Some day this may be configurable, currently it just unconditionally writes
344 -- the message to stderr. The PHP host will redirect those errors to /dev/null
345 -- by default, but it can be configured to send them to a file.
346 --
347 -- @param s The message
348 function MWServer:debug( s )
349 if ( type(s) == 'string' ) then
350 io.stderr:write( s .. '\n' )
351 else
352 io.stderr:write( self:serialize( s ) .. '\n' )
353 end
354 end
355
356 --- Raise an internal error
357 -- Write a message to stderr and then exit with a failure status. This should
358 -- be called for errors which cannot be allowed to be caught with pcall().
359 --
360 -- This must be used for protocol errors, or indeed any error from a context
361 -- where a dispatch() call lies between the error source and a possible pcall()
362 -- handler. If dispatch() were terminated by a regular error() call, the
363 -- resulting protocol violation could lead to a deadlock.
364 --
365 -- @param msg The error message
366 function MWServer:internalError( msg )
367 io.stderr:write( debug.traceback( msg ) .. '\n' )
368 os.exit( 1 )
369 end
370
371 --- Raise an I/O error
372 -- Helper function for errors from the io and file modules, which may optionally
373 -- return an informative error message as their second return value.
374 function MWServer:ioError( header, info )
375 if type( info) == 'string' then
376 self:internalError( header .. ': ' .. info )
377 else
378 self:internalError( header )
379 end
380 end
381
382 --- Send a message to PHP
383 -- @param msg The message table
384 -- @param direction 'call' or 'reply'
385 function MWServer:sendMessage( msg, direction )
386 if not msg.op then
387 self:internalError( "MWServer:sendMessage: invalid message", 2 )
388 end
389 self:debug('TX ==> ' .. msg.op)
390
391 -- If we're making an outgoing call, let errors go to our caller. If we're
392 -- replying to a call from PHP, catch serialization errors and return them
393 -- to PHP.
394 local encMsg;
395 if direction == 'reply' then
396 local ok
397 ok, encMsg = pcall( self.encodeMessage, self, msg )
398 if not ok then
399 self:debug('Serialization failed: ' .. encMsg)
400 self:debug('TX ==> error')
401 encMsg = self:encodeMessage( { op = 'error', value = encMsg } )
402 end
403 else
404 encMsg = self:encodeMessage( msg )
405 end
406
407 local success, errorMsg = io.stdout:write( encMsg )
408 if not success then
409 self:ioError( 'Write error', errorMsg )
410 end
411 io.stdout:flush()
412 end
413
414 --- Wait for a message from PHP and then decode and return it as a table
415 -- @return The received message
416 function MWServer:receiveMessage()
417 -- Read the header
418 local header, errorMsg = io.stdin:read( 16 )
419 if header == nil and errorMsg == nil then
420 -- End of file on stdin, exit gracefully
421 os.exit(0)
422 end
423
424 if not header or #header ~= 16 then
425 self:ioError( 'Read error', errorMsg )
426 end
427 local length = self:decodeHeader( header )
428
429 -- Read the body
430 local body, errorMsg = io.stdin:read( length )
431 if not body then
432 self:ioError( 'Read error', errorMsg )
433 end
434 if #body ~= length then
435 self:ioError( 'Read error', errorMsg )
436 end
437
438 -- Unserialize it
439 msg = self:unserialize( body )
440 self:debug('RX <== ' .. msg.op)
441 if msg.op == 'error' then
442 self:debug( 'Error: ' .. tostring( msg.value ) )
443 end
444 return msg
445 end
446
447 --- Encode a message for sending to PHP
448 function MWServer:encodeMessage( message )
449 local serialized = self:serialize( message )
450 local length = #serialized
451 local check = length * 2 - 1
452 return string.format( '%08x%08x', length, check ) .. serialized
453 end
454
455 -- Faster to create the table once than for each call to MWServer:serialize()
456 local serialize_replacements = {
457 ['\r'] = '\\r',
458 ['\n'] = '\\n',
459 ['\\'] = '\\\\',
460 }
461
462 --- Convert a value to a string suitable for passing to PHP's unserialize().
463 -- Note that the following replacements must be performed before calling
464 -- unserialize:
465 -- "\\r" => "\r"
466 -- "\\n" => "\n"
467 -- "\\\\" => "\\"
468 --
469 -- @param var The value.
470 function MWServer:serialize( var )
471 local done = {}
472
473 local function isInteger( var, max )
474 return type(var) == 'number'
475 and math.floor( var ) == var
476 and var >= -max
477 and var < max
478 end
479
480 local function recursiveEncode( var, level )
481 local t = type( var )
482 if t == 'nil' then
483 return 'N;'
484 elseif t == 'number' then
485 if isInteger( var, self.intMax ) then
486 return 'i:' .. string.format( '%d', var ) .. ';'
487 elseif var < math.huge and var > -math.huge then
488 return 'd:' .. string.format( '%.17g', var ) .. ';'
489 elseif var == math.huge then
490 return 'd:INF;'
491 elseif var == -math.huge then
492 return 'd:-INF;'
493 else
494 return 'd:NAN;'
495 end
496 elseif t == 'string' then
497 return 's:' .. string.len( var ) .. ':"' .. var .. '";'
498 elseif t == 'boolean' then
499 if var then
500 return 'b:1;'
501 else
502 return 'b:0;'
503 end
504 elseif t == 'table' then
505 if done[var] then
506 error("Cannot pass circular reference to PHP")
507 end
508 done[var] = true
509 local buf = { '' }
510 local numElements = 0
511 local seen = {}
512 for key, value in pairs(var) do
513 local k = key
514 local t = type( k )
515
516 -- Convert integers in range to look like standard integers.
517 -- Use tostring() for the rest. Reject all other non-strings.
518 if isInteger( k, self.intKeyMax ) then
519 k = string.format( '%d', k )
520 elseif t == 'number' then
521 k = tostring( k );
522 elseif t ~= 'string' then
523 error("Cannot use " .. t .. " as an array key when passing data from Lua to PHP");
524 end
525
526 -- Zend PHP doesn't really care whether integer keys are serialized
527 -- as ints or strings, it converts them correctly on unserialize.
528 -- But HHVM does depend on it, so keep doing it for now.
529 local n = nil
530 if k == '0' or k:match( '^-?[1-9]%d*$' ) then
531 n = tonumber( k )
532 if n == -9223372036854775808 and k ~= '-9223372036854775808' then
533 -- Bad edge rounding
534 n = nil
535 end
536 end
537 if isInteger( n, self.intKeyMax ) then
538 buf[#buf + 1] = 'i:' .. k .. ';'
539 else
540 buf[#buf + 1] = recursiveEncode( k, level + 1 )
541 end
542
543 -- Detect collisions, e.g. { [0] = 'foo', ["0"] = 'bar' }
544 if seen[k] then
545 error( 'Collision for array key ' .. k .. ' when passing data from Lua to PHP' );
546 end
547 seen[k] = true
548
549 buf[#buf + 1] = recursiveEncode( value, level + 1 )
550 numElements = numElements + 1
551 end
552 buf[1] = 'a:' .. numElements .. ':{'
553 buf[#buf + 1] = '}'
554 return table.concat(buf)
555 elseif t == 'function' then
556 local id
557 if self.xchunks[var] then
558 id = self.xchunks[var]
559 else
560 id = self:addChunk(var)
561 end
562 -- Serialization of a PHP class name is fun when it is namespaced...
563 return 'O:42:"Scribunto_LuaStandaloneInterpreterFunction":2:{s:13:"interpreterId";i:' ..
564 self.interpreterId .. ';s:2:"id";i:' .. id .. ';}'
565 elseif t == 'thread' then
566 error("Cannot pass thread to PHP")
567 elseif t == 'userdata' then
568 error("Cannot pass userdata to PHP")
569 else
570 error("Cannot pass unrecognised type to PHP")
571 end
572 end
573
574 return recursiveEncode( var, 0 ):gsub( '[\r\n\\]', serialize_replacements )
575 end
576
577 --- Convert a Lua expression string to its corresponding value.
578 -- Convert any references of the form chunk[id] to the corresponding function
579 -- values.
580 function MWServer:unserialize( text )
581 local func = loadstring( 'return ' .. text )
582 if not func then
583 self:internalError( "MWServer:unserialize: invalid chunk" )
584 end
585 -- Don't waste JIT cache space by storing every message in it
586 if jit then
587 jit.off( func )
588 end
589 setfenv( func, { chunks = self.chunks } )
590 return func()
591 end
592
593 --- Decode a message header.
594 -- @param header The header string
595 -- @return The body length
596 function MWServer:decodeHeader( header )
597 local length = string.sub( header, 1, 8 )
598 local check = string.sub( header, 9, 16 )
599 if not string.match( length, '^%x+$' ) or not string.match( check, '^%x+$' ) then
600 self:internalError( "Error decoding message header: " .. length .. '/' .. check )
601 end
602 length = tonumber( length, 16 )
603 check = tonumber( check, 16 )
604 if length * 2 - 1 ~= check then
605 self:internalError( "Error decoding message header" )
606 end
607 return length
608 end
609
610 --- Get a traceback similar to the one from debug.traceback(), but as a table
611 -- rather than formatted as a string
612 --
613 -- @param The level to start at: 1 for the function that called getStructuredTrace()
614 -- @return A table with the backtrace information
615 function MWServer:getStructuredTrace( level )
616 level = level + 1
617 local trace = {}
618 while true do
619 local rawInfo = debug.getinfo( level, 'nSl' )
620 if rawInfo == nil then
621 break
622 end
623 local info = {}
624 for i, key in ipairs({'short_src', 'what', 'currentline', 'name', 'namewhat', 'linedefined'}) do
625 info[key] = rawInfo[key]
626 end
627 if string.match( info['short_src'], '/MWServer.lua$' ) then
628 info['short_src'] = 'MWServer.lua'
629 end
630 if string.match( rawInfo['short_src'], '/mw_main.lua$' ) then
631 info['short_src'] = 'mw_main.lua'
632 end
633 table.insert( trace, info )
634 level = level + 1
635 end
636 return trace
637 end
638
639 --- Create a table to be used as a restricted environment, based on the current
640 -- global environment.
641 --
642 -- @return The environment table
643 function MWServer:newEnvironment()
644 local allowedGlobals = {
645 -- base
646 "assert",
647 "error",
648 "getmetatable",
649 "ipairs",
650 "next",
651 "pairs",
652 "pcall",
653 "rawequal",
654 "rawget",
655 "rawset",
656 "select",
657 "setmetatable",
658 "tonumber",
659 "type",
660 "unpack",
661 "xpcall",
662 "_VERSION",
663 -- libs
664 "table",
665 "math"
666 }
667
668 local env = {}
669 for i = 1, #allowedGlobals do
670 env[allowedGlobals[i]] = mw.clone( _G[allowedGlobals[i]] )
671 end
672
673 -- Cloning 'string' doesn't work right, because strings still use the old
674 -- 'string' as the metatable. So just copy it.
675 env.string = string
676
677 env._G = env
678 env.tostring = function( val )
679 return self:tostring( val )
680 end
681 env.string.dump = nil
682 env.setfenv, env.getfenv = mw.makeProtectedEnvFuncs(
683 self.protectedEnvironments, self.protectedFunctions )
684 env.debug = {
685 traceback = debug.traceback
686 }
687 env.os = {
688 date = os.date,
689 difftime = os.difftime,
690 time = os.time,
691 clock = os.clock
692 }
693 return env
694 end
695
696 --- An implementation of tostring() which does not expose pointers.
697 function MWServer:tostring(val)
698 local mt = getmetatable( val )
699 if mt and mt.__tostring then
700 return mt.__tostring(val)
701 end
702 local typeName = type(val)
703 local nonPointerTypes = {number = true, string = true, boolean = true, ['nil'] = true}
704 if nonPointerTypes[typeName] then
705 return tostring(val)
706 else
707 return typeName
708 end
709 end
710
711 return MWServer