fix variable declaration (leftover from break out of touch_key_file_or_fail)
[monkeysphere.git] / src / share / m / update_known_hosts
1 # -*-shell-script-*-
2 # This should be sourced by bash (though we welcome changes to make it POSIX sh compliant)
3
4 # Monkeysphere update_known_hosts subcommand
5 #
6 # The monkeysphere scripts are written by:
7 # Jameson Rollins <jrollins@finestructure.net>
8 # Jamie McClelland <jm@mayfirst.org>
9 # Daniel Kahn Gillmor <dkg@fifthhorseman.net>
10 #
11 # They are Copyright 2010, and are all released under the GPL, version
12 # 3 or later.
13
14 # update the known_hosts file for a set of hosts listed on command
15 # line
16 update_known_hosts() {
17     local returnCode=0
18     local fileCheck
19     local host
20
21     # touch the known_hosts file so that the file permission check
22     # below won't fail upon not finding the file
23     touch_key_file_or_fail "$KNOWN_HOSTS"
24     check_key_file_permissions $(whoami) "$KNOWN_HOSTS" \
25         || failure "Bad permissions governing known_hosts file $KNOWN_HOSTS"
26
27     lock create "$KNOWN_HOSTS"
28
29     # FIXME: we're discarding any pre-existing EXIT trap; is this bad?
30     trap "log debug TRAP; lock remove $KNOWN_HOSTS" EXIT
31
32     tmpFile=$(mktemp "${KNOWN_HOSTS}.monkeysphere.XXXXXX")
33
34     trap "log debug TRAP; lock remove $KNOWN_HOSTS; rm -f $tmpFile" EXIT
35
36     cat "$KNOWN_HOSTS" >"$tmpFile"
37
38     for host ; do
39         FILE_TYPE='known_hosts' process_keys_for_file "$tmpFile" "ssh://${host}"
40
41         lock touch "$KNOWN_HOSTS"
42     done
43
44     if [ "$(file_hash "$KNOWN_HOSTS")" != "$(file_hash "$tmpFile")" ] ; then
45         mv -f "$tmpFile" "$KNOWN_HOSTS"
46         log debug "known_hosts file updated."
47     else
48         rm -f "$tmpFile"
49     fi
50
51     lock remove "$KNOWN_HOSTS"
52
53     trap - EXIT
54 }
55
56 # process hosts from a known_hosts file
57 process_known_hosts() {
58     local hosts
59
60     if [ ! -e "$KNOWN_HOSTS" ] ; then
61         failure "known_hosts file '$KNOWN_HOSTS' does not exist."
62     fi
63
64     log debug "processing known_hosts file:"
65     log debug " $KNOWN_HOSTS"
66
67     hosts=$(meat "$KNOWN_HOSTS" | cut -d ' ' -f 1 | grep -v '^|.*$' | tr , ' ' | tr '\n' ' ')
68
69     if [ -z "$hosts" ] ; then
70         log debug "no hosts to process."
71         return
72     fi
73
74     # take all the hosts from the known_hosts file (first
75     # field), grep out all the hashed hosts (lines starting
76     # with '|')...
77     update_known_hosts $hosts
78 }