summaryrefslogtreecommitdiff
path: root/src/share/m/update_known_hosts
blob: d167ae011b1297e947bc966dddf2fea15df79995 (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 returnCode=0
  16. local fileCheck
  17. local host
  18. # touch the known_hosts file so that the file permission check
  19. # below won't fail upon not finding the file
  20. touch_key_file_or_fail "$KNOWN_HOSTS"
  21. check_key_file_permissions $(whoami) "$KNOWN_HOSTS" \
  22. || failure "Bad permissions governing known_hosts file $KNOWN_HOSTS"
  23. lock create "$KNOWN_HOSTS"
  24. # FIXME: we're discarding any pre-existing EXIT trap; is this bad?
  25. trap "log debug TRAP; lock remove $KNOWN_HOSTS" EXIT
  26. tmpFile=$(mktemp "${KNOWN_HOSTS}.monkeysphere.XXXXXX")
  27. trap "log debug TRAP; lock remove $KNOWN_HOSTS; rm -f $tmpFile" EXIT
  28. cat "$KNOWN_HOSTS" >"$tmpFile"
  29. for host ; do
  30. FILE_TYPE='known_hosts' process_keys_for_file "$tmpFile" "ssh://${host}"
  31. lock touch "$KNOWN_HOSTS"
  32. done
  33. if [ "$(file_hash "$KNOWN_HOSTS")" != "$(file_hash "$tmpFile")" ] ; then
  34. mv -f "$tmpFile" "$KNOWN_HOSTS"
  35. log debug "known_hosts file updated."
  36. else
  37. rm -f "$tmpFile"
  38. fi
  39. lock remove "$KNOWN_HOSTS"
  40. trap - EXIT
  41. }
  42. # process hosts from a known_hosts file
  43. process_known_hosts() {
  44. local hosts
  45. if [ ! -e "$KNOWN_HOSTS" ] ; then
  46. failure "known_hosts file '$KNOWN_HOSTS' does not exist."
  47. fi
  48. log debug "processing known_hosts file:"
  49. log debug " $KNOWN_HOSTS"
  50. hosts=$(meat "$KNOWN_HOSTS" | cut -d ' ' -f 1 | grep -v '^|.*$' | tr , ' ' | tr '\n' ' ')
  51. if [ -z "$hosts" ] ; then
  52. log debug "no hosts to process."
  53. return
  54. fi
  55. # take all the hosts from the known_hosts file (first
  56. # field), grep out all the hashed hosts (lines starting
  57. # with '|')...
  58. update_known_hosts $hosts
  59. }