Ab initio theory of superconductivity. I. Density functional formalism and approximate functionals