File size: 6,176 Bytes
591f8bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
"""
وحدة تنفيذ كود Python بأمان
- تعمل في subprocess معفى (subprocess)
- حدود زمنية (timeout)
- حد ذاكرة
- التقاط stdout و stderr
- منع الوصول للنظام
"""
import asyncio
import os
import resource
import shutil
import subprocess
import sys
import tempfile
import time
import uuid
from typing import Dict, Optional, Tuple

# قائمة الوحدات المسموح بها (whitelist)
ALLOWED_MODULES = {
    "math", "random", "datetime", "json", "re", "collections", "itertools",
    "functools", "operator", "string", "textwrap", "unicodedata",
    "statistics", "fractions", "decimal", "heapq", "bisect",
    "hashlib", "base64", "binascii", "uuid", "secrets",
    # للرسم
    "matplotlib", "numpy", "pandas",
    # للنصوص
    "csv", "io",
    # للمعالجة
    "typing",
}

# وحدات محظورة تماماً (blacklist)
BLOCKED_MODULES = {
    "os", "sys", "subprocess", "shutil", "pathlib",
    "socket", "http", "urllib", "requests", "ftplib", "smtplib",
    "multiprocessing", "threading", "asyncio",
    "ctypes", "cffi", "importlib",
    "pickle", "shelve",
    "builtins",
}

MAX_OUTPUT_CHARS = 4000
MAX_EXECUTION_TIME = 15  # seconds
MAX_MEMORY_MB = 256


def check_code_safety(code: str) -> Tuple[bool, str]:
    """فحص أمني أولي للكود"""
    # منع imports خطرة
    for blocked in BLOCKED_MODULES:
        if f"import {blocked}" in code or f"from {blocked}" in code:
            return False, f"وحدة محظورة: {blocked}"
    # منع eval/exec من أي نوع
    if "__import__" in code:
        return False, "__import__ محظور"
    if "exec(" in code or "eval(" in code:
        return False, "exec/eval محظور"
    # منع فتح ملفات خارجية
    if "open(" in code and "/etc" in code:
        return False, "الوصول لـ /etc محظور"
    # منع الكتابة خارج المجلد المؤقت
    if "open('/" in code or 'open("/' in code:
        # نسمح فقط بمسارات نسبية أو في /tmp
        pass  # الفحص يحدث عبر subprocess restrictions
    return True, "OK"


def set_memory_limit():
    """ضبط حد الذاكرة للـ subprocess"""
    try:
        soft, hard = MAX_MEMORY_MB * 1024 * 1024, MAX_MEMORY_MB * 1024 * 1024
        resource.setrlimit(resource.RLIMIT_AS, (soft, hard))
    except (ValueError, resource.error):
        pass  # في بعض الأنظمة لا يعمل


async def execute_python(
    code: str,
    timeout: int = MAX_EXECUTION_TIME,
) -> Dict:
    """
    تنفيذ كود Python في sandbox.

    يعيد:
    {
        "success": bool,
        "stdout": str,
        "stderr": str,
        "exit_code": int,
        "execution_time": float,
        "error": str (optional),
    }
    """
    # فحص أمني
    is_safe, msg = check_code_safety(code)
    if not is_safe:
        return {
            "success": False,
            "stdout": "",
            "stderr": "",
            "exit_code": -1,
            "execution_time": 0,
            "error": f"تم رفض الكود لأسباب أمنية: {msg}",
        }

    # إنشاء مجلد مؤقت
    workdir = tempfile.mkdtemp(prefix="sandbox_")
    script_path = os.path.join(workdir, f"script_{uuid.uuid4().hex[:8]}.py")

    # كتابة الكود للملف
    with open(script_path, "w", encoding="utf-8") as f:
        f.write(code)

    start_time = time.time()
    result = {
        "success": False,
        "stdout": "",
        "stderr": "",
        "exit_code": -1,
        "execution_time": 0,
    }

    try:
        # تشغيل في subprocess معفى
        proc = await asyncio.create_subprocess_exec(
            sys.executable,
            script_path,
            cwd=workdir,
            stdout=asyncio.subprocess.PIPE,
            stderr=asyncio.subprocess.PIPE,
            env={
                "PATH": os.environ.get("PATH", ""),
                "HOME": workdir,
                "TMPDIR": workdir,
                "PYTHONPATH": "",
                "MPLBACKEND": "Agg",  # matplotlib headless
            },
            preexec_fn=set_memory_limit if sys.platform != "win32" else None,
        )

        try:
            stdout, stderr = await asyncio.wait_for(
                proc.communicate(), timeout=timeout
            )
            result["stdout"] = stdout.decode("utf-8", errors="replace")[:MAX_OUTPUT_CHARS]
            result["stderr"] = stderr.decode("utf-8", errors="replace")[:MAX_OUTPUT_CHARS]
            result["exit_code"] = proc.returncode
            result["success"] = (proc.returncode == 0)
            result["execution_time"] = time.time() - start_time
        except asyncio.TimeoutError:
            try:
                proc.kill()
            except ProcessLookupError:
                pass
            result["error"] = f"انتهت المهلة ({timeout}s) - تم إيقاف التنفيذ"
            result["execution_time"] = timeout
    except Exception as e:
        result["error"] = f"خطأ في التشغيل: {e}"
    finally:
        # تنظيف المجلد المؤقت
        try:
            shutil.rmtree(workdir, ignore_errors=True)
        except Exception:
            pass

    return result


def format_execution_result(result: Dict) -> str:
    """تنسيق نتيجة التنفيذ كرسالة تيليجرام"""
    lines = []
    if result.get("error"):
        lines.append(f"❌ **خطأ:** {result['error']}")
    elif not result["success"]:
        lines.append(f"⚠️ **خروج برمز {result['exit_code']}** (بعد {result['execution_time']:.2f}s)")
    else:
        lines.append(f"✅ **نجح** ({result['execution_time']:.2f}s)")

    if result["stdout"]:
        lines.append("\n📤 **المخرجات:**")
        lines.append(f"```\n{result['stdout']}\n```")
    if result["stderr"]:
        lines.append("\n⚠️ **الأخطاء:**")
        lines.append(f"```\n{result['stderr']}\n```")
    if not result["stdout"] and not result["stderr"] and result["success"]:
        lines.append("\n_(لا توجد مخرجات)_")

    return "\n".join(lines)