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