summaryrefslogtreecommitdiffstats
path: root/lib/control.sh
blob: 9115d7f563c61bca0eabeea3aad997b4727ea0a2 (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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
# Functions for parsing control files
#
# Copyright (C) 2012, 2018 Patrick McDermott
#
# This file is part of opkbuild.
#
# opkbuild is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# opkbuild is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with opkbuild.  If not, see <http://www.gnu.org/licenses/>.

_OB_SUBSTVARS_MAX_DEPTH=50

OB_CONTROL_NAME=
OB_CONTROL_VALUE=

_ob_parse_control_error()
{
	local file=
	local line_nr=
	local msg_id=
	local file_info=
	local orig_text_domain=

	file="${1}"
	line_nr="${2}"
	msg_id="${3}"
	shift 3

	if [ ${line_nr} -eq 0 ]; then
		file_info="$(printf '%20s:' "${file}")"
	else
		file_info="$(printf '%20s(l%d):' "${file}" "${line_nr}")"
	fi

	orig_text_domain="$(ob_get_text_domain)"
	ob_set_text_domain "${_OB_INTERNAL_TEXT_DOMAIN}"

	ob_warn "${file_info} $(ob_get_msg "${msg_id}")" "${@}"

	ob_set_text_domain "${orig_text_domain}"

	return 0
}

## @brief Parse a control file
## @details \fBob_parse_control\fP parses a control file of field names and
##          values formatted like RFC 822 (or RFC 2822 or RFC 5322) headers. 
##          For each field, \fBob_parse_control\fP calls \fIfield_cb\fP after
##          setting \fIOB_CONTROL_NAME\fP to the field name and
##          \fIOB_CONTROL_VALUE\fP to the field value.  If \fIreq_fields\fP and
##          \fIopt_fields\fP are given, \fBob_parse_control\fP verifies that the
##          input control file contains all fields listed in \fIreq_fields\fP
##          and no fields that are listed in neither \fIreq_fields\fP nor
##          \fIopt_fields\fP.  If \fIfield_cb\fP returns non-zero,
##          \fBob_parse_control\fP stops parsing and immediately returns,
##          without verifying that all required fields were found.
## @operand file       req The control file to parse, or "-" for standard input.
## @operand field_cb   req Callback to run for each field.
## @operand req_fields opt Required fields that must appear in the control file.
## @operand opt_fields opt Optional fields that may appear in the control file.
## @return Returns 0 after parsing, or 125 if called with an incorrect number of
##         arguments.
## @stderr Prints error messages on parse errors.
## @pure maybe This function sets global variables, but they're only intended
##             for use by \fIfield_cb\fP, which is called during the lifetime of
##             this function.  Whether this function is subshell-safe in
##             practice depends on whether \fIfield_cb\fP is subshell-safe.
ob_parse_control()
{
	local file=
	local field_cb=
	local req_fields=
	local opt_fields=
	local check_fields=
	local all_fields=
	local got_fields=
	local line_nr=
	local line=
	local name=
	local value=

	if [ ${#} -eq 2 ]; then
		file="${1}"
		field_cb="${2}"
		check_fields='false'
	elif [ ${#} -eq 4 ]; then
		file="${1}"
		field_cb="${2}"
		req_fields="${3}"
		opt_fields="${4}"
		check_fields='true'
		all_fields=" ${req_fields} ${opt_fields} "
	else
		return 125
	fi

	got_fields=' '

	line_nr=0

	while IFS= read -r line; do
		line_nr=$(($line_nr + 1))
		if [ -z "$(echo ${line})" ]; then
			_ob_parse_control_error "${file}" "${line_nr}" \
				'control_empty_line'
		elif [ "${line#\#}" != "${line}" ]; then
			# Comment.
			:
		elif [ "${line# }" = "${line}" ]; then
			# "Name: Value" line.
			if [ -n "${name}" ]; then
				OB_CONTROL_NAME="${name}"
				OB_CONTROL_VALUE="${value}"
				"${field_cb}"
				if [ ${?} -ne 0 ]; then
					return 0
				fi
			fi
			name="${line%%:*}"
			value="${line#*:}"
			value="${value# }"
			if [ -z "${name}" \
				-o "${name}" = "${line}" ]; then
				# Badly formatted control field.
				_ob_parse_control_error "${file}" "${line_nr}" \
					'control_bad_nv'
				continue
			fi
			if ${check_fields}; then
				if [ "${all_fields% ${name} *}" = \
						"${all_fields}" ]; then
					# Unknown field.
					_ob_parse_control_error \
						"${file}" "${line_nr}" \
						'control_unknown_field' "${name}"
				else
					# Remove field from list of required fields.
					req_fields="$(echo "${req_fields}" | \
						sed "s/${name}//")"
				fi
			fi
			if [ "${got_fields% ${name} *}" != \
					"${got_fields}" ]; then
				# Duplicate field.
				_ob_parse_control_error "${file}" "${line_nr}" \
					'control_duplicate_field' "${name}"
			else
				got_fields="${got_fields}${name} "
			fi
		else
			# Continuation line.
			if [ -z "${name}" ]; then
				# Expecting a "Name: Value" line.
				_ob_parse_control_error "${file}" "${line_nr}" \
					'control_found_continuation'
				continue
			fi
			value="${value}
${line# }"
		fi
	done <<-EOF
		$(cat "${file}")
		EOF

	if [ -n "${name}" ]; then
		OB_CONTROL_NAME="${name}"
		OB_CONTROL_VALUE="${value}"
		"${field_cb}"
		if [ ${?} -ne 0 ]; then
			return 0
		fi
	fi

	if ${check_fields}; then
		req_fields="${req_fields## }"
		req_fields="${req_fields%% }"
		if [ -n "${req_fields}" ]; then
			# Missing required control fields.
			req_fields="$(echo "${req_fields}" | sed 's/  / /g' | \
				sed "s/ /$(ob_get_msg 'list_item_separator')/g")"
			_ob_parse_control_error "${file}" '0' \
				'control_missing_fields' "${req_fields}"
		fi
	fi

	return 0
}

## @brief Set a substitution variable
## @details \fBob_set_substvar\fP sets a substitution variable for later use by
##          \fBob_substvars\fP(3).
## @operand name  req The name of the substitution variable.  May only consist
##                    of uppercase and lowercase Latin letters, digits, and
##                    hyphens and must be at least one character long.
## @operand value req The value of the substitution variable.
## @return Returns 0 on success, or 125 if called with an incorrect number of
##         arguments or if \fIname\fP is empty or contains invalid characters.
## @pure no This function sets an internal global variable.
ob_set_substvar()
{
	local name=
	local value=

	if [ ${#} -eq 2 ]; then
		name="${1}"
		value="${2}"
	else
		return 125
	fi

	# Convert variable name to uppercase and validate.
	name="$(echo "${name}" | tr 'a-z-' 'A-Z_')"
	case "${name:- }" in
		*[!A-Z0-9_]*)
			return 125
			;;
	esac

	# Trim leading and trailing whitespace from value.
	# TODO: "read" can probably do this more simply.
	value="$(echo "${value}" | sed -n '
		H;             # Store each input line in the hold space.
		${             # At the last line of input:
		  g;           # restore the hold space into the pattern space,
		  s/^[\n]*//;  # remove leading newline characters,
		  s/[\n]*$//;  # remove trailing newline characters, and
		  p;           # print the results.
		};
		')"

	eval "_OB_SUBSTVAR_${name}=\"\${value}\""

	return 0
}

## @brief Substitute variables in text
## @details \fBob_substvars\fP substitutes variables previously set with
##          \fBob_set_substvar\fP(3) in a string.  The format for variable
##          substitutions is \fI${var}\fP, and substitutions can be nested.
## @operand string req The string in which to substitute variables.
## @return Returns 0 on success, 1 on possible recursion, or 125 if called with
##         an incorrect number of arguments.
## @stderr Prints a warning on possible recursion.
## @pure yes This function has no side effects.
ob_substvars()
{
	local string=
	local depth=
	local lhs=
	local name=
	local rhs=
	local old_rhs=
	local value=

	if [ ${#} -eq 1 ]; then
		string="${1}"
	else
		return 125
	fi

	# Logic inspired by that of dpkg's Dpkg::Substvars::substvars() subroutine.

	depth=0

	while true; do
		lhs="${string%%\$\{*}"
		if [ ${#lhs} -eq ${#string} ]; then
			# No "${" was found.
			break
		fi
		string="${string#*\$\{}"
		name="${string%%\}*}"
		rhs="${string#*\}}"

		if [ ${#rhs} -lt ${#old_rhs} ]; then
			# Reset the nesting counter if we've advanced the right side of the
			# matched space.
			depth=0
		fi
		if [ ${depth} -ge ${_OB_SUBSTVARS_MAX_DEPTH} ]; then
			# Warn of possible recursion.
			# TODO: This doesn't set the text domain.
			ob_warn "$(ob_get_msg 'substvar_deep_nesting')"
			return 1
		fi
		old_rhs="${rhs}"

		# Perform the substitution.
		name="$(echo "${name}" | tr 'a-z-' 'A-Z_')"
		value="$(eval echo \"\$\{"_OB_SUBSTVAR_${name}"\}\")"
		string="${lhs}${value}${rhs}"
		depth=$(($depth + 1))
	done

	printf '%s\n' "${string}"

	return 0
}