1# Copyright 2021-2022 Google LLC 2# 3# Licensed under the Apache License, Version 2.0 (the "License"); 4# you may not use this file except in compliance with the License. 5# You may obtain a copy of the License at 6# 7# https://www.apache.org/licenses/LICENSE-2.0 8# 9# Unless required by applicable law or agreed to in writing, software 10# distributed under the License is distributed on an "AS IS" BASIS, 11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12# See the License for the specific language governing permissions and 13# limitations under the License. 14 15# ----------------------------------------------------------------------------- 16# Imports 17# ----------------------------------------------------------------------------- 18import asyncio 19import io 20import logging 21 22from .common import Transport, StreamPacketSource, StreamPacketSink 23 24# ----------------------------------------------------------------------------- 25# Logging 26# ----------------------------------------------------------------------------- 27logger = logging.getLogger(__name__) 28 29 30# ----------------------------------------------------------------------------- 31async def open_file_transport(spec): 32 ''' 33 Open a File transport (typically not for a real file, but for a PTY or other unix virtual files). 34 The parameter string is the path of the file to open 35 ''' 36 37 # Open the file 38 file = io.open(spec, 'r+b', buffering=0) 39 40 # Setup reading 41 read_transport, packet_source = await asyncio.get_running_loop().connect_read_pipe( 42 lambda: StreamPacketSource(), 43 file 44 ) 45 46 # Setup writing 47 write_transport, _ = await asyncio.get_running_loop().connect_write_pipe( 48 lambda: asyncio.BaseProtocol(), 49 file 50 ) 51 packet_sink = StreamPacketSink(write_transport) 52 53 class FileTransport(Transport): 54 async def close(self): 55 read_transport.close() 56 write_transport.close() 57 file.close() 58 59 return FileTransport(packet_source, packet_sink) 60 61