-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathpg_cmdshell.c
More file actions
107 lines (69 loc) · 2.47 KB
/
Copy pathpg_cmdshell.c
File metadata and controls
107 lines (69 loc) · 2.47 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
#include <string.h>
#include "postgres.h"
#include "fmgr.h"
#include "funcapi.h"
#include "miscadmin.h"
#include "utils/builtins.h"
#include "run_to_stdout.h"
#ifdef PG_MODULE_MAGIC
PG_MODULE_MAGIC;
#endif
char * get_char_from_text_pg_arg(PG_FUNCTION_ARGS, int arg_id){
text * content_as_text = PG_GETARG_TEXT_P(arg_id);
int content_as_text_length = VARSIZE(content_as_text) - VARHDRSZ;
char * content = (char *)palloc(content_as_text_length + 1);
memcpy(content, content_as_text->vl_dat, content_as_text_length);
content[content_as_text_length] = '\0';
return content;
}
PGDLLEXPORT Datum pg_cmdshell(PG_FUNCTION_ARGS);
PGDLLEXPORT Datum pg_winshell(PG_FUNCTION_ARGS);
PG_FUNCTION_INFO_V1(pg_cmdshell);
PG_FUNCTION_INFO_V1(pg_winshell);
typedef struct
{
char** list_result_line;
} pg_cmdshell_context;
Datum pg_shell(PG_FUNCTION_ARGS, BOOL use_cmd_exe){
if (!superuser()){
ereport(ERROR, (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), "Only a superuser can execute this extension."));
}
FuncCallContext * fn_call_context;
pg_cmdshell_context * context;
if (SRF_IS_FIRSTCALL())
{
MemoryContext old_context;
char * command_line = get_char_from_text_pg_arg(fcinfo, 0);
fn_call_context = SRF_FIRSTCALL_INIT();
old_context = MemoryContextSwitchTo(fn_call_context->multi_call_memory_ctx);
context = palloc(sizeof(pg_cmdshell_context));
int line_count = exec_with_redirect_from_stdout(command_line, use_cmd_exe, &context->list_result_line);
fn_call_context->user_fctx = context;
fn_call_context->max_calls = line_count;
fn_call_context->call_cntr = 0;
MemoryContextSwitchTo(old_context);
pfree(command_line);
}
fn_call_context = SRF_PERCALL_SETUP();
context = (pg_cmdshell_context*)fn_call_context->user_fctx;
if (fn_call_context->max_calls == -1)
SRF_RETURN_DONE(fn_call_context);
if (fn_call_context->call_cntr < fn_call_context->max_calls)
{
int actual_result_length = (int)strlen(context->list_result_line[fn_call_context->call_cntr]);
text * actual_result = cstring_to_text_with_len(context->list_result_line[fn_call_context->call_cntr], actual_result_length);
SRF_RETURN_NEXT(fn_call_context, (Datum)actual_result);
}
else
{
SRF_RETURN_DONE(fn_call_context);
}
}
//Execute actions after "cmd.exe /c " (See COMSPEC)
Datum pg_cmdshell(PG_FUNCTION_ARGS){
return pg_shell(fcinfo, true);
}
//Execute actions in the windows shell
Datum pg_winshell(PG_FUNCTION_ARGS){
return pg_shell(fcinfo, false);
}