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