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