ftp.subr revision 253545
1if [ ! "$_MEDIA_FTP_SUBR" ]; then _MEDIA_FTP_SUBR=1
2#
3# Copyright (c) 2012-2013 Devin Teske
4# All rights reserved.
5#
6# Redistribution and use in source and binary forms, with or without
7# modification, are permitted provided that the following conditions
8# are met:
9# 1. Redistributions of source code must retain the above copyright
10#    notice, this list of conditions and the following disclaimer.
11# 2. Redistributions in binary form must reproduce the above copyright
12#    notice, this list of conditions and the following disclaimer in the
13#    documentation and/or other materials provided with the distribution.
14#
15# THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18# ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25# SUCH DAMAGE.
26#
27# $FreeBSD: head/usr.sbin/bsdconfig/share/media/ftp.subr 253545 2013-07-22 13:56:35Z dteske $
28#
29############################################################ INCLUDES
30
31BSDCFG_SHARE="/usr/share/bsdconfig"
32. $BSDCFG_SHARE/common.subr || exit 1
33f_dprintf "%s: loading includes..." media/ftp.subr
34f_include $BSDCFG_SHARE/device.subr
35f_include $BSDCFG_SHARE/dialog.subr
36f_include $BSDCFG_SHARE/media/common.subr
37f_include $BSDCFG_SHARE/media/tcpip.subr
38f_include $BSDCFG_SHARE/strings.subr
39f_include $BSDCFG_SHARE/struct.subr
40f_include $BSDCFG_SHARE/variable.subr
41
42BSDCFG_LIBE="/usr/libexec/bsdconfig"
43f_include_lang $BSDCFG_LIBE/include/messages.subr
44
45############################################################ GLOBALS
46
47FTP_SKIP_RESOLV=
48
49URL_MAX=261261 # according to actual fetch(1) test-results
50
51FTP_DIRS="
52	.
53	releases/$UNAME_P
54	snapshots/$UNAME_P
55	pub/FreeBSD
56	pub/FreeBSD/releases/$UNAME_P
57	pub/FreeBSD/snapshots/$UNAME_P
58	pub/FreeBSD-Archive/old-releases/$UNAME_P
59" # END-QUOTE
60
61############################################################ FUNCTIONS
62
63# f_dialog_menu_media_ftp
64#
65# Prompt the user to select from a range of ``built-in'' FTP servers or specify
66# their own. If the user makes a choice and doesn't cancel or press Esc, stores
67# the user's choice in VAR_FTP_PATH (see variables.subr) and returns success.
68#
69f_dialog_menu_media_ftp()
70{
71	f_dialog_title "$msg_please_select_a_freebsd_ftp_distribution_site"
72	local title="$DIALOG_TITLE" btitle="$DIALOG_BACKTITLE"
73	f_dialog_title_restore
74	local prompt="$msg_please_select_the_site_closest_to_you_or_other"
75	local menu_list="
76		'$msg_main_site'          'ftp.freebsd.org'
77		'URL'                     '$msg_specify_some_other_ftp_site'
78		'IPv6 $msg_main_site'     'ftp.freebsd.org'
79		' IPv6 $msg_france'       'ftp4.fr.freebsd.org'
80		' IPv6 $msg_france #8'    'ftp8.fr.freebsd.org'
81		' IPv6 $msg_ireland'      'ftp3.ie.freebsd.org'
82		' IPv6 $msg_japan'        'ftp2.jp.freebsd.org'
83		' IPv6 $msg_sweden'       'ftp4.se.freebsd.org'
84		' IPv6 $msg_usa'          'ftp4.us.freebsd.org'
85		' IPv6 $msg_turkey'       'ftp2.tr.freebsd.org'
86		'$msg_primary'            'ftp1.freebsd.org'
87		' $msg_primary #2'        'ftp2.freebsd.org'
88		' $msg_primary #3'        'ftp3.freebsd.org'
89		' $msg_primary #4'        'ftp4.freebsd.org'
90		' $msg_primary #5'        'ftp5.freebsd.org'
91		' $msg_primary #6'        'ftp6.freebsd.org'
92		' $msg_primary #7'        'ftp7.freebsd.org'
93		' $msg_primary #10'       'ftp10.freebsd.org'
94		' $msg_primary #11'       'ftp11.freebsd.org'
95		' $msg_primary #12'       'ftp12.freebsd.org'
96		' $msg_primary #13'       'ftp13.freebsd.org'
97		' $msg_primary #14'       'ftp14.freebsd.org'
98		'$msg_armenia'            'ftp1.am.freebsd.org'
99		'$msg_australia'          'ftp.au.freebsd.org'
100		' $msg_australia #2'      'ftp2.au.freebsd.org'
101		' $msg_australia #3'      'ftp3.au.freebsd.org'
102		'$msg_austria'            'ftp.at.freebsd.org'
103		'$msg_brazil'             'ftp2.br.freebsd.org'
104		' $msg_brazil #3'         'ftp3.br.freebsd.org'
105		' $msg_brazil #4'         'ftp4.br.freebsd.org'
106		'$msg_canada'             'ftp.ca.freebsd.org'
107		'$msg_china'              'ftp.cn.freebsd.org'
108		'$msg_czech_republic'     'ftp.cz.freebsd.org'
109		'$msg_denmark'            'ftp.dk.freebsd.org'
110		'$msg_estonia'            'ftp.ee.freebsd.org'
111		'$msg_finland'            'ftp.fi.freebsd.org'
112		'$msg_france'             'ftp.fr.freebsd.org'
113		' $msg_france #3'         'ftp3.fr.freebsd.org'
114		' $msg_france #4'         'ftp4.fr.freebsd.org'
115		' $msg_france #5'         'ftp5.fr.freebsd.org'
116		' $msg_france #6'         'ftp6.fr.freebsd.org'
117		' $msg_france #7'         'ftp7.fr.freebsd.org'
118		' $msg_france #8'         'ftp8.fr.freebsd.org'
119		'$msg_germany'            'ftp.de.freebsd.org'
120		' $msg_germany #2'        'ftp2.de.freebsd.org'
121		' $msg_germany #4'        'ftp4.de.freebsd.org'
122		' $msg_germany #5'        'ftp5.de.freebsd.org'
123		' $msg_germany #6'        'ftp6.de.freebsd.org'
124		' $msg_germany #7'        'ftp7.de.freebsd.org'
125		' $msg_germany #8'        'ftp8.de.freebsd.org'
126		'$msg_greece'             'ftp.gr.freebsd.org'
127		' $msg_greece #2'         'ftp2.gr.freebsd.org'
128		'$msg_iceland'            'ftp.is.freebsd.org'
129		'$msg_ireland'            'ftp3.ie.freebsd.org'
130		'$msg_israel'             'ftp.il.freebsd.org'
131		'$msg_italy'              'ftp.it.freebsd.org'
132		'$msg_japan'              'ftp.jp.freebsd.org'
133		' $msg_japan #2'          'ftp2.jp.freebsd.org'
134		' $msg_japan #3'          'ftp3.jp.freebsd.org'
135		' $msg_japan #4'          'ftp4.jp.freebsd.org'
136		' $msg_japan #5'          'ftp5.jp.freebsd.org'
137		' $msg_japan #6'          'ftp6.jp.freebsd.org'
138		' $msg_japan #7'          'ftp7.jp.freebsd.org'
139		' $msg_japan #8'          'ftp8.jp.freebsd.org'
140		' $msg_japan #9'          'ftp9.jp.freebsd.org'
141		'$msg_korea'              'ftp.kr.freebsd.org'
142		' $msg_korea #2'          'ftp2.kr.freebsd.org'
143		'$msg_latvia'             'ftp.lv.freebsd.org'
144		'$msg_lithuania'          'ftp.lt.freebsd.org'
145		'$msg_netherlands'        'ftp.nl.freebsd.org'
146		' $msg_netherlands #2'    'ftp2.nl.freebsd.org'
147		'$msg_new_zealand'        'ftp.nz.freebsd.org'
148		'$msg_norway'             'ftp.no.freebsd.org'
149		'$msg_poland'             'ftp.pl.freebsd.org'
150		' $msg_poland #2'         'ftp2.pl.freebsd.org'
151		'$msg_russia'             'ftp.ru.freebsd.org'
152		' $msg_russia #2'         'ftp2.ru.freebsd.org'
153		' $msg_russia #4'         'ftp4.ru.freebsd.org'
154		' $msg_russia #5'         'ftp5.ru.freebsd.org'
155		' $msg_russia #6'         'ftp6.ru.freebsd.org'
156		'$msg_slovak_republic'    'ftp.sk.freebsd.org'
157		' $msg_slovak_republic #2' 'ftp2.sk.freebsd.org'
158		'$msg_slovenia'           'ftp.si.freebsd.org'
159		'$msg_south_africa'       'ftp.za.freebsd.org'
160		' $msg_south_africa #2'   'ftp2.za.freebsd.org'
161		' $msg_south_africa #4'   'ftp4.za.freebsd.org'
162		'$msg_spain'              'ftp.es.freebsd.org'
163		' $msg_spain #3'          'ftp3.es.freebsd.org'
164		'$msg_sweden'             'ftp.se.freebsd.org'
165		' $msg_sweden #2'         'ftp2.se.freebsd.org'
166		' $msg_sweden #3'         'ftp3.se.freebsd.org'
167		' $msg_sweden #4'         'ftp4.se.freebsd.org'
168		' $msg_sweden #5'         'ftp5.se.freebsd.org'
169		' $msg_sweden #6'         'ftp6.se.freebsd.org'
170		'$msg_switzerland'        'ftp.ch.freebsd.org'
171		'$msg_taiwan'             'ftp.tw.freebsd.org'
172		' $msg_taiwan #2'         'ftp2.tw.freebsd.org'
173		' $msg_taiwan #3'         'ftp3.tw.freebsd.org'
174		' $msg_taiwan #4'         'ftp4.tw.freebsd.org'
175		' $msg_taiwan #6'         'ftp6.tw.freebsd.org'
176		' $msg_taiwan #11'        'ftp11.tw.freebsd.org'
177		'$msg_turkey'             'ftp2.tr.freebsd.org'
178		'$msg_uk'                 'ftp.uk.freebsd.org'
179		' $msg_uk #2'             'ftp2.uk.freebsd.org'
180		' $msg_uk #3'             'ftp3.uk.freebsd.org'
181		' $msg_uk #4'             'ftp4.uk.freebsd.org'
182		' $msg_uk #5'             'ftp5.uk.freebsd.org'
183		'$msg_ukraine'            'ftp.ua.freebsd.org'
184		' $msg_ukraine #7'        'ftp7.ua.freebsd.org'
185		'$msg_usa #1'             'ftp1.us.freebsd.org'
186		' $msg_usa #2'            'ftp2.us.freebsd.org'
187		' $msg_usa #3'            'ftp3.us.freebsd.org'
188		' $msg_usa #4'            'ftp4.us.freebsd.org'
189		' $msg_usa #5'            'ftp5.us.freebsd.org'
190		' $msg_usa #6'            'ftp6.us.freebsd.org'
191		' $msg_usa #8'            'ftp8.us.freebsd.org'
192		' $msg_usa #10'           'ftp10.us.freebsd.org'
193		' $msg_usa #11'           'ftp11.us.freebsd.org'
194		' $msg_usa #13'           'ftp13.us.freebsd.org'
195		' $msg_usa #14'           'ftp14.us.freebsd.org'
196		' $msg_usa #15'           'ftp15.us.freebsd.org'
197	" # END-QUOTE
198	local hline="$msg_select_a_site_thats_close"
199
200	local height width rows
201	eval f_dialog_menu_size height width rows \
202	                        \"\$title\"  \
203	                        \"\$btitle\" \
204	                        \"\$prompt\" \
205	                        \"\$hline\"  \
206	                        $menu_list
207
208	local mtag
209	mtag=$( eval $DIALOG \
210		--title \"\$title\"             \
211		--backtitle \"\$btitle\"        \
212		--hline \"\$hline\"             \
213		--ok-label \"\$msg_ok\"         \
214		--cancel-label \"\$msg_cancel\" \
215		--menu \"\$prompt\"             \
216		$height $width $rows            \
217		$menu_list                      \
218		2>&1 >&$DIALOG_TERMINAL_PASSTHRU_FD
219	) || return $FAILURE
220	f_dialog_data_sanitize mtag
221
222	case "$mtag" in
223	URL) setvar $VAR_FTP_PATH "other" ;;
224	*)
225		local value
226		value=$( eval f_dialog_menutag2item \"\$mtag\" $menu_list )
227		setvar $VAR_FTP_PATH "ftp://$value"
228	esac
229	
230	return $SUCCESS
231}
232
233# f_media_set_ftp
234#
235# Return success if we both found and set the media type to be an FTP server.
236# Variables from variable.subr that can be used to script user input:
237#
238# 	VAR_FTP_PATH
239# 		Can be a URL (including "ftp://" protocol-prefix) or "other"
240# 		(user is prompted to enter FTP URL). If a URL, can optionally
241# 		contain directory prefix after hostname/port. Valid examples
242# 		include:
243# 			ftp://myhost
244# 			ftp://somename:21/pub/
245# 			ftp://192.168.2.3/pub/
246# 			ftp://[::1]:21/
247# 		The default port if not specified is 21.
248# 	VAR_NAMESERVER [Optional]
249# 		If set, overrides resolv.conf(5) and sets the nameserver that
250# 		is used to convert names into addresses (when a name converts
251# 		into multiple addresses, the first address to successfully
252# 		connect is used).
253#
254# Meanwhile, the following variables from variable.subr are set after
255# successful execution:
256#
257# 	VAR_FTP_HOST
258# 		The FTP host to connect to, parsed from VAR_FTP_PATH. In the
259# 		example case of IPv6 where VAR_FTP_PATH is "ftp://[::1]", this
260# 		variable will be set to "::1" (the outer brackets are removed).
261# 	VAR_FTP_PORT
262# 		The TCP port to connect to, parsed from VAR_FTP_PATH. Usually
263# 		21 unless VAR_FTP_PATH was of one of the following forms:
264# 			ftp://hostname:OTHER_PORT
265# 			ftp://hostname:OTHER_PORT/*
266# 			ftp://ip:OTHER_PORT
267# 			ftp://ip:OTHER_PORT/*
268# 			ftp://[ip6]:OTHER_PORT
269# 			ftp://[ip6]:OTHER_PORT/*
270# 	VAR_FTP_DIR
271# 		If VAR_FTP_PATH contained a directory element (e.g.,
272# 		"ftp://localhost/pub") this variable contains only the
273# 		directory element (e.g., "/pub").
274#
275f_media_set_ftp()
276{
277	f_media_close
278
279	local url
280	f_getvar $VAR_FTP_PATH url
281
282	# If we've been through here before ...
283	if f_struct device_network && [ "${url#$msg_other}" ]; then
284		f_dialog_yesno "$msg_reuse_old_ftp_site_selection_values" ||
285			url=
286	fi
287
288	if [ ! "$url" ]; then
289		f_dialog_menu_media_ftp || return $FAILURE
290		f_getvar $VAR_FTP_PATH url
291	fi
292	[ "$url" ] || return $FAILURE
293
294	case "$url" in
295	other)
296		setvar $VAR_FTP_PATH "ftp://"
297		f_variable_get_value $VAR_FTP_PATH \
298			"$msg_please_specify_url_of_a_freebsd_distribution"
299		f_getvar $VAR_FTP_PATH url
300		if [ ! "${url#ftp://}" ]; then
301			unset $VAR_FTP_PATH
302			return $FAILURE
303		fi
304		if [ ${#url} -gt ${URL_MAX:-261261} ]; then
305			f_show_msg "$msg_length_of_specified_url_is_too_long" \
306			           ${#url} ${URL_MAX:-261261}
307			unset $VAR_FTP_PATH
308			return $FAILURE
309		fi
310		case "$url" in
311		ftp://*) : valid URL ;;
312		*)
313			f_show_msg "$msg_sorry_invalid_url" "$url"
314			unset $VAR_FTP_PATH
315			return $FAILURE
316		esac
317	esac
318	case "$url" in
319	ftp://*) : valid URL ;;
320	*)
321		f_show_msg "$msg_sorry_invalid_url" "$url"
322		unset $VAR_FTP_PATH
323		return $FAILURE
324	esac
325
326	# Set the name of the FTP device to the URL
327	f_struct_new DEVICE device_ftp
328	device_ftp set name "$url"
329
330	if ! f_struct device_network ||
331	   ! f_dialog_yesno "$msg_youve_already_done_the_network_configuration"
332	then
333		f_struct device_network &&
334			f_device_shutdown network
335		if ! f_device_select_tcp; then
336			unset $VAR_FTP_PATH
337			return $FAILURE
338		fi
339		local dev
340		f_getvar $VAR_NETWORK_DEVICE dev
341		f_struct_copy "device_$dev" device_network
342	fi
343	if ! f_device_init network; then
344		f_dprintf "f_media_set_ftp: %s" "$msg_net_device_init_failed"
345		unset $VAR_FTP_PATH
346		return $FAILURE
347	fi
348
349	local hostname="${url#*://}" port=21 dir=/
350	case "$hostname" in
351	#
352	# The order in-which the below individual cases appear is important!
353	#
354	"["*"]":*/*) # IPv6 address with port and directory
355		f_dprintf "Looks like an IPv6 addr with port/dir: %s" \
356		          "$hostname"
357		hostname="${hostname#\[}"
358		port="${hostname#*\]:}"
359		port="${port%%[!0-9]*}"
360		dir="/${hostname#*/}"
361		hostname="${hostname%%\]:*}"
362		;;
363	"["*"]":*) # IPv6 address with port
364		f_dprintf "Looks like an IPv6 addr with port: %s" "$hostname"
365		hostname="${hostname#\[}"
366		port="${hostname#*\]:}"
367		port="${port%%[!0-9]*}"
368		hostname="${hostname%%\]:*}"
369		;;
370	"["*"]"/*) # IPv6 address with directory
371		f_dprintf "Looks like an IPv6 addr with dir: %s" "$hostname"
372		hostname="${hostname#\[}"
373		dir="/${hostname#*/}"
374		hostname="${hostname%%\]*}"
375		;;
376	"["*"]") # IPv6 address
377		f_dprintf "Looks like an IPv6 addr: %s" "$hostname"
378		hostname="${hostname#\[}"
379		hostname="${hostname%\]}"
380		;;
381	#
382	# ^^^ IPv6 above / DNS Name or IPv4 below vvv
383	#
384	*:*/*) # DNS name or IPv4 address with port and directory
385		f_dprintf "Looks like a %s with port/dir: %s" \
386		          "DNS name or IPv4 addr" "$hostname"
387		port="${hostname#*:}"
388		port="${port%%[!0-9]*}"
389		dir="/${hostname#*/}"
390		hostname="${hostname%%:*}"
391		;;
392	*:*) # DNS name or IPv4 address with port
393		f_dprintf "Looks like a DNS name or IPv4 addr with port: %s" \
394		          "$hostname"
395		port="${hostname#*:}"
396		hostname="${hostname%%:*}"
397		;;
398	*/*) # DNS name or IPv4 address with directory
399		f_dprintf "Looks like a DNS name or IPv4 addr with dir: %s" \
400		          "$hostname"
401		dir="/${hostname#*/}"
402		hostname="${hostname%%/*}"
403		;;
404	*) # DNS name or IPv4 address
405		f_dprintf "Looks like a DNS name or IPv4 addr: %s" "$hostname"
406		: leave hostname as-is
407	esac
408
409	f_dprintf "hostname = \`%s'" "$hostname"
410	f_dprintf "dir = \`%s'" "$dir"
411	f_dprintf "port \# = \`%d'" "$port"
412
413	local ns
414	f_getvar $VAR_NAMESERVER ns
415	[ "$ns" ] || f_resolv_conf_nameservers ns
416	if [ "$ns" -a ! "$FTP_SKIP_RESOLV" ] && ! {
417		f_validate_ipaddr "$hostname" ||
418		f_validate_ipaddr6 "$hostname"
419	}; then
420		f_show_info "$msg_looking_up_host" "$hostname"
421		f_dprintf "%s: Looking up hostname, %s, using host(1)" \
422		          "f_media_set_ftp" "$hostname"
423		if ! f_quietly f_host_lookup "$hostname"; then
424			f_show_msg "$msg_cannot_resolve_hostname" "$hostname"
425			f_struct device_network &&
426				f_device_shutdown network
427			f_struct_free device_network
428			unset $VAR_FTP_PATH
429			return $FAILURE
430		fi
431		f_dprintf "Found DNS entry for %s successfully." "$hostname"
432	fi
433
434	setvar $VAR_FTP_HOST "$hostname"
435	setvar $VAR_FTP_PORT "$port"
436	setvar $VAR_FTP_DIR  "$dir"
437
438	device_ftp set type     $DEVICE_TYPE_FTP
439	device_ftp set init     f_media_init_ftp
440	device_ftp set get      f_media_get_ftp
441	device_ftp set shutdown f_media_shutdown_ftp
442	device_ftp set private  network
443	f_struct_copy device_ftp device_media
444	f_struct_free device_ftp
445
446	return $SUCCESS
447}
448
449# f_media_set_ftp_active
450#
451# Wrapper to f_media_set_ftp to access FTP servers actively.
452#
453f_media_set_ftp_active()
454{
455	setvar $VAR_FTP_STATE "active"
456	f_media_set_ftp
457}
458
459# f_media_set_ftp_passive
460#
461# Wrapper to f_media_set_ftp to access FTP servers passively.
462#
463f_media_set_ftp_passive()
464{
465	setvar $VAR_FTP_STATE "passive"
466	f_media_set_ftp
467}
468
469# f_media_set_ftp_userpass
470#
471# Prompt the user to enter/confirm the username/password variables that will
472# be used to communicate with the FTP servers. Returns success if the user does
473# not cancel or press Esc to either username or password.
474#
475# Variables from variable.subr that can be used to script user input:
476#
477# 	VAR_FTP_USER
478# 		The username to send via ftp(1) when connecting to an FTP
479# 		server.
480# 	VAR_FTP_PASS
481# 		The password to send with the above username.
482#
483# Does not prompt for confirmation of values if VAR_NONINTERACTIVE is set (see
484# variable.subr for more information).
485#
486f_media_set_ftp_userpass()
487{
488	local user pass
489	f_variable_get_value $VAR_FTP_USER \
490		"$msg_please_enter_the_username_you_wish_to_login_as"
491	f_getvar $VAR_FTP_USER user
492	if [ "$user" ]; then
493		f_variable_get_value $VAR_FTP_PASS \
494			"$msg_please_enter_the_password_for_this_user"
495		f_getvar $VAR_FTP_PASS pass
496	else
497		pass=
498	fi
499	[ "$pass" ] # Return status
500}
501
502# f_device_network_up $device
503#
504# Brings up attached network device, if any - takes FTP device as arg.
505#
506f_device_network_up()
507{
508	local dev="$1" netDev
509	f_struct device_$dev || return $FAILURE
510	device_$dev get private netDev || return $SUCCESS # No net == happy net
511	f_device_init $netDev
512}
513
514# f_device_network_down $device
515#
516# Brings down attached network device, if any - takes FTP device as arg.
517#
518f_device_network_down()
519{
520	local dev="$1" netDev
521	f_struct device_$dev || return $FAILURE
522	device_$dev get private netDev || return $SUCCESS
523	f_device_shutdown $netDev
524}
525
526# f_media_init_ftp $device
527#
528# Initializes the FTP media device. Returns success if both able to log into
529# the FTP server and confirm the existence of at least one known release path
530# using ftp(1).
531#
532# Variables from variable.subr used to initialize the connection are as follows
533# (all of which are configured by f_media_set_ftp above):
534#
535# 	VAR_FTP_PATH
536# 		The unparsed FTP URL representing the server to contact.
537# 		Usually "ftp://server" for example. Can contain TCP port number
538# 		and/or directory path (but should not contain username/password
539# 		info).
540# 	VAR_FTP_HOST
541# 		The FTP host to connect to. Can be an IPv4 address (e.g.,
542# 		127.0.0.1), IPv6 address (e.g., ::1), or DNS hostname. Usually
543# 		set automatically in f_media_set_ftp() by parsing VAR_FTP_PATH.
544# 	VAR_FTP_PORT
545# 		The TCP port to connect to. Usually set automatically in
546# 		f_media_set_ftp() by parsing VAR_FTP_PATH.
547# 	VAR_FTP_DIR
548# 		The base FTP directory to use when downloading files from the
549# 		FTP server. Usually set automatically in f_media_set_ftp() by
550# 		parsing VAR_FTP_PATH.
551# 	VAR_FTP_USER [Optional]
552# 		If unset, defaults to using anonymous access.
553# 	VAR_FTP_PASS [Optional]
554# 		If unset, defaults to a sensible value.
555#
556# In addition, the following (managed either manually or by f_media_set_ftp_*):
557#
558# 	VAR_FTP_STATE
559# 		Sets FTPMODE for ftp(1) and can be one of:
560# 			active    active mode FTP only
561# 			auto      automatic determination of passive or active
562# 			          (this is the default)
563# 			gate      gate-ftp mode
564# 			passive   passive mode FTP only
565# 		See ftp(1) for additional information.
566#
567# And last, but not least (managed automatically or manually):
568#
569# 	VAR_RELNAME
570# 		Defaults to being set to $(uname -r) but can be overridden.
571# 		This sets the name of a release to look for as part of a well
572# 		known set of paths to search for release data once connected
573# 		via FTP. If set to "__RELEASE" or "any" then the VAR_FTP_DIR is
574# 		taken as the absolute path to the release and no further
575# 		searching is done (see FTP_DIRS above in the GLOBALS section
576# 		for a list of well known paths that are used when searching for
577# 		a VAR_RELNAME sub-directory).
578#
579f_media_init_ftp()
580{
581	local dev="$1"
582
583	local url
584	device_$dev get name url
585	f_dprintf "Init routine called for FTP device. url=[%s]" "$url"
586
587	if [ "$FTP_INITIALIZED" ]; then
588		f_dprintf "FTP device already initialized."
589		return $SUCCESS
590	fi
591
592	# If we can't initialize the network, bag it!
593	f_device_network_up $dev || return $FAILURE
594
595	local cp
596	while :; do
597		f_getvar $VAR_FTP_PATH cp
598		if [ ! "$cp" ]; then
599			if ! f_media_set_ftp ||
600			   ! f_getvar $VAR_FTP_PATH cp ||
601			   [ ! "$cp" ]
602			then
603				f_show_msg "$msg_unable_to_get_proper_ftp_path"
604				f_device_network_down $dev
605				return $FAILURE
606			fi
607		fi
608
609		local ftp_host ftp_dir
610		if ! {
611			f_getvar $VAR_FTP_HOST ftp_host &&
612			f_getvar $VAR_FTP_DIR ftp_dir
613		}; then
614			f_show_msg "$msg_missing_ftp_host_or_directory"
615			f_device_network_down $dev
616			return $FAILURE
617		fi
618
619		local ftp_port
620		f_getvar $VAR_FTP_PORT ftp_port
621		local host="$ftp_host" port="${ftp_port:+:$ftp_port}"
622		case "$host" in *:*) host="[$host]"; esac
623
624		local user pass use_anon=
625		f_getvar $VAR_FTP_USER user
626		if [ ! "$user" ]; then
627			user="anonymous"
628			use_anon=1
629		fi
630		if ! f_getvar $VAR_FTP_PASS pass; then
631			f_getvar $VAR_HOSTNAME cp
632			if f_running_as_init; then
633				pass="installer@$cp"
634			else
635				local name="$( id -un 2> /dev/null )"
636				pass="${name:-ftp}@$cp"
637			fi
638		fi
639
640		f_show_info "$msg_logging_in_to_user_at_host" \
641		            "$user" "$ftp_host"
642
643		local userpass=""
644		if [ ! "$use_anon" ] && [ "$user" -o "$pass" ]; then
645			userpass="$user${pass:+:$( f_uriencode "$pass" )}"
646			userpass="$userpass${userpass:+@}"
647		fi
648
649		local mode rx
650		f_getvar $VAR_FTP_STATE mode
651
652		if [ "$ftp_dir" ]; then
653			if ! rx=$(
654				printf 'cd "%s"\npwd\n' "$ftp_dir" | eval \
655					FTPMODE=\"\$mode\" \
656					${use_anon:+FTPANONPASS=\"\$pass\"} \
657					ftp -V ${use_anon:+-a} \
658					    \"ftp://\$userpass\$host\$port\" \
659				2>&1
660			); then
661				f_show_msg "$msg_couldnt_open_ftp_connection" \
662				           "$ftp_host" "$rx"
663				break # to failure
664			fi
665			if echo "$rx" | awk -v dir="/${ftp_dir#/}" '
666				BEGIN {
667					found = 0
668					if ( dir != "/" ) sub("/$", "", dir)
669				}
670				/^Remote directory: / {
671					sub(/^[^:]*:[[:space:]]*/, "")
672					if ($0 != dir) next
673					found = 1; exit
674				}
675				END { exit ! found }
676			'; then
677				setvar $VAR_FTP_DIR "$ftp_dir"
678				setvar $VAR_FTP_PATH \
679					"ftp://$ftp_host/${ftp_dir#/}"
680			else
681				f_show_msg \
682				    "$msg_please_check_the_url_and_try_again" \
683				    "ftp://$ftp_host/${ftp_dir#/}"
684				break # to failure
685			fi
686		fi
687
688		#
689		# Now that we've verified that the path we're given is ok,
690		# let's try to be a bit intelligent in locating the release we
691		# are looking for.  First off, if the release is specified as
692		# "__RELEASE" or "any", then just assume that the current
693		# directory is the one we want and give up.
694		#
695		local rel
696		f_getvar $VAR_RELNAME rel
697		f_dprintf "f_media_init_ftp: rel=[%s]" "$rel"
698
699		case "$rel" in
700		__RELEASE|any)
701			FTP_INITIALIZED=YES
702			return $SUCCESS
703			;;
704		*)
705			#
706			# Ok, since we have a release variable, let's walk
707			# through the list of directories looking for a release
708			# directory. First successful CWD wins.
709			#
710			if ! rx=$(
711				for dir in $FTP_DIRS; do
712					# Avoid confusing some servers
713					[ "$dir" = "." ] && continue
714					printf 'cd "/%s/%s"\npwd\n' \
715					       "$dir" "$rel"
716				done | eval \
717					FTPMODE=\"\$mode\" \
718					${use_anon:+FTPANONPASS=\"\$pass\"} \
719					ftp -V ${use_anon:+-a} \
720					    \"ftp://\$userpass\$host\$port\" \
721				2>&1
722			); then
723				f_show_msg "$msg_couldnt_open_ftp_connection" \
724				           "$ftp_host" "$rx"
725				break # to failure
726			fi
727
728			local fdir
729			if fdir=$( echo "$rx" | awk '
730				BEGIN { found = 0 }
731				/^Remote directory: / {
732					sub(/^[^:]*:[[:space:]]*/, "")
733					if ($0 == "/") next
734					# Exit after the first dir
735					found++; print; exit
736				}
737				END { exit ! found }
738			' ); then
739				setvar $VAR_FTP_DIR "$fdir"
740				setvar $VAR_FTP_PATH "ftp://$ftp_host$fdir"
741				FTP_INITIALIZED=YES
742				return $SUCCESS
743			else
744				f_yesno "$msg_cant_find_distribution" \
745				        "$rel" "$ftp_host"
746				if [ $? -eq $SUCCESS ]; then
747					unset $VAR_FTP_PATH
748					f_media_set_ftp && continue
749				fi
750			fi
751		esac
752		break # to failure
753	done
754
755	unset FTP_INITIALIZED $VAR_FTP_PATH
756	f_device_network_down $dev
757	return $FAILURE
758}
759
760# f_media_get_ftp $device $file [$probe_type]
761#
762# Returns data from $file on an FTP server using ftp(1). Please note that
763# $device is unused but must be present (even if null). Information is instead
764# gathered from the environment. If $probe_type is present and non-NULL,
765# returns success if $file exists. If $probe_type is equal to $PROBE_SIZE,
766# prints the size of $file in bytes to standard-out.
767#
768# Variables from variable.subr used to configure the connection are as follows
769# (all of which are configured by f_media_set_ftp above):
770#
771# 	VAR_FTP_HOST
772# 		FTP host to connect to. Can be an IPv4 address, IPv6 address,
773# 		or DNS hostname of your choice.
774# 	VAR_FTP_PORT
775# 		TCP port to connect on; see f_media_set_ftp() above.
776# 	VAR_FTP_USER [Optional]
777# 		If unset, defaults to using anonymous access.
778# 	VAR_FTP_PASS [Optional]
779# 		If unset, defaults to a sensible value.
780#
781# In addition, the following (managed either manually or by f_media_set_ftp_*):
782#
783# 	VAR_FTP_STATE
784# 		Sets FTPMODE for ftp(1) and can be one of:
785# 			active    active mode FTP only
786# 			auto      automatic determination of passive or active
787# 			          (this is the default)
788# 			gate      gate-ftp mode
789# 			passive   passive mode FTP only
790# 		See ftp(1) for additional information.
791#
792# See variable.subr for additional information.
793#
794# Example usage:
795# 	f_media_set_ftp
796# 	f_media_get_ftp media $file
797#
798f_media_get_ftp()
799{
800	local dev="$1" file="$2" probe_type="$3" hosts=
801
802	f_dprintf "f_media_get_ftp: dev=[%s] file=[%s] probe_type=%s" \
803	          "$dev" "$file" "$probe_type"
804
805	local ftp_host ftp_port
806	f_getvar $VAR_FTP_HOST ftp_host
807	f_getvar $VAR_FTP_PORT ftp_port
808
809	if [ ! "$FTP_INITIALIZED" ]; then
810		f_dprintf "No FTP connection open, can't get file %s" "$file"
811		return $FAILURE
812	fi
813
814	if ! {
815		f_validate_ipaddr "$ftp_host" ||
816		f_validate_ipaddr6 "$ftp_host" ||
817		{
818		  f_dprintf "%s: Looking up hostname, %s, using host(1)" \
819		            "f_media_get_ftp" "$ftp_host"
820		  f_host_lookup "$ftp_host" hosts
821		}
822	}; then
823		# All the above validations failed
824		[ "$hosts" ] && f_dialog_msgbox "$hosts"
825		return $FAILURE
826	elif [ ! "$hosts" ]; then
827		# One of the first two validations passed
828		hosts="$ftp_host"
829	fi
830
831	local host connected=
832	for host in $hosts; do
833		f_quietly nc -nz "$host" "$ftp_port" || continue
834		connected=1; break
835	done
836	if [ ! "$connected" ]; then
837		f_show_msg "$msg_couldnt_connect_to_ftp_server %s:%s" \
838		           "$ftp_host" "$ftp_port"
839		return $FAILURE
840	fi
841
842	local user pass use_anon=
843	f_getvar $VAR_FTP_USER user
844	if [ ! "$user" ]; then
845		user="anonymous"
846		use_anon=1
847	fi
848	if ! f_getvar $VAR_FTP_PASS pass; then
849		f_getvar $VAR_HOSTNAME cp
850		if f_running_as_init; then
851			pass="installer@$cp"
852		else
853			local name="$( id -un 2> /dev/null )"
854			pass="${name:-ftp}@$cp"
855		fi
856	fi
857
858	local userpass=""
859	if [ ! "$use_anon" ] && [ "$user" -o "$pass" ]; then
860		userpass="$user${pass:+:$( f_uriencode "$pass" )}"
861		userpass="$userpass${userpass:+@}"
862	fi
863
864	local dir mode rx
865	f_getvar $VAR_FTP_DIR\#/ dir
866	f_getvar $VAR_FTP_STATE mode
867
868	local port="${ftp_port:+:$ftp_port}"
869	case "$host" in *:*) host="[$host]"; esac
870
871	f_dprintf "sending ftp request for: %s" "ftp://$host$port/$dir/$file"
872
873	if [ "$probe_type" ]; then
874		local url="ftp://$userpass$host$port/$dir/$file" size
875		[ "$use_anon" ] && url="ftp://$host$port/$dir/$file"
876		if ! size=$( fetch -s "$url" 2>&1 ) || ! f_isinteger "$size"
877		then
878			f_dprintf "request failed! size response=[%s]" "$size"
879			[ "$probe_type" = "$PROBE_SIZE" ] && echo "-1"
880			return $FAILURE
881		fi
882		[ "$probe_type" = "$PROBE_SIZE" ] && echo "$size"
883		return $SUCCESS
884	fi
885
886	eval FTPMODE=\"\$mode\" ${use_anon:+FTPANONPASS=\"\$pass\"} \
887	     ftp -V ${use_anon:+-a} -o - \
888	     	\"ftp://\$userpass\$host\$port/\$dir/\$file\" 2> /dev/null
889	local retval=$?
890
891	[ $retval -eq $SUCCESS ] || f_dprintf "request failed!"
892	return $retval
893}
894
895# f_media_shutdown_ftp $device
896#
897# Shuts down the FTP device. Return status should be ignored. Note that since
898# we don't maintain an open connection to the FTP server there's nothing to do.
899#
900f_media_shutdown_ftp()
901{
902	[ "$FTP_INITIALIZED" ] || return $SUCCESS
903
904	unset FTP_INITIALIZED
905}
906
907############################################################ MAIN
908
909f_dprintf "%s: Successfully loaded." media/ftp.subr
910
911fi # ! $_MEDIA_FTP_SUBR
912