summaryrefslogtreecommitdiffstats
path: root/sub.sh
blob: c5b8c127927e80ade9f0c39995bf04a21a141394 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
#!/bin/ksh
# OpenBSD ksh daemon to process remote spool files over SSH

SSH_HOST="lex-spool"
SPOOL_DIR="/var/spool/remote_spool"
DICT_DIR="/var/www/var/lex/dict"
SOCKET_PATH="/var/run/my_program.sock"
SLEEP_INTERVAL=2

log_err() {
	logger -t lexd_sub -p daemon.err "$1"
}

while true; do
	# Grab the first spool file name
	LS_CMD="ls -1 '${SPOOL_DIR}' 2>/dev/null | head -n 1"
	SPOOL_FILE=$(ssh -n "${SSH_HOST}" "${LS_CMD}")
	if [ $? -ne 0 ]; then
		log_err "Failed to reach remote server ${SSH_HOST}"
		sleep "${SLEEP_INTERVAL}"
		continue
	fi

	# If spool is empty, wait and retry
	if [ -z "${SPOOL_FILE}" ]; then
		sleep "${SLEEP_INTERVAL}"
		continue
	fi

	# Fork to mitigate resource leaks in the main process
	(
		set -e

		# Fetch remote file into Unix socket
		CAT_CMD="cat '${SPOOL_DIR}/${SPOOL_FILE}'"
		response=$(ssh -n "${SSH_HOST}" "${CAT_CMD}" \
			| nc -U "${SOCKET_PATH}")

		if [ -z "${response}" ]; then
			log_err "Empty socket response: ${SPOOL_FILE}"
			exit 1
		fi

		# Extract first word (lowercased)
		target_word=$(print -r -- "${response}" \
			| awk '{print tolower($1); exit}')

		if [ -z "${target_word}" ]; then
			log_err "No target filename for: ${SPOOL_FILE}"
			exit 1
		fi

		# Validate target word from socket
		case "${target_word}" in
			*[!a-z-]*)
				log_err "Invalid word '${target_word}': ${SPOOL_FILE}"
				exit 1
				;;
			[!a-z]*|*[!a-z])
				log_err "Bad bounds '${target_word}': ${SPOOL_FILE}"
				exit 1
				;;
		esac

		target_file="${DICT_DIR}/${target_word}"

		# Write dict file & remove spool file
		WRITE_DEL_CMD="cat > '${target_file}' && \
			rm -f '${SPOOL_DIR}/${SPOOL_FILE}'"

		print -r -- "${response}" \
			| ssh -n "${SSH_HOST}" "${WRITE_DEL_CMD}"
	)

	if [ $? -ne 0 ]; then
		log_err "Processing failed for file: ${SPOOL_FILE}"
	fi

	sleep "${SLEEP_INTERVAL}"
done