File size: 2,905 Bytes
95c8cc1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
import stat
import subprocess
from flask import Flask, request, jsonify
from flask_cors import CORS
import uuid # Import the uuid library to create unique filenames

app = Flask(__name__)
CORS(app)

@app.route('/')
def home():
    return jsonify({
        "status": "ok",
        "message": "C++ compiler backend is running. Send POST requests to /api/run-cpp"
    })

@app.route('/api/run-cpp', methods=['POST'])
def run_cpp():
    code = request.json.get('code', '')
    user_input = request.json.get('input', '')
    
    if not code:
        return jsonify({'error': 'No code provided.'}), 400

    # **CRITICAL FIX: Use the /tmp directory for all file operations.**
    # This directory is guaranteed to be writable in Linux container environments.
    # A unique name prevents conflicts if two requests happen at once.
    unique_name = str(uuid.uuid4())
    temp_dir = "/tmp"
    source_file_path = os.path.join(temp_dir, f"{unique_name}.cpp")
    executable_path = os.path.join(temp_dir, unique_name)

    try:
        # Write the user's code to the temporary .cpp file in /tmp
        with open(source_file_path, "w") as f:
            f.write(code)

        # --- Compilation Step ---
        compile_process = subprocess.run(
            ['g++', '-std=c++17', source_file_path, '-o', executable_path],
            capture_output=True, text=True, timeout=10
        )
        
        if compile_process.returncode != 0:
            return jsonify({'compileErrors': compile_process.stderr})

        # --- Set Execute Permissions ---
        # This is still necessary for the compiled file in /tmp.
        st = os.stat(executable_path)
        os.chmod(executable_path, st.st_mode | stat.S_IEXEC)

        # --- Execution Step ---
        # Execute the program using its full, absolute path.
        run_process = subprocess.run(
            [executable_path], # No './' is needed when using the full path
            input=user_input,
            capture_output=True, text=True, timeout=15
        )
                
        if run_process.returncode != 0:
            return jsonify({'runErrors': run_process.stderr})
        else:
            return jsonify({'output': run_process.stdout})

    except subprocess.TimeoutExpired:
        return jsonify({'error': 'Execution timed out. Your program took too long to run or has an infinite loop.'})
    except Exception as e:
        # This will catch any other unexpected errors.
        return jsonify({'error': f"An unexpected server error occurred: {str(e)}"})
        
    finally:
        # --- Cleanup Step ---
        # Always clean up the files from the /tmp directory to be a good citizen.
        if os.path.exists(source_file_path):
            os.remove(source_file_path)
        if os.path.exists(executable_path):
            os.remove(executable_path)

if __name__ == '__main__':
    app.run(host="0.0.0.0", port=7860)