vmailpasswd
[hcoop/domtool2.git] / src / mail / vmailpasswd.c
diff --git a/src/mail/vmailpasswd.c b/src/mail/vmailpasswd.c
new file mode 100644 (file)
index 0000000..13b38a9
--- /dev/null
@@ -0,0 +1,121 @@
+/*
+Domtool (http://hcoop.sf.net/)
+Copyright (C) 2005-2007  Adam Chlipala
+
+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., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
+*/
+
+// Setting a virtual mailbox's password if you know its current password
+
+#define _XOPEN_SOURCE
+#include <unistd.h>
+#include <stdio.h>
+#include <ctype.h>
+#include <string.h>
+
+int validDomain(const char *dom) {
+  for (; *dom; ++dom)
+    if (*dom != '.' && *dom != '_' && *dom != '-' && !isalnum(*dom))
+      return 0;
+  return 1;
+}
+
+main(int argc, char *argv[]) {
+  char *domain, addr[1024], cmd[1024], *crypted;
+  FILE *pw;
+  int rc;
+
+  if (argc != 4) {
+    puts("Wrong number of arguments");
+    return 1;
+  }
+
+  if (strlen(argv[1]) >= 1024) {
+    puts("Address too long");
+    return 1;
+  }
+  strcpy(addr, argv[1]);
+
+  domain = strchr(addr, '@');
+
+  if (!domain) {
+    puts("No @-sign found in address");
+    return 1;
+  }
+  *domain = 0;
+  ++domain;
+
+  if (!validDomain(addr)) {
+    puts("Invalid local part");
+    return 1;
+  }
+  if (!validDomain(domain)) {
+    puts("Invalid domain");
+    return 1;
+  }
+
+  sprintf(cmd, "/usr/sbin/userdb -show \"%s/%s\" | /bin/grep ^systempw=", domain, argv[1]);
+  pw = popen(cmd, "r");
+  if (!pw) {
+    puts("popen failure");
+    return 1;
+  }
+
+  if (fscanf(pw, "systempw=%1023[^\n]", cmd) != 1) {
+    puts("Error parsing userdb output");
+    return 1;
+  }
+
+  pclose(pw);
+
+  memcpy(addr, cmd, 2);
+  addr[2] = 0;
+
+  crypted = crypt(argv[2], addr);
+
+  if (!crypted) {
+    puts("Error encrypting");
+    return 1;
+  }
+
+  if (strlen(crypted) > 200){
+    puts("Encrypted password too long");
+    return 1;
+  }
+
+  if (strcmp(crypted, cmd)) {
+    puts("Wrong password");
+    return 2;
+  }
+
+  sprintf(cmd, "/usr/sbin/userdbpw | /usr/sbin/userdb \"%s/%s\" set systempw", domain, argv[1]);
+  pw = popen(cmd, "w");
+
+  if (!pw) {
+    puts("Error running userdbpw");
+    return 1;
+  }
+
+  fputs(argv[3], pw);
+  fputc('\n', pw);
+
+  rc = pclose(pw);
+  if (rc) {
+    puts("userdbpw error");
+    return rc;
+  }
+
+  return 0;
+}