#!/usr/bin/python3 # SPDX-License-Identifier: MIT ''' Simple clipboard storing anything from stdin in a file or outputing from the file to stdout. Direction is determined from pipe redirection. Examples: Store something to clipboard: echo abc | clip Output clipboard content to console: clip Use content: clip > file clip | command ''' import contextlib import functools import getpass import os import sys class Error(Exception): pass class SecurityError(Error): pass @contextlib.contextmanager def secure_opendir(dirname): os.makedirs(dirname, mode=0o700, exist_ok=True) dfd = os.open(dirname, os.O_RDONLY | os.O_DIRECTORY) try: dir_stat = os.stat(dfd) if (dir_stat.st_uid != os.getuid() or dir_stat.st_mode & 0o777 != 0o700): raise SecurityError('Wrong directory permissions/owner') yield dfd finally: os.close(dfd) @contextlib.contextmanager def secure_open(*l, **kw): with secure_opendir(os.path.dirname(l[0])) as dfd: _opener = functools.partial(os.open, dir_fd=dfd) with open(*l, **kw, opener=_opener) as ffd: yield ffd if __name__ == '__main__': os.umask(0o077) clipboard_filepath = '/dev/shm/%s-clipboard/content' % getpass.getuser() if(sys.stdin.isatty()): # Should write clipboard contents out to stdout try: with secure_open(clipboard_filepath, 'rb') as fo: sys.stdout.buffer.write(fo.read()) except FileNotFoundError: # equivalent to an empty file pass elif(sys.stdout.isatty()): # Should save stdin to clipboard with secure_open(clipboard_filepath, 'wb') as fo: fo.write(sys.stdin.buffer.read())