Doujinshi, as defined on Wikipedia, are self-published works. While not all doujinshi are derived from other manga, they mostly are, like the many Touhou and Naruto doujins. The works that they are derived from are mainly those with copyrights, meaning that the characters depicted in those original works are also protected and thus cannot be used without consent of the copyright holders. However, as we can see from Yuru Yuri, Oreimo and the Comiket in real life, doujinshi are sold in Comiket. When they are derived from other works and sold, it means that their use is for commercial purpose, which would be very likely prohibited by the copyright holders. Yet, they keep selling doujinshi in every Comiket and the police ain't doing anything about it.
Thus my question: what is the law behind doujinshi? Does every doujinshi sold in Comiket have a written consent from the copyright holders? Or is it the case that by labeling their works as doujinshi, they are exempted from the copyright law? What about the R-18+ doujinshi?