helpers

package
v0.0.0-...-32ce2be Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 18, 2021 License: MIT Imports: 34 Imported by: 0

Documentation

Index

Constants

View Source
const (
	PubkeyFileName     = "pubkey.asc"            // Public key
	PrivkeyFileName    = "privkey.asc"           // Private key
	EncPrivkeyFileName = "privkey.asc.enc"       // Encrypted private key
	EnvSuperSecret     = "super_secret_password" // Name of the secret environment variable stored on Travis CI
)
View Source
const ExecLocationKey = "X-ExecLocation"

This key in the desktop files written by appimaged describes where the AppImage is in the filesystem. We need this because we rewrite Exec= to include things like wrap and Firejail

View Source
const MQTTNamespace = "p9q358t" // Our namespace. Our topic begins with this
View Source
const MQTTServerURI = "http://broker.hivemq.com:1883"

TODO: Instead of using hardcoded values here, we should grab those values from some URL where we can change them, to allow the broker and namespace to be switched at any time without having to update all clients. We should also publish the version of the message format there so that we could force applications to be updated if they are not built for that version of the message format

View Source
const UpdateInformationKey = "X-AppImage-UpdateInformation"

This key in the desktop files written by appimaged contains the updateinformation string that we write there so that we can get all updateinformation strings easily when we get a MQTT message telling us that an update is available. Then we need to find quickly all AppImages that have a matching updateinformation string, and figure out which of the existing ones is the newest

Variables

This section is empty.

Functions

func AddDirsToPath

func AddDirsToPath(dirs []string)

AddDirsToPath adds the directories in []string to the $PATH

func AddHereToPath

func AddHereToPath()

AddHereToPath adds the location of the executable to the $PATH

func AppendIfMissing

func AppendIfMissing(slice []string, s string) []string

func Args0

func Args0() string

Args0 returns the absolute path to the executable based on os.Args[0] For AppImages, it will resolve to the outside of an AppImage

func CalculateDigestSkippingRanges

func CalculateDigestSkippingRanges(f *os.File, ranges []ByteRange) hash.Hash

CalculateDigestSkippingRanges calculates the sha256 hash of a file while assuming that the supplied byteRanges are consisting fo '0x00's

func CalculateElfSize

func CalculateElfSize(file string) int64

CalculateElfSize returns the size of an ELF binary as an int64 based on the information in the ELF header

func CalculateSHA256Digest

func CalculateSHA256Digest(path string) string

func CheckDesktopFile

func CheckDesktopFile(desktopfile string) error

func CheckForNeededTools

func CheckForNeededTools(tools []string) error

Check for needed files on $PATH. Returns err

func CheckIfAllToolsArePresent

func CheckIfAllToolsArePresent(tools []string)

CheckIfAllToolsArePresent checks if all the required tools, for example. mksquashfs, unsquashfs are present using exec.LookPath. Function exits with exit code 1, if any tool is missing and reports that particular missing tool to the user

func CheckIfExecFileExists

func CheckIfExecFileExists(desktopfilepath string) bool

CheckIfExecFileExists checks whether a desktop file that points to an-existing Exec= entries. Returns true if it does, false otherwise.

func CheckIfFileExists

func CheckIfFileExists(filepath string) bool

CheckIfFileExists checks if a file exists and is not a directory before we try using it to prevent further errors. Returns true if it does, false otherwise.

func CheckIfFileOrFolderExists

func CheckIfFileOrFolderExists(filepath string) bool

CheckIfFileOrFolderExists checks if a file exists and is not a directory before we try using it to prevent further errors. Returns true if it does, false otherwise.

func CheckIfFolderExists

func CheckIfFolderExists(filepath string) bool

CheckIfFolderExists checks if a folder exists and is a directory before we try using it to prevent further errors. Returns true if it does, false otherwise.

func CheckIfSquashfsVersionSufficient

func CheckIfSquashfsVersionSufficient(toolname string) bool

CheckIfSquashfsVersionSufficient checks whether mksquashfs/unsquashfs is recent enough to use -offset, prints an error message otherwise Returns true if sufficient, false otherwise

func CheckMagicAtOffset

func CheckMagicAtOffset(f *os.File, magic string, offset int64) bool

Return true if magic string (hex) is found at offset TODO: Instead of magic string, could probably use something like []byte{'\r', '\n'} or []byte("AI")

func CheckMagicAtOffsetBytes

func CheckMagicAtOffsetBytes(byts []byte, magic string, offset int) bool

Return true if magic string (hex) is found at offset TODO: Instead of magic string, could probably use something like []byte{'\r', '\n'} or []byte("AI")

func CheckSignature

func CheckSignature(path string) (*openpgp.Entity, error)

CheckSignature checks the signature embedded in an AppImage at path, returns the entity that has signed the AppImage and error based on https://stackoverflow.com/a/34008326

func CopyFile

func CopyFile(src string, dst string) error

CopyFile copies the src file to dst. Any existing file will be overwritten and will not copy file attributes. Unclear why such basic functionality is not in the standard library.

func CreateAndValidateKeyPair

func CreateAndValidateKeyPair()

func Decrypt

func Decrypt(passphrase, encrypted []byte) ([]byte, error)

Decrypt decrypts a []byte that was encrypted using OpenSSL and AES-256-CBC.

func DecryptBase64

func DecryptBase64(passphrase, encryptedBase64 []byte) ([]byte, error)

DecryptBase64 decrypts a base64 encoded []byte that was encrypted using OpenSSL and AES-256-CBC.

func DecryptString

func DecryptString(passphrase, encryptedBase64String string) (string, error)

DecryptString decrypts a base64 encoded string that was encrypted using OpenSSL and AES-256-CBC.

func DeleteDesktopFilesWithNonExistingTargets

func DeleteDesktopFilesWithNonExistingTargets()

DeleteDesktopFilesWithNonExistingTargets deletes desktop files in xdg.DataHome + "/applications/" that point to non-existing Exec= entries

func EmbedStringInSegment

func EmbedStringInSegment(path string, section string, s string) error

EmbedStringInSegment embeds a string in an ELF segment, returns error

func Encrypt

func Encrypt(passphrase, plaintext []byte) ([]byte, error)

Encrypt encrypts a []byte in a manner compatible to OpenSSL encryption functions using AES-256-CBC as encryption algorithm

func EncryptBase64

func EncryptBase64(passphrase, plaintext []byte) ([]byte, error)

EncryptBase64 encrypts a []byte in a manner compatible to OpenSSL encryption functions using AES-256-CBC as encryption algorithm and encode to base64 format.

func EncryptString

func EncryptString(passphrase, plaintextString string) (string, error)

EncryptString encrypts a string in a manner compatible to OpenSSL encryption functions using AES-256-CBC as encryption algorithm and encode to base64 format.

func Exists

func Exists(name string) bool

Returns true if file or directory exists Why is this not in the standard library?

func FilesWithPrefixInDirectory

func FilesWithPrefixInDirectory(directory string, prefix string) []string

FilesWithPrefixInDirectory returns the files in a given directory with the given filename extension, and err

func FilesWithSuffixInDirectory

func FilesWithSuffixInDirectory(directory string, extension string) []string

FilesWithSuffixInDirectory returns the files in a given directory with the given filename extension, and err

func FilesWithSuffixInDirectoryRecursive

func FilesWithSuffixInDirectoryRecursive(directory string, extension string) []string

FilesWithSuffixInDirectoryRecursive returns the files in a given directory with the given filename extension, and err

func FindMostRecentFile

func FindMostRecentFile(files []string) string

FindMostRecentFile returns the most recent file from a slice of files, (currently) based on its mtime based on https://stackoverflow.com/a/45579190 TODO: mtime may be fast, but is it "good enough" for our purposes?

func GetCommitMessageForLatestCommit

func GetCommitMessageForLatestCommit(ui UpdateInformation) (string, error)

GetCommitMessageForLatestCommit gets the commit message for the latest commit (currently only on GitHub) using UpdateInformation. Returns commit string and err Can get rather quickly: 403 API rate limit exceeded for xxx.xxx.xxx.xxx. (But here's the good news: Authenticated requests get a higher rate limit. Check out the documentation for more details.) [rate reset in 59m39s]

func GetCommitMessageForThisCommitOnTravis

func GetCommitMessageForThisCommitOnTravis() (string, error)

GetCommitMessageForThisCommitOnTravis returns a string with the most recent commit message for the commit in the TRAVIS_COMMIT environment variable, and error

func GetElfArchitecture

func GetElfArchitecture(filepath string) (string, error)

GetElfArchitecture returns the architecture of a file, and err

func GetGitRepository

func GetGitRepository() (*git.Repository, error)

GetGitRepository returns a git Repository if cwd is a git repository, and error otherwise

func GetReleaseURL

func GetReleaseURL(ui UpdateInformation) (string, error)

GetReleaseURL gets the URL message for the latest release (currently only on GitHub) matching the given UpdateInformation. Returns commit string and err

func GetSectionData

func GetSectionData(filepath string, name string) ([]byte, error)

GetSectionData returns the contents of an ELF section and error

func GetSectionOffsetAndLength

func GetSectionOffsetAndLength(filepath string, name string) (uint64, uint64, error)

GetSectionOffsetAndLength returns the Offset and Length of an ELF section and error

func GetValuesForAllDesktopFiles

func GetValuesForAllDesktopFiles(key string) []string

GetValuesForAllDesktopFiles gets the values for a given key from all desktop files in xdg.DataHome + "/applications/"

func Here

func Here() string

Here returns the absolute path to the parent directory of the executable based on /proc/self/exe This will only work on Linux. For AppImages, it will resolve to the inside of an AppImage

func HereArgs0

func HereArgs0() string

HereArgs0 returns the absolute path to the parent directory of the executable based on os.Args[0] For AppImages, it will resolve to the outside of an AppImage

func IsCommandAvailable

func IsCommandAvailable(name string) bool

IsCommandAvailable returns true if a file is on the $PATH

func IsDirectory

func IsDirectory(path string) bool

Returns true if path is a directory Why is this not in the standard library?

func LogError

func LogError(context string, e error)

LogError logs error, prefixed by a string that explains the context

func PrintError

func PrintError(context string, e error)

PrintError prints error, prefixed by a string that explains the context

func PublishMQTTMessage

func PublishMQTTMessage(updateinformation string, version string)

func ReplaceTextInFile

func ReplaceTextInFile(path string, search string, replace string) error

ReplaceTextInFile replaces search string with replce string in a file. Returns error or nil

func RunCmdStringTransparently

func RunCmdStringTransparently(command string) error

RunCmdStringTransparently works like RunCmdTransparently but accepts a string rather than a []string as its input. Why is this not part of the standard library?

func RunCmdTransparently

func RunCmdTransparently(command []string) error

RunCmdTransparently runs the command given in a []string and runs it transparently (stdin and stderr appear immediately while the command is running). Blocks until command has completed. Returns error. https://stackoverflow.com/a/31004293 https://stackoverflow.com/q/33452726 Why is this not part of the standard library?

func SignAppImage

func SignAppImage(path string, digest string) error

SignAppImage signs an AppImage, returns error Based on https://gist.github.com/eliquious/9e96017f47d9bd43cdf9

func SliceContains

func SliceContains(s []string, e string) bool

SliceContains returns true if the []string contains string, false otherwise. Why is this not in the standard library as a method of every []string?

func TestGit

func TestGit()

func ValidateAppStreamMetainfoFile

func ValidateAppStreamMetainfoFile(appdirpath string) error

ValidateAppStreamMetainfoFile validates an AppStream metainfo file using the appstreamcli tool on the $PATH Returns error if validation fails and prints any errors to stderr

func ValidateDesktopFile

func ValidateDesktopFile(desktopfile string) error

ValidateDesktopFile validates a desktop file using the desktop-file-validate tool on the $PATH Returns error if validation fails and prints any errors to stderr

func ValidateUpdateInformation

func ValidateUpdateInformation(updateinformation string) error

ValidateUpdateInformation validates an updateinformation string, returns error. TODO: Build this into NewUpdateInformationFromString and get rid of it?

func WriteFileIntoOtherFileAtOffset

func WriteFileIntoOtherFileAtOffset(inputfilepath string, outputfilepath string, offset uint64) error

WriteFileIntoOtherFileAtOffset writes the content of inputfile into outputfile at Offset, without truncating Returns error in case of errors, otherwise returns nil

func WriteStringIntoOtherFileAtOffset

func WriteStringIntoOtherFileAtOffset(inputstring string, outputfilepath string, offset uint64) error

WriteStringIntoOtherFileAtOffset writes the content of inputstring into outputfile at Offset, without truncating Returns error in case of errors, otherwise returns nil

Types

type AppDir

type AppDir struct {
	Path            string
	DesktopFilePath string
	MainExecutable  string
}

func NewAppDir

func NewAppDir(desktopFilePath string) (AppDir, error)

func (AppDir) CopyMainIconToRoot

func (appdir AppDir) CopyMainIconToRoot(iconName string) error

CopyMainIconToRoot copies the most suitable icon for the Icon= entry in DesktopFilePath to the root of the AppDir

func (AppDir) CreateIconDirectories

func (appdir AppDir) CreateIconDirectories() error

CreateIconDirectories creates empty directories in <AppDir>/usr/share/icons/<size>/apps

func (AppDir) GetElfInterpreter

func (AppDir) GetElfInterpreter(appdir AppDir) (string, error)

type ByteRange

type ByteRange struct {
	Offset int64
	Length int64
}

type PubSubData

type PubSubData struct {
	Name    string
	Version string
	// Fruit   []string
	// Size int64 // FIXME: Size is not sufficient to tell two AppImages apart since squashfs pads the end
	// Id      int64  `json:"ref"` // A field can be encoded to a different key name in JSON
	// private string // An unexported (lowercase) field is not encoded
	FSTime time.Time // Use this format and time.Now() to transport timestamps. We (ab)use FSTime to check local files with "unsquashfs -fstime" to see whether they are "different"
}

Define the PubSubData that gets exchanged between AppImage authoring tool and AppImage desktop integration tool (e.g., appimagetool and appimaged). For best practices regarding JSON payloads, see https://yourbasic.org/golang/json-example/ e.g., use int64 for number. We try to keep the messages as small as possible and not transmit redundant information here that can be constructed by the client directly (e.g., the URL to the GitHub repository can logially be derived from the updateinformation string)

type UpdateInformation

type UpdateInformation struct {
	// contains filtered or unexported fields
}

Please note that pre-releases are not being considered when using "latest". You will have to explicitly provide the name of a release. When using e.g., uploadtool, the name of the release created will always be "continuous", hence, you can just specify that value instead of "latest".

func NewUpdateInformationFromString

func NewUpdateInformationFromString(updateinformation string) (UpdateInformation, error)

NewUpdateInformationFromString returns an UpdateInformation struct for the given updateinformation string, and err TODO: Use UpdateInformation structs throughout the codebase

type Watchdog

type Watchdog struct {
	// contains filtered or unexported fields
}

Watchdog calls a function once after a certain delay has elapsed; kicking it resets the delay. Kicking it after the function has already been called restarts it. https://codereview.stackexchange.com/questions/144273/watchdog-in-golang

func NewWatchdog

func NewWatchdog(interval time.Duration, callback func()) *Watchdog

func (*Watchdog) Kick

func (w *Watchdog) Kick()

func (*Watchdog) Stop

func (w *Watchdog) Stop()

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL