source code taken from cacert-20090625.tar.bz2
authorMarkus Warg <mw@it-sls.de>
Thu, 11 Mar 2010 14:17:02 +0000 (15:17 +0100)
committerMarkus Warg <mw@it-sls.de>
Thu, 11 Mar 2010 14:17:02 +0000 (15:17 +0100)
434 files changed:
cacert/CVS/Entries [new file with mode: 0644]
cacert/CVS/Repository [new file with mode: 0644]
cacert/CVS/Root [new file with mode: 0644]
cacert/CommModule/CVS/Entries [new file with mode: 0644]
cacert/CommModule/CVS/Repository [new file with mode: 0644]
cacert/CommModule/CVS/Root [new file with mode: 0644]
cacert/CommModule/client.pl [new file with mode: 0755]
cacert/CommModule/clientloop.sh [new file with mode: 0755]
cacert/CommModule/error.txt [new file with mode: 0644]
cacert/CommModule/logclean.sh [new file with mode: 0755]
cacert/CommModule/readme.txt [new file with mode: 0644]
cacert/CommModule/serial.conf [new file with mode: 0755]
cacert/CommModule/usbclient.pl [new file with mode: 0755]
cacert/LICENSE [new file with mode: 0644]
cacert/Makefile [new file with mode: 0644]
cacert/README [new file with mode: 0644]
cacert/cacertupload.pl [new file with mode: 0644]
cacert/cgi-bin/CVS/Entries [new file with mode: 0644]
cacert/cgi-bin/CVS/Repository [new file with mode: 0644]
cacert/cgi-bin/CVS/Root [new file with mode: 0644]
cacert/cgi-bin/siteseal.cgi [new file with mode: 0755]
cacert/includes/.cvsignore [new file with mode: 0644]
cacert/includes/CVS/Entries [new file with mode: 0644]
cacert/includes/CVS/Repository [new file with mode: 0644]
cacert/includes/CVS/Root [new file with mode: 0644]
cacert/includes/about_menu.php [new file with mode: 0644]
cacert/includes/account.php [new file with mode: 0644]
cacert/includes/account_stuff.php [new file with mode: 0644]
cacert/includes/general.php [new file with mode: 0644]
cacert/includes/general_stuff.php [new file with mode: 0644]
cacert/includes/loggedin.php [new file with mode: 0644]
cacert/includes/mysql.php.sample [new file with mode: 0644]
cacert/includes/shutdown.php [new file with mode: 0644]
cacert/includes/sponsorinfo.php [new file with mode: 0644]
cacert/includes/tverify_stuff.php [new file with mode: 0644]
cacert/locale/CVS/Entries [new file with mode: 0644]
cacert/locale/CVS/Repository [new file with mode: 0644]
cacert/locale/CVS/Root [new file with mode: 0644]
cacert/locale/ar.po [new file with mode: 0644]
cacert/locale/bg.po [new file with mode: 0644]
cacert/locale/cs.po [new file with mode: 0644]
cacert/locale/cv.c [new file with mode: 0644]
cacert/locale/da.po [new file with mode: 0644]
cacert/locale/de.po [new file with mode: 0644]
cacert/locale/el.po [new file with mode: 0644]
cacert/locale/es.po [new file with mode: 0644]
cacert/locale/fa.po [new file with mode: 0644]
cacert/locale/fi.po [new file with mode: 0644]
cacert/locale/fi_FI/CVS/Entries [new file with mode: 0644]
cacert/locale/fi_FI/CVS/Repository [new file with mode: 0644]
cacert/locale/fi_FI/CVS/Root [new file with mode: 0644]
cacert/locale/fi_FI/LC_MESSAGES/CVS/Entries [new file with mode: 0644]
cacert/locale/fi_FI/LC_MESSAGES/CVS/Repository [new file with mode: 0644]
cacert/locale/fi_FI/LC_MESSAGES/CVS/Root [new file with mode: 0644]
cacert/locale/fr.po [new file with mode: 0644]
cacert/locale/he.po [new file with mode: 0644]
cacert/locale/hr.po [new file with mode: 0644]
cacert/locale/hu.po [new file with mode: 0644]
cacert/locale/is.po [new file with mode: 0644]
cacert/locale/it.po [new file with mode: 0644]
cacert/locale/ja.po [new file with mode: 0644]
cacert/locale/ka.po [new file with mode: 0644]
cacert/locale/ko.po [new file with mode: 0644]
cacert/locale/make.php [new file with mode: 0755]
cacert/locale/nb.po [new file with mode: 0644]
cacert/locale/nl.po [new file with mode: 0644]
cacert/locale/pl.po [new file with mode: 0644]
cacert/locale/pt.po [new file with mode: 0644]
cacert/locale/pt_BR/CVS/Entries [new file with mode: 0644]
cacert/locale/pt_BR/CVS/Repository [new file with mode: 0644]
cacert/locale/pt_BR/CVS/Root [new file with mode: 0644]
cacert/locale/pt_BR/LC_MESSAGES/CVS/Entries [new file with mode: 0644]
cacert/locale/pt_BR/LC_MESSAGES/CVS/Repository [new file with mode: 0644]
cacert/locale/pt_BR/LC_MESSAGES/CVS/Root [new file with mode: 0644]
cacert/locale/ro.po [new file with mode: 0644]
cacert/locale/ru.po [new file with mode: 0644]
cacert/locale/sv.po [new file with mode: 0644]
cacert/locale/tl.po [new file with mode: 0644]
cacert/locale/tr.po [new file with mode: 0644]
cacert/locale/zh.po [new file with mode: 0644]
cacert/messages.po [new file with mode: 0644]
cacert/pages/CVS/Entries [new file with mode: 0644]
cacert/pages/CVS/Repository [new file with mode: 0644]
cacert/pages/CVS/Root [new file with mode: 0644]
cacert/pages/account/0.php [new file with mode: 0644]
cacert/pages/account/1.php [new file with mode: 0644]
cacert/pages/account/10.php [new file with mode: 0644]
cacert/pages/account/11.php [new file with mode: 0644]
cacert/pages/account/12.php [new file with mode: 0644]
cacert/pages/account/13.php [new file with mode: 0644]
cacert/pages/account/14.php [new file with mode: 0644]
cacert/pages/account/15.php [new file with mode: 0644]
cacert/pages/account/16.php [new file with mode: 0644]
cacert/pages/account/17.php [new file with mode: 0644]
cacert/pages/account/18.php [new file with mode: 0644]
cacert/pages/account/19.php [new file with mode: 0644]
cacert/pages/account/2.php [new file with mode: 0644]
cacert/pages/account/20.php [new file with mode: 0644]
cacert/pages/account/21.php [new file with mode: 0644]
cacert/pages/account/22.php [new file with mode: 0644]
cacert/pages/account/23.php [new file with mode: 0644]
cacert/pages/account/24.php [new file with mode: 0644]
cacert/pages/account/25.php [new file with mode: 0644]
cacert/pages/account/26.php [new file with mode: 0644]
cacert/pages/account/27.php [new file with mode: 0644]
cacert/pages/account/28.php [new file with mode: 0644]
cacert/pages/account/29.php [new file with mode: 0644]
cacert/pages/account/3.php [new file with mode: 0644]
cacert/pages/account/30.php [new file with mode: 0644]
cacert/pages/account/31.php [new file with mode: 0644]
cacert/pages/account/32.php [new file with mode: 0644]
cacert/pages/account/33.php [new file with mode: 0644]
cacert/pages/account/34.php [new file with mode: 0644]
cacert/pages/account/35.php [new file with mode: 0644]
cacert/pages/account/36.php [new file with mode: 0644]
cacert/pages/account/37.php [new file with mode: 0755]
cacert/pages/account/38.php [new file with mode: 0755]
cacert/pages/account/39.php [new file with mode: 0755]
cacert/pages/account/4.php [new file with mode: 0644]
cacert/pages/account/40.php [new file with mode: 0755]
cacert/pages/account/41.php [new file with mode: 0644]
cacert/pages/account/42.php [new file with mode: 0644]
cacert/pages/account/43.php [new file with mode: 0644]
cacert/pages/account/44.php [new file with mode: 0644]
cacert/pages/account/45.php [new file with mode: 0644]
cacert/pages/account/48.php [new file with mode: 0644]
cacert/pages/account/49.php [new file with mode: 0644]
cacert/pages/account/5.php [new file with mode: 0644]
cacert/pages/account/50.php [new file with mode: 0644]
cacert/pages/account/51.php [new file with mode: 0644]
cacert/pages/account/52.php [new file with mode: 0644]
cacert/pages/account/53.php [new file with mode: 0644]
cacert/pages/account/54.php [new file with mode: 0644]
cacert/pages/account/55.php [new file with mode: 0644]
cacert/pages/account/6.php [new file with mode: 0644]
cacert/pages/account/7.php [new file with mode: 0644]
cacert/pages/account/8.php [new file with mode: 0644]
cacert/pages/account/9.php [new file with mode: 0644]
cacert/pages/account/CVS/Entries [new file with mode: 0644]
cacert/pages/account/CVS/Repository [new file with mode: 0644]
cacert/pages/account/CVS/Root [new file with mode: 0644]
cacert/pages/advertise/CVS/Entries [new file with mode: 0644]
cacert/pages/advertise/CVS/Repository [new file with mode: 0644]
cacert/pages/advertise/CVS/Root [new file with mode: 0644]
cacert/pages/advertising/0.php [new file with mode: 0644]
cacert/pages/advertising/1.php [new file with mode: 0644]
cacert/pages/advertising/CVS/Entries [new file with mode: 0644]
cacert/pages/advertising/CVS/Repository [new file with mode: 0644]
cacert/pages/advertising/CVS/Root [new file with mode: 0644]
cacert/pages/disputes/0.php [new file with mode: 0644]
cacert/pages/disputes/1.php [new file with mode: 0644]
cacert/pages/disputes/2.php [new file with mode: 0644]
cacert/pages/disputes/4.php [new file with mode: 0644]
cacert/pages/disputes/5.php [new file with mode: 0644]
cacert/pages/disputes/6.php [new file with mode: 0644]
cacert/pages/disputes/CVS/Entries [new file with mode: 0644]
cacert/pages/disputes/CVS/Repository [new file with mode: 0644]
cacert/pages/disputes/CVS/Root [new file with mode: 0644]
cacert/pages/gpg/0.php [new file with mode: 0644]
cacert/pages/gpg/2.php [new file with mode: 0644]
cacert/pages/gpg/3.php [new file with mode: 0644]
cacert/pages/gpg/CVS/Entries [new file with mode: 0644]
cacert/pages/gpg/CVS/Repository [new file with mode: 0644]
cacert/pages/gpg/CVS/Root [new file with mode: 0644]
cacert/pages/help/0.php [new file with mode: 0644]
cacert/pages/help/2.php [new file with mode: 0644]
cacert/pages/help/3.php [new file with mode: 0644]
cacert/pages/help/4.php [new file with mode: 0644]
cacert/pages/help/5.php [new file with mode: 0644]
cacert/pages/help/6.php [new file with mode: 0644]
cacert/pages/help/7.php [new file with mode: 0644]
cacert/pages/help/8.php [new file with mode: 0644]
cacert/pages/help/9.php [new file with mode: 0644]
cacert/pages/help/CVS/Entries [new file with mode: 0644]
cacert/pages/help/CVS/Repository [new file with mode: 0644]
cacert/pages/help/CVS/Root [new file with mode: 0644]
cacert/pages/index/0.php [new file with mode: 0644]
cacert/pages/index/1.php [new file with mode: 0644]
cacert/pages/index/10.php [new file with mode: 0644]
cacert/pages/index/11.php [new file with mode: 0644]
cacert/pages/index/12.php [new file with mode: 0644]
cacert/pages/index/13.php [new file with mode: 0644]
cacert/pages/index/16.php [new file with mode: 0755]
cacert/pages/index/17.php [new file with mode: 0644]
cacert/pages/index/18.php [new file with mode: 0644]
cacert/pages/index/19.php [new file with mode: 0644]
cacert/pages/index/2.php [new file with mode: 0644]
cacert/pages/index/21.php [new file with mode: 0644]
cacert/pages/index/3.php [new file with mode: 0644]
cacert/pages/index/4.php [new file with mode: 0644]
cacert/pages/index/47.php [new file with mode: 0644]
cacert/pages/index/5.php [new file with mode: 0644]
cacert/pages/index/51.php [new file with mode: 0644]
cacert/pages/index/6.php [new file with mode: 0644]
cacert/pages/index/7.php [new file with mode: 0644]
cacert/pages/index/8.php [new file with mode: 0644]
cacert/pages/index/CVS/Entries [new file with mode: 0644]
cacert/pages/index/CVS/Repository [new file with mode: 0644]
cacert/pages/index/CVS/Root [new file with mode: 0644]
cacert/pages/wot/0.php [new file with mode: 0644]
cacert/pages/wot/1.php [new file with mode: 0644]
cacert/pages/wot/10.php [new file with mode: 0644]
cacert/pages/wot/11.php [new file with mode: 0644]
cacert/pages/wot/12.php [new file with mode: 0644]
cacert/pages/wot/13.php [new file with mode: 0644]
cacert/pages/wot/14.php [new file with mode: 0644]
cacert/pages/wot/2.php [new file with mode: 0644]
cacert/pages/wot/3.php [new file with mode: 0644]
cacert/pages/wot/4.php [new file with mode: 0644]
cacert/pages/wot/5.php [new file with mode: 0644]
cacert/pages/wot/6.php [new file with mode: 0644]
cacert/pages/wot/7-old.php [new file with mode: 0644]
cacert/pages/wot/8.php [new file with mode: 0644]
cacert/pages/wot/9.php [new file with mode: 0644]
cacert/pages/wot/CVS/Entries [new file with mode: 0644]
cacert/pages/wot/CVS/Repository [new file with mode: 0644]
cacert/pages/wot/CVS/Root [new file with mode: 0644]
cacert/scripts/CVS/Entries [new file with mode: 0644]
cacert/scripts/CVS/Repository [new file with mode: 0644]
cacert/scripts/CVS/Root [new file with mode: 0644]
cacert/scripts/Makefile [new file with mode: 0644]
cacert/scripts/addpoints.php [new file with mode: 0755]
cacert/scripts/areacheck.php [new file with mode: 0755]
cacert/scripts/assurer.php [new file with mode: 0644]
cacert/scripts/assurer.txt [new file with mode: 0644]
cacert/scripts/ate-bi-email.txt [new file with mode: 0644]
cacert/scripts/ate-bi-mail.php [new file with mode: 0644]
cacert/scripts/ate-d-email.txt [new file with mode: 0644]
cacert/scripts/ate-d-mail.php.txt [new file with mode: 0644]
cacert/scripts/ate-de09-email.txt [new file with mode: 0644]
cacert/scripts/ate-de09-mail.php.txt [new file with mode: 0644]
cacert/scripts/ate-f-email.txt [new file with mode: 0644]
cacert/scripts/ate-f-mail.php.txt [new file with mode: 0644]
cacert/scripts/ate-hh-email.txt [new file with mode: 0644]
cacert/scripts/ate-hh-mail.php.txt [new file with mode: 0644]
cacert/scripts/ate-l-email.txt [new file with mode: 0644]
cacert/scripts/ate-l-mail.php.txt [new file with mode: 0644]
cacert/scripts/ate-m-email.txt [new file with mode: 0644]
cacert/scripts/ate-m-mail.php.txt [new file with mode: 0644]
cacert/scripts/ate-nl01-email.txt [new file with mode: 0644]
cacert/scripts/ate-nl01-mail.php.txt [new file with mode: 0644]
cacert/scripts/ate-s-email.txt [new file with mode: 0644]
cacert/scripts/ate-s-mail.php.txt [new file with mode: 0644]
cacert/scripts/ate-us02-email.txt [new file with mode: 0644]
cacert/scripts/ate-us02-mail.php.txt [new file with mode: 0644]
cacert/scripts/cebitemail.txt [new file with mode: 0644]
cacert/scripts/clientcerts.php [new file with mode: 0755]
cacert/scripts/country.php [new file with mode: 0755]
cacert/scripts/findexp3.pl [new file with mode: 0644]
cacert/scripts/gpgcerts.php [new file with mode: 0755]
cacert/scripts/gpgcheck3.php [new file with mode: 0644]
cacert/scripts/gpgfillmissingemail.php [new file with mode: 0644]
cacert/scripts/gpgfillmissingkeyid.php [new file with mode: 0644]
cacert/scripts/koelnemail.txt [new file with mode: 0644]
cacert/scripts/nearest.php [new file with mode: 0755]
cacert/scripts/newsletter.php [new file with mode: 0755]
cacert/scripts/newslettercebit.php [new file with mode: 0755]
cacert/scripts/notify.php [new file with mode: 0755]
cacert/scripts/removedead.php [new file with mode: 0755]
cacert/scripts/runclient.c [new file with mode: 0644]
cacert/scripts/rungpg.c [new file with mode: 0644]
cacert/scripts/runserver.c [new file with mode: 0644]
cacert/scripts/scanforexponents.php [new file with mode: 0755]
cacert/scripts/servercerts.php [new file with mode: 0755]
cacert/scripts/test.c [new file with mode: 0644]
cacert/scripts/updatesort.php [new file with mode: 0755]
cacert/scripts/warning.php [new file with mode: 0755]
cacert/stamp/.htaccess [new file with mode: 0644]
cacert/stamp/CVS/Entries [new file with mode: 0644]
cacert/stamp/CVS/Repository [new file with mode: 0644]
cacert/stamp/CVS/Root [new file with mode: 0644]
cacert/stamp/certdet.php [new file with mode: 0644]
cacert/stamp/common.php [new file with mode: 0644]
cacert/stamp/displogo.php [new file with mode: 0644]
cacert/stamp/images/CAverify.png [new file with mode: 0644]
cacert/stamp/images/CVS/Entries [new file with mode: 0644]
cacert/stamp/images/CVS/Repository [new file with mode: 0644]
cacert/stamp/images/CVS/Root [new file with mode: 0644]
cacert/stamp/index.php [new file with mode: 0644]
cacert/stamp/old_showlogo.php.broken [new file with mode: 0644]
cacert/stamp/report.php [new file with mode: 0644]
cacert/stamp/showlogo.php [new file with mode: 0644]
cacert/stamp/style.css [new file with mode: 0644]
cacert/tverify/.htaccess [new file with mode: 0644]
cacert/tverify/CVS/Entries [new file with mode: 0644]
cacert/tverify/CVS/Repository [new file with mode: 0644]
cacert/tverify/CVS/Root [new file with mode: 0644]
cacert/tverify/favicon.ico [new file with mode: 0644]
cacert/tverify/index.php [new file with mode: 0644]
cacert/tverify/index/0.php [new file with mode: 0644]
cacert/tverify/index/1.php [new file with mode: 0644]
cacert/tverify/index/CVS/Entries [new file with mode: 0644]
cacert/tverify/index/CVS/Repository [new file with mode: 0644]
cacert/tverify/index/CVS/Root [new file with mode: 0644]
cacert/www/.htaccess [new file with mode: 0644]
cacert/www/CVS/Entries [new file with mode: 0644]
cacert/www/CVS/Repository [new file with mode: 0644]
cacert/www/CVS/Root [new file with mode: 0644]
cacert/www/ac.js [new file with mode: 0644]
cacert/www/ac.php [new file with mode: 0644]
cacert/www/account.php [new file with mode: 0644]
cacert/www/advertising.php [new file with mode: 0644]
cacert/www/alert_hash_collision.php [new file with mode: 0644]
cacert/www/analyse.php [new file with mode: 0644]
cacert/www/api/CVS/Entries [new file with mode: 0644]
cacert/www/api/CVS/Repository [new file with mode: 0644]
cacert/www/api/CVS/Root [new file with mode: 0644]
cacert/www/api/ccsr.php [new file with mode: 0644]
cacert/www/api/cemails.php [new file with mode: 0644]
cacert/www/api/edu.php [new file with mode: 0644]
cacert/www/api/index.php [new file with mode: 0644]
cacert/www/cap.html.php [new file with mode: 0644]
cacert/www/cap.php [new file with mode: 0644]
cacert/www/capnew.php [new file with mode: 0644]
cacert/www/cats/.#cats_import.php.1.2 [new file with mode: 0644]
cacert/www/cats/CVS/Entries [new file with mode: 0644]
cacert/www/cats/CVS/Repository [new file with mode: 0644]
cacert/www/cats/CVS/Root [new file with mode: 0644]
cacert/www/cats/cats_import.php [new file with mode: 0644]
cacert/www/certs/CVS/Entries [new file with mode: 0644]
cacert/www/certs/CVS/Repository [new file with mode: 0644]
cacert/www/certs/CVS/Root [new file with mode: 0644]
cacert/www/certs/cacert.asc [new file with mode: 0644]
cacert/www/certs/class3.crt [new file with mode: 0644]
cacert/www/certs/class3.der [new file with mode: 0644]
cacert/www/certs/class3.txt [new file with mode: 0644]
cacert/www/certs/root.crt [new file with mode: 0644]
cacert/www/certs/root.der [new file with mode: 0644]
cacert/www/certs/root.txt [new file with mode: 0644]
cacert/www/coap.html.php [new file with mode: 0644]
cacert/www/coapnew.php [new file with mode: 0644]
cacert/www/cps.php [new file with mode: 0644]
cacert/www/disputes.php [new file with mode: 0644]
cacert/www/docs/CAcert_Rules.pdf [new file with mode: 0644]
cacert/www/docs/CAcert_Rules.sxw [new file with mode: 0644]
cacert/www/docs/CVS/Entries [new file with mode: 0644]
cacert/www/docs/CVS/Repository [new file with mode: 0644]
cacert/www/docs/CVS/Root [new file with mode: 0644]
cacert/www/docs/banner.jpg [new file with mode: 0644]
cacert/www/docs/cacert0304.pdf [new file with mode: 0644]
cacert/www/docs/cacert_display.pdf [new file with mode: 0644]
cacert/www/docs/cacert_display.sxw [new file with mode: 0644]
cacert/www/docs/encryption in the real world.sxi [new file with mode: 0644]
cacert/www/docs/flyer.sxw [new file with mode: 0644]
cacert/www/docs/incorporation.jpg [new file with mode: 0644]
cacert/www/docs/keys.pdf [new file with mode: 0644]
cacert/www/docs/keys.ps [new file with mode: 0644]
cacert/www/error403.php [new file with mode: 0644]
cacert/www/error404.php [new file with mode: 0644]
cacert/www/gpg.php [new file with mode: 0644]
cacert/www/help.php [new file with mode: 0644]
cacert/www/iistutorial/CVS/Entries [new file with mode: 0644]
cacert/www/iistutorial/CVS/Repository [new file with mode: 0644]
cacert/www/iistutorial/CVS/Root [new file with mode: 0644]
cacert/www/iistutorial/image001.jpg [new file with mode: 0644]
cacert/www/iistutorial/image002.jpg [new file with mode: 0644]
cacert/www/iistutorial/image003.gif [new file with mode: 0644]
cacert/www/iistutorial/image004.gif [new file with mode: 0644]
cacert/www/iistutorial/image005.gif [new file with mode: 0644]
cacert/www/iistutorial/image006.gif [new file with mode: 0644]
cacert/www/iistutorial/image007.gif [new file with mode: 0644]
cacert/www/iistutorial/image008.gif [new file with mode: 0644]
cacert/www/iistutorial/image009.gif [new file with mode: 0644]
cacert/www/iistutorial/image010.gif [new file with mode: 0644]
cacert/www/iistutorial/image011.jpg [new file with mode: 0644]
cacert/www/iistutorial/image011b.png [new file with mode: 0644]
cacert/www/iistutorial/image012.gif [new file with mode: 0644]
cacert/www/iistutorial/image013.gif [new file with mode: 0644]
cacert/www/iistutorial/image014.jpg [new file with mode: 0644]
cacert/www/iistutorial/image015.gif [new file with mode: 0644]
cacert/www/images/CVS/Entries [new file with mode: 0644]
cacert/www/images/CVS/Repository [new file with mode: 0644]
cacert/www/images/CVS/Root [new file with mode: 0644]
cacert/www/images/cacert2.png [new file with mode: 0644]
cacert/www/index.php [new file with mode: 0644]
cacert/www/logos.php [new file with mode: 0644]
cacert/www/logos/CAcert-logo-colour.eps [new file with mode: 0644]
cacert/www/logos/CAcert-logo-mono.eps [new file with mode: 0644]
cacert/www/logos/CVS/Entries [new file with mode: 0644]
cacert/www/logos/CVS/Repository [new file with mode: 0644]
cacert/www/logos/CVS/Root [new file with mode: 0644]
cacert/www/logos/animated.gif [new file with mode: 0644]
cacert/www/logos/cacert-free-certificates2.png [new file with mode: 0644]
cacert/www/logos/cacert-free-certificates3.png [new file with mode: 0644]
cacert/www/logos/cacert-free-certificates4.png [new file with mode: 0644]
cacert/www/logos/cacert-grey.png [new file with mode: 0644]
cacert/www/logos/cacert-grey2.png [new file with mode: 0644]
cacert/www/logos/cacert-secure-site.png [new file with mode: 0644]
cacert/www/logos/cacert-secure-site2.png [new file with mode: 0644]
cacert/www/logos/cacert-secured3.png [new file with mode: 0644]
cacert/www/logos/cacert-secured4.png [new file with mode: 0644]
cacert/www/logos/cacert-secured5.png [new file with mode: 0644]
cacert/www/logos/cacert-secured7.png [new file with mode: 0644]
cacert/www/logos/cacert1.png [new file with mode: 0644]
cacert/www/logos/small-ssl-secured-site.png [new file with mode: 0644]
cacert/www/logos/small-ssl-security.png [new file with mode: 0644]
cacert/www/news.php [new file with mode: 0644]
cacert/www/policy/AssurancePolicy.php [new file with mode: 0644]
cacert/www/policy/CAcertCommunityAgreement.php [new file with mode: 0644]
cacert/www/policy/CVS/Entries [new file with mode: 0644]
cacert/www/policy/CVS/Repository [new file with mode: 0644]
cacert/www/policy/CVS/Root [new file with mode: 0644]
cacert/www/policy/DisputeResolutionPolicy.php [new file with mode: 0644]
cacert/www/policy/NRPDisclaimerAndLicence.php [new file with mode: 0644]
cacert/www/policy/OrganisationAssurancePolicy.php [new file with mode: 0644]
cacert/www/policy/PolicyOnPolicy.php [new file with mode: 0644]
cacert/www/policy/index.php [new file with mode: 0644]
cacert/www/rss.php [new file with mode: 0644]
cacert/www/sealgen.php [new file with mode: 0644]
cacert/www/siteimages/CVS/Entries [new file with mode: 0644]
cacert/www/siteimages/CVS/Repository [new file with mode: 0644]
cacert/www/siteimages/CVS/Root [new file with mode: 0644]
cacert/www/siteimages/bg_grad.jpg [new file with mode: 0644]
cacert/www/siteimages/bg_nav.jpg [new file with mode: 0644]
cacert/www/siteimages/gblnav_left.gif [new file with mode: 0644]
cacert/www/siteimages/glblnav_selected.gif [new file with mode: 0644]
cacert/www/siteimages/glbnav_background.gif [new file with mode: 0644]
cacert/www/siteimages/glbnav_right.gif [new file with mode: 0644]
cacert/www/siteimages/tl_curve_white.gif [new file with mode: 0644]
cacert/www/siteimages/tr_curve_white.gif [new file with mode: 0644]
cacert/www/sqldump.php [new file with mode: 0644]
cacert/www/src-lic.php [new file with mode: 0644]
cacert/www/stats.php [new file with mode: 0644]
cacert/www/styles/CVS/Entries [new file with mode: 0644]
cacert/www/styles/CVS/Repository [new file with mode: 0644]
cacert/www/styles/CVS/Root [new file with mode: 0644]
cacert/www/styles/default.css [new file with mode: 0644]
cacert/www/ttp.php [new file with mode: 0644]
cacert/www/tverify/CVS/Entries [new file with mode: 0644]
cacert/www/tverify/CVS/Repository [new file with mode: 0644]
cacert/www/tverify/CVS/Root [new file with mode: 0644]
cacert/www/tverify/seclayer.php [new file with mode: 0644]
cacert/www/verify.php [new file with mode: 0644]
cacert/www/wot.php [new file with mode: 0644]

diff --git a/cacert/CVS/Entries b/cacert/CVS/Entries
new file mode 100644 (file)
index 0000000..034ba4b
--- /dev/null
@@ -0,0 +1,14 @@
+D/cgi-bin////
+D/includes////
+D/locale////
+D/pages////
+D/scripts////
+D/tverify////
+D/www////
+D/stamp////
+D/CommModule////
+/Makefile/1.2/Sun Apr 22 17:42:25 2007//
+/LICENSE/1.2/Sun Apr  6 19:45:24 2008//
+/README/1.2/Sun Apr  6 12:16:10 2008//
+/cacertupload.pl/1.4/Sun Sep  7 22:20:28 2008//
+/messages.po/1.80/Thu Jun 25 20:09:26 2009//
diff --git a/cacert/CVS/Repository b/cacert/CVS/Repository
new file mode 100644 (file)
index 0000000..97ea8c8
--- /dev/null
@@ -0,0 +1 @@
+cacert
diff --git a/cacert/CVS/Root b/cacert/CVS/Root
new file mode 100644 (file)
index 0000000..da7816b
--- /dev/null
@@ -0,0 +1 @@
+/var/lib/cvs/
diff --git a/cacert/CommModule/CVS/Entries b/cacert/CommModule/CVS/Entries
new file mode 100644 (file)
index 0000000..c493e28
--- /dev/null
@@ -0,0 +1,8 @@
+/clientloop.sh/1.1/Sun Jan 13 00:05:44 2008//
+/error.txt/1.1/Sun Jan 13 00:05:44 2008//
+/readme.txt/1.1/Sun Jan 13 00:05:44 2008//
+/usbclient.pl/1.3/Fri Jul 18 16:37:02 2008//
+/serial.conf/1.2/Mon Oct  6 21:29:19 2008//
+/client.pl/1.11/Fri May 22 05:12:05 2009//
+/logclean.sh/1.2/Sun May 24 18:08:23 2009//
+D
diff --git a/cacert/CommModule/CVS/Repository b/cacert/CommModule/CVS/Repository
new file mode 100644 (file)
index 0000000..4e4c1e9
--- /dev/null
@@ -0,0 +1 @@
+cacert/CommModule
diff --git a/cacert/CommModule/CVS/Root b/cacert/CommModule/CVS/Root
new file mode 100644 (file)
index 0000000..a363882
--- /dev/null
@@ -0,0 +1 @@
+/var/lib/cvs
diff --git a/cacert/CommModule/client.pl b/cacert/CommModule/client.pl
new file mode 100755 (executable)
index 0000000..0cab835
--- /dev/null
@@ -0,0 +1,1036 @@
+#!/usr/bin/perl -w
+
+# CommModule - CAcert Communication Module
+# Copyright (C) 2006-2008  CAcert Inc.
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; version 2 of the License.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+
+
+# Production Client / CommModule
+
+use strict;
+use Device::SerialPort qw( :PARAM :STAT 0.07 );
+use POSIX;
+use IO::Select;
+use Time::HiRes q(usleep);
+use File::CounterFile;
+use IPC::Open3;
+use File::Copy;
+use DBI;
+use Locale::gettext;
+use IO::Socket;
+use MIME::Base64;
+use Digest::SHA1 qw(sha1_hex);
+
+#Protocol version:
+my $ver=1;
+
+my $paranoid=1;
+
+my $debug=0;
+
+my $serialport="/dev/ttyS0";
+#my $serialport="/dev/ttyUSB0";
+
+my $gpgbin="/usr/bin/gpg";
+
+my $opensslbin="/usr/bin/openssl";
+
+
+my $mysqlphp="/home/cacert/www/includes/mysql.php";
+
+my %revokefile=(2=>"../www/class3-revoke.crl",1=>"../www/revoke.crl",0=>"../www/revoke.crl");
+
+
+#End of configurations
+
+########################################################
+
+
+my %monarr = ("Jan" => 1, "Feb" => 2, "Mar" => 3, "Apr" => 4, "May" => 5, "Jun" => 6, "Jul" => 7, "Aug" => 8, "Sep" => 9, "Oct" => 10, "Nov" => 11, "Dec" => 12);
+
+
+my $password="";
+if(open IN,"<$mysqlphp")
+{
+my $content="";
+undef $/;
+$content=<IN>;
+$password=$1 if($content=~m/mysql_connect\("[^"]+",\s*"\w+",\s*"(\w+)"/);
+close IN;
+$/="\n";
+
+}
+
+my $dbh = DBI->connect("DBI:mysql:cacert:localhost","cacert",$password, { RaiseError => 1, AutoCommit => 1 }) || die ("Error with the database connection.\n");
+
+sub readfile($)
+{
+  my $save=$/;
+  undef $/;
+  open READIN,"<$_[0]";
+  my $content=<READIN>;
+  close READIN;
+  $/=$save;
+  return $content;
+}
+
+
+#mkdir "revokehashes";
+foreach (keys %revokefile)
+{
+  my $revokehash=sha1_hex(readfile($revokefile{$_}));
+  print "Root $_: Hash $revokefile{$_} = $revokehash\n";
+}
+
+
+#Logging functions:
+my $lastdate = "";
+
+sub SysLog($)
+{
+    return if(not defined($_[0]));
+    my $timestamp = strftime("%Y-%m-%d %H:%M:%S", localtime);
+    my $currdate = substr($timestamp, 0, 10);
+    if ($lastdate ne $currdate) {
+       close LOG if ($lastdate ne "");
+       $lastdate = $currdate;
+       open LOG,">>logfile$lastdate.txt";
+    }
+    print LOG "$timestamp $_[0]";
+    flush LOG;
+}
+
+sub Error($)
+{
+SysLog($_[0]);
+if($paranoid)
+{
+die $_[0];
+}
+}
+
+
+my $timestamp=strftime("%Y-%m-%d %H:%M:%S",localtime);
+
+
+sub mysql_query($)
+{
+$dbh->do($_[0]);
+}
+
+sub trim($)
+{
+my $new=$_[0];
+$new=~s/^\s*//;
+$new=~s/\s*$//;
+return($new);
+}
+sub addslashes($)
+{
+my $new=$_[0];
+$new=~s/['"\\]/\\$1/g;
+return($new);
+}
+
+sub recode
+{
+return $_[1];
+}
+
+
+
+SysLog("Opening Serial interface:\n");
+sub SerialSettings($)
+{
+my $PortObj=$_[0];
+if(!defined($PortObj))
+{
+Error "Could not open Serial Port!\n" ;
+}
+else
+{
+$PortObj->baudrate(115200);
+$PortObj->parity("none");
+$PortObj->databits(8);
+$PortObj->stopbits(1);        
+}
+}
+
+#We have to open the SerialPort and close it again, so that we can bind it to a Handle
+if(! -f "serial.conf")
+{
+my $PortObj = new Device::SerialPort($serialport);
+SerialSettings($PortObj);
+$PortObj->save("serial.conf");
+undef $PortObj;
+}
+
+my $PortObj = tie (*SER, 'Device::SerialPort', "serial.conf") || Error "Can't tie using Configuration_File_Name: $!\n";
+
+Error "Could not open Serial Interface!\n" if(not defined($PortObj));
+SerialSettings($PortObj);
+#open SER,">$serialport";
+
+SysLog("Serial interface opened: $PortObj\n");
+
+my $sel = new IO::Select( \*SER );
+
+
+
+#Hexdump function: Returns the hexdump representation of a string
+sub hexdump($)
+{
+return "" if(not defined($_[0]));
+my $content="";
+$content.=sprintf("%02X ",unpack("C",substr($_[0],$_,1))) foreach (0 .. length($_[0])-1);
+return $content;
+}
+
+#pack3 packs together the length of the data in 3 bytes and the data itself, size limited to 16MB. In case the data is more than 16 MB, it is ignored, and a 0 Byte block is transferred
+sub pack3
+{
+  return "\x00\x00\x00" if(!defined($_[0]));
+  my $data=(length($_[0]) >= 2**24)? "":$_[0];
+  my $len=pack("N",length($data));
+  SysLog "len: ".length($data)."\n" if($debug);
+  return substr($len,1,3).$data;
+}
+
+
+#unpack3 unpacks packed data.
+sub unpack3($)
+{
+return undef if((not defined($_[0])) or length($_[0])<3);
+#SysLog "hexdump: ".hexdump("\x00".substr($_[0],0,3))."\n";
+my $len=unpack("N","\x00".substr($_[0],0,3));
+#SysLog "len3: $len length(): ".length($_[0])." length()-3: ".(length($_[0])-3)."\n";
+return undef if(length($_[0])-3 != $len);
+return substr($_[0],3);
+}
+
+
+#unpack3array extracts a whole array of concatented pack3ed data.
+sub unpack3array($)
+{
+my @retarr=();
+if((not defined($_[0])) or length($_[0])<3)
+{
+SysLog "Begin of structure corrupt\n";
+return ();
+}
+my $dataleft=$_[0];
+while(length($dataleft)>=3)
+{
+#SysLog "hexdump: ".hexdump("\x00".substr($dataleft,0,3))."\n";
+my $len=unpack("N","\x00".substr($dataleft,0,3));
+#SysLog "len3: $len length(): ".length($dataleft)." length()-3: ".(length($dataleft)-3)."\n";
+if(length($dataleft)-3 < $len)
+{
+SysLog "Structure cut off\n";
+return ();
+}
+push @retarr, substr($dataleft,3,$len);
+$dataleft=substr($dataleft,3+$len);
+}
+if(length($dataleft)!=0)
+{
+SysLog "End of structure cut off\n";
+return ();
+}
+return @retarr;
+}
+
+
+#Raw send function over the Serial Interface  (+debugging)
+sub SendIt($)
+{
+  return unless defined($_[0]);
+  SysLog "Sending ".length($_[0])."\n"; #hexdump($_[0])."\n" if($debug);
+  my $data=$_[0];
+  my $runcount=0;
+  my $total=0;
+  my $mtu=30;
+  while(length($data))
+  {
+    my $iwrote=scalar($PortObj->write(substr($data,0,$mtu)))||0;
+    #usleep(270*$iwrote+9000); # On Linux, we have to wait to make sure it is being sent, and we dont loose any data.
+    $total+=$iwrote;
+    $data=substr($data,$iwrote);
+    if ($debug) {
+      print "i wrote: $iwrote total: $total left: ".length($data)."\n" if(!($runcount++ %10));
+    }
+  }
+  SysLog "Sent message.\n" if($debug);
+  #  print "Sending ".length($_[0])."\n"; #hexdump($_[0])."\n";
+  #  foreach(0 .. length($_[0]))
+  #  {
+  #    $PortObj->write(substr($_[0],$_,1));
+  #  }
+  
+}  
+
+
+my $modus=0;
+my $cnt=0;
+
+
+#Send data over the Serial Interface with handshaking:
+sub SendHandshaked($)
+{
+  SysLog "Shaking hands ...\n" if($debug);
+  SendIt("\x02");
+
+  Error "Handshake uncompleted. Connection lost2!\n" if(!scalar($sel->can_read(20)));
+  my $data="";
+  my $length=read SER,$data,1;
+  if($length && $data eq "\x10")
+  {
+    #print "OK ...\n";
+    my $xor=0;
+    foreach(0 .. length($_[0])-1)
+    {
+      #print "xor mit ".unpack("C",substr($_[0],$_,1))."\n";
+      $xor ^= unpack("C",substr($_[0],$_,1));
+    }
+    #print "XOR: $xor\n";
+  
+    my $tryagain=1;
+    while($tryagain)
+    {
+      SendIt($_[0].pack("C",$xor)."rie4Ech7");
+  
+      Error "Packet receipt was not confirmed in 5 seconds. Connection lost!\n" if(!scalar($sel->can_read(5)));
+
+      $data="";
+      $length=read SER,$data,1;
+    
+      if($length && $data eq "\x10")
+      {
+        SysLog "Sent successfully!...\n";
+        $tryagain=0;
+      }
+      elsif($length && $data eq "\x11")
+      {
+        $tryagain=1;
+      }
+      else
+      {
+        Error "I cannot send! $length ".unpack("C",$data)."\n"; 
+      }
+    }
+
+  }
+  else
+  {
+    print "!Cannot send! $length \n"; 
+    Error "!Stopped sending.\n";
+  }
+}
+
+
+
+sub Receive
+{
+my $data="";
+my @ready = $sel->can_read(120);
+
+my $length=read SER,$data,1,0;
+
+#SysLog "Data: ".hexdump($data)."\n";
+
+if($data eq "\x02")
+{
+$modus=1;
+SysLog "Start received, sending OK\n" if($debug);
+SendIt("\x10");
+
+my $block="";
+my $blockfinished=0;
+my $tries=100000;
+
+while(!$blockfinished)
+{
+Error("Tried reading too often\n") if(($tries--)<=0);
+print ("tries: $tries\n") if(!($tries%10));
+
+$data="";
+if(!scalar($sel->can_read(5)))
+{
+Error "Handshake uncompleted. Connection lost variant2!\n" ;
+return;
+}
+$length=read SER,$data,100,0;
+if($length)
+{
+$block.=$data;
+}
+#SysLog("Received: $length ".length($block)."\n");
+$blockfinished=defined(unpack3(substr($block,0,-9)))?1:0;
+
+if(!$blockfinished and substr($block,-8,8) eq "rie4Ech7")
+{
+SysLog "BROKEN Block detected!\n";
+SendIt("\x11");
+$block="";
+$blockfinished=0;
+$tries=100000;
+}
+
+}
+SysLog "Block done: ".hexdump($block)."\n" if($debug);
+SendIt("\x10");
+return($block);
+}
+else
+{
+Error("Error: No Answer received, Timeout.\n") if(length($data)==0);
+Error("Error: Wrong Startbyte: ".hexdump($data)." !\n");
+}
+
+SysLog "Waiting on next request ...\n";
+
+}
+
+
+
+# @result(Version,Action,Errorcode,Response)=Request(Version=1,Action=1,System=1,Root=1,Configuration="...",Parameter="...",Request="...");
+sub Request($$$$$$$$$$$)
+{
+  SysLog "Version: $_[0] Action: $_[1] System: $_[2] Root: $_[3] Config: $_[4]\n";
+  $_[3]=0 if($_[3]<0);
+  SendHandshaked(pack3(pack3(pack("C*",$_[0],$_[1],$_[2],$_[3],$_[4],$_[5],$_[6]>>8,$_[6]&255,$_[7])).pack3($_[8]).pack3($_[9]).pack3($_[10])));
+  my $data=Receive();
+  my @fields=unpack3array(substr($data,3,-9));
+
+  SysLog "Answer from Server: ".hexdump($data)."\n" if($debug);
+  #if(open OUT,">result.dat")
+  #{
+  #  print OUT $data;
+  #  close OUT;
+  #}
+  #else
+  #{
+  #  SysLog "Could not write result: $!\n";
+  #}
+  return $fields[1];
+}
+
+
+sub calculateDays($)
+{
+  if($_[0])
+  {
+    my @sum = $dbh->selectrow_array("select sum(`points`) as `total` from `notary` where `to`='".$_[0]."' group by `to`");
+    SysLog("Summe: $sum[0]\n") if($debug);
+
+    return ($sum[0]>=50)?730:180;
+  }
+  return 180;
+}
+
+sub X509extractSAN($)
+{
+  my @bits = split("/", $_[0]);
+  my $SAN="";
+  my $newsubject="";
+  foreach my $val(@bits)
+  {
+    my @bit=split("=",$val);
+    if($bit[0] eq "subjectAltName")
+    {
+      $SAN.="," if($SAN ne "");
+      $SAN.= trim($bit[1]);
+    } 
+    else 
+    {
+      $newsubject .= "/".$val;
+    }
+  }
+  $newsubject=~s{^//}{/};
+  $newsubject=~s/[\n\r\t\x00"\\']//g;
+  $SAN=~s/[ \n\r\t\x00"\\']//g;
+  return($SAN,$newsubject); 
+}
+
+sub X509extractExpiryDate($)
+{
+  # TIMEZONE ?!?
+  my $data=`$opensslbin x509 -in "$_[0]" -noout -enddate`;
+
+  #notAfter=Aug  8 10:26:34 2007 GMT
+  if($data=~m/notAfter=(\w{2,4}) *(\d{1,2}) *(\d{1,2}:\d{1,2}:\d{1,2}) (\d{4}) GMT/)
+  {
+    my $date="$4-".$monarr{$1}."-$2 $3";
+    SysLog "Expiry Date found: $date\n" if($debug);
+    return $date;
+  }
+  else
+  {
+    SysLog "Expiry Date not found: $data\n";
+  }
+  return "";
+}
+sub X509extractSerialNumber($)
+{
+  # TIMEZONE ?!?
+  my $data=`$opensslbin x509 -in "$_[0]" -noout -serial`;
+  if($data=~m/serial=([0-9A-F]+)/)
+  {
+    return $1;
+  }
+  return "";
+}
+
+sub OpenPGPextractExpiryDate ($) 
+{
+  my $r="";
+  my $cts;
+  my @date;
+  open(RGPG, $gpgbin.' -vv '.$_[0].' 2>&1 |') or Error('Can\'t start GnuPG($gpgbin): '.$!."\n");
+  open(OUT,  '> infogpg.txt'           ) or Error('Can\'t open output file: infogpg.txt: '.$!);
+  $/="\n";
+  while (<RGPG>) 
+  {
+    print OUT $_;
+    unless ($r) 
+    {
+      if ( /^\s*version \d+, created (\d+), md5len 0, sigclass \d+\s*$/ ) 
+      {
+        SysLog "Detected CTS: $1\n";
+        $cts = int($1);
+      } elsif ( /^\s*critical hashed subpkt \d+ len \d+ \(sig expires after ((\d+)y)?((\d+)d)?((\d+)h)?(\d+)m\)\s*$/ ) 
+      {
+        SysLog "Detected FRAME $2 $4 $6 $8\n";
+        $cts += $2 * 31536000; # secs per year (60 * 60 * 24 * 365)
+        $cts += $4 * 86400;    # secs per day  (60 * 60 * 24)
+        $cts += $6 * 3600;     # secs per hour (60 * 60)
+        $cts += $8 * 60;       # secs per min  (60)
+        $r    = $cts;
+      }
+      elsif(/version/)
+      {
+        SysLog "Detected VERSION\n";
+      }
+    }
+  }
+
+  close(OUT );      
+  close(RGPG);
+
+  SysLog "CTS: $cts  R: $r\n";
+  if ( $r ) 
+  {
+    @date = gmtime($r);
+    $r = sprintf('%.4i-%.2i-%.2i %.2i:%.2i:%.2i',            # date format
+    $date[5] + 1900, $date[4] + 1, $date[3], # day
+    $date[2],        $date[1],     $date[0], # time
+    );
+                                                       
+  }
+  SysLog "$r\n";
+  return $r;
+}
+
+#sub OpenPGPextractExpiryDate($)
+#{
+#  my $data=`$gpgbin -v $_[0]`;
+#  open OUT,">infogpg.txt";
+#  print OUT $data;
+#  close OUT;
+#  if($data=~m/^sig\s+[0-9A-F]{8} (\d{4}-\d\d-\d\d)   [^\[]/)
+#  {
+#    return "$1 00:00:00";
+#  }
+#  return "";
+#}
+
+
+# Sets the locale according to the users preferred language
+sub setUsersLanguage($)
+{
+  my $lang="de_DE"; 
+  print "Searching for the language of the user $_[0]\n";
+  my @a=$dbh->selectrow_array("select language from users where id='".int($_[0])."'");
+  $lang = $1 if($a[0]=~m/(\w+_[\w.@]+)/);
+
+  SysLog "The users preferred language: $lang\n";
+
+  if($lang ne "")
+  {
+    $ENV{"LANG"}=$lang;
+    setlocale(LC_ALL, $lang);     
+  } else {
+    $ENV{"LANG"}="en_AU";
+    setlocale(LC_ALL, "en_AU");
+  }
+}
+
+
+sub getUserData($)
+{
+  my $sth = $dbh->prepare("select * from users where id='$_[0]'");
+  $sth->execute();
+  #SysLog "USER DUMP:\n";
+  while ( my $rowdata = $sth->fetchrow_hashref() )
+  {
+    my %tmp=%{$rowdata};
+    #foreach (sort keys %tmp)
+    #{
+      #SysLog "  $_ -> $tmp{$_}\n";
+    #}
+    return %tmp;
+  }
+  return ();
+}
+
+
+sub _($)
+{
+  return gettext($_[0]);
+}
+
+sub sendmail($$$$$$$)
+{
+  my ($to, $subject, $message, $from, $replyto, $toname, $fromname)=@_;
+  my $errorsto="returns\@cacert.org";
+  my $extra="";
+  
+
+  # sendmail($user{email}, "[CAcert.org] Your GPG/PGP Key", $body, "support\@cacert.org", "", "", "CAcert Support");
+  my @lines=split("\n",$message);
+  $message = "";
+  foreach my $line (@lines)
+  {
+    $line = trim($line);
+    if($line eq ".")
+    {
+      $message .= " .\n";
+    } else 
+    {
+      $message .= $line."\n";
+    } 
+  }
+
+  $fromname = $from if($fromname eq "");
+               
+  my @bits = split(",", $from);
+  $from = addslashes($bits['0']);
+  $fromname = addslashes($fromname);
+
+  my $smtp = IO::Socket::INET->new(PeerAddr => 'localhost:25');
+  $/="\n";
+  SysLog "SMTP: ".<$smtp>;
+  print $smtp "HELO hlin.cacert.org\r\n";
+  SysLog "SMTP: ".<$smtp>;
+  print $smtp "MAIL FROM: <returns\@cacert.org>\r\n";
+  SysLog "MAIL FROM: ".<$smtp>;
+  @bits = split(",", $to);
+  foreach my $user (@bits)
+  {
+    print $smtp "RCPT TO: <".trim($user).">\r\n";
+    SysLog "RCPT TO: ".<$smtp>;
+  }
+  print $smtp "DATA\r\n";
+  SysLog "DATA: ".<$smtp>;
+
+  print $smtp "X-Mailer: CAcert.org Website\r\n";
+  print $smtp "X-OriginatingIP: ".$ENV{"REMOTE_ADDR"}."\r\n";
+  print $smtp "Sender: $errorsto\r\n";
+  print $smtp "Errors-To: $errorsto\r\n";
+  if($replyto ne "")
+  {
+       print $smtp "Reply-To: $replyto\r\n";
+  }
+  else
+  {
+       print $smtp "Reply-To: $from\r\n";
+  }
+  print $smtp "From: $from ($fromname)\r\n";
+  print $smtp "To: $to\r\n";
+  my $newsubj=encode_base64(recode("html..utf-8", trim($subject)));
+  #SysLog("NewSubj: --".$newsubj."--\n") if($debug);
+  $newsubj=~s/\n*$//;
+  #SysLog("NewSubj: --".$newsubj."--\n") if($debug);
+  print $smtp trim($subject)=~m/[^a-zA-Z0-9 ,.\[\]\/-]/?"Subject: =?utf-8?B?$newsubj?=\r\n":"Subject: $subject\r\n";
+  print $smtp "Mime-Version: 1.0\r\n";
+  if($extra eq "")
+  {
+       print $smtp "Content-Type: text/plain; charset=\"utf-8\"\r\n";
+       print $smtp "Content-Transfer-Encoding: 8bit\r\n";
+  } else {
+       print $smtp "Content-Type: text/plain; charset=\"iso-8859-1\"\r\n";
+       print $smtp "Content-Transfer-Encoding: quoted-printable\r\n";
+       print $smtp "Content-Disposition: inline\r\n";
+  };
+#      print $smtp "Content-Transfer-Encoding: BASE64\r\n";
+  print $smtp "\r\n";
+#              print $smtp chunk_split(encode_base64(recode("html..utf-8", $message)))."\r\n.\r\n";
+  print $smtp recode("html..utf-8", $message)."\r\n.\r\n";
+  SysLog "ENDOFTEXT: ".<$smtp>;
+  print $smtp "QUIT\n";
+  SysLog "QUIT: ".<$smtp>;
+  close($smtp);
+}
+
+
+sub HandleCerts($$)
+{
+  my $org=$_[0]?"org":"";
+  my $server=$_[1];
+
+
+  my $table=$org.($server?"domaincerts":"emailcerts");
+
+  SysLog "HandleCerts $table\n";
+
+  my $sth = $dbh->prepare("select * from $table where crt_name='' and csr_name!='' and warning<3");
+  $sth->execute();
+  #$rowdata;
+  while ( my $rowdata = $sth->fetchrow_hashref() )
+  {
+    my %row=%{$rowdata};
+
+    my $csrname = "../csr/".$org.($server?"server-":"client-").$row{'id'}.".csr";
+    my $crtname = "../crt/".$org.($server?"server-":"client-").$row{'id'}.".crt";
+
+
+    if($server)
+    {
+      #Weird SQL structure ...
+      my @sqlres=$dbh->selectrow_array("select memid from domains where id='".int($row{'domid'})."'");
+      $row{'memid'}=$sqlres[0]; 
+      SysLog("Fetched memid: $row{'memid'}\n") if($debug);
+    }
+
+    SysLog "Opening $csrname\n";
+
+    my $crt="";
+
+    my $profile=0;
+
+    #   "0"=>"client.cnf",
+    #   "1"=>"client-org.cnf",
+    #   "2"=>"client-codesign.cnf",
+    #   "3"=>"client-machine.cnf",
+    #   "4"=>"client-ads.cnf",
+    #   "5"=>"server.cnf",
+    #   "6"=>"server-org.cnf",
+    #   "7"=>"server-jabber.cnf",
+    #   "8"=>"server-ocsp.cnf",
+    #   "9"=>"server-timestamp.cnf",
+    #   "10"=>"proxy.cnf",
+    #   "11"=>"subca.cnf"
+
+
+    if($row{"type"} =~ m/^(8|9)$/)
+    {
+      $profile=$row{"type"};
+    }
+    elsif($org)
+    {
+      if($row{'codesign'})
+      {
+        $profile=2; ## TODO!
+      }
+      elsif($server)
+      {
+        $profile=6;
+      }
+      else
+      {
+        $profile=1;
+      }
+    }
+    else
+    {
+      if($row{'codesign'})
+      {
+        $profile=2;
+      }
+      elsif($server)
+      {
+        $profile=5;
+      }
+      else
+      {
+        $profile=0;
+      }
+
+
+    }
+
+
+
+    if(open(IN,"<$csrname"))
+    {
+      undef $/;
+      my $content=<IN>;
+      close IN;
+      SysLog "Read $csrname.\n" if($debug);
+      SysLog "Subject: --$row{'subject'}--\n" if($debug);
+
+      my ($SAN,$subject)=X509extractSAN($row{'subject'});
+      SysLog "Subject: --$subject--\n" if($debug);
+      SysLog "SAN: --$SAN--\n" if($debug);
+      SysLog "memid: $row{'memid'}\n" if($debug);
+
+      my $days=$org?($server?(365*2):365):calculateDays($row{"memid"});
+
+
+      $crt=Request($ver,1,1,$row{'rootcert'}-1,$profile,$row{'md'}eq"sha1"?2:0,$days,$row{'keytype'}eq"NS"?1:0,$content,$SAN,$subject);
+      if(length($crt))
+      {
+        if($crt=~m/^-----BEGIN CERTIFICATE-----/)
+        {
+          open OUT,">$crtname";
+          print OUT $crt;
+          close OUT;
+        }
+        else
+        {
+          open OUT,">$crtname.der";
+          print OUT $crt;
+          close OUT;
+          system "$opensslbin x509 -in $crtname.der -inform der -out $crtname";
+        }      
+      }
+      else
+      {
+        SysLog "ZERO Length certificate received.\n";
+      }
+    }
+    else
+    {
+      print "Error: $! Konnte $csrname nicht laden\n";
+    }
+
+
+
+    if(-s $crtname)
+    {
+      SysLog "Opening $crtname\n";
+
+      my $date=X509extractExpiryDate($crtname);
+      my $serial=X509extractSerialNumber($crtname);
+
+      setUsersLanguage($row{memid});
+
+      my %user=getUserData($row{memid});
+
+      foreach (sort keys %user)
+      {
+        SysLog "  $_ -> $user{$_}\n" if($debug);
+      }
+
+      SysLog("update `$table` set `crt_name`='$crtname', modified=now(), serial='$serial', `expire`='$date' where `id`='".$row{'id'}."'\n");
+
+      $dbh->do("update `$table` set `crt_name`='$crtname', modified=now(), serial='$serial', `expire`='$date' where `id`='".$row{'id'}."'");
+
+      my $body = _("Hi")." $user{fname},\n\n";
+      $body .= sprintf(_("You can collect your certificate for %s by going to the following location:")."\n\n", $row{'email'}.$row{'CN'});
+      $body .= "https://www.cacert.org/account.php?id=".($server?"15":"6")."&cert=$row{id}\n\n";
+      $body .= _("If you have not imported CAcert´s root certificate, please go to:")."\n";
+      $body .= "https://www.cacert.org/index.php?id=3\n";
+      $body .= "Root cert fingerprint = A6:1B:37:5E:39:0D:9C:36:54:EE:BD:20:31:46:1F:6B\n";
+      $body .= "Root cert fingerprint = 135C EC36 F49C B8E9 3B1A B270 CD80 8846 76CE 8F33\n\n";
+      $body .= _("Best regards")."\n"._("CAcert.org Support!")."\n\n";
+      sendmail($user{email}, "[CAcert.org] "._("Your certificate"), $body, "support\@cacert.org", "", "", "CAcert Support");
+    } else {
+
+      SysLog("Could not find the issued certificate. $crtname ".$row{"id"}."\n");
+      $dbh->do("update `$table` set warning=warning+1 where `id`='".$row{'id'}."'");
+    }
+  }
+}
+
+
+sub RevokeCerts($$)
+{
+  my $org=$_[0]?"org":"";
+  my $server=$_[1];
+
+  my $table=$org.($server?"domaincerts":"emailcerts");
+
+  my $sth = $dbh->prepare("select * from $table where revoked='1970-01-01 10:00:01'"); # WHICH TIMEZONE?
+  $sth->execute();
+  #$rowdata;
+  while ( my $rowdata = $sth->fetchrow_hashref() )
+  {
+    my %row=%{$rowdata};
+
+    my $csrname = "../csr/".$org.($server?"server-":"client-").$row{'id'}.".csr";
+    my $crtname = "../crt/".$org.($server?"server-":"client-").$row{'id'}.".crt";
+    my $crlname = $revokefile{$row{'rootcert'}};
+
+    my $crt="";
+
+
+    if(open(IN,"<$crtname"))
+    {
+      undef $/;
+      my $content=<IN>;
+      close IN;
+      my $revokehash=sha1_hex(readfile($crlname));
+
+      my $crl=Request($ver,2,1,$row{'rootcert'}-1,0,0,365,0,$content,"",$revokehash);
+      if(length($crl))
+      {
+        if(1)
+       {
+          open OUT,">$crlname.patch";
+          print OUT $crl;
+          close OUT;
+          system "xdelta patch $crlname.patch $crlname $crlname.tmp"; 
+
+       }
+        #if($crl=~m/^-----BEGIN X509 CRL-----/)
+        #{
+        #  open OUT,">$crlname.pem";
+        #  print OUT $crl;
+        #  close OUT;
+        #  system "$opensslbin crl -in $crlname.pem -outform der -out $crlname.tmp";
+        #}
+        #else
+        #{
+        #  open OUT,">$crlname.tmp";
+        #  print OUT $crl;
+        #  close OUT;
+        #}
+        rename "$crlname.tmp","$crlname";
+
+      }
+
+      if(-s $crlname)
+      {
+        setUsersLanguage($row{memid});
+
+        my %user=getUserData($row{memid});
+
+        $dbh->do("update `$table` set `revoked`=now() where `id`='".$row{'id'}."'");
+
+        my $body = _("Hi")." $user{fname},\n\n";
+        $body .= sprintf(_("Your certificate for %s has been revoked, as per request.")."\n\n", $row{'CN'});
+        $body .= _("Best regards")."\n"._("CAcert.org Support!")."\n\n";
+       SysLog("Sending email to ".$user{"email"}."\n") if($debug);
+        sendmail($user{email}, "[CAcert.org] "._("Your certificate"), $body, "support\@cacert.org", "", "", "CAcert Support");
+      }
+
+    }
+    else
+    {
+      SysLog("Error: $crtname $!\n") if($debug);
+    }
+
+  }
+
+}
+
+
+
+
+
+sub HandleGPG()
+{
+  my $sth = $dbh->prepare("select * from gpg where crt='' and csr!='' ");
+  $sth->execute();
+  my $rowdata;
+  while ( $rowdata = $sth->fetchrow_hashref() )
+  {
+    my %row=%{$rowdata};
+  
+    my $csrname = "../csr/gpg-".$row{'id'}.".csr";
+    my $crtname = "../crt/gpg-".$row{'id'}.".crt";
+  
+    SysLog "Opening $csrname\n";
+  
+    my $crt="";
+  
+    if(-s $csrname && open(IN,"<$csrname"))
+    {
+      undef $/;
+      my $content=<IN>;
+      close IN;
+      SysLog "Read $csrname.\n";
+      $crt=Request($ver,1,2,0,0,2,366,0,$content,"","");
+      if(length($crt))
+      {
+        open OUT,">$crtname";
+        print OUT $crt;
+        close OUT;
+      }
+
+    }
+    else
+    {
+      #Error("Error: $!\n");
+      next;
+    }
+
+    if(-s $crtname)
+    {
+      SysLog "Opening $crtname\n";
+      setUsersLanguage($row{memid});
+  
+      my $date=OpenPGPextractExpiryDate($crtname);
+      my %user=getUserData($row{memid});
+  
+      $dbh->do("update `gpg` set `crt`='$crtname', issued=now(), `expire`='$date' where `id`='".$row{'id'}."'");
+  
+      my $body = _("Hi")." $user{fname},\n\n";
+      $body .= sprintf(_("Your CAcert signed key for %s is available online at:")."\n\n", $row{'email'});
+      $body .= "https://www.cacert.org/gpg.php?id=3&cert=$row{id}\n\n";
+      $body .= _("To help improve the trust of CAcert in general, it's appreciated if you could also sign our key and upload it to a key server. Below is a copy of our primary key details:")."\n\n";
+      $body .= "pub 1024D/65D0FD58 2003-07-11 CA Cert Signing Authority (Root CA) <gpg\@cacert.org>\n";
+      $body .= "Key fingerprint = A31D 4F81 EF4E BD07 B456 FA04 D2BB 0D01 65D0 FD58\n\n";
+      $body .= _("Best regards")."\n"._("CAcert.org Support!")."\n\n";
+      sendmail($user{email}, "[CAcert.org] Your GPG/PGP Key", $body, "support\@cacert.org", "", "", "CAcert Support");
+    } else {
+      SysLog("Could not find the issued gpg key. ".$row{"id"}."\n");
+      #$dbh->do("delete from `gpg` where `id`='".$row{'id'}."'");
+    }
+  }
+}
+
+
+# Main program loop
+
+while(1)
+{
+  SysLog("Handling GPG database ...\n");
+  HandleGPG();
+  SysLog("Issueing certs ...\n");
+  HandleCerts(0,0); #personal client certs
+  HandleCerts(0,1); #personal server certs
+  HandleCerts(1,0); #org client certs
+  HandleCerts(1,1); #org server certs
+  SysLog("Revoking certs ...\n");
+  RevokeCerts(0,0); #personal client certs
+  RevokeCerts(0,1); #personal server certs
+  RevokeCerts(1,0); #org client certs
+  RevokeCerts(1,1); #org server certs
+
+  #print "Sign Request X.509, Root0\n";
+  #my $reqcontent="";
+  #Request($ver,1,1,0,5,2,365,0,$reqcontent,"","/CN=supertest.cacert.at");
+
+  SysLog("NUL Request:\n");
+  my $timestamp=strftime("%m%d%H%M%Y.%S",gmtime);
+  Request($ver,0,0,0,0,0,0,0,$timestamp,"","");
+  usleep(700000); 
+}
diff --git a/cacert/CommModule/clientloop.sh b/cacert/CommModule/clientloop.sh
new file mode 100755 (executable)
index 0000000..c1254f2
--- /dev/null
@@ -0,0 +1,12 @@
+#!/bin/bash
+
+while true
+do
+perl ./client.pl
+#mail -s CAcert-Alert pg@futureware.at <error.txt 
+echo ******************************************************************
+echo ******************************************************************
+echo ******************************************************************
+sleep 1
+done
+
diff --git a/cacert/CommModule/error.txt b/cacert/CommModule/error.txt
new file mode 100644 (file)
index 0000000..7224707
--- /dev/null
@@ -0,0 +1 @@
+The CommModule has a problem.
diff --git a/cacert/CommModule/logclean.sh b/cacert/CommModule/logclean.sh
new file mode 100755 (executable)
index 0000000..99963ee
--- /dev/null
@@ -0,0 +1,57 @@
+#! /bin/sh
+# logclean.sh - maintenance script for logfiles generated by CommModule
+#               run this daily or weekly from cron
+
+syslog_error()
+{
+       logger -i -t CommModule/logclean.sh -p user.err $1
+}
+
+syslog_notice()
+{
+       logger -i -t CommModule/logclean.sh -p user.notice $1
+}
+
+# determine location of CommModule
+if [ -d /home/cacert/www/CommModule ]
+then   # webdb server
+       cd /home/cacert/www/CommModule
+elif [ -d /root/CommModule ]
+then   # signing server
+       cd /root/CommModule
+else
+       echo "$0: cannot find CommModule directory" 1>&2
+       syslog_error "cannot find CommModule directory"
+       exit 1
+fi
+
+# compress logfiles which have not been modified in at least 48 hours
+FILES=`find logfile20*.txt -mtime +1 -print`
+if [ -n "${FILES}" ]
+then
+       for F in ${FILES}
+       do
+               syslog_notice "Compressing ${F}" && bzip2 ${F}
+       done
+fi
+
+# move compressed logfiles to oldlogs directory
+FILES=`find logfile20*.txt.bz2 -print`
+if [ -n "${FILES}" ]
+then
+       mkdir -p oldlogs
+       for F in ${FILES}
+       do
+               syslog_notice "Moving ${F} to oldlogs" && mv ${F} oldlogs
+       done
+fi
+
+# delete old logfiles which have not been modified in at least 2.5+ years
+FILES=`find oldlogs/logfile20*.txt.bz2 -mtime +913 -print`
+if [ -n "${FILES}" ]
+then
+       for F in ${FILES}
+       do
+               syslog_notice "Deleting ${F}" && rm -f ${F}
+       done
+fi
diff --git a/cacert/CommModule/readme.txt b/cacert/CommModule/readme.txt
new file mode 100644 (file)
index 0000000..206f09d
--- /dev/null
@@ -0,0 +1,4 @@
+client.pl      The real client, running on the webserver
+serial.conf     Serial Port configuration file
+SerialPort.so  A part of the serial port module
+error.txt      Textfile with the error message for sending emails
diff --git a/cacert/CommModule/serial.conf b/cacert/CommModule/serial.conf
new file mode 100755 (executable)
index 0000000..918dedd
--- /dev/null
@@ -0,0 +1,32 @@
+Device::SerialPort_Configuration_File -- DO NOT EDIT --
+/dev/ttyS0
+
+C_CFLAG,6322
+C_IFLAG,1
+C_ISPEED,4098
+C_LFLAG,2608
+C_OFLAG,4
+C_OSPEED,4098
+C_VERASE,127
+C_VQUIT,28
+C_VSUSP,26
+C_VINTR,3
+C_VSTOP,19
+C_VSTART,17
+C_VKILL,21
+C_VMIN,0
+C_VEOF,4
+C_VEOL,0
+C_VTIME,0
+CFG_1,none
+RCONST,0
+CFG_2,none
+HNAME,localhost
+ALIAS,/dev/ttyS0
+CFG_3,none
+U_MSG,0
+DATYPE,raw
+E_MSG,0
+HADDR,0
+RTOT,0
+DVTYPE,none
diff --git a/cacert/CommModule/usbclient.pl b/cacert/CommModule/usbclient.pl
new file mode 100755 (executable)
index 0000000..3cbe2c3
--- /dev/null
@@ -0,0 +1,1019 @@
+#!/usr/bin/perl -w
+
+# CommModule - CAcert Communication module
+# Copyright (C) 2004-2008  CAcert Inc.
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; version 2 of the License.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+
+# Production Client / CommModule
+
+use strict;
+use Device::USB;
+use POSIX;
+use Time::HiRes q(usleep);
+use File::CounterFile;
+use File::Copy;
+use DBI;
+use Locale::gettext;
+use IO::Socket;
+use MIME::Base64;
+use Digest::SHA1 qw(sha1_hex sha1);
+
+#Protocol version:
+my $ver=1;
+
+#Debugging does not delete work-files for later inspection
+my $debug=0;
+
+#Paranoid exists the program on a malicious request
+my $paranoid=1;
+
+#Location of the openssl and gpg binaries
+my $gpgbin="/usr/bin/gpg";
+my $opensslbin="/usr/bin/openssl";
+
+my $mysqlphp="/home/cacert/www/includes/mysql.php";
+
+my %revokefile=(2=>"../www/class3-revoke.crl",1=>"../www/revoke.crl",0=>"../www/revoke.crl");
+
+#USB-Link settings
+my $PACKETSIZE=0x100;
+my $SALT="Salz";
+my $HASHSIZE=20;
+
+#End of configurations
+
+########################################################
+
+
+#Reads a while file and returns the content
+#Returns undef on failure
+sub readfile($)
+{
+  my $olds=$/;
+  my $content=undef;
+  if(open READIN,"<$_[0]")
+  {
+    binmode READIN;
+    undef $/;
+    $content=<READIN>;
+    close READIN;
+    $/=$olds;
+  }
+  return $content;
+}
+
+#Writes/Overwrites a file with content.
+#Returns 1 on success, 0 on failure.
+sub writefile($$)
+{
+  if(open WRITEOUT,">$_[0]")
+  {
+    binmode WRITEOUT;
+    print WRITEOUT $_[1];
+    close WRITEOUT;
+    return 1;
+  }
+  return 0;
+}
+
+#mkdir "revokehashes";
+foreach (keys %revokefile)
+{
+  my $revokehash=sha1_hex(readfile($revokefile{$_}));
+  print "Root $_: Hash $revokefile{$_} = $revokehash\n";
+}
+
+my %monarr = ("Jan" => 1, "Feb" => 2, "Mar" => 3, "Apr" => 4, "May" => 5, "Jun" => 6, "Jul" => 7, "Aug" => 8, "Sep" => 9, "Oct" => 10, "Nov" => 11, "Dec" => 12);
+
+my $content=readfile($mysqlphp);
+my $password="";$password=$1 if($content=~m/mysql_connect\("[^"]+",\s*"\w+",\s*"(\w+)"/);
+$content="";
+
+my $dbh = DBI->connect("DBI:mysql:cacert:localhost",$password?"cacert":"",$password, { RaiseError => 1, AutoCommit => 1 }) || die ("Error with the database connection.\n");
+
+
+#Logging functions:
+sub SysLog($)
+{
+  my @ltime=localtime;
+  my $date=strftime("%Y-%m-%d",@ltime);
+  open LOG,">>logfile$date.txt";
+  return if(not defined($_[0]));
+  my $timestamp=strftime("%Y-%m-%d %H:%M:%S",@ltime);
+  #$syslog->write($_[0]."\x00");
+  print LOG "$timestamp $_[0]";
+  print "$timestamp $_[0]";
+  flush LOG;
+  close LOG;
+}
+
+
+sub Error($)
+{
+  SysLog($_[0]);
+  if($paranoid)
+  {
+    die $_[0];
+  }
+}
+
+
+my $timestamp=strftime("%Y-%m-%d %H:%M:%S",localtime);
+
+
+sub mysql_query($)
+{
+  $dbh->do($_[0]);
+}
+
+sub trim($)
+{
+  my $new=$_[0];
+  $new=~s/^\s*//;
+  $new=~s/\s*$//;
+  return($new);
+}
+
+sub addslashes($)
+{
+  my $new=$_[0];
+  $new=~s/['"\\]/\\$1/g;
+  return($new);
+}
+
+sub recode
+{
+  return $_[1];
+}
+
+
+#Hexdump function: Returns the hexdump representation of a string
+sub hexdump($)
+{
+  return "" if(not defined($_[0]));
+  my $content="";
+  $content.=sprintf("%02X ",unpack("C",substr($_[0],$_,1))) foreach (0 .. length($_[0])-1);
+  return $content;
+}
+
+#pack3 packs together the length of the data in 3 bytes and the data itself, size limited to 16MB. In case the data is more than 16 MB, it is ignored, and a 0 Byte block is transferred
+sub pack3
+{
+  return "\x00\x00\x00" if(!defined($_[0]));
+  my $data=(length($_[0]) >= 2**24)? "":$_[0];
+  my $len=pack("N",length($data));
+  #print "len: ".length($data)."\n";
+  return substr($len,1,3).$data;
+}
+
+
+#unpack3 unpacks packed data.
+sub unpack3($)
+{
+  return undef if((not defined($_[0])) or length($_[0])<3);
+  #print "hexdump: ".hexdump("\x00".substr($_[0],0,3))."\n";
+  my $len=unpack("N","\x00".substr($_[0],0,3));
+  #print "len3: $len length(): ".length($_[0])." length()-3: ".(length($_[0])-3)."\n";
+  return undef if(length($_[0])-3 != $len);
+  return substr($_[0],3);
+}
+
+
+#unpack3array extracts a whole array of concatented packed data.
+sub unpack3array($)
+{
+  my @retarr=();
+  if((not defined($_[0])) or length($_[0])<3)
+  {
+    SysLog "Datenanfang kaputt\n";
+    return ();
+  }
+  my $dataleft=$_[0];
+  while(length($dataleft)>=3)
+  {
+    #print "hexdump: ".hexdump("\x00".substr($dataleft,0,3))."\n";
+    my $len=unpack("N","\x00".substr($dataleft,0,3));
+    #print "len3: $len length(): ".length($dataleft)." length()-3: ".(length($dataleft)-3)."\n";
+    if(length($dataleft)-3 < $len)
+    {
+      SysLog "Datensatz abgeschnitten\n";
+      return ();
+    }
+    push @retarr, substr($dataleft,3,$len);
+    $dataleft=substr($dataleft,3+$len);
+  }
+  if(length($dataleft)!=0)
+  {
+    SysLog "Ende abgeschnitten\n";
+    return ();
+  }
+  return @retarr;
+}
+
+#Pack4 packs and secret-key signs some data.
+sub pack4($)
+{
+  return pack("N",length($_[0])).$_[0].sha1($SALT.$_[0]);
+}
+
+
+
+
+
+$timestamp=strftime("%Y-%m-%d %H:%M:%S",localtime);
+
+SysLog("Starting Server at $timestamp\n");
+
+$SALT=readfile(".salt.key");
+
+SysLog("Opening USB-Link interface:\n");
+
+#Opening USB device:
+my $usb = Device::USB->new();
+my @list=$usb->list_devices(0x067b,0x2501);
+my $dev = $list[0];
+if(defined($dev))
+{
+  #print "USB-Link Device found: ", $dev->filename(), "\n";
+  if($dev->open())
+  {
+    #print "\t", $dev->manufacturer(), ": ", $dev->product(), "\n";
+    $dev->claim_interface(0);
+
+    my $buffer="  ";
+
+    $dev->control_msg(0xc0 , 0xfb, 0, 0, $buffer, 2, 1000);
+
+    if($buffer ne "\x04\x08" and $buffer ne "\x0c\x04" and $buffer ne "\x00\x0c" and $buffer ne "\x04\x0c")
+    {
+      print "Please plug the USB-Link cable into the other computer.\n";
+    }
+    else
+    {
+      print "USB-Link ok.\n";
+    }
+  }
+  else
+  {
+    print "Unable to  work with USB-Link device: $!\n";
+  }
+}
+else
+{
+  print "USB-Link Device not found. Please plug the cable into this computer.\n";
+}
+
+
+
+
+
+
+#sends a single packet (pack4 encoded). Returns the returncode
+sub send_packet($)
+{
+  if((14+length($_[0])+$HASHSIZE) > $PACKETSIZE)
+  {
+    return -1;
+  }
+  # 4 Bytes Length, N Bytes Data, 20 Bytes SHA1 Hash, 0 Padding
+  my $data="CommModule".pack4($_[0]);
+  $data.=("\x00"x($PACKETSIZE-length($data)));
+  my $ret=$dev->bulk_write(0x2,$data,length($data),1000);
+  print "Send-result: $ret\n";
+  return $ret;
+}
+
+#Receives several consecutive packets. Returns the concatenated payload
+sub receive_packets()
+{
+  print "Receiving packets ...\n";
+  my $collectedpayload="";
+  my $done=0;
+  while(!$done)
+  {
+    my $data=" "x$PACKETSIZE;
+    my $re=$dev->bulk_read(0x83,$data,length($data),10000);
+    writefile("usbpacket.dat",$data);
+    print "Read: $re Bytes: ".length($data)."\n";
+    if($re > 0)
+    {
+      $data=~s/^.*?CommModule//s;
+      my $len=unpack("N",substr($data,0,4));
+      print "len: $len\n";
+      if($len>=0 and $len<=$PACKETSIZE-$HASHSIZE-4)
+      {
+        my $payload=substr($data,4,$len);
+        if(sha1($SALT.$payload) eq substr($data,4+$len,$HASHSIZE))
+        {
+          print "Hash OK!\n";
+          $collectedpayload.=substr($payload,1);
+          $done=1 if(substr($payload,0,1)eq "0");
+        }
+        else
+        {
+          print "Hash NOT OK: ".sha1_hex($SALT.$payload)." vs. ".hexdump(substr($data,4+$len,$HASHSIZE))." !\n";
+          return "";
+        }
+      }
+    }
+    elsif($re == 0)
+    {
+      print "USB-Link cable disconnected?\n";
+      #return "";
+    }
+  }
+  print "Receiving done.\n";
+  return $collectedpayload;
+}
+
+
+
+
+my $MAXCHUNK=$PACKETSIZE-100;
+
+#Sends data over the USB-Link, without handshaking
+sub SendPackets($)
+{
+  print "Sending Packets ...\n";
+  my $data=pack4($_[0]);
+  my $done=0;
+  return if(!defined($data) or !length($data));
+
+  while(!$done)
+  {
+    while(length($data)>0)
+    {
+      my $d=substr($data,0,$MAXCHUNK);
+      if(length($data)>$MAXCHUNK)
+      {
+        send_packet("1".$d);
+        $data=substr($data,$MAXCHUNK);
+      }
+      else
+      {
+        send_packet("0".$d);
+        $data="";
+      }
+    }
+    $done=1;
+  }
+  print "Sending Packets done.\n";
+}
+
+#Receives several packets, verifies the secret key signature and extracts the payload
+#Returns the payload
+sub Receive
+{
+  my $data=receive_packets();
+  if (!defined($data) or length($data)<4)
+  {
+    print "Received data too short!\n";
+    return "";
+  }
+  my $len=unpack("N",substr($data,0,4));
+  if($len != (length($data)-$HASHSIZE-4))
+  {
+    print "Length field does not match data on Receive!\n";
+    return "";
+  }
+  my $payload=substr($data,4,$len);
+  if(sha1($SALT.$payload) ne substr($data,4+$len,$HASHSIZE))
+  {
+    print "Hash on Receive is BROKEN!\n";
+    return "";
+  }
+  return $payload;
+}
+
+
+
+
+# @result(Version,Action,Errorcode,Response)=Request(Version=1,Action=1,System=1,Root=1,Configuration="...",Parameter="...",Request="...");
+sub Request($$$$$$$$$$$)
+{
+  print "Version: $_[0] Action: $_[1] System: $_[2] Root: $_[3] Config: $_[4]\n";
+  $_[3]=0 if($_[3]<0);
+  SendPackets(pack3(pack3(pack("C*",$_[0],$_[1],$_[2],$_[3],$_[4],$_[5],$_[6]>>8,$_[6]&255,$_[7])).pack3($_[8]).pack3($_[9]).pack3($_[10])));
+  my $data=Receive();
+  if(defined($data) and length($data)>6)
+  {
+    my @fields=unpack3array(substr($data,3));
+
+    SysLog "Answer from Server: ".hexdump($data)."\n" if($debug);
+
+    #writefile("result.dat",$data);
+
+    return $fields[1];
+  }
+  return "";
+}
+
+
+sub calculateDays($)
+{
+  if($_[0])
+  {
+    my @sum = $dbh->selectrow_array("select sum(`points`) as `total` from `notary` where `to`='".$_[0]."' group by `to`");
+    SysLog("Summe: $sum[0]\n") if($debug);
+
+    return ($sum[0]>=50)?730:180;
+  }
+  return 180;
+}
+
+sub X509extractSAN($)
+{
+  my @bits = split("/", $_[0]);
+  my $SAN="";
+  my $newsubject="";
+  foreach my $val(@bits)
+  {
+    my @bit=split("=",$val);
+    if($bit[0] eq "subjectAltName")
+    {
+      $SAN.="," if($SAN ne "");
+      $SAN.= trim($bit[1]);
+    } 
+    else 
+    {
+      $newsubject .= "/".$val;
+    }
+  }
+  $newsubject=~s{^//}{/};
+  $newsubject=~s/[\n\r\t\x00"\\']//g;
+  $SAN=~s/[ \n\r\t\x00"\\']//g;
+  return($SAN,$newsubject); 
+}
+
+sub X509extractExpiryDate($)
+{
+  # TIMEZONE ?!?
+  my $data=`$opensslbin x509 -in "$_[0]" -noout -enddate`;
+
+  #notAfter=Aug  8 10:26:34 2007 GMT
+  if($data=~m/notAfter=(\w{2,4}) *(\d{1,2}) *(\d{1,2}:\d{1,2}:\d{1,2}) (\d{4}) GMT/)
+  {
+    my $date="$4-".$monarr{$1}."-$2 $3";
+    SysLog "Expiry Date found: $date\n" if($debug);
+    return $date;
+  }
+  else
+  {
+    SysLog "Expiry Date not found: $data\n";
+  }
+  return "";
+}
+sub X509extractSerialNumber($)
+{
+  # TIMEZONE ?!?
+  my $data=`$opensslbin x509 -in "$_[0]" -noout -serial`;
+  if($data=~m/serial=([0-9A-F]+)/)
+  {
+    return $1;
+  }
+  return "";
+}
+
+sub OpenPGPextractExpiryDate ($) 
+{
+  my $r="";
+  my $cts;
+  my @date;
+  open(RGPG, $gpgbin.' -vv '.$_[0].' 2>&1 |') or Error('Can\'t start GnuPG($gpgbin): '.$!."\n");
+  open(OUT,  '> infogpg.txt'           ) or Error('Can\'t open output file: infogpg.txt: '.$!);
+  $/="\n";
+  while (<RGPG>) 
+  {
+    print OUT $_;
+    unless ($r) 
+    {
+      if ( /^\s*version \d+, created (\d+), md5len 0, sigclass \d+\s*$/ ) 
+      {
+        SysLog "Detected CTS: $1\n";
+        $cts = int($1);
+      } elsif ( /^\s*critical hashed subpkt \d+ len \d+ \(sig expires after ((\d+)y)?((\d+)d)?((\d+)h)?(\d+)m\)\s*$/ ) 
+      {
+        SysLog "Detected FRAME $2 $4 $6 $8\n";
+        $cts += $2 * 31536000; # secs per year (60 * 60 * 24 * 365)
+        $cts += $4 * 86400;    # secs per day  (60 * 60 * 24)
+        $cts += $6 * 3600;     # secs per hour (60 * 60)
+        $cts += $8 * 60;       # secs per min  (60)
+        $r    = $cts;
+      }
+      elsif(/version/)
+      {
+        SysLog "Detected VERSION\n";
+      }
+    }
+  }
+
+  close(OUT );      
+  close(RGPG);
+
+  SysLog "CTS: $cts  R: $r\n";
+  if ( $r ) 
+  {
+    @date = gmtime($r);
+    $r = sprintf('%.4i-%.2i-%.2i %.2i:%.2i:%.2i',            # date format
+    $date[5] + 1900, $date[4] + 1, $date[3], # day
+    $date[2],        $date[1],     $date[0], # time
+    );
+                                                       
+  }
+  SysLog "$r\n";
+  return $r;
+}
+
+
+# Sets the locale according to the users preferred language
+sub setUsersLanguage($)
+{
+  my $lang="de_DE"; 
+  print "Searching for the language of the user $_[0]\n";
+  my @a=$dbh->selectrow_array("select language from users where id='".int($_[0])."'");
+  $lang = $1 if($a[0]=~m/(\w+_[\w.@]+)/);
+
+  SysLog "The users preferred language: $lang\n";
+
+  if($lang ne "")
+  {
+    $ENV{"LANG"}=$lang;
+    setlocale(LC_ALL, $lang);     
+  } else {
+    $ENV{"LANG"}="en_AU";
+    setlocale(LC_ALL, "en_AU");
+  }
+}
+
+
+sub getUserData($)
+{
+  my $sth = $dbh->prepare("select * from users where id='$_[0]'");
+  $sth->execute();
+  #SysLog "USER DUMP:\n";
+  while ( my $rowdata = $sth->fetchrow_hashref() )
+  {
+    my %tmp=%{$rowdata};
+    #foreach (sort keys %tmp)
+    #{
+      #SysLog "  $_ -> $tmp{$_}\n";
+    #}
+    return %tmp;
+  }
+  return ();
+}
+
+
+sub _($)
+{
+  return gettext($_[0]);
+}
+
+sub sendmail($$$$$$$)
+{
+  my ($to, $subject, $message, $from, $replyto, $toname, $fromname)=@_;
+  my $errorsto="returns\@cacert.org";
+  my $extra="";
+  
+
+  # sendmail($user{email}, "[CAcert.org] Your GPG/PGP Key", $body, "support\@cacert.org", "", "", "CAcert Support");
+  my @lines=split("\n",$message);
+  $message = "";
+  foreach my $line (@lines)
+  {
+    $line = trim($line);
+    if($line eq ".")
+    {
+      $message .= " .\n";
+    } else 
+    {
+      $message .= $line."\n";
+    } 
+  }
+
+  $fromname = $from if($fromname eq "");
+               
+  my @bits = split(",", $from);
+  $from = addslashes($bits['0']);
+  $fromname = addslashes($fromname);
+
+  my $smtp = IO::Socket::INET->new(PeerAddr => 'localhost:25');
+  $/="\n";
+  SysLog "SMTP: ".<$smtp>."\n";
+  print $smtp "HELO hlin.cacert.org\r\n";
+  SysLog "SMTP: ".<$smtp>."\n";
+  print $smtp "MAIL FROM: <returns\@cacert.org>\r\n";
+  SysLog "MAIL FROM: ".<$smtp>."\n";
+  @bits = split(",", $to);
+  foreach my $user (@bits)
+  {
+    print $smtp "RCPT TO: <".trim($user).">\r\n";
+    SysLog "RCPT TO: ".<$smtp>."\n";
+  }
+  print $smtp "DATA\r\n";
+  SysLog "DATA: ".<$smtp>."\n";
+
+  print $smtp "X-Mailer: CAcert.org Website\r\n";
+  print $smtp "X-OriginatingIP: ".$ENV{"REMOTE_ADDR"}."\r\n";
+  print $smtp "Sender: $errorsto\r\n";
+  print $smtp "Errors-To: $errorsto\r\n";
+  if($replyto ne "")
+  {
+       print $smtp "Reply-To: $replyto\r\n";
+  }
+  else
+  {
+       print $smtp "Reply-To: $from\r\n";
+  }
+  print $smtp "From: $from ($fromname)\r\n";
+  print $smtp "To: $to\r\n";
+  my $newsubj=encode_base64(recode("html..utf-8", trim($subject)));
+  #SysLog("NewSubj: --".$newsubj."--\n") if($debug);
+  $newsubj=~s/\n*$//;
+  #SysLog("NewSubj: --".$newsubj."--\n") if($debug);
+  print $smtp "Subject: =?utf-8?B?$newsubj?=\r\n";
+  print $smtp "Mime-Version: 1.0\r\n";
+  if($extra eq "")
+  {
+       print $smtp "Content-Type: text/plain; charset=\"utf-8\"\r\n";
+       print $smtp "Content-Transfer-Encoding: 8bit\r\n";
+  } else {
+       print $smtp "Content-Type: text/plain; charset=\"iso-8859-1\"\r\n";
+       print $smtp "Content-Transfer-Encoding: quoted-printable\r\n";
+       print $smtp "Content-Disposition: inline\r\n";
+  };
+#      print $smtp "Content-Transfer-Encoding: BASE64\r\n";
+  print $smtp "\r\n";
+#              print $smtp chunk_split(encode_base64(recode("html..utf-8", $message)))."\r\n.\r\n";
+  print $smtp recode("html..utf-8", $message)."\r\n.\r\n";
+  SysLog "ENDOFTEXT: ".<$smtp>."\n";
+  print $smtp "QUIT\n";
+  SysLog "QUIT: ".<$smtp>."\n";
+  close($smtp);
+}
+
+
+sub HandleCerts($$)
+{
+  my $org=$_[0]?"org":"";
+  my $server=$_[1];
+
+  my $table=$org.($server?"domaincerts":"emailcerts");
+
+  my $sth = $dbh->prepare("select * from $table where crt_name='' and csr_name!='' ");
+  $sth->execute();
+  #$rowdata;
+  while ( my $rowdata = $sth->fetchrow_hashref() )
+  {
+    my %row=%{$rowdata};
+
+    my $csrname = "../csr/".$org.($server?"server-":"client-").$row{'id'}.".csr";
+    my $crtname = "../crt/".$org.($server?"server-":"client-").$row{'id'}.".crt";
+
+
+    if($server)
+    {
+      #Weird SQL structure ...
+      my @sqlres=$dbh->selectrow_array("select memid from domains where id='".int($row{'domid'})."'");
+      $row{'memid'}=$sqlres[0]; 
+      SysLog("Fetched memid: $row{'memid'}\n") if($debug);
+    }
+
+    SysLog "Opening $csrname\n";
+
+    my $crt="";
+
+    my $profile=0;
+
+    #   "0"=>"client.cnf",
+    #   "1"=>"client-org.cnf",
+    #   "2"=>"client-codesign.cnf",
+    #   "3"=>"client-machine.cnf",
+    #   "4"=>"client-ads.cnf",
+    #   "5"=>"server.cnf",
+    #   "6"=>"server-org.cnf",
+    #   "7"=>"server-jabber.cnf",
+    #   "8"=>"server-ocsp.cnf",
+    #   "9"=>"server-timestamp.cnf",
+    #   "10"=>"proxy.cnf",
+    #   "11"=>"subca.cnf"
+
+
+    if($row{"type"} =~ m/^(8|9)$/)
+    {
+      $profile=$row{"type"};
+    }
+    elsif($org)
+    {
+      if($row{'codesign'})
+      {
+        $profile=2; ## TODO!
+      }
+      elsif($server)
+      {
+        $profile=6;
+      }
+      else
+      {
+        $profile=1;
+      }
+    }
+    else
+    {
+      if($row{'codesign'})
+      {
+        $profile=2;
+      }
+      elsif($server)
+      {
+        $profile=5;
+      }
+      else
+      {
+        $profile=0;
+      }
+
+
+    }
+
+
+
+    if(open(IN,"<$csrname"))
+    {
+      undef $/;
+      my $content=<IN>;
+      close IN;
+      SysLog "Read.\n" if($debug);
+      SysLog "Subject: --$row{'subject'}--\n" if($debug);
+
+      my ($SAN,$subject)=X509extractSAN($row{'subject'});
+      SysLog "Subject: --$subject--\n" if($debug);
+      SysLog "SAN: --$SAN--\n" if($debug);
+      SysLog "memid: $row{'memid'}\n" if($debug);
+
+      my $days=$org?($server?(365*2):365):calculateDays($row{"memid"});
+
+
+      $crt=Request($ver,1,1,$row{'rootcert'}-1,$profile,$row{'md'}eq"sha1"?2:0,$days,$row{'keytype'}eq"NS"?1:0,$content,$SAN,$subject);
+      if(length($crt))
+      {
+        if($crt=~m/^-----BEGIN CERTIFICATE-----/)
+        {
+          open OUT,">$crtname";
+          print OUT $crt;
+          close OUT;
+        }
+        else
+        {
+          open OUT,">$crtname.der";
+          print OUT $crt;
+          close OUT;
+          system "$opensslbin x509 -in $crtname.der -inform der -out $crtname";
+        }      
+      }
+
+    }
+    else
+    {
+      print "Error: $! Konnte $csrname nicht laden\n";
+    }
+
+
+
+    if(-s $crtname)
+    {
+      SysLog "Opening $crtname\n";
+
+      my $date=X509extractExpiryDate($crtname);
+      my $serial=X509extractSerialNumber($crtname);
+
+      setUsersLanguage($row{memid});
+
+      my %user=getUserData($row{memid});
+
+      foreach (sort keys %user)
+      {
+        SysLog "  $_ -> $user{$_}\n" if($debug);
+      }
+
+      SysLog("update `$table` set `crt_name`='$crtname', modified=now(), serial='$serial', `expire`='$date' where `id`='".$row{'id'}."'\n");
+
+      $dbh->do("update `$table` set `crt_name`='$crtname', modified=now(), serial='$serial', `expire`='$date' where `id`='".$row{'id'}."'");
+
+      my $body = _("Hi")." $user{fname},\n\n";
+      $body .= sprintf(_("You can collect your certificate for %s by going to the following location:")."\n\n", $row{'email'});
+      $body .= "https://www.cacert.org/account.php?id=".($server?"15":"6")."&cert=$row{id}\n\n";
+      $body .= _("If you havent imported CAcert´s root certificate, please go to:")."\n";
+      $body .= "https://www.cacert.org/index.php?id=3\n";
+      $body .= "Root cert fingerprint = A6:1B:37:5E:39:0D:9C:36:54:EE:BD:20:31:46:1F:6B\n";
+      $body .= "Root cert fingerprint = 135C EC36 F49C B8E9 3B1A B270 CD80 8846 76CE 8F33\n\n";
+      $body .= _("Best regards")."\n"._("CAcert.org Support!")."\n\n";
+      sendmail($user{email}, "[CAcert.org] "._("Your certificate"), $body, "support\@cacert.org", "", "", "CAcert Support");
+    } else {
+      $dbh->do("delete from `$table` where `id`='".$row{'id'}."'");
+    }
+  }
+}
+
+sub HandleNewCRL($$)
+{
+  my ($crl,$crlname)=@_;
+  if(length($crl))
+  {
+    if($crl=~m/^\%XD/)
+    {
+      writefile("$crlname.patch",$crl);
+      system "xdelta patch $crlname.patch $crlname $crlname.tmp"; 
+    }
+    elsif($crl=~m/^-----BEGIN X509 CRL-----/)
+    {
+      writefile("$crlname.pem",$crl);
+      system "$opensslbin crl -in $crlname.pem -outform der -out $crlname.tmp";
+    }
+    elsif($crl=~m/^\x30/)
+    {
+      writefile("$crlname.tmp",$crl);
+    }
+    else
+    {
+      Error "Unknown CRL format!".(substr($crl,0,5))."\n";
+    }
+    rename "$crlname.tmp","$crlname"; # Atomic move
+  }
+}
+
+
+sub RevokeCerts($$)
+{
+  my $org=$_[0]?"org":"";
+  my $server=$_[1];
+
+  my $table=$org.($server?"domaincerts":"emailcerts");
+
+  my $sth = $dbh->prepare("select * from $table where revoked='1970-01-01 10:00:01'"); # WHICH TIMEZONE?
+  $sth->execute();
+  #$rowdata;
+  while ( my $rowdata = $sth->fetchrow_hashref() )
+  {
+    my %row=%{$rowdata};
+
+    my $csrname = "../csr/".$org.($server?"server-":"client-").$row{'id'}.".csr";
+    my $crtname = "../crt/".$org.($server?"server-":"client-").$row{'id'}.".crt";
+    my $crlname = $revokefile{$row{'rootcert'}};
+
+    my $crt="";
+
+
+    if(open(IN,"<$crtname"))
+    {
+      undef $/;
+      my $content=<IN>;
+      close IN;
+      my $revokehash=sha1_hex(readfile($crlname));
+
+      my $crl=Request($ver,2,1,$row{'rootcert'}-1,0,0,365,0,$content,"",$revokehash);
+      HandleNewCRL($crl,$crlname);
+
+      if(-s $crlname)
+      {
+        setUsersLanguage($row{memid});
+
+        my %user=getUserData($row{memid});
+
+        $dbh->do("update `$table` set `revoked`=now() where `id`='".$row{'id'}."'");
+
+        my $body = _("Hi")." $user{fname},\n\n";
+        $body .= sprintf(_("Your certificate for %s has been revoked, as per request.")."\n\n", $row{'CN'});
+        $body .= _("Best regards")."\n"._("CAcert.org Support!")."\n\n";
+        sendmail($user{email}, "[CAcert.org] "._("Your certificate"), $body, "support\@cacert.org", "", "", "CAcert Support");
+      }
+
+    }
+    else
+    {
+      SysLog("Error: $crtname $!\n") if($debug);
+    }
+
+  }
+
+}
+
+
+
+
+
+sub HandleGPG()
+{
+  my $sth = $dbh->prepare("select * from gpg where crt='' and csr!='' ");
+  $sth->execute();
+  my $rowdata;
+  while ( $rowdata = $sth->fetchrow_hashref() )
+  {
+    my %row=%{$rowdata};
+  
+    my $csrname = "../csr/gpg-".$row{'id'}.".csr";
+    my $crtname = "../crt/gpg-".$row{'id'}.".crt";
+  
+    SysLog "Opening $csrname\n";
+  
+    my $crt="";
+  
+    if(-s $csrname && open(IN,"<$csrname"))
+    {
+      undef $/;
+      my $content=<IN>;
+      close IN;
+      SysLog "Read.\n";
+      $crt=Request($ver,1,2,0,0,2,366,0,$content,"","");
+      if(length($crt))
+      {
+        open OUT,">$crtname";
+        print OUT $crt;
+        close OUT;
+      }
+
+    }
+    else
+    {
+      #Error("Error: $!\n");
+      next;
+    }
+
+    if(-s $crtname)
+    {
+      SysLog "Opening $crtname\n";
+      setUsersLanguage($row{memid});
+  
+      my $date=OpenPGPextractExpiryDate($crtname);
+      my %user=getUserData($row{memid});
+  
+      $dbh->do("update `gpg` set `crt`='$crtname', issued=now(), `expire`='$date' where `id`='".$row{'id'}."'");
+  
+      my $body = _("Hi")." $user{fname},\n\n";
+      $body .= sprintf(_("Your CAcert signed key for %s is available online at:")."\n\n", $row{'email'});
+      $body .= "https://www.cacert.org/gpg.php?id=3&cert=$row{id}\n\n";
+      $body .= _("To help improve the trust of CAcert in general, it's appreciated if you could also sign our key and upload it to a key server. Below is a copy of our primary key details:")."\n\n";
+      $body .= "pub 1024D/65D0FD58 2003-07-11 CA Cert Signing Authority (Root CA) <gpg\@cacert.org>\n";
+      $body .= "Key fingerprint = A31D 4F81 EF4E BD07 B456 FA04 D2BB 0D01 65D0 FD58\n\n";
+      $body .= _("Best regards")."\n"._("CAcert.org Support!")."\n\n";
+      sendmail($user{email}, "[CAcert.org] Your GPG/PGP Key", $body, "support\@cacert.org", "", "", "CAcert Support");
+    } else {
+      $dbh->do("delete from `gpg` where `id`='".$row{'id'}."'");
+    }
+  }
+}
+
+
+# Main program loop
+
+while(1)
+{
+  SysLog("Handling GPG database ...\n");
+#  HandleGPG();
+  SysLog("Issueing certs ...\n");
+#  HandleCerts(0,0); #personal client certs
+#  HandleCerts(0,1); #personal server certs
+#  HandleCerts(1,0); #org client certs
+#  HandleCerts(1,1); #org server certs
+#  SysLog("Revoking certs ...\n");
+#  RevokeCerts(0,0); #personal client certs
+#  RevokeCerts(0,1); #personal server certs
+#  RevokeCerts(1,0); #org client certs
+#  RevokeCerts(1,1); #org server certs
+
+  #print "Sign Request X.509, Root0\n";
+  #my $reqcontent="";
+  #Request($ver,1,1,0,5,2,365,0,$reqcontent,"","/CN=supertest.cacert.at");
+
+  SysLog("NUL Request:\n");
+  my $timestamp=strftime("%m%d%H%M%Y.%S",gmtime);
+  my $ret=Request($ver,0,0,0,0,0,0,0,$timestamp,"","");
+  print "RET: $ret\n";
+
+  SysLog("Generate regular CRLs:\n");
+  foreach my $root ((1,2))
+  {
+    my $crlname = $revokefile{$root};
+    my $revokehash=sha1_hex(readfile($crlname));
+    print "Aktueller Hash am Webserver: $revokehash\n";
+    my $crl=Request($ver,2,1,$root-1,0,0,365,0,"","",$revokehash);
+    HandleNewCRL($crl,$crlname);
+  }
+
+  usleep(700000); 
+}
diff --git a/cacert/LICENSE b/cacert/LICENSE
new file mode 100644 (file)
index 0000000..21b9363
--- /dev/null
@@ -0,0 +1,341 @@
+                   GNU GENERAL PUBLIC LICENSE
+                      Version 2, June 1991
+
+ Copyright (C) 1989, 1991 Free Software Foundation, Inc.
+               51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+                           Preamble
+
+  The licenses for most software are designed to take away your
+freedom to share and change it.  By contrast, the GNU General Public
+License is intended to guarantee your freedom to share and change free
+software--to make sure the software is free for all its users.  This
+General Public License applies to most of the Free Software
+Foundation's software and to any other program whose authors commit to
+using it.  (Some other Free Software Foundation software is covered by
+the GNU Library General Public License instead.)  You can apply it to
+your programs, too.
+
+  When we speak of free software, we are referring to freedom, not
+price.  Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+this service if you wish), that you receive source code or can get it
+if you want it, that you can change the software or use pieces of it
+in new free programs; and that you know you can do these things.
+
+  To protect your rights, we need to make restrictions that forbid
+anyone to deny you these rights or to ask you to surrender the rights.
+These restrictions translate to certain responsibilities for you if you
+distribute copies of the software, or if you modify it.
+
+  For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must give the recipients all the rights that
+you have.  You must make sure that they, too, receive or can get the
+source code.  And you must show them these terms so they know their
+rights.
+
+  We protect your rights with two steps: (1) copyright the software, and
+(2) offer you this license which gives you legal permission to copy,
+distribute and/or modify the software.
+
+  Also, for each author's protection and ours, we want to make certain
+that everyone understands that there is no warranty for this free
+software.  If the software is modified by someone else and passed on, we
+want its recipients to know that what they have is not the original, so
+that any problems introduced by others will not reflect on the original
+authors' reputations.
+
+  Finally, any free program is threatened constantly by software
+patents.  We wish to avoid the danger that redistributors of a free
+program will individually obtain patent licenses, in effect making the
+program proprietary.  To prevent this, we have made it clear that any
+patent must be licensed for everyone's free use or not licensed at all.
+
+  The precise terms and conditions for copying, distribution and
+modification follow.
+\f
+                   GNU GENERAL PUBLIC LICENSE
+   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+  0. This License applies to any program or other work which contains
+a notice placed by the copyright holder saying it may be distributed
+under the terms of this General Public License.  The "Program", below,
+refers to any such program or work, and a "work based on the Program"
+means either the Program or any derivative work under copyright law:
+that is to say, a work containing the Program or a portion of it,
+either verbatim or with modifications and/or translated into another
+language.  (Hereinafter, translation is included without limitation in
+the term "modification".)  Each licensee is addressed as "you".
+
+Activities other than copying, distribution and modification are not
+covered by this License; they are outside its scope.  The act of
+running the Program is not restricted, and the output from the Program
+is covered only if its contents constitute a work based on the
+Program (independent of having been made by running the Program).
+Whether that is true depends on what the Program does.
+
+  1. You may copy and distribute verbatim copies of the Program's
+source code as you receive it, in any medium, provided that you
+conspicuously and appropriately publish on each copy an appropriate
+copyright notice and disclaimer of warranty; keep intact all the
+notices that refer to this License and to the absence of any warranty;
+and give any other recipients of the Program a copy of this License
+along with the Program.
+
+You may charge a fee for the physical act of transferring a copy, and
+you may at your option offer warranty protection in exchange for a fee.
+
+  2. You may modify your copy or copies of the Program or any portion
+of it, thus forming a work based on the Program, and copy and
+distribute such modifications or work under the terms of Section 1
+above, provided that you also meet all of these conditions:
+
+    a) You must cause the modified files to carry prominent notices
+    stating that you changed the files and the date of any change.
+
+    b) You must cause any work that you distribute or publish, that in
+    whole or in part contains or is derived from the Program or any
+    part thereof, to be licensed as a whole at no charge to all third
+    parties under the terms of this License.
+
+    c) If the modified program normally reads commands interactively
+    when run, you must cause it, when started running for such
+    interactive use in the most ordinary way, to print or display an
+    announcement including an appropriate copyright notice and a
+    notice that there is no warranty (or else, saying that you provide
+    a warranty) and that users may redistribute the program under
+    these conditions, and telling the user how to view a copy of this
+    License.  (Exception: if the Program itself is interactive but
+    does not normally print such an announcement, your work based on
+    the Program is not required to print an announcement.)
+\f
+These requirements apply to the modified work as a whole.  If
+identifiable sections of that work are not derived from the Program,
+and can be reasonably considered independent and separate works in
+themselves, then this License, and its terms, do not apply to those
+sections when you distribute them as separate works.  But when you
+distribute the same sections as part of a whole which is a work based
+on the Program, the distribution of the whole must be on the terms of
+this License, whose permissions for other licensees extend to the
+entire whole, and thus to each and every part regardless of who wrote it.
+
+Thus, it is not the intent of this section to claim rights or contest
+your rights to work written entirely by you; rather, the intent is to
+exercise the right to control the distribution of derivative or
+collective works based on the Program.
+
+In addition, mere aggregation of another work not based on the Program
+with the Program (or with a work based on the Program) on a volume of
+a storage or distribution medium does not bring the other work under
+the scope of this License.
+
+  3. You may copy and distribute the Program (or a work based on it,
+under Section 2) in object code or executable form under the terms of
+Sections 1 and 2 above provided that you also do one of the following:
+
+    a) Accompany it with the complete corresponding machine-readable
+    source code, which must be distributed under the terms of Sections
+    1 and 2 above on a medium customarily used for software interchange; or,
+
+    b) Accompany it with a written offer, valid for at least three
+    years, to give any third party, for a charge no more than your
+    cost of physically performing source distribution, a complete
+    machine-readable copy of the corresponding source code, to be
+    distributed under the terms of Sections 1 and 2 above on a medium
+    customarily used for software interchange; or,
+
+    c) Accompany it with the information you received as to the offer
+    to distribute corresponding source code.  (This alternative is
+    allowed only for noncommercial distribution and only if you
+    received the program in object code or executable form with such
+    an offer, in accord with Subsection b above.)
+
+The source code for a work means the preferred form of the work for
+making modifications to it.  For an executable work, complete source
+code means all the source code for all modules it contains, plus any
+associated interface definition files, plus the scripts used to
+control compilation and installation of the executable.  However, as a
+special exception, the source code distributed need not include
+anything that is normally distributed (in either source or binary
+form) with the major components (compiler, kernel, and so on) of the
+operating system on which the executable runs, unless that component
+itself accompanies the executable.
+
+If distribution of executable or object code is made by offering
+access to copy from a designated place, then offering equivalent
+access to copy the source code from the same place counts as
+distribution of the source code, even though third parties are not
+compelled to copy the source along with the object code.
+\f
+  4. You may not copy, modify, sublicense, or distribute the Program
+except as expressly provided under this License.  Any attempt
+otherwise to copy, modify, sublicense or distribute the Program is
+void, and will automatically terminate your rights under this License.
+However, parties who have received copies, or rights, from you under
+this License will not have their licenses terminated so long as such
+parties remain in full compliance.
+
+  5. You are not required to accept this License, since you have not
+signed it.  However, nothing else grants you permission to modify or
+distribute the Program or its derivative works.  These actions are
+prohibited by law if you do not accept this License.  Therefore, by
+modifying or distributing the Program (or any work based on the
+Program), you indicate your acceptance of this License to do so, and
+all its terms and conditions for copying, distributing or modifying
+the Program or works based on it.
+
+  6. Each time you redistribute the Program (or any work based on the
+Program), the recipient automatically receives a license from the
+original licensor to copy, distribute or modify the Program subject to
+these terms and conditions.  You may not impose any further
+restrictions on the recipients' exercise of the rights granted herein.
+You are not responsible for enforcing compliance by third parties to
+this License.
+
+  7. If, as a consequence of a court judgment or allegation of patent
+infringement or for any other reason (not limited to patent issues),
+conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License.  If you cannot
+distribute so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you
+may not distribute the Program at all.  For example, if a patent
+license would not permit royalty-free redistribution of the Program by
+all those who receive copies directly or indirectly through you, then
+the only way you could satisfy both it and this License would be to
+refrain entirely from distribution of the Program.
+
+If any portion of this section is held invalid or unenforceable under
+any particular circumstance, the balance of the section is intended to
+apply and the section as a whole is intended to apply in other
+circumstances.
+
+It is not the purpose of this section to induce you to infringe any
+patents or other property right claims or to contest validity of any
+such claims; this section has the sole purpose of protecting the
+integrity of the free software distribution system, which is
+implemented by public license practices.  Many people have made
+generous contributions to the wide range of software distributed
+through that system in reliance on consistent application of that
+system; it is up to the author/donor to decide if he or she is willing
+to distribute software through any other system and a licensee cannot
+impose that choice.
+
+This section is intended to make thoroughly clear what is believed to
+be a consequence of the rest of this License.
+\f
+  8. If the distribution and/or use of the Program is restricted in
+certain countries either by patents or by copyrighted interfaces, the
+original copyright holder who places the Program under this License
+may add an explicit geographical distribution limitation excluding
+those countries, so that distribution is permitted only in or among
+countries not thus excluded.  In such case, this License incorporates
+the limitation as if written in the body of this License.
+
+  9. The Free Software Foundation may publish revised and/or new versions
+of the General Public License from time to time.  Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+Each version is given a distinguishing version number.  If the Program
+specifies a version number of this License which applies to it and "any
+later version", you have the option of following the terms and conditions
+either of that version or of any later version published by the Free
+Software Foundation.  If the Program does not specify a version number of
+this License, you may choose any version ever published by the Free Software
+Foundation.
+
+  10. If you wish to incorporate parts of the Program into other free
+programs whose distribution conditions are different, write to the author
+to ask for permission.  For software which is copyrighted by the Free
+Software Foundation, write to the Free Software Foundation; we sometimes
+make exceptions for this.  Our decision will be guided by the two goals
+of preserving the free status of all derivatives of our free software and
+of promoting the sharing and reuse of software generally.
+
+                           NO WARRANTY
+
+  11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
+FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN
+OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
+PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
+OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS
+TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE
+PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
+REPAIR OR CORRECTION.
+
+  12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
+REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
+INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
+OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
+TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
+YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
+PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
+POSSIBILITY OF SUCH DAMAGES.
+
+                    END OF TERMS AND CONDITIONS
+
+
+           How to Apply These Terms to Your New Programs
+
+  If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+  To do so, attach the following notices to the program.  It is safest
+to attach them to the start of each source file to most effectively
+convey the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+    <one line to give the program's name and a brief idea of what it does.>
+    Copyright (C) 19yy  <name of author>
+
+    This program is free software; you can redistribute it and/or modify
+    it under the terms of the GNU General Public License as published by
+    the Free Software Foundation; either version 2 of the License, or
+    (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License
+    along with this program; if not, write to the Free Software
+    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+
+
+Also add information on how to contact you by electronic and paper mail.
+
+If the program is interactive, make it output a short notice like this
+when it starts in an interactive mode:
+
+    Gnomovision version 69, Copyright (C) 19yy name of author
+    Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+    This is free software, and you are welcome to redistribute it
+    under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License.  Of course, the commands you use may
+be called something other than `show w' and `show c'; they could even be
+mouse-clicks or menu items--whatever suits your program.
+
+You should also get your employer (if you work as a programmer) or your
+school, if any, to sign a "copyright disclaimer" for the program, if
+necessary.  Here is a sample; alter the names:
+
+  Yoyodyne, Inc., hereby disclaims all copyright interest in the program
+  `Gnomovision' (which makes passes at compilers) written by James Hacker.
+
+  <signature of Ty Coon>, 1 April 1989
+  Ty Coon, President of Vice
+
+This General Public License does not permit incorporating your program into
+proprietary programs.  If your program is a subroutine library, you may
+consider it more useful to permit linking proprietary applications with the
+library.  If this is what you want to do, use the GNU Library General
+Public License instead of this License.
diff --git a/cacert/Makefile b/cacert/Makefile
new file mode 100644 (file)
index 0000000..914d979
--- /dev/null
@@ -0,0 +1,7 @@
+all:
+       xgettext -s -o messages.po --no-wrap --foreign-user includes/*.php www/*.php pages/account/*.php pages/index/*.php pages/wot/*.php pages/gpg/*.php pages/disputes/*.php pages/help/*.php pages/disputes/*.php scripts/removedead.php
+       perl cacertupload.pl
+       cd locale; php make.php
+
+other: all
+       cat messages.po|sed "s/CHARSET/iso-8859-1/"|sed "s/PACKAGE VERSION/CAcert/"|sed "s/This file is put in the public domain./This file is distributed under the same license as the CAcert package./"|sed "s/# SOME DESCRIPTIVE TITLE.//" > messages.po
diff --git a/cacert/README b/cacert/README
new file mode 100644 (file)
index 0000000..02b2937
--- /dev/null
@@ -0,0 +1,15 @@
+LibreSSL Documentation
+
+(c) 2005-2008 by CAcert Inc.
+License: GNU-GPLv2
+
+System Requirements:
+Linux/POSIX
+PHP
+UFPDF - PDF generation library from http://acko.net/node/56
+OpenSSL - X.509 toolkit from http://www.openssl.org/
+GnuPG - OpenPGP toolkit from http://www.gnupg.org/
+whois - whois client from http://www.linux.it/~md/software/
+XEnroll - Enrollment Active-X control for IE5/6 from Microsoft (search for xenroll.cab)
+CommModule - CAcert Communication Module
+
diff --git a/cacert/cacertupload.pl b/cacert/cacertupload.pl
new file mode 100644 (file)
index 0000000..4c883c8
--- /dev/null
@@ -0,0 +1,53 @@
+#!/usr/bin/perl
+
+#LibreSSL - CAcert web application
+#Copyright (C) 2004-2008  CAcert Inc.
+#
+#This program is free software; you can redistribute it and/or modify
+#it under the terms of the GNU General Public License as published by
+#the Free Software Foundation; version 2 of the License.
+#
+#This program is distributed in the hope that it will be useful,
+#but WITHOUT ANY WARRANTY; without even the implied warranty of
+#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+#GNU General Public License for more details.
+#
+#You should have received a copy of the GNU General Public License
+#along with this program; if not, write to the Free Software
+#Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+
+use LWP::UserAgent;
+$ua = LWP::UserAgent->new(agent => 'Translingo Client 1.0');
+use HTTP::Request::Common qw(POST);
+
+$ua->cookie_jar({});
+$ua->timeout(10000);
+
+my $req = POST 'http://translingo.cacert.org/login.php',
+[
+];
+# ggf. Referer faken
+$req->referer('http://translingo.cacert.org/');
+ $ua->request($req)->as_string;
+
+# 1.Test - Umgebung
+my $req = POST 'http://translingo.cacert.org/login.php',
+[
+ username => 'support@cacert.org',
+ password => 'ilccSSAMNIemU',
+ submit => 'Login',
+];
+# ggf. Referer faken
+$req->referer('http://translingo.cacert.org/');
+$ua->request($req)->as_string;
+
+# 2.Test - FileUpload
+my $req = POST 'http://translingo.cacert.org/upload.php',
+Content_Type => 'form-data',
+Content => [
+ project => '1',
+ fileformat => '1',
+ pofile   => ["messages.po" => "messages.po", 'Content_Type' => "application/x-gettext"],
+];
+print $ua->request($req)->as_string;
+
diff --git a/cacert/cgi-bin/CVS/Entries b/cacert/cgi-bin/CVS/Entries
new file mode 100644 (file)
index 0000000..883ec37
--- /dev/null
@@ -0,0 +1,2 @@
+/siteseal.cgi/1.4/Sun Apr  6 19:45:25 2008//
+D
diff --git a/cacert/cgi-bin/CVS/Repository b/cacert/cgi-bin/CVS/Repository
new file mode 100644 (file)
index 0000000..0dca230
--- /dev/null
@@ -0,0 +1 @@
+cacert/cgi-bin
diff --git a/cacert/cgi-bin/CVS/Root b/cacert/cgi-bin/CVS/Root
new file mode 100644 (file)
index 0000000..a363882
--- /dev/null
@@ -0,0 +1 @@
+/var/lib/cvs
diff --git a/cacert/cgi-bin/siteseal.cgi b/cacert/cgi-bin/siteseal.cgi
new file mode 100755 (executable)
index 0000000..ac28697
--- /dev/null
@@ -0,0 +1,92 @@
+#!/usr/bin/php -q
+<?
+/**
+ * check site seal
+ *
+ * @package org.cacert.framework
+ * @author Duane Groth <duane@groth.net>
+ * @copyright Copyright (C) 2003-2008, {@link http://www.cacert.org/ CAcert Inc.}
+ * @license GPL Version 2
+ * @version $Id: siteseal.cgi,v 1.4 2008-04-06 19:44:25 root Exp $
+ */
+
+if($_SERVER["HTTPS"] == "on")
+  $http = "https";
+else
+  $http = "http";
+
+/* obfuscate var names */
+srand((double)microtime()*1000000);
+$var1 = "ca1-".md5(rand(0,9999999));
+$var2 = "ca2-".md5(rand(0,9999999));
+$var3 = "ca3-".md5(rand(0,9999999));
+$var4 = "ca4-".md5(rand(0,9999999));
+$var5 = "ca5-".md5(rand(0,9999999));
+$var6 = "ca6-".md5(rand(0,9999999));
+$var7 = "ca7-".md5(rand(0,9999999));
+$var8 = "ca8-".md5(rand(0,9999999));
+$var9 = "ca9-".md5(rand(0,9999999));
+$var10 = "caa-".md5(rand(0,9999999));
+$var11 = "cab-".md5(rand(0,9999999));
+
+header("Content-Type: text/javascript");
+header("Content-Disposition: inline; filename=\"siteseal.js\"");
+
+?>
+
+var <?=$var1?> = window.location.href;
+<? // var <?=$var2?> = '<?=$http?>://www.cacert.org/certdetails.php?referer=' + <?=$var1?>; ?>
+var <?=$var2?> = '<?=$http?>://www.cacert.org';
+var <?=$var3?> = (new Date()).getTimezoneOffset();
+
+var <?=$var4?> = navigator.userAgent.toLowerCase();
+var <?=$var5?> = false;
+if (<?=$var4?>.indexOf("msid") != 1) {
+  <?=$var5?> = (<?=$var4?>.indexOf("msie 5") == -1 && <?=$var4?>.indexOf("msie 6") == -1);
+}
+
+function <?=$var6?>(e) {
+  if (document.addEventListener) {
+    if (e.target.name == '<?=$var7?>') {
+      <?=$var8?>();
+      return false;
+    }
+  } else if (document.captureEvents) {
+    if (e.target.toString().indexOf('certdetails') != -1) {
+      <?=$var8?>();
+      return false;
+    }
+  }
+  return true;
+}
+
+function <?=$var9?>() {
+  if (event.button == 1) {
+    if (<?=$var5?>) {
+      return true;
+    } else {
+      <?=$var8?>();
+      return false;
+    }
+  } else if (event.button == 2) {
+    <?=$var8?>();
+    return false;
+  }
+}
+
+function <?=$var8?>() {
+  cacertWindow = window.open(<?=$var2?>, '<?=$var10?>', config='height=420,width=523,toolbar=no,menubar=no,scrollbars=no,resizable=no,location=no,directories=no,status=yes');
+  cacertWindow.focus();
+}
+
+if (document.addEventListener) {
+  document.addEventListener('mouseup', <?=$var6?>, true);
+} else {
+  if (document.layers) {
+    document.captureEvents(Event.MOUSEDOWN);
+    document.onmousedown=<?=$var6?>;
+  }
+}
+
+document.write("<a href='" + <?=$var2?> + "' target='<?=$var10?>'  tabindex='-1' onmousedown='<?=$var9?>(); return false;'><img name='<?=$var7?>' border='0' src='<?=$http?>://www.cacert.org/sealgen.php?cert=<?=$cert?>&referer=" + <?=$var1?> + "' alt='Click to verify' oncontextmenu='return false;' /></a>"); ?>
+
diff --git a/cacert/includes/.cvsignore b/cacert/includes/.cvsignore
new file mode 100644 (file)
index 0000000..3317ea5
--- /dev/null
@@ -0,0 +1,2 @@
+mysql.php
+hash_password.php
diff --git a/cacert/includes/CVS/Entries b/cacert/includes/CVS/Entries
new file mode 100644 (file)
index 0000000..cb3aa42
--- /dev/null
@@ -0,0 +1,12 @@
+/mysql.php.sample/1.10/Sun Apr  6 19:45:25 2008//
+/shutdown.php/1.2/Sun Apr  6 19:45:25 2008//
+/.cvsignore/1.2/Thu Sep  4 13:54:37 2008//
+/loggedin.php/1.17/Sun Nov 23 05:09:08 2008//
+/about_menu.php/1.9/Sun Apr 19 23:37:56 2009//
+/account.php/1.141/Sun May 31 16:50:55 2009//
+/account_stuff.php/1.52/Sun May 31 16:50:55 2009//
+/sponsorinfo.php/1.4/Sun May 31 16:50:55 2009//
+/tverify_stuff.php/1.6/Sun May 31 16:50:55 2009//
+/general.php/1.79/Thu Jun 25 20:09:26 2009//
+/general_stuff.php/1.45/Thu Jun 25 20:09:26 2009//
+D
diff --git a/cacert/includes/CVS/Repository b/cacert/includes/CVS/Repository
new file mode 100644 (file)
index 0000000..4cf480c
--- /dev/null
@@ -0,0 +1 @@
+cacert/includes
diff --git a/cacert/includes/CVS/Root b/cacert/includes/CVS/Root
new file mode 100644 (file)
index 0000000..a363882
--- /dev/null
@@ -0,0 +1 @@
+/var/lib/cvs
diff --git a/cacert/includes/about_menu.php b/cacert/includes/about_menu.php
new file mode 100644 (file)
index 0000000..66ec38f
--- /dev/null
@@ -0,0 +1,21 @@
+    <div class="relatedLinks">
+      <h3 onclick="explode('misc')">+ <?=_("About CAcert.org")?></h3>
+      <ul class="menu" id="misc">
+        <li><a href="http://blog.cacert.org/"><?=_("CAcert News")?></a></li>
+       <li><a href="/help.php"><?=_("Howto Information")?></a></li>
+       <li><a href="http://wiki.CAcert.org/"><?=_("Wiki Documentation")?></a></li>
+       <li><a href="/policy/"><?=_("Policies")?></a></li>
+       <li><a href="/index.php?id=19"><?=_("Point System")?></a></li>
+       <li><a href="/policy/NRPDisclaimerAndLicence.php" target="_blank"><?=_("Disclaimer")?></a></li>
+       <li><a href="http://bugs.CAcert.org/"><?=_("Bug Database")?></a></li>
+<? //  <li><a href="/index.php?id=47"><  = _ ("PR Materials" )  > </a></li> ?>
+<? //  <li><a href="/logos.php">< ? = _ ( " CAcert Logos " ) ? > </a></li> ?>
+<? if(array_key_exists('mconn',$_SESSION) && $_SESSION['mconn']) { ?>  <li><a href="/stats.php"><?=_("CAcert Statistics")?></a></li> <? } ?>
+       <li><a href="http://blog.CAcert.org/feed/"><?=_("RSS News Feed")?></a></li>
+<? //- <li><a href="/index.php?id=7"> < ? = _ ( " Credits " ) ? > </a></li> ?>
+       <li><a href="/index.php?id=8"><?=_("CAcert Board")?></a></li>
+       <li><a href="https://lists.cacert.org/wws"><?=_("Mailing Lists")?></a></li>
+       <li><a href="/src-lic.php"><?=_("Sourcecode")?></a></li>
+      </ul>
+    </div>
+
diff --git a/cacert/includes/account.php b/cacert/includes/account.php
new file mode 100644 (file)
index 0000000..bee04ee
--- /dev/null
@@ -0,0 +1,2792 @@
+<? /*
+    LibreSSL - CAcert web application
+    Copyright (C) 2004-2008  CAcert Inc.
+
+    This program is free software; you can redistribute it and/or modify
+    it under the terms of the GNU General Public License as published by
+    the Free Software Foundation; version 2 of the License.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+    GNU General Public License for more details.
+  
+    You should have received a copy of the GNU General Public License
+    along with this program; if not, write to the Free Software
+    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+*/
+       require_once("../includes/loggedin.php");
+
+       loadem("account");
+
+       $id = 0; if(array_key_exists("id",$_REQUEST)) $id=intval($_REQUEST['id']);
+       $oldid = 0; if(array_key_exists("oldid",$_REQUEST)) $oldid=intval($_REQUEST['oldid']);
+       $process = ""; if(array_key_exists("process",$_REQUEST)) $process=$_REQUEST['process'];
+
+       $cert=0; if(array_key_exists('cert',$_REQUEST)) $cert=intval($_REQUEST['cert']);
+       $orgid=0; if(array_key_exists('orgid',$_REQUEST)) $orgid=intval($_REQUEST['orgid']);
+       $memid=0; if(array_key_exists('memid',$_REQUEST)) $memid=intval($_REQUEST['memid']);
+       $domid=0; if(array_key_exists('domid',$_REQUEST)) $domid=intval($_REQUEST['domid']);
+
+
+       if(!$_SESSION['mconn'])
+       {
+               echo _("Several CAcert Services are currently unavailable. Please try again later.");
+               exit;
+       }
+
+
+       if($id == 45 || $id == 46 || $oldid == 45 || $oldid == 46)
+       {
+               $id = 1;
+               $oldid=0;
+       }
+
+       if($process != "" && $oldid == 1)
+       {
+               $id = 1;
+               csrf_check('addemail');
+               if(strstr($_REQUEST['newemail'], "xn--") && $_SESSION['profile']['codesign'] <= 0)
+               {
+                       showheader(_("My CAcert.org Account!"));
+                       echo _("Due to the possibility for punycode domain exploits we currently do not allow any certificates to sign punycode domains or email addresses.");
+                       showfooter();
+                       exit;
+               }
+               if(trim(mysql_real_escape_string(stripslashes($_REQUEST['newemail']))) == "")
+               {
+                       showheader(_("My CAcert.org Account!"));
+                       printf(_("Not a valid email address. Can't continue."));
+                       showfooter();
+                       exit;
+               }
+               $oldid=0;
+               $_REQUEST['email'] = trim(mysql_real_escape_string(stripslashes($_REQUEST['newemail'])));
+               $query = "select * from `email` where `email`='".$_REQUEST['email']."' and `deleted`=0";
+               $res = mysql_query($query);
+               if(mysql_num_rows($res) > 0)
+               {
+                       showheader(_("My CAcert.org Account!"));
+                       printf(_("The email address '%s' is already in the system. Can't continue."), sanitizeHTML($_REQUEST['email']));
+                       showfooter();
+                       exit;
+               }
+               $checkemail = checkEmail($_REQUEST['newemail']);
+               if($checkemail != "OK")
+               {
+                       showheader(_("My CAcert.org Account!"));
+                       if (substr($checkemail, 0, 1) == "4") 
+                       {
+                               echo "<p>"._("The mail server responsible for your domain indicated a temporary failure. This may be due to anti-SPAM measures, such as greylisting. Please try again in a few minutes.")."</p>\n";
+                       } else {
+                               echo "<p>"._("Email Address given was invalid, or a test connection couldn't be made to your server, or the server rejected the email address as invalid")."</p>\n";
+                       }
+                       echo "<p>$checkemail</p>\n";
+                       showfooter();
+                       exit;
+               }
+               $hash = make_hash();
+               $query = "insert into `email` set `email`='".$_REQUEST['email']."',`memid`='".$_SESSION['profile']['id']."',`created`=NOW(),`hash`='$hash'";
+               mysql_query($query);
+               $emailid = mysql_insert_id();
+
+               $body = _("Below is the link you need to open to verify your email address. Once your address is verified you will be able to start issuing certificates to your heart's content!")."\n\n";
+               $body .= "http://".$_SESSION['_config']['normalhostname']."/verify.php?type=email&emailid=$emailid&hash=$hash\n\n";
+               $body .= _("Best regards")."\n"._("CAcert.org Support!");
+
+               sendmail($_REQUEST['email'], "[CAcert.org] "._("Email Probe"), $body, "support@cacert.org", "", "", "CAcert Support");
+
+               showheader(_("My CAcert.org Account!"));
+               printf(_("The email address '%s' has been added to the system, however before any certificates for this can be issued you need to open the link in a browser that has been sent to your email address."), sanitizeHTML($_REQUEST['email']));
+               showfooter();
+               exit;
+       }
+
+       if(array_key_exists("makedefault",$_REQUEST) && $_REQUEST['makedefault'] != "" && $oldid == 2)
+       {
+               $id = 2;
+               $emailid = intval($_REQUEST['emailid']);
+               $query = "select * from `email` where `id`='$emailid' and `memid`='".$_SESSION['profile']['id']."' and `hash` = '' and `deleted`=0";
+               $res = mysql_query($query);
+               if(mysql_num_rows($res) <= 0)
+               {
+                       showheader(_("Error!"));
+                       echo _("You currently don't have access to the email address you selected, or you haven't verified it yet.");
+                       showfooter();
+                       exit;
+               }
+               $row = mysql_fetch_assoc($res);
+               $body  = sprintf(_("Hi %s,"),$_SESSION['profile']['fname'])."\n";
+               $body .= _("You are receiving this email because you or someone else")."\n";
+               $body .= _("has changed the default email on your account.")."\n\n";
+
+               $body .= _("Best regards")."\n"._("CAcert.org Support!");
+
+               sendmail($_SESSION['profile']['email'], "[CAcert.org] "._("Default Account Changed"), $body,
+                               "support@cacert.org", "", "", "CAcert Support");
+
+               $_SESSION['profile']['email'] = $row['email'];
+               $query = "update `users` set `email`='".$row['email']."' where `id`='".$_SESSION['profile']['id']."'";
+               mysql_query($query);
+               showheader(_("My CAcert.org Account!"));
+               printf(_("Your default email address has been updated to '%s'."), sanitizeHTML($row['email']));
+               showfooter();
+               exit;
+       }
+
+       if($process != "" && $oldid == 2)
+       {
+               $id = 2;
+               csrf_check("chgdef");
+               showheader(_("My CAcert.org Account!"));
+               $delcount = 0;
+               if(array_key_exists('delid',$_REQUEST) && is_array($_REQUEST['delid']))
+               {
+                       foreach($_REQUEST['delid'] as $id)
+                       {
+                               $id = intval($id);
+                               $query = "select * from `email` where `id`='$id' and `memid`='".intval($_SESSION['profile']['id'])."' and
+                                               `email`!='".$_SESSION['profile']['email']."'";
+                               $res = mysql_query($query);
+                               if(mysql_num_rows($res) > 0)
+                               {
+                                       $row = mysql_fetch_assoc($res);
+                                       echo $row['email']."<br>\n";
+                                       $query = "select `emailcerts`.`id` 
+                                                       from `emaillink`,`emailcerts` where
+                                                       `emailid`='$id' and `emaillink`.`emailcertsid`=`emailcerts`.`id` and
+                                                       `revoked`=0 and UNIX_TIMESTAMP(`expire`)-UNIX_TIMESTAMP() > 0
+                                                       group by `emailcerts`.`id`";
+                                       $dres = mysql_query($query);
+                                       while($drow = mysql_fetch_assoc($dres))
+                                               mysql_query("update `emailcerts` set `revoked`='1970-01-01 10:00:01' where `id`='".$drow['id']."'");
+       
+                                       $query = "update `email` set `deleted`=NOW() where `id`='$id'";
+                                       mysql_query($query);
+                                       $delcount++;
+                               }
+                       }
+               }
+               else
+               {
+                       echo _("You did not select any email accounts for removal.");
+               }
+               if($delcount > 0)
+               {
+                       echo _("The following accounts have been removed:")."<br>\n";
+               } else {
+                       echo _("You failed to select any accounts to be removed, or you attempted to remove the default account. No action was taken.");
+               }
+
+               showfooter();
+               exit;
+       }
+
+       if($process != "" && $oldid == 3)
+       {
+               if(!(array_key_exists('addid',$_REQUEST) && is_array($_REQUEST['addid'])) && $_REQUEST['SSO'] != '1')
+               {
+                       showheader(_("My CAcert.org Account!"));
+                       echo _("I didn't receive a valid Certificate Request, hit the back button and try again.");
+                       showfooter();
+                       exit;
+               }
+
+               $_SESSION['_config']['SSO'] = intval($_REQUEST['SSO']);
+
+               $_SESSION['_config']['addid'] = $_REQUEST['addid'];
+               if($_SESSION['profile']['points'] >= 50)
+                       $_SESSION['_config']['incname'] = intval($_REQUEST['incname']);
+               if(array_key_exists('codesign',$_REQUEST) && $_REQUEST['codesign'] != 0 && ($_SESSION['profile']['codesign'] == 0 || $_SESSION['profile']['points'] < 100))
+               {
+                       $_REQUEST['codesign'] = 0;
+               }
+               if($_SESSION['profile']['points'] >= 100 && $_SESSION['profile']['codesign'] > 0 && array_key_exists('codesign',$_REQUEST) && $_REQUEST['codesign'] == 1)
+               {
+                       if($_SESSION['_config']['incname'] < 1 || $_SESSION['_config']['incname'] > 4)
+                               $_SESSION['_config']['incname'] = 1;
+               }
+               if(array_key_exists('codesign',$_REQUEST) && $_REQUEST['codesign'] == 1 && $_SESSION['profile']['points'] >= 100)
+                       $_SESSION['_config']['codesign'] = 1;
+               else
+                       $_SESSION['_config']['codesign'] = 0;
+
+               if(array_key_exists('login',$_REQUEST) && $_REQUEST['login'] == 1)
+                       $_SESSION['_config']['disablelogin'] = 0;
+               else
+                       $_SESSION['_config']['disablelogin'] = 1;
+
+               $_SESSION['_config']['rootcert'] = 1;
+               if($_SESSION['profile']['points'] >= 50)
+               {
+                       $_SESSION['_config']['rootcert'] = intval($_REQUEST['rootcert']);
+                       if($_SESSION['_config']['rootcert'] < 1 || $_SESSION['_config']['rootcert'] > 2)
+                               $_SESSION['_config']['rootcert'] = 1;
+               }
+               $csr = "";
+               if(trim($_REQUEST['optionalCSR']) == "")
+               {
+                       $id = 4;
+               } else {
+                       $oldid = 4;
+                       $_REQUEST['keytype'] = "MS";
+                       $csr = clean_csr($_REQUEST['optionalCSR']);
+               }
+       }
+
+       if($oldid == 4)
+       {
+               if($_REQUEST['keytype'] == "NS")
+               {
+                       $spkac=""; if(array_key_exists('SPKAC',$_REQUEST) && preg_match("/^[a-zA-Z0-9+=\/]+$/", trim(str_replace("\n", "", str_replace("\r", "",$_REQUEST['SPKAC']))))) $spkac=trim(str_replace("\n", "", str_replace("\r", "",$_REQUEST['SPKAC'])));
+
+                       if($spkac=="" || $spkac == "deadbeef")
+                       {
+                               $id = 4;
+                               showheader(_("My CAcert.org Account!"));
+                               echo _("I didn't receive a valid Certificate Request, please try a different browser.");
+                               showfooter();
+                               exit;
+                       }
+                       $count = 0;
+                       $emails = "";
+                       $addys = array();
+                       $defaultemail="";
+                       if(is_array($_SESSION['_config']['addid']))
+                       foreach($_SESSION['_config']['addid'] as $id)
+                       {
+                               $res = mysql_query("select * from `email` where `memid`='".$_SESSION['profile']['id']."' and `id`='".intval($id)."'");
+                               if(mysql_num_rows($res) > 0)
+                               {
+                                       $row = mysql_fetch_assoc($res);
+                                       if(!$emails)
+                                               $defaultemail = $row['email'];
+                                       $emails .= "$count.emailAddress = ".$row['email']."\n";
+                                       $count++;
+                                       $addys[] = intval($row['id']);
+                               }
+                       }
+                       if($count <= 0 && $_SESSION['_config']['SSO'] != 1)
+                       {
+                               $id = 4;
+                               showheader(_("My CAcert.org Account!"));
+                               echo _("You submitted invalid email addresses, or email address you no longer have control of. Can't continue with certificate request.");
+                               showfooter();
+                               exit;
+                       }
+                       $user = mysql_fetch_assoc(mysql_query("select * from `users` where `id`='".$_SESSION['profile']['id']."'"));
+                       if($_SESSION['_config']['SSO'] == 1)
+                               $emails .= "$count.emailAddress = ".$user['uniqueID']."\n";
+
+                       if(strlen($user['mname']) == 1)
+                               $user['mname'] .= '.';
+                       if(!array_key_exists('incname',$_SESSION['_config']) || $_SESSION['_config']['incname'] <= 0 || $_SESSION['_config']['incname'] > 4)
+                       {
+                               $emails .= "commonName = CAcert WoT User\n";
+                       }
+                       else
+                       {
+                               if($_SESSION['_config']['incname'] == 1)
+                                       $emails .= "commonName = ".$user['fname']." ".$user['lname']."\n";
+                               if($_SESSION['_config']['incname'] == 2)
+                                       $emails .= "commonName = ".$user['fname']." ".$user['mname']." ".$user['lname']."\n";
+                               if($_SESSION['_config']['incname'] == 3)
+                                       $emails .= "commonName = ".$user['fname']." ".$user['lname']." ".$user['suffix']."\n";
+                               if($_SESSION['_config']['incname'] == 4)
+                                       $emails .= "commonName = ".$user['fname']." ".$user['mname']." ".$user['lname']." ".$user['suffix']."\n";
+                       }
+                       $emails .= "SPKAC = $spkac";
+                       $query = "insert into emailcerts set
+                                               `CN`='$defaultemail', 
+                                               `keytype`='NS',
+                                               `memid`='".intval($_SESSION['profile']['id'])."',
+                                               `created`=FROM_UNIXTIME(UNIX_TIMESTAMP()),
+                                               `codesign`='".intval($_SESSION['_config']['codesign'])."',
+                                               `disablelogin`='".($_SESSION['_config']['disablelogin']?1:0)."',
+                                               `rootcert`='".intval($_SESSION['_config']['rootcert'])."'";
+                       mysql_query($query);
+                       $emailid = mysql_insert_id();
+                       if(is_array($addys))
+                       foreach($addys as $addy)
+                               mysql_query("insert into `emaillink` set `emailcertsid`='$emailid', `emailid`='$addy'");
+                       $CSRname = $_SESSION['_config']['filepath']."/csr/client-".intval($emailid).".csr";
+                       $fp = fopen($CSRname, "w");
+                       fputs($fp, $emails);
+                       fclose($fp);
+                       $challenge=$_SESSION['spkac_hash'];
+                        $res=`openssl spkac -verify -in $CSRname`;
+                        if(!strstr($res,"Challenge String: ".$challenge))
+                        {
+                                $id = $oldid;
+                                showheader(_("My CAcert.org Account!"));
+                                echo _("The challenge-response code of your certificate request did not match. Can't continue with certificaterequest.");
+                                showfooter();
+                                exit;
+                        }
+                       mysql_query("update `emailcerts` set `csr_name`='$CSRname' where `id`='".intval($emailid)."'");
+               } else if($_REQUEST['keytype'] == "MS" || $_REQUEST['keytype'] == "VI") {
+                       if($csr == "")
+                               $csr = "-----BEGIN CERTIFICATE REQUEST-----\n".clean_csr($_REQUEST['CSR'])."\n-----END CERTIFICATE REQUEST-----\n";
+                       $tmpfname = tempnam("/tmp", "id4CSR");
+                       $fp = fopen($tmpfname, "w");
+                       fputs($fp, $csr);
+                       fclose($fp);
+
+                       $addys = array();
+                       $defaultemail = "";
+                       $csrsubject="";
+
+                       $user = mysql_fetch_assoc(mysql_query("select * from `users` where `id`='".intval($_SESSION['profile']['id'])."'"));
+                        if(strlen($user['mname']) == 1)
+                                $user['mname'] .= '.';
+                       if($_SESSION['_config']['incname'] <= 0 || $_SESSION['_config']['incname'] > 4)
+                               $csrsubject = "/CN=CAcert WoT User";
+                       if($_SESSION['_config']['incname'] == 1)
+                               $csrsubject = "/CN=".$user['fname']." ".$user['lname'];
+                       if($_SESSION['_config']['incname'] == 2)
+                               $csrsubject = "/CN=".$user['fname']." ".$user['mname']." ".$user['lname'];
+                       if($_SESSION['_config']['incname'] == 3)
+                               $csrsubject = "/CN=".$user['fname']." ".$user['lname']." ".$user['suffix'];
+                       if($_SESSION['_config']['incname'] == 4)
+                               $csrsubject = "/CN=".$user['fname']." ".$user['mname']." ".$user['lname']." ".$user['suffix'];
+                       if(is_array($_SESSION['_config']['addid']))
+                       foreach($_SESSION['_config']['addid'] as $id)
+                       {
+                               $res = mysql_query("select * from `email` where `memid`='".intval($_SESSION['profile']['id'])."' and `id`='".intval($id)."'");
+                               if(mysql_num_rows($res) > 0)
+                               {
+                                       $row = mysql_fetch_assoc($res);
+                                       if($defaultemail == "")
+                                               $defaultemail = $row['email'];
+                                       $csrsubject .= "/emailAddress=".$row['email'];
+                                       $addys[] = $row['id'];
+                               }
+                       }
+                       if($_SESSION['_config']['SSO'] == 1)
+                               $csrsubject .= "/emailAddress = ".$user['uniqueID'];
+
+                       $tmpname = tempnam("/tmp", "id4csr");
+                       $do = `/usr/bin/openssl req -in $tmpfname -out $tmpname`; // -subj "$csr"`;
+                       @unlink($tmpfname);
+                       $csr = "";
+                       $fp = fopen($tmpname, "r");
+                       while($data = fgets($fp, 4096))
+                               $csr .= $data;
+                       fclose($fp);
+                       @unlink($tmpname);
+
+                       if($csr == "")
+                       {
+                               $id = 4;
+                               showheader(_("My CAcert.org Account!"));
+                               echo _("I didn't receive a valid Certificate Request, hit the back button and try again.");
+                               showfooter();
+                               exit;
+                       }
+                       $query = "insert into emailcerts set 
+                                               `CN`='$defaultemail', 
+                                               `keytype`='".sanitizeHTML($_REQUEST['keytype'])."',
+                                               `memid`='".$_SESSION['profile']['id']."',
+                                               `created`=FROM_UNIXTIME(UNIX_TIMESTAMP()),
+                                               `subject`='".mysql_real_escape_string($csrsubject)."',
+                                               `codesign`='".$_SESSION['_config']['codesign']."',
+                                               `rootcert`='".$_SESSION['_config']['rootcert']."'";
+                       mysql_query($query);
+                       $emailid = mysql_insert_id();
+                       if(is_array($addys))
+                       foreach($addys as $addy)
+                               mysql_query("insert into `emaillink` set `emailcertsid`='$emailid', `emailid`='".mysql_real_escape_string($addy)."'");
+                       $CSRname = $_SESSION['_config']['filepath']."/csr/client-$emailid.csr";
+                       $fp = fopen($CSRname, "w");
+                       fputs($fp, $csr);
+                       fclose($fp);
+                       mysql_query("update `emailcerts` set `csr_name`='$CSRname' where `id`='$emailid'");
+               }
+               waitForResult("emailcerts", $emailid, 4);
+               $query = "select * from `emailcerts` where `id`='$emailid' and `crt_name` != ''";
+               $res = mysql_query($query);
+               if(mysql_num_rows($res) <= 0)
+               {
+                       $id = 4;
+                       showheader(_("My CAcert.org Account!"));
+                       printf(_("Your certificate request has failed to be processed correctly, see %sthe WIKI page%s for reasons and solutions."), "<a href='http://wiki.cacert.org/wiki/FAQ/CertificateRenewal'>", "</a>");
+                       showfooter();
+                       exit;
+               } else {
+                       $id = 6;
+                       $cert = $emailid;
+                       $_REQUEST['cert']=$emailid;
+               }
+       }
+
+       if($oldid == 7)
+       {
+               list($newdomain) = explode(" ", $_REQUEST['newdomain'], 2); // Ignore the rest
+               while($newdomain['0'] == '-')
+                       $newdomain = substr($newdomain, 1);
+               if(strstr($newdomain, "xn--") && $_SESSION['profile']['codesign'] <= 0)
+               {
+                       showheader(_("My CAcert.org Account!"));
+                       echo _("Due to the possibility for punycode domain exploits we currently do not allow any certificates to sign punycode domains or email addresses.");
+                       showfooter();
+                       exit;
+               }
+
+               $newdom = trim(escapeshellarg($newdomain));
+               $newdomain = mysql_real_escape_string(trim($newdomain));
+
+               $res1 = mysql_query("select * from `orgdomains` where `domain`='$newdomain'");
+               $query = "select * from `domains` where `domain`='$newdomain' and `deleted`=0";
+               $res2 = mysql_query($query);
+               if(mysql_num_rows($res1) > 0 || mysql_num_rows($res2))
+               {
+                       $oldid=0;
+                       $id = 7;
+                       showheader(_("My CAcert.org Account!"));
+                       printf(_("The domain '%s' is already in the system and is listed as valid. Can't continue."), sanitizeHTML($newdomain));
+                       showfooter();
+                       exit;
+               }
+       }
+
+       if($oldid == 7)
+       {
+               $oldid=0;
+               $id = 8;
+               $addy = array();
+               $adds = array();
+               if(strtolower(substr($newdom, -4, 3)) != ".jp")
+                       $adds = explode("\n", trim(`/usr/bin/whois $newdom|grep "@"`));
+               if(substr($newdomain, -4) == ".org" || substr($newdomain, -5) == ".info")
+               {
+                       if(is_array($adds))
+                       foreach($adds as $line)
+                       {
+                               $bits = explode(":", $line, 2);
+                               $line = trim($bits[1]);
+                               if(!in_array($line, $addy) && $line != "")
+                                       $addy[] = trim(mysql_real_escape_string(stripslashes($line)));
+                       }
+               } else {
+                       if(is_array($adds))
+                       foreach($adds as $line)
+                       {
+                               $line = trim(str_replace("\t", " ", $line));
+                               $line = trim(str_replace("(", "", $line));
+                               $line = trim(str_replace(")", " ", $line));
+
+                               $bits = explode(" ", $line);
+                               foreach($bits as $bit)
+                               {
+                                       if(strstr($bit, "@"))
+                                               $line = $bit;
+                               }
+                               if(!in_array($line, $addy) && $line != "")
+                                       $addy[] = trim(mysql_real_escape_string(stripslashes($line)));
+                       }
+               }
+
+               $rfc = array("root@$newdomain", "hostmaster@$newdomain", "postmaster@$newdomain", "admin@$newdomain", "webmaster@$newdomain");
+               foreach($rfc as $sub)
+                       if(!in_array($sub, $addy))
+                               $addy[] = $sub;
+               $_SESSION['_config']['addy'] = $addy;
+               $_SESSION['_config']['domain'] = mysql_real_escape_string($newdomain);
+       }
+
+       if($process != "" && $oldid == 8)
+       {
+               $oldid=0;
+               $id = 8;
+
+               $authaddy = trim(mysql_real_escape_string(stripslashes($_REQUEST['authaddy'])));
+
+               if($authaddy == "" || !is_array($_SESSION['_config']['addy']))
+               {
+                       showheader(_("My CAcert.org Account!"));
+                       echo _("The address you submitted isn't a valid authority address for the domain.");
+                       showfooter();
+                       exit;
+               }
+
+               if(!in_array($authaddy, $_SESSION['_config']['addy']))
+               {
+                       showheader(_("My CAcert.org Account!"));
+                       echo _("The address you submitted isn't a valid authority address for the domain.");
+                       showfooter();
+                       exit;
+               }
+
+               $query = "select * from `domains` where `domain`='".mysql_real_escape_string($_SESSION['_config']['domain'])."' and `deleted`=0";
+               $res = mysql_query($query);
+               if(mysql_num_rows($res) > 0)
+               {
+                       showheader(_("My CAcert.org Account!"));
+                       printf(_("The domain '%s' is already in the system and is listed as valid. Can't continue."), sanitizeHTML($_SESSION['_config']['domain']));
+                       showfooter();
+                       exit;
+               }
+               $checkemail = checkEmail($authaddy);
+               if($checkemail != "OK")
+               {
+                       showheader(_("My CAcert.org Account!"));
+                       //echo "<p>"._("Email Address given was invalid, or a test connection couldn't be made to your server, or the server rejected the email address as invalid")."</p>\n";
+                       if (substr($checkemail, 0, 1) == "4") 
+                       {
+                               echo "<p>"._("The mail server responsible for your domain indicated a temporary failure. This may be due to anti-SPAM measures, such as greylisting. Please try again in a few minutes.")."</p>\n";
+                       } else {
+                               echo "<p>"._("Email Address given was invalid, or a test connection couldn't be made to your server, or the server rejected the email address as invalid")."</p>\n";
+                       }
+                       echo "<p>$checkemail</p>\n";
+                       showfooter();
+                       exit;
+               }
+
+               $hash = make_hash();
+               $query = "insert into `domains` set `domain`='".mysql_real_escape_string($_SESSION['_config']['domain'])."',
+                                       `memid`='".$_SESSION['profile']['id']."',`created`=NOW(),`hash`='$hash'";
+               mysql_query($query);
+               $domainid = mysql_insert_id();
+
+               $body = sprintf(_("Below is the link you need to open to verify your domain '%s'. Once your address is verified you will be able to start issuing certificates to your heart's content!"),$_SESSION['_config']['domain'])."\n\n";
+               $body .= "http://".$_SESSION['_config']['normalhostname']."/verify.php?type=domain&domainid=$domainid&hash=$hash\n\n";
+               $body .= _("Best regards")."\n"._("CAcert.org Support!");
+
+               sendmail($authaddy, "[CAcert.org] "._("Email Probe"), $body, "support@cacert.org", "", "", "CAcert Support");
+
+               showheader(_("My CAcert.org Account!"));
+               printf(_("The domain '%s' has been added to the system, however before any certificates for this can be issued you need to open the link in a browser that has been sent to your email address."), $_SESSION['_config']['domain']);
+               showfooter();
+               exit;
+       }
+
+       if($process != "" && $oldid == 9)
+       {
+               $id = 9;
+               showheader(_("My CAcert.org Account!"));
+               if(array_key_exists('delid',$_REQUEST) && is_array($_REQUEST['delid']))
+               {
+                       echo _("The following domains have been removed:")."<br>
+                               ("._("Any valid certificates will be revoked as well").")<br>\n";
+
+                       foreach($_REQUEST['delid'] as $id)
+                       {
+                               $id = intval($id);
+                               $query = "select * from `domains` where `id`='$id' and `memid`='".$_SESSION['profile']['id']."'";
+                               $res = mysql_query($query);
+                               if(mysql_num_rows($res) > 0)
+                               {
+                                       $row = mysql_fetch_assoc($res);
+                                       echo $row['domain']."<br>\n";
+                                       mysql_query("update `domains` set `deleted`=NOW() where `id`='$id'");
+                                       $dres = mysql_query("select * from `domlink` where `domid`='$id'");
+                                       while($drow = mysql_fetch_assoc($dres))
+                                               mysql_query("update `domaincerts` set `revoked`='1970-01-01 10:00:01' where `id`='".$drow['certid']."' and `revoked`=0 and UNIX_TIMESTAMP(`expire`)-UNIX_TIMESTAMP() > 0");
+                               }
+                       }
+               }
+               else
+               {
+                       echo _("You did not select any domains for removal.");
+               }
+
+               showfooter();
+               exit;
+       }
+
+       if($process != "" && $oldid == 10)
+       {
+               $CSR = clean_csr($_REQUEST['CSR']);
+               $_SESSION['_config']['tmpfname'] = tempnam("/tmp", "id10CSR");
+               $fp = fopen($_SESSION['_config']['tmpfname'], "w");
+               if(strpos($CSR,"---BEGIN")===FALSE)
+               {
+                 // In case the CSR is missing the ---BEGIN lines, add them automatically:
+                 fputs($fp,"-----BEGIN CERTIFICATE REQUEST-----\n".$CSR."\n-----END CERTIFICATE REQUEST-----\n");
+               }
+               else
+               {
+                 fputs($fp, $CSR);
+               }
+               fclose($fp);
+               $CSR = $_SESSION['_config']['tmpfname'];
+               $_SESSION['_config']['subject'] = trim(`/usr/bin/openssl req -text -noout -in "$CSR"|tr -d "\\0"|grep "Subject:"`);
+               $bits = explode(",", trim(`/usr/bin/openssl req -text -noout -in "$CSR"|tr -d "\\0"|grep -A1 'X509v3 Subject Alternative Name:'|grep DNS:`));
+               foreach($bits as $val)
+               {
+                       $_SESSION['_config']['subject'] .= "/subjectAltName=".trim($val);
+               }
+               $id = 11;
+
+               $_SESSION['_config']['0.CN'] = $_SESSION['_config']['0.subjectAltName'] = "";
+               extractit();
+               getcn();
+               getalt();
+
+               if($_SESSION['_config']['0.CN'] == "" && $_SESSION['_config']['0.subjectAltName'] == "")
+               {
+                       showheader(_("My CAcert.org Account!"));
+                       echo _("CommonName field was blank. This is usually caused by entering your own name when openssl prompt's you for 'YOUR NAME', or if you try to issue certificates for domains you haven't already verified, as such this process can't continue.");
+                       showfooter();
+                       exit;
+               }
+
+               $_SESSION['_config']['rootcert'] = 1;
+               if($_SESSION['profile']['points'] >= 50)
+               {
+                       $_SESSION['_config']['rootcert'] = intval($_REQUEST['rootcert']);
+                       if($_SESSION['_config']['rootcert'] < 1 || $_SESSION['_config']['rootcert'] > 2)
+                               $_SESSION['_config']['rootcert'] = 1;
+               }
+       }
+
+       if($process != "" && $oldid == 11)
+       {
+               $id = 11;
+               if($_SESSION['_config']['0.CN'] == "" && $_SESSION['_config']['0.subjectAltName'] == "")
+               {
+                       showheader(_("My CAcert.org Account!"));
+                       echo _("CommonName field was blank. This is usually caused by entering your own name when openssl prompt's you for 'YOUR NAME', or if you try to issue certificates for domains you haven't already verified, as such this process can't continue.");
+                       showfooter();
+                       exit;
+               }
+
+               $subject = "";
+               $count = 0;
+               $supressSAN=0;
+                if($_SESSION["profile"]["id"] == 104074) $supressSAN=1;
+
+               if(is_array($_SESSION['_config']['rows']))
+                       foreach($_SESSION['_config']['rows'] as $row)
+                       {
+                               $count++;
+                               if($count <= 1)
+                               {
+                                       $subject .= "/CN=$row";
+                                       if(!$supressSAN) $subject .= "/subjectAltName=DNS:$row";
+                                       if(!$supressSAN) $subject .= "/subjectAltName=otherName:1.3.6.1.5.5.7.8.5;UTF8:$row";
+                               } else {
+                                       if(!$supressSAN) $subject .= "/subjectAltName=DNS:$row";
+                                       if(!$supressSAN) $subject .= "/subjectAltName=otherName:1.3.6.1.5.5.7.8.5;UTF8:$row";
+                               }
+                       }
+               if(is_array($_SESSION['_config']['altrows']))
+                       foreach($_SESSION['_config']['altrows'] as $row)
+                       {
+                               if(substr($row, 0, 4) == "DNS:")
+                               {
+                                       $row = substr($row, 4);
+                                       if(!$supressSAN) $subject .= "/subjectAltName=DNS:$row";
+                                       if(!$supressSAN) $subject .= "/subjectAltName=otherName:1.3.6.1.5.5.7.8.5;UTF8:$row";
+                               }
+                       }
+
+               if(array_key_exists('0',$_SESSION['_config']['rowid']) && $_SESSION['_config']['rowid']['0'] > 0)
+               {
+                       $query = "insert into `domaincerts` set 
+                                               `CN`='".mysql_real_escape_string($_SESSION['_config']['rows']['0'])."',
+                                               `domid`='".mysql_real_escape_string($_SESSION['_config']['rowid']['0'])."',
+                                               `created`=NOW(),`subject`='".mysql_real_escape_string($subject)."',
+                                               `rootcert`='".mysql_real_escape_string($_SESSION['_config']['rootcert'])."'";
+               } elseif(array_key_exists('0',$_SESSION['_config']['altid']) && $_SESSION['_config']['altid']['0'] > 0) {
+                       $query = "insert into `domaincerts` set 
+                                               `CN`='".mysql_real_escape_string($_SESSION['_config']['altrows']['0'])."',
+                                               `domid`='".mysql_real_escape_string($_SESSION['_config']['altid']['0'])."',
+                                               `created`=NOW(),`subject`='".mysql_real_escape_string($subject)."',
+                                               `rootcert`='".mysql_real_escape_string($_SESSION['_config']['rootcert'])."'";
+               } else {
+                       showheader(_("My CAcert.org Account!"));
+                       echo _("Domain not verified.");
+                       showfooter();
+                       exit;
+
+               }
+
+               mysql_query($query);
+               $CSRid = mysql_insert_id();
+
+               if(is_array($_SESSION['_config']['rowid']))
+                       foreach($_SESSION['_config']['rowid'] as $dom)
+                               mysql_query("insert into `domlink` set `certid`='$CSRid', `domid`='$dom'");
+               if(is_array($_SESSION['_config']['altid']))
+               foreach($_SESSION['_config']['altid'] as $dom)
+                       mysql_query("insert into `domlink` set `certid`='$CSRid', `domid`='$dom'");
+
+               $CSRname = $_SESSION['_config']['filepath']."/csr/server-$CSRid.csr";
+               if(!file_exists($_SESSION['_config']['tmpfname']))
+               {
+                       showheader(_("My CAcert.org Account!"));
+                       printf(_("Your certificate request has failed to be processed correctly, see %sthe WIKI page%s for reasons and solutions."), "<a href='http://wiki.cacert.org/wiki/FAQ/CertificateRenewal'>", "</a>");
+                       showfooter();
+                       exit;
+               }
+               rename($_SESSION['_config']['tmpfname'], $CSRname);
+               chmod($CSRname,0644);
+               mysql_query("update `domaincerts` set `CSR_name`='$CSRname' where `id`='$CSRid'");
+               waitForResult("domaincerts", $CSRid, 11);
+               $query = "select * from `domaincerts` where `id`='$CSRid' and `crt_name` != ''";
+               $res = mysql_query($query);
+               if(mysql_num_rows($res) <= 0)
+               {
+                       $id = 11;
+                       showheader(_("My CAcert.org Account!"));
+                       printf(_("Your certificate request has failed to be processed correctly, see %sthe WIKI page%s for reasons and solutions."), "<a href='http://wiki.cacert.org/wiki/FAQ/CertificateRenewal'>", "</a>");
+                       showfooter();
+                       exit;
+               } else {
+                       $id = 15;
+                       $cert = $CSRid;
+                       $_REQUEST['cert']=$CSRid;
+               }
+       }
+
+       if($oldid == 12 && array_key_exists('renew',$_REQUEST) && $_REQUEST['renew'] != "")
+       {
+               $id = 12;
+               showheader(_("My CAcert.org Account!"));
+               if(is_array($_REQUEST['revokeid']))
+               {
+                       echo _("Now renewing the following certificates:")."<br>\n";
+                       foreach($_REQUEST['revokeid'] as $id)
+                       {
+                               $id = intval($id);
+                               echo _("Processing request")." $id:<br/>";
+                               $query = "select *,UNIX_TIMESTAMP(`domaincerts`.`revoked`) as `revoke` from `domaincerts`,`domains`
+                                               where `domaincerts`.`id`='$id' and
+                                               `domaincerts`.`domid`=`domains`.`id` and
+                                               `domains`.`memid`='".$_SESSION['profile']['id']."'";
+                               $res = mysql_query($query);
+                               if(mysql_num_rows($res) <= 0)
+                               {
+                                       printf(_("Invalid ID '%s' presented, can't do anything with it.")."<br/>\n", $id);
+                                       continue;
+                               }
+                               mysql_query("update `domaincerts` set `renewed`='1' where `id`='$id'");
+                               $row = mysql_fetch_assoc($res);
+                               $query = "insert into `domaincerts` set 
+                                               `domid`='".$row['domid']."', 
+                                               `CN`='".mysql_real_escape_string($row['CN'])."',
+                                               `subject`='".mysql_real_escape_string($row['subject'])."',".
+                                               //`csr_name`='".$row['csr_name']."', // RACE CONDITION
+                                               "`created`='".$row['created']."',
+                                               `modified`=NOW(), 
+                                               `rootcert`='".$row['rootcert']."',
+                                               `type`='".$row['type']."',
+                                               `pkhash`='".$row['pkhash']."'";
+                               mysql_query($query);
+                               $newid = mysql_insert_id();
+                               $newfile = $_SESSION['_config']['filepath']."/csr/server-$newid.csr";
+                               copy($row['csr_name'], $newfile);
+                               $_SESSION['_config']['subject'] = trim(`/usr/bin/openssl req -text -noout -in "$newfile"|tr -d "\\0"|grep "Subject:"`);
+                               $bits = explode(",", trim(`/usr/bin/openssl req -text -noout -in "$newfile"|tr -d "\\0"|grep -A1 'X509v3 Subject Alternative Name:'|grep DNS:`));
+                               foreach($bits as $val)
+                               {
+                                       $_SESSION['_config']['subject'] .= "/subjectAltName=".trim($val);
+                               }
+                               $_SESSION['_config']['0.CN'] = $_SESSION['_config']['0.subjectAltName'] = "";
+                               extractit();
+                               getcn();
+                               getalt();
+
+                               if($_SESSION['_config']['0.CN'] == "" && $_SESSION['_config']['0.subjectAltName'] == "")
+                               {
+                                       echo _("CommonName field was blank. This is usually caused by entering your own name when openssl prompt's you for 'YOUR NAME', or if you try to issue certificates for domains you haven't already verified, as such this process can't continue.");
+                                       continue;
+                               }
+
+                               $subject = "";
+                               $count = 0;
+                               if(is_array($_SESSION['_config']['rows']))
+                                       foreach($_SESSION['_config']['rows'] as $row)
+                                       {
+                                               $count++;
+                                               if($count <= 1)
+                                               {
+                                                       $subject .= "/CN=$row";
+                                                       if(!strstr($subject, "=$row/") &&
+                                                               substr($subject, -strlen("=$row")) != "=$row")
+                                                               $subject .= "/subjectAltName=$row";
+                                               } else {
+                                                       if(!strstr($subject, "=$row/") &&
+                                                               substr($subject, -strlen("=$row")) != "=$row")
+                                                               $subject .= "/subjectAltName=$row";
+                                               }
+                                       }
+                               if(is_array($_SESSION['_config']['altrows']))
+                                       foreach($_SESSION['_config']['altrows'] as $row)
+                                               if(!strstr($subject, "=$row/") &&
+                                                       substr($subject, -strlen("=$row")) != "=$row")
+                                                       $subject .= "/subjectAltName=$row";
+                               $subject = mysql_real_escape_string($subject);
+                               mysql_query("update `domaincerts` set `subject`='$subject',`csr_name`='$newfile' where `id`='$newid'");
+
+                               echo _("Renewing").": ".sanitizeHTML($_SESSION['_config']['0.CN'])."<br>\n";
+                               waitForResult("domaincerts", $newid,$oldid,0);
+                               $query = "select * from `domaincerts` where `id`='$newid' and `crt_name` != ''";
+                               $res = mysql_query($query);
+                               if(mysql_num_rows($res) <= 0)
+                               {
+                                       printf(_("Your certificate request has failed to be processed correctly, see %sthe WIKI page%s for reasons and solutions."), "<a href='http://wiki.cacert.org/wiki/FAQ/CertificateRenewal'>", "</a>");
+                               } else {
+                                       $drow = mysql_fetch_assoc($res);
+                                       $cert = `/usr/bin/openssl x509 -in $drow[crt_name]`;
+                                       echo "<pre>\n$cert\n</pre>\n";
+                               }
+                       }
+               }
+               else
+               {
+                       echo _("You did not select any certificates for renewal.");
+               }
+               showfooter();
+               exit;
+       }
+
+       if($oldid == 12 && array_key_exists('revoke',$_REQUEST) && $_REQUEST['revoke'] != "")
+       {
+               $id = 12;
+               showheader(_("My CAcert.org Account!"));
+               if(is_array($_REQUEST['revokeid']))
+               {
+                       echo _("Now revoking the following certificates:")."<br>\n";
+                       foreach($_REQUEST['revokeid'] as $id)
+                       {
+                               $id = intval($id);
+                               $query = "select *,UNIX_TIMESTAMP(`domaincerts`.`revoked`) as `revoke` from `domaincerts`,`domains` 
+                                               where `domaincerts`.`id`='$id' and
+                                               `domaincerts`.`domid`=`domains`.`id` and
+                                               `domains`.`memid`='".$_SESSION['profile']['id']."'";
+                               $res = mysql_query($query);
+                               if(mysql_num_rows($res) <= 0)
+                               {
+                                       printf(_("Invalid ID '%s' presented, can't do anything with it.")."<br>\n", $id);
+                                       continue;
+                               }
+                               $row = mysql_fetch_assoc($res);
+                               if($row['revoke'] > 0)
+                               {
+                                       printf(_("It would seem '%s' has already been revoked. I'll skip this for now.")."<br>\n", $row['CN']);
+                                       continue;
+                               }
+                               mysql_query("update `domaincerts` set `revoked`='1970-01-01 10:00:01' where `id`='$id'");
+                               printf(_("Certificate for '%s' has been revoked.")."<br>\n", $row['CN']);
+                       }
+               }
+               else
+               {
+                       echo _("You did not select any certificates for revocation.");
+               }
+
+               if(array_key_exists('delid',$_REQUEST) && is_array($_REQUEST['delid']))
+               {
+                       echo _("Now deleting the following pending requests:")."<br>\n";
+                       foreach($_REQUEST['delid'] as $id)
+                       {
+                               $id = intval($id);
+                               $query = "select *,UNIX_TIMESTAMP(`domaincerts`.`expire`) as `expired` from `domaincerts`,`domains` 
+                                               where `domaincerts`.`id`='$id' and
+                                               `domaincerts`.`domid`=`domains`.`id` and
+                                               `domains`.`memid`='".$_SESSION['profile']['id']."'";
+                               $res = mysql_query($query);
+                               if(mysql_num_rows($res) <= 0)
+                               {
+                                       printf(_("Invalid ID '%s' presented, can't do anything with it.")."<br>\n", $id);
+                                       continue;
+                               }
+                               $row = mysql_fetch_assoc($res);
+                               if($row['expired'] > 0)
+                               {
+                                       printf(_("Couldn't remove the request for `%s`, request had already been processed.")."<br>\n", $row['CN']);
+                                       continue;
+                               }
+                               mysql_query("delete from `domaincerts` where `id`='$id'");
+                               @unlink($row['csr_name']);
+                               @unlink($row['crt_name']);
+                               printf(_("Removed a pending request for '%s'")."<br>\n", $row['CN']);
+                       }
+               }
+               showfooter();
+               exit;
+       }
+
+       if($oldid == 5 && array_key_exists('renew',$_REQUEST) && $_REQUEST['renew'] != "")
+       {
+               showheader(_("My CAcert.org Account!"));
+               if(is_array($_REQUEST['revokeid']))
+               {
+                       echo _("Now renewing the following certificates:")."<br>\n";
+                       foreach($_REQUEST['revokeid'] as $id)
+                       {
+                               $id = intval($id);
+                               $query = "select *,UNIX_TIMESTAMP(`revoked`) as `revoke` from `emailcerts` 
+                                               where `id`='$id' and `memid`='".$_SESSION['profile']['id']."'";
+                               $res = mysql_query($query);
+                               if(mysql_num_rows($res) <= 0)
+                               {
+                                       printf(_("Invalid ID '%s' presented, can't do anything with it.")."<br>\n", $id);
+                                       continue;
+                               }
+                               mysql_query("update `emailcerts` set `renewed`='1' where `id`='$id'");
+                               $row = mysql_fetch_assoc($res);
+                               $query = "insert into emailcerts set 
+                                               `memid`='".$row['memid']."', 
+                                               `CN`='".mysql_real_escape_string($row['CN'])."',
+                                               `subject`='".mysql_real_escape_string($row['subject'])."',
+                                               `keytype`='".$row['keytype']."', 
+                                               `csr_name`='".$row['csr_name']."', 
+                                               `created`='".$row['created']."', 
+                                               `modified`=NOW(),
+                                               `disablelogin`='".$row['disablelogin']."',
+                                               `codesign`='".$row['codesign']."',
+                                               `rootcert`='".$row['rootcert']."'";
+                               mysql_query($query);
+                               $newid = mysql_insert_id();
+                               $newfile = $_SESSION['_config']['filepath']."/csr/client-$newid.csr";
+                               copy($row['csr_name'], $newfile);
+                               mysql_query("update `emailcerts` set `csr_name`='$newfile' where `id`='$newid'");
+                               $res = mysql_query("select * from `emaillink` where `emailcertsid`='".$row['id']."'");
+                               while($r2 = mysql_fetch_assoc($res))
+                               {
+                                       mysql_query("insert into `emaillink` set `emailid`='".$r2['emailid']."',
+                                                       `emailcertsid`='$newid'");
+                               }
+                               waitForResult("emailcerts", $newid,$oldid,0);
+                               $query = "select * from `emailcerts` where `id`='$newid' and `crt_name` != ''";
+                               $res = mysql_query($query);
+                               if(mysql_num_rows($res) <= 0)
+                               {
+                                       printf(_("Your certificate request has failed to be processed correctly, see %sthe WIKI page%s for reasons and solutions."), "<a href='http://wiki.cacert.org/wiki/FAQ/CertificateRenewal'>", "</a>");
+                               } else {
+                                       printf(_("Certificate for '%s' has been renewed."), $row['CN']);
+                                       echo "<a href='account.php?id=6&cert=$newid' target='_new'>".
+                                               _("Click here")."</a> "._("to install your certificate.");
+                               }
+                       }
+               }
+               else
+               {
+                       echo _("You did not select any certificates for renewal.");
+               }
+
+               showfooter();
+               exit;
+       }
+
+       if($oldid == 5 && array_key_exists('revoke',$_REQUEST) && $_REQUEST['revoke'] != "")
+       {
+               $id = 5;
+               showheader(_("My CAcert.org Account!"));
+               if(is_array($_REQUEST['revokeid']))
+               {
+                       echo _("Now revoking the following certificates:")."<br>\n";
+                       foreach($_REQUEST['revokeid'] as $id)
+                       {
+                               $id = intval($id);
+                               $query = "select *,UNIX_TIMESTAMP(`revoked`) as `revoke` from `emailcerts` 
+                                               where `id`='$id' and `memid`='".$_SESSION['profile']['id']."'";
+                               $res = mysql_query($query);
+                               if(mysql_num_rows($res) <= 0)
+                               {
+                                       printf(_("Invalid ID '%s' presented, can't do anything with it.")."<br>\n", $id);
+                                       continue;
+                               }
+                               $row = mysql_fetch_assoc($res);
+                               if($row['revoke'] > 0)
+                               {
+                                       printf(_("It would seem '%s' has already been revoked. I'll skip this for now.")."<br>\n", $row['CN']);
+                                       continue;
+                               }
+                               mysql_query("update `emailcerts` set `revoked`='1970-01-01 10:00:01' where `id`='$id'");
+                               printf(_("Certificate for '%s' has been revoked.")."<br>\n", $row['CN']);
+                       }
+               }
+               else
+               {
+                       echo _("You did not select any certificates for revocation.");
+               }
+
+               if(array_key_exists('delid',$_REQUEST) && is_array($_REQUEST['delid']))
+               {
+                       echo _("Now deleting the following pending requests:")."<br>\n";
+                       foreach($_REQUEST['delid'] as $id)
+                       {
+                               $id = intval($id);
+                               $query = "select *,UNIX_TIMESTAMP(`expire`) as `expired` from `emailcerts` 
+                                               where `id`='$id' and `memid`='".$_SESSION['profile']['id']."'";
+                               $res = mysql_query($query);
+                               if(mysql_num_rows($res) <= 0)
+                               {
+                                       printf(_("Invalid ID '%s' presented, can't do anything with it.")."<br>\n", $id);
+                                       continue;
+                               }
+                               $row = mysql_fetch_assoc($res);
+                               if($row['expired'] > 0)
+                               {
+                                       printf(_("Couldn't remove the request for `%s`, request had already been processed.")."<br>\n", $row['CN']);
+                                       continue;
+                               }
+                               mysql_query("delete from `emailcerts` where `id`='$id'");
+                               @unlink($row['csr_name']);
+                               @unlink($row['crt_name']);
+                               printf(_("Removed a pending request for '%s'")."<br>\n", $row['CN']);
+                       }
+               }
+               showfooter();
+               exit;
+       }
+
+       if($oldid == 5 && array_key_exists('change',$_REQUEST) && $_REQUEST['change'] != "")
+       {
+         showheader(_("My CAcert.org Account!"));
+         //echo _("Now changing the settings for the following certificates:")."<br>\n";
+         foreach($_REQUEST as $id => $val)
+         {
+           //echo $id."<br/>";
+           if(substr($id,0,5)=="cert_")
+           {
+             $id = intval(substr($id,5));
+             $dis=(array_key_exists('disablelogin_'.$id,$_REQUEST) && $_REQUEST['disablelogin_'.$id]=="1")?"0":"1";
+             //echo "$id -> ".$_REQUEST['disablelogin_'.$id]."<br/>\n";
+             mysql_query("update `emailcerts` set `disablelogin`='$dis' where `id`='$id' and `memid`='".$_SESSION['profile']['id']."'");
+             //$row = mysql_fetch_assoc($res);
+           }
+         }
+         echo(_("Certificate settings have been changed.")."<br/>\n");
+         showfooter();
+         exit;
+       }
+
+
+       if($oldid == 13 && $process != "")
+       {
+               csrf_check("perschange");
+               $_SESSION['_config']['user'] = $_SESSION['profile'];
+
+               $_SESSION['_config']['user']['Q1'] = trim(mysql_real_escape_string(stripslashes(strip_tags($_REQUEST['Q1']))));
+               $_SESSION['_config']['user']['Q2'] = trim(mysql_real_escape_string(stripslashes(strip_tags($_REQUEST['Q2']))));
+               $_SESSION['_config']['user']['Q3'] = trim(mysql_real_escape_string(stripslashes(strip_tags($_REQUEST['Q3']))));
+               $_SESSION['_config']['user']['Q4'] = trim(mysql_real_escape_string(stripslashes(strip_tags($_REQUEST['Q4']))));
+               $_SESSION['_config']['user']['Q5'] = trim(mysql_real_escape_string(stripslashes(strip_tags($_REQUEST['Q5']))));
+               $_SESSION['_config']['user']['A1'] = trim(mysql_real_escape_string(stripslashes(strip_tags($_REQUEST['A1']))));
+               $_SESSION['_config']['user']['A2'] = trim(mysql_real_escape_string(stripslashes(strip_tags($_REQUEST['A2']))));
+               $_SESSION['_config']['user']['A3'] = trim(mysql_real_escape_string(stripslashes(strip_tags($_REQUEST['A3']))));
+               $_SESSION['_config']['user']['A4'] = trim(mysql_real_escape_string(stripslashes(strip_tags($_REQUEST['A4']))));
+               $_SESSION['_config']['user']['A5'] = trim(mysql_real_escape_string(stripslashes(strip_tags($_REQUEST['A5']))));
+
+                if($_SESSION['_config']['user']['Q1'] == $_SESSION['_config']['user']['Q2'] ||
+                        $_SESSION['_config']['user']['Q1'] == $_SESSION['_config']['user']['Q3'] ||
+                        $_SESSION['_config']['user']['Q1'] == $_SESSION['_config']['user']['Q4'] ||
+                        $_SESSION['_config']['user']['Q1'] == $_SESSION['_config']['user']['Q5'] ||
+                        $_SESSION['_config']['user']['Q2'] == $_SESSION['_config']['user']['Q3'] ||
+                        $_SESSION['_config']['user']['Q2'] == $_SESSION['_config']['user']['Q4'] ||
+                        $_SESSION['_config']['user']['Q2'] == $_SESSION['_config']['user']['Q5'] ||
+                        $_SESSION['_config']['user']['Q3'] == $_SESSION['_config']['user']['Q4'] ||
+                        $_SESSION['_config']['user']['Q3'] == $_SESSION['_config']['user']['Q5'] ||
+                        $_SESSION['_config']['user']['Q4'] == $_SESSION['_config']['user']['Q5'] ||
+                        $_SESSION['_config']['user']['A1'] == $_SESSION['_config']['user']['Q1'] ||
+                        $_SESSION['_config']['user']['A1'] == $_SESSION['_config']['user']['Q2'] ||
+                        $_SESSION['_config']['user']['A1'] == $_SESSION['_config']['user']['Q3'] ||
+                        $_SESSION['_config']['user']['A1'] == $_SESSION['_config']['user']['Q4'] ||
+                        $_SESSION['_config']['user']['A1'] == $_SESSION['_config']['user']['Q5'] ||
+                        $_SESSION['_config']['user']['A2'] == $_SESSION['_config']['user']['Q3'] ||
+                        $_SESSION['_config']['user']['A2'] == $_SESSION['_config']['user']['Q4'] ||
+                        $_SESSION['_config']['user']['A2'] == $_SESSION['_config']['user']['Q5'] ||
+                        $_SESSION['_config']['user']['A3'] == $_SESSION['_config']['user']['Q4'] ||
+                        $_SESSION['_config']['user']['A3'] == $_SESSION['_config']['user']['Q5'] ||
+                        $_SESSION['_config']['user']['A4'] == $_SESSION['_config']['user']['Q5'] ||
+                        $_SESSION['_config']['user']['A1'] == $_SESSION['_config']['user']['A2'] ||
+                        $_SESSION['_config']['user']['A1'] == $_SESSION['_config']['user']['A3'] ||
+                        $_SESSION['_config']['user']['A1'] == $_SESSION['_config']['user']['A4'] ||
+                        $_SESSION['_config']['user']['A1'] == $_SESSION['_config']['user']['A5'] ||
+                        $_SESSION['_config']['user']['A2'] == $_SESSION['_config']['user']['A3'] ||
+                        $_SESSION['_config']['user']['A2'] == $_SESSION['_config']['user']['A4'] ||
+                        $_SESSION['_config']['user']['A2'] == $_SESSION['_config']['user']['A5'] ||
+                        $_SESSION['_config']['user']['A3'] == $_SESSION['_config']['user']['A4'] ||
+                        $_SESSION['_config']['user']['A3'] == $_SESSION['_config']['user']['A5'] ||
+                        $_SESSION['_config']['user']['A4'] == $_SESSION['_config']['user']['A5'])
+                {
+                        $_SESSION['_config']['errmsg'] .= _("For your own security you must enter 5 different password questions and answers. You aren't allowed to duplicate questions, set questions as answers or use the question as the answer.")."<br>\n";
+                        $id = $oldid;
+                       $oldid=0;
+                }
+
+               if($_SESSION['_config']['user']['Q1'] == "" || $_SESSION['_config']['user']['Q2'] == "" ||
+                       $_SESSION['_config']['user']['Q3'] == "" || $_SESSION['_config']['user']['Q4'] == "" ||
+                       $_SESSION['_config']['user']['Q5'] == "")
+               {
+                       $_SESSION['_config']['errmsg'] .= _("For your own security you must enter 5 lost password questions and answers.")."<br>";
+                       $id = $oldid;
+                       $oldid=0;
+               }
+       }
+
+       if($oldid == 13 && $process != "")
+       {
+               $ddquery = "select sum(`points`) as `total` from `notary` where `to`='".$_SESSION['profile']['id']."' group by `to`";
+               $ddres = mysql_query($ddquery);
+               $ddrow = mysql_fetch_assoc($ddres);
+               $_SESSION['profile']['points'] = $ddrow['total'];
+               
+               if($_SESSION['profile']['points'] == 0)
+               {
+                       $_SESSION['_config']['user']['fname'] = trim(mysql_real_escape_string(stripslashes(strip_tags($_REQUEST['fname']))));
+                       $_SESSION['_config']['user']['mname'] = trim(mysql_real_escape_string(stripslashes(strip_tags($_REQUEST['mname']))));
+                       $_SESSION['_config']['user']['lname'] = trim(mysql_real_escape_string(stripslashes(strip_tags($_REQUEST['lname']))));
+                       $_SESSION['_config']['user']['suffix'] = trim(mysql_real_escape_string(stripslashes(strip_tags($_REQUEST['suffix']))));
+                       $_SESSION['_config']['user']['day'] = intval($_REQUEST['day']);
+                       $_SESSION['_config']['user']['month'] = intval($_REQUEST['month']);
+                       $_SESSION['_config']['user']['year'] = intval($_REQUEST['year']);
+
+                       if($_SESSION['_config']['user']['fname'] == "" || $_SESSION['_config']['user']['lname'] == "")
+                       {
+                               $_SESSION['_config']['errmsg'] .= _("First and Last name fields can not be blank.")."<br>";
+                               $id = $oldid;
+                               $oldid=0;
+                       }
+                       if($_SESSION['_config']['user']['year'] < 1900 || $_SESSION['_config']['user']['month'] < 1 || $_SESSION['_config']['user']['month'] > 12 ||
+                               $_SESSION['_config']['user']['day'] < 1 || $_SESSION['_config']['user']['day'] > 31)
+                       {
+                               $_SESSION['_config']['errmsg'] .= _("Invalid date of birth")."<br>\n";
+                               $id = $oldid;
+                               $oldid=0;
+                       }
+               }
+       }
+
+       if($oldid == 13 && $process != "")
+       {
+               if($_SESSION['profile']['points'] == 0)
+               {
+                       $query = "update `users` set `fname`='".$_SESSION['_config']['user']['fname']."',
+                                               `mname`='".$_SESSION['_config']['user']['mname']."',
+                                               `lname`='".$_SESSION['_config']['user']['lname']."',
+                                               `suffix`='".$_SESSION['_config']['user']['suffix']."',
+                                               `dob`='".$_SESSION['_config']['user']['year']."-".$_SESSION['_config']['user']['month']."-".$_SESSION['_config']['user']['day']."'
+                                               where `id`='".$_SESSION['profile']['id']."'";
+                       mysql_query($query);
+               }
+               $query = "update `users` set `Q1`='".$_SESSION['_config']['user']['Q1']."',
+                                               `Q2`='".$_SESSION['_config']['user']['Q2']."',
+                                               `Q3`='".$_SESSION['_config']['user']['Q3']."',
+                                               `Q4`='".$_SESSION['_config']['user']['Q4']."',
+                                               `Q5`='".$_SESSION['_config']['user']['Q5']."',
+                                               `A1`='".$_SESSION['_config']['user']['A1']."',
+                                               `A2`='".$_SESSION['_config']['user']['A2']."',
+                                               `A3`='".$_SESSION['_config']['user']['A3']."',
+                                               `A4`='".$_SESSION['_config']['user']['A4']."',
+                                               `A5`='".$_SESSION['_config']['user']['A5']."'
+                                               where `id`='".$_SESSION['profile']['id']."'";
+               mysql_query($query);
+
+               //!!!Should be rewritten 
+               $_SESSION['_config']['user']['otphash'] = trim(mysql_real_escape_string(stripslashes(strip_tags($_REQUEST['otphash']))));
+               $_SESSION['_config']['user']['otppin'] = trim(mysql_real_escape_string(stripslashes(strip_tags($_REQUEST['otppin']))));
+               if($_SESSION['_config']['user']['otphash'] != "" && $_SESSION['_config']['user']['otppin'] != "")
+               {
+                       $query = "update `users` set `otphash`='".$_SESSION['_config']['user']['otphash']."',
+                                               `otppin`='".$_SESSION['_config']['user']['otppin']."' where `id`='".$_SESSION['profile']['id']."'";
+                       mysql_query($query);
+               }
+
+               $_SESSION['_config']['user']['set'] = 0;
+               $_SESSION['profile'] = mysql_fetch_assoc(mysql_query("select * from `users` where `id`='".$_SESSION['profile']['id']."'"));
+               $_SESSION['profile']['loggedin'] = 1;
+
+               $ddquery = "select sum(`points`) as `total` from `notary` where `to`='".$_SESSION['profile']['id']."' group by `to`";
+               $ddres = mysql_query($ddquery);
+               $ddrow = mysql_fetch_assoc($ddres);
+               $_SESSION['profile']['points'] = $ddrow['total'];
+
+
+               $id = 13;
+               showheader(_("My CAcert.org Account!"));
+               echo _("Your details have been updated with the database.");
+               showfooter();
+               exit;
+       }
+
+       if($oldid == 14 && $process != "")
+       {
+               $_SESSION['_config']['user']['oldpass'] = trim(mysql_real_escape_string(stripslashes($_REQUEST['oldpassword'])));
+               $_SESSION['_config']['user']['pword1'] = trim(mysql_real_escape_string(stripslashes($_REQUEST['pword1'])));
+               $_SESSION['_config']['user']['pword2'] = trim(mysql_real_escape_string(stripslashes($_REQUEST['pword2'])));
+
+               $id = 14;
+               csrf_check("pwchange");
+
+               showheader(_("My CAcert.org Account!"));
+               if($_SESSION['_config']['user']['pword1'] == "" || $_SESSION['_config']['user']['pword1'] != $_SESSION['_config']['user']['pword2'])
+               {
+                       echo _("New Pass Phrases specified don't match or were blank.");
+               } else {
+                       $score = checkpw($_SESSION['_config']['user']['pword1'], $_SESSION['profile']['email'], $_SESSION['profile']['fname'],
+                                               $_SESSION['profile']['mname'], $_SESSION['profile']['lname'], $_SESSION['profile']['suffix']);
+
+                       if($_SESSION['_config']['hostname'] != $_SESSION['_config']['securehostname'])
+                       {
+                               $match = mysql_query("select * from `users` where `id`='".$_SESSION['profile']['id']."' and
+                                               (`password`=old_password('".$_SESSION['_config']['user']['oldpass']."') or
+                                               `password`=sha1('".$_SESSION['_config']['user']['oldpass']."'))");
+                               $rc = mysql_num_rows($match);
+                       } else {
+                               $rc = 1;
+                       }
+
+                       if(strlen($_SESSION['_config']['user']['pword1']) < 6) {
+                               echo _("The Pass Phrase you submitted was too short.");
+                       } else if($score < 3) {
+                               printf(_("The Pass Phrase you submitted failed to contain enough differing characters and/or contained words from your name and/or email address. Only scored %s points out of 6."), $score);
+                       } else if($rc <= 0) {
+                               echo _("You failed to correctly enter your current Pass Phrase.");
+                       } else {
+                               mysql_query("update `users` set `password`=sha1('".$_SESSION['_config']['user']['pword1']."')
+                                               where `id`='".$_SESSION['profile']['id']."'");
+                               echo _("Your Pass Phrase has been updated and your primary email account has been notified of the change.");
+                               $body  = sprintf(_("Hi %s,"),$_SESSION['profile']['fname'])."\n";
+                               $body .= _("You are receiving this email because you or someone else")."\n";
+                               $body .= _("has changed the password on your account.")."\n";
+
+                               $body .= _("Best regards")."\n"._("CAcert.org Support!");
+
+                               sendmail($_SESSION['profile']['email'], "[CAcert.org] "._("Password Update Notification"), $body,
+                                               "support@cacert.org", "", "", "CAcert Support");
+                       }
+               }
+               showfooter();
+               exit;
+       }
+
+       if($oldid == 16)
+       {
+               $id = 16;
+               $_SESSION['_config']['emails'] = array();
+
+               foreach($_REQUEST['emails'] as $val)
+               {
+                       $val = mysql_real_escape_string(stripslashes(trim($val)));
+                       $bits = explode("@", $val);
+                       $count = count($bits);
+                       if($count != 2)
+                               continue;
+
+                       if(checkownership($bits[1]) == false)
+                               continue;
+
+                       if(!is_array($_SESSION['_config']['row']))
+                               continue;
+                       else if($_SESSION['_config']['row']['id'] > 0)
+                               $_SESSION['_config']['domids'][] = $_SESSION['_config']['row']['id'];
+
+                       if($val != "")
+                               $_SESSION['_config']['emails'][] = $val;
+               }
+               $_SESSION['_config']['name'] = mysql_real_escape_string(stripslashes(trim($_REQUEST['name'])));
+               $_SESSION['_config']['OU'] = mysql_real_escape_string(stripslashes(trim($_REQUEST['OU'])));
+       }
+
+       if($oldid == 16 && (intval(count($_SESSION['_config']['emails'])) + 0) <= 0)
+       {
+               $id = 16;
+               showheader(_("My CAcert.org Account!"));
+               echo _("I couldn't match any emails against your organisational account.");
+               showfooter();
+               exit;
+       }
+
+       if($oldid == 16 && $process != "")
+       {
+
+               if(array_key_exists('codesign',$_REQUEST) && $_REQUEST['codesign'] && $_SESSION['profile']['codesign'] && ($_SESSION['profile']['points'] >= 100))
+               {
+                       $_REQUEST['codesign'] = 1;
+                       $_SESSION['_config']['codesign'] = 1;
+               }
+               else
+               {
+                       $_REQUEST['codesign'] = 0;
+                       $_SESSION['_config']['codesign'] = 0;
+               }
+
+               $_SESSION['_config']['rootcert'] = intval($_REQUEST['rootcert']);
+               if($_SESSION['_config']['rootcert'] < 1 || $_SESSION['_config']['rootcert'] > 2)
+                       $_SESSION['_config']['rootcert'] = 1;
+
+               if(@count($_SESSION['_config']['emails']) > 0)
+                       $id = 17;
+       }
+
+       if($oldid == 17)
+       {
+               $org = $_SESSION['_config']['row'];
+               if($_REQUEST['keytype'] == "NS")
+               {
+                       $spkac=""; if(preg_match("/^[a-zA-Z0-9+=\/]+$/", trim(str_replace("\n", "", str_replace("\r", "",$_REQUEST['SPKAC']))))) $spkac=trim(str_replace("\n", "", str_replace("\r", "",$_REQUEST['SPKAC'])));
+
+                       if($spkac == "" || strlen($spkac) < 128)
+                       {
+                               $id = 17;
+                               showheader(_("My CAcert.org Account!"));
+                               echo _("I didn't receive a valid Certificate Request, hit the back button and try again.");
+                               showfooter();
+                               exit;
+                       }
+
+                       $count = 0;
+                       $emails = "";
+                       $addys = array();
+                       if(is_array($_SESSION['_config']['emails']))
+                       foreach($_SESSION['_config']['emails'] as $_REQUEST['email'])
+                       {
+                               if(!$emails)
+                                       $defaultemail = $_REQUEST['email'];
+                               $emails .= "$count.emailAddress = $_REQUEST[email]\n";
+                               $count++;
+                       }
+                       if($_SESSION['_config']['name'] != "")
+                               $emails .= "commonName = ".$_SESSION['_config']['name']."\n";
+                       if($_SESSION['_config']['OU'])
+                               $emails .= "organizationalUnitName = ".$_SESSION['_config']['OU']."\n";
+                       if($org['O'])
+                               $emails .= "organizationName = ".$org['O']."\n";
+                       if($org['L'])
+                               $emails .= "localityName = ".$org['L']."\n";
+                       if($org['ST'])
+                               $emails .= "stateOrProvinceName = ".$org['ST']."\n";
+                       if($org['C'])
+                               $emails .= "countryName = ".$org['C']."\n";
+
+                       $emails .= "SPKAC = $spkac";
+                       $query = "insert into `orgemailcerts` set 
+                                               `CN`='$defaultemail', 
+                                               `keytype`='NS',
+                                               `orgid`='".$org['orgid']."',
+                                               `created`=FROM_UNIXTIME(UNIX_TIMESTAMP()),
+                                               `codesign`='".$_SESSION['_config']['codesign']."',
+                                               `rootcert`='".$_SESSION['_config']['rootcert']."'";
+                       mysql_query($query);
+                       $emailid = mysql_insert_id();
+
+                       foreach($_SESSION['_config']['domids'] as $addy)
+                               mysql_query("insert into `domemaillink` set `emailcertsid`='$emailid', `emailid`='$addy'");
+
+                       $CSRname = $_SESSION['_config']['filepath']."/csr/orgclient-$emailid.csr";
+                       $fp = fopen($CSRname, "w");
+                       fputs($fp, $emails);
+                       fclose($fp);
+                       $challenge=$_SESSION['spkac_hash'];
+                        $res=`openssl spkac -verify -in $CSRname`;
+                        if(!strstr($res,"Challenge String: ".$challenge))
+                        {
+                                $id = $oldid;
+                                showheader(_("My CAcert.org Account!"));
+                                echo _("The challenge-response code of your certificate request did not match. Can't continue with certificaterequest.");
+                                showfooter();
+                                exit;
+                        }
+                       mysql_query("update `orgemailcerts` set `csr_name`='$CSRname' where `id`='$emailid'");
+               } else if($_REQUEST['keytype'] == "MS" || $_REQUEST['keytype']=="VI") {
+                       $csr = "-----BEGIN CERTIFICATE REQUEST-----\n".clean_csr($_REQUEST['CSR'])."-----END CERTIFICATE REQUEST-----\n";
+                       $tmpfname = tempnam("/tmp", "id17CSR");
+                       $fp = fopen($tmpfname, "w");
+                       fputs($fp, $csr);
+                       fclose($fp);
+
+                       $addys = array();
+                       $defaultemail = "";
+                       $csrsubject="";
+
+                       if($_SESSION['_config']['name'] != "")
+                               $csrsubject = "/CN=".$_SESSION['_config']['name'];
+                       if(is_array($_SESSION['_config']['emails']))
+                       foreach($_SESSION['_config']['emails'] as $_REQUEST['email'])
+                       {
+                               if($defaultemail == "")
+                                       $defaultemail = $_REQUEST['email'];
+                               $csrsubject .= "/emailAddress=$_REQUEST[email]";
+                       }
+                       if($_SESSION['_config']['OU'])
+                               $csrsubject .= "/organizationalUnitName=".$_SESSION['_config']['OU'];
+                       if($org['O'])
+                               $csrsubject .= "/organizationName=".$org['O'];
+                       if($org['L'])
+                               $csrsubject .= "/localityName=".$org['L'];
+                       if($org['ST'])
+                               $csrsubject .= "/stateOrProvinceName=".$org['ST'];
+                       if($org['C'])
+                               $csrsubject .= "/countryName=".$org['C'];
+
+                       $tmpname = tempnam("/tmp", "id17csr");
+                       $do = `/usr/bin/openssl req -in $tmpfname -out $tmpname`;
+                       @unlink($tmpfname);
+                       $csr = "";
+                       $fp = fopen($tmpname, "r");
+                       while($data = fgets($fp, 4096))
+                               $csr .= $data;
+                       fclose($fp);
+                       @unlink($tmpname);
+
+                       if($csr == "")
+                       {
+                               showheader(_("My CAcert.org Account!"));
+                               echo _("I didn't receive a valid Certificate Request, hit the back button and try again.");
+                               showfooter();
+                               exit;
+                       }
+                       $query = "insert into `orgemailcerts` set 
+                                               `CN`='$defaultemail', 
+                                               `keytype`='" . sanitizeHTML($_REQUEST['keytype']) . "',
+                                               `orgid`='".$org['orgid']."',
+                                               `created`=FROM_UNIXTIME(UNIX_TIMESTAMP()),
+                                               `subject`='$csrsubject',
+                                               `codesign`='".$_SESSION['_config']['codesign']."',
+                                               `rootcert`='".$_SESSION['_config']['rootcert']."'";
+                       mysql_query($query);
+                       $emailid = mysql_insert_id();
+
+                       foreach($_SESSION['_config']['domids'] as $addy)
+                               mysql_query("insert into `domemaillink` set `emailcertsid`='$emailid', `emailid`='$addy'");
+
+                       $CSRname = $_SESSION['_config']['filepath']."/csr/orgclient-$emailid.csr";
+                       $fp = fopen($CSRname, "w");
+                       fputs($fp, $csr);
+                       fclose($fp);
+                       mysql_query("update `orgemailcerts` set `csr_name`='$CSRname' where `id`='$emailid'");
+               }
+               waitForResult("orgemailcerts", $emailid,$oldid);
+               $query = "select * from `orgemailcerts` where `id`='$emailid' and `crt_name` != ''";
+               $res = mysql_query($query);
+               if(mysql_num_rows($res) <= 0)
+               {
+                       showheader(_("My CAcert.org Account!"));
+                       printf(_("Your certificate request has failed to be processed correctly, see %sthe WIKI page%s for reasons and solutions."), "<a href='http://wiki.cacert.org/wiki/FAQ/CertificateRenewal'>", "</a>");
+                       showfooter();
+                       exit;
+               } else {
+                       $id = 19;
+                       $cert = $emailid;
+                       $_REQUEST['cert']=$emailid;
+               }
+       }
+
+       if($oldid == 18 && array_key_exists('renew',$_REQUEST) && $_REQUEST['renew'] != "")
+       {
+               showheader(_("My CAcert.org Account!"));
+               if(is_array($_REQUEST['revokeid']))
+               {
+                       $id = 18;
+                       echo _("Now renewing the following certificates:")."<br>\n";
+                       foreach($_REQUEST['revokeid'] as $id)
+                       {
+                               echo "Renewing certificate #$id ...\n<br/>";
+                               $id = intval($id);
+                               $query = "select *,UNIX_TIMESTAMP(`revoked`) as `revoke` from `orgemailcerts`, `org`
+                                               where `orgemailcerts`.`id`='$id' and `org`.`memid`='".$_SESSION['profile']['id']."' and
+                                               `org`.`orgid`=`orgemailcerts`.`orgid`";
+                               $res = mysql_query($query);
+                               if(mysql_num_rows($res) <= 0)
+                               {
+                                       printf(_("Invalid ID '%s' presented, can't do anything with it.")."<br>\n", $id);
+                                       continue;
+                               }
+                               mysql_query("update `orgemailcerts` set `renewed`='1' where `id`='$id'");
+                               $row = mysql_fetch_assoc($res);
+                               if($row['revoke'] > 0)
+                               {
+                                       printf(_("It would seem '%s' has already been revoked. I'll skip this for now.")."<br>\n", $row['CN']);
+                                       continue;
+                               }
+                               $query = "insert into `orgemailcerts` set 
+                                               `orgid`='".$row['orgid']."', 
+                                               `CN`='".$row['CN']."',
+                                               `subject`='".$row['subject']."',
+                                               `keytype`='".$row['keytype']."', 
+                                               `csr_name`='".$row['csr_name']."', 
+                                               `created`='".$row['created']."', 
+                                               `modified`=NOW(),
+                                               `codesign`='".$row['codesign']."',
+                                               `rootcert`='".$row['rootcert']."'";
+                               mysql_query($query);
+                               $newid = mysql_insert_id();
+                               $newfile = $_SESSION['_config']['filepath']."/csr/orgclient-$newid.csr";
+                               copy($row['csr_name'], $newfile);
+                               mysql_query("update `orgemailcerts` set `csr_name`='$newfile' where `id`='$newid'");
+                               waitForResult("orgemailcerts", $newid,$oldid,0);
+                               $query = "select * from `orgemailcerts` where `id`='$newid' and `crt_name` != ''";
+                               $res = mysql_query($query);
+                               if(mysql_num_rows($res) > 0)
+                               {
+                                       printf(_("Certificate for '%s' has been renewed."), $row['CN']);
+                                       echo "<a href='account.php?id=19&cert=$newid' target='_new'>".
+                                               _("Click here")."</a> "._("to install your certificate.");
+                               }
+                               echo("<br/>");
+                       }
+               }
+               else
+               {
+                       echo _("You did not select any certificates for renewal.");
+               }
+               showfooter();
+               exit;
+       }
+
+       if($oldid == 18 && array_key_exists('revoke',$_REQUEST) && $_REQUEST['revoke'] != "")
+       {
+               $id = 18;
+               showheader(_("My CAcert.org Account!"));
+               if(is_array($_REQUEST['revokeid']))
+               {
+                       echo _("Now revoking the following certificates:")."<br>\n";
+                       foreach($_REQUEST['revokeid'] as $id)
+                       {
+                               $id = intval($id);
+                               $query = "select *,UNIX_TIMESTAMP(`revoked`) as `revoke` from `orgemailcerts`, `org`
+                                               where `orgemailcerts`.`id`='$id' and `org`.`memid`='".$_SESSION['profile']['id']."' and
+                                               `org`.`orgid`=`orgemailcerts`.`orgid`";
+                               $res = mysql_query($query);
+                               if(mysql_num_rows($res) <= 0)
+                               {
+                                       printf(_("Invalid ID '%s' presented, can't do anything with it.")."<br>\n", $id);
+                                       continue;
+                               }
+                               $row = mysql_fetch_assoc($res);
+                               if($row['revoke'] > 0)
+                               {
+                                       printf(_("It would seem '%s' has already been revoked. I'll skip this for now.")."<br>\n", $row['CN']);
+                                       continue;
+                               }
+                               mysql_query("update `orgemailcerts` set `revoked`='1970-01-01 10:00:01' where `id`='$id'");
+                               printf(_("Certificate for '%s' has been revoked.")."<br>\n", $row['CN']);
+                       }
+               }
+               else
+               {
+                       echo _("You did not select any certificates for revocation.");
+               }
+
+               if(array_key_exists('delid',$_REQUEST) && is_array($_REQUEST['delid']))
+               {
+                       echo _("Now deleting the following pending requests:")."<br>\n";
+                       foreach($_REQUEST['delid'] as $id)
+                       {
+                               $id = intval($id);
+                               $query = "select *,UNIX_TIMESTAMP(`expire`) as `expired` from `orgemailcerts`, `org`
+                                               where `orgemailcerts`.`id`='$id' and `org`.`memid`='".$_SESSION['profile']['id']."' and
+                                               `org`.`orgid`=`orgemailcerts`.`orgid`";
+                               $res = mysql_query($query);
+                               if(mysql_num_rows($res) <= 0)
+                               {
+                                       printf(_("Invalid ID '%s' presented, can't do anything with it.")."<br>\n", $id);
+                                       continue;
+                               }
+                               $row = mysql_fetch_assoc($res);
+                               if($row['expired'] > 0)
+                               {
+                                       printf(_("Couldn't remove the request for `%s`, request had already been processed.")."<br>\n", $row['CN']);
+                                       continue;
+                               }
+                               mysql_query("delete from `orgemailcerts` where `id`='$id'");
+                               @unlink($row['csr_name']);
+                               @unlink($row['crt_name']);
+                               printf(_("Removed a pending request for '%s'")."<br>\n", $row['CN']);
+                       }
+               }
+               showfooter();
+               exit;
+       }
+
+       if($process != "" && $oldid == 20)
+       {
+               $CSR = clean_csr($_REQUEST['CSR']);
+               $_SESSION['_config']['tmpfname'] = tempnam("/tmp", "id20CSR");
+               $fp = fopen($_SESSION['_config']['tmpfname'], "w");
+               fputs($fp, $CSR);
+               fclose($fp);
+               $CSR = $_SESSION['_config']['tmpfname'];
+               $_SESSION['_config']['subject'] = trim(`/usr/bin/openssl req -text -noout -in "$CSR"|tr -d "\\0"|grep "Subject:"`);
+               $bits = explode(",", trim(`/usr/bin/openssl req -text -noout -in "$CSR"|tr -d "\\0"|grep -A1 'X509v3 Subject Alternative Name:'|grep DNS:`));
+               foreach($bits as $val)
+               {
+                       $_SESSION['_config']['subject'] .= "/subjectAltName=".trim($val);
+               }
+               $id = 21;
+
+               $_SESSION['_config']['0.CN'] = $_SESSION['_config']['0.subjectAltName'] = "";
+               extractit();
+               getcn2();
+               getalt2();
+
+               $query = "select * from `orginfo`,`org`,`orgdomains` where
+                               `org`.`memid`='".$_SESSION['profile']['id']."' and
+                               `org`.`orgid`=`orginfo`.`id` and
+                               `org`.`orgid`=`orgdomains`.`orgid` and
+                               `orgdomains`.`domain`='".$_SESSION['_config']['0.CN']."'";
+               $_SESSION['_config']['CNorg'] = mysql_fetch_assoc(mysql_query($query));
+               $query = "select * from `orginfo`,`org`,`orgdomains` where
+                               `org`.`memid`='".$_SESSION['profile']['id']."' and
+                               `org`.`orgid`=`orginfo`.`id` and
+                               `org`.`orgid`=`orgdomains`.`orgid` and
+                               `orgdomains`.`domain`='".$_SESSION['_config']['0.subjectAltName']."'";
+               $_SESSION['_config']['SANorg'] = mysql_fetch_assoc(mysql_query($query));
+//echo "<pre>"; print_r($_SESSION['_config']); die;
+
+               if($_SESSION['_config']['0.CN'] == "" && $_SESSION['_config']['0.subjectAltName'] == "")
+               {
+                       $id = 20;
+                       showheader(_("My CAcert.org Account!"));
+                       echo _("CommonName field was blank. This is usually caused by entering your own name when openssl prompt's you for 'YOUR NAME', or if you try to issue certificates for domains you haven't already verified, as such this process can't continue.");
+                       showfooter();
+                       exit;
+               }
+
+               $_SESSION['_config']['rootcert'] = intval($_REQUEST['rootcert']);
+               if($_SESSION['_config']['rootcert'] < 1 || $_SESSION['_config']['rootcert'] > 2)
+                       $_SESSION['_config']['rootcert'] = 1;
+       }
+
+       if($process != "" && $oldid == 21)
+       {
+               $id = 21;
+
+               if($_SESSION['_config']['0.CN'] == "" && $_SESSION['_config']['0.subjectAltName'] == "")
+               {
+                       showheader(_("My CAcert.org Account!"));
+                       echo _("CommonName field was blank. This is usually caused by entering your own name when openssl prompt's you for 'YOUR NAME', or if you try to issue certificates for domains you haven't already verified, as such this process can't continue.");
+                       showfooter();
+                       exit;
+               }
+
+                if($_SESSION['_config']['rowid']['0'] > 0)
+                {
+                       $query = "select * from `org`,`orginfo` where
+                                       `orginfo`.`id`='".$_SESSION['_config']['rowid']['0']."' and
+                                       `orginfo`.`id`=`org`.`orgid` and
+                                       `org`.`memid`='".$_SESSION['profile']['id']."'";
+               } else {
+                       $query = "select * from `org`,`orginfo` where
+                                       `orginfo`.`id`='".$_SESSION['_config']['altid']['0']."' and
+                                       `orginfo`.`id`=`org`.`orgid` and
+                                       `org`.`memid`='".$_SESSION['profile']['id']."'";
+               }
+               $org = mysql_fetch_assoc(mysql_query($query));
+               $csrsubject = "";
+
+               if($_SESSION['_config']['OU'])
+                       $csrsubject .= "/organizationalUnitName=".$_SESSION['_config']['OU'];
+               if($org['O'])
+                       $csrsubject .= "/organizationName=".$org['O'];
+               if($org['L'])
+                       $csrsubject .= "/localityName=".$org['L'];
+               if($org['ST'])
+                       $csrsubject .= "/stateOrProvinceName=".$org['ST'];
+               if($org['C'])
+                       $csrsubject .= "/countryName=".$org['C'];
+               //if($org['contact'])
+               //      $csrsubject .= "/emailAddress=".trim($org['contact']);
+
+               if(is_array($_SESSION['_config']['rows']))
+                       foreach($_SESSION['_config']['rows'] as $row)
+                               $csrsubject .= "/commonName=$row";
+               $SAN="";                
+               if(is_array($_SESSION['_config']['altrows']))
+                       foreach($_SESSION['_config']['altrows'] as $subalt)
+                       {
+                               if($SAN != "")
+                                       $SAN .= ",";
+                               $SAN .= "$subalt";
+                       }
+
+               if($SAN != "")
+                       $csrsubject .= "/subjectAltName=".$SAN;
+
+               $type="";
+               if($_REQUEST["ocspcert"]!="" && $_SESSION['profile']['admin'] == 1) $type="8";
+
+                if($_SESSION['_config']['rowid']['0'] > 0)
+                {
+                        $query = "insert into `orgdomaincerts` set 
+                                               `CN`='".$_SESSION['_config']['rows']['0']."',
+                                               `orgid`='".$org['id']."',
+                                                `created`=NOW(),
+                                               `subject`='$csrsubject',
+                                               `rootcert`='".$_SESSION['_config']['rootcert']."',
+                                               `type`='$type'";
+                } else {
+                        $query = "insert into `orgdomaincerts` set 
+                                               `CN`='".$_SESSION['_config']['altrows']['0']."',
+                                               `orgid`='".$org['id']."',
+                                                `created`=NOW(),
+                                               `subject`='$csrsubject',
+                                               `rootcert`='".$_SESSION['_config']['rootcert']."',
+                                               `type`='$type'";
+                }
+                mysql_query($query);
+               $CSRid = mysql_insert_id();
+
+               $CSRname = $_SESSION['_config']['filepath']."/csr/orgserver-$CSRid.csr";
+               rename($_SESSION['_config']['tmpfname'], $CSRname);
+               chmod($CSRname,0644);
+               mysql_query("update `orgdomaincerts` set `CSR_name`='$CSRname' where `id`='$CSRid'");
+               if(is_array($_SESSION['_config']['rowid']))
+                       foreach($_SESSION['_config']['rowid'] as $id)
+                               mysql_query("insert into `orgdomlink` set `orgdomid`='$id', `orgcertid`='$CSRid'");
+               if(is_array($_SESSION['_config']['altid']))
+                       foreach($_SESSION['_config']['altid'] as $id)
+                               mysql_query("insert into `orgdomlink` set `orgdomid`='$id', `orgcertid`='$CSRid'");
+               waitForResult("orgdomaincerts", $CSRid,$oldid);
+               $query = "select * from `orgdomaincerts` where `id`='$CSRid' and `crt_name` != ''";
+               $res = mysql_query($query);
+               if(mysql_num_rows($res) <= 0)
+               {
+                       showheader(_("My CAcert.org Account!"));
+                       printf(_("Your certificate request has failed to be processed correctly, see %sthe WIKI page%s for reasons and solutions.")." CSRid: $CSRid", "<a href='http://wiki.cacert.org/wiki/FAQ/CertificateRenewal'>", "</a>");
+                       showfooter();
+                       exit;
+               } else {
+                       $id = 23;
+                       $cert = $CSRid;
+                       $_REQUEST['cert']=$CSRid;
+               }
+       }
+
+       if($oldid == 22 && array_key_exists('renew',$_REQUEST) && $_REQUEST['renew'] != "")
+       {
+               showheader(_("My CAcert.org Account!"));
+               if(is_array($_REQUEST['revokeid']))
+               {
+                       echo _("Now renewing the following certificates:")."<br>\n";
+                       foreach($_REQUEST['revokeid'] as $id)
+                       {
+                               $id = intval($id);
+                               $query = "select *,UNIX_TIMESTAMP(`orgdomaincerts`.`revoked`) as `revoke` from
+                                               `orgdomaincerts`,`org`
+                                               where `orgdomaincerts`.`id`='$id' and
+                                               `orgdomaincerts`.`orgid`=`org`.`orgid` and
+                                               `org`.`memid`='".$_SESSION['profile']['id']."'";
+                               $res = mysql_query($query);
+                               if(mysql_num_rows($res) <= 0)
+                               {
+                                       printf(_("Invalid ID '%s' presented, can't do anything with it.")."<br>\n", $id);
+                                       continue;
+                               }
+                               mysql_query("update `orgdomaincerts` set `renewed`='1' where `id`='$id'");
+                               $row = mysql_fetch_assoc($res);
+                               if($row['revoke'] > 0)
+                               {
+                                       printf(_("It would seem '%s' has already been revoked. I'll skip this for now.")."<br>\n", $row['CN']);
+                                       continue;
+                               }
+                               $query = "insert into `orgdomaincerts` set 
+                                               `orgid`='".$row['orgid']."', 
+                                               `CN`='".$row['CN']."',
+                                               `csr_name`='".$row['csr_name']."', 
+                                               `created`='".$row['created']."',
+                                               `modified`=NOW(), 
+                                               `subject`='".$row['subject']."', 
+                                               `type`='".$row['type']."',
+                                               `rootcert`='".$row['rootcert']."'";
+                               mysql_query($query);
+                               $newid = mysql_insert_id();
+                               //echo "NewID: $newid<br/>\n";
+                               $newfile = $_SESSION['_config']['filepath']."/csr/orgserver-$newid.csr";
+                               copy($row['csr_name'], $newfile);
+                               mysql_query("update `orgdomaincerts` set `csr_name`='$newfile' where `id`='$newid'");
+                               echo _("Renewing").": ".$row['CN']."<br>\n";
+                               $res = mysql_query("select * from `orgdomlink` where `orgcertid`='".$row['id']."'");
+                               while($r2 = mysql_fetch_assoc($res))
+                                       mysql_query("insert into `orgdomlink` set `orgdomid`='".$r2['id']."', `orgcertid`='$newid'");
+                               waitForResult("orgdomaincerts", $newid,$oldid,0);
+                               $query = "select * from `orgdomaincerts` where `id`='$newid' and `crt_name` != ''";
+                               $res = mysql_query($query);
+                               if(mysql_num_rows($res) <= 0)
+                               {
+                                       printf(_("Your certificate request has failed to be processed correctly, see %sthe WIKI page%s for reasons and solutions.")." newid: $newid", "<a href='http://wiki.cacert.org/wiki/FAQ/CertificateRenewal'>", "</a>");
+                               } else {
+                                       $drow = mysql_fetch_assoc($res);
+                                       $cert = `/usr/bin/openssl x509 -in $drow[crt_name]`;
+                                       echo "<pre>\n$cert\n</pre>\n";
+                               }
+                       }
+               }
+               else
+               {
+                       echo _("You did not select any certificates for renewal.");
+               }
+               showfooter();
+               exit;
+       }
+
+       if($oldid == 22 && array_key_exists('revoke',$_REQUEST) && $_REQUEST['revoke'] != "")
+       {
+               showheader(_("My CAcert.org Account!"));
+               if(is_array($_REQUEST['revokeid']))
+               {
+                       echo _("Now revoking the following certificates:")."<br>\n";
+                       foreach($_REQUEST['revokeid'] as $id)
+                       {
+                               $id = intval($id);
+                               $query = "select *,UNIX_TIMESTAMP(`orgdomaincerts`.`revoked`) as `revoke` from
+                                               `orgdomaincerts`,`org`
+                                               where `orgdomaincerts`.`id`='$id' and
+                                               `orgdomaincerts`.`orgid`=`org`.`orgid` and
+                                               `org`.`memid`='".$_SESSION['profile']['id']."'";
+                               $res = mysql_query($query);
+                               if(mysql_num_rows($res) <= 0)
+                               {
+                                       printf(_("Invalid ID '%s' presented, can't do anything with it.")."<br>\n", $id);
+                                       continue;
+                               }
+                               $row = mysql_fetch_assoc($res);
+                               if($row['revoke'] > 0)
+                               {
+                                       printf(_("It would seem '%s' has already been revoked. I'll skip this for now.")."<br>\n", $row['CN']);
+                                       continue;
+                               }
+                               mysql_query("update `orgdomaincerts` set `revoked`='1970-01-01 10:00:01' where `id`='$id'");
+                               printf(_("Certificate for '%s' has been revoked.")."<br>\n", $row['CN']);
+                       }
+               }
+               else
+               {
+                       echo _("You did not select any certificates for revocation.");
+               }
+
+               if(array_key_exists('delid',$_REQUEST) && is_array($_REQUEST['delid']))
+               {
+                       echo _("Now deleting the following pending requests:")."<br>\n";
+                       foreach($_REQUEST['delid'] as $id)
+                       {
+                               $id = intval($id);
+                               $query = "select *,UNIX_TIMESTAMP(`orgdomaincerts`.`expire`) as `expired` from
+                                               `orgdomaincerts`,`org`
+                                               where `orgdomaincerts`.`id`='$id' and
+                                               `orgdomaincerts`.`orgid`=`org`.`orgid` and
+                                               `org`.`memid`='".$_SESSION['profile']['id']."'";
+                               $res = mysql_query($query);
+                               if(mysql_num_rows($res) <= 0)
+                               {
+                                       printf(_("Invalid ID '%s' presented, can't do anything with it.")."<br>\n", $id);
+                                       continue;
+                               }
+                               $row = mysql_fetch_assoc($res);
+                               if($row['expired'] > 0)
+                               {
+                                       printf(_("Couldn't remove the request for `%s`, request had already been processed.")."<br>\n", $row['CN']);
+                                       continue;
+                               }
+                               mysql_query("delete from `orgdomaincerts` where `id`='$id'");
+                               @unlink($row['csr_name']);
+                               @unlink($row['crt_name']);
+                               printf(_("Removed a pending request for '%s'")."<br>\n", $row['CN']);
+                       }
+               }
+               showfooter();
+               exit;
+       }
+
+       if(($id == 24 || $oldid == 24 || $id == 25 || $oldid == 25 || $id == 26 || $oldid == 26 ||
+               $id == 27 || $oldid == 27 || $id == 28 || $oldid == 28 || $id == 29 || $oldid == 29 ||
+               $id == 30 || $oldid == 30 || $id == 31 || $oldid == 31) &&
+               $_SESSION['profile']['orgadmin'] != 1)
+       {
+               showheader(_("My CAcert.org Account!"));
+               echo _("You don't have access to this area.");
+               showfooter();
+               exit;
+       }
+
+       if($oldid == 24 && $process != "")
+       {
+               $id = intval($oldid);
+               $_SESSION['_config']['O'] = trim(mysql_real_escape_string(stripslashes($_REQUEST['O'])));
+               $_SESSION['_config']['contact'] = trim(mysql_real_escape_string(stripslashes($_REQUEST['contact'])));
+               $_SESSION['_config']['L'] = trim(mysql_real_escape_string(stripslashes($_REQUEST['L'])));
+               $_SESSION['_config']['ST'] = trim(mysql_real_escape_string(stripslashes($_REQUEST['ST'])));
+               $_SESSION['_config']['C'] = trim(mysql_real_escape_string(stripslashes($_REQUEST['C'])));
+               $_SESSION['_config']['comments'] = trim(mysql_real_escape_string(stripslashes($_REQUEST['comments'])));
+
+               if($_SESSION['_config']['O'] == "" || $_SESSION['_config']['contact'] == "")
+               {
+                       $_SESSION['_config']['errmsg'] = _("Organisation Name and Contact Email are required fields.");
+               } else {
+                       mysql_query("insert into `orginfo` set `O`='".$_SESSION['_config']['O']."',
+                                               `contact`='".$_SESSION['_config']['contact']."',
+                                               `L`='".$_SESSION['_config']['L']."',
+                                               `ST`='".$_SESSION['_config']['ST']."',
+                                               `C`='".$_SESSION['_config']['C']."',
+                                               `comments`='".$_SESSION['_config']['comments']."'");
+                       showheader(_("My CAcert.org Account!"));
+                       printf(_("'%s' has just been successfully added as an organisation to the database."), sanitizeHTML($_SESSION['_config']['O']));
+                       showfooter();
+                       exit;
+               }
+       }
+
+       if($oldid == 27 && $process != "")
+       {
+               $id = intval($oldid);
+               $_SESSION['_config']['O'] = trim(mysql_real_escape_string(stripslashes($_REQUEST['O'])));
+               $_SESSION['_config']['contact'] = trim(mysql_real_escape_string(stripslashes($_REQUEST['contact'])));
+               $_SESSION['_config']['L'] = trim(mysql_real_escape_string(stripslashes($_REQUEST['L'])));
+               $_SESSION['_config']['ST'] = trim(mysql_real_escape_string(stripslashes($_REQUEST['ST'])));
+               $_SESSION['_config']['C'] = trim(mysql_real_escape_string(stripslashes($_REQUEST['C'])));
+               $_SESSION['_config']['comments'] = trim(mysql_real_escape_string(stripslashes($_REQUEST['comments'])));
+
+               if($_SESSION['_config']['O'] == "" || $_SESSION['_config']['contact'] == "")
+               {
+                       $_SESSION['_config']['errmsg'] = _("Organisation Name and Contact Email are required fields.");
+               } else {
+                       mysql_query("update `orginfo` set `O`='".$_SESSION['_config']['O']."',
+                                               `contact`='".$_SESSION['_config']['contact']."',
+                                               `L`='".$_SESSION['_config']['L']."',
+                                               `ST`='".$_SESSION['_config']['ST']."',
+                                               `C`='".$_SESSION['_config']['C']."',
+                                               `comments`='".$_SESSION['_config']['comments']."'
+                                       where `id`='".$_SESSION['_config']['orgid']."'");
+                       showheader(_("My CAcert.org Account!"));
+                       printf(_("'%s' has just been successfully updated in the database."), sanitizeHTML($_SESSION['_config']['O']));
+                       showfooter();
+                       exit;
+               }
+       }
+
+       if($oldid == 28 && $process != "" && array_key_exists("domainname",$_REQUEST))
+       {
+               $domain = $_SESSION['_config']['domain'] = trim(mysql_real_escape_string(stripslashes($_REQUEST['domainname'])));
+               $res1 = mysql_query("select * from `orgdomains` where `domain`='$domain'");
+               if(mysql_num_rows($res1) > 0)
+               {
+                       $_SESSION['_config']['errmsg'] = sprintf(_("The domain '%s' is already in the system and is listed as valid. Can't continue."), sanitizeHTML($domain));
+                       $id = $oldid;
+                       $oldid=0;
+               }
+       }
+
+       if($oldid == 28 && $_SESSION['_config']['orgid'] <= 0)
+       {
+               $oldid=0;
+               $id = 25;
+       }
+
+       if($oldid == 28 && $process != "" && array_key_exists("orgid",$_SESSION["_config"]))
+       {
+               mysql_query("insert into `orgdomains` set `orgid`='".intval($_SESSION['_config']['orgid'])."', `domain`='$domain'");
+               showheader(_("My CAcert.org Account!"));
+               printf(_("'%s' has just been successfully added to the database."), sanitizeHTML($domain));
+               echo "<br><br><a href='account.php?id=26&orgid=".intval($_SESSION['_config']['orgid'])."'>"._("Click here")."</a> "._("to continue.");
+               showfooter();
+               exit;
+       }
+
+       if($oldid == 29 && $process != "")
+       {
+               $domain = mysql_real_escape_string(stripslashes(trim($domainname)));
+
+               $res1 = mysql_query("select * from `orgdomains` where `domain` like '$domain' and `id`!='".intval($_SESSION['_config']['domid'])."'");
+               $res2 = mysql_query("select * from `domains` where `domain` like '$domain' and `deleted`=0");
+               if(mysql_num_rows($res1) > 0 || mysql_num_rows($res2) > 0)
+               {
+                       $_SESSION['_config']['errmsg'] = sprintf(_("The domain '%s' is already in the system and is listed as valid. Can't continue."), sanitizeHTML($domain));
+                       $id = $oldid;
+                       $oldid=0;
+               }
+       }
+
+       if(($oldid == 29 || $oldid == 30) && $process != _("Cancel"))
+       {
+               $query = "select `orgdomaincerts`.`id` as `id` from `orgdomlink`, `orgdomaincerts`, `orgdomains` where 
+                               `orgdomlink`.`orgdomid`=`orgdomains`.`id` and
+                               `orgdomaincerts`.`id`=`orgdomlink`.`orgcertid` and
+                               `orgdomains`.`id`='".intval($_SESSION['_config']['domid'])."'";
+               $res = mysql_query($query);
+               while($row = mysql_fetch_assoc($res))
+                       mysql_query("update `orgdomaincerts` set `revoked`='1970-01-01 10:00:01' where `id`='".$row['id']."'");
+
+               $query = "select `orgemailcerts`.`id` as `id` from `orgemailcerts`, `orgemaillink`, `orgdomains` where 
+                               `orgemaillink`.`domid`=`orgdomains`.`id` and
+                               `orgemailcerts`.`id`=`orgemaillink`.`emailcertsid` and
+                               `orgdomains`.`id`='".intval($_SESSION['_config']['domid'])."'";
+               $res = mysql_query($query);
+               while($row = mysql_fetch_assoc($res))
+                       mysql_query("update `orgemailcerts` set `revoked`='1970-01-01 10:00:01' where `id`='".intval($row['id'])."'");
+       }
+
+       if($oldid == 29 && $process != "")
+       {
+               $row = mysql_fetch_assoc(mysql_query("select * from `orgdomains` where `id`='".intval($_SESSION['_config']['domid'])."'"));
+               mysql_query("update `orgdomains` set `domain`='$domain' where `id`='".intval($_SESSION['_config']['domid'])."'");
+               showheader(_("My CAcert.org Account!"));
+               printf(_("'%s' has just been successfully updated in the database."), sanitizeHTML($domain));
+               echo "<br><br><a href='account.php?id=26&orgid=".intval($_SESSION['_config']['orgid'])."'>"._("Click here")."</a> "._("to continue.");
+               showfooter();
+               exit;
+       }
+
+       if($oldid == 30 && $process != "")
+       {
+               $row = mysql_fetch_assoc(mysql_query("select * from `orgdomains` where `id`='".intval($_SESSION['_config']['domid'])."'"));
+               $domain = $row['domain'];
+               mysql_query("delete from `orgdomains` where `id`='".intval($_SESSION['_config']['domid'])."'");
+               showheader(_("My CAcert.org Account!"));
+               printf(_("'%s' has just been successfully deleted from the database."), sanitizeHTML($domain));
+               echo "<br><br><a href='account.php?id=26&orgid=".intval($_SESSION['_config']['orgid'])."'>"._("Click here")."</a> "._("to continue.");
+               showfooter();
+               exit;
+       }
+
+       if($oldid == 30)
+       {
+               $id = 26;
+               $orgid = 0;
+       }
+
+       if($oldid == 31 && $process != _("Cancel"))
+       {
+               $query = "select * from `orgdomains` where `orgid`='".intval($_SESSION['_config']['orgid'])."'";
+               $dres = mysql_query($query);
+               while($drow = mysql_fetch_assoc($dres))
+               {
+                       $query = "select `orgdomaincerts`.`id` as `id` from `orgdomlink`, `orgdomaincerts`, `orgdomains` where 
+                                       `orgdomlink`.`orgdomid`=`orgdomains`.`id` and
+                                       `orgdomaincerts`.`id`=`orgdomlink`.`orgcertid` and
+                                       `orgdomains`.`id`='".intval($drow['id'])."'";
+                       $res = mysql_query($query);
+                       while($row = mysql_fetch_assoc($res))
+                       {
+                               mysql_query("update `orgdomaincerts` set `revoked`='1970-01-01 10:00:01' where `id`='".intval($row['id'])."'");
+                               mysql_query("delete from `orgdomaincerts` where `orgid`='".intval($row['id'])."'");
+                               mysql_query("delete from `orgdomlink` where `domid`='".intval($row['id'])."'");
+                       }
+
+                       $query = "select `orgemailcerts`.`id` as `id` from `orgemailcerts`, `orgemaillink`, `orgdomains` where 
+                                       `orgemaillink`.`domid`=`orgdomains`.`id` and
+                                       `orgemailcerts`.`id`=`orgemaillink`.`emailcertsid` and
+                                       `orgdomains`.`id`='".intval($drow['id'])."'";
+                       $res = mysql_query($query);
+                       while($row = mysql_fetch_assoc($res))
+                       {
+                               mysql_query("update `orgemailcerts` set `revoked`='1970-01-01 10:00:01' where `id`='".intval($row['id'])."'");
+                               mysql_query("delete from `orgemailcerts` where `id`='".intval($row['id'])."'");
+                               mysql_query("delete from `orgemaillink` where `domid`='".intval($row['id'])."'");
+                       }
+               }
+               mysql_query("delete from `org` where `orgid`='".intval($_SESSION['_config']['orgid'])."'");
+               mysql_query("delete from `orgdomains` where `orgid`='".intval($_SESSION['_config']['orgid'])."'");
+               mysql_query("delete from `orginfo` where `id`='".intval($_SESSION['_config']['orgid'])."'");
+       }
+
+       if($oldid == 31)
+       {
+               $id = 25;
+               $orgid = 0;
+       }
+
+       if($id == 32 || $oldid == 32 || $id == 33 || $oldid == 33 || $id == 34 || $oldid == 34 ||
+               $id == 35 || $oldid == 35)
+       {
+               $query = "select * from `org` where `memid`='".intval($_SESSION['profile']['id'])."' and `masteracc`='1'";
+               $_macc = mysql_num_rows(mysql_query($query));
+               if($_SESSION['profile']['orgadmin'] != 1 && $_macc <= 0)
+               {
+                       showheader(_("My CAcert.org Account!"));
+                       echo _("You don't have access to this area.");
+                       showfooter();
+                       exit;
+               }
+       }
+
+       if($id == 33 && $_SESSION['profile']['orgadmin'] != 1)
+       {
+               $orgid = intval($_SESSION['_config']['orgid']);
+               $query = "select * from `org` where `orgid`='$orgid' and `memid`='".intval($_SESSION['profile']['id'])."' and `masteracc`='1'";
+               $res = mysql_query($query);
+               if(mysql_num_rows($res) <= 0)
+               {
+                       $id = 35;
+               }
+       }
+
+       if($oldid == 33 && $process != "")
+       {
+               if($_SESSION['profile']['orgadmin'] == 1)
+                       $masteracc = $_SESSION['_config'][masteracc] = intval($_REQUEST['masteracc']);
+               else
+                       $masteracc = $_SESSION['_config'][masteracc] = 0;
+               $_REQUEST['email'] = $_SESSION['_config']['email'] = mysql_real_escape_string(stripslashes(trim($_REQUEST['email'])));
+               $OU = $_SESSION['_config']['OU'] = mysql_real_escape_string(stripslashes(trim($_REQUEST['OU'])));
+               $comments = $_SESSION['_config']['comments'] = mysql_real_escape_string(stripslashes(trim($_REQUEST['comments'])));
+               $res = mysql_query("select * from `users` where `email`='".$_REQUEST['email']."' and `deleted`=0");
+               if(mysql_num_rows($res) <= 0)
+               {
+                       $id = $oldid;
+                       $oldid=0;
+                       $_SESSION['_config']['errmsg'] = sprintf(_("Wasn't able to match '%s' against any user in the system"), sanitizeHTML($_REQUEST['email']));
+               } else {
+                       $row = mysql_fetch_assoc($res);
+                       mysql_query("insert into `org` set `memid`='".intval($row['id'])."', `orgid`='".intval($_SESSION['_config']['orgid'])."',
+                                       `masteracc`='$masteracc', `OU`='$OU', `comments`='$comments'");
+               }
+       }
+
+       if(($oldid == 34 || $id == 34) && $_SESSION['profile']['orgadmin'] != 1)
+       {
+               $orgid = intval($_SESSION['_config']['orgid']);
+               $res = mysql_query("select * from `org` where `orgid`='$orgid' and `memid`='".$_SESSION['profile']['id']."' and `masteracc`='1'");
+               if(mysql_num_rows($res) <= 0)
+                       $id = 32;
+       }
+
+       if($oldid == 34 && $process != "")
+       {
+               $orgid = intval($_SESSION['_config']['orgid']);
+               $memid = intval($_REQUEST['memid']);
+               $query = "delete from `org` where `orgid`='$orgid' and `memid`='$memid'";
+               mysql_query($query);
+       }
+
+       if($oldid == 34 || $oldid == 33)
+       {
+               $oldid=0;
+               $id = 32;
+               $orgid = 0;
+       }
+
+       if($id == 36)
+       {
+               $row = mysql_fetch_assoc(mysql_query("select * from `alerts` where `memid`='".intval($_SESSION['profile']['id'])."'"));
+               $_REQUEST['general'] = $row['general'];
+               $_REQUEST['country'] = $row['country'];
+               $_REQUEST['regional'] = $row['regional'];
+               $_REQUEST['radius'] = $row['radius'];
+       }
+
+       if($oldid == 36)
+       {
+               $rc = mysql_num_rows(mysql_query("select * from `alerts` where `memid`='".intval($_SESSION['profile']['id'])."'"));
+               if($rc > 0)
+               {
+                       $query = "update `alerts` set `general`='".intval(array_key_exists('general',$_REQUEST)?$_REQUEST['general']:0)."',
+                                                       `country`='".intval(array_key_exists('country',$_REQUEST)?$_REQUEST['country']:0)."',
+                                                       `regional`='".intval(array_key_exists('regional',$_REQUEST)?$_REQUEST['regional']:0)."',
+                                                       `radius`='".intval(array_key_exists('radius',$_REQUEST)?$_REQUEST['radius']:0)."'
+                                       where `memid`='".intval($_SESSION['profile']['id'])."'";
+               } else {
+                       $query = "insert into `alerts` set `general`='".intval(array_key_exists('general',$_REQUEST)?$_REQUEST['general']:0)."',
+                                                       `country`='".intval(array_key_exists('country',$_REQUEST)?$_REQUEST['country']:0)."',
+                                                       `regional`='".intval(array_key_exists('regional',$_REQUEST)?$_REQUEST['regional']:0)."',
+                                                       `radius`='".intval(array_key_exists('radius',$_REQUEST)?$_REQUEST['radius']:0)."',
+                                                       `memid`='".intval($_SESSION['profile']['id'])."'";
+               }
+               mysql_query($query);
+               $id = $oldid;
+               $oldid=0;
+       }
+
+       if($oldid == 41 && $_REQUEST['action'] == 'default')
+       {
+               csrf_check("mainlang");
+               $lang = mysql_real_escape_string($_REQUEST['lang']);
+               foreach($_SESSION['_config']['translations'] as $key => $val)
+               {
+                       if($key == $lang)
+                       {
+                               mysql_query("update `users` set `language`='$lang' where `id`='".$_SESSION['profile']['id']."'");
+                               $_SESSION['profile']['language'] = $lang;
+                               showheader(_("My CAcert.org Account!"));
+                               echo _("Your language setting has been updated.");
+                               showfooter();
+                               exit;
+                       }
+               }
+
+               showheader(_("My CAcert.org Account!"));
+               echo _("You tried to use an invalid language.");
+               showfooter();
+               exit;
+       }
+
+       if($oldid == 41 && $_REQUEST['action'] == 'addsec')
+       {
+               csrf_check("seclang");
+               $addlang = mysql_real_escape_string($_REQUEST['addlang']);
+               // Does the language exist?
+               mysql_query("insert into `addlang` set `userid`='".intval($_SESSION['profile']['id'])."', `lang`='$addlang'");
+               showheader(_("My CAcert.org Account!"));
+               echo _("Your language setting has been updated.");
+               showfooter();
+               exit;
+       }
+
+       if($oldid == 41 && $_REQUEST['action'] == 'dellang')
+       {
+               csrf_check("seclang");
+               $remove = mysql_real_escape_string($_REQUEST['remove']);
+               mysql_query("delete from `addlang` where `userid`='".intval($_SESSION['profile']['id'])."' and `lang`='$remove'");
+               showheader(_("My CAcert.org Account!"));
+               echo _("Your language setting has been updated.");
+               showfooter();
+               exit;
+       }
+
+       if(($id == 42 || $id == 43 || $id == 44 || $id == 48 || $id == 49 || $id == 50 ||
+               $oldid == 42 || $oldid == 43 || $oldid == 44 || $oldid == 48 || $oldid == 49 || $oldid == 50) &&
+               $_SESSION['profile']['admin'] != 1)
+       {
+               showheader(_("My CAcert.org Account!"));
+               echo _("You don't have access to this area.");
+               showfooter();
+               exit;
+       }
+
+       if(($id == 53 || $id == 54 || $oldid == 53 || $oldid == 54) &&
+               $_SESSION['profile']['locadmin'] != 1)
+       {
+               showheader(_("My CAcert.org Account!"));
+               echo _("You don't have access to this area.");
+               showfooter();
+               exit;
+       }
+
+       if($oldid == 54 || ($id == 53 && array_key_exists('action',$_REQUEST) && $_REQUEST['action'] != "") || 
+                    ($id == 54 && array_key_exists('action',$_REQUEST) && $_REQUEST['action'] != "" &&
+                       $_REQUEST['action'] != "aliases" && $_REQUEST['action'] != "edit" && $_REQUEST['action'] != "add"))
+       {
+               $id = 53;
+               $ccid = intval(array_key_exists('ccid',$_REQUEST)?$_REQUEST['ccid']:0);
+               $regid = intval(array_key_exists('regid',$_REQUEST)?$_REQUEST['regid']:0);
+               $newreg = intval(array_key_exists('newreg',$_REQUEST)?$_REQUEST['newreg']:0);
+               $locid = intval(array_key_exists('locid',$_REQUEST)?$_REQUEST['locid']:0);
+               $name = array_key_exists('name',$_REQUEST)?mysql_real_escape_string(strip_tags($_REQUEST['name'])):"";
+               $long = array_key_exists('longitude',$_REQUEST)?doubleval($_REQUEST['longitude']):"";
+               $lat =  array_key_exists('latitude', $_REQUEST)?doubleval($_REQUEST['latitude']):"";
+               $action = array_key_exists('action',$_REQUEST)?$_REQUEST['action']:"";
+
+               if($locid > 0 && $action == "edit")
+               {
+                       $query = "update `locations` set `name`='$name', `lat`='$lat', `long`='$long' where `id`='$locid'";
+                       mysql_query($query);
+                       $row = mysql_fetch_assoc(mysql_query("select * from `locations` where `id`='$locid'"));
+                       $_REQUEST['regid'] = $row['regid'];
+                       unset($_REQUEST['ccid']);
+                       unset($_REQUEST['locid']);
+                       unset($_REQUEST['action']);
+               } else if($regid > 0 && $action == "edit") {
+                       $query = "update `regions` set `name`='$name' where `id`='$regid'";
+                       mysql_query($query);
+                       $row = mysql_fetch_assoc(mysql_query("select * from `regions` where `id`='$regid'"));
+                       $_REQUEST['ccid'] = $row['ccid'];
+                       unset($_REQUEST['regid']);
+                       unset($_REQUEST['locid']);
+                       unset($_REQUEST['action']);
+               } else if($regid > 0 && $action == "add") {
+            &nb