http://en.wikipedia.org/wiki/Caffeine#Mechanism_of_action
Long story really short - you've got this hormone called adenosine that tells you when you're tired. Andenosine floats around and attaches itself in your brain to an andenosine receptor. As it attaches, you feel tired.
Caffeine is shaped similarly to andenosine, so it sort of "blocks" the andenosine from getting to the receptor. You're still tired, you still need rest, but you don't feel tired. So that's the tiredness-removal effect of caffeine, it's stopping the andenosine from getting to the receptor.
Now, your body kind of minorly panics at this and secretes adrenalin - y'know, adrenalin, like when you get excited or sacred? Yeah, that one. When andenosine gets cut off, your body perks up like something is happening and releases adrenalin. So there's the energy boost.
Over time, your body start naturally producing more andenosine to compensate, hence, you need caffeine just to feel normal. And your body starts to realize that you don't need the adrenalin, so you start to produce less of it when having caffeine. If you've ever gone a while without caffeine and then had a coffee, you remember how off the wall hyper you got? That slowly fades because your body starts producing more andenosine (the sleepy hormone) if you're a habitual caffeine user, and less adrenalin.
There's more to it than that, but that's some of the basics. Wikipedia's got some decent stuff, a few minutes here and there skimming on this sort of thing is time well spent.