Some dogs will commonly get ear infections.
Some vets recommend that you give him an aspirin to control pain. You can get the dosage information here:
Aspirin Info
You will need to see the vet. It sounds like he has a severe ear infection and might even have a hematoma if the ear flap is sticking out like a pillow. If he doesn't have a hematoma yet, he might soon get one because the head shaking will commonly cause a blood vessel to burst in the ear. This requires surgery to fix so you will want to take care of this as soon as you can.
Be sure you don't put anything in the ear through the night. Hot compresses are fine to ease the muscles around the ear but don't put anything in the ear canal until you find out what you are dealing with.
The problem with ear infections is that they can be bacterial or fungal in nature. If you put the wrong medication in the ear, you can actually do more harm than good so you want to be sure of what you are dealing with before you put anything in the ear. So, no peroxide, no ear wash. See your vet for a culture of the gunk in the ear so you can find out what you're dealing with.
Let me know if you still have questions.