ftp.subr revision 247280
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 247280 2013-02-25 19:55:32Z 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 size
233	size=$( eval f_dialog_menu_size \
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\" $size       \
248		$menu_list                      \
249		2>&1 >&$DIALOG_TERMINAL_PASSTHRU_FD
250	)
251	retval=$?
252	setvar DIALOG_MENU_$$ "$dialog_menu"
253	mtag=$( f_dialog_menutag )
254
255	[ $retval -eq 0 ] || return $FAILURE
256
257	case "$mtag" in
258	URL) setvar $VAR_FTP_PATH "other" ;;
259	*)
260		value=$( eval f_dialog_menutag2item \"\$mtag\" $menu_list )
261		setvar $VAR_FTP_PATH "ftp://$value"
262	esac
263	
264	return $SUCCESS
265}
266
267# f_media_set_ftp
268#
269# Return success if we both found and set the media type to be an FTP server.
270# Variables from variable.subr that can be used to script user input:
271#
272# 	VAR_FTP_PATH
273# 		Can be a URL (including "ftp://" protocol-prefix) or "other"
274# 		(user is prompted to enter FTP URL). If a URL, can optionally
275# 		contain directory prefix after hostname/port. Valid examples
276# 		include:
277# 			ftp://myhost
278# 			ftp://somename:21/pub/
279# 			ftp://192.168.2.3/pub/
280# 			ftp://[::1]:21/
281# 		The default port if not specified is 21.
282# 	VAR_NAMESERVER [Optional]
283# 		If set, overrides resolv.conf(5) and sets the nameserver that
284# 		is used to convert names into addresses (when a name converts
285# 		into multiple addresses, the first address to successfully
286# 		connect is used).
287#
288# Meanwhile, the following variables from variable.subr are set after
289# successful execution:
290#
291# 	VAR_FTP_HOST
292# 		The FTP host to connect to, parsed from VAR_FTP_PATH. In the
293# 		example case of IPv6 where VAR_FTP_PATH is a "ftp://[::1]" this
294# 		variable will be set to "::1" (the outer brackets are removed).
295# 	VAR_FTP_PORT
296# 		The TCP port to connect to, parsed from VAR_FTP_PATH. Usually
297# 		21 unless VAR_FTP_PATH was of one of the following forms:
298# 			ftp://hostname:OTHER_PORT
299# 			ftp://hostname:OTHER_PORT/*
300# 			ftp://ip:OTHER_PORT
301# 			ftp://ip:OTHER_PORT/*
302# 			ftp://[ip6]:OTHER_PORT
303# 			ftp://[ip6]:OTHER_PORT/*
304# 	VAR_FTP_DIR
305# 		If VAR_FTP_PATH contained a directory element (e.g.,
306# 		"ftp://localhost/pub") this variable contains only the
307# 		directory element (e.g., "/pub").
308#
309f_media_set_ftp()
310{
311	f_media_close
312
313	local url
314	f_getvar $VAR_FTP_PATH url
315
316	# If we've been through here before ...
317	if f_struct device_network && [ "${url#$msg_other}" ]; then
318		f_dialog_yesno "$msg_reuse_old_ftp_site_selection_values" ||
319			url=
320	fi
321
322	if [ ! "$url" ]; then
323		f_dialog_menu_media_ftp || return $FAILURE
324		f_getvar $VAR_FTP_PATH url
325	fi
326	[ "$url" ] || return $FAILURE
327
328	case "$url" in
329	other)
330		setvar $VAR_FTP_PATH "ftp://"
331		f_variable_get_value $VAR_FTP_PATH \
332			"$msg_please_specify_url_of_a_freebsd_distribution"
333		f_getvar $VAR_FTP_PATH url
334		if [ ! "${url#ftp://}" ]; then
335			unset $VAR_FTP_PATH
336			return $FAILURE
337		fi
338		if [ ${#url} -gt ${URL_MAX:-261261} ]; then
339			f_show_msg "$msg_length_of_specified_url_is_too_long" \
340			           ${#url} ${URL_MAX:-261261}
341			unset $VAR_FTP_PATH
342			return $FAILURE
343		fi
344		case "$url" in
345		ftp://*) : valid URL ;;
346		*)
347			f_show_msg "$msg_sorry_invalid_url" "$url"
348			unset $VAR_FTP_PATH
349			return $FAILURE
350		esac
351	esac
352	case "$url" in
353	ftp://*) : valid URL ;;
354	*)
355		f_show_msg "$msg_sorry_invalid_url" "$url"
356		unset $VAR_FTP_PATH
357		return $FAILURE
358	esac
359
360	# Set the name of the FTP device to the URL
361	f_struct_new DEVICE device_ftp
362	device_ftp set name "$url"
363
364	if ! f_struct device_network ||
365	   ! f_dialog_yesno "$msg_youve_already_done_the_network_configuration"
366	then
367		f_struct device_network &&
368			f_device_shutdown network
369		if ! f_device_select_tcp; then
370			unset $VAR_FTP_PATH
371			return $FAILURE
372		fi
373		local dev
374		f_getvar $VAR_NETWORK_DEVICE dev
375		f_struct_copy "device_$dev" device_network
376	fi
377	if ! f_device_init network; then
378		f_dprintf "f_media_set_ftp: %s" "$msg_net_device_init_failed"
379		unset $VAR_FTP_PATH
380		return $FAILURE
381	fi
382
383	local hostname="${url#*://}" port=21 dir=/
384	case "$hostname" in
385	"["*"]")
386		hostname="${hostname#\[}"
387		hostname="${hostname%%\]*}"
388		;;
389	"["*"]/"*)
390		hostname="${hostname#\[}"
391		dir="/${hostname#*/}"
392		hostname="${hostname%%\]*}"
393		;;
394	*"/"*)
395		dir="/${hostname#*/}"
396		hostname="${hostname%%/*}"
397		;;
398	"["*"]:"*)
399		hostname="${hostname#\[}"
400		port="${hostname#*\]:}"
401		port="${port%%[!0-9]*}"
402		hostname="${hostname%%\]:*}"
403		;;
404	*)
405		hostname="${hostname%%/*}"
406	esac
407
408	f_dprintf "hostname = \`%s'" "$hostname"
409	f_dprintf "dir = \`%s'" "$dir"
410	f_dprintf "port \# = \`%d'" "$port"
411
412	local ns
413	f_getvar $VAR_NAMESERVER ns
414	[ "$ns" ] || f_resolv_conf_nameservers ns
415	if [ "$ns" -a ! "$FTP_SKIP_RESOLV" ] && ! {
416		f_validate_ipaddr "$hostname" ||
417		f_validate_ipaddr6 "$hostname"
418	}; then
419		f_show_info "$msg_looking_up_host" "$hostname"
420		f_dprintf "%s: Looking up hostname, %s, using host(1)" \
421		          "f_media_set_ftp" "$hostname"
422		if ! f_quietly f_host_lookup "$hostname"; then
423			f_show_msg "$msg_cannot_resolve_hostname" "$hostname"
424			f_struct device_network &&
425				f_device_shutdown network
426			f_struct_free device_network
427			unset $VAR_FTP_PATH
428			return $FAILURE
429		fi
430		f_dprintf "Found DNS entry for %s successfully." "$hostname"
431	fi
432
433	setvar $VAR_FTP_HOST "$hostname"
434	setvar $VAR_FTP_PORT "$port"
435	setvar $VAR_FTP_DIR  "$dir"
436
437	device_ftp set type     $DEVICE_TYPE_FTP
438	device_ftp set init     f_media_init_ftp
439	device_ftp set get      f_media_get_ftp
440	device_ftp set shutdown f_media_shutdown_ftp
441	device_ftp set private  network
442	f_struct_copy device_ftp device_media
443	f_struct_free device_ftp
444
445	return $SUCCESS
446}
447
448# f_media_set_ftp_active
449#
450# Wrapper to f_media_set_ftp to access FTP servers actively.
451#
452f_media_set_ftp_active()
453{
454	setvar $VAR_FTP_STATE "active"
455	f_media_set_ftp
456}
457
458# f_media_set_ftp_passive
459#
460# Wrapper to f_media_set_ftp to access FTP servers passively.
461#
462f_media_set_ftp_passive()
463{
464	setvar $VAR_FTP_STATE "passive"
465	f_media_set_ftp
466}
467
468# f_media_set_ftp_userpass
469#
470# Prompt the user to enter/confirm the username/password variables that will
471# be used to communicate with the FTP servers. Returns success if the user does
472# not cancel or press Esc to either username or password.
473#
474# Variables from variable.subr that can be used to script user input:
475#
476# 	VAR_FTP_USER
477# 		The username to send via ftp(1) when connecting to an FTP
478# 		server.
479# 	VAR_FTP_PASS
480# 		The password to send with the above username.
481#
482# Does not prompt for confirmation of values if VAR_NONINTERACTIVE is set (see
483# variable.subr for more information).
484#
485f_media_set_ftp_userpass()
486{
487	local user pass
488	f_variable_get_value $VAR_FTP_USER \
489		"$msg_please_enter_the_username_you_wish_to_login_as"
490	f_getvar $VAR_FTP_USER user
491	if [ "$user" ]; then
492		f_variable_get_value $VAR_FTP_PASS \
493			"$msg_please_enter_the_password_for_this_user"
494		f_getvar $VAR_FTP_PASS pass
495	else
496		pass=
497	fi
498	[ "$pass" ] # Return status
499}
500
501# f_device_network_up $device
502#
503# Brings up attached network device, if any - takes FTP device as arg.
504#
505f_device_network_up()
506{
507	local dev="$1" netDev
508	device_$dev get private netDev || return $SUCCESS # No net == happy net
509	f_device_init $netDev
510}
511
512# f_device_network_down $device
513#
514# Brings down attached network device, if any - takes FTP device as arg.
515#
516f_device_network_down()
517{
518	local dev="$1" netDev
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_dialog_msgbox \
601					"$msg_unable_to_get_proper_ftp_path"
602				f_device_network_down $dev
603				return $FAILURE
604			fi
605		fi
606
607		local ftp_host ftp_dir
608		if ! {
609			f_getvar $VAR_FTP_HOST ftp_host &&
610			f_getvar $VAR_FTP_DIR ftp_dir
611		}; then
612			f_dialog_msgbox "$msg_missing_ftp_host_or_directory"
613			f_device_network_down $dev
614			return $FAILURE
615		fi
616
617		local ftp_port
618		f_getvar $VAR_FTP_PORT ftp_port
619		local host="$ftp_host" port="${ftp_port:+:$ftp_port}"
620		case "$host" in *:*) host="[$host]"; esac
621
622		local user pass use_anon=""
623		f_getvar $VAR_FTP_USER user
624		if [ ! "$user" ]; then
625			user="anonymous"
626			use_anon=1
627		fi
628		if ! f_getvar $VAR_FTP_PASS pass; then
629			f_getvar $VAR_HOSTNAME cp
630			if f_running_as_init; then
631				pass="installer@$cp"
632			else
633				local name="$( id -un 2> /dev/null )"
634				pass="${name:-ftp}@$cp"
635			fi
636		fi
637
638		f_show_info "$msg_logging_in_to_user_at_host" \
639		            "$user" "$ftp_host"
640
641		local userpass=""
642		if [ ! "$use_anon" ] && [ "$user" -o "$pass" ]; then
643			userpass="$user${pass:+:$( f_uriencode "$pass" )}"
644			userpass="$userpass${userpass:+@}"
645		fi
646
647		local mode rx
648		f_getvar $VAR_FTP_STATE mode
649
650		if [ "$ftp_dir" ]; then
651			if ! rx=$(
652				printf 'cd "%s"\npwd\n' "$ftp_dir" | eval \
653					FTPMODE=\"\$mode\" \
654					${use_anon:+FTPANONPASS=\"\$pass\"} \
655					ftp -V ${use_anon:+-a} \
656					    \"ftp://\$userpass\$host\$port\" \
657				2>&1
658			); then
659				f_show_msg "$msg_couldnt_open_ftp_connection" \
660				           "$ftp_host" "$rx"
661				break # to failure
662			fi
663			if echo "$rx" | awk -v dir="/${ftp_dir#/}" '
664				BEGIN { found = 0 }
665				/^Remote directory: / {
666					sub(/^[^:]*:[[:space:]]*/, "")
667					if ($0 != dir) next
668					found = 1; exit
669				}
670				END { exit ! found }
671			'; then
672				setvar $VAR_FTP_DIR "$ftp_dir"
673				setvar $VAR_FTP_PATH \
674					"ftp://$ftp_host/${ftp_dir#/}"
675			else
676				f_show_msg \
677				    "$msg_please_check_the_url_and_try_again" \
678				    "ftp://$ftp_host/${ftp_dir#/}"
679				break # to failure
680			fi
681		fi
682
683		#
684		# Now that we've verified that the path we're given is ok,
685		# let's try to be a bit intelligent in locating the release we
686		# are looking for.  First off, if the release is specified as
687		# "__RELEASE" or "any", then just assume that the current
688		# directory is the one we want and give up.
689		#
690		local rel
691		f_getvar $VAR_RELNAME rel
692		f_dprintf "f_media_init_ftp: rel=[%s]" "$rel"
693
694		case "$rel" in
695		__RELEASE|any)
696			FTP_INITIALIZED=YES
697			return $SUCCESS
698			;;
699		*)
700			#
701			# Ok, since we have a release variable, let's walk
702			# through the list of directories looking for a release
703			# directory. First successful CWD wins.
704			#
705			if ! rx=$(
706				for dir in $FTP_DIRS; do
707					# Avoid confusing some servers
708					[ "$dir" = "." ] && continue
709					printf 'cd "/%s/%s"\npwd\n' \
710					       "$dir" "$rel"
711				done | eval \
712					FTPMODE=\"\$mode\" \
713					${use_anon:+FTPANONPASS=\"\$pass\"} \
714					ftp -V ${use_anon:+-a} \
715					    \"ftp://\$userpass\$host\$port\" \
716				2>&1
717			); then
718				f_show_msg "$msg_couldnt_open_ftp_connection" \
719				           "$ftp_host" "$rx"
720				break # to failure
721			fi
722
723			local fdir
724			if fdir=$( echo "$rx" | awk '
725				BEGIN { found = 0 }
726				/^Remote directory: / {
727					sub(/^[^:]*:[[:space:]]*/, "")
728					if ($0 == "/") next
729					# Exit after the first dir
730					found++; print; exit
731				}
732				END { exit ! found }
733			' ); then
734				setvar $VAR_FTP_DIR "$fdir"
735				setvar $VAR_FTP_PATH "ftp://$ftp_host$fdir"
736				FTP_INITIALIZED=YES
737				return $SUCCESS
738			else
739				f_yesno "$msg_cant_find_distribution" \
740				        "$rel" "$ftp_host"
741				if [ $? -eq $SUCCESS ]; then
742					unset $VAR_FTP_PATH
743					f_media_set_ftp && continue
744				fi
745			fi
746		esac
747		break # to failure
748	done
749
750	unset FTP_INITIALIZED $VAR_FTP_PATH
751	f_device_network_down $dev
752	return $FAILURE
753}
754
755# f_media_get_ftp $device $file [$probe_only]
756#
757# Returns data from $file on an FTP server using ftp(1). Please note that
758# $device is unused but must be present (even if null). Information is instead
759# gathered from the environment. $probe_only is currently unused by this media
760# type.
761#
762# Variables from variable.subr used to configure the connection are as follows
763# (all of which are configured by f_media_set_ftp above):
764#
765# 	VAR_FTP_HOST
766# 		FTP host to connect to. Can be an IPv4 address, IPv6 address,
767# 		or DNS hostname of your choice.
768# 	VAR_FTP_PORT
769# 		TCP port to connect on; see f_media_set_ftp() above.
770# 	VAR_FTP_USER [Optional]
771# 		If unset, defaults to using anonymous access.
772# 	VAR_FTP_PASS [Optional]
773# 		If unset, defaults to a sensible value.
774#
775# In addition, the following (managed either manually or by f_media_set_ftp_*):
776#
777# 	VAR_FTP_STATE
778# 		Sets FTPMODE for ftp(1) and can be one of:
779# 			active    active mode FTP only
780# 			auto      automatic determination of passive or active
781# 			          (this is the default)
782# 			gate      gate-ftp mode
783# 			passive   passive mode FTP only
784# 		See ftp(1) for additional information.
785#
786# See variable.subr for additional information.
787#
788# Example usage:
789# 	f_media_set_ftp
790# 	f_media_get_ftp media $file
791#
792f_media_get_ftp()
793{
794	local dev="$1" file="$2" probe_only="$3"
795
796	f_dprintf "f_media_get_ftp: dev=[%s] file=[%s] probe_only=%s" \
797	          "$dev" "$file" "$probe_only"
798
799	local ftp_host ftp_port
800	f_getvar $VAR_FTP_HOST ftp_host
801	f_getvar $VAR_FTP_PORT ftp_port
802
803	if [ ! "$FTP_INITIALIZED" ]; then
804		f_dprintf "No FTP connection open, can't get file %s" "$file"
805		return $FAILURE
806	fi
807
808	if ! {
809		f_validate_ipaddr "$ftp_host" ||
810		f_validate_ipaddr6 "$ftp_host" ||
811		{
812		  f_dprintf "%s: Looking up hostname, %s, using host(1)" \
813		            "f_media_get_ftp" "$ftp_host"
814		  f_host_lookup "$ftp_host" hosts
815		}
816	}; then
817		# All the above validations failed
818		[ "$hosts" ] && f_dialog_msgbox "$hosts"
819		return $FAILURE
820	elif [ ! "$hosts" ]; then
821		# One of the first two validations passed
822		hosts="$ftp_host"
823	fi
824
825	local host connected=
826	for host in $hosts; do
827		f_quietly nc -nz "$host" "$ftp_port" || continue
828		connected=1; break
829	done
830	if [ ! "$connected" ]; then
831		f_show_msg "$msg_couldnt_connect_to_ftp_server %s:%s" \
832		           "$ftp_host" "$ftp_port"
833		return $FAILURE
834	fi
835
836	local user pass use_anon=""
837	f_getvar $VAR_FTP_USER user
838	if [ ! "$user" ]; then
839		user="anonymous"
840		use_anon=1
841	fi
842	if ! f_getvar $VAR_FTP_PASS pass; then
843		f_getvar $VAR_HOSTNAME cp
844		if f_running_as_init; then
845			pass="installer@$cp"
846		else
847			local name="$( id -un 2> /dev/null )"
848			pass="${name:-ftp}@$cp"
849		fi
850	fi
851
852	local userpass=""
853	if [ ! "$use_anon" ] && [ "$user" -o "$pass" ]; then
854		userpass="$user${pass:+:$( f_uriencode "$pass" )}"
855		userpass="$userpass${userpass:+@}"
856	fi
857
858	local ftp_dir mode rx
859	f_getvar $VAR_FTP_DIR ftp_dir
860	f_getvar $VAR_FTP_STATE mode
861
862	local dir="${ftp_dir#/}"
863	local port="${ftp_port:+:$ftp_port}"
864	case "$host" in *:*) host="[$host]"; esac
865
866	f_dprintf "sending ftp request for: %s" "ftp://$host$port/$dir/$file"
867
868	eval FTPMODE=\"\$mode\" ${use_anon:+FTPANONPASS=\"\$pass\"} \
869	     ftp -V ${use_anon:+-a} -o - \
870	     	\"ftp://\$userpass\$host\$port/\$dir/\$file\" 2> /dev/null
871	local retval=$?
872
873	[ $retval -eq $SUCCESS ] || f_dprintf "request failed!"
874	return $retval
875}
876
877# f_media_shutdown_ftp $device
878#
879# Shuts down the FTP device. Return status should be ignored. Note that since
880# we don't maintain an open connection to the FTP server there's nothing to do.
881#
882f_media_shutdown_ftp()
883{
884	[ "$FTP_INITIALIZED" ] || return $SUCCESS
885
886	unset FTP_INITIALIZED
887}
888
889############################################################ MAIN
890
891f_dprintf "%s: Successfully loaded." media/ftp.subr
892
893fi # ! $_MEDIA_FTP_SUBR
894