Density functional theory in the canonical ensemble: I. General formalism