Tristan Stubbs and Temba Bavuma hit centuries to put South Africa in an impregnable position before their bowlers dismissed five Sri Lankan batsmen.