diff --git a/cli/__init__.py b/cli/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/cli/cliLogger.py b/cli/cliLogger.py new file mode 100644 index 000000000..878f5527a --- /dev/null +++ b/cli/cliLogger.py @@ -0,0 +1,28 @@ +import subprocess +import time + +class cliLogger: + fileName = "/home/cyberpanel/error-logs.txt" + + + @staticmethod + def writeforCLI(message, level, method): + try: + file = open(cliLogger.fileName, 'a') + file.writelines("[" + time.strftime( + "%I-%M-%S-%a-%b-%Y") + "] [" + level + ":" + method + "] " + message + "\n") + file.close() + file.close() + except IOError: + return "Can not write to error file!" + + @staticmethod + def readLastNFiles(numberOfLines,fileName): + try: + + lastFewLines = subprocess.check_output(["tail", "-n",str(numberOfLines),fileName]) + + return lastFewLines + + except subprocess.CalledProcessError,msg: + return "File was empty" diff --git a/cli/cyberPanel.py b/cli/cyberPanel.py new file mode 100755 index 000000000..2863d00e8 --- /dev/null +++ b/cli/cyberPanel.py @@ -0,0 +1,123 @@ +#!/usr/bin/env python2.7 +import os,sys +sys.path.append('/usr/local/CyberCP') +import django +os.environ.setdefault("DJANGO_SETTINGS_MODULE", "CyberCP.settings") +django.setup() +import argparse +from inspect import stack +from cliLogger import cliLogger as logger +import json +from plogical.virtualHostUtilities import virtualHostUtilities +import re +from websiteFunctions.models import Websites, ChildDomains +from plogical.vhost import vhost + +class cyberPanel: + def printStatus(self, operationStatus, errorMessage): + data = json.dumps({'success': operationStatus, + 'errorMessage': errorMessage + }) + + print data + + def createWebsite(self, package, owner, domainName, email, php, ssl, dkim, openBasedir): + try: + externalApp = "".join(re.findall("[a-zA-Z]+", domainName))[:7] + numberOfWebsites = str(Websites.objects.count() + ChildDomains.objects.count()) + sslpath = "/home/" + domainName + "/public_html" + phpSelection = 'PHP ' + php + + result = virtualHostUtilities.createVirtualHost(domainName, email, phpSelection, externalApp, numberOfWebsites, ssl, sslpath, dkim, + openBasedir, owner, package) + + if result[0] == 1: + self.printStatus(1,'None') + else: + self.printStatus(0, result[1]) + + except BaseException, msg: + logger.writeforCLI(str(msg), "Error", stack()[0][3]) + self.printStatus(0, str(msg)) + + def deleteWebsite(self, domainName): + try: + + numberOfWebsites = Websites.objects.count() + ChildDomains.objects.count() + vhost.deleteVirtualHostConfigurations(domainName, numberOfWebsites) + self.printStatus(1, 'None') + + except BaseException, msg: + logger.writeforCLI(str(msg), "Error", stack()[0][3]) + print 0 + + + +def main(): + + parser = argparse.ArgumentParser(description='CyberPanel Command Line Interface!') + parser.add_argument('function', help='Specific a operation to perform!') + + + ## Website creation arguemtns + parser.add_argument('--package', help='Select a package for website.') + parser.add_argument('--owner', help='Select a website owner.') + parser.add_argument('--domainName', help='Domain name!') + parser.add_argument('--email', help='Administrator email.') + parser.add_argument('--php', help='Administrator email.') + parser.add_argument('--ssl', help='Weather to obtain SSL.') + parser.add_argument('--dkim', help='DKIM Signing') + parser.add_argument('--openBasedir', help='To enable or disable open_basedir protection for domain.') + + + args = parser.parse_args() + + if args.function == "createWebsite": + + completeCommandExample = 'cyberpanel createWebsite --package Detault --owner admin --domainName cyberpanel.net --email support@cyberpanel.net --php 5.6' + + if not args.package: + print "\n\nPlease enter the package name. For example:\n\n" + completeCommandExample + "\n\n" + + if not args.owner: + print "\n\nPlease enter the owner name. For example:\n\n" + completeCommandExample + "\n\n" + + if not args.domainName: + print "\n\nPlease enter the domain name. For example:\n\n" + completeCommandExample + "\n\n" + + if not args.email: + print "\n\nPlease enter the email. For example:\n\n" + completeCommandExample + "\n\n" + + if not args.php: + print "\n\nPlease enter the PHP version such as 5.6 for PHP version 5.6. For example:\n\n" + completeCommandExample + "\n\n" + + if args.ssl: + ssl = args.ssl + else: + ssl = 0 + + if args.dkim: + dkim = args.dkim + else: + dkim = 0 + + if args.openBasedir: + openBasedir = args.openBasedir + else: + openBasedir = 0 + + cyberpanel = cyberPanel() + cyberpanel.createWebsite(args.package, args.owner, args.domainName, args.email, args.php, ssl, dkim, openBasedir) + elif args.function == "deleteWebsite": + + completeCommandExample = 'cyberpanel deleteWebsite --domainName cyberpanel.net' + + if not args.domainName: + print "\n\nPlease enter the domain to delete. For example:\n\n" + completeCommandExample + "\n\n" + return + + cyberpanel = cyberPanel() + cyberpanel.deleteWebsite(args.domainName) + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/dns/views.py b/dns/views.py index 3fdfdc381..7d0d66a4a 100644 --- a/dns/views.py +++ b/dns/views.py @@ -593,26 +593,6 @@ def submitZoneDeletion(request): final_json = json.dumps(final_dic) return HttpResponse(final_json) -def createDNSRecord(request, zone, name, type, value, priority, ttl): - try: - val = request.session['userID'] - - if Records.objects.filter(name=name, type=type).count() == 0: - record = Records(domainOwner=zone, - domain_id=zone.id, - name=name, - type=type, - content=value, - ttl=ttl, - prio=priority, - disabled=0, - auth=1) - record.save() - except KeyError,msg: - final_dic = {'add_status': 0, 'error_message': "Not Logged In, please refresh the page or login again."} - final_json = json.dumps(final_dic) - return HttpResponse(final_json) - diff --git a/install/install.py b/install/install.py index 7b21449b8..a5fe654be 100644 --- a/install/install.py +++ b/install/install.py @@ -2669,7 +2669,7 @@ def main(): parser = argparse.ArgumentParser(description='CyberPanel Installer') parser.add_argument('publicip', help='Please enter public IP for your VPS or dedicated server.') - parser.add_argument('mysql', help='Specify number of MySQL instances to be used.') + parser.add_argument('--mysql', help='Specify number of MySQL instances to be used.') args = parser.parse_args() logging.InstallLog.writeToFile("Starting CyberPanel installation..") @@ -2687,6 +2687,11 @@ def main(): checks = preFlightsChecks("/usr/local/lsws/",args.publicip,"/usr/local",cwd,"/usr/local/CyberCP") + try: + mysql = args.mysql + except: + mysql = 'One' + checks.checkPythonVersion() checks.setup_account_cyberpanel() @@ -2706,12 +2711,12 @@ def main(): import installCyberPanel - installCyberPanel.Main(cwd, args.mysql) + installCyberPanel.Main(cwd, mysql) checks.fix_selinux_issue() checks.install_psmisc() checks.install_postfix_davecot() - checks.setup_email_Passwords(installCyberPanel.InstallCyberPanel.mysqlPassword, args.mysql) - checks.setup_postfix_davecot_config(args.mysql) + checks.setup_email_Passwords(installCyberPanel.InstallCyberPanel.mysqlPassword, mysql) + checks.setup_postfix_davecot_config(mysql) checks.install_unzip() @@ -2731,7 +2736,7 @@ def main(): checks.installCertBot() checks.test_Requests() - checks.download_install_CyberPanel(installCyberPanel.InstallCyberPanel.mysqlPassword, args.mysql) + checks.download_install_CyberPanel(installCyberPanel.InstallCyberPanel.mysqlPassword, mysql) checks.setup_cron() checks.installTLDExtract() #checks.installdnsPython() diff --git a/plogical/CyberCPLogFileWriter.py b/plogical/CyberCPLogFileWriter.py index 127aa0d21..5324eea56 100644 --- a/plogical/CyberCPLogFileWriter.py +++ b/plogical/CyberCPLogFileWriter.py @@ -14,6 +14,17 @@ class CyberCPLogFileWriter: except IOError,msg: return "Can not write to error file." + @staticmethod + def writeforCLI(message, level, method): + try: + file = open(CyberCPLogFileWriter.fileName, 'a') + file.writelines("[" + time.strftime( + "%I-%M-%S-%a-%b-%Y") + "] [" + level + ":" + method + "] " + message + "\n") + file.close() + file.close() + except IOError: + return "Can not write to error file!" + @staticmethod def readLastNFiles(numberOfLines,fileName): try: diff --git a/plogical/childDomain.py b/plogical/childDomain.py new file mode 100644 index 000000000..e69de29bb diff --git a/plogical/dnsUtilities.py b/plogical/dnsUtilities.py index 9fc4f1853..9324ad0ee 100644 --- a/plogical/dnsUtilities.py +++ b/plogical/dnsUtilities.py @@ -1,7 +1,14 @@ +#!/usr/bin/env python2.7 +import os,sys +sys.path.append('/usr/local/CyberCP') +import django +os.environ.setdefault("DJANGO_SETTINGS_MODULE", "CyberCP.settings") +django.setup() import CyberCPLogFileWriter as logging -import os import subprocess -import shutil +import shlex +from dns.models import Domains,Records + class DNS: @@ -9,373 +16,298 @@ class DNS: zones_base_dir = "/usr/local/lsws/conf/zones/" create_zone_dir = "/usr/local/lsws/conf/zones" + ## DNS Functions + @staticmethod - def createNameServer(virtualHostName, firstNS, firstNSIP, secondNS, secondNSIP): + def dnsTemplate(domain, admin): try: - if not os.path.exists(DNS.zones_base_dir): - os.mkdir(DNS.create_zone_dir) + ipFile = "/etc/cyberpanel/machineIP" + f = open(ipFile) + ipData = f.read() + ipAddress = ipData.split('\n', 1)[0] - zonePath = DNS.zones_base_dir + virtualHostName - zoneFilePath = zonePath + "/zone.conf" + import tldextract + extractDomain = tldextract.extract(domain) + topLevelDomain = extractDomain.domain + '.' + extractDomain.suffix + subDomain = extractDomain.subdomain + if len(subDomain) == 0: - data = open(DNS.nsd_base, "r").readlines() + if Domains.objects.filter(name=topLevelDomain).count() == 0: + zone = Domains(admin=admin, name=topLevelDomain, type="NATIVE") + zone.save() - if DNS.checkIfZoneExists(virtualHostName, data) == 1: + content = "ns1." + topLevelDomain + " hostmaster." + topLevelDomain + " 1 10800 3600 604800 3600" - os.mkdir(zonePath) - zoneFileToWrite = open(zoneFilePath, "w") + soaRecord = Records(domainOwner=zone, + domain_id=zone.id, + name=topLevelDomain, + type="SOA", + content=content, + ttl=3600, + prio=0, + disabled=0, + auth=1) + soaRecord.save() - if DNS.addEntryInMainZone(virtualHostName, data) == 1: - if DNS.perVirtualHostZoneFile(virtualHostName, zoneFileToWrite) == 1: - if DNS.addNSRecord(firstNS, firstNSIP, secondNS, secondNSIP, zoneFileToWrite) == 1: - DNS.restartNSD() - zoneFileToWrite.close() - return 1 - else: - zoneFileToWrite.close() - return 0 - else: - zoneFileToWrite.close() - return 0 - else: - zoneFileToWrite.close() - return 0 + ## Main A record. + record = Records(domainOwner=zone, + domain_id=zone.id, + name=topLevelDomain, + type="A", + content=ipAddress, + ttl=3600, + prio=0, + disabled=0, + auth=1) + record.save() + + # CNAME Records. + + cNameValue = "www." + topLevelDomain + + record = Records(domainOwner=zone, + domain_id=zone.id, + name=cNameValue, + type="CNAME", + content=topLevelDomain, + ttl=3600, + prio=0, + disabled=0, + auth=1) + record.save() + + cNameValue = "ftp." + topLevelDomain + + record = Records(domainOwner=zone, + domain_id=zone.id, + name=cNameValue, + type="CNAME", + content=topLevelDomain, + ttl=3600, + prio=0, + disabled=0, + auth=1) + record.save() + + ## MX Record. + + mxValue = "mail." + topLevelDomain + + record = Records(domainOwner=zone, + domain_id=zone.id, + name=topLevelDomain, + type="MX", + content=mxValue, + ttl=3600, + prio="10", + disabled=0, + auth=1) + record.save() + + record = Records(domainOwner=zone, + domain_id=zone.id, + name=mxValue, + type="A", + content=ipAddress, + ttl=3600, + prio=0, + disabled=0, + auth=1) + record.save() + + ## TXT Records for mail + + record = Records(domainOwner=zone, + domain_id=zone.id, + name=topLevelDomain, + type="TXT", + content="v=spf1 a mx ip4:" + ipAddress + " ~all", + ttl=3600, + prio=0, + disabled=0, + auth=1) + record.save() + + record = Records(domainOwner=zone, + domain_id=zone.id, + name="_dmarc." + topLevelDomain, + type="TXT", + content="v=DMARC1; p=none", + ttl=3600, + prio=0, + disabled=0, + auth=1) + record.save() + + record = Records(domainOwner=zone, + domain_id=zone.id, + name="_domainkey." + topLevelDomain, + type="TXT", + content="t=y; o=~;", + ttl=3600, + prio=0, + disabled=0, + auth=1) + record.save() else: - if not os.path.exists(zonePath): - os.mkdir(zonePath) - zoneFileToWrite = open(zoneFilePath, "w") + if Domains.objects.filter(name=topLevelDomain).count() == 0: + zone = Domains(admin=admin, name=topLevelDomain, type="NATIVE") + zone.save() + content = "ns1." + topLevelDomain + " hostmaster." + topLevelDomain + " 1 10800 3600 604800 3600" - if DNS.perVirtualHostZoneFile(virtualHostName, zoneFileToWrite) == 1: - if DNS.addNSRecord(firstNS, firstNSIP, secondNS, secondNSIP, zoneFileToWrite) == 1: - DNS.restartNSD() - zoneFileToWrite.close() - return 1 - else: - zoneFileToWrite.close() - return 0 - else: - zoneFileToWrite.close() - return 0 + soaRecord = Records(domainOwner=zone, + domain_id=zone.id, + name=topLevelDomain, + type="SOA", + content=content, + ttl=3600, + prio=0, + disabled=0, + auth=1) + soaRecord.save() - else: + ## Main A record. - zoneFileToWrite = open(zoneFilePath, "a") - if DNS.addNSRecord(firstNS, firstNSIP, secondNS, secondNSIP, zoneFileToWrite) == 1: - DNS.restartNSD() - zoneFileToWrite.close() - return 1 - else: - zoneFileToWrite.close() - return 0 + record = Records(domainOwner=zone, + domain_id=zone.id, + name=topLevelDomain, + type="A", + content=ipAddress, + ttl=3600, + prio=0, + disabled=0, + auth=1) + record.save() - zoneFileToWrite.close() - logging.CyberCPLogFileWriter.writeToFile( - "Zone file for virtualhost already exists. " + "[createNameServer]") - return 1 + # CNAME Records. - except IOError, msg: - logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [addEntryInMainZone]") - return 0 + cNameValue = "www." + topLevelDomain - @staticmethod - def checkIfZoneExists(virtualHostName,data): - for items in data: - if items.find(virtualHostName) > -1: - return 0 - return 1 + record = Records(domainOwner=zone, + domain_id=zone.id, + name=cNameValue, + type="CNAME", + content=topLevelDomain, + ttl=3600, + prio=0, + disabled=0, + auth=1) + record.save() + cNameValue = "ftp." + topLevelDomain - @staticmethod - def addEntryInMainZone(virtualHostName,data): + record = Records(domainOwner=zone, + domain_id=zone.id, + name=cNameValue, + type="CNAME", + content=topLevelDomain, + ttl=3600, + prio=0, + disabled=0, + auth=1) + record.save() - # Defining zone to be added - zone = "zone:" + "\n" - zoneName = " name: " + virtualHostName + "\n" - zoneFile = " zonefile: "+virtualHostName+"/zone.conf" + "\n" + ## MX Record. + mxValue = "mail." + topLevelDomain - try: - mainZoneFile = open(DNS.nsd_base,"w") - zoneCheck = 1 - noZones = 1 + record = Records(domainOwner=zone, + domain_id=zone.id, + name=topLevelDomain, + type="MX", + content=mxValue, + ttl=3600, + prio="10", + disabled=0, + auth=1) + record.save() - for items in data: - if items.find("zone:")>-1 and zoneCheck==1: - mainZoneFile.writelines(zone) - mainZoneFile.writelines(zoneName) - mainZoneFile.writelines(zoneFile) - mainZoneFile.writelines("\n") - mainZoneFile.writelines(items) - noZones = 0 - zoneCheck = 0 - else: - mainZoneFile.writelines(items) + record = Records(domainOwner=zone, + domain_id=zone.id, + name=mxValue, + type="A", + content=ipAddress, + ttl=3600, + prio=0, + disabled=0, + auth=1) + record.save() - if noZones ==1: - mainZoneFile.writelines(zone) - mainZoneFile.writelines(zoneName) - mainZoneFile.writelines(zoneFile) - mainZoneFile.writelines("\n") + ## Creating sub-domain level record. - mainZoneFile.close() - return 1 - except IOError,msg: - mainZoneFile.close() - logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [addEntryInMainZone]") - return 0 + zone = Domains.objects.get(name=topLevelDomain) - @staticmethod - def perVirtualHostZoneFile(virtualHostName, zoneFileToWrite): + actualSubDomain = subDomain + "." + topLevelDomain - # Make zone directory + ## Main A record. - origin = "$ORIGIN " + virtualHostName + "." + "\n" - ttl = "$TTL 86400" + "\n" + DNS.createDNSRecord(zone, actualSubDomain, "A", ipAddress, 0, 3600) - try: - zoneFileToWrite.writelines(origin) - zoneFileToWrite.writelines(ttl) - zoneFileToWrite.writelines("\n") + # CNAME Records. - # Create SOA Record - - DNS.createSOARecord(virtualHostName, zoneFileToWrite) - - return 1 + cNameValue = "www." + actualSubDomain + DNS.createDNSRecord(zone, cNameValue, "CNAME", actualSubDomain, 0, 3600) except BaseException, msg: - logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [perVirtualHostZoneFile]") - return 0 + logging.CyberCPLogFileWriter.writeToFile( + "We had errors while creating DNS records for: " + domain + ". Error message: " + str(msg)) @staticmethod - def createSOARecord(virtualHostName,fileHandle): - - # Define SOA Record - - soa = "@ IN SOA ns1 admin@"+virtualHostName+" (" + "\n" - serialNumber = " 2012082703" + "\n" - refreshRate = " 28800" + "\n" - retryRate = " 1400" + "\n" - expiry = " 864000" + "\n" - minTTL = " 86400" + "\n" - endSOA = " )" + "\n" - - + def createDKIMRecords(domain): try: - fileHandle.writelines("\n") - fileHandle.writelines(soa) - fileHandle.writelines(serialNumber) - fileHandle.writelines(refreshRate) - fileHandle.writelines(retryRate) - fileHandle.writelines(expiry) - fileHandle.writelines(minTTL) - fileHandle.writelines(endSOA) + import tldextract + extractDomain = tldextract.extract(domain) + topLevelDomain = extractDomain.domain + '.' + extractDomain.suffix - fileHandle.writelines("\n") + zone = Domains.objects.get(name=topLevelDomain) + path = "/etc/opendkim/keys/" + topLevelDomain + "/default.txt" + command = "sudo cat " + path + output = subprocess.check_output(shlex.split(command)) - return 1 - except IOError,msg: - logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [createSOARecord]") - return 0 - + record = Records(domainOwner=zone, + domain_id=zone.id, + name="default._domainkey." + topLevelDomain, + type="TXT", + content="v=DKIM1; k=rsa; p=" + output[53:269], + ttl=3600, + prio=0, + disabled=0, + auth=1) + record.save() + except BaseException, msg: + logging.CyberCPLogFileWriter.writeToFile( + "We had errors while creating DNS records for: " + domain + ". Error message: " + str(msg)) @staticmethod - def addNSRecord(nsRecordOne,firstNSIP, nsRecordTwo, secondNSIP, fileHandle): - # Defining NS Record - - NSARecordOne = nsRecordOne.split(".")[0] - NSARecordTwo = nsRecordTwo.split(".")[0] - - NS1 = "\t\t" + "NS" + "\t" + nsRecordOne + "." "\n" - NS2 = "\t\t" + "NS" + "\t" + nsRecordTwo + "." - - try: - fileHandle.writelines("\n") - fileHandle.writelines("\n") - - fileHandle.writelines(NS1) - fileHandle.writelines(NS2) - - DNS.addRecord(NSARecordOne, "A", firstNSIP, fileHandle) - DNS.addRecord(NSARecordTwo, "A", secondNSIP, fileHandle) - - fileHandle.writelines("\n") - return 1 - except IOError, msg: - logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [addRecord]") - return 0 - + def createDNSRecord(zone, name, type, value, priority, ttl): + if Records.objects.filter(name=name, type=type).count() == 0: + record = Records(domainOwner=zone, + domain_id=zone.id, + name=name, + type=type, + content=value, + ttl=ttl, + prio=priority, + disabled=0, + auth=1) + record.save() @staticmethod - def addRecord(recordValue, recordType, recordIP, fileHandle): - - # Define Record - - recordString = recordValue +"\t" + "IN" + "\t" + recordType + "\t" + recordIP - + def deleteDNSZone(virtualHostName): try: - fileHandle.writelines("\n") - fileHandle.writelines(recordString) - fileHandle.writelines("\n") - return 1 - except IOError, msg: - logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [addRecord]") - return 0 - - - @staticmethod - def restartNSD(): - - try: - - ############## Restart NSD ###################### - - cmd = [] - - cmd.append("systemctl") - cmd.append("restart") - cmd.append("nsd") - - res = subprocess.call(cmd) - - if res == 1: - print("###############################################") - print(" Could restart NSD ") - print("###############################################") - logging.CyberCPLogFileWriter.writeToFile("[Failed to restart NSD]") - return 0 - else: - print("###############################################") - print(" NSD Restarted ") - print("###############################################") - return 1 - - - except OSError, msg: - logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [restartNSD]") - return 0 - - @staticmethod - def deleteZone(virtualHostname): - try: - if os.path.exists(DNS.zones_base_dir+virtualHostname): - shutil.rmtree(DNS.zones_base_dir+virtualHostname) - - data = open(DNS.nsd_base, "r").readlines() - - writeDataToFile = open(DNS.nsd_base,"w") - - index = 0 - - for items in data: - if items.find(virtualHostname) >-1: - try: - del data[index-1] - del data[index-1] - del data[index-1] - except: - break - break - index = index+1 - - for items in data: - writeDataToFile.writelines(items) - - writeDataToFile.close() - - - - except OSError,msg: - logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [deleteZone]") - - @staticmethod - def addARecord(virtualHostName,recordValue,recordIP): - try: - - if not os.path.exists(DNS.zones_base_dir): - os.mkdir(DNS.create_zone_dir) - - data = open(DNS.nsd_base, "r").readlines() - - zonePath = DNS.zones_base_dir + virtualHostName - zoneFilePath = zonePath + "/zone.conf" - - if DNS.checkIfZoneExists(virtualHostName,data) == 1: - - DNS.addEntryInMainZone(virtualHostName,data) - - os.mkdir(zonePath) - zoneFileToWrite = open(zoneFilePath, "w") - - DNS.perVirtualHostZoneFile(virtualHostName, zoneFileToWrite) - DNS.addRecord(recordValue,"A",recordIP,zoneFileToWrite) - - - else: - - if not os.path.exists(zonePath): - os.mkdir(zonePath) - zoneFileToWrite = open(zoneFilePath, "w") - - - if DNS.perVirtualHostZoneFile(virtualHostName, zoneFileToWrite) == 1: - if DNS.addRecord(recordValue,"A",recordIP,zoneFileToWrite) == 1: - DNS.restartNSD() - zoneFileToWrite.close() - return 1 - else: - zoneFileToWrite.close() - return 0 - else: - zoneFileToWrite.close() - return 0 - - else: - - zoneFileToWrite = open(zoneFilePath, "a") - if DNS.addRecord(recordValue,"A",recordIP,zoneFileToWrite) == 1: - DNS.restartNSD() - zoneFileToWrite.close() - return 1 - else: - zoneFileToWrite.close() - return 0 - - except BaseException,msg: - logging.CyberCPLogFileWriter.writeToFile(str(msg) + ' [addARecord]') - - - @staticmethod - def deleteRecord(recordValue, recordType, recordIP, virtualHostName): - - try: - zonePath = DNS.zones_base_dir + virtualHostName - zoneFilePath = zonePath + "/zone.conf" - - data = open(zoneFilePath, "r").readlines() - - writeDataToFile = open(zoneFilePath, "w") - - for items in data: - if items.find(recordIP) > -1 and items.find(recordValue) > -1 and items.find(recordType)>-1: - continue - else: - writeDataToFile.writelines(items) - - writeDataToFile.close() - - return 1 - except IOError, msg: - logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [addRecord]") - return 0 \ No newline at end of file + delZone = Domains.objects.get(name=virtualHostName) + delZone.delete() + except: + ## There does not exist a zone for this domain. + pass \ No newline at end of file diff --git a/plogical/installUtilities.py b/plogical/installUtilities.py index b213c8d5a..b95c9f3a8 100644 --- a/plogical/installUtilities.py +++ b/plogical/installUtilities.py @@ -143,7 +143,7 @@ class installUtilities: cmd = shlex.split(command) - res = subprocess.call(cmd) + res = subprocess.call(cmd, stdout=FNULL, stderr=subprocess.STDOUT) if res == 1: print("###############################################") diff --git a/plogical/vhost.py b/plogical/vhost.py new file mode 100644 index 000000000..49c650d2b --- /dev/null +++ b/plogical/vhost.py @@ -0,0 +1,1069 @@ +#!/usr/bin/env python2.7 +import os +import os.path +import sys +import django +sys.path.append('/usr/local/CyberCP') +os.environ.setdefault("DJANGO_SETTINGS_MODULE", "CyberCP.settings") +django.setup() +import shutil +import installUtilities +from websiteFunctions.models import Websites, ChildDomains +import subprocess +import shlex +import CyberCPLogFileWriter as logging +from databases.models import Databases +from mysqlUtilities import mysqlUtilities +from dnsUtilities import DNS +from random import randint + + +## If you want justice, you have come to the wrong place. + + +class vhost: + + Server_root = "/usr/local/lsws" + cyberPanel = "/usr/local/CyberCP" + + @staticmethod + def addUser(virtualHostUser, path): + try: + + FNULL = open(os.devnull, 'w') + + command = "adduser " + virtualHostUser + " -M -d " + path + cmd = shlex.split(command) + subprocess.call(cmd, stdout=FNULL, stderr=subprocess.STDOUT) + + command = "groupadd " + virtualHostUser + cmd = shlex.split(command) + subprocess.call(cmd, stdout=FNULL, stderr=subprocess.STDOUT) + + command = "usermod -a -G " + virtualHostUser + " " + virtualHostUser + cmd = shlex.split(command) + subprocess.call(cmd, stdout=FNULL, stderr=subprocess.STDOUT) + + except BaseException, msg: + logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [addingUsers]") + + @staticmethod + def createDirectories(path, virtualHostUser, pathHTML, pathLogs, confPath, completePathToConfigFile): + try: + + FNULL = open(os.devnull, 'w') + + try: + os.makedirs(path) + + command = "chown " + virtualHostUser + ":" + virtualHostUser + " " + path + cmd = shlex.split(command) + subprocess.call(cmd, stdout=FNULL, stderr=subprocess.STDOUT) + + except OSError, msg: + logging.CyberCPLogFileWriter.writeToFile( + str(msg) + " [27 Not able create to directories for virtual host [createDirectories]]") + return [0, "[27 Not able to directories for virtual host [createDirectories]]"] + + try: + os.makedirs(pathHTML) + + command = "chown " + virtualHostUser + ":" + virtualHostUser + " " + pathHTML + cmd = shlex.split(command) + subprocess.call(cmd, stdout=FNULL, stderr=subprocess.STDOUT) + + except OSError, msg: + logging.CyberCPLogFileWriter.writeToFile( + str(msg) + " [33 Not able to directories for virtual host [createDirectories]]") + return [0, "[33 Not able to directories for virtual host [createDirectories]]"] + + try: + os.makedirs(pathLogs) + + command = "chown " + "nobody" + ":" + "nobody" + " " + pathLogs + cmd = shlex.split(command) + subprocess.call(cmd, stdout=FNULL, stderr=subprocess.STDOUT) + + command = "chmod -R 666 " + pathLogs + cmd = shlex.split(command) + subprocess.call(cmd, stdout=FNULL, stderr=subprocess.STDOUT) + + except OSError, msg: + logging.CyberCPLogFileWriter.writeToFile( + str(msg) + " [39 Not able to directories for virtual host [createDirectories]]") + return [0, "[39 Not able to directories for virtual host [createDirectories]]"] + + try: + ## For configuration files permissions will be changed later globally. + os.makedirs(confPath) + except OSError, msg: + logging.CyberCPLogFileWriter.writeToFile( + str(msg) + " [45 Not able to directories for virtual host [createDirectories]]") + return [0, "[45 Not able to directories for virtual host [createDirectories]]"] + + try: + ## For configuration files permissions will be changed later globally. + file = open(completePathToConfigFile, "w+") + + command = "chown " + "lsadm" + ":" + "lsadm" + " " + completePathToConfigFile + cmd = shlex.split(command) + subprocess.call(cmd, stdout=FNULL, stderr=subprocess.STDOUT) + + except IOError, msg: + logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [createDirectories]]") + return [0, "[45 Not able to directories for virtual host [createDirectories]]"] + + return [1, 'None'] + + except BaseException, msg: + logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [createDirectories]") + return [0, str(msg)] + + @staticmethod + def finalizeVhostCreation(virtualHostName, virtualHostUser): + try: + + FNULL = open(os.devnull, 'w') + + shutil.copy("/usr/local/CyberCP/index.html", "/home/" + virtualHostName + "/public_html/index.html") + + command = "chown " + virtualHostUser + ":" + virtualHostUser + " " + "/home/" + virtualHostName + "/public_html/index.html" + cmd = shlex.split(command) + subprocess.call(cmd, stdout=FNULL, stderr=subprocess.STDOUT) + + vhostPath = vhost.Server_root + "/conf/vhosts" + + command = "chown -R " + "lsadm" + ":" + "lsadm" + " " + vhostPath + cmd = shlex.split(command) + subprocess.call(cmd, stdout=FNULL, stderr=subprocess.STDOUT) + + except BaseException, msg: + logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [finalizeVhostCreation]") + + @staticmethod + def createDirectoryForVirtualHost(virtualHostName,administratorEmail,virtualHostUser, phpVersion, openBasedir): + + path = "/home/" + virtualHostName + pathHTML = "/home/" + virtualHostName + "/public_html" + pathLogs = "/home/" + virtualHostName + "/logs" + confPath = vhost.Server_root + "/conf/vhosts/"+virtualHostName + completePathToConfigFile = confPath +"/vhost.conf" + + + ## adding user + + vhost.addUser(virtualHostUser, path) + + ## Creating Directories + + result = vhost.createDirectories(path, virtualHostUser, pathHTML, pathLogs, confPath, completePathToConfigFile) + + if result[0] == 0: + return [0, result[1]] + + + ## Creating Per vhost Configuration File + + + if vhost.perHostVirtualConf(completePathToConfigFile,administratorEmail,virtualHostUser,phpVersion, virtualHostName, openBasedir) == 1: + return [1,"None"] + else: + return [0,"[61 Not able to create per host virtual configurations [perHostVirtualConf]"] + + + @staticmethod + def perHostVirtualConf(vhFile, administratorEmail,virtualHostUser, phpVersion, virtualHostName, openBasedir): + # General Configurations tab + try: + confFile = open(vhFile, "w+") + + docRoot = "docRoot $VH_ROOT/public_html" + "\n" + vhDomain = "vhDomain $VH_NAME" + "\n" + vhAliases = "vhAliases www.$VH_NAME"+ "\n" + adminEmails = "adminEmails " + administratorEmail + "\n" + enableGzip = "enableGzip 1" + "\n" + enableIpGeo = "enableIpGeo 1" + "\n" + "\n" + + confFile.writelines(docRoot) + confFile.writelines(vhDomain) + confFile.writelines(vhAliases) + confFile.writelines(adminEmails) + confFile.writelines(enableGzip) + confFile.writelines(enableIpGeo) + + # Index file settings + + index = "index {" + "\n" + userServer = " useServer 0" + "\n" + indexFiles = " indexFiles index.php, index.html" + "\n" + index_end = "}" + "\n" + "\n" + + confFile.writelines(index) + confFile.writelines(userServer) + confFile.writelines(indexFiles) + confFile.writelines(index_end) + + # Error Log Settings + + + error_log = "errorlog $VH_ROOT/logs/$VH_NAME.error_log {" + "\n" + useServer = " useServer 0" + "\n" + logLevel = " logLevel ERROR" + "\n" + rollingSize = " rollingSize 10M" + "\n" + error_log_end = "}" + "\n" + "\n" + + confFile.writelines(error_log) + confFile.writelines(useServer) + confFile.writelines(logLevel) + confFile.writelines(rollingSize) + confFile.writelines(error_log_end) + + # Access Log Settings + + access_Log = "accesslog $VH_ROOT/logs/$VH_NAME.access_log {" + "\n" + useServer = " useServer 0" + "\n" + logFormat = ' logFormat "%v %h %l %u %t \"%r\" %>s %b"' + "\n" + logHeaders = " logHeaders 5" + "\n" + rollingSize = " rollingSize 10M" + "\n" + keepDays = " keepDays 10" + compressArchive = " compressArchive 1" + "\n" + access_Log_end = "}" + "\n" + "\n" + + confFile.writelines(access_Log) + confFile.writelines(useServer) + confFile.writelines(logFormat) + confFile.writelines(logHeaders) + confFile.writelines(rollingSize) + confFile.writelines(keepDays) + confFile.writelines(compressArchive) + confFile.writelines(access_Log_end) + + # php settings + + scripthandler = "scripthandler {" + "\n" + add = " add lsapi:"+virtualHostUser+" php" + "\n" + php_end = "}" + "\n" + "\n" + + confFile.writelines(scripthandler) + confFile.writelines(add) + confFile.writelines(php_end) + + + ## external app + + if phpVersion == "PHP 5.3": + php = "53" + elif phpVersion == "PHP 5.4": + php = "55" + elif phpVersion == "PHP 5.5": + php = "55" + elif phpVersion == "PHP 5.6": + php = "56" + elif phpVersion == "PHP 7.0": + php = "70" + elif phpVersion == "PHP 7.1": + php = "71" + elif phpVersion == "PHP 7.2": + php = "72" + + extprocessor = "extprocessor "+virtualHostUser+" {\n" + type = " type lsapi\n" + address = " address UDS://tmp/lshttpd/"+virtualHostUser+".sock\n" + maxConns = " maxConns 10\n" + env = " env LSAPI_CHILDREN=10\n" + initTimeout = " initTimeout 60\n" + retryTimeout = " retryTimeout 0\n" + persistConn = " persistConn 1\n" + persistConnTimeout = " pcKeepAliveTimeout 1\n" + respBuffer = " respBuffer 0\n" + autoStart = " autoStart 1\n" + path = " path /usr/local/lsws/lsphp"+php+"/bin/lsphp\n" + extUser = " extUser " + virtualHostUser + "\n" + extGroup = " extGroup " + virtualHostUser + "\n" + memSoftLimit = " memSoftLimit 2047M\n" + memHardLimit = " memHardLimit 2047M\n" + procSoftLimit = " procSoftLimit 400\n" + procHardLimit = " procHardLimit 500\n" + extprocessorEnd = "}\n" + + confFile.writelines(extprocessor) + confFile.writelines(type) + confFile.writelines(address) + confFile.writelines(maxConns) + confFile.writelines(env) + confFile.writelines(initTimeout) + confFile.writelines(retryTimeout) + confFile.writelines(persistConn) + confFile.writelines(persistConnTimeout) + confFile.writelines(respBuffer) + confFile.writelines(autoStart) + confFile.writelines(path) + confFile.writelines(extUser) + confFile.writelines(extGroup) + confFile.writelines(memSoftLimit) + confFile.writelines(memHardLimit) + confFile.writelines(procSoftLimit) + confFile.writelines(procHardLimit) + confFile.writelines(extprocessorEnd) + + ## File Manager defination + + context = "context /.filemanager {\n" + type = " type NULL\n" + location = " location /usr/local/lsws/Example/html/FileManager\n" + allowBrowse = " allowBrowse 1\n" + autoIndex = " autoIndex 1\n\n" + + accessControl = " accessControl {\n" + allow = " allow 127.0.0.1, localhost\n" + deny = " deny 0.0.0.0/0\n" + accessControlEnds = " }\n" + + phpIniOverride = "phpIniOverride {\n" + php_admin_value = 'php_admin_value open_basedir "/tmp:/usr/local/lsws/Example/html/FileManager:$VH_ROOT"\n' + endPHPIniOverride = "}\n" + + + defaultCharSet = " addDefaultCharset off\n" + contextEnds = "}\n" + + confFile.writelines(context) + confFile.writelines(type) + confFile.writelines(location) + confFile.writelines(allowBrowse) + confFile.writelines(autoIndex) + confFile.writelines(accessControl) + confFile.writelines(allow) + confFile.writelines(deny) + confFile.writelines(accessControlEnds) + if openBasedir == 1: + confFile.writelines(phpIniOverride) + confFile.writelines(php_admin_value) + confFile.writelines(endPHPIniOverride) + confFile.writelines(defaultCharSet) + confFile.writelines(contextEnds) + + ## OpenBase Dir Protection + + phpIniOverride = "phpIniOverride {\n" + php_admin_value = 'php_admin_value open_basedir "/tmp:$VH_ROOT"\n' + endPHPIniOverride = "}\n" + + if openBasedir == 1: + confFile.writelines(phpIniOverride) + confFile.writelines(php_admin_value) + confFile.writelines(endPHPIniOverride) + + confFile.close() + + except BaseException, msg: + logging.CyberCPLogFileWriter.writeToFile( + str(msg) + " [IO Error with per host config file [perHostVirtualConf]]") + return 0 + return 1 + + @staticmethod + def createNONSSLMapEntry(virtualHostName): + try: + data = open("/usr/local/lsws/conf/httpd_config.conf").readlines() + writeDataToFile = open("/usr/local/lsws/conf/httpd_config.conf", 'w') + + map = " map " + virtualHostName + " " + virtualHostName + "\n" + + mapchecker = 1 + + for items in data: + if (mapchecker == 1 and (items.find("listener") > -1 and items.find("Default") > -1)): + writeDataToFile.writelines(items) + writeDataToFile.writelines(map) + mapchecker = 0 + else: + writeDataToFile.writelines(items) + + return 1 + except BaseException, msg: + logging.CyberCPLogFileWriter.writeToFile(str(msg)) + return 0 + + + @staticmethod + def createConfigInMainVirtualHostFile(virtualHostName): + + #virtualhost project.cyberpersons.com { + #vhRoot / home / project.cyberpersons.com + #configFile $SERVER_ROOT / conf / vhosts /$VH_NAME / vhconf.conf + #allowSymbolLink 1 + #enableScript 1 + #restrained 1 + #} + + try: + + if vhost.createNONSSLMapEntry(virtualHostName) == 0: + return [0, "Failed to create NON SSL Map Entry [createConfigInMainVirtualHostFile]"] + + writeDataToFile = open("/usr/local/lsws/conf/httpd_config.conf", 'a') + + writeDataToFile.writelines("\n") + writeDataToFile.writelines("virtualHost " + virtualHostName + " {\n") + writeDataToFile.writelines(" vhRoot /home/$VH_NAME\n") + writeDataToFile.writelines(" configFile $SERVER_ROOT/conf/vhosts/$VH_NAME/vhost.conf\n") + writeDataToFile.writelines(" allowSymbolLink 1\n") + writeDataToFile.writelines(" enableScript 1\n") + writeDataToFile.writelines(" restrained 1\n") + writeDataToFile.writelines("}\n") + writeDataToFile.writelines("\n") + + writeDataToFile.close() + + + writeDataToFile.close() + return [1,"None"] + + except BaseException,msg: + logging.CyberCPLogFileWriter.writeToFile(str(msg) + "223 [IO Error with main config file [createConfigInMainVirtualHostFile]]") + return [0,"223 [IO Error with main config file [createConfigInMainVirtualHostFile]]"] + + @staticmethod + def deleteVirtualHostConfigurations(virtualHostName, numberOfSites): + + try: + + ## Deleting master conf + vhost.deleteCoreConf(virtualHostName, numberOfSites) + + delWebsite = Websites.objects.get(domain=virtualHostName) + databases = Databases.objects.filter(website=delWebsite) + + childDomains = delWebsite.childdomains_set.all() + + ## Deleting child domains + + for items in childDomains: + numberOfSites = Websites.objects.count() + ChildDomains.objects.count() + vhost.deleteCoreConf(items.domain, numberOfSites) + + for items in databases: + mysqlUtilities.deleteDatabase(items.dbName, items.dbUser) + + delWebsite.delete() + + ## Deleting DNS Zone if there is any. + + DNS.deleteDNSZone(virtualHostName) + + installUtilities.installUtilities.reStartLiteSpeed() + + ## Delete mail accounts + + command = "sudo rm -rf /home/vmail/" + virtualHostName + subprocess.call(shlex.split(command)) + + except BaseException, msg: + logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [Not able to remove virtual host configuration from main configuration file.]") + return 0 + + return 1 + + @staticmethod + def deleteCoreConf(virtualHostName, numberOfSites): + + virtualHostPath = "/home/" + virtualHostName + try: + shutil.rmtree(virtualHostPath) + except BaseException, msg: + logging.CyberCPLogFileWriter.writeToFile( + str(msg) + " [Not able to remove virtual host directory from /home continuing..]") + + try: + confPath = vhost.Server_root + "/conf/vhosts/" + virtualHostName + shutil.rmtree(confPath) + except BaseException, msg: + logging.CyberCPLogFileWriter.writeToFile( + str(msg) + " [Not able to remove virtual host configuration directory from /conf ]") + + try: + data = open("/usr/local/lsws/conf/httpd_config.conf").readlines() + + writeDataToFile = open("/usr/local/lsws/conf/httpd_config.conf", 'w') + + check = 1 + sslCheck = 1 + + for items in data: + + if numberOfSites == 1: + + if (items.find(virtualHostName) > -1 and items.find( + " map " + virtualHostName) > -1): + continue + if (items.find(virtualHostName) > -1 and ( + items.find("virtualHost") > -1 or items.find("virtualhost") > -1)): + check = 0 + if items.find("listener") > -1 and items.find("SSL") > -1: + sslCheck = 0 + if (check == 1 and sslCheck == 1): + writeDataToFile.writelines(items) + if (items.find("}") > -1 and (check == 0 or sslCheck == 0)): + check = 1 + sslCheck = 1 + else: + if (items.find(virtualHostName) > -1 and items.find( + " map " + virtualHostName) > -1): + continue + if (items.find(virtualHostName) > -1 and ( + items.find("virtualHost") > -1 or items.find("virtualhost") > -1)): + check = 0 + if (check == 1): + writeDataToFile.writelines(items) + if (items.find("}") > -1 and check == 0): + check = 1 + + except BaseException, msg: + logging.CyberCPLogFileWriter.writeToFile( + str(msg) + " [Not able to remove virtual host configuration from main configuration file.]") + return 0 + + return 1 + + @staticmethod + def checkIfVirtualHostExists(virtualHostName): + if os.path.exists("/home/" + virtualHostName): + return 1 + return 0 + + @staticmethod + def changePHP(vhFile, phpVersion): + + # General Configurations tab + + finalphp = 0 + + try: + data = open(vhFile, "r").readlines() + + if phpVersion == "PHP 5.3": + finalphp = 53 + elif phpVersion == "PHP 5.4": + finalphp = 54 + elif phpVersion == "PHP 5.5": + finalphp = 55 + elif phpVersion == "PHP 5.6": + finalphp = 56 + elif phpVersion == "PHP 7.0": + finalphp = 70 + elif phpVersion == "PHP 7.1": + finalphp = 71 + elif phpVersion == "PHP 7.2": + finalphp = 72 + + writeDataToFile = open(vhFile, "w") + + sockRandomPath = str(randint(1000, 9999)) + + address = " address UDS://tmp/lshttpd/" + sockRandomPath + ".sock\n" + path = " path /usr/local/lsws/lsphp" + str(finalphp) + "/bin/lsphp\n" + + for items in data: + if items.find("/usr/local/lsws/lsphp") > -1 and items.find("path") > -1: + writeDataToFile.writelines(path) + else: + writeDataToFile.writelines(items) + + writeDataToFile.close() + + installUtilities.installUtilities.reStartLiteSpeed() + + print "1,None" + + except BaseException, msg: + logging.CyberCPLogFileWriter.writeToFile( + str(msg) + " [IO Error with per host config file [changePHP]]") + return [0, str(msg) + " [IO Error with per host config file [changePHP]]"] + + @staticmethod + def getDiskUsage(path, totalAllowed): + try: + + totalUsageInMB = subprocess.check_output(["sudo", "du", "-hs", path, "--block-size=1M"]).split()[0] + + percentage = float(100) / float(totalAllowed) + + percentage = float(percentage) * float(totalUsageInMB) + + data = [int(totalUsageInMB), int(percentage)] + return data + except BaseException, msg: + logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [getDiskUsage]") + return [int(0), int(0)] + + @staticmethod + def addRewriteRules(virtualHostName, fileName=None): + + try: + path = vhost.Server_root + "/conf/vhosts/" + virtualHostName + "/vhost.conf" + + data = open(path, "r").readlines() + + if fileName == None: + dataToWritten = "rewriteFile /home/" + virtualHostName + "/public_html/.htaccess" + "\n" + else: + dataToWritten = "rewriteFile " + fileName + "\n" + + ### Data if re-writes are not already enabled + + rewrite = "rewrite {\n" + enables = " enable 1\n" + rules = " rules << -1: + return 1 + return 0 + + except BaseException, msg: + logging.CyberCPLogFileWriter.writeToFile( + str(msg) + " [IO Error with per host config file [checkIfRewriteEnabled]]") + return 0 + return 1 + + @staticmethod + def suspendVirtualHost(virtualHostName): + try: + + confPath = vhost.Server_root + "/conf/vhosts/" + virtualHostName + + command = "sudo mv " + confPath + " " + confPath + "-suspended" + subprocess.call(shlex.split(command)) + + except BaseException, msg: + logging.CyberCPLogFileWriter.writeToFile( + str(msg) + " [suspendVirtualHost]") + return 0 + return 1 + + @staticmethod + def UnsuspendVirtualHost(virtualHostName): + try: + + confPath = vhost.Server_root + "/conf/vhosts/" + virtualHostName + + command = "sudo mv " + confPath + "-suspended" + " " + confPath + subprocess.call(shlex.split(command)) + + command = "chown -R " + "lsadm" + ":" + "lsadm" + " " + confPath + cmd = shlex.split(command) + subprocess.call(cmd) + + + except BaseException, msg: + logging.CyberCPLogFileWriter.writeToFile( + str(msg) + " [UnsuspendVirtualHost]") + return 0 + return 1 + + @staticmethod + def findDomainBW(domainName, totalAllowed): + try: + path = "/home/" + domainName + "/logs/" + domainName + ".access_log" + + if not os.path.exists("/home/" + domainName + "/logs"): + print "0,0" + + bwmeta = "/home/" + domainName + "/logs/bwmeta" + + if not os.path.exists(path): + print "0,0" + + if os.path.exists(bwmeta): + try: + data = open(bwmeta).readlines() + currentUsed = int(data[0].strip("\n")) + + inMB = int(float(currentUsed) / (1024.0 * 1024.0)) + + percentage = float(100) / float(totalAllowed) + + percentage = float(percentage) * float(inMB) + except: + print "0,0" + + if percentage > 100.0: + percentage = 100 + + print str(inMB) + "," + str(percentage) + else: + print "0,0" + + + except OSError, msg: + logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [findDomainBW]") + print "0,0" + except ValueError, msg: + logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [findDomainBW]") + print "0,0" + + @staticmethod + def permissionControl(path): + try: + command = 'sudo chown -R cyberpanel:cyberpanel ' + path + + cmd = shlex.split(command) + + res = subprocess.call(cmd) + + except BaseException, msg: + logging.CyberCPLogFileWriter.writeToFile(str(msg)) + + @staticmethod + def leaveControl(path): + try: + command = 'sudo chown -R root:root ' + path + + cmd = shlex.split(command) + + res = subprocess.call(cmd) + + except BaseException, msg: + logging.CyberCPLogFileWriter.writeToFile(str(msg)) + + @staticmethod + def checkIfAliasExists(aliasDomain): + try: + confPath = os.path.join(vhost.Server_root, "conf/httpd_config.conf") + data = open(confPath, 'r').readlines() + + for items in data: + if items.find(aliasDomain) > -1: + domains = filter(None, items.split(" ")) + for domain in domains: + if domain.strip(',').strip('\n') == aliasDomain: + return 1 + + return 0 + except BaseException, msg: + logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [checkIfAliasExists]") + return 1 + + @staticmethod + def checkIfSSLAliasExists(data, aliasDomain): + try: + for items in data: + if items.strip(',').strip('\n') == aliasDomain: + return 1 + return 0 + + except BaseException, msg: + logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [checkIfSSLAliasExists]") + return 1 + + @staticmethod + def createAliasSSLMap(confPath, masterDomain, aliasDomain): + try: + + data = open(confPath, 'r').readlines() + writeToFile = open(confPath, 'w') + sslCheck = 0 + + for items in data: + if (items.find("listener SSL") > -1): + sslCheck = 1 + if items.find(masterDomain) > -1 and items.find('map') > -1 and sslCheck == 1: + data = filter(None, items.split(" ")) + if data[1] == masterDomain: + if vhost.checkIfSSLAliasExists(data, aliasDomain) == 0: + writeToFile.writelines(items.rstrip('\n') + ", " + aliasDomain + "\n") + sslCheck = 0 + else: + writeToFile.writelines(items) + else: + writeToFile.writelines(items) + + writeToFile.close() + installUtilities.installUtilities.reStartLiteSpeed() + + except BaseException, msg: + logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [createAliasSSLMap]") + + + ## Child Domain Functions + + @staticmethod + def finalizeDomainCreation(virtualHostUser, path): + try: + + FNULL = open(os.devnull, 'w') + + shutil.copy("/usr/local/CyberCP/index.html", path + "/index.html") + + command = "chown " + virtualHostUser + ":" + virtualHostUser + " " + path + "/index.html" + cmd = shlex.split(command) + subprocess.call(cmd, stdout=FNULL, stderr=subprocess.STDOUT) + + vhostPath = vhost.Server_root + "/conf/vhosts" + command = "chown -R " + "lsadm" + ":" + "lsadm" + " " + vhostPath + cmd = shlex.split(command) + subprocess.call(cmd, stdout=FNULL, stderr=subprocess.STDOUT) + + except BaseException, msg: + logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [finalizeDomainCreation]") + + @staticmethod + def createDirectoryForDomain(masterDomain, domain, phpVersion, path, administratorEmail, virtualHostUser, + openBasedir): + + FNULL = open(os.devnull, 'w') + + confPath = vhost.Server_root + "/conf/vhosts/" + domain + completePathToConfigFile = confPath + "/vhost.conf" + + try: + os.makedirs(path) + command = "chown " + virtualHostUser + ":" + virtualHostUser + " " + path + cmd = shlex.split(command) + subprocess.call(cmd, stdout=FNULL, stderr=subprocess.STDOUT) + except OSError, msg: + logging.CyberCPLogFileWriter.writeToFile( + str(msg) + "329 [Not able to create directories for virtual host [createDirectoryForDomain]]") + + try: + ## For configuration files permissions will be changed later globally. + os.makedirs(confPath) + except OSError, msg: + logging.CyberCPLogFileWriter.writeToFile( + str(msg) + "335 [Not able to create directories for virtual host [createDirectoryForDomain]]") + return [0, "[344 Not able to directories for virtual host [createDirectoryForDomain]]"] + + try: + ## For configuration files permissions will be changed later globally. + file = open(completePathToConfigFile, "w+") + except IOError, msg: + logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [createDirectoryForDomain]]") + return [0, "[351 Not able to directories for virtual host [createDirectoryForDomain]]"] + + if vhost.perHostDomainConf(path, masterDomain, completePathToConfigFile, + administratorEmail, phpVersion, virtualHostUser, openBasedir) == 1: + return [1, "None"] + else: + return [0, "[359 Not able to create per host virtual configurations [perHostVirtualConf]"] + + @staticmethod + def perHostDomainConf(path, masterDomain, vhFile, administratorEmail, phpVersion, virtualHostUser, openBasedir): + + # General Configurations tab + + try: + confFile = open(vhFile, "w+") + + docRoot = "docRoot " + path + "\n" + vhDomain = "vhDomain $VH_NAME" + "\n" + vhAliases = "vhAliases www.$VH_NAME" + "\n" + adminEmails = "adminEmails " + administratorEmail + "\n" + enableGzip = "enableGzip 1" + "\n" + enableIpGeo = "enableIpGeo 1" + "\n" + "\n" + + confFile.writelines(docRoot) + confFile.writelines(vhDomain) + confFile.writelines(vhAliases) + confFile.writelines(adminEmails) + confFile.writelines(enableGzip) + confFile.writelines(enableIpGeo) + + # Index file settings + + index = "index {" + "\n" + userServer = " useServer 0" + "\n" + indexFiles = " indexFiles index.php, index.html" + "\n" + index_end = "}" + "\n" + "\n" + + confFile.writelines(index) + confFile.writelines(userServer) + confFile.writelines(indexFiles) + confFile.writelines(index_end) + + # Error Log Settings + + + error_log = "errorlog $VH_ROOT/logs/" + masterDomain + ".error_log {" + "\n" + useServer = " useServer 0" + "\n" + logLevel = " logLevel ERROR" + "\n" + rollingSize = " rollingSize 10M" + "\n" + error_log_end = "}" + "\n" + "\n" + + confFile.writelines(error_log) + confFile.writelines(useServer) + confFile.writelines(logLevel) + confFile.writelines(rollingSize) + confFile.writelines(error_log_end) + + # Access Log Settings + + access_Log = "accesslog $VH_ROOT/logs/" + masterDomain + ".access_log {" + "\n" + useServer = " useServer 0" + "\n" + logFormat = ' logFormat "%v %h %l %u %t \"%r\" %>s %b"' + "\n" + logHeaders = " logHeaders 5" + "\n" + rollingSize = " rollingSize 10M" + "\n" + keepDays = " keepDays 10" + compressArchive = " compressArchive 1" + "\n" + access_Log_end = "}" + "\n" + "\n" + + confFile.writelines(access_Log) + confFile.writelines(useServer) + confFile.writelines(logFormat) + confFile.writelines(logHeaders) + confFile.writelines(rollingSize) + confFile.writelines(keepDays) + confFile.writelines(compressArchive) + confFile.writelines(access_Log_end) + + ## OpenBase Dir Protection + + phpIniOverride = "phpIniOverride {\n" + php_admin_value = 'php_admin_value open_basedir "/tmp:/usr/local/lsws/Example/html/FileManager:$VH_ROOT"\n' + endPHPIniOverride = "}\n" + + if openBasedir == 1: + confFile.writelines(phpIniOverride) + confFile.writelines(php_admin_value) + confFile.writelines(endPHPIniOverride) + + # php settings + + sockRandomPath = str(randint(1000, 9999)) + + scripthandler = "scripthandler {" + "\n" + add = " add lsapi:" + virtualHostUser + sockRandomPath + " php" + "\n" + php_end = "}" + "\n" + "\n" + + confFile.writelines(scripthandler) + confFile.writelines(add) + confFile.writelines(php_end) + + ## external app + + if phpVersion == "PHP 5.3": + php = "53" + elif phpVersion == "PHP 5.4": + php = "55" + elif phpVersion == "PHP 5.5": + php = "55" + elif phpVersion == "PHP 5.6": + php = "56" + elif phpVersion == "PHP 7.0": + php = "70" + elif phpVersion == "PHP 7.1": + php = "71" + elif phpVersion == "PHP 7.2": + php = "72" + + extprocessor = "extprocessor " + virtualHostUser + sockRandomPath + " {\n" + type = " type lsapi\n" + address = " address UDS://tmp/lshttpd/" + virtualHostUser + sockRandomPath + ".sock\n" + maxConns = " maxConns 10\n" + env = " env LSAPI_CHILDREN=10\n" + initTimeout = " initTimeout 60\n" + retryTimeout = " retryTimeout 0\n" + persistConn = " persistConn 1\n" + persistConnTimeout = " pcKeepAliveTimeout 1\n" + respBuffer = " respBuffer 0\n" + autoStart = " autoStart 1\n" + path = " path /usr/local/lsws/lsphp" + php + "/bin/lsphp\n" + extUser = " extUser " + virtualHostUser + "\n" + extGroup = " extGroup " + virtualHostUser + "\n" + memSoftLimit = " memSoftLimit 2047M\n" + memHardLimit = " memHardLimit 2047M\n" + procSoftLimit = " procSoftLimit 400\n" + procHardLimit = " procHardLimit 500\n" + extprocessorEnd = "}\n" + + confFile.writelines(extprocessor) + confFile.writelines(type) + confFile.writelines(address) + confFile.writelines(maxConns) + confFile.writelines(env) + confFile.writelines(initTimeout) + confFile.writelines(retryTimeout) + confFile.writelines(persistConn) + confFile.writelines(persistConnTimeout) + confFile.writelines(respBuffer) + confFile.writelines(autoStart) + confFile.writelines(path) + confFile.writelines(extUser) + confFile.writelines(extGroup) + confFile.writelines(memSoftLimit) + confFile.writelines(memHardLimit) + confFile.writelines(procSoftLimit) + confFile.writelines(procHardLimit) + confFile.writelines(extprocessorEnd) + + confFile.close() + + except BaseException, msg: + logging.CyberCPLogFileWriter.writeToFile( + str(msg) + " [IO Error with per host config file [perHostDomainConf]]") + return 0 + return 1 + + @staticmethod + def createConfigInMainDomainHostFile(domain, masterDomain): + # virtualhost project.cyberpersons.com { + # vhRoot / home / project.cyberpersons.com + # configFile $SERVER_ROOT / conf / vhosts /$VH_NAME / vhconf.conf + # allowSymbolLink 1 + # enableScript 1 + # restrained 1 + # } + + try: + + if vhost.createNONSSLMapEntry(domain) == 0: + return [0, "Failed to create NON SSL Map Entry [createConfigInMainVirtualHostFile]"] + + writeDataToFile = open("/usr/local/lsws/conf/httpd_config.conf", 'a') + + writeDataToFile.writelines("\n") + writeDataToFile.writelines("virtualHost " + domain + " {\n") + writeDataToFile.writelines(" vhRoot /home/" + masterDomain + "\n") + writeDataToFile.writelines(" configFile $SERVER_ROOT/conf/vhosts/$VH_NAME/vhost.conf\n") + writeDataToFile.writelines(" allowSymbolLink 1\n") + writeDataToFile.writelines(" enableScript 1\n") + writeDataToFile.writelines(" restrained 1\n") + writeDataToFile.writelines("}\n") + writeDataToFile.writelines("\n") + + writeDataToFile.close() + + return [1, "None"] + + except BaseException, msg: + logging.CyberCPLogFileWriter.writeToFile( + str(msg) + "223 [IO Error with main config file [createConfigInMainDomainHostFile]]") + return [0, "223 [IO Error with main config file [createConfigInMainDomainHostFile]]"] \ No newline at end of file diff --git a/plogical/virtualHostUtilities.py b/plogical/virtualHostUtilities.py index 0cbb9f1cd..fabbf4078 100644 --- a/plogical/virtualHostUtilities.py +++ b/plogical/virtualHostUtilities.py @@ -1,18 +1,30 @@ +#!/usr/bin/env python2.7 +import os import os.path +import sys +import django +sys.path.append('/usr/local/CyberCP') +os.environ.setdefault("DJANGO_SETTINGS_MODULE", "CyberCP.settings") +django.setup() import shutil -import CyberCPLogFileWriter as logging -import subprocess import argparse -import shlex import installUtilities -from random import randint import sslUtilities from os.path import join from os import listdir, rmdir from shutil import move import randomPassword as randomPassword -from mailUtilities import mailUtilities from multiprocessing import Process +from websiteFunctions.models import Websites, ChildDomains +from loginSystem.models import Administrator +from packages.models import Package +import subprocess +import shlex +from plogical.mailUtilities import mailUtilities +import CyberCPLogFileWriter as logging +from dnsUtilities import DNS +from vhost import vhost + ## If you want justice, you have come to the wrong place. @@ -21,766 +33,192 @@ class virtualHostUtilities: Server_root = "/usr/local/lsws" cyberPanel = "/usr/local/CyberCP" - @staticmethod - def addUser(virtualHostUser, path): + def createVirtualHost(virtualHostName, administratorEmail, phpVersion, virtualHostUser, numberOfSites, ssl, sslPath, + dkimCheck, openBasedir, websiteOwner, packageName): try: - FNULL = open(os.devnull, 'w') + if Websites.objects.filter(domain=virtualHostName).count() > 0: + raise BaseException("This website already exists.") - command = "adduser " + virtualHostUser + " -M -d " + path - cmd = shlex.split(command) - subprocess.call(cmd, stdout=FNULL, stderr=subprocess.STDOUT) + if ChildDomains.objects.filter(domain=virtualHostName).count() > 0: + raise BaseException("This website already exists as child domain.") - command = "groupadd " + virtualHostUser - cmd = shlex.split(command) - subprocess.call(cmd, stdout=FNULL, stderr=subprocess.STDOUT) + ####### Limitations Check End - command = "usermod -a -G " + virtualHostUser + " " + virtualHostUser - cmd = shlex.split(command) - subprocess.call(cmd, stdout=FNULL, stderr=subprocess.STDOUT) + ##### Zone creation - except BaseException, msg: - logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [addingUsers]") + admin = Administrator.objects.get(userName=websiteOwner) + DNS.dnsTemplate(virtualHostName, admin) - @staticmethod - def createDirectories(path, virtualHostUser, pathHTML, pathLogs, confPath, completePathToConfigFile): - try: + ## zone creation - FNULL = open(os.devnull, 'w') + if vhost.checkIfVirtualHostExists(virtualHostName) == 1: + raise BaseException("Virtual Host Directory already exists!") - try: - os.makedirs(path) + if vhost.checkIfAliasExists(virtualHostName) == 1: + raise BaseException("This domain exists as Alias.") - command = "chown " + virtualHostUser + ":" + virtualHostUser + " " + path - cmd = shlex.split(command) - subprocess.call(cmd, stdout=FNULL, stderr=subprocess.STDOUT) + if dkimCheck == 1: + if mailUtilities.checkIfDKIMInstalled() == 0: + raise BaseException("OpenDKIM is not installed, install OpenDKIM from DKIM Manager.") - except OSError, msg: - logging.CyberCPLogFileWriter.writeToFile( - str(msg) + " [27 Not able create to directories for virtual host [createDirectories]]") - return [0, "[27 Not able to directories for virtual host [createDirectories]]"] + retValues = mailUtilities.setupDKIM(virtualHostName) + if retValues[0] == 0: + raise BaseException(retValues[1]) - try: - os.makedirs(pathHTML) + retValues = vhost.createDirectoryForVirtualHost(virtualHostName, administratorEmail, + virtualHostUser, phpVersion, openBasedir) + if retValues[0] == 0: + raise BaseException(retValues[1]) - command = "chown " + virtualHostUser + ":" + virtualHostUser + " " + pathHTML - cmd = shlex.split(command) - subprocess.call(cmd, stdout=FNULL, stderr=subprocess.STDOUT) + retValues = vhost.createConfigInMainVirtualHostFile(virtualHostName) + if retValues[0] == 0: + raise BaseException(retValues[1]) - except OSError, msg: - logging.CyberCPLogFileWriter.writeToFile( - str(msg) + " [33 Not able to directories for virtual host [createDirectories]]") - return [0, "[33 Not able to directories for virtual host [createDirectories]]"] - - try: - os.makedirs(pathLogs) - - command = "chown " + "nobody" + ":" + "nobody" + " " + pathLogs - cmd = shlex.split(command) - subprocess.call(cmd, stdout=FNULL, stderr=subprocess.STDOUT) - - command = "chmod -R 666 " + pathLogs - cmd = shlex.split(command) - subprocess.call(cmd, stdout=FNULL, stderr=subprocess.STDOUT) - - except OSError, msg: - logging.CyberCPLogFileWriter.writeToFile( - str(msg) + " [39 Not able to directories for virtual host [createDirectories]]") - return [0, "[39 Not able to directories for virtual host [createDirectories]]"] - - try: - ## For configuration files permissions will be changed later globally. - os.makedirs(confPath) - except OSError, msg: - logging.CyberCPLogFileWriter.writeToFile( - str(msg) + " [45 Not able to directories for virtual host [createDirectories]]") - return [0, "[45 Not able to directories for virtual host [createDirectories]]"] - - try: - ## For configuration files permissions will be changed later globally. - file = open(completePathToConfigFile, "w+") - - command = "chown " + "lsadm" + ":" + "lsadm" + " " + completePathToConfigFile - cmd = shlex.split(command) - subprocess.call(cmd, stdout=FNULL, stderr=subprocess.STDOUT) - - except IOError, msg: - logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [createDirectories]]") - return [0, "[45 Not able to directories for virtual host [createDirectories]]"] - - return [1, 'None'] - - except BaseException, msg: - logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [createDirectories]") - return [0, str(msg)] - - @staticmethod - def finalizeVhostCreation(virtualHostName, virtualHostUser): - try: - - FNULL = open(os.devnull, 'w') - - shutil.copy("/usr/local/CyberCP/index.html", "/home/" + virtualHostName + "/public_html/index.html") - - command = "chown " + virtualHostUser + ":" + virtualHostUser + " " + "/home/" + virtualHostName + "/public_html/index.html" - cmd = shlex.split(command) - subprocess.call(cmd, stdout=FNULL, stderr=subprocess.STDOUT) - - vhostPath = virtualHostUtilities.Server_root + "/conf/vhosts" - - command = "chown -R " + "lsadm" + ":" + "lsadm" + " " + vhostPath - cmd = shlex.split(command) - subprocess.call(cmd, stdout=FNULL, stderr=subprocess.STDOUT) - - except BaseException, msg: - logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [finalizeVhostCreation]") - - @staticmethod - def createDirectoryForVirtualHost(virtualHostName,administratorEmail,virtualHostUser, phpVersion, openBasedir): - - path = "/home/" + virtualHostName - pathHTML = "/home/" + virtualHostName + "/public_html" - pathLogs = "/home/" + virtualHostName + "/logs" - confPath = virtualHostUtilities.Server_root + "/conf/vhosts/"+virtualHostName - completePathToConfigFile = confPath +"/vhost.conf" - - - ## adding user - - virtualHostUtilities.addUser(virtualHostUser, path) - - ## Creating Directories - - result = virtualHostUtilities.createDirectories(path, virtualHostUser, pathHTML, pathLogs, confPath, completePathToConfigFile) - - if result[0] == 0: - return [0, result[1]] - - - ## Creating Per vhost Configuration File - - - if virtualHostUtilities.perHostVirtualConf(completePathToConfigFile,administratorEmail,virtualHostUser,phpVersion, virtualHostName, openBasedir) == 1: - return [1,"None"] - else: - return [0,"[61 Not able to create per host virtual configurations [perHostVirtualConf]"] - - - @staticmethod - def perHostVirtualConf(vhFile, administratorEmail,virtualHostUser, phpVersion, virtualHostName, openBasedir): - # General Configurations tab - try: - confFile = open(vhFile, "w+") - - docRoot = "docRoot $VH_ROOT/public_html" + "\n" - vhDomain = "vhDomain $VH_NAME" + "\n" - vhAliases = "vhAliases www.$VH_NAME"+ "\n" - adminEmails = "adminEmails " + administratorEmail + "\n" - enableGzip = "enableGzip 1" + "\n" - enableIpGeo = "enableIpGeo 1" + "\n" + "\n" - - confFile.writelines(docRoot) - confFile.writelines(vhDomain) - confFile.writelines(vhAliases) - confFile.writelines(adminEmails) - confFile.writelines(enableGzip) - confFile.writelines(enableIpGeo) - - # Index file settings - - index = "index {" + "\n" - userServer = " useServer 0" + "\n" - indexFiles = " indexFiles index.php, index.html" + "\n" - index_end = "}" + "\n" + "\n" - - confFile.writelines(index) - confFile.writelines(userServer) - confFile.writelines(indexFiles) - confFile.writelines(index_end) - - # Error Log Settings - - - error_log = "errorlog $VH_ROOT/logs/$VH_NAME.error_log {" + "\n" - useServer = " useServer 0" + "\n" - logLevel = " logLevel ERROR" + "\n" - rollingSize = " rollingSize 10M" + "\n" - error_log_end = "}" + "\n" + "\n" - - confFile.writelines(error_log) - confFile.writelines(useServer) - confFile.writelines(logLevel) - confFile.writelines(rollingSize) - confFile.writelines(error_log_end) - - # Access Log Settings - - access_Log = "accesslog $VH_ROOT/logs/$VH_NAME.access_log {" + "\n" - useServer = " useServer 0" + "\n" - logFormat = ' logFormat "%v %h %l %u %t \"%r\" %>s %b"' + "\n" - logHeaders = " logHeaders 5" + "\n" - rollingSize = " rollingSize 10M" + "\n" - keepDays = " keepDays 10" - compressArchive = " compressArchive 1" + "\n" - access_Log_end = "}" + "\n" + "\n" - - confFile.writelines(access_Log) - confFile.writelines(useServer) - confFile.writelines(logFormat) - confFile.writelines(logHeaders) - confFile.writelines(rollingSize) - confFile.writelines(keepDays) - confFile.writelines(compressArchive) - confFile.writelines(access_Log_end) - - # php settings - - scripthandler = "scripthandler {" + "\n" - add = " add lsapi:"+virtualHostUser+" php" + "\n" - php_end = "}" + "\n" + "\n" - - confFile.writelines(scripthandler) - confFile.writelines(add) - confFile.writelines(php_end) - - - ## external app - - if phpVersion == "PHP 5.3": - php = "53" - elif phpVersion == "PHP 5.4": - php = "55" - elif phpVersion == "PHP 5.5": - php = "55" - elif phpVersion == "PHP 5.6": - php = "56" - elif phpVersion == "PHP 7.0": - php = "70" - elif phpVersion == "PHP 7.1": - php = "71" - elif phpVersion == "PHP 7.2": - php = "72" - - extprocessor = "extprocessor "+virtualHostUser+" {\n" - type = " type lsapi\n" - address = " address UDS://tmp/lshttpd/"+virtualHostUser+".sock\n" - maxConns = " maxConns 10\n" - env = " env LSAPI_CHILDREN=10\n" - initTimeout = " initTimeout 60\n" - retryTimeout = " retryTimeout 0\n" - persistConn = " persistConn 1\n" - persistConnTimeout = " pcKeepAliveTimeout 1\n" - respBuffer = " respBuffer 0\n" - autoStart = " autoStart 1\n" - path = " path /usr/local/lsws/lsphp"+php+"/bin/lsphp\n" - extUser = " extUser " + virtualHostUser + "\n" - extGroup = " extGroup " + virtualHostUser + "\n" - memSoftLimit = " memSoftLimit 2047M\n" - memHardLimit = " memHardLimit 2047M\n" - procSoftLimit = " procSoftLimit 400\n" - procHardLimit = " procHardLimit 500\n" - extprocessorEnd = "}\n" - - confFile.writelines(extprocessor) - confFile.writelines(type) - confFile.writelines(address) - confFile.writelines(maxConns) - confFile.writelines(env) - confFile.writelines(initTimeout) - confFile.writelines(retryTimeout) - confFile.writelines(persistConn) - confFile.writelines(persistConnTimeout) - confFile.writelines(respBuffer) - confFile.writelines(autoStart) - confFile.writelines(path) - confFile.writelines(extUser) - confFile.writelines(extGroup) - confFile.writelines(memSoftLimit) - confFile.writelines(memHardLimit) - confFile.writelines(procSoftLimit) - confFile.writelines(procHardLimit) - confFile.writelines(extprocessorEnd) - - ## File Manager defination - - context = "context /.filemanager {\n" - type = " type NULL\n" - location = " location /usr/local/lsws/Example/html/FileManager\n" - allowBrowse = " allowBrowse 1\n" - autoIndex = " autoIndex 1\n\n" - - accessControl = " accessControl {\n" - allow = " allow 127.0.0.1, localhost\n" - deny = " deny 0.0.0.0/0\n" - accessControlEnds = " }\n" - - phpIniOverride = "phpIniOverride {\n" - php_admin_value = 'php_admin_value open_basedir "/tmp:/usr/local/lsws/Example/html/FileManager:$VH_ROOT"\n' - endPHPIniOverride = "}\n" - - - defaultCharSet = " addDefaultCharset off\n" - contextEnds = "}\n" - - confFile.writelines(context) - confFile.writelines(type) - confFile.writelines(location) - confFile.writelines(allowBrowse) - confFile.writelines(autoIndex) - confFile.writelines(accessControl) - confFile.writelines(allow) - confFile.writelines(deny) - confFile.writelines(accessControlEnds) - if openBasedir == 1: - confFile.writelines(phpIniOverride) - confFile.writelines(php_admin_value) - confFile.writelines(endPHPIniOverride) - confFile.writelines(defaultCharSet) - confFile.writelines(contextEnds) - - ## OpenBase Dir Protection - - phpIniOverride = "phpIniOverride {\n" - php_admin_value = 'php_admin_value open_basedir "/tmp:$VH_ROOT"\n' - endPHPIniOverride = "}\n" - - if openBasedir == 1: - confFile.writelines(phpIniOverride) - confFile.writelines(php_admin_value) - confFile.writelines(endPHPIniOverride) - - confFile.close() - - except BaseException, msg: - logging.CyberCPLogFileWriter.writeToFile( - str(msg) + " [IO Error with per host config file [perHostVirtualConf]]") - return 0 - return 1 - - @staticmethod - def createNONSSLMapEntry(virtualHostName): - try: - data = open("/usr/local/lsws/conf/httpd_config.conf").readlines() - writeDataToFile = open("/usr/local/lsws/conf/httpd_config.conf", 'w') - - map = " map " + virtualHostName + " " + virtualHostName + "\n" - - mapchecker = 1 - - for items in data: - if (mapchecker == 1 and (items.find("listener") > -1 and items.find("Default") > -1)): - writeDataToFile.writelines(items) - writeDataToFile.writelines(map) - mapchecker = 0 + if ssl == 1: + installUtilities.installUtilities.reStartLiteSpeed() + retValues = sslUtilities.issueSSLForDomain(virtualHostName, administratorEmail, sslPath) + if retValues[0] == 0: + raise BaseException(retValues[1]) else: - writeDataToFile.writelines(items) + installUtilities.installUtilities.reStartLiteSpeed() + + if ssl == 0: + installUtilities.installUtilities.reStartLiteSpeed() + + vhost.finalizeVhostCreation(virtualHostName, virtualHostUser) + + ## Create Configurations ends here + + ## DKIM Check + + if dkimCheck == 1: + DNS.createDKIMRecords(virtualHostName) + + selectedPackage = Package.objects.get(packageName=packageName) + + website = Websites(admin=admin, package=selectedPackage, domain=virtualHostName, + adminEmail=administratorEmail, + phpSelection=phpVersion, ssl=ssl, externalApp=virtualHostUser) + + website.save() + + print "1,None" + return 1, 'None' - return 1 except BaseException, msg: - logging.CyberCPLogFileWriter.writeToFile(str(msg)) - return 0 - + vhost.deleteVirtualHostConfigurations(virtualHostName, numberOfSites) + logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [createVirtualHost]") + print "0," + str(msg) + return 0, str(msg) @staticmethod - def createConfigInMainVirtualHostFile(virtualHostName): - - #virtualhost project.cyberpersons.com { - #vhRoot / home / project.cyberpersons.com - #configFile $SERVER_ROOT / conf / vhosts /$VH_NAME / vhconf.conf - #allowSymbolLink 1 - #enableScript 1 - #restrained 1 - #} - - try: - - if virtualHostUtilities.createNONSSLMapEntry(virtualHostName) == 0: - return [0, "Failed to create NON SSL Map Entry [createConfigInMainVirtualHostFile]"] - - writeDataToFile = open("/usr/local/lsws/conf/httpd_config.conf", 'a') - - writeDataToFile.writelines("\n") - writeDataToFile.writelines("virtualHost " + virtualHostName + " {\n") - writeDataToFile.writelines(" vhRoot /home/$VH_NAME\n") - writeDataToFile.writelines(" configFile $SERVER_ROOT/conf/vhosts/$VH_NAME/vhost.conf\n") - writeDataToFile.writelines(" allowSymbolLink 1\n") - writeDataToFile.writelines(" enableScript 1\n") - writeDataToFile.writelines(" restrained 1\n") - writeDataToFile.writelines("}\n") - writeDataToFile.writelines("\n") - - writeDataToFile.close() - - - writeDataToFile.close() - return [1,"None"] - - except BaseException,msg: - logging.CyberCPLogFileWriter.writeToFile(str(msg) + "223 [IO Error with main config file [createConfigInMainVirtualHostFile]]") - return [0,"223 [IO Error with main config file [createConfigInMainVirtualHostFile]]"] - - - ## Domain Specific Functions - - @staticmethod - def finalizeDomainCreation(virtualHostUser, path): + def issueSSL(virtualHost, path, adminEmail): try: FNULL = open(os.devnull, 'w') - shutil.copy("/usr/local/CyberCP/index.html", path + "/index.html") + retValues = sslUtilities.issueSSLForDomain(virtualHost, adminEmail, path) - command = "chown " + virtualHostUser + ":" + virtualHostUser + " " + path + "/index.html" - cmd = shlex.split(command) - subprocess.call(cmd, stdout=FNULL, stderr=subprocess.STDOUT) + if retValues[0] == 0: + print "0," + str(retValues[1]) + return + + installUtilities.installUtilities.reStartLiteSpeed() vhostPath = virtualHostUtilities.Server_root + "/conf/vhosts" command = "chown -R " + "lsadm" + ":" + "lsadm" + " " + vhostPath cmd = shlex.split(command) subprocess.call(cmd, stdout=FNULL, stderr=subprocess.STDOUT) - except BaseException, msg: - logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [finalizeDomainCreation]") - - - @staticmethod - def createDirectoryForDomain(masterDomain, domain, phpVersion, path, administratorEmail,virtualHostUser, openBasedir): - - FNULL = open(os.devnull, 'w') - - confPath = virtualHostUtilities.Server_root + "/conf/vhosts/" + domain - completePathToConfigFile = confPath + "/vhost.conf" - - try: - os.makedirs(path) - command = "chown " + virtualHostUser + ":" + virtualHostUser + " " + path - cmd = shlex.split(command) - subprocess.call(cmd,stdout=FNULL, stderr=subprocess.STDOUT) - except OSError, msg: - logging.CyberCPLogFileWriter.writeToFile( - str(msg) + "329 [Not able to create directories for virtual host [createDirectoryForDomain]]") - - try: - ## For configuration files permissions will be changed later globally. - os.makedirs(confPath) - except OSError, msg: - logging.CyberCPLogFileWriter.writeToFile( - str(msg) + "335 [Not able to create directories for virtual host [createDirectoryForDomain]]") - return [0, "[344 Not able to directories for virtual host [createDirectoryForDomain]]"] - - try: - ## For configuration files permissions will be changed later globally. - file = open(completePathToConfigFile, "w+") - except IOError, msg: - logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [createDirectoryForDomain]]") - return [0, "[351 Not able to directories for virtual host [createDirectoryForDomain]]"] - - - if virtualHostUtilities.perHostDomainConf(path, masterDomain, completePathToConfigFile, - administratorEmail, phpVersion,virtualHostUser, openBasedir) == 1: - return [1,"None"] - else: - return [0, "[359 Not able to create per host virtual configurations [perHostVirtualConf]"] - - @staticmethod - def perHostDomainConf(path, masterDomain, vhFile, administratorEmail, phpVersion,virtualHostUser, openBasedir): - - # General Configurations tab - - try: - confFile = open(vhFile, "w+") - - docRoot = "docRoot " + path + "\n" - vhDomain = "vhDomain $VH_NAME" + "\n" - vhAliases = "vhAliases www.$VH_NAME" + "\n" - adminEmails = "adminEmails " + administratorEmail + "\n" - enableGzip = "enableGzip 1" + "\n" - enableIpGeo = "enableIpGeo 1" + "\n" + "\n" - - confFile.writelines(docRoot) - confFile.writelines(vhDomain) - confFile.writelines(vhAliases) - confFile.writelines(adminEmails) - confFile.writelines(enableGzip) - confFile.writelines(enableIpGeo) - - # Index file settings - - index = "index {" + "\n" - userServer = " useServer 0" + "\n" - indexFiles = " indexFiles index.php, index.html" + "\n" - index_end = "}" + "\n" + "\n" - - confFile.writelines(index) - confFile.writelines(userServer) - confFile.writelines(indexFiles) - confFile.writelines(index_end) - - # Error Log Settings - - - error_log = "errorlog $VH_ROOT/logs/" + masterDomain + ".error_log {" + "\n" - useServer = " useServer 0" + "\n" - logLevel = " logLevel ERROR" + "\n" - rollingSize = " rollingSize 10M" + "\n" - error_log_end = "}" + "\n" + "\n" - - confFile.writelines(error_log) - confFile.writelines(useServer) - confFile.writelines(logLevel) - confFile.writelines(rollingSize) - confFile.writelines(error_log_end) - - # Access Log Settings - - access_Log = "accesslog $VH_ROOT/logs/" + masterDomain + ".access_log {" + "\n" - useServer = " useServer 0" + "\n" - logFormat = ' logFormat "%v %h %l %u %t \"%r\" %>s %b"' + "\n" - logHeaders = " logHeaders 5" + "\n" - rollingSize = " rollingSize 10M" + "\n" - keepDays = " keepDays 10" - compressArchive = " compressArchive 1" + "\n" - access_Log_end = "}" + "\n" + "\n" - - confFile.writelines(access_Log) - confFile.writelines(useServer) - confFile.writelines(logFormat) - confFile.writelines(logHeaders) - confFile.writelines(rollingSize) - confFile.writelines(keepDays) - confFile.writelines(compressArchive) - confFile.writelines(access_Log_end) - - ## OpenBase Dir Protection - - phpIniOverride = "phpIniOverride {\n" - php_admin_value = 'php_admin_value open_basedir "/tmp:/usr/local/lsws/Example/html/FileManager:$VH_ROOT"\n' - endPHPIniOverride = "}\n" - - if openBasedir == 1: - confFile.writelines(phpIniOverride) - confFile.writelines(php_admin_value) - confFile.writelines(endPHPIniOverride) - - # php settings - - sockRandomPath = str(randint(1000, 9999)) - - scripthandler = "scripthandler {" + "\n" - add = " add lsapi:" + virtualHostUser + sockRandomPath + " php" + "\n" - php_end = "}" + "\n" + "\n" - - confFile.writelines(scripthandler) - confFile.writelines(add) - confFile.writelines(php_end) - - ## external app - - if phpVersion == "PHP 5.3": - php = "53" - elif phpVersion == "PHP 5.4": - php = "55" - elif phpVersion == "PHP 5.5": - php = "55" - elif phpVersion == "PHP 5.6": - php = "56" - elif phpVersion == "PHP 7.0": - php = "70" - elif phpVersion == "PHP 7.1": - php = "71" - elif phpVersion == "PHP 7.2": - php = "72" - - - extprocessor = "extprocessor " + virtualHostUser+sockRandomPath + " {\n" - type = " type lsapi\n" - address = " address UDS://tmp/lshttpd/" + virtualHostUser+sockRandomPath + ".sock\n" - maxConns = " maxConns 10\n" - env = " env LSAPI_CHILDREN=10\n" - initTimeout = " initTimeout 60\n" - retryTimeout = " retryTimeout 0\n" - persistConn = " persistConn 1\n" - persistConnTimeout = " pcKeepAliveTimeout 1\n" - respBuffer = " respBuffer 0\n" - autoStart = " autoStart 1\n" - path = " path /usr/local/lsws/lsphp" + php + "/bin/lsphp\n" - extUser = " extUser " + virtualHostUser + "\n" - extGroup = " extGroup " + virtualHostUser + "\n" - memSoftLimit = " memSoftLimit 2047M\n" - memHardLimit = " memHardLimit 2047M\n" - procSoftLimit = " procSoftLimit 400\n" - procHardLimit = " procHardLimit 500\n" - extprocessorEnd = "}\n" - - confFile.writelines(extprocessor) - confFile.writelines(type) - confFile.writelines(address) - confFile.writelines(maxConns) - confFile.writelines(env) - confFile.writelines(initTimeout) - confFile.writelines(retryTimeout) - confFile.writelines(persistConn) - confFile.writelines(persistConnTimeout) - confFile.writelines(respBuffer) - confFile.writelines(autoStart) - confFile.writelines(path) - confFile.writelines(extUser) - confFile.writelines(extGroup) - confFile.writelines(memSoftLimit) - confFile.writelines(memHardLimit) - confFile.writelines(procSoftLimit) - confFile.writelines(procHardLimit) - confFile.writelines(extprocessorEnd) - - - confFile.close() + print "1,None" + return except BaseException, msg: logging.CyberCPLogFileWriter.writeToFile( - str(msg) + " [IO Error with per host config file [perHostDomainConf]]") - return 0 - return 1 + str(msg) + " [issueSSL]") + print "0," + str(msg) @staticmethod - def createConfigInMainDomainHostFile(domain, masterDomain): - # virtualhost project.cyberpersons.com { - # vhRoot / home / project.cyberpersons.com - # configFile $SERVER_ROOT / conf / vhosts /$VH_NAME / vhconf.conf - # allowSymbolLink 1 - # enableScript 1 - # restrained 1 - # } - + def getAccessLogs(fileName, page): try: - if virtualHostUtilities.createNONSSLMapEntry(domain) == 0: - return [0, "Failed to create NON SSL Map Entry [createConfigInMainVirtualHostFile]"] + numberOfTotalLines = int(subprocess.check_output(["wc", "-l", fileName]).split(" ")[0]) - writeDataToFile = open("/usr/local/lsws/conf/httpd_config.conf", 'a') - - writeDataToFile.writelines("\n") - writeDataToFile.writelines("virtualHost " + domain + " {\n") - writeDataToFile.writelines(" vhRoot /home/" + masterDomain + "\n") - writeDataToFile.writelines(" configFile $SERVER_ROOT/conf/vhosts/$VH_NAME/vhost.conf\n") - writeDataToFile.writelines(" allowSymbolLink 1\n") - writeDataToFile.writelines(" enableScript 1\n") - writeDataToFile.writelines(" restrained 1\n") - writeDataToFile.writelines("}\n") - writeDataToFile.writelines("\n") - - writeDataToFile.close() - - return [1, "None"] - - except BaseException, msg: - logging.CyberCPLogFileWriter.writeToFile( - str(msg) + "223 [IO Error with main config file [createConfigInMainDomainHostFile]]") - return [0, "223 [IO Error with main config file [createConfigInMainDomainHostFile]]"] - - @staticmethod - def deleteVirtualHostConfigurations(virtualHostName, numberOfSites): - - virtualHostPath = "/home/" + virtualHostName - try: - shutil.rmtree(virtualHostPath) - except BaseException,msg: - logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [Not able to remove virtual host directory from /home continuing..]") - - - try: - confPath = virtualHostUtilities.Server_root + "/conf/vhosts/" + virtualHostName - shutil.rmtree(confPath) - except BaseException, msg: - logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [Not able to remove virtual host configuration directory from /conf ]") - - try: - data = open("/usr/local/lsws/conf/httpd_config.conf").readlines() - - writeDataToFile = open("/usr/local/lsws/conf/httpd_config.conf", 'w') - - check = 1 - sslCheck=1 - - for items in data: - - if numberOfSites == 1: - - if (items.find(virtualHostName) > -1 and items.find(" map " + virtualHostName) > -1): - continue - if (items.find(virtualHostName) > -1 and (items.find("virtualHost") > -1 or items.find("virtualhost") > -1)): - check = 0 - if items.find("listener")>-1 and items.find("SSL") > -1: - sslCheck = 0 - if (check == 1 and sslCheck == 1): - writeDataToFile.writelines(items) - if (items.find("}") > -1 and (check == 0 or sslCheck == 0)): - check = 1 - sslCheck = 1 + if numberOfTotalLines < 25: + data = subprocess.check_output(["cat", fileName]) + else: + if page == 1: + end = numberOfTotalLines + start = end - 24 + if start <= 0: + start = 1 + startingAndEnding = "'" + str(start) + "," + str(end) + "p'" + command = "sed -n " + startingAndEnding + " " + fileName + proc = subprocess.Popen(shlex.split(command), stdout=subprocess.PIPE) + data = proc.stdout.read() else: - if (items.find(virtualHostName) > -1 and items.find(" map "+virtualHostName) > -1): - continue - if (items.find(virtualHostName) > -1 and (items.find("virtualHost") > -1 or items.find("virtualhost") > -1)): - check = 0 - if(check==1): - writeDataToFile.writelines(items) - if(items.find("}")>-1 and check == 0): - check = 1 - + end = numberOfTotalLines - ((page - 1) * 25) + start = end - 24 + if start <= 0: + start = 1 + startingAndEnding = "'" + str(start) + "," + str(end) + "p'" + command = "sed -n " + startingAndEnding + " " + fileName + proc = subprocess.Popen(shlex.split(command), stdout=subprocess.PIPE) + data = proc.stdout.read() + print data except BaseException, msg: - logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [Not able to remove virtual host configuration from main configuration file.]") - return 0 - - return 1 - - ## Utilities starts here onwards + logging.CyberCPLogFileWriter.writeToFile( + str(msg) + " [getAccessLogs]") + print "1,None" @staticmethod - def checkIfVirtualHostExists(virtualHostName): - if os.path.exists("/home/"+virtualHostName): - return 1 - return 0 - - @staticmethod - def changePHP(vhFile,phpVersion): - - # General Configurations tab - - finalphp = 0 - + def getErrorLogs(fileName, page): try: - data = open(vhFile, "r").readlines() - if phpVersion == "PHP 5.3": - finalphp = 53 - elif phpVersion == "PHP 5.4": - finalphp = 54 - elif phpVersion == "PHP 5.5": - finalphp = 55 - elif phpVersion == "PHP 5.6": - finalphp = 56 - elif phpVersion == "PHP 7.0": - finalphp = 70 - elif phpVersion == "PHP 7.1": - finalphp = 71 - elif phpVersion == "PHP 7.2": - finalphp = 72 + numberOfTotalLines = int(subprocess.check_output(["wc", "-l", fileName]).split(" ")[0]) - writeDataToFile = open(vhFile,"w") - - sockRandomPath = str(randint(1000, 9999)) - - address = " address UDS://tmp/lshttpd/" + sockRandomPath + ".sock\n" - path = " path /usr/local/lsws/lsphp" + str(finalphp) + "/bin/lsphp\n" - - for items in data: - if items.find("/usr/local/lsws/lsphp") > -1 and items.find("path") > -1: - writeDataToFile.writelines(path) + if numberOfTotalLines < 25: + data = subprocess.check_output(["cat", fileName]) + else: + if page == 1: + end = numberOfTotalLines + start = end - 24 + if start <= 0: + start = 1 + startingAndEnding = "'" + str(start) + "," + str(end) + "p'" + command = "sed -n " + startingAndEnding + " " + fileName + proc = subprocess.Popen(shlex.split(command), stdout=subprocess.PIPE) + data = proc.stdout.read() else: - writeDataToFile.writelines(items) + end = numberOfTotalLines - ((page - 1) * 25) + start = end - 24 + if start <= 0: + start = 1 + startingAndEnding = "'" + str(start) + "," + str(end) + "p'" + command = "sed -n " + startingAndEnding + " " + fileName + proc = subprocess.Popen(shlex.split(command), stdout=subprocess.PIPE) + data = proc.stdout.read() + print data + except BaseException, msg: + logging.CyberCPLogFileWriter.writeToFile( + str(msg) + " [getErrorLogs]") + print "1,None" - writeDataToFile.close() + @staticmethod + def saveVHostConfigs(fileName, tempPath): + try: + + vhost = open(fileName, "w") + + vhost.write(open(tempPath, "r").read()) + + vhost.close() + + if os.path.exists(tempPath): + os.remove(tempPath) installUtilities.installUtilities.reStartLiteSpeed() @@ -788,1145 +226,811 @@ class virtualHostUtilities: except BaseException, msg: logging.CyberCPLogFileWriter.writeToFile( - str(msg) + " [IO Error with per host config file [changePHP]]") - return [0,str(msg) + " [IO Error with per host config file [changePHP]]"] + str(msg) + " [saveVHostConfigs]") + print "0," + str(msg) @staticmethod - def getDiskUsage(path, totalAllowed): + def saveRewriteRules(virtualHost, fileName, tempPath): try: - totalUsageInMB = subprocess.check_output(["sudo","du", "-hs",path,"--block-size=1M"]).split()[0] + vhost.addRewriteRules(virtualHost, fileName) - percentage = float(100)/float(totalAllowed) + vhostFile = open(fileName, "w") - percentage = float(percentage) * float(totalUsageInMB) + vhostFile.write(open(tempPath, "r").read()) - data = [int(totalUsageInMB),int(percentage)] - return data - except BaseException,msg: - logging.CyberCPLogFileWriter.writeToFile(str(msg)+ " [getDiskUsage]") - return [int(0), int(0)] + vhostFile.close() - @staticmethod - def addRewriteRules(virtualHostName, fileName = None): + if os.path.exists(tempPath): + os.remove(tempPath) - try: - path = virtualHostUtilities.Server_root + "/conf/vhosts/" + virtualHostName + "/vhost.conf" + installUtilities.installUtilities.reStartLiteSpeed() - data = open(path, "r").readlines() - - if fileName == None: - dataToWritten = "rewriteFile /home/"+virtualHostName+"/public_html/.htaccess"+"\n" - else: - dataToWritten = "rewriteFile " + fileName + "\n" - - - - - ### Data if re-writes are not already enabled - - rewrite = "rewrite {\n" - enables = " enable 1\n" - rules =" rules << -1: - return 1 - return 0 + print "1,None" except BaseException, msg: logging.CyberCPLogFileWriter.writeToFile( - str(msg) + " [IO Error with per host config file [checkIfRewriteEnabled]]") - return 0 - return 1 + str(msg) + " [saveRewriteRules]") + print "0," + str(msg) @staticmethod - def suspendVirtualHost(virtualHostName): + def installWordPress(domainName, finalPath, virtualHostUser, dbName, dbUser, dbPassword): try: - confPath = virtualHostUtilities.Server_root + "/conf/vhosts/"+virtualHostName + FNULL = open(os.devnull, 'w') - command = "sudo mv " + confPath + " " + confPath+"-suspended" - subprocess.call(shlex.split(command)) + if not os.path.exists(finalPath): + os.makedirs(finalPath) - except BaseException, msg: - logging.CyberCPLogFileWriter.writeToFile( - str(msg) + " [suspendVirtualHost]") - return 0 - return 1 + ## checking for directories/files - @staticmethod - def UnsuspendVirtualHost(virtualHostName): - try: + dirFiles = os.listdir(finalPath) - confPath = virtualHostUtilities.Server_root + "/conf/vhosts/" + virtualHostName - - command = "sudo mv " + confPath + "-suspended" + " " + confPath - subprocess.call(shlex.split(command)) - - command = "chown -R " + "lsadm" + ":" + "lsadm" + " " + confPath - cmd = shlex.split(command) - subprocess.call(cmd) - - - except BaseException, msg: - logging.CyberCPLogFileWriter.writeToFile( - str(msg) + " [UnsuspendVirtualHost]") - return 0 - return 1 - - @staticmethod - def findDomainBW(domainName,totalAllowed): - try: - path = "/home/"+domainName+"/logs/"+domainName+".access_log" - - if not os.path.exists("/home/"+domainName+"/logs"): - print "0,0" - - bwmeta = "/home/" + domainName + "/logs/bwmeta" - - if not os.path.exists(path): - print "0,0" - - - - if os.path.exists(bwmeta): - try: - data = open(bwmeta).readlines() - currentUsed = int(data[0].strip("\n")) - - inMB = int(float(currentUsed)/(1024.0*1024.0)) - - percentage = float(100) / float(totalAllowed) - - percentage = float(percentage) * float(inMB) - except: - print "0,0" - - if percentage > 100.0: - percentage = 100 - - print str(inMB)+","+str(percentage) - else: - print "0,0" - - - except OSError, msg: - logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [findDomainBW]") - print "0,0" - except ValueError, msg: - logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [findDomainBW]") - print "0,0" - - @staticmethod - def permissionControl(path): - try: - command = 'sudo chown -R cyberpanel:cyberpanel ' + path - - cmd = shlex.split(command) - - res = subprocess.call(cmd) - - except BaseException, msg: - logging.CyberCPLogFileWriter.writeToFile(str(msg)) - - @staticmethod - def leaveControl(path): - try: - command = 'sudo chown -R root:root ' + path - - cmd = shlex.split(command) - - res = subprocess.call(cmd) - - except BaseException, msg: - logging.CyberCPLogFileWriter.writeToFile(str(msg)) - - @staticmethod - def checkIfAliasExists(aliasDomain): - try: - confPath = os.path.join(virtualHostUtilities.Server_root, "conf/httpd_config.conf") - data = open(confPath, 'r').readlines() - - for items in data: - if items.find(aliasDomain) > -1: - domains = filter(None, items.split(" ")) - for domain in domains: - if domain.strip(',').strip('\n') == aliasDomain: - return 1 - - return 0 - except BaseException, msg: - logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [checkIfAliasExists]") - return 1 - - @staticmethod - def checkIfSSLAliasExists(data, aliasDomain): - try: - for items in data: - if items.strip(',').strip('\n') == aliasDomain: - return 1 - return 0 - - except BaseException, msg: - logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [checkIfSSLAliasExists]") - return 1 - - @staticmethod - def createAliasSSLMap(confPath, masterDomain, aliasDomain): - try: - - data = open(confPath, 'r').readlines() - writeToFile = open(confPath, 'w') - sslCheck = 0 - - for items in data: - if (items.find("listener SSL") > -1): - sslCheck = 1 - if items.find(masterDomain) > -1 and items.find('map') > -1 and sslCheck == 1: - data = filter(None, items.split(" ")) - if data[1] == masterDomain: - if virtualHostUtilities.checkIfSSLAliasExists(data, aliasDomain) == 0: - writeToFile.writelines(items.rstrip('\n') + ", " + aliasDomain + "\n") - sslCheck = 0 - else: - writeToFile.writelines(items) + if len(dirFiles) == 1: + if dirFiles[0] == ".well-known": + pass else: - writeToFile.writelines(items) - - writeToFile.close() - installUtilities.installUtilities.reStartLiteSpeed() - - except BaseException, msg: - logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [createAliasSSLMap]") - - - -def createVirtualHost(virtualHostName, administratorEmail, phpVersion, virtualHostUser, numberOfSites, ssl, sslPath, dkimCheck, openBasedir): - try: - if virtualHostUtilities.checkIfVirtualHostExists(virtualHostName) == 1: - raise BaseException("Virtual Host Directory already exists!") - - if virtualHostUtilities.checkIfAliasExists(virtualHostName) == 1: - raise BaseException("This domain exists as Alias.") - - if dkimCheck == 1: - if mailUtilities.checkIfDKIMInstalled() == 0: - raise BaseException("OpenDKIM is not installed, install OpenDKIM from DKIM Manager.") - - retValues = mailUtilities.setupDKIM(virtualHostName) - if retValues[0] == 0: - raise BaseException(retValues[1]) - - retValues = virtualHostUtilities.createDirectoryForVirtualHost(virtualHostName, administratorEmail, virtualHostUser, phpVersion, openBasedir) - if retValues[0] == 0: - raise BaseException(retValues[1]) - - retValues = virtualHostUtilities.createConfigInMainVirtualHostFile(virtualHostName) - if retValues[0] == 0: - raise BaseException(retValues[1]) - - if ssl == 1: - installUtilities.installUtilities.reStartLiteSpeed() - retValues = sslUtilities.issueSSLForDomain(virtualHostName, administratorEmail, sslPath) - if retValues[0] == 0: - raise BaseException(retValues[1]) - else: - installUtilities.installUtilities.reStartLiteSpeed() - - if ssl == 0: - installUtilities.installUtilities.reStartLiteSpeed() - - virtualHostUtilities.finalizeVhostCreation(virtualHostName, virtualHostUser) - - print "1,None" - - except BaseException,msg: - virtualHostUtilities.deleteVirtualHostConfigurations(virtualHostName, numberOfSites) - logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [createVirtualHost]") - print "0,"+str(msg) - -def createDomain(masterDomain, virtualHostName, phpVersion, path,administratorEmail,virtualHostUser,restart,numberOfSites,ssl, dkimCheck, openBasedir): - try: - if virtualHostUtilities.checkIfVirtualHostExists(virtualHostName) == 1: - raise BaseException("Virtual Host Directory already exists!") - - - if virtualHostUtilities.checkIfAliasExists(virtualHostName) == 1: - raise BaseException("This domain exists as Alias.") - - - if dkimCheck == 1: - if mailUtilities.checkIfDKIMInstalled() == 0: - raise BaseException("OpenDKIM is not installed, install OpenDKIM from DKIM Manager.") - - retValues = mailUtilities.setupDKIM(virtualHostName) - if retValues[0] == 0: - raise BaseException(retValues[1]) - - FNULL = open(os.devnull, 'w') - - retValues = virtualHostUtilities.createDirectoryForDomain(masterDomain, virtualHostName, phpVersion, path,administratorEmail,virtualHostUser, openBasedir) - if retValues[0] == 0: - raise BaseException(retValues[1]) - - retValues = virtualHostUtilities.createConfigInMainDomainHostFile(virtualHostName, masterDomain) - - if retValues[0] == 0: - raise BaseException(retValues[1]) - - ## Now restart litespeed after initial configurations are done - - - if ssl == 1: - installUtilities.installUtilities.reStartLiteSpeed() - retValues = sslUtilities.issueSSLForDomain(virtualHostName, administratorEmail, path) - installUtilities.installUtilities.reStartLiteSpeed() - if retValues[0] == 0: - raise BaseException(retValues[1]) - - - ## Final Restart - if ssl == 0: - installUtilities.installUtilities.reStartLiteSpeed() - virtualHostUtilities.finalizeDomainCreation(virtualHostUser, path) - - print "1,None" - - except BaseException,msg: - virtualHostUtilities.deleteVirtualHostConfigurations(virtualHostName, numberOfSites) - logging.CyberCPLogFileWriter.writeToFile( - str(msg) + " [createDomain]") - print "0,"+str(msg) - -def issueSSL(virtualHost,path,adminEmail): - try: - - FNULL = open(os.devnull, 'w') - - retValues = sslUtilities.issueSSLForDomain(virtualHost, adminEmail, path) - - if retValues[0] == 0: - print "0," + str(retValues[1]) - return - - installUtilities.installUtilities.reStartLiteSpeed() - - vhostPath = virtualHostUtilities.Server_root + "/conf/vhosts" - command = "chown -R " + "lsadm" + ":" + "lsadm" + " " + vhostPath - cmd = shlex.split(command) - subprocess.call(cmd, stdout=FNULL, stderr=subprocess.STDOUT) - - print "1,None" - return - - except BaseException,msg: - logging.CyberCPLogFileWriter.writeToFile( - str(msg) + " [issueSSL]") - print "0,"+str(msg) - -def getAccessLogs(fileName,page): - try: - - numberOfTotalLines = int(subprocess.check_output(["wc", "-l", fileName]).split(" ")[0]) - - if numberOfTotalLines < 25: - data = subprocess.check_output(["cat", fileName]) - else: - if page == 1: - end = numberOfTotalLines - start = end - 24 - if start <= 0: - start = 1 - startingAndEnding = "'" + str(start) + "," + str(end) + "p'" - command = "sed -n " + startingAndEnding + " " + fileName - proc = subprocess.Popen(shlex.split(command), stdout=subprocess.PIPE) - data = proc.stdout.read() - else: - end = numberOfTotalLines - ((page - 1) * 25) - start = end - 24 - if start <= 0: - start = 1 - startingAndEnding = "'" + str(start) + "," + str(end) + "p'" - command = "sed -n " + startingAndEnding + " " + fileName - proc = subprocess.Popen(shlex.split(command), stdout=subprocess.PIPE) - data = proc.stdout.read() - print data - except BaseException,msg: - logging.CyberCPLogFileWriter.writeToFile( - str(msg) + " [getAccessLogs]") - print "1,None" - -def getErrorLogs(fileName,page): - try: - - numberOfTotalLines = int(subprocess.check_output(["wc", "-l", fileName]).split(" ")[0]) - - if numberOfTotalLines < 25: - data = subprocess.check_output(["cat", fileName]) - else: - if page == 1: - end = numberOfTotalLines - start = end - 24 - if start <= 0: - start = 1 - startingAndEnding = "'" + str(start) + "," + str(end) + "p'" - command = "sed -n " + startingAndEnding + " " + fileName - proc = subprocess.Popen(shlex.split(command), stdout=subprocess.PIPE) - data = proc.stdout.read() - else: - end = numberOfTotalLines - ((page - 1) * 25) - start = end - 24 - if start <= 0: - start = 1 - startingAndEnding = "'" + str(start) + "," + str(end) + "p'" - command = "sed -n " + startingAndEnding + " " + fileName - proc = subprocess.Popen(shlex.split(command), stdout=subprocess.PIPE) - data = proc.stdout.read() - print data - except BaseException,msg: - logging.CyberCPLogFileWriter.writeToFile( - str(msg) + " [getErrorLogs]") - print "1,None" - -def saveVHostConfigs(fileName,tempPath): - try: - - vhost = open(fileName, "w") - - vhost.write(open(tempPath,"r").read()) - - vhost.close() - - if os.path.exists(tempPath): - os.remove(tempPath) - - installUtilities.installUtilities.reStartLiteSpeed() - - print "1,None" - - except BaseException,msg: - logging.CyberCPLogFileWriter.writeToFile( - str(msg) + " [saveVHostConfigs]") - print "0,"+str(msg) - -def saveRewriteRules(virtualHost,fileName,tempPath): - try: - - virtualHostUtilities.addRewriteRules(virtualHost, fileName) - - vhost = open(fileName, "w") - - vhost.write(open(tempPath,"r").read()) - - vhost.close() - - if os.path.exists(tempPath): - os.remove(tempPath) - - installUtilities.installUtilities.reStartLiteSpeed() - - print "1,None" - - except BaseException,msg: - logging.CyberCPLogFileWriter.writeToFile( - str(msg) + " [saveRewriteRules]") - print "0,"+str(msg) - -def installWordPress(domainName,finalPath,virtualHostUser,dbName,dbUser,dbPassword): - try: - - FNULL = open(os.devnull, 'w') - - if not os.path.exists(finalPath): - os.makedirs(finalPath) - - ## checking for directories/files - - dirFiles = os.listdir(finalPath) - - if len(dirFiles) == 1: - if dirFiles[0] == ".well-known": + print "0,Target directory should be empty before installation, otherwise data loss could occur." + return + elif len(dirFiles) == 0: pass else: print "0,Target directory should be empty before installation, otherwise data loss could occur." return - elif len(dirFiles) == 0: - pass - else: - print "0,Target directory should be empty before installation, otherwise data loss could occur." - return + + ## Get wordpress - ## Get wordpress + if not os.path.exists("latest.tar.gz"): + command = 'wget --no-check-certificate http://wordpress.org/latest.tar.gz -O latest.tar.gz' + cmd = shlex.split(command) + res = subprocess.call(cmd, stdout=FNULL, stderr=subprocess.STDOUT) - - if not os.path.exists("latest.tar.gz"): - command = 'wget --no-check-certificate http://wordpress.org/latest.tar.gz -O latest.tar.gz' - cmd = shlex.split(command) - res = subprocess.call(cmd,stdout=FNULL, stderr=subprocess.STDOUT) - - command = 'tar -xzvf latest.tar.gz -C ' + finalPath - - cmd = shlex.split(command) - - res = subprocess.call(cmd,stdout=FNULL, stderr=subprocess.STDOUT) - - ## Get plugin - - if not os.path.exists("litespeed-cache.1.1.5.1.zip"): - command = 'wget --no-check-certificate https://downloads.wordpress.org/plugin/litespeed-cache.1.1.5.1.zip' + command = 'tar -xzvf latest.tar.gz -C ' + finalPath cmd = shlex.split(command) - res = subprocess.call(cmd,stdout=FNULL, stderr=subprocess.STDOUT) + res = subprocess.call(cmd, stdout=FNULL, stderr=subprocess.STDOUT) - command = 'unzip litespeed-cache.1.1.5.1.zip -d ' + finalPath + ## Get plugin - cmd = shlex.split(command) + if not os.path.exists("litespeed-cache.1.1.5.1.zip"): + command = 'wget --no-check-certificate https://downloads.wordpress.org/plugin/litespeed-cache.1.1.5.1.zip' - res = subprocess.call(cmd,stdout=FNULL, stderr=subprocess.STDOUT) + cmd = shlex.split(command) - root = finalPath + res = subprocess.call(cmd, stdout=FNULL, stderr=subprocess.STDOUT) - for filename in listdir(join(root, 'wordpress')): - move(join(root, 'wordpress', filename), join(root, filename)) + command = 'unzip litespeed-cache.1.1.5.1.zip -d ' + finalPath - rmdir(root + "wordpress") - - shutil.copytree(finalPath + "litespeed-cache", finalPath + "wp-content/plugins/litespeed-cache") - shutil.rmtree(finalPath + "litespeed-cache") - - - - ## edit config file - - wpconfigfile = finalPath + "wp-config-sample.php" - - data = open(wpconfigfile, "r").readlines() - - writeDataToFile = open(wpconfigfile, "w") - - defDBName = "define('DB_NAME', '" + dbName + "');" + "\n" - defDBUser = "define('DB_USER', '" + dbUser + "');" + "\n" - defDBPassword = "define('DB_PASSWORD', '" + dbPassword + "');" + "\n" - - for items in data: - if items.find("DB_NAME") > -1: - if items.find("database_name_here") > -1: - writeDataToFile.writelines(defDBName) - elif items.find("DB_USER") > -1: - if items.find("username_here") > -1: - writeDataToFile.writelines(defDBUser) - elif items.find("DB_PASSWORD") > -1: - writeDataToFile.writelines(defDBPassword) - else: - writeDataToFile.writelines(items) - - writeDataToFile.close() - - os.rename(wpconfigfile, finalPath + 'wp-config.php') - - command = "chown -R "+virtualHostUser+":"+virtualHostUser+" " + "/home/" + domainName + "/public_html/" - - cmd = shlex.split(command) - - res = subprocess.call(cmd,stdout=FNULL, stderr=subprocess.STDOUT) - - virtualHostUtilities.addRewriteRules(domainName) - - installUtilities.installUtilities.reStartLiteSpeed() - - print "1,None" - - - except BaseException, msg: - # remove the downloaded files - try: - - shutil.rmtree(finalPath) - except: - logging.CyberCPLogFileWriter.writeToFile("shutil.rmtree(finalPath)") - - homeDir = "/home/" + domainName + "/public_html" - - if not os.path.exists(homeDir): - FNULL = open(os.devnull, 'w') - os.mkdir(homeDir) - command = "chown -R "+virtualHostUser+":"+virtualHostUser+" " + homeDir cmd = shlex.split(command) - res = subprocess.call(cmd,stdout=FNULL, stderr=subprocess.STDOUT) - print "0," + str(msg) - return + res = subprocess.call(cmd, stdout=FNULL, stderr=subprocess.STDOUT) -def installJoomla(domainName,finalPath,virtualHostUser,dbName,dbUser,dbPassword,username,password,prefix,sitename): + root = finalPath - try: - FNULL = open(os.devnull, 'w') + for filename in listdir(join(root, 'wordpress')): + move(join(root, 'wordpress', filename), join(root, filename)) + rmdir(root + "wordpress") - if not os.path.exists(finalPath): - os.makedirs(finalPath) + shutil.copytree(finalPath + "litespeed-cache", finalPath + "wp-content/plugins/litespeed-cache") + shutil.rmtree(finalPath + "litespeed-cache") - ## checking for directories/files + ## edit config file - dirFiles = os.listdir(finalPath) + wpconfigfile = finalPath + "wp-config-sample.php" - if len(dirFiles) == 1: - if dirFiles[0] == ".well-known": - pass - else: - print "0,Target directory should be empty before installation, otherwise data loss could occur." - return - elif len(dirFiles) == 0: - pass - else: - print "0,Target directory should be empty before installation, otherwise data loss could occur." - return + data = open(wpconfigfile, "r").readlines() - ## Get Joomla + writeDataToFile = open(wpconfigfile, "w") - os.chdir(finalPath) + defDBName = "define('DB_NAME', '" + dbName + "');" + "\n" + defDBUser = "define('DB_USER', '" + dbUser + "');" + "\n" + defDBPassword = "define('DB_PASSWORD', '" + dbPassword + "');" + "\n" - - if not os.path.exists("staging.zip"): - command = 'wget --no-check-certificate https://github.com/joomla/joomla-cms/archive/staging.zip -P ' + finalPath - cmd = shlex.split(command) - res = subprocess.call(cmd,stdout=FNULL, stderr=subprocess.STDOUT) - else: - print "0,File already exists" - return - - command = 'unzip '+finalPath+'staging.zip -d ' + finalPath - - cmd = shlex.split(command) - - res = subprocess.call(cmd,stdout=FNULL, stderr=subprocess.STDOUT) - - os.remove(finalPath+'staging.zip') - - command = 'cp -r '+finalPath+'joomla-cms-staging/. ' + finalPath - cmd = shlex.split(command) - res = subprocess.call(cmd,stdout=FNULL, stderr=subprocess.STDOUT) - - shutil.rmtree(finalPath + "joomla-cms-staging") - os.rename(finalPath+"installation/configuration.php-dist", finalPath+"configuration.php") - os.rename(finalPath+"robots.txt.dist", finalPath+"robots.txt") - os.rename(finalPath+"htaccess.txt", finalPath+".htaccess") - - ## edit config file - - configfile = finalPath + "configuration.php" - - data = open(configfile, "r").readlines() - - writeDataToFile = open(configfile, "w") - - secret = randomPassword.generate_pass() - - defDBName = " public $user = '"+dbName+"';" + "\n" - defDBUser = " public $db = '"+dbUser+"';" + "\n" - defDBPassword = " public $password = '"+dbPassword+"';" + "\n" - secretKey = " public $secret = '"+secret+"';" + "\n" - logPath = " public $log_path = '"+finalPath+"administrator/logs';" + "\n" - tmpPath = " public $tmp_path = '"+finalPath+"administrator/tmp';" + "\n" - dbprefix = " public $dbprefix = '"+prefix+"';" + "\n" - sitename = " public $sitename = '"+sitename+"';" + "\n" - - for items in data: - if items.find("public $user ") > -1: - writeDataToFile.writelines(defDBUser) - elif items.find("public $password ") > -1: - writeDataToFile.writelines(defDBPassword) - elif items.find("public $db ") > -1: - writeDataToFile.writelines(defDBName) - elif items.find("public $log_path ") > -1: - writeDataToFile.writelines(logPath) - elif items.find("public $tmp_path ") > -1: - writeDataToFile.writelines(tmpPath) - elif items.find("public $secret ") > -1: - writeDataToFile.writelines(secretKey) - elif items.find("public $dbprefix ") > -1: - writeDataToFile.writelines(dbprefix) - elif items.find("public $sitename ") > -1: - writeDataToFile.writelines(sitename) - elif items.find("/*") > -1: - pass - elif items.find(" *") > -1: - pass - else: - writeDataToFile.writelines(items) - - writeDataToFile.close() - - #Rename SQL db prefix - - f1 = open(finalPath+'installation/sql/mysql/joomla.sql', 'r') - f2 = open('installation/sql/mysql/joomlaInstall.sql', 'w') - for line in f1: - f2.write(line.replace('#__', prefix)) - f1.close() - f2.close() - - #Restore SQL - proc = subprocess.Popen(["mysql", "--user=%s" % dbUser, "--password=%s" % dbPassword, dbName],stdin=subprocess.PIPE,stdout=subprocess.PIPE) - - usercreation = """INSERT INTO `%susers` - (`name`, `username`, `password`, `params`) - VALUES ('Administrator', '%s', - '%s', ''); - INSERT INTO `%suser_usergroup_map` (`user_id`,`group_id`) - VALUES (LAST_INSERT_ID(),'8');""" % (prefix, username, password, prefix) - - out, err = proc.communicate(file(finalPath + 'installation/sql/mysql/joomlaInstall.sql').read() + "\n" + usercreation) - - shutil.rmtree(finalPath + "installation") - - htaccessCache = """ - -RewriteEngine on -CacheLookup on -CacheDisable public / -RewriteCond %{REQUEST_METHOD} ^HEAD|GET$ -RewriteCond %{ORG_REQ_URI} !/administrator -RewriteRule .* - [E=cache-control:max-age=120] - - """ - - f=open(finalPath + '.htaccess', "a+") - f.write(htaccessCache) - f.close() - - command = "chown -R "+virtualHostUser+":"+virtualHostUser+" " + "/home/" + domainName + "/public_html/" - - cmd = shlex.split(command) - - res = subprocess.call(cmd,stdout=FNULL, stderr=subprocess.STDOUT) - - virtualHostUtilities.addRewriteRules(domainName) - - installUtilities.installUtilities.reStartLiteSpeed() - - print "1,None" - return - - except BaseException, msg: - # remove the downloaded files - try: - shutil.rmtree(finalPath) - except: - logging.CyberCPLogFileWriter.writeToFile("shutil.rmtree(finalPath)") - - homeDir = "/home/" + domainName + "/public_html" - - if not os.path.exists(homeDir): - FNULL = open(os.devnull, 'w') - os.mkdir(homeDir) - command = "chown -R "+virtualHostUser+":"+virtualHostUser+" " + homeDir - cmd = shlex.split(command) - res = subprocess.call(cmd,stdout=FNULL, stderr=subprocess.STDOUT) - return - -def issueSSLForHostName(virtualHost,path): - try: - - FNULL = open(os.devnull, 'w') - - pathToStoreSSL = virtualHostUtilities.Server_root + "/conf/vhosts/" + "SSL-" + virtualHost - - pathToStoreSSLPrivKey = pathToStoreSSL + "/privkey.pem" - pathToStoreSSLFullChain = pathToStoreSSL + "/fullchain.pem" - - destPrivKey = "/usr/local/lscp/key.pem" - destCert = "/usr/local/lscp/cert.pem" - - ## removing old certs for lscpd - if os.path.exists(destPrivKey): - os.remove(destPrivKey) - if os.path.exists(destCert): - os.remove(destCert) - - letsEncryptPath = "/etc/letsencrypt/live/" + virtualHost - - if os.path.exists(letsEncryptPath) and os.path.exists(pathToStoreSSL): - pass - else: - adminEmail = "email@" + virtualHost - - retValues = sslUtilities.issueSSLForDomain(virtualHost, adminEmail, path) - - if retValues[0] == 0: - print "0," + str(retValues[1]) - return - - shutil.copy(pathToStoreSSLPrivKey, destPrivKey) - shutil.copy(pathToStoreSSLFullChain, destCert) - - command = 'systemctl restart lscpd' - cmd = shlex.split(command) - subprocess.call(cmd) - - vhostPath = virtualHostUtilities.Server_root + "/conf/vhosts" - command = "chown -R " + "lsadm" + ":" + "lsadm" + " " + vhostPath - cmd = shlex.split(command) - subprocess.call(cmd, stdout=FNULL, stderr=subprocess.STDOUT) - - print "1,None" - - - except BaseException,msg: - logging.CyberCPLogFileWriter.writeToFile( - str(msg) + " [issueSSLForHostName]") - print "0,"+str(msg) - -def issueSSLForMailServer(virtualHost,path): - try: - - FNULL = open(os.devnull, 'w') - - pathToStoreSSL = virtualHostUtilities.Server_root + "/conf/vhosts/" + "SSL-" + virtualHost - - srcPrivKey = pathToStoreSSL + "/privkey.pem" - srcFullChain = pathToStoreSSL + "/fullchain.pem" - - - letsEncryptPath = "/etc/letsencrypt/live/" + virtualHost - - if os.path.exists(letsEncryptPath) and os.path.exists(pathToStoreSSL): - pass - else: - adminEmail = "email@" + virtualHost - - retValues = sslUtilities.issueSSLForDomain(virtualHost, adminEmail, path) - - if retValues[0] == 0: - print "0," + str(retValues[1]) - return - - - ## MailServer specific functions - - if os.path.exists("/etc/postfix/cert.pem"): - os.remove("/etc/postfix/cert.pem") - - if os.path.exists("/etc/postfix/key.pem"): - os.remove("/etc/postfix/key.pem") - - if os.path.exists("/etc/pki/dovecot/private/dovecot.pem"): - os.remove("/etc/pki/dovecot/private/dovecot.pem") - - if os.path.exists("/etc/pki/dovecot/certs/dovecot.pem"): - os.remove("/etc/pki/dovecot/certs/dovecot.pem") - - if os.path.exists("/etc/dovecot/key.pem"): - os.remove("/etc/dovecot/key.pem") - - if os.path.exists("/etc/dovecot/cert.pem"): - os.remove("/etc/dovecot/cert.pem") - - - ## Postfix - - shutil.copy(srcPrivKey, "/etc/postfix/key.pem") - shutil.copy(srcFullChain, "/etc/postfix/cert.pem") - - ## Dovecot - - shutil.copy(srcPrivKey, "/etc/pki/dovecot/private/dovecot.pem") - shutil.copy(srcFullChain, "/etc/pki/dovecot/certs/dovecot.pem") - - ## Dovecot 2ND - - shutil.copy(srcPrivKey, "/etc/dovecot/key.pem") - shutil.copy(srcFullChain, "/etc/dovecot/cert.pem") - - - vhostPath = virtualHostUtilities.Server_root + "/conf/vhosts" - command = "chown -R " + "lsadm" + ":" + "lsadm" + " " + vhostPath - cmd = shlex.split(command) - subprocess.call(cmd, stdout=FNULL, stderr=subprocess.STDOUT) - - ## Update postmaster address dovecot - - filePath = "/etc/dovecot/dovecot.conf" - - data = open(filePath,'r').readlines() - - writeFile = open(filePath,'w') - - for items in data: - if items.find('postmaster_address') > -1: - writeFile.writelines(' postmaster_address = postmaster@' + virtualHost + '\n') - else: - writeFile.writelines(items) - - writeFile.close() - - ## Update myhostname address postfix - - filePath = "/etc/postfix/main.cf" - - data = open(filePath, 'r').readlines() - - writeFile = open(filePath, 'w') - - for items in data: - if items.find('myhostname') > -1: - writeFile.writelines('myhostname = ' + virtualHost + '\n') - else: - writeFile.writelines(items) - - writeFile.close() - - p = Process(target=mailUtilities.restartServices, args=('restart',)) - p.start() - - print "1,None" - - except BaseException,msg: - logging.CyberCPLogFileWriter.writeToFile( - str(msg) + " [issueSSLForHostName]") - print "0,"+str(msg) - -def createAlias(masterDomain,aliasDomain,ssl,sslPath, administratorEmail): - try: - - if virtualHostUtilities.checkIfAliasExists(aliasDomain) == 0: - - confPath = os.path.join(virtualHostUtilities.Server_root, "conf/httpd_config.conf") - data = open(confPath,'r').readlines() - writeToFile = open(confPath,'w') - listenerTrueCheck = 0 - for items in data: - if items.find("listener") > -1 and items.find("Default") > -1: - listenerTrueCheck = 1 - if items.find(masterDomain) > -1 and items.find('map') > -1 and listenerTrueCheck == 1: - data = filter(None, items.split(" ")) - if data[1] == masterDomain: - writeToFile.writelines(items.rstrip('\n') + ", " + aliasDomain + "\n") - listenerTrueCheck = 0 + if items.find("DB_NAME") > -1: + if items.find("database_name_here") > -1: + writeDataToFile.writelines(defDBName) + elif items.find("DB_USER") > -1: + if items.find("username_here") > -1: + writeDataToFile.writelines(defDBUser) + elif items.find("DB_PASSWORD") > -1: + writeDataToFile.writelines(defDBPassword) else: - writeToFile.writelines(items) - - writeToFile.close() - + writeDataToFile.writelines(items) + + writeDataToFile.close() + + os.rename(wpconfigfile, finalPath + 'wp-config.php') + + command = "chown -R " + virtualHostUser + ":" + virtualHostUser + " " + "/home/" + domainName + "/public_html/" + + cmd = shlex.split(command) + + res = subprocess.call(cmd, stdout=FNULL, stderr=subprocess.STDOUT) + + vhost.addRewriteRules(domainName) + installUtilities.installUtilities.reStartLiteSpeed() - else: - print "0, This domain already exists as vHost or Alias." - return + + print "1,None" - if ssl == 1: - retValues = sslUtilities.issueSSLForDomain(masterDomain, administratorEmail, sslPath, aliasDomain) - if retValues[0] == 0: - print "0," + str(retValues[1]) - return - else: - virtualHostUtilities.createAliasSSLMap(confPath,masterDomain, aliasDomain) - - print "1,None" - - except BaseException,msg: - - logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [createAlias]") - print "0,"+str(msg) - -def issueAliasSSL(masterDomain, aliasDomain, sslPath, administratorEmail): + except BaseException, msg: + # remove the downloaded files try: - confPath = os.path.join(virtualHostUtilities.Server_root, "conf/httpd_config.conf") + shutil.rmtree(finalPath) + except: + logging.CyberCPLogFileWriter.writeToFile("shutil.rmtree(finalPath)") - retValues = sslUtilities.issueSSLForDomain(masterDomain, administratorEmail, sslPath, aliasDomain) + homeDir = "/home/" + domainName + "/public_html" + + if not os.path.exists(homeDir): + FNULL = open(os.devnull, 'w') + os.mkdir(homeDir) + command = "chown -R " + virtualHostUser + ":" + virtualHostUser + " " + homeDir + cmd = shlex.split(command) + res = subprocess.call(cmd, stdout=FNULL, stderr=subprocess.STDOUT) + + print "0," + str(msg) + return + + @staticmethod + def installJoomla(domainName, finalPath, virtualHostUser, dbName, dbUser, dbPassword, username, password, prefix, + sitename): + + try: + FNULL = open(os.devnull, 'w') + + if not os.path.exists(finalPath): + os.makedirs(finalPath) + + ## checking for directories/files + + dirFiles = os.listdir(finalPath) + + if len(dirFiles) == 1: + if dirFiles[0] == ".well-known": + pass + else: + print "0,Target directory should be empty before installation, otherwise data loss could occur." + return + elif len(dirFiles) == 0: + pass + else: + print "0,Target directory should be empty before installation, otherwise data loss could occur." + return + + ## Get Joomla + + os.chdir(finalPath) + + if not os.path.exists("staging.zip"): + command = 'wget --no-check-certificate https://github.com/joomla/joomla-cms/archive/staging.zip -P ' + finalPath + cmd = shlex.split(command) + res = subprocess.call(cmd, stdout=FNULL, stderr=subprocess.STDOUT) + else: + print "0,File already exists" + return + + command = 'unzip ' + finalPath + 'staging.zip -d ' + finalPath + + cmd = shlex.split(command) + + res = subprocess.call(cmd, stdout=FNULL, stderr=subprocess.STDOUT) + + os.remove(finalPath + 'staging.zip') + + command = 'cp -r ' + finalPath + 'joomla-cms-staging/. ' + finalPath + cmd = shlex.split(command) + res = subprocess.call(cmd, stdout=FNULL, stderr=subprocess.STDOUT) + + shutil.rmtree(finalPath + "joomla-cms-staging") + os.rename(finalPath + "installation/configuration.php-dist", finalPath + "configuration.php") + os.rename(finalPath + "robots.txt.dist", finalPath + "robots.txt") + os.rename(finalPath + "htaccess.txt", finalPath + ".htaccess") + + ## edit config file + + configfile = finalPath + "configuration.php" + + data = open(configfile, "r").readlines() + + writeDataToFile = open(configfile, "w") + + secret = randomPassword.generate_pass() + + defDBName = " public $user = '" + dbName + "';" + "\n" + defDBUser = " public $db = '" + dbUser + "';" + "\n" + defDBPassword = " public $password = '" + dbPassword + "';" + "\n" + secretKey = " public $secret = '" + secret + "';" + "\n" + logPath = " public $log_path = '" + finalPath + "administrator/logs';" + "\n" + tmpPath = " public $tmp_path = '" + finalPath + "administrator/tmp';" + "\n" + dbprefix = " public $dbprefix = '" + prefix + "';" + "\n" + sitename = " public $sitename = '" + sitename + "';" + "\n" + + for items in data: + if items.find("public $user ") > -1: + writeDataToFile.writelines(defDBUser) + elif items.find("public $password ") > -1: + writeDataToFile.writelines(defDBPassword) + elif items.find("public $db ") > -1: + writeDataToFile.writelines(defDBName) + elif items.find("public $log_path ") > -1: + writeDataToFile.writelines(logPath) + elif items.find("public $tmp_path ") > -1: + writeDataToFile.writelines(tmpPath) + elif items.find("public $secret ") > -1: + writeDataToFile.writelines(secretKey) + elif items.find("public $dbprefix ") > -1: + writeDataToFile.writelines(dbprefix) + elif items.find("public $sitename ") > -1: + writeDataToFile.writelines(sitename) + elif items.find("/*") > -1: + pass + elif items.find(" *") > -1: + pass + else: + writeDataToFile.writelines(items) + + writeDataToFile.close() + + # Rename SQL db prefix + + f1 = open(finalPath + 'installation/sql/mysql/joomla.sql', 'r') + f2 = open('installation/sql/mysql/joomlaInstall.sql', 'w') + for line in f1: + f2.write(line.replace('#__', prefix)) + f1.close() + f2.close() + + # Restore SQL + proc = subprocess.Popen(["mysql", "--user=%s" % dbUser, "--password=%s" % dbPassword, dbName], + stdin=subprocess.PIPE, stdout=subprocess.PIPE) + + usercreation = """INSERT INTO `%susers` + (`name`, `username`, `password`, `params`) + VALUES ('Administrator', '%s', + '%s', ''); + INSERT INTO `%suser_usergroup_map` (`user_id`,`group_id`) + VALUES (LAST_INSERT_ID(),'8');""" % (prefix, username, password, prefix) + + out, err = proc.communicate( + file(finalPath + 'installation/sql/mysql/joomlaInstall.sql').read() + "\n" + usercreation) + + shutil.rmtree(finalPath + "installation") + + htaccessCache = """ + + RewriteEngine on + CacheLookup on + CacheDisable public / + RewriteCond %{REQUEST_METHOD} ^HEAD|GET$ + RewriteCond %{ORG_REQ_URI} !/administrator + RewriteRule .* - [E=cache-control:max-age=120] + + """ + + f = open(finalPath + '.htaccess', "a+") + f.write(htaccessCache) + f.close() + + command = "chown -R " + virtualHostUser + ":" + virtualHostUser + " " + "/home/" + domainName + "/public_html/" + + cmd = shlex.split(command) + + res = subprocess.call(cmd, stdout=FNULL, stderr=subprocess.STDOUT) + + vhost.addRewriteRules(domainName) + + installUtilities.installUtilities.reStartLiteSpeed() + + print "1,None" + return + + except BaseException, msg: + # remove the downloaded files + try: + shutil.rmtree(finalPath) + except: + logging.CyberCPLogFileWriter.writeToFile("shutil.rmtree(finalPath)") + + homeDir = "/home/" + domainName + "/public_html" + + if not os.path.exists(homeDir): + FNULL = open(os.devnull, 'w') + os.mkdir(homeDir) + command = "chown -R " + virtualHostUser + ":" + virtualHostUser + " " + homeDir + cmd = shlex.split(command) + res = subprocess.call(cmd, stdout=FNULL, stderr=subprocess.STDOUT) + return + + @staticmethod + def issueSSLForHostName(virtualHost, path): + try: + + FNULL = open(os.devnull, 'w') + + pathToStoreSSL = virtualHostUtilities.Server_root + "/conf/vhosts/" + "SSL-" + virtualHost + + pathToStoreSSLPrivKey = pathToStoreSSL + "/privkey.pem" + pathToStoreSSLFullChain = pathToStoreSSL + "/fullchain.pem" + + destPrivKey = "/usr/local/lscp/key.pem" + destCert = "/usr/local/lscp/cert.pem" + + ## removing old certs for lscpd + if os.path.exists(destPrivKey): + os.remove(destPrivKey) + if os.path.exists(destCert): + os.remove(destCert) + + letsEncryptPath = "/etc/letsencrypt/live/" + virtualHost + + if os.path.exists(letsEncryptPath) and os.path.exists(pathToStoreSSL): + pass + else: + adminEmail = "email@" + virtualHost + + retValues = sslUtilities.issueSSLForDomain(virtualHost, adminEmail, path) if retValues[0] == 0: print "0," + str(retValues[1]) return - else: - virtualHostUtilities.createAliasSSLMap(confPath, masterDomain, aliasDomain) - print "1,None" + shutil.copy(pathToStoreSSLPrivKey, destPrivKey) + shutil.copy(pathToStoreSSLFullChain, destCert) + + command = 'systemctl restart lscpd' + cmd = shlex.split(command) + subprocess.call(cmd) + + vhostPath = virtualHostUtilities.Server_root + "/conf/vhosts" + command = "chown -R " + "lsadm" + ":" + "lsadm" + " " + vhostPath + cmd = shlex.split(command) + subprocess.call(cmd, stdout=FNULL, stderr=subprocess.STDOUT) + + print "1,None" - except BaseException, msg: + except BaseException, msg: + logging.CyberCPLogFileWriter.writeToFile( + str(msg) + " [issueSSLForHostName]") + print "0," + str(msg) - logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [issueAliasSSL]") - print "0," + str(msg) + @staticmethod + def issueSSLForMailServer(virtualHost, path): + try: + FNULL = open(os.devnull, 'w') -def deleteAlias(masterDomain, aliasDomain): - try: + pathToStoreSSL = virtualHostUtilities.Server_root + "/conf/vhosts/" + "SSL-" + virtualHost - confPath = os.path.join(virtualHostUtilities.Server_root, "conf/httpd_config.conf") + srcPrivKey = pathToStoreSSL + "/privkey.pem" + srcFullChain = pathToStoreSSL + "/fullchain.pem" - data = open(confPath, 'r').readlines() - writeToFile = open(confPath, 'w') - aliases = [] - - for items in data: - if items.find(masterDomain) > -1 and items.find('map') > -1: - data = filter(None, items.split(" ")) - if data[1] == masterDomain: - length = len(data) - for i in range(3, length): - currentAlias = data[i].rstrip(',').strip('\n') - if currentAlias != aliasDomain: - aliases.append(currentAlias) - - aliasString = "" - - for alias in aliases: - aliasString = ", " + alias - - writeToFile.writelines(' map ' + masterDomain + " " + masterDomain + aliasString + "\n") - aliases = [] - aliasString = "" - else: - writeToFile.writelines(items) + letsEncryptPath = "/etc/letsencrypt/live/" + virtualHost + if os.path.exists(letsEncryptPath) and os.path.exists(pathToStoreSSL): + pass else: - writeToFile.writelines(items) + adminEmail = "email@" + virtualHost - writeToFile.close() - installUtilities.installUtilities.reStartLiteSpeed() + retValues = sslUtilities.issueSSLForDomain(virtualHost, adminEmail, path) - print "1,None" + if retValues[0] == 0: + print "0," + str(retValues[1]) + return + ## MailServer specific functions - except BaseException, msg: - logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [deleteAlias]") - print "0," + str(msg) + if os.path.exists("/etc/postfix/cert.pem"): + os.remove("/etc/postfix/cert.pem") -def changeOpenBasedir(domainName, openBasedirValue): - try: + if os.path.exists("/etc/postfix/key.pem"): + os.remove("/etc/postfix/key.pem") - confPath = virtualHostUtilities.Server_root + "/conf/vhosts/" + domainName - completePathToConfigFile = confPath + "/vhost.conf" + if os.path.exists("/etc/pki/dovecot/private/dovecot.pem"): + os.remove("/etc/pki/dovecot/private/dovecot.pem") + + if os.path.exists("/etc/pki/dovecot/certs/dovecot.pem"): + os.remove("/etc/pki/dovecot/certs/dovecot.pem") + + if os.path.exists("/etc/dovecot/key.pem"): + os.remove("/etc/dovecot/key.pem") + + if os.path.exists("/etc/dovecot/cert.pem"): + os.remove("/etc/dovecot/cert.pem") + + ## Postfix + + shutil.copy(srcPrivKey, "/etc/postfix/key.pem") + shutil.copy(srcFullChain, "/etc/postfix/cert.pem") + + ## Dovecot + + shutil.copy(srcPrivKey, "/etc/pki/dovecot/private/dovecot.pem") + shutil.copy(srcFullChain, "/etc/pki/dovecot/certs/dovecot.pem") + + ## Dovecot 2ND + + shutil.copy(srcPrivKey, "/etc/dovecot/key.pem") + shutil.copy(srcFullChain, "/etc/dovecot/cert.pem") + + vhostPath = virtualHostUtilities.Server_root + "/conf/vhosts" + command = "chown -R " + "lsadm" + ":" + "lsadm" + " " + vhostPath + cmd = shlex.split(command) + subprocess.call(cmd, stdout=FNULL, stderr=subprocess.STDOUT) + + ## Update postmaster address dovecot + + filePath = "/etc/dovecot/dovecot.conf" + + data = open(filePath, 'r').readlines() + + writeFile = open(filePath, 'w') - data = open(completePathToConfigFile, 'r').readlines() - skip = 0 - if openBasedirValue == 'Disable': - writeToFile = open(completePathToConfigFile, 'w') for items in data: - if items.find('phpIniOverride') > -1: - skip = 1 + if items.find('postmaster_address') > -1: + writeFile.writelines(' postmaster_address = postmaster@' + virtualHost + '\n') + else: + writeFile.writelines(items) - if skip == 1 and items.find('}') > -1: - skip = 0 - continue + writeFile.close() - if skip == 1: - continue + ## Update myhostname address postfix - writeToFile.writelines(items) - writeToFile.close() - else: + filePath = "/etc/postfix/main.cf" - ## Check if phpini already active + data = open(filePath, 'r').readlines() + + writeFile = open(filePath, 'w') - inistatus = 0 for items in data: - if items.find('phpIniOverride') > -1: - inistatus = 1 + if items.find('myhostname') > -1: + writeFile.writelines('myhostname = ' + virtualHost + '\n') + else: + writeFile.writelines(items) + + writeFile.close() + + p = Process(target=mailUtilities.restartServices, args=('restart',)) + p.start() + + print "1,None" + + except BaseException, msg: + logging.CyberCPLogFileWriter.writeToFile( + str(msg) + " [issueSSLForHostName]") + print "0," + str(msg) + + @staticmethod + def createAlias(masterDomain, aliasDomain, ssl, sslPath, administratorEmail, owner=None): + try: + if owner != None: + admin = Administrator.objects.get(userName=owner) + DNS.dnsTemplate(aliasDomain, owner) + + if vhost.checkIfAliasExists(aliasDomain) == 0: + + confPath = os.path.join(virtualHostUtilities.Server_root, "conf/httpd_config.conf") + data = open(confPath, 'r').readlines() + writeToFile = open(confPath, 'w') + listenerTrueCheck = 0 - if inistatus == 0: - writeToFile = open(completePathToConfigFile, 'w') for items in data: - if items.find('context /.filemanager') > -1: - writeToFile.writelines(items) - phpIniOverride = "phpIniOverride {\n" - php_admin_value = 'php_admin_value open_basedir "/tmp:/usr/local/lsws/Example/html/FileManager:$VH_ROOT"\n' - endPHPIniOverride = "}\n" - writeToFile.writelines(phpIniOverride) - writeToFile.writelines(php_admin_value) - writeToFile.writelines(endPHPIniOverride) + if items.find("listener") > -1 and items.find("Default") > -1: + listenerTrueCheck = 1 + if items.find(masterDomain) > -1 and items.find('map') > -1 and listenerTrueCheck == 1: + data = filter(None, items.split(" ")) + if data[1] == masterDomain: + writeToFile.writelines(items.rstrip('\n') + ", " + aliasDomain + "\n") + listenerTrueCheck = 0 else: writeToFile.writelines(items) - phpIniOverride = "phpIniOverride {\n" - php_admin_value = 'php_admin_value open_basedir "/tmp:$VH_ROOT"\n' - endPHPIniOverride = "}\n" - - writeToFile.writelines(phpIniOverride) - writeToFile.writelines(php_admin_value) - writeToFile.writelines(endPHPIniOverride) - writeToFile.close() - installUtilities.installUtilities.reStartLiteSpeed() - print "1,None" + + installUtilities.installUtilities.reStartLiteSpeed() + else: + print "0, This domain already exists as vHost or Alias." + return + + if ssl == 1: + retValues = sslUtilities.issueSSLForDomain(masterDomain, administratorEmail, sslPath, aliasDomain) + if retValues[0] == 0: + print "0," + str(retValues[1]) + return + else: + vhost.createAliasSSLMap(confPath, masterDomain, aliasDomain) + + print "1,None" + + except BaseException, msg: + + logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [createAlias]") + print "0," + str(msg) + + @staticmethod + def issueAliasSSL(masterDomain, aliasDomain, sslPath, administratorEmail): + try: + + confPath = os.path.join(virtualHostUtilities.Server_root, "conf/httpd_config.conf") + + retValues = sslUtilities.issueSSLForDomain(masterDomain, administratorEmail, sslPath, aliasDomain) + + if retValues[0] == 0: + print "0," + str(retValues[1]) + return + else: + vhost.createAliasSSLMap(confPath, masterDomain, aliasDomain) + + print "1,None" - except BaseException, msg: - logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [changeOpenBasedir]") - print "0," + str(msg) + except BaseException, msg: + + logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [issueAliasSSL]") + print "0," + str(msg) + + @staticmethod + def deleteAlias(masterDomain, aliasDomain): + try: + + confPath = os.path.join(virtualHostUtilities.Server_root, "conf/httpd_config.conf") + + data = open(confPath, 'r').readlines() + writeToFile = open(confPath, 'w') + aliases = [] + + for items in data: + if items.find(masterDomain) > -1 and items.find('map') > -1: + data = filter(None, items.split(" ")) + if data[1] == masterDomain: + length = len(data) + for i in range(3, length): + currentAlias = data[i].rstrip(',').strip('\n') + if currentAlias != aliasDomain: + aliases.append(currentAlias) + + aliasString = "" + + for alias in aliases: + aliasString = ", " + alias + + writeToFile.writelines( + ' map ' + masterDomain + " " + masterDomain + aliasString + "\n") + aliases = [] + aliasString = "" + else: + writeToFile.writelines(items) + + else: + writeToFile.writelines(items) + + writeToFile.close() + installUtilities.installUtilities.reStartLiteSpeed() + + print "1,None" -def saveSSL(virtualHost,pathToStoreSSL,keyPath,certPath,sslCheck): - try: + except BaseException, msg: + logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [deleteAlias]") + print "0," + str(msg) - if not os.path.exists(pathToStoreSSL): - os.mkdir(pathToStoreSSL) + @staticmethod + def changeOpenBasedir(domainName, openBasedirValue): + try: - pathToStoreSSLPrivKey = pathToStoreSSL + "/privkey.pem" - pathToStoreSSLFullChain = pathToStoreSSL + "/fullchain.pem" + confPath = virtualHostUtilities.Server_root + "/conf/vhosts/" + domainName + completePathToConfigFile = confPath + "/vhost.conf" - privkey = open(pathToStoreSSLPrivKey, 'w') - privkey.write(open(keyPath,"r").read()) - privkey.close() + data = open(completePathToConfigFile, 'r').readlines() + skip = 0 + if openBasedirValue == 'Disable': + writeToFile = open(completePathToConfigFile, 'w') + for items in data: + if items.find('phpIniOverride') > -1: + skip = 1 - fullchain = open(pathToStoreSSLFullChain, 'w') - fullchain.write(open(certPath,"r").read()) - fullchain.close() + if skip == 1 and items.find('}') > -1: + skip = 0 + continue - if sslCheck == "0": - sslUtilities.sslUtilities.installSSLForDomain(virtualHost) + if skip == 1: + continue - installUtilities.installUtilities.reStartLiteSpeed() + writeToFile.writelines(items) + writeToFile.close() + else: - FNULL = open(os.devnull, 'w') + ## Check if phpini already active - command = "chown " + "lsadm" + ":" + "lsadm" + " " + pathToStoreSSL - cmd = shlex.split(command) - subprocess.call(cmd, stdout=FNULL, stderr=subprocess.STDOUT) + inistatus = 0 + for items in data: + if items.find('phpIniOverride') > -1: + inistatus = 1 + + if inistatus == 0: + writeToFile = open(completePathToConfigFile, 'w') + for items in data: + if items.find('context /.filemanager') > -1: + writeToFile.writelines(items) + phpIniOverride = "phpIniOverride {\n" + php_admin_value = 'php_admin_value open_basedir "/tmp:/usr/local/lsws/Example/html/FileManager:$VH_ROOT"\n' + endPHPIniOverride = "}\n" + writeToFile.writelines(phpIniOverride) + writeToFile.writelines(php_admin_value) + writeToFile.writelines(endPHPIniOverride) + else: + writeToFile.writelines(items) + + phpIniOverride = "phpIniOverride {\n" + php_admin_value = 'php_admin_value open_basedir "/tmp:$VH_ROOT"\n' + endPHPIniOverride = "}\n" + + writeToFile.writelines(phpIniOverride) + writeToFile.writelines(php_admin_value) + writeToFile.writelines(endPHPIniOverride) + + writeToFile.close() + installUtilities.installUtilities.reStartLiteSpeed() + print "1,None" - print "1,None" + except BaseException, msg: + logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [changeOpenBasedir]") + print "0," + str(msg) - except BaseException,msg: - logging.CyberCPLogFileWriter.writeToFile( - str(msg) + " [saveSSL]") - print "0,"+str(msg) + @staticmethod + def saveSSL(virtualHost, pathToStoreSSL, keyPath, certPath, sslCheck): + try: + + if not os.path.exists(pathToStoreSSL): + os.mkdir(pathToStoreSSL) + + pathToStoreSSLPrivKey = pathToStoreSSL + "/privkey.pem" + pathToStoreSSLFullChain = pathToStoreSSL + "/fullchain.pem" + + privkey = open(pathToStoreSSLPrivKey, 'w') + privkey.write(open(keyPath, "r").read()) + privkey.close() + + fullchain = open(pathToStoreSSLFullChain, 'w') + fullchain.write(open(certPath, "r").read()) + fullchain.close() + + if sslCheck == "0": + sslUtilities.sslUtilities.installSSLForDomain(virtualHost) + + installUtilities.installUtilities.reStartLiteSpeed() + + FNULL = open(os.devnull, 'w') + + command = "chown " + "lsadm" + ":" + "lsadm" + " " + pathToStoreSSL + cmd = shlex.split(command) + subprocess.call(cmd, stdout=FNULL, stderr=subprocess.STDOUT) + + print "1,None" + + except BaseException, msg: + logging.CyberCPLogFileWriter.writeToFile( + str(msg) + " [saveSSL]") + print "0," + str(msg) + + @staticmethod + def createDomain(masterDomain, virtualHostName, phpVersion, path, ssl, dkimCheck, openBasedir, restore, owner=None): + try: + + ## Check if this domain either exists as website or child domain + + if restore == '0': + admin = Administrator.objects.get(userName=owner) + DNS.dnsTemplate(virtualHostName, admin) + + if Websites.objects.filter(domain=virtualHostName).count() > 0: + raise BaseException("This Domain already exists as a website.") + + if ChildDomains.objects.filter(domain=virtualHostName).count() > 0: + raise BaseException("This domain already exists as child domain.") + + ####### Limitations check + + master = Websites.objects.get(domain=masterDomain) + domainsInPackage = master.package.allowedDomains + + if domainsInPackage == 0: + pass + elif domainsInPackage > master.childdomains_set.all().count(): + pass + else: + raise BaseException("Exceeded maximum number of domains for this package") + + ####### Limitations Check End + + + if vhost.checkIfVirtualHostExists(virtualHostName) == 1: + raise BaseException("Virtual Host Directory already exists!") + + if vhost.checkIfAliasExists(virtualHostName) == 1: + raise BaseException("This domain exists as Alias.") + + if dkimCheck == 1: + if mailUtilities.checkIfDKIMInstalled() == 0: + raise BaseException("OpenDKIM is not installed, install OpenDKIM from DKIM Manager.") + + retValues = mailUtilities.setupDKIM(virtualHostName) + if retValues[0] == 0: + raise BaseException(retValues[1]) + + FNULL = open(os.devnull, 'w') + + retValues = vhost.createDirectoryForDomain(masterDomain, virtualHostName, phpVersion, path, + master.adminEmail, master.externalApp, openBasedir) + if retValues[0] == 0: + raise BaseException(retValues[1]) + + retValues = vhost.createConfigInMainDomainHostFile(virtualHostName, masterDomain) + + if retValues[0] == 0: + raise BaseException(retValues[1]) + + ## Now restart litespeed after initial configurations are done + + + if ssl == 1: + installUtilities.installUtilities.reStartLiteSpeed() + retValues = sslUtilities.issueSSLForDomain(virtualHostName, master.adminEmail, path) + installUtilities.installUtilities.reStartLiteSpeed() + if retValues[0] == 0: + raise BaseException(retValues[1]) + + ## Final Restart + if ssl == 0: + installUtilities.installUtilities.reStartLiteSpeed() + + vhost.finalizeDomainCreation(master.externalApp, path) + + ## DKIM Check + + if restore == '0': + if dkimCheck == 1: + DNS.createDKIMRecords(virtualHostName) + + website = ChildDomains(master=master, domain=virtualHostName, path=path, phpSelection=phpVersion, ssl=ssl) + + website.save() + + print "1,None" + return 1, "None" + + except BaseException, msg: + numberOfWebsites = Websites.objects.count() + ChildDomains.objects.count() + vhost.deleteVirtualHostConfigurations(virtualHostName, numberOfWebsites) + logging.CyberCPLogFileWriter.writeToFile( + str(msg) + " [createDomain]") + print "0," + str(msg) + return 0, str(msg) + + @staticmethod + def deleteDomain(virtualHostName): + try: + + numberOfWebsites = Websites.objects.count() + ChildDomains.objects.count() + vhost.deleteCoreConf(virtualHostName, numberOfWebsites) + delWebsite = ChildDomains.objects.get(domain=virtualHostName) + delWebsite.delete() + installUtilities.installUtilities.reStartLiteSpeed() + + print "1,None" + + except BaseException, msg: + logging.CyberCPLogFileWriter.writeToFile( + str(msg) + " [deleteDomain]") + print "0," + str(msg) def main(): @@ -1941,6 +1045,9 @@ def main(): parser.add_argument("--sslPath", help="Path to website document root!") parser.add_argument('--dkimCheck', help='To enable or disable DKIM support for domain.') parser.add_argument('--openBasedir', help='To enable or disable open_basedir protection for domain.') + parser.add_argument('--websiteOwner', help='Website Owner Name') + parser.add_argument('--package', help='Website package') + parser.add_argument('--restore', help='Restore Check.') ## arguments for creation child domains @@ -2003,10 +1110,9 @@ def main(): except: openBasedir = 0 - createVirtualHost(args.virtualHostName, args.administratorEmail, args.phpVersion, args.virtualHostUser, int(args.numberOfSites), int(args.ssl), args.sslPath, dkimCheck, openBasedir) - + virtualHostUtilities.createVirtualHost(args.virtualHostName, args.administratorEmail, args.phpVersion, args.virtualHostUser, int(args.numberOfSites), int(args.ssl), args.sslPath, dkimCheck, openBasedir, args.websiteOwner, args.package) elif args.function == "deleteVirtualHostConfigurations": - virtualHostUtilities.deleteVirtualHostConfigurations(args.virtualHostName,int(args.numberOfSites)) + vhost.deleteVirtualHostConfigurations(args.virtualHostName,int(args.numberOfSites)) elif args.function == "createDomain": try: dkimCheck = int(args.dkimCheck) @@ -2018,40 +1124,41 @@ def main(): except: openBasedir = 0 - - createDomain(args.masterDomain, args.virtualHostName, args.phpVersion, args.path,args.administratorEmail,args.virtualHostUser,args.restart,int(args.numberOfSites),int(args.ssl),dkimCheck, openBasedir) + virtualHostUtilities.createDomain(args.masterDomain, args.virtualHostName, args.phpVersion, args.path, int(args.ssl), dkimCheck, openBasedir, args.restore, args.websiteOwner) elif args.function == "issueSSL": - issueSSL(args.virtualHostName,args.path,args.administratorEmail) + virtualHostUtilities.issueSSL(args.virtualHostName,args.path,args.administratorEmail) elif args.function == "changePHP": - virtualHostUtilities.changePHP(args.path,args.phpVersion) + vhost.changePHP(args.path,args.phpVersion) elif args.function == "getAccessLogs": - getAccessLogs(args.path,int(args.page)) + virtualHostUtilities.getAccessLogs(args.path,int(args.page)) elif args.function == "getErrorLogs": - getErrorLogs(args.path,int(args.page)) + virtualHostUtilities.getErrorLogs(args.path,int(args.page)) elif args.function == "saveVHostConfigs": - saveVHostConfigs(args.path,args.tempPath) + virtualHostUtilities.saveVHostConfigs(args.path,args.tempPath) elif args.function == "saveRewriteRules": - saveRewriteRules(args.virtualHostName,args.path,args.tempPath) + virtualHostUtilities.saveRewriteRules(args.virtualHostName,args.path,args.tempPath) elif args.function == "saveSSL": - saveSSL(args.virtualHostName,args.path,args.tempKeyPath,args.tempCertPath,args.sslCheck) + virtualHostUtilities.saveSSL(args.virtualHostName,args.path,args.tempKeyPath,args.tempCertPath,args.sslCheck) elif args.function == "installWordPress": - installWordPress(args.virtualHostName,args.path,args.virtualHostUser,args.dbName,args.dbUser,args.dbPassword) + virtualHostUtilities.installWordPress(args.virtualHostName,args.path,args.virtualHostUser,args.dbName,args.dbUser,args.dbPassword) elif args.function == "installJoomla": - installJoomla(args.virtualHostName,args.path,args.virtualHostUser,args.dbName,args.dbUser,args.dbPassword,args.username,args.password,args.prefix,args.sitename) + virtualHostUtilities.installJoomla(args.virtualHostName,args.path,args.virtualHostUser,args.dbName,args.dbUser,args.dbPassword,args.username,args.password,args.prefix,args.sitename) elif args.function == "issueSSLForHostName": - issueSSLForHostName(args.virtualHostName,args.path) + virtualHostUtilities.issueSSLForHostName(args.virtualHostName,args.path) elif args.function == "issueSSLForMailServer": - issueSSLForMailServer(args.virtualHostName,args.path) + virtualHostUtilities.issueSSLForMailServer(args.virtualHostName,args.path) elif args.function == "findDomainBW": - virtualHostUtilities.findDomainBW(args.virtualHostName, int(args.bandwidth)) + vhost.findDomainBW(args.virtualHostName, int(args.bandwidth)) elif args.function == 'createAlias': - createAlias(args.masterDomain,args.aliasDomain,int(args.ssl),args.sslPath, args.administratorEmail) + virtualHostUtilities.createAlias(args.masterDomain,args.aliasDomain,int(args.ssl),args.sslPath, args.administratorEmail, args.websiteOwner) elif args.function == 'issueAliasSSL': - issueAliasSSL(args.masterDomain, args.aliasDomain, args.sslPath, args.administratorEmail) + virtualHostUtilities.issueAliasSSL(args.masterDomain, args.aliasDomain, args.sslPath, args.administratorEmail) elif args.function == 'deleteAlias': - deleteAlias(args.masterDomain, args.aliasDomain) + virtualHostUtilities.deleteAlias(args.masterDomain, args.aliasDomain) elif args.function == 'changeOpenBasedir': - changeOpenBasedir(args.virtualHostName, args.openBasedirValue) + virtualHostUtilities.changeOpenBasedir(args.virtualHostName, args.openBasedirValue) + elif args.function == 'deleteDomain': + virtualHostUtilities.deleteDomain(args.virtualHostName) if __name__ == "__main__": main() \ No newline at end of file diff --git a/websiteFunctions/views.py b/websiteFunctions/views.py index 63d4faa53..202f3cc14 100644 --- a/websiteFunctions/views.py +++ b/websiteFunctions/views.py @@ -25,7 +25,6 @@ from random import randint import hashlib from xml.etree import ElementTree from plogical.mailUtilities import mailUtilities -from dns.views import createDNSRecord # Create your views here. @@ -170,248 +169,6 @@ def deleteWebsite(request): except KeyError: return redirect(loadLoginPage) -def dnsTemplate(request, domain, admin): - try: - - ipFile = "/etc/cyberpanel/machineIP" - f = open(ipFile) - ipData = f.read() - ipAddress = ipData.split('\n', 1)[0] - - import tldextract - - extractDomain = tldextract.extract(domain) - topLevelDomain = extractDomain.domain + '.' + extractDomain.suffix - subDomain = extractDomain.subdomain - - if len(subDomain) == 0: - - if Domains.objects.filter(name=topLevelDomain).count() == 0: - - zone = Domains(admin=admin, name=topLevelDomain, type="NATIVE") - zone.save() - - content = "ns1." + topLevelDomain + " hostmaster." + topLevelDomain + " 1 10800 3600 604800 3600" - - soaRecord = Records(domainOwner=zone, - domain_id=zone.id, - name=topLevelDomain, - type="SOA", - content=content, - ttl=3600, - prio=0, - disabled=0, - auth=1) - soaRecord.save() - - ## Main A record. - - record = Records(domainOwner=zone, - domain_id=zone.id, - name=topLevelDomain, - type="A", - content=ipAddress, - ttl=3600, - prio=0, - disabled=0, - auth=1) - record.save() - - # CNAME Records. - - cNameValue = "www." + topLevelDomain - - record = Records(domainOwner=zone, - domain_id=zone.id, - name=cNameValue, - type="CNAME", - content=topLevelDomain, - ttl=3600, - prio=0, - disabled=0, - auth=1) - record.save() - - cNameValue = "ftp." + topLevelDomain - - record = Records(domainOwner=zone, - domain_id=zone.id, - name=cNameValue, - type="CNAME", - content=topLevelDomain, - ttl=3600, - prio=0, - disabled=0, - auth=1) - record.save() - - ## MX Record. - - mxValue = "mail." + topLevelDomain - - record = Records(domainOwner=zone, - domain_id=zone.id, - name=topLevelDomain, - type="MX", - content=mxValue, - ttl=3600, - prio="10", - disabled=0, - auth=1) - record.save() - - record = Records(domainOwner=zone, - domain_id=zone.id, - name=mxValue, - type="A", - content=ipAddress, - ttl=3600, - prio=0, - disabled=0, - auth=1) - record.save() - - ## TXT Records for mail - - record = Records(domainOwner=zone, - domain_id=zone.id, - name=topLevelDomain, - type="TXT", - content="v=spf1 a mx ip4:" + ipAddress + " ~all", - ttl=3600, - prio=0, - disabled=0, - auth=1) - record.save() - - record = Records(domainOwner=zone, - domain_id=zone.id, - name="_dmarc." + topLevelDomain, - type="TXT", - content="v=DMARC1; p=none", - ttl=3600, - prio=0, - disabled=0, - auth=1) - record.save() - - record = Records(domainOwner=zone, - domain_id=zone.id, - name="_domainkey." + topLevelDomain, - type="TXT", - content="t=y; o=~;", - ttl=3600, - prio=0, - disabled=0, - auth=1) - record.save() - - else: - if Domains.objects.filter(name=topLevelDomain).count() == 0: - zone = Domains(admin=admin, name=topLevelDomain, type="NATIVE") - zone.save() - - content = "ns1." + topLevelDomain + " hostmaster." + topLevelDomain + " 1 10800 3600 604800 3600" - - soaRecord = Records(domainOwner=zone, - domain_id=zone.id, - name=topLevelDomain, - type="SOA", - content=content, - ttl=3600, - prio=0, - disabled=0, - auth=1) - soaRecord.save() - - ## Main A record. - - record = Records(domainOwner=zone, - domain_id=zone.id, - name=topLevelDomain, - type="A", - content=ipAddress, - ttl=3600, - prio=0, - disabled=0, - auth=1) - record.save() - - # CNAME Records. - - cNameValue = "www." + topLevelDomain - - record = Records(domainOwner=zone, - domain_id=zone.id, - name=cNameValue, - type="CNAME", - content=topLevelDomain, - ttl=3600, - prio=0, - disabled=0, - auth=1) - record.save() - - cNameValue = "ftp." + topLevelDomain - - record = Records(domainOwner=zone, - domain_id=zone.id, - name=cNameValue, - type="CNAME", - content=topLevelDomain, - ttl=3600, - prio=0, - disabled=0, - auth=1) - record.save() - - ## MX Record. - - mxValue = "mail." + topLevelDomain - - record = Records(domainOwner=zone, - domain_id=zone.id, - name=topLevelDomain, - type="MX", - content=mxValue, - ttl=3600, - prio="10", - disabled=0, - auth=1) - record.save() - - record = Records(domainOwner=zone, - domain_id=zone.id, - name=mxValue, - type="A", - content=ipAddress, - ttl=3600, - prio=0, - disabled=0, - auth=1) - record.save() - - ## Creating sub-domain level record. - - zone = Domains.objects.get(name=topLevelDomain) - - actualSubDomain = subDomain + "." + topLevelDomain - - - ## Main A record. - - createDNSRecord(request, zone, actualSubDomain, "A", ipAddress, 0, 3600) - - # CNAME Records. - - cNameValue = "www." + actualSubDomain - - createDNSRecord(request, zone, cNameValue, "CNAME", actualSubDomain, 0, 3600) - - except BaseException, msg: - logging.CyberCPLogFileWriter.writeToFile( - "We had errors while creating DNS records for: " + domain + ". Error message: " + str(msg)) - def createDKIMRecords(request, domain, admin): try: @@ -495,19 +252,6 @@ def submitWebsiteCreation(request): externalApp = "".join(re.findall("[a-zA-Z]+", domain))[:7] - if Websites.objects.filter(domain=domain).count() > 0: - data_ret = {"existsStatus": 0, 'createWebSiteStatus': 0, - 'error_message': "This website already exists."} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - - if ChildDomains.objects.filter(domain=domain).count() > 0: - data_ret = {"existsStatus": 0, 'createWebSiteStatus': 0, - 'error_message': "This website already exists as child domain."} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - ####### Limitations check admin = Administrator.objects.get(userName=websiteOwner) @@ -523,12 +267,6 @@ def submitWebsiteCreation(request): ####### Limitations Check End - ##### Zone creation - - dnsTemplate(requests, domain, admin) - - ## zone creation - numberOfWebsites = str(Websites.objects.count() + ChildDomains.objects.count()) sslpath = "/home/" + domain + "/public_html" @@ -536,9 +274,12 @@ def submitWebsiteCreation(request): execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" - execPath = execPath + " createVirtualHost --virtualHostName " + domain + " --administratorEmail " + adminEmail + " --phpVersion '" + phpSelection + "' --virtualHostUser " + externalApp + " --numberOfSites " + numberOfWebsites + " --ssl " + str( - data['ssl']) + " --sslPath " + sslpath + " --dkimCheck " + str(data['dkimCheck']) + " --openBasedir " + str(data['openBasedir']) - + execPath = execPath + " createVirtualHost --virtualHostName " + domain + \ + " --administratorEmail " + adminEmail + " --phpVersion '" + phpSelection + \ + "' --virtualHostUser " + externalApp + " --numberOfSites " + numberOfWebsites + \ + " --ssl " + str(data['ssl']) + " --sslPath " + sslpath + " --dkimCheck " + str(data['dkimCheck'])\ + + " --openBasedir " + str(data['openBasedir']) + ' --websiteOwner ' + websiteOwner \ + + ' --package ' + packageName output = subprocess.check_output(shlex.split(execPath)) @@ -549,18 +290,6 @@ def submitWebsiteCreation(request): json_data = json.dumps(data_ret) return HttpResponse(json_data) - ## Create Configurations ends here - - ## DKIM Check - - if data['dkimCheck'] == 1: - createDKIMRecords(request, domain, admin) - - selectedPackage = Package.objects.get(packageName=packageName) - - website = Websites(admin=admin, package=selectedPackage, domain=domain, adminEmail=adminEmail,phpSelection=phpSelection, ssl=data['ssl'], externalApp=externalApp) - - website.save() data_ret = {'createWebSiteStatus': 1, 'error_message': "None", "existsStatus": 0} json_data = json.dumps(data_ret) @@ -579,71 +308,45 @@ def submitDomainCreation(request): masterDomain = data['masterDomain'] domain = data['domainName'] phpSelection = data['phpSelection'] - - - ## Check if this domain either exists as website or child domain - - if Websites.objects.filter(domain=domain).count() > 0: - data_ret = {"existsStatus": 0, 'createWebSiteStatus': 0, - 'error_message': "This Domain already exists as a website."} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - - if ChildDomains.objects.filter(domain=domain).count() > 0: - data_ret = {"existsStatus": 0, 'createWebSiteStatus': 0, - 'error_message': "This domain already exists as child domain."} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - ####### Limitations check - - master = Websites.objects.get(domain=masterDomain) - domainsInPackage = master.package.allowedDomains - - if domainsInPackage == 0: - pass - elif domainsInPackage > master.childdomains_set.all().count(): - pass - else: - data_ret = {"existsStatus": 0, 'createWebSiteStatus': 0, - 'error_message': "Exceeded maximum number of domains for this package"} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - ####### Limitations Check End - - ssl = data['ssl'] path = data['path'] - restart = 1 - - ## Create Configurations try: restore = data['restore'] - restart = 0 - except: + restore = '1' + if len(path) > 0: path = path.lstrip("/") path = "/home/" + masterDomain + "/public_html/" + path else: path = "/home/" + masterDomain + "/public_html/" + domain - ### Zone creation. + execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" + + execPath = execPath + " createDomain --masterDomain " + masterDomain + " --virtualHostName " + domain + \ + " --phpVersion '" + phpSelection + "' --ssl " + str(data['ssl']) + " --dkimCheck " + \ + str(data['dkimCheck']) + " --openBasedir " + str(data['openBasedir']) + ' --path ' + path \ + + ' --restore ' + restore + + except: + restore = '0' + + if len(path) > 0: + path = path.lstrip("/") + path = "/home/" + masterDomain + "/public_html/" + path + else: + path = "/home/" + masterDomain + "/public_html/" + domain val = request.session['userID'] admin = Administrator.objects.get(pk=val) - dnsTemplate(requests, domain, admin) + execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" - externalApp = master.externalApp - numberOfWebsites = str(Websites.objects.count() + ChildDomains.objects.count()) + execPath = execPath + " createDomain --masterDomain " + masterDomain + " --virtualHostName " + domain + \ + " --phpVersion '" + phpSelection + "' --ssl " + str(data['ssl']) + " --dkimCheck " + str(data['dkimCheck']) \ + + " --openBasedir " + str(data['openBasedir']) + ' --path ' + path \ + + ' --restore ' + restore + ' --websiteOwner ' + admin.userName - execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" - - execPath = execPath + " createDomain --masterDomain " + masterDomain + " --virtualHostName " + domain + " --administratorEmail " + master.adminEmail + " --phpVersion '" + phpSelection + "' --virtualHostUser " + externalApp + " --numberOfSites " + numberOfWebsites + " --ssl " + str( - data['ssl']) + " --path " + path + " --dkimCheck " + str(data['dkimCheck']) + " --openBasedir " + str(data['openBasedir']) output = subprocess.check_output(shlex.split(execPath)) @@ -654,21 +357,6 @@ def submitDomainCreation(request): json_data = json.dumps(data_ret) return HttpResponse(json_data) - ## Create Configurations ends here - - ## DKIM Check - - try: - restore = data['restore'] - restart = 0 - except BaseException, msg: - if data['dkimCheck'] == 1: - admin = Administrator.objects.get(pk=val) - createDKIMRecords(request, domain, admin) - - website = ChildDomains(master=master, domain=domain, path=path, phpSelection=phpSelection, ssl=ssl) - - website.save() data_ret = {'createWebSiteStatus': 1, 'error_message': "None", "existsStatus": 0} json_data = json.dumps(data_ret) @@ -850,41 +538,6 @@ def submitWebsiteDeletion(request): subprocess.check_output(shlex.split(execPath)) - delWebsite = Websites.objects.get(domain=websiteName) - databases = Databases.objects.filter(website=delWebsite) - - childDomains = delWebsite.childdomains_set.all() - - ## Deleting child domains - - for items in childDomains: - numberOfWebsites = str(Websites.objects.count()+ChildDomains.objects.count()) - execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" - execPath = execPath + " deleteVirtualHostConfigurations --virtualHostName " + items.domain + " --numberOfSites " + numberOfWebsites - - subprocess.check_output(shlex.split(execPath)) - - - for items in databases: - mysqlUtilities.deleteDatabase(items.dbName, items.dbUser) - - - delWebsite.delete() - - try: - delZone = Domains.objects.get(name=websiteName) - delZone.delete() - except: - ## There does not exist a zone for this domain. - pass - - installUtilities.reStartLiteSpeed() - - ## Delete mail accounts - - command = "sudo rm -rf /home/vmail/" + websiteName - subprocess.call(shlex.split(command)) - data_ret = {'websiteDeleteStatus': 1,'error_message': "None"} json_data = json.dumps(data_ret) @@ -909,25 +562,12 @@ def submitDomainDeletion(request): data = json.loads(request.body) websiteName = data['websiteName'] - numberOfWebsites = str(Websites.objects.count() + ChildDomains.objects.count()) - execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" - execPath = execPath + " deleteVirtualHostConfigurations --virtualHostName " + websiteName + " --numberOfSites " + numberOfWebsites + execPath = execPath + " deleteDomain --virtualHostName " + websiteName subprocess.check_output(shlex.split(execPath)) - - delWebsite = ChildDomains.objects.get(domain=websiteName) - - delWebsite.delete() - - - installUtilities.reStartLiteSpeed() - - - - data_ret = {'websiteDeleteStatus': 1,'error_message': "None"} json_data = json.dumps(data_ret) return HttpResponse(json_data) @@ -2718,14 +2358,6 @@ def submitAliasCreation(request): admin = Administrator.objects.get(pk=request.session['userID']) - ##### Zone creation - - dnsTemplate(requests, aliasDomain, admin) - - ### Zone creation - - - sslpath = "/home/" + masterDomain + "/public_html" ## Create Configurations @@ -2733,7 +2365,7 @@ def submitAliasCreation(request): execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" execPath = execPath + " createAlias --masterDomain " + masterDomain + " --aliasDomain " + aliasDomain + " --ssl " + str( - ssl) + " --sslPath " + sslpath + " --administratorEmail " + admin.email + ssl) + " --sslPath " + sslpath + " --administratorEmail " + admin.email + ' --websiteOwner ' + admin.userName output = subprocess.check_output(shlex.split(execPath)) @@ -2746,8 +2378,6 @@ def submitAliasCreation(request): ## Create Configurations ends here - - data_ret = {'createAliasStatus': 1, 'error_message': "None", "existsStatus": 0} json_data = json.dumps(data_ret) return HttpResponse(json_data)