-
-
Notifications
You must be signed in to change notification settings - Fork 138
/
exec.erl
1929 lines (1811 loc) · 79.1 KB
/
exec.erl
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
%%% vim:ts=4:sw=4:et
%%%------------------------------------------------------------------------
%%% File: $Id$
%%%------------------------------------------------------------------------
%%% @doc OS shell command runner.
%%% It communicates with a separate C++ port process `exec-port'
%%% spawned by this module, which is responsible
%%% for starting, killing, listing, terminating, and notifying of
%%% state changes.
%%%
%%% The port program serves as a middle-man between
%%% the OS and the virtual machine to carry out OS-specific low-level
%%% process control. The Erlang/C++ protocol is described in the
%%% `exec.cpp' file. The `exec' application can execute tasks by
%%% impersonating as a different effective user. This impersonation
%%% can be accomplished in one of the following two ways (assuming
%%% that the emulator is not running as `root':
%%% <ul>
%%% <li>Having the user account running the erlang emulator added to
%%% the `/etc/sudoers' file, so that it can execute `exec-port'
%%% task as `root'. (Preferred option)</li>
%%% <li>Setting `root' ownership on `exec-port', and setting the
%%% SUID bit: `chown root:root exec-port; chmod 4755 exec-port'.
%%% (This option is discouraged as it's less secure).</li>
%%% </ul>
%%% In either of these two cases, `exec:start_link/2' must be started
%%% with options `[root, {user, User}, {limit_users, Users}]',
%%% so that `exec-port' process will not actually run as
%%% root but will switch to the effective `User', and set the kernel
%%% capabilities so that it's able to start processes as other
%%% effective users given in the `Users' list and adjust process
%%% priorities.
%%%
%%% Though, in the initial design, `exec' prohibited such use, upon
%%% user requests a feature was added (in order to support `docker'
%%% deployment and CI testing) to be able to execute `exec-port' as
%%% `root' without switching the effective user to anying other than
%%% `root'. To accomplish this use the following options to start
%%% `exec': `[root, {user, "root"}, {limit_users, ["root"]}]'.
%%%
%%% At exit the port program makes its best effort to perform
%%% clean shutdown of all child OS processes.
%%% Every started OS process is linked to a spawned light-weight
%%% Erlang process returned by the run/2, run_link/2 command.
%%% The application ensures that termination of spawned OsPid
%%% leads to termination of the associated Erlang Pid, and vice
%%% versa.
%%%
%%% @author Serge Aleynikov <saleyn@gmail.com>
%%% @version {@vsn}
%%% @end
%%%------------------------------------------------------------------------
%%% Created: 2003-06-10 by Serge Aleynikov <saleyn@gmail.com>
%%% $Header$
%%%------------------------------------------------------------------------
-module(exec).
-author('saleyn@gmail.com').
-behaviour(gen_server).
%% External exports
-export([
start/0, start/1, start_link/1, run/2, run/3,
run_link/2, run_link/3,
manage/2, send/2, winsz/3, pty_opts/2,
which_children/0, kill/2, setpgid/2, stop/1, stop_and_wait/2,
ospid/1, pid/1, status/1, signal/1, signal_to_int/1, debug/1
]).
%% Internal exports
-export([default/0, default/1]).
%% gen_server callbacks
-export([init/1, handle_call/3, handle_cast/2, handle_info/2,
code_change/3, terminate/2]).
-include("exec.hrl").
-include_lib("kernel/include/file.hrl").
-ifdef(TEST).
-include_lib("eunit/include/eunit.hrl").
-endif.
-define(TIMEOUT, 30000).
-record(state, {
port,
last_trans = 0, % Last transaction number sent to port
trans = queue:new(), % Queue of outstanding transactions sent to port
limit_users = [], % Restricted list of users allowed to run commands
registry, % Pids to notify when an OsPid exits
debug = false,
root = false
}).
-type exec_options() :: [exec_option()].
-type exec_option() ::
debug
| {debug, integer()}
| root | {root, boolean()}
| verbose
| {args, [string()|binary(), ...]}
| {alarm, non_neg_integer()}
| {user, string()|binary()}
| {limit_users, [string()|binary(), ...]}
| {portexe, string()|binary()}
| {env, [{string()|binary(), string()|binary()|false}, ...]}.
%% Options passed to the exec process at startup. They can be specified in the
%% `sys.config' file for the `erlexec' application to customize application
%% startup.
%% <dl>
%% <dt>debug</dt><dd>Same as {debug, 1}</dd>
%% <dt>{debug, Level}</dt><dd>Enable port-programs debug trace at `Level'.</dd>
%% <dt>verbose</dt><dd>Enable verbose prints of the Erlang process.</dd>
%% <dt>root | {root, Boolean}</dt><dd>Allow running child processes as root.</dd>
%% <dt>{args, Args}</dt><dd>Append `Args' to the port command.</dd>
%% <dt>{alarm, Secs}</dt>
%% <dd>Give `Secs' deadline for the port program to clean up
%% child pids before exiting</dd>
%% <dt>{user, User}</dt>
%% <dd>When the port program was compiled with capability (Linux)
%% support enabled, and is owned by root with a a suid bit set,
%% this option must be specified so that upon startup the port
%% program is running under the effective user different from root.
%% This is a security measure that will also prevent the port program
%% to execute root commands.</dd>
%% <dt>{limit_users, LimitUsers}</dt>
%% <dd>Limit execution of external commands to these set of users.
%% This option is only valid when the port program is owned
%% by root.</dd>
%% <dt>{portexe, Exe}</dt>
%% <dd>Provide an alternative location of the port program.
%% This option is useful when this application is stored
%% on NFS and the port program needs to be copied locally
%% so that root suid bit can be set.</dd>
%% <dt>{env, Env}</dt>
%% <dd>Extend environment of the port program by using `Env' specification.
%% `Env' should be a list of tuples `{Name, Val}', where Name is the
%% name of an environment variable, and Val is the value it is to have
%% in the spawned port process. If Val is `false', then the `Name'
%% environment variable is unset.</dd>
%% </dl>
-export_type([exec_option/0, exec_options/0]).
-type cmd() :: binary() | string() | [string()].
%% Command to be executed. If specified as a string, the specified command
%% will be executed through the shell. The current shell is obtained
%% from environment variable `SHELL'. This can be useful if you
%% are using Erlang primarily for the enhanced control flow it
%% offers over most system shells and still want convenient
%% access to other shell features such as shell pipes, filename
%% wildcards, environment variable expansion, and expansion of
%% `~' to a user's home directory. All command arguments must
%% be properly escaped including whitespace and shell
%% metacharacters.
%%
%% Any part of the command string can contain unicode characters.
%%
%% <ul>
%% <b><u>Warning:</u></b> Executing shell commands that
%% incorporate unsanitized input from an untrusted source makes
%% a program vulnerable to
%% [http://en.wikipedia.org/wiki/Shell_injection#Shell_injection shell injection],
%% a serious security flaw which can result in arbitrary command
%% execution. For this reason, the use of `shell' is strongly
%% discouraged in cases where the command string is constructed
%% from external input:
%% </ul>
%%
%% ```
%% 1> {ok, Filename} = io:read("Enter filename: ").
%% Enter filename: "non_existent; rm -rf / #".
%% {ok, "non_existent; rm -rf / #"}
%% 2> exec(Filename, []) % Argh!!! This is not good!
%% '''
%%
%% When command is given in the form of a list of strings,
%% it is passed to `execve(3)' library call directly without
%% involving the shell process, so the list of strings
%% represents the program to be executed given with a full path,
%% followed by the list of arguments (e.g. `["/bin/echo", "ok"]').
%% In this case all shell-based features are disabled
%% and there's no shell injection vulnerability.
-export_type([cmd/0]).
-type cmd_options() :: [cmd_option()].
-type cmd_option() ::
monitor
| sync
| link
| {executable, string()|binary()}
| {cd, WorkDir::string()|binary()}
| {env, [string() | clear | {Name::string()|binary(), Val::string()|binary()|false}, ...]}
| {kill, KillCmd::string()|binary()}
| {kill_timeout, Sec::non_neg_integer()}
| kill_group
| {group, GID :: string()|binary() | integer()}
| {user, RunAsUser :: string()|binary()}
| {nice, Priority :: integer()}
| {success_exit_code, ExitCode :: integer() }
| stdin | {stdin, null | close | string()|binary()}
| stdout | stderr
| {stdout, stderr | output_dev_opt()}
| {stderr, stdout | output_dev_opt()}
| {stdout | stderr, string()|binary(), [output_file_opt()]}
| {winsz, {Rows::non_neg_integer(), Cols::non_neg_integer()}}
| pty | {pty, pty_opts()}
| pty_echo
| debug | {debug, integer()}.
%% Command options:
%% <dl>
%% <dt>monitor</dt>
%% <dd>Set up a monitor for the spawned process. The monitor is not
%% a standard `erlang:montior/2' function call, but it's emulated
%% by ensuring that the monitoring process receives notification
%% in the form:
%% ``{'DOWN', OsPid::integer(), process, Pid::pid(), Reason}''.
%% If the `Reason' is `normal', then process exited with status `0',
%% otherwise there was an error. If the Reason is `{status, Status}'
%% the returned `Status' can be decoded with `status/1' to determine
%% the exit code of the process and if it was killed by signal.
%% </dd>
%% <dt>sync</dt><dd>Block the caller until the OS command exits</dd>
%% <dt>{executable, Executable::string()}</dt>
%% <dd>Specifies a replacement program to execute. It is very seldom
%% needed. When the port program executes a child process using
%% `execve(3)' call, the call takes the following arguments:
%% `(Executable, Args, Env)'. When `Cmd' argument passed to the
%% `run/2' function is specified as the list of strings,
%% the executable replaces the first parameter in the call, and
%% the original args provided in the `Cmd' parameter are passed as
%% as the second parameter. Most programs treat the program
%% specified by args as the command name, which can then be different
%% from the program actually executed. On Unix, the args name becomes
%% the display name for the executable in utilities such as `ps'.
%%
%% If `Cmd' argument passed to the `run/2' function is given as a
%% string, on Unix the `Executable' specifies a replacement shell
%% for the default `/bin/sh'.</dd>
%% <dt>{cd, WorkDir}</dt><dd>Working directory</dd>
%% <dt>{env, Env :: [{Name,Value}|string()|clear]}</dt>
%% <dd>List of "VAR=VALUE" environment variables or
%% list of {Name, Value} tuples or strings (like "NAME=VALUE") or `clear'.
%% `clear' will clear environment of a spawned child OS process
%% (so that it doesn't inherit parent's environment).
%% If `Value' is `false' then the `Var' env variable is unset.
%% </dd>
%% <dt>{kill, KillCmd}</dt>
%% <dd>This command will be used for killing the process. After
%% a 5-sec timeout if the process is still alive, it'll be
%% killed with SIGKILL. The kill command will have a `CHILD_PID'
%% environment variable set to the pid of the process it is
%% expected to kill. If the `kill' option is not specified,
%% by default first the command is sent a `SIGTERM' signal,
%% followed by `SIGKILL' after a default timeout.</dd>
%% <dt>{kill_timeout, Sec::integer()}</dt>
%% <dd>Number of seconds to wait after issuing a SIGTERM or
%% executing the custom `kill' command (if specified) before
%% killing the process with the `SIGKILL' signal</dd>
%% <dt>kill_group</dt>
%% <dd>At process exit kill the whole process group associated with this pid.
%% The process group is obtained by the call to getpgid(3).</dd>
%% <dt>{group, GID}</dt>
%% <dd>Sets the effective group ID of the spawned process. The value 0
%% means to create a new group ID equal to the OS pid of the process.</dd>
%% <dt>{user, RunAsUser}</dt>
%% <dd>When exec-port was compiled with capability (Linux) support
%% enabled and has a suid bit set, it's capable of running
%% commands with a different RunAsUser effective user. Passing
%% "root" value of `RunAsUser' is prohibited.</dd>
%% <dt>{success_exit_code, IntExitCode}</dt>
%% <dd>On success use `IntExitCode' return value instead of default 0.</dd>
%% <dt>{nice, Priority}</dt>
%% <dd>Set process priority between -20 and 20. Note that
%% negative values can be specified only when `exec-port'
%% is started with a root suid bit set.</dd>
%% <dt>stdin | {stdin, null | close | Filename}</dt>
%% <dd>Enable communication with an OS process via its `stdin'. The
%% input to the process is sent by `exec:send(OsPid, Data)'.
%% When specified as a tuple, `null' means redirection from `/dev/null',
%% `close' means to close `stdin' stream, and `Filename' means to
%% take input from file.</dd>
%% <dt>stdout</dt>
%% <dd>Same as `{stdout, self()}'.</dd>
%% <dt>stderr</dt>
%% <dd>Same as `{stderr, self()}'.</dd>
%% <dt>{stdout, output_device()}</dt>
%% <dd>Redirect process's standard output stream</dd>
%% <dt>{stderr, output_device()}</dt>
%% <dd>Redirect process's standard error stream</dd>
%% <dt>{stdout | stderr, Filename::string(), [output_dev_opt()]}</dt>
%% <dd>Redirect process's stdout/stderr stream to file</dd>
%% <dt>{winsz, {Rows, Cols}}</dt>
%% <dd>Set the (psudo) terminal's dimensions of rows and columns</dd>
%% <dt>pty</dt>
%% <dd>Use pseudo terminal for the process's stdin, stdout and stderr</dd>
%% <dt>pty_echo</dt>
%% <dd>Allow the pty to run in echo mode, disabled by default</dd>
%% <dt>debug</dt>
%% <dd>Same as `{debug, 1}'</dd>
%% <dt>{debug, Level::integer()}</dt>
%% <dd>Enable debug printing in port program for this command</dd>
%% </dl>
-export_type([cmd_option/0, cmd_options/0]).
-type output_dev_opt() :: null | close | print | string() | binary() | pid()
| fun((stdout | stderr, integer(), binary()) -> none()).
%% Output device option:
%% <dl>
%% <dt>null</dt><dd>Suppress output.</dd>
%% <dt>close</dt><dd>Close file descriptor for writing.</dd>
%% <dt>print</dt>
%% <dd>A debugging convenience device that prints the output to the
%% console shell</dd>
%% <dt>Filename</dt><dd>Save output to file by overwriting it.</dd>
%% <dt>pid()</dt><dd>Redirect output to this pid.</dd>
%% <dt>fun((Stream, OsPid, Data) -> none())</dt>
%% <dd>Execute this callback on receiving output data</dd>
%% </dl>
-export_type([output_dev_opt/0]).
-type output_file_opt() :: append | {mode, Mode::integer()}.
%% Defines file opening attributes:
%% <dl>
%% <dt>append</dt><dd>Open the file in `append' mode</dd>
%% <dt>{mode, Mode}</dt>
%% <dd>File creation access mode <b>specified in base 8</b> (e.g. 8#0644)</dd>
%% </dl>
-export_type([output_file_opt/0]).
-type ospid() :: integer().
%% Representation of OS process ID.
-type osgid() :: integer().
%% Representation of OS group ID.
-export_type([ospid/0, osgid/0]).
-type tty_char() ::
vintr | vquit | verase | vkill | veof | veol | veol2 |
vstart | vstop | vsusp | vdsusp | vreprint | vwerase | vlnext |
vflush | vswtch | vstatus | vdiscard.
-type tty_mode() ::
ignpar | parmrk | inpck | istrip | inlcr | igncr | icrnl | xcase |
iuclc | ixon | ixany | ixoff | imaxbel | iutf8 | isig | icanon |
echo | echoe | echok | echonl | noflsh | tostop | iexten | echoctl |
echoke | pendin | opost | olcuc | onlcr | ocrnl | onocr | onlret |
cs7 | cs8 | parenb | parodd.
-type tty_speed() :: tty_op_ispeed | tty_op_ospeed.
-type pty_opt() :: {tty_char(), byte()}
| {tty_mode(), boolean()|0|1}
| {tty_speed(), non_neg_integer()}.
%% Pty options, see:
%% <ul>
%% <li>[https://man7.org/linux/man-pages/man3/termios.3.html]</li>
%% <li>[https://datatracker.ietf.org/doc/html/rfc4254#section-8]</li>
%% </ul>
%% <dl>
%% <dt>{tty_char(), Byte}</dt>
%% <dd>A special character with value from 0 to 255</dd>
%% <dt>{tty_mode(), Enable}</dt>
%% <dd>Enable/disable a tty mode</dd>
%% <dt>{tty_speed(), Speed}</dt>
%% <dd>Specify input or output baud rate. Provided for
%% completeness. Not useful for pseudo terminals.</dd>
%% </dl>
-type pty_opts() :: list(pty_opt()).
%% List of pty options.
-export_type([pty_opt/0, pty_opts/0]).
%%-------------------------------------------------------------------------
%% @doc Supervised start an external program manager.
%% Note that the port program requires `SHELL' environment variable to
%% be set.
%% @end
%%-------------------------------------------------------------------------
-spec start_link(exec_options()) -> {ok, pid()} | {error, any()}.
start_link(Options) when is_list(Options) ->
% Debug = {debug, [trace, log, statistics, {log_to_file, "./execserver.log"}]},
gen_server:start_link({local, ?MODULE}, ?MODULE, [Options], []). % , [Debug]).
%%-------------------------------------------------------------------------
%% @equiv start_link/1
%% @doc Start of an external program manager without supervision.
%% Note that the port program requires `SHELL' environment variable to
%% be set.
%% @end
%%-------------------------------------------------------------------------
-spec start() -> {ok, pid()} | {error, any()}.
start() ->
start([]).
-spec start(exec_options()) -> {ok, pid()} | {error, any()}.
start(Options) when is_list(Options) ->
case check_options(Options) of
ok ->
gen_server:start({local, ?MODULE}, ?MODULE, [Options], []);
{error, Reason} ->
{error, Reason}
end.
%%-------------------------------------------------------------------------
%% @doc Run an external program. `OsPid' is the OS process identifier of
%% the new process. If `sync' is specified in `Options' the return
%% value is `{ok, Status}' where `Status' is OS process exit status.
%% The `Status' can be decoded with `status/1' to determine the
%% process's exit code and if it was killed by signal.
%% @end
%%-------------------------------------------------------------------------
-spec run(cmd(), cmd_options(), integer()) ->
{ok, pid(), ospid()} | {ok, [{stdout | stderr, [binary()]}]} | {error, any()}.
run(Exe, Options, Timeout) when (is_binary(Exe) orelse is_list(Exe))
andalso is_list(Options) andalso is_integer(Timeout) ->
do_run({run, Exe, Options}, Options, Timeout).
run(Exe, Options) ->
run(Exe, Options, ?TIMEOUT).
%%-------------------------------------------------------------------------
%% @equiv run/2
%% @doc Run an external program and link to the OsPid. If OsPid exits,
%% the calling process will be killed or if it's trapping exits,
%% it'll get {'EXIT', OsPid, Status} message. If the calling process
%% dies the OsPid will be killed.
%% The `Status' can be decoded with `status/1' to determine the
%% process's exit code and if it was killed by signal.
%% @end
%%-------------------------------------------------------------------------
-spec run_link(cmd(), cmd_options(), integer()) ->
{ok, pid(), ospid()} | {ok, [{stdout | stderr, [binary()]}]} | {error, any()}.
run_link(Exe, Options, Timeout) when (is_binary(Exe) orelse is_list(Exe))
andalso is_list(Options) andalso is_integer(Timeout) ->
do_run({run, Exe, Options}, [link | Options], Timeout).
run_link(Exe, Options) ->
run_link(Exe, Options, ?TIMEOUT).
%%-------------------------------------------------------------------------
%% @doc Manage an existing external process. `OsPid' is the OS process
%% identifier of the external OS process or an Erlang `Port' that
%% would be managed by erlexec.
%% @end
%%-------------------------------------------------------------------------
-spec manage(ospid() | port(), Options::cmd_options(), Timeout::integer()) ->
{ok, pid(), ospid()} | {error, any()}.
manage(Pid, Options, Timeout) when is_integer(Pid), is_integer(Timeout) ->
do_run({manage, Pid, Options}, Options, Timeout);
manage(Port, Options, Timeout) when is_port(Port), is_integer(Timeout) ->
{os_pid, OsPid} = erlang:port_info(Port, os_pid),
manage(OsPid, Options, Timeout).
manage(Port, Options) ->
manage(Port, Options, ?TIMEOUT).
%%-------------------------------------------------------------------------
%% @doc Get a list of children managed by port program.
%% @end
%%-------------------------------------------------------------------------
-spec which_children() -> [ospid(), ...].
which_children() ->
gen_server:call(?MODULE, {port, {list}}).
%%-------------------------------------------------------------------------
%% @doc Send a `Signal' to a child `Pid', `OsPid' or an Erlang `Port'.
%% @end
%%-------------------------------------------------------------------------
-spec kill(pid() | ospid(), atom()|integer()) -> ok | {error, any()}.
kill(Pid, Signal) when is_atom(Signal) ->
kill(Pid, signal_to_int(Signal));
kill(Pid, Signal) when (is_pid(Pid) orelse is_integer(Pid))
andalso is_integer(Signal) ->
gen_server:call(?MODULE, {port, {kill, Pid, Signal}});
kill(Port, Signal) when is_port(Port) ->
{os_pid, Pid} = erlang:port_info(Port, os_pid),
kill(Pid, Signal).
%%-------------------------------------------------------------------------
%% @doc Change group ID of a given `OsPid' to `Gid'.
%% @end
%%-------------------------------------------------------------------------
-spec setpgid(ospid(), osgid()) -> ok | {error, any()}.
setpgid(OsPid, Gid) when is_integer(OsPid), is_integer(Gid) ->
gen_server:call(?MODULE, {port, {setpgid, OsPid, Gid}}).
%%-------------------------------------------------------------------------
%% @doc Terminate a managed `Pid', `OsPid', or `Port' process. The OS process is
%% terminated gracefully. If it was given a `{kill, Cmd}' option at
%% startup, that command is executed and a timer is started. If
%% the program doesn't exit, then the default termination is
%% performed. Default termination implies sending a `SIGTERM' command
%% followed by `SIGKILL' in 5 seconds, if the program doesn't get
%% killed.
%% @end
%%-------------------------------------------------------------------------
-spec stop(pid() | ospid() | port()) -> ok | {error, any()}.
stop(Pid) when is_pid(Pid); is_integer(Pid) ->
gen_server:call(?MODULE, {port, {stop, Pid}}, 30000);
stop(Port) when is_port(Port) ->
{os_pid, Pid} = erlang:port_info(Port, os_pid),
stop(Pid).
%%-------------------------------------------------------------------------
%% @doc Terminate a managed `Pid', `OsPid', or `Port' process, like
%% `stop/1', and wait for it to exit.
%% @end
%%-------------------------------------------------------------------------
-spec stop_and_wait(pid() | ospid() | port(), integer()) -> term() | {error, any()}.
stop_and_wait(Port, Timeout) when is_port(Port) ->
{os_pid, OsPid} = erlang:port_info(Port, os_pid),
stop_and_wait(OsPid, Timeout);
stop_and_wait(OsPid, Timeout) when is_integer(OsPid) ->
case ets:lookup(exec_mon, OsPid) of
[{_, Pid}] ->
stop_and_wait(Pid, Timeout);
[] ->
{error, not_found}
end;
stop_and_wait(Pid, Timeout) when is_pid(Pid) ->
gen_server:call(?MODULE, {port, {stop, Pid}}, Timeout),
receive
{'DOWN', _Ref, process, Pid, ExitStatus} -> ExitStatus
after Timeout -> {error, timeout}
end;
stop_and_wait(Port, Timeout) when is_port(Port) ->
{os_pid, Pid} = erlang:port_info(Port, os_pid),
stop_and_wait(Pid, Timeout).
%%-------------------------------------------------------------------------
%% @doc Get `OsPid' of the given Erlang `Pid'. The `Pid' must be created
%% previously by running the run/2 or run_link/2 commands.
%% @end
%%-------------------------------------------------------------------------
-spec ospid(pid()) -> ospid() | {error, Reason::any()}.
ospid(Pid) when is_pid(Pid) ->
Ref = make_ref(),
Pid ! {{self(), Ref}, ospid},
receive
{Ref, Reply} -> Reply;
Other -> Other
after 5000 -> {error, timeout}
end.
%%-------------------------------------------------------------------------
%% @doc Get `Pid' of the given `OsPid'. The `OsPid' must be created
%% previously by running the run/2 or run_link/2 commands.
%% @end
%%-------------------------------------------------------------------------
-spec pid(OsPid::ospid()) -> pid() | undefined | {error, timeout}.
pid(OsPid) when is_integer(OsPid) ->
gen_server:call(?MODULE, {pid, OsPid}).
%%-------------------------------------------------------------------------
%% @doc Send `Data' to stdin of the OS process identified by `OsPid'.
%%
%% Sending eof instead of binary Data causes close of stdin of the
%% corresponding process. Data sent to closed stdin is ignored.
%%
%% @end
%%-------------------------------------------------------------------------
-spec send(OsPid :: ospid() | pid(), binary() | 'eof') -> ok.
send(OsPid, Data)
when (is_integer(OsPid) orelse is_pid(OsPid)),
(is_binary(Data) orelse Data =:= eof) ->
gen_server:call(?MODULE, {port, {send, OsPid, Data}}).
%%-------------------------------------------------------------------------
%% @doc Set the pty terminal `Rows' and `Cols' of the OS process identified by `OsPid'.
%%
%% The process must have been created with the `pty' option.
%%
%% @end
%%-------------------------------------------------------------------------
-spec winsz(OsPid :: ospid() | pid(), integer(), integer()) -> ok | {error, Reason::any()}.
winsz(OsPid, Rows, Cols)
when (is_integer(OsPid) orelse is_pid(OsPid)),
is_integer(Rows),
is_integer(Cols) ->
gen_server:call(?MODULE, {port, {winsz, OsPid, Rows, Cols}}).
%%-------------------------------------------------------------------------
%% @doc Set the pty terminal options of the OS process identified by `OsPid'.
%%
%% The process must have been created with the `pty' option.
%%
%% @end
%%-------------------------------------------------------------------------
-spec pty_opts(OsPid :: ospid() | pid(), pty_opts()) -> ok | {error, Reason::any()}.
pty_opts(OsPid, Opts)
when (is_integer(OsPid) orelse is_pid(OsPid)),
is_list(Opts) ->
gen_server:call(?MODULE, {port, {pty_opts, OsPid, Opts}}).
%%-------------------------------------------------------------------------
%% @doc Set debug level of the port process.
%% @end
%%-------------------------------------------------------------------------
-spec debug(Level::integer()) -> {ok, OldLevel::integer()} | {error, timeout}.
debug(Level) when is_integer(Level), Level >= 0, Level =< 10 ->
gen_server:call(?MODULE, {port, {debug, Level}}).
%%-------------------------------------------------------------------------
%% @doc Decode the program's exit_status. If the program exited by signal
%% the function returns `{signal, Signal, Core}' where the `Signal'
%% is the signal number or atom, and `Core' indicates if the core file
%% was generated.
%% @end
%%-------------------------------------------------------------------------
-spec status(integer()) ->
{status, ExitStatus :: integer()} |
{signal, Signal :: integer() | atom(), Core :: boolean()}.
status(Status) when is_integer(Status) ->
TermSignal = Status band 16#7F,
IfSignaled = ((TermSignal + 1) bsr 1) > 0,
ExitStatus = (Status band 16#FF00) bsr 8,
case IfSignaled of
true ->
CoreDump = (Status band 16#80) =:= 16#80,
{signal, signal(TermSignal), CoreDump};
false ->
{status, ExitStatus}
end.
%%-------------------------------------------------------------------------
%% @doc Convert a signal number to atom
%% @end
%%-------------------------------------------------------------------------
-spec signal(integer()) -> atom() | integer().
signal( 1) -> sighup;
signal( 2) -> sigint;
signal( 3) -> sigquit;
signal( 4) -> sigill;
signal( 5) -> sigtrap;
signal( 6) -> sigabrt;
signal( 7) -> sigbus;
signal( 8) -> sigfpe;
signal( 9) -> sigkill;
signal(11) -> sigsegv;
signal(13) -> sigpipe;
signal(14) -> sigalrm;
signal(15) -> sigterm;
signal(16) -> sigstkflt;
signal(17) -> sigchld;
signal(18) -> sigcont;
signal(19) -> sigstop;
signal(20) -> sigtstp;
signal(21) -> sigttin;
signal(22) -> sigttou;
signal(23) -> sigurg;
signal(24) -> sigxcpu;
signal(25) -> sigxfsz;
signal(26) -> sigvtalrm;
signal(27) -> sigprof;
signal(28) -> sigwinch;
signal(29) -> sigio;
signal(30) -> sigpwr;
signal(31) -> sigsys;
signal(34) -> sigrtmin;
signal(64) -> sigrtmax;
signal(Num) when is_integer(Num) -> Num.
signal_to_int(sighup) -> 1;
signal_to_int(sigint) -> 2;
signal_to_int(sigquit) -> 3;
signal_to_int(sigill) -> 4;
signal_to_int(sigtrap) -> 5;
signal_to_int(sigabrt) -> 6;
signal_to_int(sigbus) -> 7;
signal_to_int(sigfpe) -> 8;
signal_to_int(sigkill) -> 9;
signal_to_int(sigsegv) -> 11;
signal_to_int(sigpipe) -> 13;
signal_to_int(sigalrm) -> 14;
signal_to_int(sigterm) -> 15;
signal_to_int(sigstkflt) -> 16;
signal_to_int(sigchld) -> 17;
signal_to_int(sigcont) -> 18;
signal_to_int(sigstop) -> 19;
signal_to_int(sigtstp) -> 20;
signal_to_int(sigttin) -> 21;
signal_to_int(sigttou) -> 22;
signal_to_int(sigurg) -> 23;
signal_to_int(sigxcpu) -> 24;
signal_to_int(sigxfsz) -> 25;
signal_to_int(sigvtalrm) -> 26;
signal_to_int(sigprof) -> 27;
signal_to_int(sigwinch) -> 28;
signal_to_int(sigio) -> 29;
signal_to_int(sigpwr) -> 30;
signal_to_int(sigsys) -> 31;
signal_to_int(sigrtmin) -> 34;
signal_to_int(sigrtmax) -> 64.
%%-------------------------------------------------------------------------
%% @private
%% @doc Provide default value of a given option.
%% @end
%%-------------------------------------------------------------------------
-spec default() -> [{atom(), term()}].
default() ->
[{debug, 0}, % Debug mode of the port program.
{verbose, false}, % Verbose print of events on the Erlang side.
{root, false}, % Allow running processes as root.
{args, ""}, % Extra arguments that can be passed to port program
{alarm, 12},
{portexe, noportexe},
{user, ""}, % Run port program as this user
{limit_users, []}]. % Restricted list of users allowed to run commands
%% @private
default(portexe) ->
% Retrieve the Priv directory
case code:priv_dir(erlexec) of
{error, _} ->
error_logger:warning_msg("Priv directory not available", []),
"";
Priv ->
% Find all ports using wildcard for resiliency
Bin = case filelib:wildcard("*/exec-port", Priv) of
[Port] -> Port;
_ ->
Arch = erlang:system_info(system_architecture),
Tail = filename:join([Arch, "exec-port"]),
os:find_executable(filename:join([Priv, Tail]))
end,
% Join the priv/port path
filename:join([Priv, Bin])
end;
default(Option) ->
proplists:get_value(Option, default()).
%%%----------------------------------------------------------------------
%%% Callback functions from gen_server
%%%----------------------------------------------------------------------
%%-----------------------------------------------------------------------
%% Func: init/1
%% Returns: {ok, State} |
%% {ok, State, Timeout} |
%% ignore |
%% {stop, Reason}
%% @private
%%-----------------------------------------------------------------------
init([Options]) ->
process_flag(trap_exit, true),
Opts0 = proplists:expand([{debug, [{debug, 1}]},
{root, [{root, true}]},
{verbose, [{verbose, true}]}], Options),
Opts1 = [T || T = {O,_} <- Opts0,
lists:member(O, [debug, verbose, root, args, alarm, user])],
Opts = proplists:normalize(Opts1, [{aliases, [{args, ''}]}]),
Args0 = lists:foldl(
fun
(Opt, Acc) when is_atom(Opt) ->
[" -"++atom_to_list(Opt)++" " | Acc];
({Opt, I}, Acc) when is_atom(I) ->
[" -"++atom_to_list(Opt)++" "++atom_to_list(I) | Acc];
({Opt, I}, Acc) when is_list(I), I /= ""; is_binary(I), I /= <<"">> ->
[" -"++atom_to_list(Opt)++" "++to_list(I) | Acc];
({Opt, I}, Acc) when is_integer(I) ->
[" -"++atom_to_list(Opt)++" "++integer_to_list(I) | Acc];
(_, Acc) -> Acc
end, [], Opts),
Exe0 = case proplists:get_value(portexe, Options, noportexe) of
noportexe -> default(portexe);
UserExe -> to_list(UserExe)
end,
Exe1 = ?FMT("~p", [Exe0]),
Args = lists:flatten(Args0),
Users = case proplists:get_value(limit_users, Options, default(limit_users)) of
[] -> [];
L -> [to_list(I) || I <- L]
end,
User = to_list(proplists:get_value(user,Options)),
Debug = proplists:get_value(verbose, Options, default(verbose)),
Root = proplists:get_value(root, Options, default(root)),
Env = case proplists:get_value(env, Options) of
undefined -> [];
Other -> [{env, parse_env(Other)}]
end,
% When instructing to run as root, check that the port program has
% the SUID bit set or else use "sudo"
{SUID,NeedSudo} = is_suid_and_root_owner(Exe0),
EffUsr= os:getenv("USER"),
IsRoot= EffUsr =:= "root",
Exe = if not Root ->
Exe1++Args;
Root, IsRoot, User/=undefined, User/="", ((SUID andalso Users/=[]) orelse
(not SUID andalso Users==[])) ->
Exe1++Args;
%Root, not IsRoot, NeedSudo, User/=undefined, User/="" ->
% Asked to enable root, but running as non-root, and have no SUID: use sudo.
% lists:append(["/usr/bin/sudo -u ", to_list(User), " ", Exe1, Args]);
Root, not IsRoot, NeedSudo, ((User/=undefined andalso User/="") orelse
(EffUsr/=User andalso User/=undefined
andalso User/=root
andalso User/="root")) ->
% Asked to enable root, but running as non-root, and have SUID: use sudo.
lists:append(["/usr/bin/sudo ", Exe1, Args]);
true ->
Exe1++Args
end,
debug(Debug, "exec: ~s~sport program: ~s\n~s",
[if SUID -> "[SUID] "; true -> "" end,
if (Root orelse IsRoot) andalso User =:= [] -> "[ROOT] "; true -> "" end,
Exe,
if Env =/= [] -> " env: "++?FMT("~p", Env)++"\n"; true -> "" end]),
try
PortOpts = Env ++ [binary, exit_status, {packet, 2}, hide],
Port = erlang:open_port({spawn, Exe}, PortOpts),
receive
{Port, {exit_status, Status}} ->
{stop, {port_exited_with_status, Status}}
after 350 ->
Tab = ets:new(exec_mon, [protected,named_table]),
{ok, #state{port=Port, limit_users=Users, debug=Debug, registry=Tab, root=Root}}
end
catch
?EXCEPTION(_, Reason, Stacktrace) ->
{stop, ?FMT("Error starting port '~s': ~200p\n ~p\n",
[Exe, Reason, ?GET_STACK(Stacktrace)])}
end.
%%----------------------------------------------------------------------
%% Func: handle_call/3
%% Returns: {reply, Reply, State} |
%% {reply, Reply, State, Timeout} |
%% {noreply, State} |
%% {noreply, State, Timeout} |
%% {stop, Reason, Reply, State} | (terminate/2 is called)
%% {stop, Reason, State} (terminate/2 is called)
%% @private
%%----------------------------------------------------------------------
handle_call({port, Instruction}, From, #state{last_trans=Last} = State) ->
try is_port_command(Instruction, element(1, From), State) of
{ok, Term} ->
erlang:port_command(State#state.port, term_to_binary({0, Term})),
{reply, ok, State};
{ok, Term, Link, Sync, PidOpts} ->
Next = next_trans(Last),
erlang:port_command(State#state.port, term_to_binary({Next, Term})),
{noreply, State#state{trans = queue:in({Next, From, Link, Sync, PidOpts}, State#state.trans)}}
catch _:{error, Why} ->
{reply, {error, Why}, State}
end;
handle_call({pid, OsPid}, _From, State) ->
case ets:lookup(exec_mon, OsPid) of
[{_, Pid}] -> {reply, Pid, State};
_ -> {reply, undefined, State}
end;
handle_call(Request, _From, _State) ->
{stop, {not_implemented, Request}}.
%%----------------------------------------------------------------------
%% Func: handle_cast/2
%% Returns: {noreply, State} |
%% {noreply, State, Timeout} |
%% {stop, Reason, State} (terminate/2 is called)
%% @private
%%----------------------------------------------------------------------
handle_cast(_Msg, State) ->
{noreply, State}.
%%----------------------------------------------------------------------
%% Func: handle_info/2
%% Returns: {noreply, State} |
%% {noreply, State, Timeout} |
%% {stop, Reason, State} (terminate/2 is called)
%% @private
%%----------------------------------------------------------------------
handle_info({Port, {data, Bin}}, #state{port=Port, debug=Debug} = State) ->
Msg = binary_to_term(Bin),
debug(Debug, "~w got msg from port: ~p\n", [?MODULE, Msg]),
case Msg of
{N, Reply} when N =/= 0 ->
case get_transaction(State#state.trans, N) of
{true, {Pid,_} = From, MonType, Sync, PidOpts, Q} ->
NewReply = maybe_add_monitor(Reply, Pid, MonType, Sync, PidOpts, Debug),
gen_server:reply(From, NewReply);
{false, Q} ->
ok
end,
{noreply, State#state{trans=Q}};
{0, {Stream, OsPid, Data}} when Stream =:= stdout; Stream =:= stderr ->
send_to_ospid_owner(OsPid, {Stream, Data}),
{noreply, State};
{0, {exit_status, OsPid, Status}} ->
debug(Debug, "Pid ~w exited with status: ~s{~w,~w}\n",
[OsPid, if (((Status band 16#7F)+1) bsr 1) > 0 -> "signaled "; true -> "" end,
(Status band 16#FF00 bsr 8), Status band 127]),
notify_ospid_owner(OsPid, Status),
{noreply, State};
{0, ok} ->
{noreply, State};
{0, Ignore} ->
error_logger:warning_msg("~w [~w] unknown msg: ~p\n", [self(), ?MODULE, Ignore]),
{noreply, State}
end;
handle_info({Port, {exit_status, 0}}, #state{port=Port} = State) ->
{stop, normal, State};
handle_info({Port, {exit_status, Status}}, #state{port=Port} = State) ->
{stop, {exit_status, Status}, State};
handle_info({'EXIT', Port, Reason}, #state{port=Port} = State) ->
{stop, Reason, State};
handle_info({'EXIT', Pid, Reason}, State) ->
% OsPid's Pid owner died. Kill linked OsPid.
do_unlink_ospid(Pid, Reason, State),
{noreply, State};
handle_info(_Info, State) ->
error_logger:info_msg("~w - unhandled message: ~p\n", [?MODULE, _Info]),
{noreply, State}.
%%----------------------------------------------------------------------
%% Func: code_change/3
%% Purpose: Convert process state when code is changed
%% Returns: {ok, NewState}
%% @private
%%----------------------------------------------------------------------
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
%%----------------------------------------------------------------------
%% Func: terminate/2
%% Purpose: Shutdown the server
%% Returns: any (ignored by gen_server)
%% @private
%%----------------------------------------------------------------------
terminate(_Reason, State) ->
try
erlang:port_command(State#state.port, term_to_binary({0, {shutdown}})),
case wait_port_exit(State#state.port) of
0 -> ok;
S -> error_logger:warning_msg("~w - exec process terminated (status: ~w)\n",
[self(), S])
end
catch _:_ ->
ok
end.
to_list(undefined) -> [];
to_list(A) when is_atom(A) -> atom_to_list(A);
to_list(L) when is_list(L) -> L;
to_list(B) when is_binary(B) -> binary_to_list(B).
wait_port_exit(Port) ->
receive
{Port,{exit_status,Status}} ->
Status;
_ ->
wait_port_exit(Port)
end.
%%%---------------------------------------------------------------------
%%% Internal functions
%%%---------------------------------------------------------------------
-spec do_run(Cmd::any(), Options::cmd_options(), Timeout::integer()) ->
{ok, pid(), ospid()} | {ok, [{stdout | stderr, [binary()]}]} | {error, any()}.
do_run(Cmd, Options, Timeout) when is_integer(Timeout) ->
Link = case {proplists:get_bool(link, Options),
proplists:get_bool(monitor, Options)} of
{true, _} -> link;
{_, true} -> monitor;
_ -> undefined
end,
Sync = proplists:get_value(sync, Options, false),
Cmd2 = {port, {Cmd, Link, Sync}},
case gen_server:call(?MODULE, Cmd2, Timeout) of
{ok, Pid, OsPid, _Sync = true} ->
wait_for_ospid_exit(OsPid, Pid, [], []);
{ok, Pid, OsPid, _} ->
{ok, Pid, OsPid};
{error, Reason} ->
{error, Reason}
end.
wait_for_ospid_exit(OsPid, Pid, OutAcc, ErrAcc) ->
% Note when a monitored process exits
receive
{stdout, OsPid, Data} ->
wait_for_ospid_exit(OsPid, Pid, [Data | OutAcc], ErrAcc);
{stderr, OsPid, Data} ->
wait_for_ospid_exit(OsPid, Pid, OutAcc, [Data | ErrAcc]);
{'DOWN', OsPid, process, Pid, normal} ->
{ok, sync_res(OutAcc, ErrAcc)};
{'DOWN', OsPid, process, Pid, noproc} ->
{ok, sync_res(OutAcc, ErrAcc)};
{'DOWN', OsPid, process, Pid, {exit_status,_}=R} ->
{error, [R | sync_res(OutAcc, ErrAcc)]}
end.
sync_res([], []) -> [];
sync_res([], L) -> [{stderr, lists:reverse(L)}];
sync_res(LO, LE) -> [{stdout, lists:reverse(LO)} | sync_res([], LE)].
%% Add a link for Pid to OsPid if requested.
maybe_add_monitor({pid, OsPid}, Pid, MonType, Sync, PidOpts, Debug) when is_integer(OsPid) ->
% This is a reply to a run/run_link command. The port program indicates