CoCalc Shared Fileswww / calc / calc / magma.py
Author: William A. Stein
1###########################################################
2#                                                         #
3# magma.py -- compute things using system calls to MAGMA  #
4#                                                         #
5# Original author: William Stein, 10/10/2003              #
6# Released under GPL, etc.                                #
7#                                                         #
8###########################################################
9
10import os, string
11
12BAD=['system', 'open', 'getcurrentdirectory', 'getuid', 'isintrinsic',\
13     'file', 'pipe', 'memory', 'editor', 'outputfile', \
14     'load', 'save', 'attach', 'read', 'write', 'alarm', '%', 'sethelp',\
15     'put']
16
17MAXTIME="20"
18MAXMEMORY="100000000"
19MAXLEN = 10000
20
21MAGMA='ulimit -t %s; nice -n 19 /usr/local/bin/magma'%MAXTIME
22
23def strip(cmd):
24    cmd0 = cmd.lower()
25    ans=""
26    for x in cmd.lower():
27        if ord(x) >= ord("a") and ord(x) <= ord("z"):
28            ans=ans+x
29    return ans
30
31def magma(cmd):
32    s=strip(cmd)
33    for word in BAD:
34        if s.find(word) != -1:
35            return "WARNING: MAGMA command contains unsafe command "+\
36                   "'%s', so it will not be executed."%word
37    for word in BAD:
38        if cmd.replace("%o","").find(word) != -1:
39            return "WARNING: MAGMA command contains unsafe command "+\
40                   "'%s', so it will not be executed."%word
41    mtime=MAXTIME
42    cmd="SetIgnorePrompt(true);\n"+cmd
43    cmd="Alarm(%s);"%mtime+cmd
44    cmd="SetMemoryLimit(%s);\n;"%MAXMEMORY+cmd
45    cmd=cmd+';\nquit;'
46
47    process = os.popen3(MAGMA)
48    process[0].write(cmd)
49    process[0].close()
52    n0=out.find("Type ?")
53    n1=out.find("quit.")+5
54    out=out[:n0]+"   -------------------------------------\n"+out[n1:]
55    if len(out) > MAXLEN:
56        out = out[:MAXLEN]
57        out = out + "\n ** WARNING: Output too long, hence truncated."
58    if err!="":
59        out=out+"\nErrors: "+err
60    if out.find("Alarm clock") != -1 or out.find("Killed") != -1:
61        out = "** WARNING: Computation time exceeded %s seconds, so computation was terminated after %s seconds. **\n\n"%(MAXTIME,MAXTIME) + "\n"+out
62    if out.find("User memory limit") != -1:
63        out = "** WARNING: Computation used more memory than allowed. **\n\n" + out
64    return out
65
66
67
68