Skip to content

Commit

Permalink
First version of sharm agent
Browse files Browse the repository at this point in the history
  • Loading branch information
asdek committed Jun 25, 2019
0 parents commit 4ce41d0
Show file tree
Hide file tree
Showing 14 changed files with 674 additions and 0 deletions.
12 changes: 12 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
# Binaries for programs and plugins
*.exe
*.exe~
*.dll
*.so
*.dylib

# Test binary, build with `go test -c`
*.test

# Output of the go coverage tool, specifically when used with LiteIDE
*.out
11 changes: 11 additions & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
dist: xenial

language: go

go:
- 1.12.x
- 1.11.x
- 1.10.x

notifications:
email: false
29 changes: 29 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
BSD 3-Clause License

Copyright (c) 2019, VXControl
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.

3. Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
59 changes: 59 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
# Sharm Agent

[![Build Status](https://travis-ci.org/vxcontrol/sharm.svg?branch=master)](https://travis-ci.org/vxcontrol/sharm)

Sharm is a public service to recording you terminal and to showing to everybody as real time broadcasting. Also, you are able to record and broadcast your voice and to attach chat comments to final result and to share this.

### Sharm key features:

- Totally free service
- Broadcast terminal and sound
- Chat in real time broadcast
- Supports MacOS, Linux and Windows
- Unlimited storage of records

### Support

It's main page of the service and you should post your questions, issues and suggestions to this tracker page.
While the service is still young, we will welcome your suggestions for its improvement.

**Important**: We aren't responsible for any risks and losses associated with using of this service and this code.

## Dependencies

- Windows version of the agent based on [winpty project](https://github.com/rprichard/winpty)
- Transport subsystem has based on [websockets](https://github.com/gorilla/websocket) and TLS connection over golang library
- Logging subsystem has based on [logrus](https://github.com/sirupsen/logrus)

## Building

It's very simple and native procedure:

```sh
$ cd sharm
$ go get
$ go build -o build/sharm
```

Of course you can use **GOARCH** and **GOOS** environment variables on build.

## Using

The agent working with original [Sharm service](https://sharm.io) and to use it you need to follow the instructions from this service.

## Changelog

### sharm v1.0

- Supports MacOS, Linux and Windows
- Share one screen at one time
- Control from environment variables
- Protocol v1 over JSON struct based on WebSocket

## Copyright

This project is distributed under the BSD 3-Clause license (see the LICENSE file in the project root).

By submitting a pull request for this project, you agree to license your contribution under the BSD 3-Clause license to this project.

© 2019 [vxcontrol.com](https://vxcontrol.com)[sharm.io](https://sharm.io)
Empty file added build/.gitkeep
Empty file.
177 changes: 177 additions & 0 deletions client.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,177 @@
package main

import (
"encoding/json"
"errors"
"net/http"
"sync"
"time"

"github.com/gorilla/websocket"
"github.com/sirupsen/logrus"
"github.com/vxcontrol/sharm/term"
)

const (
// UnknownInput is unknown message type, maybe sent by a bug
UnknownInput = '0'
// Input is user input typically from a keyboard
Input = '1'
// Ping to the server
Ping = '2'
// ResizeTerminal is a notification that the browser size has been changed
ResizeTerminal = '3'
// Quit is a notification that client must close current connection and exit
Quit = '4'
)

const (
// UnknownOutput is unknown message type, maybe set by a bug
UnknownOutput = '0'
// Output is normal output to the terminal
Output = '1'
// Pong to the browser
Pong = '2'
// SetWindowTitle is set window title of the terminal
SetWindowTitle = '3'
// SetPreferences is set terminal preference
SetPreferences = '4'
// SetReconnect is make terminal to reconnect
SetReconnect = '5'
)

type clientContext struct {
request *http.Request
connection *websocket.Conn
pty *term.Term
closed bool
writeMutex *sync.Mutex
}

type argResizeTerminal struct {
Columns int
Rows int
}

func (context *clientContext) goHandleClient() error {
var wg sync.WaitGroup
var errSend, errRecv error

wg.Add(1)
go func() {
defer wg.Done()
errSend = context.processSend()
}()

wg.Add(1)
go func() {
defer wg.Done()
errRecv = context.processReceive()
}()

log.Info("Sharm client handler is waiting")
wg.Wait()
log.Info("Sharm client handler was released")

if errSend != nil {
return errSend
} else if errRecv != nil {
return errRecv
}
return nil
}

func (context *clientContext) processSend() (errResult error) {
log.Info("Sharm sender has running")
defer log.Info("Sharm sender was stopped")
buf := make([]byte, term.DefBufferSize)
var size int
var err error
defer func() {
context.closed = true
if errResult != nil {
log.WithFields(logrus.Fields{
"error": err.Error(),
}).Error(errResult.Error())
}
}()

for !context.closed {
if size, err = context.pty.Read(buf); err != nil {
return errors.New("Failed to read data from termital")
}
if size > 0 {
if err = context.write(append([]byte("1"), buf[:size]...)); err != nil {
return errors.New("Failed to send data to server")
}
}
}
return nil
}

func (context *clientContext) write(data []byte) error {
context.writeMutex.Lock()
defer context.writeMutex.Unlock()
context.connection.SetWriteDeadline(time.Now().Add(10 * time.Second))
return context.connection.WriteMessage(websocket.TextMessage, data)
}

func (context *clientContext) processReceive() (errResult error) {
log.Info("Sharm receiver has running")
defer log.Info("Sharm receiver was stopped")
var data []byte
var err error
defer func() {
context.closed = true
if errResult != nil {
log.WithFields(logrus.Fields{
"error": err.Error(),
}).Error(errResult.Error())
}
}()

for !context.closed {
_, data, err = context.connection.ReadMessage()
if err != nil {
return errors.New("Failed to get message from server")
}
if len(data) == 0 {
return errors.New("Received empty data from server")
}

log.WithFields(logrus.Fields{
"data": data,
}).Trace("Received new data from server")
payload := data[1:]
switch data[0] {
case Input:
if err = context.pty.Write(payload); err != nil {
return errors.New("Failed to write data to termital")
}

case Ping:
log.Debug("Received healthcheck packet")
if err = context.write([]byte{Pong}); err != nil {
return errors.New("Failed to send healthcheck packet")
}

case ResizeTerminal:
log.Debug("Received resize packet")
var args argResizeTerminal
if err = json.Unmarshal(payload, &args); err != nil {
return errors.New("Failed to parse resize message")
}
if err = context.pty.Resize(args.Columns, args.Rows); err != nil {
return errors.New("Failed to resize terminal")
}

case Quit:
log.Debug("Received quit packet")
return nil

default:
return errors.New("Received unknown message type")
}
}
return nil
}
52 changes: 52 additions & 0 deletions include/pty.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
#ifndef PTY_H
#define PTY_H

// __cplusplus gets defined when a C++ compiler processes the file
#ifdef __cplusplus
// extern "C" is needed so the C++ compiler exports the symbols without name
// manging.
extern "C" {
#endif

//External API

#ifndef DWORD
#define DWORD unsigned long
#endif

/*
* PtyOpen
* pty.open(cols, rows, shell_path)
* return handle of PTY object (self)
*/
void * PtyOpen(int cols, int rows, char * cmd);

/*
* PtyResize
* pty.resize(self, cols, rows);
*/
DWORD PtyResize(void *self, int cols, int rows);

/*
* PtyKill
* pty.kill(self);
*/
DWORD PtyKill(void *self);

/*
* PtyRead
* pty.read(self, data, size)
*/
DWORD PtyRead(void *self, unsigned char *data, DWORD size);

/*
* PtyWrite
* pty.write(self, data, amount)
*/
DWORD PtyWrite(void *self, const unsigned char *data, DWORD size);

#ifdef __cplusplus
}
#endif

#endif
Binary file added lib/windows_386/libpty.a
Binary file not shown.
Binary file added lib/windows_amd64/libpty.a
Binary file not shown.
Loading

0 comments on commit 4ce41d0

Please sign in to comment.