Reconstruction of cosmic and beam-halo muons with the CMS detector