It's a negative feedback system, like a pendulum (which, as it swings higher, also feels a stronger force pulling it back towards the central position). Startling thing number 1: one crucial step in the feedback loop is DNA transcription. I'd always vaguely assumed that, roughly speaking, the instructions in a cell's DNA determine how the cell is "built" and are more or less passive thereafter (readers who actually know some biology, please feel free to laugh at me at this point), but no.
Here's a simplified description of how it works: there are two proteins (call them A and B), described by genes a and b. Protein B promotes the expression of gene a, but protein A attaches to protein B and stops it doing this. So, the more A we have, the less A gets made; if the details of how this works out are right, we get the sort of negative feedback loop required to produce an oscillation.
Startling thing number 2 is how easily this produces entrainment to the light/dark cycle. It turns out that A is degraded by exposure to light, and this is enough. (Which shouldn't have been surprising, since in general oscillators very easily get entrained to anything in their environment, but it surprised me anyway.)
So: suppose we have a stable 24-hour-ish cycle, and then it becomes light earlier than "expected". Then A gets degraded more rapidly, at around the time when it would have been being degraded anyway, and so the cycle is a bit shorter. Similarly if the onset of light is later than expected. If the light period goes on for longer than expected, then again A gets degraded faster -- but now at a time when its quantity should be beginning to ramp up; so the cycle becomes longer. And so forth.
Three caveats. Firstly, this is all oversimplified; for instance, A and B are actually pairs of proteins that work together, and there are other mechanisms involved in, e.g., arranging for the period of the oscillator not to be much too fast. Secondly, strictly it only applies to fruit flies, and the corresponding systems in other organisms aren't so well understood. Thirdly, lots of important details (for instance, how the period of the clock manages to be largely insensitive to temperature, when chemical reactions consistently run faster at higher termperatures) are still unknown.