Commit ab699313 authored by Kjetil Thuen's avatar Kjetil Thuen

Initial commit (Almost done)

parents
target
.idea
.settings
.classpath
.project
tags
*.swp
*.iml
TODO
Sjekk at nødvendige parametre er på plass i doGet (der er en egen returverdi for manglende parametre)
Autentisering?
Fiks at bash scriptet faktisk blir kjørt
Finn ut av linjeskift i SMS
Finn ut av prefix streng fra pam_otpsms.conf
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.nesstar</groupId>
<artifactId>smsgateway</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>A sms-sending webapp</name>
<description>SMS Gateway</description>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<httpclient.version>4.1.2</httpclient.version>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.mortbay.jetty</groupId>
<artifactId>maven-jetty-plugin</artifactId>
<version>6.1.10</version>
<configuration>
<scanIntervalSeconds>10</scanIntervalSeconds>
<contextPath>/sms</contextPath>
<connectors>
<connector implementation="org.mortbay.jetty.nio.SelectChannelConnector">
<port>8080</port>
<maxIdleTime>60000</maxIdleTime>
</connector>
</connectors>
<stopKey>foo</stopKey>
<stopPort>9999</stopPort>
<scanTargetPatterns>
<scanTargetPattern>
<directory>src/main/webapp</directory>
<includes>
<include>**/*.html</include>
<include>**/*.js</include>
<include>**/*.css</include>
<include>**/*.less</include>
</includes>
</scanTargetPattern>
<scanTargetPattern>
<directory>src/main/java</directory>
<includes>
<include>**/*.java</include>
</includes>
</scanTargetPattern>
</scanTargetPatterns>
</configuration>
<executions>
<execution>
<id>start-jetty</id>
<phase>pre-integration-test</phase>
<goals>
<goal>run</goal>
</goals>
<configuration>
<scanIntervalSeconds>0</scanIntervalSeconds>
<daemon>true</daemon>
</configuration>
</execution>
<execution>
<id>stop-jetty</id>
<phase>post-integration-test</phase>
<goals>
<goal>stop</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>${httpclient.version}</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.16</version>
</dependency>
</dependencies>
</project>
package com.nesstar;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import org.apache.log4j.Logger;
public class SMSByFile extends SMSSend {
private static Logger logger = Logger.getLogger(SMSByFile.class);
@Override
public void sendSMS(String number, String message) throws IOException {
File dir = new File(getOption("file.outgoing.dir"));
if (!dir.exists() || !dir.isDirectory()) {
throw new RuntimeException(dir.getAbsolutePath() + " is not a directory.");
}
if (!dir.canWrite()) {
throw new RuntimeException("Cannot write to " + dir.getAbsolutePath());
}
File outputFile = File.createTempFile("SMS", ".txt", dir);
FileWriter fstream = new FileWriter(outputFile);
BufferedWriter out = new BufferedWriter(fstream);
out.write("To: " + number);
out.write("\n\n");
out.write(prepareMessage(message));
out.close();
logger.info("Saved SMS to " + outputFile.getAbsolutePath());
}
}
package com.nesstar;
import org.apache.log4j.Logger;
public class SMSByHand extends SMSSend {
private static Logger logger = Logger.getLogger(SMSByHand.class);
@Override
public void sendSMS(String number, String message) {
logger.info("Please type in and send the following SMS to " + number + ": " + prepareMessage(message));
}
}
package com.nesstar;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import org.apache.log4j.Logger;
public class SMSByScript extends SMSSend {
private static Logger logger = Logger.getLogger(SMSByScript.class);
private static String scriptInterpreter = "/usr/bin/env bash";
@Override
public void sendSMS(String number, String message) throws IOException {
File script = new File(getOption("script.path"));
if (!script.exists()) {
throw new RuntimeException("Could not find sms script " + script.getAbsolutePath() + ".");
} else {
String command = scriptInterpreter + " " + script.getAbsolutePath() + " " + number + " '" + prepareMessage(message) + "'";
logger.info("Running command: " + command);
Process proc = Runtime.getRuntime().exec(command);
BufferedReader read = new BufferedReader(new InputStreamReader(proc.getInputStream()));
try {
while (read.ready()) {
logger.info(read.readLine());
}
int ret = proc.waitFor();
logger.info("Return value " + ret);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
package com.nesstar;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.Collections;
import java.util.Enumeration;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
public class SMSGateway extends HttpServlet {
private static final long serialVersionUID = 1L;
private static Logger logger = Logger.getLogger(SMSGateway.class);
protected HttpServletResponse response;
private SMSSend sender;
public SMSGateway() {
super();
}
@Override
public void init(ServletConfig servletConfig) throws ServletException {
super.init(servletConfig);
sender = getSenderImplementation();
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
logger.debug("Got request");
this.response = response;
int httpStatus = 200;
int messageID = 1234;
int serviceStatus = 0;
String statusString = "OK";
try {
if (null == request.getParameter("DESTADDR")) {
httpStatus = 500;
messageID = -1;
serviceStatus = 2;
statusString = "Mandatory parameter DESTADDR missing";
}
if (serviceStatus == 0 && null == request.getParameter("MESSAGE")) {
httpStatus = 500;
messageID = -1;
serviceStatus = 2;
statusString = "Mandatory parameter MESSAGE missing";
}
if (serviceStatus == 0) {
if (authenticateUser(request)) {
sendSMS(request.getParameter("DESTADDR"), request.getParameter("MESSAGE"), sender);
} else {
httpStatus = 401;
messageID = -1;
serviceStatus = 10;
statusString = "Access Denied";
}
}
} catch (RuntimeException e) {
httpStatus = 500;
messageID = -1;
serviceStatus = 1;
statusString = "Failed: " + e.getMessage();
logger.error(e, e);
}
try {
response.setStatus(httpStatus);
response.setContentType("text/plain");
PrintWriter out = new PrintWriter(new OutputStreamWriter(response.getOutputStream(), "UTF8"), true);
out.write(messageID + "\n");
out.write(serviceStatus + "\n");
out.write(statusString + "\n");
out.flush();
out.close();
} catch (Exception e) {
logger.fatal("Unknown error", e);
}
}
private boolean authenticateUser(HttpServletRequest request) {
String username = getInitParameter("username");
String passwordHash = getInitParameter("passwordhash");
if (null != username && null != passwordHash) {
String requestUser = request.getParameter("USERNAME");
String requestPassword = request.getParameter("PASSWORD");
if (!requestUser.equals(username) || !requestPassword.equals(passwordHash)) {
return false;
}
}
return true;
}
private SMSSend getSenderImplementation() {
SMSSend sender = null;
String senderClass = getInitParameter("sms.sender.implementation");
switch (senderClass.toLowerCase()) {
case "script":
sender = new SMSByScript();
break;
case "file":
sender = new SMSByFile();
break;
default:
sender = new SMSByHand();
break;
}
getInitParameterNames();
for (String key : Collections.list((Enumeration<String>) getInitParameterNames())) {
if (key.startsWith(senderClass.toLowerCase()) || key.startsWith("global")) {
sender.setOption(key, getInitParameter(key));
}
}
return sender;
}
private void sendSMS(String number, String message, SMSSend sender) throws RuntimeException, IOException {
sender.sendSMS(number, message);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
package com.nesstar;
import java.io.IOException;
import java.util.Hashtable;
import org.apache.log4j.Logger;
public abstract class SMSSend {
private Hashtable<String, String> options;
private static Logger logger = Logger.getLogger(SMSSend.class);
abstract public void sendSMS(String number, String message) throws RuntimeException, IOException;
void setOption(String key, String value) {
if (options == null) {
options = new Hashtable<String, String>();
}
options.put(key, value);
}
String getOption(String key) {
if (options == null) {
options = new Hashtable<String, String>();
}
String value = options.get(key);
if (null == value) {
value = "";
}
return value;
}
String prepareMessage(String mainContent) {
String prefix = getOption("global.message.prefix");
String suffix = getOption("global.message.suffix");
String message = prefix + " " + mainContent + " " + suffix;
logger.info("SMS content: " + message);
return message;
}
}
log4j.rootLogger=INFO, CONSOLE
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern= %d{HH:mm:ss,SSS} [%t] %-5p %x %C{1} : %m%n
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>sms</display-name>
<servlet>
<servlet-name>sms</servlet-name>
<servlet-class>com.nesstar.SMSGateway</servlet-class>
<init-param>
<param-name>sms.sender.implementation</param-name>
<!-- Available implementations: script, file, hand -->
<param-value>script</param-value>
</init-param>
<init-param>
<param-name>username</param-name>
<!-- Available implementations: script, file, hand -->
<param-value>smsuser</param-value>
</init-param>
<init-param>
<param-name>passwordhash</param-name>
<!-- Available implementations: script, file, hand -->
<param-value>smspass</param-value>
</init-param>
<init-param>
<param-name>file.outgoing.dir</param-name>
<param-value>/var/spool/sms/outgoing/</param-value>
</init-param>
<init-param>
<param-name>script.path</param-name>
<param-value>/usr/local/bin/sendsms</param-value>
</init-param>
<init-param>
<param-name>global.message.prefix</param-name>
<param-value>Your password is: </param-value>
</init-param>
<init-param>
<param-name>global.message.suffix</param-name>
<param-value>...</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>sms</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment