This file is indexed.

/usr/lib/python3/dist-packages/asyncssh/process.py is in python3-asyncssh 1.11.1-1.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

   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
# Copyright (c) 2016-2017 by Ron Frederick <ronf@timeheart.net>.else:
# All rights reserved.
#
# This program and the accompanying materials are made available under
# the terms of the Eclipse Public License v1.0 which accompanies this
# distribution and is available at:
#
#     http://www.eclipse.org/legal/epl-v10.html
#
# Contributors:
#     Ron Frederick - initial implementation, API, and documentation

"""SSH process handlers"""

import asyncio
from asyncio.subprocess import DEVNULL, PIPE, STDOUT
from collections import OrderedDict
import io
import os
import socket
import stat

from .constants import DEFAULT_LANG, DISC_PROTOCOL_ERROR, EXTENDED_DATA_STDERR
from .misc import DisconnectError, Error, Record
from .stream import SSHClientStreamSession, SSHServerStreamSession
from .stream import SSHReader, SSHWriter


def _is_regular_file(file):
    """Return if argument is a regular file or file-like object"""

    try:
        return stat.S_ISREG(os.fstat(file.fileno()).st_mode)
    except OSError:
        return True


class _UnicodeReader:
    """Handle buffering partial Unicode data"""

    def __init__(self, encoding, textmode=False):
        self._encoding = encoding
        self._textmode = textmode
        self._partial = b''

    def decode(self, data):
        """Decode Unicode bytes when reading from binary sources"""

        if self._encoding and not self._textmode:
            data = self._partial + data
            self._partial = b''

            try:
                data = data.decode(self._encoding)
            except UnicodeDecodeError as exc:
                if exc.start > 0:
                    # Avoid pylint false positive
                    # pylint: disable=invalid-slice-index
                    self._partial = data[exc.start:]
                    data = data[:exc.start].decode(self._encoding)
                elif exc.reason == 'unexpected end of data':
                    self._partial = data
                    data = ''
                else:
                    self.close()
                    raise DisconnectError(DISC_PROTOCOL_ERROR,
                                          'Unicode decode error')

        return data

    def check_partial(self):
        """Check if there's partial Unicode data left at EOF"""

        if self._partial:
            self.close()
            raise DisconnectError(DISC_PROTOCOL_ERROR, 'Unicode decode error')

    def close(self):
        """Perform necessary cleanup on error (provided by derived classes)"""


class _UnicodeWriter:
    """Handle encoding Unicode data before writing it"""

    def __init__(self, encoding, textmode=False):
        self._encoding = encoding
        self._textmode = textmode

    def encode(self, data):
        """Encode Unicode bytes when writing to binary targets"""

        if self._encoding and not self._textmode:
            data = data.encode(self._encoding)

        return data


class _FileReader(_UnicodeReader):
    """Forward data from a file"""

    def __init__(self, process, file, bufsize, datatype, encoding):
        super().__init__(encoding, hasattr(file, 'encoding'))

        self._process = process
        self._file = file
        self._bufsize = bufsize
        self._datatype = datatype
        self._paused = False

    def feed(self):
        """Feed file data"""

        while not self._paused:
            data = self._file.read(self._bufsize)

            if data:
                self._process.feed_data(self.decode(data), self._datatype)
            else:
                self.check_partial()
                self._process.feed_eof(self._datatype)
                break

    def pause_reading(self):
        """Pause reading from the file"""

        self._paused = True

    def resume_reading(self):
        """Resume reading from the file"""

        self._paused = False
        self.feed()

    def close(self):
        """Stop forwarding data from the file"""

        self._file.close()


class _FileWriter(_UnicodeWriter):
    """Forward data to a file"""

    def __init__(self, file, encoding):
        super().__init__(encoding, hasattr(file, 'encoding'))

        self._file = file

    def write(self, data):
        """Write data to the file"""

        self._file.write(self.encode(data))

    def write_eof(self):
        """Close output file when end of file is received"""

        self.close()

    def close(self):
        """Stop forwarding data to the file"""

        self._file.close()


class _PipeReader(_UnicodeReader, asyncio.Protocol):
    """Forward data from a pipe"""

    def __init__(self, process, datatype, encoding):
        super().__init__(encoding)

        self._process = process
        self._datatype = datatype
        self._transport = None

    def connection_made(self, transport):
        """Handle a newly opened pipe"""

        self._transport = transport

    def data_received(self, data):
        """Forward data from the pipe"""

        self._process.feed_data(self.decode(data), self._datatype)

    def eof_received(self):
        """Forward EOF from the pipe"""

        self.check_partial()
        self._process.feed_eof(self._datatype)

    def pause_reading(self):
        """Pause reading from the pipe"""

        self._transport.pause_reading()

    def resume_reading(self):
        """Resume reading from the pipe"""

        self._transport.resume_reading()

    def close(self):
        """Stop forwarding data from the pipe"""

        self._transport.close()


class _PipeWriter(_UnicodeWriter, asyncio.BaseProtocol):
    """Forward data to a pipe"""

    def __init__(self, process, datatype, encoding):
        super().__init__(encoding)

        self._process = process
        self._datatype = datatype
        self._transport = None

    def connection_made(self, transport):
        """Handle a newly opened pipe"""

        self._transport = transport

    def pause_writing(self):
        """Pause writing to the pipe"""

        self._process.pause_feeding(self._datatype)

    def resume_writing(self):
        """Resume writing to the pipe"""

        self._process.resume_feeding(self._datatype)

    def write(self, data):
        """Write data to the pipe"""

        self._transport.write(self.encode(data))

    def write_eof(self):
        """Write EOF to the pipe"""

        self._transport.write_eof()

    def close(self):
        """Stop forwarding data to the pipe"""

        self._transport.close()


class _ProcessReader:
    """Forward data from another SSH process"""

    def __init__(self, process, datatype):
        self._process = process
        self._datatype = datatype

    def pause_reading(self):
        """Pause reading from the other channel"""

        self._process.pause_feeding(self._datatype)

    def resume_reading(self):
        """Resume reading from the other channel"""

        self._process.resume_feeding(self._datatype)

    def close(self):
        """Stop forwarding data from the other channel"""

        self._process.clear_writer(self._datatype)


class _ProcessWriter:
    """Forward data to another SSH process"""

    def __init__(self, process, datatype):
        self._process = process
        self._datatype = datatype

    def write(self, data):
        """Write data to the other channel"""

        self._process.feed_data(data, self._datatype)

    def write_eof(self):
        """Write EOF to the other channel"""

        self._process.feed_eof(self._datatype)

    def close(self):
        """Stop forwarding data to the other channel"""

        self._process.clear_reader(self._datatype)


class _DevNullWriter:
    """Discard data"""

    def write(self, data):
        """Discard data being written"""

    def write_eof(self):
        """Ignore end of file"""

    def close(self):
        """Ignore close"""


class _StdoutWriter:
    """Forward data to an SSH process' stdout instead of stderr"""

    def __init__(self, process):
        self._process = process

    def write(self, data):
        """Pretend data was received on stdout"""

        self._process.data_received(data, None)

    def write_eof(self):
        """Ignore end of file"""

    def close(self):
        """Ignore close"""


class ProcessError(Error):
    """SSH Process error

       This exception is raised when an :class:`SSHClientProcess` exits
       with a non-zero exit status and error checking is enabled. In
       addition to the usual error code, reason, and language, it
       contains the following fields:

         ============ ======================================= ================
         Field        Description                             Type
         ============ ======================================= ================
         env          The environment the client requested    str or ``None``
                      to be set for the process
         command      The command the client requested the    str or ``None``
                      process to execute (if any)
         subsystem    The subsystem the client requested the  str or ``None``
                      process to open (if any)
         exit_status  The exit status returned, or -1 if an   int
                      exit signal is sent
         exit_signal  The exit signal sent (if any) in the    tuple or ``None``
                      form of a tuple containing the signal
                      name, a bool for whether a core dump
                      occurred, a message associated with the
                      signal, and the language the message
                      was in
         stdout       The output sent by the process to       str or bytes
                      stdout (if not redirected)
         stderr       The output sent by the process to       str or bytes
                      stderr (if not redirected)
         ============ ======================================= ================

    """

    def __init__(self, env, command, subsystem, exit_status,
                 exit_signal, stdout, stderr):
        self.env = env
        self.command = command
        self.subsystem = subsystem
        self.exit_status = exit_status
        self.exit_signal = exit_signal
        self.stdout = stdout
        self.stderr = stderr

        if exit_signal:
            signal, core_dumped, msg, lang = exit_signal
            reason = 'Process exited with signal %s%s%s' % \
                (signal, ': ' + msg if msg else '',
                 ' (core dumped)' if core_dumped else '')
        else:
            reason = 'Process exited with non-zero exit status %s' % \
                exit_status
            lang = DEFAULT_LANG

        super().__init__('Process', exit_status, reason, lang)


class SSHCompletedProcess(Record):
    """Results from running an SSH process

       This object is returned by the :meth:`run <SSHClientConnection.run>`
       method on :class:`SSHClientConnection` when the requested command
       has finished running. It contains the following fields:

         ============ ======================================= ================
         Field        Description                             Type
         ============ ======================================= ================
         env          The environment the client requested    str or ``None``
                      to be set for the process
         command      The command the client requested the    str or ``None``
                      process to execute (if any)
         subsystem    The subsystem the client requested the  str or ``None``
                      process to open (if any)
         exit_status  The exit status returned, or -1 if an   int
                      exit signal is sent
         exit_signal  The exit signal sent (if any) in the    tuple or ``None``
                      form of a tuple containing the signal
                      name, a bool for whether a core dump
                      occurred, a message associated with the
                      signal, and the language the message
                      was in
         stdout       The output sent by the process to       str or bytes
                      stdout (if not redirected)
         stderr       The output sent by the process to       str or bytes
                      stderr (if not redirected)
         ============ ======================================= ================

    """

    __slots__ = OrderedDict((('env', None), ('command', None),
                             ('subsystem', None), ('exit_status', None),
                             ('exit_signal', None), ('stdout', None),
                             ('stderr', None)))


class SSHProcess:
    """SSH process handler"""

    # Pylint doesn't know that all SSHProcess instances will always be
    # subclasses of SSHStreamSession.
    # pylint: disable=no-member

    def __init__(self):
        self._readers = {}
        self._send_eof = {}

        self._writers = {}
        self._paused_write_streams = set()

        self._stdin = None
        self._stdout = None
        self._stderr = None

    def __enter__(self):
        """Allow SSHProcess to be used as a context manager"""

        return self

    def __exit__(self, *exc_info):
        """Automatically close the channel when exiting the context"""

        self.close()

    @asyncio.coroutine
    def __aenter__(self):
        """Allow SSHProcess to be used as an async context manager"""

        return self

    @asyncio.coroutine
    def __aexit__(self, *exc_info):
        """Wait for a full channel close when exiting the async context"""

        self.close()
        yield from self._chan.wait_closed()

    @property
    def channel(self):
        """The channel associated with the process"""

        return self._chan

    @property
    def env(self):
        """The environment set by the client for the process

           This method returns the environment set by the client
           when the session was opened.

           :returns: A dictionary containing the environment variables
                     set by the client

        """

        return self._chan.get_environment()

    @property
    def command(self):
        """The command the client requested to execute, if any

           This method returns the command the client requested to
           execute when the process was started, if any. If the client
           did not request that a command be executed, this method
           will return ``None``.

           :returns: A str containing the command or ``None`` if
                     no command was specified

        """

        return self._chan.get_command()

    @property
    def subsystem(self):
        """The subsystem the client requested to open, if any

           This method returns the subsystem the client requested to
           open when the process was started, if any. If the client
           did not request that a subsystem be opened, this method will
           return ``None``.

           :returns: A str containing the subsystem name or ``None``
                     if no subsystem was specified

        """

        return self._chan.get_subsystem()

    @asyncio.coroutine
    def _create_reader(self, source, bufsize, send_eof, datatype=None):
        """Create a reader to forward data to the SSH channel"""

        def pipe_factory():
            """Return a pipe read handler"""

            return _PipeReader(self, datatype, self._encoding)

        if source == PIPE:
            reader = None
        elif source == DEVNULL:
            self._chan.write_eof()
            reader = None
        elif isinstance(source, SSHReader):
            reader_process, reader_datatype = source.get_redirect_info()
            writer = _ProcessWriter(self, datatype)
            reader_process.set_writer(writer, reader_datatype)
            reader = _ProcessReader(reader_process, reader_datatype)
        else:
            if isinstance(source, str):
                file = open(source, 'rb', buffering=bufsize)
            elif isinstance(source, int):
                file = os.fdopen(source, 'rb', buffering=bufsize)
            elif isinstance(source, socket.socket):
                file = os.fdopen(source.detach(), 'rb', buffering=bufsize)
            else:
                file = source

            if _is_regular_file(file):
                reader = _FileReader(self, file, bufsize,
                                     datatype, self._encoding)
            else:
                if hasattr(source, 'buffer'):
                    # If file was opened in text mode, remove that wrapper
                    file = source.buffer

                _, reader = \
                    yield from self._loop.connect_read_pipe(pipe_factory, file)

        self.set_reader(reader, send_eof, datatype)

        if isinstance(reader, _FileReader):
            reader.feed()
        elif isinstance(reader, _ProcessReader):
            reader_process.feed_recv_buf(reader_datatype, writer)

    @asyncio.coroutine
    def _create_writer(self, target, bufsize, send_eof, datatype=None):
        """Create a writer to forward data from the SSH channel"""

        def pipe_factory():
            """Return a pipe write handler"""

            return _PipeWriter(self, datatype, self._encoding)

        if target == DEVNULL:
            writer = _DevNullWriter()
        elif target == PIPE:
            writer = None
        elif target == STDOUT:
            writer = _StdoutWriter(self)
        elif isinstance(target, SSHWriter):
            writer_process, writer_datatype = target.get_redirect_info()
            reader = _ProcessReader(self, datatype)
            writer_process.set_reader(reader, send_eof, writer_datatype)
            writer = _ProcessWriter(writer_process, writer_datatype)
        else:
            if isinstance(target, str):
                file = open(target, 'wb', buffering=bufsize)
            elif isinstance(target, int):
                file = os.fdopen(target, 'wb', buffering=bufsize)
            elif isinstance(target, socket.socket):
                file = os.fdopen(target.detach(), 'wb', buffering=bufsize)
            else:
                file = target

            if _is_regular_file(file):
                writer = _FileWriter(file, self._encoding)
            else:
                if hasattr(target, 'buffer'):
                    # If file was opened in text mode, remove that wrapper
                    file = target.buffer

                _, writer = \
                    yield from self._loop.connect_write_pipe(pipe_factory,
                                                             file)

        self.set_writer(writer, datatype)

        if writer:
            self.feed_recv_buf(datatype, writer)

    def _should_block_drain(self, datatype):
        """Return whether output is still being written to the channel"""

        return (datatype in self._readers or
                super()._should_block_drain(datatype))

    def _should_pause_reading(self):
        """Return whether to pause reading from the channel"""

        return self._paused_write_streams or super()._should_pause_reading()

    def connection_lost(self, exc):
        """Handle a close of the SSH channel"""

        super().connection_lost(exc)

        for reader in self._readers.values():
            reader.close()

        for writer in self._writers.values():
            writer.close()

        self._readers = {}
        self._writers = {}

    def data_received(self, data, datatype):
        """Handle incoming data from the SSH channel"""

        writer = self._writers.get(datatype)

        if writer:
            writer.write(data)
        else:
            super().data_received(data, datatype)

    def eof_received(self):
        """Handle an incoming end of file from the SSH channel"""

        for writer in list(self._writers.values()):
            writer.write_eof()

        return super().eof_received()

    def pause_writing(self):
        """Pause forwarding data to the channel"""

        super().pause_writing()

        for reader in self._readers.values():
            reader.pause_reading()

    def resume_writing(self):
        """Resume forwarding data to the channel"""

        super().resume_writing()

        for reader in list(self._readers.values()):
            reader.resume_reading()

    def feed_data(self, data, datatype):
        """Feed data to the channel"""

        self._chan.write(data, datatype)

    def feed_eof(self, datatype):
        """Feed EOF to the channel"""

        if self._send_eof[datatype]:
            self._chan.write_eof()

        self._readers[datatype].close()
        self.clear_reader(datatype)

    def feed_recv_buf(self, datatype, writer):
        """Feed current receive buffer to a newly set writer"""

        for data in self._recv_buf[datatype]:
            writer.write(data)
            self._recv_buf_len -= len(data)

        self._recv_buf[datatype].clear()

        if self._eof_received:
            writer.write_eof()

        self._maybe_resume_reading()

    def pause_feeding(self, datatype):
        """Pause feeding data from the channel"""

        self._paused_write_streams.add(datatype)
        self._maybe_pause_reading()

    def resume_feeding(self, datatype):
        """Resume feeding data from the channel"""

        self._paused_write_streams.remove(datatype)
        self._maybe_resume_reading()

    def set_reader(self, reader, send_eof, datatype):
        """Set a reader used to forward data to the channel"""

        old_reader = self._readers.get(datatype)

        if old_reader:
            old_reader.close()

        if reader:
            self._readers[datatype] = reader
            self._send_eof[datatype] = send_eof

            if self._write_paused:
                reader.pause_reading()
        elif old_reader:
            self.clear_reader(datatype)

    def clear_reader(self, datatype):
        """Clear a reader forwarding data to the channel"""

        del self._readers[datatype]
        del self._send_eof[datatype]
        self._unblock_drain(datatype)

    def set_writer(self, writer, datatype):
        """Set a writer used to forward data from the channel"""

        old_writer = self._writers.get(datatype)

        if old_writer:
            old_writer.close()
            self.clear_writer(datatype)

        if writer:
            self._writers[datatype] = writer

    def clear_writer(self, datatype):
        """Clear a writer forwarding data from the channel"""

        if datatype in self._paused_write_streams:
            self.resume_feeding(datatype)

        del self._writers[datatype]

    def close(self):
        """Shut down the process"""

        self._chan.close()

    @asyncio.coroutine
    def wait_closed(self):
        """Wait for the process to finish shutting down"""

        yield from self._chan.wait_closed()


class SSHClientProcess(SSHProcess, SSHClientStreamSession):
    """SSH client process handler"""

    def __init__(self):
        SSHProcess.__init__(self)
        SSHClientStreamSession.__init__(self)

    def _collect_output(self, datatype=None):
        """Return output from the process"""

        recv_buf = self._recv_buf[datatype]

        if recv_buf and isinstance(recv_buf[-1], Exception):
            recv_buf = recv_buf[:-1]

        buf = '' if self._encoding else b''
        return buf.join(recv_buf)

    def session_started(self):
        """Start a process for this newly opened client channel"""

        self._stdin = SSHWriter(self, self._chan)
        self._stdout = SSHReader(self, self._chan)
        self._stderr = SSHReader(self, self._chan, EXTENDED_DATA_STDERR)

    @property
    def exit_status(self):
        """The exit status of the process"""

        return self._chan.get_exit_status()

    @property
    def exit_signal(self):
        """Exit signal information for the process"""

        return self._chan.get_exit_signal()

    @property
    def stdin(self):
        """The :class:`SSHWriter` to use to write to stdin of the process"""

        return self._stdin

    @property
    def stdout(self):
        """The :class:`SSHReader` to use to read from stdout of the process"""

        return self._stdout

    @property
    def stderr(self):
        """The :class:`SSHReader` to use to read from stderr of the process"""

        return self._stderr

    @asyncio.coroutine
    def redirect(self, stdin=None, stdout=None, stderr=None,
                 bufsize=io.DEFAULT_BUFFER_SIZE, send_eof=True):
        """Perform I/O redirection for the process

           This method redirects data going to or from any or all of
           standard input, standard output, and standard error for
           the process.

           The ``stdin`` argument can be any of the following:

               * An :class:`SSHReader` object
               * A file object open for read
               * An int file descriptor open for read
               * A connected socket object
               * A string containing the name of a file or device to open
               * ``DEVNULL`` to provide no input to standard input
               * ``PIPE`` to interactively write standard input

           The ``stdout`` and ``stderr`` arguments can be any of the
           following:

               * An :class:`SSHWriter` object
               * A file object open for write
               * An int file descriptor open for write
               * A connected socket object
               * A string containing the name of a file or device to open
               * ``DEVNULL`` to discard standard error output
               * ``PIPE`` to interactively read standard error output

           The ``stderr`` argument also accepts the value ``STDOUT`` to
           request that standard error output be delivered to stdout.

           File objects passed in can be associated with plain files, pipes,
           sockets, or ttys.

           The default value of ``None`` means to not change redirection
           for that stream.

           :param stdin:
               Source of data to feed to standard input
           :param stdout:
               Target to feed data from standard output to
           :param stderr:
               Target to feed data from standard error to
           :param int bufsize:
               Buffer size to use when forwarding data from a file
           :param bool send_eof:
               Whether or not to send EOF to the channel when redirection
               is complete, defaulting to ``True``. If set to ``False``,
               multiple sources can be sequentially fed to the channel.

        """

        if stdin:
            yield from self._create_reader(stdin, bufsize, send_eof)

        if stdout:
            yield from self._create_writer(stdout, bufsize, send_eof)

        if stderr:
            yield from self._create_writer(stderr, bufsize, send_eof,
                                           EXTENDED_DATA_STDERR)

    @asyncio.coroutine
    def redirect_stdin(self, source, bufsize=io.DEFAULT_BUFFER_SIZE,
                       send_eof=True):
        """Redirect standard input of the process"""

        yield from self.redirect(source, None, None, bufsize, send_eof)

    @asyncio.coroutine
    def redirect_stdout(self, target, bufsize=io.DEFAULT_BUFFER_SIZE,
                        send_eof=True):
        """Redirect standard output of the process"""

        yield from self.redirect(None, target, None, bufsize, send_eof)

    @asyncio.coroutine
    def redirect_stderr(self, target, bufsize=io.DEFAULT_BUFFER_SIZE,
                        send_eof=True):
        """Redirect standard error of the process"""

        yield from self.redirect(None, None, target, bufsize, send_eof)

    # pylint: disable=redefined-builtin
    @asyncio.coroutine
    def communicate(self, input=None):
        """Send input to and/or collect output from the process

           This method is a coroutine which optionally provides input
           to the process and then waits for the process to exit,
           returning a tuple of the data written to stdout and stderr.

           :param input:
               Input data to feed to standard input of the process.
               Data should be a str if encoding is set, or bytes if not.
           :type input: str or bytes

           :returns: A tuple of output to stdout and stderr

        """

        self._limit = None
        self._maybe_resume_reading()

        if input:
            self._chan.write(input)
            self._chan.write_eof()

        yield from self._chan.wait_closed()

        return (self._collect_output(),
                self._collect_output(EXTENDED_DATA_STDERR))
    # pylint: enable=redefined-builtin

    def change_terminal_size(self, width, height, pixwidth=0, pixheight=0):
        """Change the terminal window size for this process

           This method changes the width and height of the terminal
           associated with this process.

           :param int width:
               The width of the terminal in characters
           :param int height:
               The height of the terminal in characters
           :param int pixwidth: (optional)
               The width of the terminal in pixels
           :param int pixheight: (optional)
               The height of the terminal in pixels

           :raises: :exc:`OSError` if the SSH channel is not open

        """

        self._chan.change_terminal_size(width, height, pixwidth, pixheight)

    def send_break(self, msec):
        """Send a break to the process

           :param int msec:
               The duration of the break in milliseconds

           :raises: :exc:`OSError` if the SSH channel is not open

        """

        self._chan.send_break(msec)

    def send_signal(self, signal):
        """Send a signal to the process

           :param str signal:
               The signal to deliver

           :raises: :exc:`OSError` if the SSH channel is not open

        """

        self._chan.send_signal(signal)

    def terminate(self):
        """Terminate the process

           :raises: :exc:`OSError` if the SSH channel is not open

        """

        self._chan.terminate()

    def kill(self):
        """Forcibly kill the process

           :raises: :exc:`OSError` if the SSH channel is not open

        """

        self._chan.kill()

    @asyncio.coroutine
    def wait(self, check=False):
        """Wait for process to exit

           This method is a coroutine which waits for the process to
           exit. It returns an :class:`SSHCompletedProcess` object with
           the exit status or signal information and the output sent
           to stdout and stderr if those are redirected to pipes.

           If the check argument is set to ``True``, a non-zero exit
           status from the process with trigger the :exc:`ProcessError`
           exception to be raised.

           :param bool check:
               Whether or not to raise an error on non-zero exit status

           :returns: :class:`SSHCompletedProcess`

           :raises: :exc:`ProcessError` if check is set to ``True``
                    and the process returns a non-zero exit status

        """

        stdout_data, stderr_data = yield from self.communicate()

        if check and self.exit_status:
            raise ProcessError(self.env, self.command, self.subsystem,
                               self.exit_status, self.exit_signal,
                               stdout_data, stderr_data)
        else:
            return SSHCompletedProcess(self.env, self.command, self.subsystem,
                                       self.exit_status, self.exit_signal,
                                       stdout_data, stderr_data)


class SSHServerProcess(SSHProcess, SSHServerStreamSession):
    """SSH server process handler"""

    def __init__(self, process_factory, sftp_factory, allow_scp):
        SSHProcess.__init__(self)
        SSHServerStreamSession.__init__(self, self._start_process,
                                        sftp_factory, allow_scp)

        self._process_factory = process_factory

    def _start_process(self, stdin, stdout, stderr):
        """Start a new server process"""

        self._stdin = stdin
        self._stdout = stdout
        self._stderr = stderr

        return self._process_factory(self)

    @property
    def stdin(self):
        """The :class:`SSHReader` to use to read from stdin of the process"""

        return self._stdin

    @property
    def stdout(self):
        """The :class:`SSHWriter` to use to write to stdout of the process"""

        return self._stdout

    @property
    def stderr(self):
        """The :class:`SSHWriter` to use to write to stderr of the process"""

        return self._stderr

    @asyncio.coroutine
    def redirect(self, stdin=None, stdout=None, stderr=None,
                 bufsize=io.DEFAULT_BUFFER_SIZE, send_eof=True):
        """Perform I/O redirection for the process

           This method redirects data going to or from any or all of
           standard input, standard output, and standard error for
           the process.

           The ``stdin`` argument can be any of the following:

               * An :class:`SSHWriter` object
               * A file object open for write
               * An int file descriptor open for write
               * A connected socket object
               * A string containing the name of a file or device to open
               * ``DEVNULL`` to discard standard error output
               * ``PIPE`` to interactively read standard error output

           The ``stdout`` and ``stderr`` arguments can be any of the
           following:

               * An :class:`SSHReader` object
               * A file object open for read
               * An int file descriptor open for read
               * A connected socket object
               * A string containing the name of a file or device to open
               * ``DEVNULL`` to provide no input to standard input
               * ``PIPE`` to interactively write standard input

           File objects passed in can be associated with plain files, pipes,
           sockets, or ttys.

           The default value of ``None`` means to not change redirection
           for that stream.

           :param stdin:
               Target to feed data from standard input to
           :param stdout:
               Source of data to feed to standard output
           :param stderr:
               Source of data to feed to standard error
           :param int bufsize:
               Buffer size to use when forwarding data from a file
           :param bool send_eof:
               Whether or not to send EOF to the channel when redirection
               is complete, defaulting to ``True``. If set to ``False``,
               multiple sources can be sequentially fed to the channel.

        """

        if stdin:
            yield from self._create_writer(stdin, bufsize, send_eof)

        if stdout:
            yield from self._create_reader(stdout, bufsize, send_eof)

        if stderr:
            yield from self._create_reader(stderr, bufsize, send_eof,
                                           EXTENDED_DATA_STDERR)

    @asyncio.coroutine
    def redirect_stdin(self, target, bufsize=io.DEFAULT_BUFFER_SIZE,
                       send_eof=True):
        """Redirect standard input of the process"""

        yield from self.redirect(target, None, None, bufsize, send_eof)

    @asyncio.coroutine
    def redirect_stdout(self, source, bufsize=io.DEFAULT_BUFFER_SIZE,
                        send_eof=True):
        """Redirect standard output of the process"""

        yield from self.redirect(None, source, None, bufsize, send_eof)

    @asyncio.coroutine
    def redirect_stderr(self, source, bufsize=io.DEFAULT_BUFFER_SIZE,
                        send_eof=True):
        """Redirect standard error of the process"""

        yield from self.redirect(None, None, source, bufsize, send_eof)

    def get_environment(self):
        """Return the environment set by the client (deprecated)"""

        return self.env # pragma: no cover

    def get_command(self):
        """Return the command the client requested to execute (deprecated)"""

        return self.command # pragma: no cover

    def get_subsystem(self):
        """Return the subsystem the client requested to open (deprecated)"""

        return self.subsystem # pragma: no cover

    def get_terminal_type(self):
        """Return the terminal type set by the client for the process

           This method returns the terminal type set by the client
           when the process was started. If the client didn't request
           a pseudo-terminal, this method will return ``None``.

           :returns: A str containing the terminal type or ``None`` if
                     no pseudo-terminal was requested

        """

        return self._chan.get_terminal_type()

    def get_terminal_size(self):
        """Return the terminal size set by the client for the process

           This method returns the latest terminal size information set
           by the client. If the client didn't set any terminal size
           information, all values returned will be zero.

           :returns: A tuple of four integers containing the width and
                     height of the terminal in characters and the width
                     and height of the terminal in pixels

        """

        return self._chan.get_terminal_size()

    def get_terminal_mode(self, mode):
        """Return the requested TTY mode for this session

           This method looks up the value of a POSIX terminal mode
           set by the client when the process was started. If the client
           didn't request a pseudo-terminal or didn't set the requested
           TTY mode opcode, this method will return ``None``.

           :param int mode:
               POSIX terminal mode taken from :ref:`POSIX terminal modes
               <PTYModes>` to look up

           :returns: An int containing the value of the requested
                     POSIX terminal mode or ``None`` if the requested
                     mode was not set

        """

        return self._chan.get_terminal_mode(mode)

    def exit(self, status):
        """Send exit status and close the channel

           This method can be called to report an exit status for the
           process back to the client and close the channel.

           :param int status:
               The exit status to report to the client

        """

        self._chan.exit(status)

    def exit_with_signal(self, signal, core_dumped=False,
                         msg='', lang=DEFAULT_LANG):
        """Send exit signal and close the channel

           This method can be called to report that the process
           terminated abnormslly with a signal. A more detailed
           error message may also provided, along with an indication
           of whether or not the process dumped core. After
           reporting the signal, the channel is closed.

           :param str signal:
               The signal which caused the process to exit
           :param bool core_dumped: (optional)
               Whether or not the process dumped core
           :param str msg: (optional)
               Details about what error occurred
           :param str lang: (optional)
               The language the error message is in

        """

        return self._chan.exit_with_signal(signal, core_dumped, msg, lang)