Remote shell using libssh2 with Objective-C, thread safe implementation.

Overview

NSRemoteShell

Remote shell using libssh2 with Objective-C. Thread safe implementation. Available as Swift Package.

git

libssh2 prebuilt binaries are required to build this package. Either clone with recursive submodules or update after clone. Bitcode is available.

git submodule update --init --recursive --remote

See following options to learn more.

Usage

In our design, all operation is blocked, and is recommended to call in background thread.

NSRemoteShell()
    .setupConnectionHost(host)
    .setupConnectionPort(NSNumber(value: port))
    .requestConnectAndWait()
    .authenticate(with: username, andPassword: password)
    .executeRemote(
        command,
        withExecTimeout: .init(value: 0)
    ) {
        createOutput($0) 
    } withContinuationHandler: {
        commandStatus != .terminating
    }

To connect, call setup function to set host and port. Class is designed with Swift function-like syntax chain.

- (instancetype)setupConnectionHost:(nonnull NSString *)targetHost;
- (instancetype)setupConnectionPort:(nonnull NSNumber *)targetPort;
- (instancetype)setupConnectionTimeout:(nonnull NSNumber *)timeout;

- (instancetype)requestConnectAndWait;
- (instancetype)requestDisconnectAndWait;

There is two authenticate method provided. Authenticate is required after connect.

Do not change username when authenticateing the same session.

- (instancetype)authenticateWith:(nonnull NSString *)username
                     andPassword:(nonnull NSString *)password;
- (instancetype)authenticateWith:(NSString *)username
                            andPublicKey:(nullable NSString *)publicKey
                            andPrivateKey:(NSString *)privateKey
                             andPassword:(nullable NSString *)password;

For various session property, see property list.

@property(nonatomic, readwrite, nullable, strong) NSString *resolvedRemoteIpAddress;
@property(nonatomic, readwrite, nullable, strong) NSString *remoteBanner;
@property(nonatomic, readwrite, nullable, strong) NSString *remoteFingerPrint;

@property(nonatomic, readwrite, getter=isConnected) BOOL connected;
@property(nonatomic, readwrite, getter=isAuthenicated) BOOL authenticated;

Request either command channel or shell channel with designated API, and do not access unexposed values. It may break the ARC or crash the app.

- (instancetype)executeRemote:(NSString*)command
             withExecTimeout:(NSNumber*)timeoutSecond
                  withOutput:(nullable void (^)(NSString*))responseDataBlock
     withContinuationHandler:(nullable BOOL (^)(void))continuationBlock;

- (instancetype)openShellWithTerminal:(nullable NSString*)terminalType
                    withTermianlSize:(nullable CGSize (^)(void))requestTermianlSize
                       withWriteData:(nullable NSString* (^)(void))requestWriteData
                          withOutput:(void (^)(NSString * _Nonnull))responseDataBlock
             withContinuationHandler:(BOOL (^)(void))continuationBlock;

On execution, once your status is changed, to apply your status quickly, call explicitRequestStatusPickup(). Take an example, when shouldTerminate changes, call this function to terminate this channel immediately or wait for the event loop to pick up on a guaranteed schedule.

- (void)explicitRequestStatusPickup;

Thread Safe

We implemented thread safe by using NSEventLoop to serialize single NSRemoteShell instance. Multiple NSRemoteShell object will be executed in parallel. Channel operations will be executed in serial for each NSRemoteShell.

@interface TSEventLoop : NSObject

+(id)sharedLoop;

- (void)explicitRequestHandle;
- (void)delegatingRemoteWith:(NSRemoteShell*)object;

@end

The event loop will guarantee status pickup is thread safe, called several times per second. To improve the performance and user experience, we use a dispatch source of your session's socket to trigger the event loop handler when you have at least one channel opened when data arrived. Check following code to see how it works.

- (void)uncheckedConcurrencyDispatchSourceMakeDecision

All event loop will call a NSRemoteShell objects' handleRequestsIfNeeded method, we deal with control blocks first, and then iterate over all channel to see if data available.

for (dispatch_block_t invocation in self.requestInvokations) {
    if (invocation) { invocation(); }
}
[self.requestInvokations removeAllObjects];
for (NSRemoteChannel *channelObject in [self.associatedChannel copy]) {
    [channelObject insanityUncheckedEventLoop];
}

ARC will take place to disconnect if a shell object is no longer holds. You can close the session manually or let ARC handle it.

- (void)dealloc {
    NSLog(@"shell object at %p deallocating", self);
    [self uncheckedConcurrencyDisconnect];
}

LICENSE

NSRemoteShell is licensed under [MIT License - Lakr's Edition].

Permissions
- Commercial use
- Modification
- Distribution
- Private use

Limitations
- NO Liability
- NO Warranty

Conditions
- NO Conditions

Copyright © 2022 Lakr Aream. All Rights Reserved.

You might also like...
Modern thread-safe and type-safe key-value observing for Swift and Objective-C

Now Archived and Forked PMKVObserver will not be maintained in this repository going forward. Please use, create issues on, and make PRs to the fork o

MemoryCache - type-safe, thread-safe memory cache class in Swift

MemoryCache is a memory cache class in swift. The MemoryCache class incorporates LRU policies, which ensure that a cache doesn’t

A Protocol-Oriented NotificationCenter which is type safe, thread safe and with memory safety
A Protocol-Oriented NotificationCenter which is type safe, thread safe and with memory safety

A Protocol-Oriented NotificationCenter which is type safe, thread safe and with memory safety. Type Safe No more userInfo dictionary and Downcasting,

JSPatch bridge Objective-C and Javascript using the Objective-C runtime. You can call any Objective-C class and method in JavaScript by just including a small engine. JSPatch is generally used to hotfix iOS App.

JSPatch 中文介绍 | 文档 | JSPatch平台 请大家不要自行接入 JSPatch,统一接入 JSPatch 平台,让热修复在一个安全和可控的环境下使用。原因详见 这里 JSPatch bridges Objective-C and JavaScript using the Object

A minimalistic, thread safe, non-boilerplate and super easy to use version of Active Record on Core Data.
A minimalistic, thread safe, non-boilerplate and super easy to use version of Active Record on Core Data.

Skopelos A minimalistic, thread-safe, non-boilerplate and super easy to use version of Active Record on Core Data. Simply all you need for doing Core

A thread safe throttle written in Swift

SwiftThrottle - A thread safe throttle written in Swift licensed under MIT. Introduction This throttle is intended to prevent the program from crashing

Track is a thread safe cache write by Swift. Composed of DiskCache and MemoryCache which support LRU.
Track is a thread safe cache write by Swift. Composed of DiskCache and MemoryCache which support LRU.

Track is a thread safe cache write by Swift. Composed of DiskCache and MemoryCache which support LRU. Features Thread safe: Implement by dispatch_sema

Type-safe thread-local storage in Swift
Type-safe thread-local storage in Swift

Threadly is a Swift µframework that allows for type-safe thread-local storage. What is Thread-Local Storage? Thread-local storage (TLS) lets you defin

A thread safe, performant, feature rich image fetcher
A thread safe, performant, feature rich image fetcher

PINRemoteImage Fast, non-deadlocking parallel image downloader and cache for iOS PINRemoteImageManager is an image downloading, processing and caching

A declarative, thread safe, and reentrant way to define code that should only execute at most once over the lifetime of an object.

SwiftRunOnce SwiftRunOnce allows a developer to mark a block of logic as "one-time" code – code that will execute at most once over the lifetime of an

Thread -safe access to a lazily retrieved value, with optional validity checking

SerialUpdatingValue Thread-safe access to a lazily retrieved value, with optional validity checking Motivation Swift's Structured Concurrency provides

OTAtomics - Multi-platform Swift thread-safe atomics library

OTAtomics Multi-platform Swift thread-safe atomics library. The library has full

A barebone, thread-safe Redux-like container for Swift.

SwiftTinyRedux SwiftTinyRedux is a barebone, thread-safe Redux-like container for Swift. It features a minimal API and supports composable reducers. I

An elegant, fast, thread-safe, multipurpose key-value storage, compatible with all Apple platforms.
An elegant, fast, thread-safe, multipurpose key-value storage, compatible with all Apple platforms.

KeyValueStorage An elegant, fast, thread-safe, multipurpose key-value storage, compatible with all Apple platforms. Supported Platforms iOS macOS watc

Secure Remote Password SRP-6a implementation by swift

Thinbus-SRP Example To run the example project, clone the repo, and run pod install from the Example directory first. Requirements Installation Thinbu

 SwiftShell - A Swift framework for shell scripting.
SwiftShell - A Swift framework for shell scripting.

Run shell commands | Parse command line arguments | Handle files and directories Swift 5.1 - 5.3 | Swift 4 | Swift 3 | Swift 2 SwiftShell A library fo

Shell scripting in Swift

Shwift Shell-scripting in Swift DISCLAIMER: Shwift depends on Swift's incoming concurrency features. As such, it requires a recent Swift toolchain, an

Created a Tic Tac Toe game with pure swift that runs within zsh shell.
Created a Tic Tac Toe game with pure swift that runs within zsh shell.

Swift TicTacToe Created a Tic Tac Toe game with pure swift that runs within zsh shell. The computer is actually really hard to beat and it ends up bei

A Swift wrapper for system shell over posix_spawn with search path and env support.

AuxiliaryExecute A Swift wrapper for system shell over posix_spawn with search path and env support. Usage import AuxiliaryExecute AuxiliaryExecute.l

Owner
Lakr Aream
🥺
Lakr Aream
Demonstration of using Tasks and TaskGroup to thread a calculation.

TasksTest Demonstration of using Tasks and TaskGroup to thread a calculation. The calculation takes place in a separate Swift class that can be reused

null 0 Dec 27, 2021
SwiftyTimer allows you to instantly schedule delays and repeating timers using convenient closure syntax. It's time to get rid of Objective-C cruft.

SwiftyTimer Modern Swifty API for NSTimer SwiftyTimer allows you to instantly schedule delays and repeating timers using convenient closure syntax. It

Radek Pietruszewski 1.2k Sep 14, 2022
Type-safe networking with Swift Concurrency

AsyncRequest AsyncRequest is a type-safe framework for building a suite of requests to communicate with an API, built on top of Swift Concurrency. Ins

Light Year Software, LLC 1 Feb 9, 2022
AsyncDispatcher is a lightweight Dispatcher implementation of Flux pattern.

Simplified Dispatcher implementation of Flux pattern written in Swift using new async/await concurrency model

Natan Zalkin 5 Aug 31, 2022
This is a Swift implementation of a D2Q9 Lattice-Boltzmann fluid flow simulation.

DMCLatticeBoltzmann This is a Swift implementation of a D2Q9 Lattice-Boltzmann fluid flow simulation. This package defines three products. The DMCLatt

Mitch Chapman 1 Aug 15, 2022
Schedule timing task in Swift using a fluent API. (A friendly alternative to Timer)

Schedule(简体中文) Schedule is a timing tasks scheduler written in Swift. It allows you run timing tasks with elegant and intuitive syntax. Features Elega

Luo Xiu 1.8k Sep 20, 2022
An introduction to using Swift's new concurrency features in SwiftUI

SwiftUI Concurrency Essentials An introduction to using Swift's new concurrency features in SwiftUI Discuss with me · Report Bug · Request Feature Art

Peter Friese 71 Sep 16, 2022
Tools for using Swift Concurrency on macOS 10.15 Catalina, iOS 13, tvOS 13, and watchOS 6.

ConcurrencyCompatibility Tools for using Swift Concurrency on macOS 10.15 Catalina, iOS 13, tvOS 13, and watchOS 6. Xcode 13.2 adds backwards deployme

Zachary Waldowski 7 Sep 21, 2022
Using async / await on iOS 13: everything you need to know

Using async / await on iOS 13: everything you need to know! ?? Content This repository contains the code sample I've used during December 14th's lives

Vincent Pradeilles 11 Feb 1, 2022
Resume-app - A simple iOS app to showcase Swift development skills using Xcode

resume-app A simple iOS app to showcase Swift development skills using Xcode. Pr

AJ Rivera 0 Jan 12, 2022