How does confusion work in Pokemon?

Per Bulbapedia:

The confused condition causes a Pokémon to sometimes hurt itself in its confusion instead of executing a selected move. From Generation I to VI, the chance to hurt itself is 50%; in Generation VII, it is 33%. The damage is done as if the Pokémon attacked itself with a 40-power typeless physical attack (without the possibility of a critical hit).

Confusion wears off after 1-4 attacking turns. This means that turns recharging, such as after using Hyper Beam, and turns unable to attack, such as from paralysis, will not lower the remaining number of turns of confusion. However, a sleeping Pokémon may hurt itself in confusion if using a move such as Snore or Sleep Talk. Multi-turn attacks such as Fly and Dive require confusion to be checked both turns, further reducing the chance of a successful attack.

Basics: A Pokemon has a 50% chance (33% chance from Sun and Moon onwards) to attack itself with a 40 power untyped physical move, so damage will be increased by attack ups, but not special attack ups. (Hence why swagger is such a good move)