Wordpress - How do I programmatically generate a 404?

function generate_404_somehow() {
   global $wp_query;
   $wp_query->is_404 = true;
}
add_action('wp','generate_404_somehow');

Of course, that will send all of you page to the 404 template. I don't know what the conditions are that this should fire or not fire.

Or to be more cautious (see comments) ...

function generate_404_somehow() {
   global $wp_query;
   $wp_query->set_404();
}
add_action('wp','generate_404_somehow');