-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathapp.py
More file actions
2264 lines (1980 loc) · 94 KB
/
app.py
File metadata and controls
2264 lines (1980 loc) · 94 KB
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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from flask import Flask, render_template, request, jsonify, session, redirect, url_for, send_file, send_from_directory, flash
import os, json, uuid, subprocess, threading, time, re, tempfile, shutil, csv, hashlib
from datetime import datetime
import logging
from typing import Dict, List, Optional, Any
from collections import OrderedDict
app = Flask(__name__, static_folder='.')
app.secret_key = os.urandom(24)
app.config['UPLOAD_FOLDER'] = 'uploads'
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024
def wants_json_response():
"""Return True if this request expects a JSON response (AJAX/API)."""
if request.is_json:
return True
if request.headers.get('X-Requested-With') == 'XMLHttpRequest':
return True
accept = (request.headers.get('Accept') or '').lower()
return 'application/json' in accept
# Ensure directories exist
os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)
os.makedirs('logs', exist_ok=True)
os.makedirs('exports', exist_ok=True)
os.makedirs('backups', exist_ok=True)
os.makedirs('img', exist_ok=True) # Ensure img directory exists
# Configure logging
# Logging (structured-ish): include execution_id/tool_id when provided via 'extra'
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
_log_fmt = "%(asctime)s %(levelname)s %(name)s exec=%(execution_id)s tool=%(tool_id)s - %(message)s"
class _SafeExtraFormatter(logging.Formatter):
def format(self, record):
if not hasattr(record, "execution_id"):
record.execution_id = "-"
if not hasattr(record, "tool_id"):
record.tool_id = "-"
return super().format(record)
_formatter = _SafeExtraFormatter(_log_fmt)
# Console handler
_ch = logging.StreamHandler()
_ch.setLevel(logging.INFO)
_ch.setFormatter(_formatter)
logger.addHandler(_ch)
# File handler (rotating)
try:
from logging.handlers import RotatingFileHandler
_fh = RotatingFileHandler("logs/app.log", maxBytes=2_000_000, backupCount=5, encoding="utf-8")
_fh.setLevel(logging.DEBUG)
_fh.setFormatter(_formatter)
logger.addHandler(_fh)
except Exception as _e:
logger.warning(f"Failed to initialize file logging: {_e}")
# Database simulation
workflows_db = OrderedDict()
execution_history = OrderedDict()
update_history = OrderedDict()
# Execution control (in-memory)
# - active_processes: current subprocess (per execution) so we can terminate on cancel
# - cancel_events: cancellation signal (per execution)
active_processes: Dict[str, subprocess.Popen] = {}
cancel_events: Dict[str, threading.Event] = {}
# Concurrency control for shared in-memory state
execution_lock = threading.RLock()
def _sha256_text(value: str) -> str:
try:
return hashlib.sha256((value or "").encode("utf-8", errors="replace")).hexdigest()
except Exception:
return ""
def _now_iso() -> str:
return datetime.now().isoformat()
def _int_or_none(v) -> Optional[int]:
"""Best-effort int parsing for values coming from JSON/forms."""
if v is None:
return None
try:
if isinstance(v, str) and v.strip() == "":
return None
return int(v)
except Exception:
return None
def _record_event(execution, event_type: str, message: str, level: str = "info", tool_id: str = None):
"""Append a structured event to an execution and bump its version."""
evt = {
"ts": _now_iso(),
"type": event_type,
"level": level,
"tool_id": tool_id,
"message": message
}
with execution_lock:
if not hasattr(execution, "events") or execution.events is None:
execution.events = []
execution.events.append(evt)
# avoid unbounded growth in memory (keep latest 500)
if len(execution.events) > 500:
execution.events = execution.events[-500:]
execution.version = int(getattr(execution, "version", 0)) + 1
execution.last_updated_at = _now_iso()
# Settings file path
SETTINGS_FILE = 'app_settings.json'
# Default settings - only essential workflow tool settings
DEFAULT_SETTINGS = {
'max_execution_time': 9999, # Maximum time per tool in seconds
'max_output_size': 999999, # Maximum output size in characters
'auto_cleanup': True, # Automatically clean up temp files
'default_theme': 'dark', # UI theme
'enable_logging': True, # Enable debug logging
'concurrent_executions': 3, # Max concurrent workflow executions
'log_retention_days': 7, # Days to keep logs
'backup_frequency': 'weekly', # Auto-backup frequency
'enable_notifications': False, # Enable desktop notifications
'enable_auto_updates': False, # Check for tool updates
'output_directory': 'exports', # Default output directory
'temp_directory': '', # Custom temp directory (empty = system default)
'enable_debug_mode': False, # Enable debug mode for tools
'tool_library': [], # Global configured tools
'wordlists': {} # Named wordlists e.g. {'wordlist1':'/path/to/file'}
}
class ToolConfig:
"""Configuration for a single tool/module"""
# input_source historically supported: 'initial', 'previous', 'specific', 'none'.
# The workflow editor now defaults to 'specific' ("any tool") and hides the legacy options,
# but we keep backward-compatibility for previously saved workflows.
def __init__(self, tool_id, name, command='', args_template='', input_source='specific',
library_tool_id=None,
command_override=None,
args_template_override=None,
update_command_override=None,
description_override=None,
specific_step=None, description="", color="#4a86e8", enabled=True,
update_command="", last_updated=None,
input_method='argument',
output_handling='stdout',
provides_output=True,
output_format='text',
output_file_path='',
placeholder_name='input'):
self.id = tool_id
self.name = name
self.library_tool_id = library_tool_id
# Overrides: if None, value will be resolved from tool library at execution time
self.command_override = command_override
self.args_template_override = args_template_override
self.update_command_override = update_command_override
self.description_override = description_override
# Backward-compatible fields (may be empty when using tool library)
self.command = command
self.args_template = args_template
self.input_source = input_source
self.specific_step = specific_step
self.description = description
self.color = color
self.enabled = enabled
self.update_command = update_command or ""
self.last_updated = last_updated
# New attributes for enhanced workflow handling
self.input_method = input_method
self.output_handling = output_handling
self.provides_output = provides_output
self.output_format = output_format
self.output_file_path = output_file_path
self.placeholder_name = placeholder_name
def to_dict(self):
return {
'id': self.id,
'name': self.name,
'command': self.command,
'args_template': self.args_template,
'library_tool_id': self.library_tool_id,
'command_override': self.command_override,
'args_template_override': self.args_template_override,
'update_command_override': self.update_command_override,
'description_override': self.description_override,
'input_source': self.input_source,
'specific_step': self.specific_step,
'description': self.description,
'color': self.color,
'enabled': self.enabled,
'update_command': self.update_command,
'last_updated': self.last_updated,
'input_method': self.input_method,
'output_handling': self.output_handling,
'provides_output': self.provides_output,
'output_format': self.output_format,
'output_file_path': self.output_file_path,
'placeholder_name': self.placeholder_name
}
@classmethod
def from_dict(cls, data):
"""Create ToolConfig from dictionary with backward compatibility"""
return cls(
tool_id=data.get('id', str(uuid.uuid4())),
name=data['name'],
command=data.get('command',''),
args_template=data.get('args_template',''),
input_source=data.get('input_source', 'specific'),
library_tool_id=data.get('library_tool_id'),
command_override=data.get('command_override'),
args_template_override=data.get('args_template_override'),
update_command_override=data.get('update_command_override'),
description_override=data.get('description_override'),
specific_step=data.get('specific_step'),
description=data.get('description', ''),
color=data.get('color', '#4a86e8'),
enabled=data.get('enabled', True),
update_command=data.get('update_command', ''),
last_updated=data.get('last_updated'),
input_method=data.get('input_method', 'argument'),
output_handling=data.get('output_handling', 'stdout'),
provides_output=data.get('provides_output', True),
output_format=data.get('output_format', 'text'),
output_file_path=data.get('output_file_path', ''),
placeholder_name=data.get('placeholder_name', 'input')
)
class Workflow:
"""Complete workflow configuration"""
def __init__(
self,
workflow_id,
name,
description,
tools,
created_at,
updated_at,
author="anonymous",
run_mode: str = "once",
interval_minutes: Optional[int] = None,
repeat_count: Optional[int] = None,
repeat_interval_minutes: Optional[int] = None,
):
self.id = workflow_id
self.name = name
self.description = description
self.tools = tools
self.created_at = created_at
self.updated_at = updated_at
self.author = author
# Recurrence configuration
# - run_mode: 'once' | 'interval' | 'repeat'
# - interval: run indefinitely every N minutes
# - repeat: run repeat_count times, sleeping repeat_interval_minutes between runs
self.run_mode = (run_mode or "once").strip().lower()
self.interval_minutes = interval_minutes
self.repeat_count = repeat_count
self.repeat_interval_minutes = repeat_interval_minutes
def to_dict(self):
return {
'id': self.id,
'name': self.name,
'description': self.description,
'tools': [tool.to_dict() for tool in self.tools],
'created_at': self.created_at,
'updated_at': self.updated_at,
'author': self.author,
'run_mode': getattr(self, 'run_mode', 'once'),
'interval_minutes': getattr(self, 'interval_minutes', None),
'repeat_count': getattr(self, 'repeat_count', None),
'repeat_interval_minutes': getattr(self, 'repeat_interval_minutes', None),
}
class ExecutionResult:
"""Result of a tool execution"""
def __init__(self, tool_id, tool_name, status='pending', start_time=None,
end_time=None, output="", error="", exit_code=None):
self.tool_id = tool_id
self.tool_name = tool_name
self.status = status
self.start_time = start_time
self.end_time = end_time
self.output = output
self.error = error
self.exit_code = exit_code
def to_dict(self):
return {
'tool_id': self.tool_id,
'tool_name': self.tool_name,
'status': self.status,
'start_time': self.start_time,
'end_time': self.end_time,
'output': self.output,
'error': self.error,
'exit_code': self.exit_code
}
class WorkflowExecution:
"""Complete execution instance"""
def __init__(self, execution_id, workflow_id, domain, status='queued',
results=None, created_at=None, started_at=None, completed_at=None,
version: int = 0, last_updated_at: str = None, events: list = None,
cancel_requested: bool = False, cancelled_at: str = None,
run_mode: str = 'once',
interval_minutes: Optional[int] = None,
repeat_count: Optional[int] = None,
repeat_interval_minutes: Optional[int] = None,
current_iteration: int = 0,
planned_iterations: Optional[int] = None,
iterations: Optional[list] = None):
self.execution_id = execution_id
self.workflow_id = workflow_id
self.domain = domain
self.status = status
self.results = results or {}
self.created_at = created_at or datetime.now().isoformat()
self.started_at = started_at
self.completed_at = completed_at
self.version = int(version or 0)
self.last_updated_at = last_updated_at or self.created_at
self.events = events or []
self.cancel_requested = bool(cancel_requested)
self.cancelled_at = cancelled_at
# Recurrence metadata (non-breaking: kept optional and ignored by older UIs)
self.run_mode = (run_mode or 'once')
self.interval_minutes = interval_minutes
self.repeat_count = repeat_count
self.repeat_interval_minutes = repeat_interval_minutes
self.current_iteration = int(current_iteration or 0)
self.planned_iterations = planned_iterations
# iterations is a list of per-iteration summaries + results snapshots
self.iterations = iterations or []
def to_dict(self, include_results: bool = True):
data = {
'execution_id': self.execution_id,
'workflow_id': self.workflow_id,
'domain': self.domain,
'status': self.status,
'created_at': self.created_at,
'started_at': self.started_at,
'completed_at': self.completed_at,
'version': self.version,
'last_updated_at': self.last_updated_at,
'events': self.events,
'cancel_requested': getattr(self, 'cancel_requested', False),
'cancelled_at': getattr(self, 'cancelled_at', None)
,
'run_mode': getattr(self, 'run_mode', 'once'),
'interval_minutes': getattr(self, 'interval_minutes', None),
'repeat_count': getattr(self, 'repeat_count', None),
'repeat_interval_minutes': getattr(self, 'repeat_interval_minutes', None),
'current_iteration': getattr(self, 'current_iteration', 0),
'planned_iterations': getattr(self, 'planned_iterations', None),
'iterations': getattr(self, 'iterations', []),
}
if include_results:
# Snapshot under lock to avoid races while the execution thread is updating results.
with execution_lock:
snapshot = dict(self.results or {})
data['results'] = {k: v.to_dict() for k, v in snapshot.items()}
return data
class UpdateResult:
"""Result of a tool update"""
def __init__(self, update_id, tool_id, tool_name, status='pending',
start_time=None, end_time=None, output="", error=""):
self.update_id = update_id
self.tool_id = tool_id
self.tool_name = tool_name
self.status = status
self.start_time = start_time
self.end_time = end_time
self.output = output
self.error = error
def to_dict(self):
return {
'update_id': self.update_id,
'tool_id': self.tool_id,
'tool_name': self.tool_name,
'status': self.status,
'start_time': self.start_time,
'end_time': self.end_time,
'output': self.output,
'error': self.error
}
# Helper Functions
def parse_args_template(template: str, context: Dict[str, Any]) -> str:
"""Parse argument template with placeholders like {0}, {1}, {domain}, {input}, etc."""
logger.debug(f"Parsing template: {template}")
logger.debug(f"Context keys: {list(context.keys())}")
for key, value in context.items():
placeholder = f"{{{key}}}"
if placeholder in template:
# If value is a file path and contains spaces, quote it.
# Only apply this to placeholders that are likely to be file paths to avoid
# accidentally quoting arbitrary strings that happen to match an existing path.
if isinstance(value, str) and os.path.exists(value) and ' ' in value:
value = f'"{value}"'
logger.debug(f"Replacing {placeholder} with: {value[:100] if isinstance(value, str) and len(value) > 100 else value}")
template = template.replace(placeholder, str(value))
logger.debug(f"Parsed template result: {template}")
return template
def resolve_tool_from_library(tool: ToolConfig, settings: Dict[str, Any]) -> Dict[str, str]:
"""Resolve effective command/args/update/description for a workflow tool step.
If tool.library_tool_id is set, merge the library tool definition with any per-step overrides.
"""
library = settings.get('tool_library', []) or []
lib_entry = None
if tool.library_tool_id:
for t in library:
if t.get('id') == tool.library_tool_id:
lib_entry = t
break
def pick(field_name: str, override_value, fallback_value: str) -> str:
if override_value is not None and str(override_value).strip() != "":
return str(override_value)
if fallback_value is None:
return ""
return str(fallback_value)
if lib_entry:
effective_command = pick('path', tool.command_override, lib_entry.get('path', lib_entry.get('command', '')))
effective_args = pick('default_command', tool.args_template_override, lib_entry.get('default_command', lib_entry.get('args_template', '')))
effective_update = pick('update_command', tool.update_command_override, lib_entry.get('update_command', ''))
effective_desc = pick('description', tool.description_override, lib_entry.get('description', ''))
else:
# No library reference; use the legacy per-step fields
effective_command = pick('command', tool.command_override, tool.command)
effective_args = pick('args_template', tool.args_template_override, tool.args_template)
effective_update = pick('update_command', tool.update_command_override, tool.update_command)
effective_desc = pick('description', tool.description_override, tool.description)
return {
'command': effective_command,
'args_template': effective_args,
'update_command': effective_update,
'description': effective_desc,
}
return template
def find_tool_by_id(workflow, tool_id):
"""Find tool in workflow by ID"""
for tool in workflow.tools:
if tool.id == tool_id:
return tool
return None
def find_tool_id_by_step(workflow, step_number):
"""Find tool ID by step number (1-indexed)"""
if 1 <= step_number <= len(workflow.tools):
return workflow.tools[step_number - 1].id
return None
def _terminate_process_tree(proc: subprocess.Popen):
"""Best-effort termination of a running subprocess (and its process group)."""
if proc is None:
return
try:
if os.name == 'nt':
# On Windows, terminate the process; child processes may require additional handling.
proc.terminate()
else:
# On POSIX, kill the whole process group (if created).
import signal
try:
os.killpg(os.getpgid(proc.pid), signal.SIGTERM)
except Exception:
proc.terminate()
except Exception:
pass
def _run_command_cancellable(execution_id: str, cmd: str, stdin_data: Optional[str], timeout_seconds: int, cancel_event: Optional[threading.Event]):
"""Run a shell command with cancellation support.
Returns: (returncode, stdout, stderr)
Raises: subprocess.TimeoutExpired
"""
start = time.time()
# Configure process group so we can terminate the whole tree on POSIX.
popen_kwargs = {
"shell": True,
"stdin": subprocess.PIPE if stdin_data is not None else None,
"stdout": subprocess.PIPE,
"stderr": subprocess.PIPE,
"text": True,
}
if os.name == 'nt':
# CREATE_NEW_PROCESS_GROUP enables sending ctrl events, but terminate() is enough for now.
try:
popen_kwargs["creationflags"] = subprocess.CREATE_NEW_PROCESS_GROUP # type: ignore[attr-defined]
except Exception:
pass
else:
import os as _os
popen_kwargs["preexec_fn"] = _os.setsid
proc = subprocess.Popen(cmd, **popen_kwargs)
with execution_lock:
active_processes[execution_id] = proc
try:
# Poll loop so we can react to cancellation.
while True:
if cancel_event is not None and cancel_event.is_set():
_terminate_process_tree(proc)
break
if timeout_seconds is not None and (time.time() - start) > timeout_seconds:
_terminate_process_tree(proc)
raise subprocess.TimeoutExpired(cmd=cmd, timeout=timeout_seconds)
rc = proc.poll()
if rc is not None:
break
time.sleep(0.1)
try:
stdout, stderr = proc.communicate(input=stdin_data, timeout=5)
except Exception:
# Best-effort: if the process is still alive, force-terminate and re-collect.
try:
_terminate_process_tree(proc)
except Exception:
pass
stdout, stderr = proc.communicate(input=stdin_data)
return proc.returncode, stdout or "", stderr or ""
finally:
with execution_lock:
# Only clear if we're still the current process for this execution.
if active_processes.get(execution_id) is proc:
active_processes.pop(execution_id, None)
def _standardize_tool_output(output: str, temp_dir: str, tool_id: str) -> Dict[str, Any]:
"""Standardize tool outputs for safe placeholder substitution.
Rules:
- If the output is a single line, it is treated as a string (trailing newlines stripped).
- If the output has more than one line, it is written to a temporary file and the file
path is used as the value.
This prevents multiline outputs from being interpreted as multiple shell commands when
interpolated into templates (shell=True), and makes behavior consistent across tools.
"""
raw = output or ""
trimmed = raw.rstrip("\r\n")
lines = trimmed.splitlines()
if len(lines) <= 1:
return {
"value": (lines[0] if lines else ""),
"as_file": False,
"file_path": None,
"raw": raw,
"line_count": len(lines),
}
fd, temp_path = tempfile.mkstemp(dir=temp_dir, prefix=f"out_{tool_id}_", suffix=".txt")
try:
with os.fdopen(fd, "w", encoding="utf-8", errors="replace") as f:
f.write(raw)
except Exception:
try:
os.close(fd)
except Exception:
pass
raise
return {
"value": temp_path,
"as_file": True,
"file_path": temp_path,
"raw": raw,
"line_count": len(lines),
}
def execute_tool(tool: ToolConfig, domain: str, previous_outputs: Dict[str, Dict[str, Any]],
temp_dir: str, execution_context: Dict[str, Any],
cancel_event: Optional[threading.Event] = None,
execution_id: Optional[str] = None) -> ExecutionResult:
"""Execute a single tool with enhanced input/output handling"""
logger.info(f"=== STARTING EXECUTION OF TOOL: {tool.name} (ID: {tool.id}) ===")
settings = load_settings()
resolved = resolve_tool_from_library(tool, settings)
logger.info(f"Tool configuration (resolved):")
logger.info(f" - Command/Path: {resolved['command']}")
logger.info(f" - Default Command (args): {resolved['args_template']}")
logger.info(f" - Input source: {tool.input_source}")
logger.info(f" - Input method: {tool.input_method}")
logger.info(f" - Placeholder name: {tool.placeholder_name}")
logger.info(f" - Output handling: {tool.output_handling}")
logger.info(f" - Provides output: {tool.provides_output}")
result = ExecutionResult(
tool_id=tool.id,
tool_name=tool.name,
status='running',
start_time=datetime.now().isoformat()
)
try:
# Build execution context with dynamic placeholders
context = {
'domain': domain,
'temp_dir': temp_dir,
'timestamp': datetime.now().strftime('%Y%m%d_%H%M%S'),
'tool_id': tool.id
}
# Add domain as {0} for backward compatibility
context['0'] = domain
logger.info(f"Initial context keys: {list(context.keys())}")
logger.info(f"Previous outputs available from tools: {list(previous_outputs.keys())}")
# Store previous outputs in the template context.
# Notes:
# - We keep the existing behavior of exposing outputs via placeholder_name and
# indexed placeholders for backward compatibility.
# - To avoid silent collisions (multiple tools using the same placeholder_name),
# we also expose stable per-tool keys: out_<tool_id> and step_<n>.
for idx, (tool_id, output_data) in enumerate(previous_outputs.items()):
# Get the tool that produced this output
prev_tool = find_tool_by_id(execution_context['workflow'], tool_id)
if prev_tool:
# Use the previous tool's placeholder name
placeholder = prev_tool.placeholder_name
# Preserve any previous value if this placeholder is reused.
if placeholder in context and context.get(placeholder) != output_data['output']:
context[f"{placeholder}_{idx}"] = context.get(placeholder)
context[placeholder] = output_data['output']
# Also add as indexed placeholder for backward compatibility
context[str(idx + 1)] = output_data['output']
# Stable keys (recommended)
context[f"out_{tool_id}"] = output_data['output']
context[f"step_{idx + 1}"] = output_data['output']
logger.info(f"Added output from tool {prev_tool.name} (ID: {tool_id}) to context:")
logger.info(f" - Key '{placeholder}': {output_data['output'][:200]}...")
logger.info(f" - Also available as '{idx + 1}'")
logger.info(f" - Also available as 'out_{tool_id}' and 'step_{idx + 1}'")
# Handle input based on input_method
input_content = None
logger.info(f"Determining input for tool {tool.name}:")
logger.info(f" - Input source setting: {tool.input_source}")
logger.info(f" - Specific step (if set): {tool.specific_step}")
if tool.input_source != 'none' and tool.input_method != 'none':
if tool.input_source == 'specific':
# Use a specific step's output ("any tool").
# If the configured step is missing/invalid, fall back safely.
step = None
try:
step = int(tool.specific_step) if tool.specific_step is not None else None
except Exception:
step = None
if step:
source_tool_id = find_tool_id_by_step(execution_context['workflow'], step)
logger.info(f" Looking for specific step {step} -> tool ID: {source_tool_id}")
if source_tool_id and source_tool_id in previous_outputs:
input_content = previous_outputs[source_tool_id]['output']
logger.info(f" Found input from specific tool {source_tool_id}")
else:
logger.warning(f" Could not find output from specific step {step}; will fall back")
# Fallback if step not set or not found
if input_content is None:
if previous_outputs:
last_tool_id = list(previous_outputs.keys())[-1]
input_content = previous_outputs[last_tool_id]['output']
logger.info(f" Fallback to most recent output (ID: {last_tool_id})")
else:
input_content = domain
logger.info(f" Fallback to domain as input: {domain}")
elif tool.input_source == 'initial':
input_content = domain
logger.info(f" Using initial domain as input: {domain}")
else: # 'previous' or default
# Use the most recent output
if previous_outputs:
last_tool_id = list(previous_outputs.keys())[-1]
input_content = previous_outputs[last_tool_id]['output']
logger.info(f" Using output from previous tool (ID: {last_tool_id})")
logger.info(f" Input content size: {len(input_content)} characters")
else:
logger.warning(f" No previous outputs available, will use domain as fallback")
input_content = domain
# Prepare input based on input_method
stdin_data = None
temp_files_to_cleanup = []
if input_content and tool.input_method != 'none':
if tool.input_method == 'file':
# Create temp file with input content
logger.info(f"Creating temporary file for tool input (input_method='file')")
fd, temp_path = tempfile.mkstemp(dir=temp_dir, suffix='.txt')
temp_files_to_cleanup.append(temp_path)
with os.fdopen(fd, 'w') as f:
f.write(input_content)
# Add the file path to context for the template
context[tool.placeholder_name] = temp_path
context['input_file'] = temp_path
logger.info(f"Created temp file: {temp_path}")
logger.info(f"File content size: {len(input_content)} characters")
elif tool.input_method == 'stdin':
# Store for stdin input during execution
stdin_data = input_content
# For template, use '-' to indicate stdin
context[tool.placeholder_name] = '-'
logger.info(f"Prepared stdin input (size: {len(input_content)} chars)")
elif tool.input_method == 'argument':
# Check if content is multiline - if so, we need to create a temp file
# because command-line arguments can't handle multiline strings properly
if '\n' in input_content and len(input_content.strip().split('\n')) > 1:
logger.warning(f"Multiline content detected for argument input. Creating temp file instead.")
logger.info(f"Content has {len(input_content.strip().splitlines())} lines")
# Create temp file
fd, temp_path = tempfile.mkstemp(dir=temp_dir, suffix='.txt')
temp_files_to_cleanup.append(temp_path)
with os.fdopen(fd, 'w') as f:
f.write(input_content)
# Replace the placeholder in args_template that needs the file
# We need to find which placeholder in the args_template is being used
args_template = tool.args_template
# Check if the template has file-related flags
if any(flag in args_template for flag in ['-l', '-i', '--input', '-f', '@']):
logger.info(f"Template has file flag, replacing placeholder with file path")
# Replace the appropriate placeholder with file path
# We'll replace both the named placeholder and indexed placeholder
if '{' + tool.placeholder_name + '}' in args_template:
context[tool.placeholder_name] = temp_path
logger.info(f"Replaced placeholder '{tool.placeholder_name}' with file path")
# Also replace indexed placeholders that might be referencing this input
for key in list(context.keys()):
if key.isdigit() and context[key] == input_content:
context[key] = temp_path
logger.info(f"Replaced indexed placeholder '{key}' with file path")
else:
# For non-file arguments, we need to handle multiline content
# Join lines with spaces or handle differently based on tool
input_content = ' '.join(input_content.strip().split('\n'))
context[tool.placeholder_name] = input_content
logger.info(f"Joined multiline content into single line argument")
else:
# Single line content, safe to pass as argument
context[tool.placeholder_name] = input_content
logger.info(f"Setting placeholder '{tool.placeholder_name}' as single-line argument")
# Prepare output file if needed
if tool.output_handling == 'file':
if tool.output_file_path:
output_file = tool.output_file_path
else:
output_file = os.path.join(temp_dir, f"output_{tool.id}_{context['timestamp']}.txt")
context['output_file'] = output_file
logger.info(f"Output will be written to file: {output_file}")
logger.info(f"Final context before parsing template:")
for key, value in context.items():
if key in ['input_file', 'output_file'] or key == tool.placeholder_name:
logger.info(f" {key}: {value}")
elif isinstance(value, str) and len(value) > 100:
logger.info(f" {key}: {value[:100]}...")
else:
logger.info(f" {key}: {value}")
# Parse arguments with context
# Inject global wordlists into context (usable as {wordlistName})
for wl_name, wl_path in (settings.get('wordlists', {}) or {}).items():
context[wl_name] = wl_path
args = parse_args_template(resolved['args_template'], context)
# Build command
cmd = f"{resolved['command']} {args}".strip()
logger.info(f"FINAL COMMAND TO EXECUTE: {cmd}")
# Get timeout from settings
settings = load_settings()
timeout_value = int(settings.get('max_execution_time', 300))
# Execute with appropriate input method (cancellable)
logger.info(f"Executing command with timeout {timeout_value} seconds...")
exec_id = execution_id or execution_context.get('execution_id')
if not exec_id:
# Fallback: no execution id; run without cancellability bookkeeping.
process = subprocess.run(
cmd,
shell=True,
input=stdin_data,
capture_output=True,
text=True,
timeout=timeout_value
)
rc, stdout, stderr = process.returncode, process.stdout, process.stderr
else:
rc, stdout, stderr = _run_command_cancellable(
execution_id=str(exec_id),
cmd=cmd,
stdin_data=stdin_data,
timeout_seconds=timeout_value,
cancel_event=cancel_event
)
result.exit_code = rc
# If output is to a file, read it
if tool.output_handling == 'file' and 'output_file' in context and os.path.exists(context['output_file']):
with open(context['output_file'], 'r') as f:
result.output = f.read()
logger.info(f"Read output from file: {context['output_file']}")
else:
result.output = stdout
result.error = stderr
# If the execution was cancelled mid-tool, mark status accordingly.
if cancel_event is not None and cancel_event.is_set():
result.status = 'cancelled'
else:
result.status = 'completed' if rc == 0 else 'failed'
logger.info(f"Command execution completed:")
logger.info(f" - Exit code: {rc}")
logger.info(f" - Status: {result.status}")
logger.info(f" - Output size: {len(result.output)} characters")
logger.info(f" - Error size: {len(result.error)} characters")
if rc != 0 and result.status != 'cancelled':
logger.error(f"Command failed with exit code {rc}")
logger.error(f"STDOUT (first 500 chars): {result.output[:500]}")
logger.error(f"STDERR (first 500 chars): {result.error[:500]}")
else:
if result.status == 'cancelled':
logger.warning("Command was cancelled by the user")
else:
logger.info(f"Command succeeded")
logger.debug(f"Output (first 500 chars): {result.output[:500]}")
except subprocess.TimeoutExpired:
settings = load_settings()
timeout_value = int(settings.get('max_execution_time', 300))
result.status = 'failed'
result.error = f"Command timed out after {timeout_value} seconds"
logger.error(f"Command timed out after {timeout_value} seconds")
except Exception as e:
result.status = 'failed'
result.error = str(e)
logger.error(f"Exception during execution: {e}")
import traceback
logger.error(f"Traceback: {traceback.format_exc()}")
finally:
# Clean up temp files
for temp_file in temp_files_to_cleanup:
try:
if os.path.exists(temp_file):
os.unlink(temp_file)
logger.debug(f"Cleaned up temp file: {temp_file}")
except Exception as e:
logger.warning(f"Failed to clean up temp file {temp_file}: {e}")
result.end_time = datetime.now().isoformat()
logger.info(f"=== COMPLETED EXECUTION OF TOOL: {tool.name} ===")
return result
def execute_update_thread(tool: ToolConfig, workflow_id: str):
"""Background thread to execute tool update"""
update_id = str(uuid.uuid4())
result = UpdateResult(
update_id=update_id,
tool_id=tool.id,
tool_name=tool.name,
status='running',
start_time=datetime.now().isoformat()
)
update_history[update_id] = result
try:
if not tool.update_command:
result.status = 'failed'
result.error = "No update command configured"
return
# Execute the update command.
# Convention: update_command is an argument string appended to the tool executable.
# (Kept as shell=True for backward compatibility with existing update commands.)
cmd = f"{tool.command} {tool.update_command}".strip()
logger.info(f"Updating tool: {cmd}")
# Get timeout from settings
settings = load_settings()
timeout_value = int(settings.get('max_execution_time', 300))
# Run the command with a timeout
process = subprocess.run(
cmd,
shell=True,
capture_output=True,
text=True,
timeout=timeout_value
)
result.output = process.stdout
result.error = process.stderr
result.status = 'completed' if process.returncode == 0 else 'failed'
# Update the tool's last_updated timestamp
if result.status == 'completed':
tool.last_updated = datetime.now().isoformat()
# If this is a library tool update, persist last_updated back into settings.
if workflow_id == '__library__':
settings = load_settings()
lib = settings.get('tool_library', []) or []
for entry in lib:
if entry.get('id') == tool.id:
entry['last_updated'] = tool.last_updated
break
save_settings(settings)
else:
# Save the workflow with updated timestamp
workflow = workflows_db.get(workflow_id)
if workflow:
# Find and update the tool in the workflow
for wf_tool in workflow.tools:
if wf_tool.id == tool.id:
wf_tool.last_updated = tool.last_updated
workflow.updated_at = datetime.now().isoformat()
except subprocess.TimeoutExpired:
settings = load_settings()
timeout_value = int(settings.get('max_execution_time', 300))
result.status = 'failed'
result.error = f"Update timed out after {timeout_value} seconds"
except Exception as e:
result.status = 'failed'
result.error = str(e)
result.end_time = datetime.now().isoformat()
return result
def run_workflow_thread(execution: WorkflowExecution):
"""Background thread to execute workflow with enhanced data flow"""
app_settings = load_settings()
base_temp = (app_settings.get("temp_directory") or "").strip()
if base_temp:
os.makedirs(base_temp, exist_ok=True)
temp_dir = tempfile.mkdtemp(prefix="workflow_", dir=base_temp)
else:
temp_dir = tempfile.mkdtemp(prefix="workflow_")
previous_outputs = {} # Store outputs by tool ID
# Cancellation signal for this execution (created when the execution is enqueued).
cancel_event = None
with execution_lock:
cancel_event = cancel_events.get(execution.execution_id)
try:
workflow = workflows_db.get(execution.workflow_id)
if not workflow:
with execution_lock:
execution.status = 'failed'
return
with execution_lock:
execution.status = 'running'
execution.started_at = datetime.now().isoformat()