aboutsummaryrefslogtreecommitdiffstats
path: root/src/com/cyanogenmod/filemanager/console/shell/ShellConsole.java
blob: fb3b5075b04a97be3ad3cd03c891b0897d81a940 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
/*
 * Copyright (C) 2012 The CyanogenMod Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.cyanogenmod.filemanager.console.shell;

import android.util.Log;

import com.cyanogenmod.filemanager.FileManagerApplication;
import com.cyanogenmod.filemanager.commands.AsyncResultExecutable;
import com.cyanogenmod.filemanager.commands.Executable;
import com.cyanogenmod.filemanager.commands.ExecutableFactory;
import com.cyanogenmod.filemanager.commands.GroupsExecutable;
import com.cyanogenmod.filemanager.commands.IdentityExecutable;
import com.cyanogenmod.filemanager.commands.ProcessIdExecutable;
import com.cyanogenmod.filemanager.commands.SIGNAL;
import com.cyanogenmod.filemanager.commands.shell.AsyncResultProgram;
import com.cyanogenmod.filemanager.commands.shell.Command;
import com.cyanogenmod.filemanager.commands.shell.InvalidCommandDefinitionException;
import com.cyanogenmod.filemanager.commands.shell.Program;
import com.cyanogenmod.filemanager.commands.shell.Shell;
import com.cyanogenmod.filemanager.commands.shell.ShellExecutableFactory;
import com.cyanogenmod.filemanager.commands.shell.SyncResultProgram;
import com.cyanogenmod.filemanager.console.CommandNotFoundException;
import com.cyanogenmod.filemanager.console.Console;
import com.cyanogenmod.filemanager.console.ConsoleAllocException;
import com.cyanogenmod.filemanager.console.ExecutionException;
import com.cyanogenmod.filemanager.console.InsufficientPermissionsException;
import com.cyanogenmod.filemanager.console.NoSuchFileOrDirectory;
import com.cyanogenmod.filemanager.console.OperationTimeoutException;
import com.cyanogenmod.filemanager.console.ReadOnlyFilesystemException;
import com.cyanogenmod.filemanager.model.Identity;
import com.cyanogenmod.filemanager.preferences.FileManagerSettings;
import com.cyanogenmod.filemanager.preferences.Preferences;
import com.cyanogenmod.filemanager.util.CommandHelper;
import com.cyanogenmod.filemanager.util.FileHelper;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.SecureRandom;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * An implementation of a {@link Console} based in the execution of shell commands.<br/>
 * <br/>
 * This class holds a <code>shell bash</code> program associated with the application, being
 * a wrapper to execute all other programs (like shell does in linux), capturing the
 * output (stdin and stderr) and the exit code of the program executed.
 */
public abstract class ShellConsole extends Console implements Program.ProgramListener {

    private static final String TAG = "ShellConsole"; //$NON-NLS-1$

    // A timeout of 5 seconds should be enough for no-debugging environments
    private static final long DEFAULT_TIMEOUT =
            FileManagerApplication.isDebuggable() ? 20000L : 5000L;

    private static final int DEFAULT_BUFFER = 512;

    //Shell References
    private final Shell mShell;
    private final String mInitialDirectory;
    private Identity mIdentity;

    //Process References
    private final Object mSync = new Object();
    /**
     * @hide
     */
    final Object mPartialSync = new Object();
    /**
     * @hide
     */
    boolean mActive = false;
    private boolean mFinished = true;
    private Process mProc = null;
    /**
     * @hide
     */
    Program mActiveCommand = null;
    /**
     * @hide
     */
    boolean mCancelled;
    /**
     * @hide
     */
    boolean mStarted;

    //Buffers
    private InputStream mIn = null;
    private InputStream mErr = null;
    private OutputStream mOut = null;
    /**
     * @hide
     */
    StringBuffer mSbIn = null;
    /**
     * @hide
     */
    StringBuffer mSbErr = null;

    private final SecureRandom mRandom;
    private String mStartControlPattern;
    private String mEndControlPattern;

    /**
     * @hide
     */
    int mBufferSize;

    private final ShellExecutableFactory mExecutableFactory;

    /**
     * Constructor of <code>ShellConsole</code>.
     *
     * @param shell The shell used to execute commands
     * @throws FileNotFoundException If the default initial directory not exists
     * @throws IOException If initial directory couldn't be resolved
     */
    public ShellConsole(Shell shell) throws FileNotFoundException, IOException {
        this(shell, Preferences.getSharedPreferences().getString(
                            FileManagerSettings.SETTINGS_INITIAL_DIR.getId(),
                            (String)FileManagerSettings.SETTINGS_INITIAL_DIR.getDefaultValue()));
    }

    /**
     * Constructor of <code>ShellConsole</code>.
     *
     * @param shell The shell used to execute commands
     * @param initialDirectory The initial directory of the shell
     * @throws FileNotFoundException If the initial directory not exists
     * @throws IOException If initial directory couldn't be resolved
     */
    public ShellConsole(Shell shell, String initialDirectory)
            throws FileNotFoundException, IOException {
        super();
        this.mShell = shell;
        this.mExecutableFactory = new ShellExecutableFactory(this);

        this.mBufferSize = DEFAULT_BUFFER;

        //Resolve and checks the initial directory
        File f = new File(initialDirectory);
        while (FileHelper.isSymlink(f)) {
            f = FileHelper.resolveSymlink(f);
        }
        if (!f.exists() || !f.isDirectory()) {
            throw new FileNotFoundException(f.toString());
        }
        this.mInitialDirectory = initialDirectory;

        //Restart the buffers
        this.mSbIn = new StringBuffer();
        this.mSbErr = new StringBuffer();

        //Generate an aleatory secure random generator
        try {
            this.mRandom = SecureRandom.getInstance("SHA1PRNG"); //$NON-NLS-1$
        } catch (Exception ex) {
            throw new IOException(ex);
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public ExecutableFactory getExecutableFactory() {
        return this.mExecutableFactory;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Identity getIdentity() {
        return this.mIdentity;
    }

    /**
     * Method that returns the buffer size
     *
     * @return int The buffer size
     */
    public int getBufferSize() {
        return this.mBufferSize;
    }

    /**
     * Method that sets the buffer size
     *
     * @param bufferSize the The buffer size
     */
    public void setBufferSize(int bufferSize) {
        this.mBufferSize = bufferSize;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public final boolean isActive() {
        return this.mActive;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public final void alloc() throws ConsoleAllocException {
        try {
            //Create command string
            List<String> cmd = new ArrayList<String>();
            cmd.add(this.mShell.getCommand());
            if (this.mShell.getArguments() != null && this.mShell.getArguments().length() > 0) {
                cmd.add(this.mShell.getArguments());
            }

            //Create the process
            Runtime rt = Runtime.getRuntime();
            this.mProc =
                    rt.exec(
                            cmd.toArray(new String[cmd.size()]),
                            null,
                            new File(this.mInitialDirectory));
            synchronized (this.mSync) {
                this.mActive = true;
            }
            if (isTrace()) {
                Log.v(TAG,
                        String.format("Create console %s, command: %s, args: %s",  //$NON-NLS-1$
                                this.mShell.getId(),
                                this.mShell.getCommand(),
                                this.mShell.getArguments()));
            }

            //Allocate buffers
            this.mIn = this.mProc.getInputStream();
            this.mErr = this.mProc.getErrorStream();
            this.mOut = this.mProc.getOutputStream();
            if (this.mIn == null || this.mErr == null || this.mOut == null) {
                try {
                    dealloc();
                } catch (Throwable ex) {
                    /**NON BLOCK**/
                }
                throw new ConsoleAllocException("Console buffer allocation error."); //$NON-NLS-1$
            }

            //Starts a thread for extract output, and check timeout
            createStdInThread(this.mIn);
            createStdErrThread(this.mErr);

            //Wait for thread start
            Thread.sleep(50L);

            //Check if process its active
            checkIfProcessExits();
            synchronized (this.mSync) {
                if (!this.mActive) {
                    throw new ConsoleAllocException("Shell not started."); //$NON-NLS-1$
                }
            }

            // Retrieve the PID of the shell
            ProcessIdExecutable processIdCmd =
                    getExecutableFactory().
                        newCreator().createShellProcessIdExecutable();
            execute(processIdCmd);
            Integer pid = processIdCmd.getResult();
            if (pid == null) {
                throw new ConsoleAllocException(
                        "can't retrieve the PID of the shell."); //$NON-NLS-1$
            }
            this.mShell.setPid(pid.intValue());

            //Retrieve identity
            IdentityExecutable identityCmd =
                    getExecutableFactory().newCreator().createIdentityExecutable();
            execute(identityCmd);
            this.mIdentity = identityCmd.getResult();
            // Identity command is required for root console detection,
            // but Groups command is not used for now. Also, this command is causing
            // problems on some implementations (maybe toolbox?) which don't
            // recognize the root AID and returns an error. Safely ignore on error.
            try {
                if (this.mIdentity.getGroups().size() == 0) {
                    //Try with groups
                    GroupsExecutable groupsCmd =
                            getExecutableFactory().newCreator().createGroupsExecutable();
                    execute(groupsCmd);
                    this.mIdentity.setGroups(groupsCmd.getResult());
                }
            } catch (Exception ex) {
                Log.w(TAG, "Groups command failed. Ignored.", ex);
            }

        } catch (Exception ex) {
            try {
                dealloc();
            } catch (Throwable ex2) {
                /**NON BLOCK**/
            }
            throw new ConsoleAllocException("Console allocation error.", ex); //$NON-NLS-1$
        }

    }

    /**
     * {@inheritDoc}
     */
    @Override
    public final void dealloc() {
        synchronized (this.mSync) {
            if (this.mActive) {
                this.mActive = false;
                this.mFinished = true;

                //Close buffers
                try {
                    if (this.mIn != null) {
                        this.mIn.close();
                    }
                } catch (Throwable ex) {
                    /**NON BLOCK**/
                }
                try {
                    if (this.mErr != null) {
                        this.mErr.close();
                    }
                } catch (Throwable ex) {
                    /**NON BLOCK**/
                }
                try {
                    if (this.mOut != null) {
                        this.mOut.close();
                    }
                } catch (Throwable ex) {
                    /**NON BLOCK**/
                }
                try {
                    this.mProc.destroy();
                } catch (Throwable e) {/**NON BLOCK**/}
                this.mIn = null;
                this.mErr = null;
                this.mOut = null;
                this.mSbIn = null;
                this.mSbErr = null;
            }
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public final void realloc() throws ConsoleAllocException {
        dealloc();
        alloc();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public final synchronized void execute(final Executable executable)
            throws ConsoleAllocException, InsufficientPermissionsException,
            CommandNotFoundException, NoSuchFileOrDirectory,
            OperationTimeoutException, ExecutionException, ReadOnlyFilesystemException {

        //Is a program?
        if (!(executable instanceof Program)) {
            throw new CommandNotFoundException("executable not instanceof Program"); //$NON-NLS-1$
        }

        //Asynchronous or synchronous execution?
        final Program program = (Program)executable;
        if (executable instanceof AsyncResultExecutable) {
            Thread asyncThread = new Thread(new Runnable() {
                @Override
                public void run() {
                    //Synchronous execution (but asynchronous running in a thread)
                    //This way syncExecute is locked until this thread ends
                    try {
                        if (ShellConsole.this.syncExecute(program, true)) {
                            ShellConsole.this.syncExecute(program, false);
                        }
                    } catch (Exception ex) {
                        if (((AsyncResultExecutable)executable).getAsyncResultListener() != null) {
                            ((AsyncResultExecutable)executable).
                                getAsyncResultListener().onException(ex);
                        } else {
                            //Capture exception
                            Log.e(TAG, "Fail asynchronous execution", ex); //$NON-NLS-1$
                        }
                    }
                }
            });
            asyncThread.start();
        } else {
            //Synchronous execution (2 tries with 1 reallocation)
            if (syncExecute(program, true)) {
                syncExecute(program, false);
            }
        }
    }

    /**
     * Method for execute a program command in the operating system layer in a synchronous way.
     *
     * @param program The program to execute
     * @param reallocate If the console must be reallocated on i/o error
     * @return boolean If the console was reallocated
     * @throws ConsoleAllocException If the console is not allocated
     * @throws InsufficientPermissionsException If an operation requires elevated permissions
     * @throws CommandNotFoundException If the command was not found
     * @throws NoSuchFileOrDirectory If the file or directory was not found
     * @throws OperationTimeoutException If the operation exceeded the maximum time of wait
     * @throws ExecutionException If the operation returns a invalid exit code
     * @throws ReadOnlyFilesystemException If the operation writes in a read-only filesystem
     * @hide
     */
    synchronized boolean syncExecute(final Program program, boolean reallocate)
            throws ConsoleAllocException, InsufficientPermissionsException,
            CommandNotFoundException, NoSuchFileOrDirectory,
            OperationTimeoutException, ExecutionException, ReadOnlyFilesystemException {

        try {
            //Check the console status before send command
            checkConsole();

            synchronized (this.mSync) {
                if (!this.mActive) {
                    throw new ConsoleAllocException("No console allocated"); //$NON-NLS-1$
                }
            }

            //Saves the active command reference
            this.mActiveCommand = program;

            //Reset the buffers
            this.mStarted = false;
            this.mCancelled = false;
            this.mSbIn = new StringBuffer();
            this.mSbErr = new StringBuffer();

            //Random start/end identifiers
            String startId1 =
                    String.format("/#%d#/", Long.valueOf(this.mRandom.nextLong())); //$NON-NLS-1$
            String startId2 =
                    String.format("/#%d#/", Long.valueOf(this.mRandom.nextLong())); //$NON-NLS-1$
            String endId1 =
                    String.format("/#%d#/", Long.valueOf(this.mRandom.nextLong())); //$NON-NLS-1$
            String endId2 =
                    String.format("/#%d#/", Long.valueOf(this.mRandom.nextLong())); //$NON-NLS-1$

            //Create command string
            String cmd = program.getCommand();
            String args = program.getArguments();

            //Audit command
            if (isTrace()) {
                Log.v(TAG,
                        String.format("%s-%s, command: %s, args: %s",  //$NON-NLS-1$
                                ShellConsole.this.mShell.getId(),
                                program.getId(),
                                cmd,
                                args));
            }

            //Is asynchronous program? Then set asynchronous
            program.setProgramListener(this);
            if (program instanceof AsyncResultProgram) {
                ((AsyncResultProgram)program).setOnCancelListener(this);
                ((AsyncResultProgram)program).setOnEndListener(this);
            }

            //Send the command + a control code with exit code
            //The process has finished where control control code is present.
            //This control code is unique in every invocation and is secure random
            //generated (control code 1 + exit code + control code 2)
            try {
                boolean hasEndControl = (!(program instanceof AsyncResultProgram) ||
                                           (program instanceof AsyncResultProgram &&
                                            ((AsyncResultProgram)program).isExpectEnd()));

                this.mStartControlPattern = startId1 + "\\d{1,3}" + startId2 + "\\n"; //$NON-NLS-1$ //$NON-NLS-2$
                this.mEndControlPattern = endId1 + "\\d{1,3}" + endId2; //$NON-NLS-1$
                String startCmd =
                        Command.getStartCodeCommandInfo(
                                FileManagerApplication.getInstance().getResources());
                startCmd = String.format(
                        startCmd, "'" + startId1 +//$NON-NLS-1$
                        "'", "'" + startId2 + "'"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
                String endCmd =
                        Command.getExitCodeCommandInfo(
                                FileManagerApplication.getInstance().getResources());
                endCmd = String.format(
                        endCmd, "'" + endId1 + //$NON-NLS-1$
                        "'", "'" + endId2 + "'"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
                StringBuilder sb = new StringBuilder()
                    .append(startCmd)
                    .append(" ")  //$NON-NLS-1$
                    .append(cmd)
                    .append(" ")  //$NON-NLS-1$
                    .append(args);
               if (hasEndControl) {
                   sb = sb.append(" ") //$NON-NLS-1$
                          .append(endCmd);
               }
               sb.append(FileHelper.NEWLINE);
                this.mOut.write(sb.toString().getBytes());
            } catch (InvalidCommandDefinitionException icdEx) {
                throw new CommandNotFoundException(
                        "ExitCodeCommandInfo not found", icdEx); //$NON-NLS-1$
            }

            //Now, wait for buffers to be filled
            synchronized (this.mSync) {
                if (program instanceof AsyncResultProgram) {
                    this.mSync.wait();
                } else {
                    this.mSync.wait(DEFAULT_TIMEOUT);
                    if (!this.mFinished) {
                        throw new OperationTimeoutException(DEFAULT_TIMEOUT, cmd);
                    }
                }
            }

            //End partial results?
            if (program instanceof AsyncResultProgram) {
                synchronized (this.mPartialSync) {
                    ((AsyncResultProgram)program).onRequestEndParsePartialResult(this.mCancelled);
                }
            }

            //Retrieve exit code
            int exitCode = getExitCode(this.mSbIn);
            if (program instanceof AsyncResultProgram) {
                synchronized (this.mPartialSync) {
                    ((AsyncResultProgram)program).onRequestExitCode(exitCode);
                }
            }
            if (isTrace()) {
                Log.v(TAG,
                        String.format("%s-%s, command: %s, exitCode: %s",  //$NON-NLS-1$
                                ShellConsole.this.mShell.getId(),
                                program.getId(),
                                cmd,
                                String.valueOf(exitCode)));
            }

            //Check if invocation was successfully or not
            if (!program.isIgnoreShellStdErrCheck()) {
                //Wait for stderr buffer to be filled
                if (exitCode != 0) {
                    try {
                        Thread.sleep(100L);
                    } catch (Throwable ex) {/**NON BLOCK**/}
                }
                this.mShell.checkStdErr(this.mActiveCommand, exitCode, this.mSbErr.toString());
            }
            this.mShell.checkExitCode(exitCode);
            program.checkExitCode(exitCode);
            program.checkStdErr(exitCode, this.mSbErr.toString());

            //Parse the result? Only if not partial results
            if (program instanceof SyncResultProgram) {
                try {
                    ((SyncResultProgram)program).parse(
                            this.mSbIn.toString(), this.mSbErr.toString());
                } catch (ParseException pEx) {
                    throw new ExecutionException(
                            "SyncResultProgram parse failed", pEx); //$NON-NLS-1$
                }
            }

            //Invocation finished. Now program.getResult() has the result of
            //the operation, if any exists

        } catch (IOException ioEx) {
            if (reallocate) {
                realloc();
                return true;
            }
            throw new ExecutionException("Console allocation error.", ioEx); //$NON-NLS-1$

        } catch (InterruptedException ioEx) {
            if (reallocate) {
                realloc();
                return true;
            }
            throw new ExecutionException("Console allocation error.", ioEx); //$NON-NLS-1$

        } finally {
            //Dereference the active command
            this.mActiveCommand = null;
        }

        //Operation complete
        return false;
    }

    /**
     * Method that creates the standard input thread for read program response.
     *
     * @param in The standard input buffer
     * @return Thread The standard input thread
     */
    private Thread createStdInThread(final InputStream in) {
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                int read = 0;

                try {
                    while (ShellConsole.this.mActive) {
                        //Read only one byte with active wait
                        final int r = in.read();
                        if (r == -1) {
                            break;
                        }

                        // Type of command
                        boolean async =
                                ShellConsole.this.mActiveCommand != null &&
                                ShellConsole.this.mActiveCommand instanceof AsyncResultProgram;

                        StringBuffer sb = new StringBuffer();
                        if (!ShellConsole.this.mCancelled) {
                            ShellConsole.this.mSbIn.append((char)r);
                            if (!ShellConsole.this.mStarted) {
                                ShellConsole.this.mStarted =
                                        isCommandStarted(ShellConsole.this.mSbIn);
                                if (ShellConsole.this.mStarted) {
                                    sb = new StringBuffer(ShellConsole.this.mSbIn.toString());
                                    if (async) {
                                        synchronized (ShellConsole.this.mPartialSync) {
                                            ((AsyncResultProgram)ShellConsole.
                                                    this.mActiveCommand).
                                                        onRequestStartParsePartialResult();
                                        }
                                    }
                                } else {
                                    sb.append(ShellConsole.this.mSbIn.toString());
                                }
                            } else {
                                sb.append((char)r);
                            }

                            //Notify asynchronous partial data
                            if (ShellConsole.this.mStarted && async) {
                                AsyncResultProgram program =
                                        ((AsyncResultProgram)ShellConsole.this.mActiveCommand);
                                String partial = sb.toString();
                                program.onRequestParsePartialResult(partial);
                                ShellConsole.this.toStdIn(partial);

                                // Reset the temp buffer
                                sb = new StringBuffer();
                            }
                        }

                        if (!async) {
                            ShellConsole.this.toStdIn(sb.toString());
                        }

                        //Has more data? Read with available as more as exists
                        //or maximum loop count is rebased
                        int count = 0;
                        while (in.available() > 0 && count < 10) {
                            count++;
                            int available = Math.min(in.available(),
                                                        ShellConsole.this.mBufferSize);
                            byte[] data = new byte[available];
                            read = in.read(data);

                            // Type of command
                            async =
                                    ShellConsole.this.mActiveCommand != null &&
                                    ShellConsole.this.mActiveCommand instanceof AsyncResultProgram;

                            // Exit if active command is cancelled
                            if (ShellConsole.this.mCancelled) continue;

                            final String s = new String(data, 0, read);
                            ShellConsole.this.mSbIn.append(s);
                            if (!ShellConsole.this.mStarted) {
                                ShellConsole.this.mStarted =
                                        isCommandStarted(ShellConsole.this.mSbIn);
                                if (ShellConsole.this.mStarted) {
                                    sb = new StringBuffer(ShellConsole.this.mSbIn.toString());
                                    if (async) {
                                        synchronized (ShellConsole.this.mPartialSync) {
                                            AsyncResultProgram p =
                                                    ((AsyncResultProgram)ShellConsole.
                                                                        this.mActiveCommand);
                                            if (p != null) {
                                                p.onRequestStartParsePartialResult();
                                            }
                                        }
                                    }
                                } else {
                                    sb.append(ShellConsole.this.mSbIn.toString());
                                }
                            } else {
                                sb.append(s);
                            }

                            //Check if the command has finished (and extract the control)
                            boolean finished = isCommandFinished(ShellConsole.this.mSbIn, sb);

                            //Notify asynchronous partial data
                            if (async) {
                                AsyncResultProgram program =
                                        ((AsyncResultProgram)ShellConsole.this.mActiveCommand);
                                String partial = sb.toString();
                                if (program != null) {
                                    program.onRequestParsePartialResult(partial);
                                }
                                ShellConsole.this.toStdIn(partial);

                                // Reset the temp buffer
                                sb = new StringBuffer();
                            }

                            if (finished) {
                                if (!async) {
                                    ShellConsole.this.toStdIn(s);
                                }

                                //Notify the end
                                notifyProcessFinished();
                                break;
                            }
                            if (!async && !finished) {
                                ShellConsole.this.toStdIn(s);
                            }

                            //Wait for buffer to be filled
                            try {
                                Thread.sleep(50L);
                            } catch (Throwable ex) {
                                /**NON BLOCK**/
                            }
                        }

                        //Asynchronous programs can cause a lot of output, control buffers
                        //for a low memory footprint
                        if (async) {
                            trimBuffer(ShellConsole.this.mSbIn);
                            trimBuffer(ShellConsole.this.mSbErr);
                        }

                        //Check if process has exited
                        checkIfProcessExits();
                    }
                } catch (Exception ioEx) {
                    notifyProcessExit(ioEx);
                }
            }
        });
        t.setName(String.format("%s", "stdin")); //$NON-NLS-1$//$NON-NLS-2$
        t.start();
        return t;
    }

    /**
     * Method that echoes the stdin
     *
     * @param stdin The buffer of the stdin
     * @hide
     */
    void toStdIn(String stdin) {
        //Audit (if not cancelled)
        if (!this.mCancelled && isTrace() && stdin.length() > 0) {
            Log.v(TAG,
                    String.format(
                            "stdin: %s", stdin)); //$NON-NLS-1$
        }
    }

    /**
     * Method that creates the standard error thread for read program response.
     *
     * @param err The standard error buffer
     * @return Thread The standard error thread
     */
    private Thread createStdErrThread(final InputStream err) {
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                int read = 0;

                try {
                    while (ShellConsole.this.mActive) {
                        //Read only one byte with active wait
                        int r = err.read();
                        if (r == -1) {
                            break;
                        }

                        // Type of command
                        boolean async =
                                ShellConsole.this.mActiveCommand != null &&
                                ShellConsole.this.mActiveCommand instanceof AsyncResultProgram;

                        StringBuffer sb = new StringBuffer();
                        if (!ShellConsole.this.mCancelled) {
                            ShellConsole.this.mSbErr.append((char)r);
                            sb.append((char)r);

                            //Notify asynchronous partial data
                            if (ShellConsole.this.mStarted && async) {
                                AsyncResultProgram program =
                                        ((AsyncResultProgram)ShellConsole.this.mActiveCommand);
                                if (program != null) {
                                    program.parsePartialErrResult(new String(new char[]{(char)r}));
                                }
                            }

                            toStdErr(sb.toString());
                        }

                        //Has more data? Read with available as more as exists
                        //or maximum loop count is rebased
                        int count = 0;
                        while (err.available() > 0 && count < 10) {
                            count++;
                            int available = Math.min(err.available(),
                                                        ShellConsole.this.mBufferSize);
                            byte[] data = new byte[available];
                            read = err.read(data);

                            // Type of command
                            async =
                                ShellConsole.this.mActiveCommand != null &&
                                ShellConsole.this.mActiveCommand instanceof AsyncResultProgram;

                            // Add to stderr
                            String s = new String(data, 0, read);
                            ShellConsole.this.mSbErr.append(s);
                            sb.append(s);

                            //Notify asynchronous partial data
                            if (async) {
                                AsyncResultProgram program =
                                        ((AsyncResultProgram)ShellConsole.this.mActiveCommand);
                                if (program != null) {
                                    program.parsePartialErrResult(s);
                                }
                            }
                            toStdErr(s);

                            //Wait for buffer to be filled
                            try {
                                Thread.sleep(50L);
                            } catch (Throwable ex) {
                                /**NON BLOCK**/
                            }
                        }

                        //Asynchronous programs can cause a lot of output, control buffers
                        //for a low memory footprint
                        if (ShellConsole.this.mActiveCommand != null &&
                                ShellConsole.this.mActiveCommand instanceof AsyncResultProgram) {
                            trimBuffer(ShellConsole.this.mSbIn);
                            trimBuffer(ShellConsole.this.mSbErr);
                        }
                    }
                } catch (Exception ioEx) {
                    notifyProcessExit(ioEx);
                }
            }
        });
        t.setName(String.format("%s", "stderr")); //$NON-NLS-1$//$NON-NLS-2$
        t.start();
        return t;
    }

    /**
     * Method that echoes the stderr
     *
     * @param stdin The buffer of the stderr
     * @hide
     */
    void toStdErr(String stderr) {
        //Audit (if not cancelled)
        if (!this.mCancelled && isTrace()) {
            Log.v(TAG,
                    String.format(
                            "stderr: %s", stderr)); //$NON-NLS-1$
        }
    }

    /**
     * Method that checks the console status and restart the console
     * if this is unusable.
     *
     * @throws ConsoleAllocException If the console can't be reallocated
     */
    private void checkConsole() throws ConsoleAllocException {
        try {
            //Test write something to the buffer
            this.mOut.write(FileHelper.NEWLINE.getBytes());
            this.mOut.write(FileHelper.NEWLINE.getBytes());
        } catch (IOException ioex) {
            //Something is wrong with the buffers. Reallocate console.
            Log.w(TAG,
                "Something is wrong with the console buffers. Reallocate console.", //$NON-NLS-1$
                ioex);

            //Reallocate the damage console
            realloc();
        }
    }

    /**
     * Method that verifies if the process had exited.
     * @hide
     */
    void checkIfProcessExits() {
        try {
            if (this.mProc != null) {
                synchronized (ShellConsole.this.mSync) {
                    this.mProc.exitValue();
                }
                this.mActive = false; //Exited
            }
        } catch (IllegalThreadStateException itsEx) {
            //Not exited
        }
    }

    /**
     * Method that notifies the ending of the process.
     *
     * @param ex The exception, only if the process exit with a exception.
     * Otherwise null
     * @hide
     */
    void notifyProcessExit(Exception ex) {
        synchronized (ShellConsole.this.mSync) {
            if (this.mActive) {
                this.mSync.notify();
                this.mActive = false;
                this.mFinished = true;
                if (ex != null) {
                    Log.w(TAG, "Exits with exception", ex); //$NON-NLS-1$
                }
            }
        }
    }

    /**
     * Method that notifies the ending of the command execution.
     * @hide
     */
    void notifyProcessFinished() {
        synchronized (ShellConsole.this.mSync) {
            if (this.mActive) {
                this.mSync.notify();
                this.mFinished = true;
            }
        }
    }

    /**
     * Method that returns if the command has started by checking the
     * standard input buffer. This method also removes the control start command
     * from the buffer, if it's present, leaving in the buffer the new data bytes.
     *
     * @param stdin The standard in buffer
     * @return boolean If the command has started
     * @hide
     */
    boolean isCommandStarted(StringBuffer stdin) {
        if (stdin == null) return false;
        Pattern pattern = Pattern.compile(this.mStartControlPattern);
        Matcher matcher = pattern.matcher(stdin.toString());
        if (matcher.find()) {
            stdin.replace(0, matcher.end(), ""); //$NON-NLS-1$
            return true;
        }
        return false;
    }

    /**
     * Method that returns if the command has finished by checking the
     * standard input buffer.
     *
     * @param stdin The standard in buffer
     * @return boolean If the command has finished
     * @hide
     */
    boolean isCommandFinished(StringBuffer stdin, StringBuffer partial) {
        Pattern pattern = Pattern.compile(this.mEndControlPattern);
        if (stdin == null) return false;
        Matcher matcher = pattern.matcher(stdin.toString());
        boolean ret = matcher.find();
        // Remove partial
        if (ret && partial != null) {
            matcher = pattern.matcher(partial.toString());
            if (matcher.find()) {
                partial.replace(matcher.start(), matcher.end(), ""); //$NON-NLS-1$
            }
        }
        return ret;
    }

    /**
     * Method that returns the exit code of the last executed command.
     *
     * @param stdin The standard in buffer
     * @return int The exit code of the last executed command
     */
    private int getExitCode(StringBuffer stdin) {
        // If process was cancelled, don't expect a exit code.
        // Returns always 143 code
        if (this.mCancelled) {
            return 143;
        }

        // Parse the stdin seeking exit code pattern
        String txt = stdin.toString();
        Pattern pattern = Pattern.compile(this.mEndControlPattern);
        Matcher matcher = pattern.matcher(txt);
        if (matcher.find()) {
            this.mSbIn = new StringBuffer(txt.substring(0, matcher.start()));
            String exitTxt = matcher.group();
            return Integer.parseInt(
                    exitTxt.substring(
                            exitTxt.indexOf("#/") + 2,  //$NON-NLS-1$
                            exitTxt.indexOf("/#", 2))); //$NON-NLS-1$
        }
        return 255;
    }

    /**
     * Method that trim a buffer, let in the buffer some
     * text to ensure that the exit code is in there.
     *
     * @param sb The buffer to trim
     * @hide
     */
    @SuppressWarnings("static-method") void trimBuffer(StringBuffer sb) {
        final int bufferSize = 200;
        if (sb.length() > bufferSize) {
            sb.delete(0, sb.length() - bufferSize);
        }
    }

    /**
     * Method that kill the current command.
     *
     * @return boolean If the program was killed
     * @hide
     */
    private boolean killCurrentCommand() {
        synchronized (this.mSync) {
            //Is synchronous program? Otherwise it can't be cancelled
            if (!(this.mActiveCommand instanceof AsyncResultProgram)) {
                return false;
            }
            // Check background console
            try {
                FileManagerApplication.getBackgroundConsole();
            } catch (Exception e) {
                Log.w(TAG, "There is not background console. Not allowed.", e); //$NON-NLS-1$
                return false;
            }

            final AsyncResultProgram program = (AsyncResultProgram)this.mActiveCommand;
            if (program.getCommand() != null) {
                try {
                    if (program.isCancellable()) {
                        //Get the PID in background
                        Integer pid =
                                CommandHelper.getProcessId(
                                        null,
                                        this.mShell.getPid(),
                                        program.getCommand(),
                                        FileManagerApplication.getBackgroundConsole());
                        if (pid != null) {
                            CommandHelper.sendSignal(
                                    null,
                                    pid.intValue(),
                                    FileManagerApplication.getBackgroundConsole());
                            try {
                                //Wait for process kill
                                Thread.sleep(100L);
                            } catch (Throwable ex) {
                                /**NON BLOCK**/
                            }
                            this.mCancelled = true;
                            notifyProcessFinished();
                            this.mSync.notify();
                            return this.mCancelled;
                        }
                    }
                } catch (Throwable ex) {
                    Log.w(TAG,
                            String.format("Unable to kill current program: %s", //$NON-NLS-1$
                                    program.getCommand()), ex);
                }
            }
        }
        return false;
    }

    /**
     * Method that send a signal to the current command.
     *
     * @param SIGNAL The signal to send
     * @return boolean If the signal was sent
     * @hide
     */
    private boolean sendSignalToCurrentCommand(SIGNAL signal) {
        synchronized (this.mSync) {
            //Is synchronous program? Otherwise it can't be cancelled
            if (!(this.mActiveCommand instanceof AsyncResultProgram)) {
                return false;
            }
            // Check background console
            try {
                FileManagerApplication.getBackgroundConsole();
            } catch (Exception e) {
                Log.w(TAG, "There is not background console. Not allowed.", e); //$NON-NLS-1$
                return false;
            }

            final AsyncResultProgram program = (AsyncResultProgram)this.mActiveCommand;
            if (program.getCommand() != null) {
                try {
                    if (program.isCancellable()) {
                        try {
                            //Get the PID in background
                            Integer pid =
                                    CommandHelper.getProcessId(
                                            null,
                                            this.mShell.getPid(),
                                            program.getCommand(),
                                            FileManagerApplication.getBackgroundConsole());
                            if (pid != null) {
                                CommandHelper.sendSignal(
                                        null,
                                        pid.intValue(),
                                        signal,
                                        FileManagerApplication.getBackgroundConsole());
                                try {
                                    //Wait for process kill
                                    Thread.sleep(100L);
                                } catch (Throwable ex) {
                                    /**NON BLOCK**/
                                }
                                return true;
                            }
                        } finally {
                            // It's finished
                            this.mCancelled = true;
                            notifyProcessFinished();
                            this.mSync.notify();
                        }
                    }
                } catch (Throwable ex) {
                    Log.w(TAG,
                        String.format("Unable to send signal to current program: %s", //$NON-NLS-1$
                                program.getCommand()), ex);
                }
            }
        }
        return false;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean onEnd() {
        //Kill the current command on end request
        return killCurrentCommand();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean onSendSignal(SIGNAL signal) {
        //Send a signal to the current command on end request
        return sendSignalToCurrentCommand(signal);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean onCancel() {
        //Kill the current command on cancel request
        return killCurrentCommand();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean onRequestWrite(
            byte[] data, int offset, int byteCount) throws ExecutionException {
        try {
            // Method that write to the stdin the data requested by the program
            if (this.mOut != null) {
                this.mOut.write(data, offset, byteCount);
                this.mOut.flush();
                Thread.yield();
                return true;
            }
        } catch (Exception ex) {
            String msg = String.format("Unable to write data to program: %s", //$NON-NLS-1$
                                                this.mActiveCommand.getCommand());
            Log.e(TAG, msg, ex);
            throw new ExecutionException(msg, ex);
        }
        return false;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public OutputStream getOutputStream() {
        return this.mOut;
    }

}