Indonesia and Malaysia have agreed to give temporary shelter to thousands of migrants stranded at sea.