Dependents:   TimeZoneDemo EthernetJackTestCode MMEx_Challenge ntp_mem ... more

Files at this revision

API Documentation at this revision

Comitter:
segundo
Date:
Sat Nov 27 23:23:43 2010 +0000
Parent:
4:966a0265edfc
Child:
6:d64fca63b94e
Commit message:

Changed in this revision

services/email/EmailMessage.cpp Show annotated file Show diff for this revision Revisions of this file
services/email/EmailMessage.h Show annotated file Show diff for this revision Revisions of this file
services/email/emailMessage.cpp Show diff for this revision Revisions of this file
services/email/emailMessage.h Show diff for this revision Revisions of this file
services/email/smtp/SMTPClient.cpp Show annotated file Show diff for this revision Revisions of this file
services/email/smtp/SMTPClient.h Show annotated file Show diff for this revision Revisions of this file
services/http/util/base64.cpp Show annotated file Show diff for this revision Revisions of this file
services/http/util/base64.h Show annotated file Show diff for this revision Revisions of this file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/services/email/EmailMessage.cpp	Sat Nov 27 23:23:43 2010 +0000
@@ -0,0 +1,68 @@
+
+/*
+Copyright (c) 2010 Donatien Garnier (donatiengar [at] gmail [dot] com) y Segundo Equipo
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+*/
+
+#include "EmailMessage.h"
+
+#include <stdio.h>
+#include <stdarg.h>
+
+#define BUF_SIZE 512
+
+EmailMessage::EmailMessage() : m_from(), m_lTo(), m_content() {
+}
+
+EmailMessage::~EmailMessage() {
+}
+
+void EmailMessage::setFrom(const char* from) {
+    m_from = from;
+}
+
+void EmailMessage::addTo(const char* to) {
+    m_lTo.push_back(to);
+}
+
+void EmailMessage::clearTo() {
+    m_lTo.clear();
+}
+
+int EmailMessage::printf(const char* format, ... ) { // Can be called multiple times to write the message
+
+    char buf[BUF_SIZE] = {0};
+    int len = 0;
+
+    va_list argp;
+
+    va_start(argp, format);
+    len += vsnprintf(buf, BUF_SIZE, format, argp);
+    va_end(argp);
+
+    if (len > 0)
+        m_content.append(buf);
+
+    return len;
+}
+
+void EmailMessage::clearContent() {
+    m_content.clear();
+}
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/services/email/EmailMessage.h	Sat Nov 27 23:23:43 2010 +0000
@@ -0,0 +1,83 @@
+
+/*
+Copyright (c) 2010 Donatien Garnier (donatiengar [at] gmail [dot] com) y Segundo Equipo
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+*/
+
+/** \file
+Email message header file
+*/
+
+#ifndef EMAIL_MESSAGE_H
+#define EMAIL_MESSAGE_H
+
+#include <vector>
+using std::vector;
+
+#include <string>
+using std::string;
+
+///A simple email message
+/**
+A class to hold the message addresses and content for sending (with SMTPClient).
+*/
+class EmailMessage {
+public:
+    ///Instantiates the email message
+    EmailMessage();
+
+    ///Destructor for the email message
+    ~EmailMessage();
+
+    ///Set FROM address
+    /**
+    @param from : email from address
+    */
+    void setFrom(const char* from);
+
+    ///Add TO address to list of recipient addresses
+    /**
+    @param host : SMTP server host
+    */
+    void addTo(const char* to);
+
+    ///Clear TO addresses
+    void clearTo();
+    
+    ///Append text to content of message using printf
+    /**
+    @param format : printf format followed by ... variables
+    
+    Can be called multiple times to write the message
+    */
+    int printf(const char* format, ... );
+
+    ///Clear content previously appended by printf
+    void clearContent();
+
+private:
+    friend class SMTPClient;
+    string m_from;
+    vector<string> m_lTo;
+    string m_content;
+
+};
+
+#endif
\ No newline at end of file
--- a/services/email/emailMessage.cpp	Sun Nov 21 17:13:44 2010 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,75 +0,0 @@
-
-/*
-Copyright (c) 2010 Donatien Garnier (donatiengar [at] gmail [dot] com)
- 
-Permission is hereby granted, free of charge, to any person obtaining a copy
-of this software and associated documentation files (the "Software"), to deal
-in the Software without restriction, including without limitation the rights
-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-copies of the Software, and to permit persons to whom the Software is
-furnished to do so, subject to the following conditions:
- 
-The above copyright notice and this permission notice shall be included in
-all copies or substantial portions of the Software.
- 
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-THE SOFTWARE.
-*/
-
-#include "emailMessage.h"
-
-#if 0
-
-#include <stdio.h>
-#include <stdarg.h>
-
-#define BUF_SIZE 512
-
-EmailMessage::EmailMessage(SMTPClient* pClient) : m_lTo(), m_from(), m_content(), m_pClient(pClient)
-{
-
-}
-
-EmailMessage::~EmailMessage()
-{
-
-}
-  
-void EmailMessage::setFrom(const char* from)
-{
-  m_from = from;
-}
-
-void EmailMessage::addTo(const char* to)
-{
-  m_lTo.push(to);
-}
-
-int EmailMessage::printf(const char* format, ... ) //Can be called multiple times to write the message
-{
-  char buf[BUF_SIZE] = {0};
-  int len = 0;
-    
-  va_list argp;
-  
-  va_start(argp, format);
-  len += vsprintf(buf, format, argp);
-  va_end(argp);
-  
-  if(len>0)
-    m_content.append(buf);
-  
-  return len;
-}
-  
-void EmailMessage::send()
-{
-  m_pClient->send(this);
-}
-
-#endif
--- a/services/email/emailMessage.h	Sun Nov 21 17:13:44 2010 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,65 +0,0 @@
-
-/*
-Copyright (c) 2010 Donatien Garnier (donatiengar [at] gmail [dot] com)
- 
-Permission is hereby granted, free of charge, to any person obtaining a copy
-of this software and associated documentation files (the "Software"), to deal
-in the Software without restriction, including without limitation the rights
-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-copies of the Software, and to permit persons to whom the Software is
-furnished to do so, subject to the following conditions:
- 
-The above copyright notice and this permission notice shall be included in
-all copies or substantial portions of the Software.
- 
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-THE SOFTWARE.
-*/
-
-#ifndef EMAIL_MESSAGE_H
-#define EMAIL_MESSAGE_H
-
-class SMTPClient;
-
-#include "smtp/SMTPClient.h"
-
-#include <queue>
-using std::queue;
-
-#include <string>
-using std::string;
-
-class EmailMessage
-{
-public:
-  EmailMessage(SMTPClient* pClient);
-  ~EmailMessage();
-  
-  void setFrom(const char* from);
-  void addTo(const char* to);
-  int printf(const char* format, ... ); //Can be called multiple times to write the message
-  
-  void send();
-  
-  //For now, only message sending is implemented
-  //int scanf(const char* format, ... ); 
-  
-private:
-  friend class SMTPClient;
-  queue<string> m_lTo;
-  string m_from;
-  
-  string m_content;
-  
-  SMTPClient* m_pClient;
-
-};
-
-
-
-#endif
--- a/services/email/smtp/SMTPClient.cpp	Sun Nov 21 17:13:44 2010 +0000
+++ b/services/email/smtp/SMTPClient.cpp	Sat Nov 27 23:23:43 2010 +0000
@@ -1,17 +1,17 @@
 
 /*
-Copyright (c) 2010 Donatien Garnier (donatiengar [at] gmail [dot] com)
- 
+Copyright (c) 2010 Donatien Garnier (donatiengar [at] gmail [dot] com) y Segundo Equipo
+
 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:
- 
+
 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.
- 
+
 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@@ -20,225 +20,439 @@
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
 */
-
+#include "core/netservice.h"
 #include "SMTPClient.h"
-
-/*
-  Provided as reference only, this code has not been tested.
-*/
-#if 0
-
-#include <stdio.h>
+#include "../util/base64.h"
 
 #define __DEBUG
-#include "dbg.h"
+#include "dbg/dbg.h"
+
+#define CHUNK_SIZE 256 //512
+#define BUF_SIZE (CHUNK_SIZE + 1)
+
+#define SMTP_REQUEST_TIMEOUT 15000
+#define SMTP_PORT 25
 
-#define BUF_SIZE 128
-#define CHUNK_SIZE 512
+SMTPClient::SMTPClient() : NetService(false) /*Not owned by the pool*/,
+        m_pCbItem(NULL), m_pCbMeth(NULL), m_pCb(NULL),
+        m_watchdog(), m_timeout(SMTP_REQUEST_TIMEOUT), m_pDnsReq(NULL), m_server(),
+        m_closed(true), m_state(SMTP_CLOSED), m_pMessage(NULL),
+        m_posInMsg(0), m_blockingResult(SMTP_PROCESSING),
+        m_username(""), m_password(""), m_auth(SMTP_AUTH_NONE),
+        m_heloDomain("localhost") {
+    DBG("New SMTPClient %p\n", this);
+}
 
-SMTPClient::SMTPClient() : m_pMessage(NULL), m_nextState(SMTP_HELLO), 
-m_pCbItem(NULL), m_pCbMeth(NULL), m_watchdog(), m_timeout(0), m_posInMsg(0), m_closed(true), m_host()
-{
-  setTimeout(SMTP_REQUEST_TIMEOUT);
+SMTPClient::SMTPClient(const Host& host, const char* heloDomain, const char* user, const char* password, SMTPAuth auth) : NetService(false),
+        m_pCbItem(NULL), m_pCbMeth(NULL), m_pCb(NULL),
+        m_watchdog(), m_timeout(SMTP_REQUEST_TIMEOUT), m_pDnsReq(NULL), m_server(host),
+        m_closed(true), m_state(SMTP_CLOSED), m_pMessage(NULL),
+        m_posInMsg(0), m_blockingResult(SMTP_PROCESSING),
+        m_username(string(user)), m_password(string(password)), m_auth(auth),
+        m_heloDomain(heloDomain) {
+    DBG("New SMTPClient %p\n", this);
+}
+
+SMTPClient::~SMTPClient() {
+    close();
+}
+
+void SMTPClient::setAuth(const char* user, const char* password) { // Plain authentication
+    m_username = string(user);
+    m_password = string(password);
+    m_auth = SMTP_AUTH_PLAIN;
+}
+
+void SMTPClient::clearAuth() { // Clear authentication
+    m_username = "";
+    m_password = "";
+    m_auth = SMTP_AUTH_NONE;
 }
 
-SMTPClient::~SMTPClient()
-{
-  close();
+string SMTPClient::encodePlainAuth() {
+    string auth = "AUTH PLAIN ";
+    string decStr = m_username;
+    decStr += '\0';
+    decStr += m_username;
+    decStr += '\0';
+    decStr += m_password;
+
+    char* out = new char[ (((decStr.length()-1)/3)+1)<<2 ];
+    base64enc(decStr.c_str(), decStr.length(), out);
+    auth.append(string(out));
+    delete[] out;
+
+    return auth;
+}
+
+void SMTPClient::setHeloDomain(const char* heloDomain) {
+    m_heloDomain = string(heloDomain);
+}
+
+SMTPResult SMTPClient::send(EmailMessage* pMessage) { //Blocking
+    doSend(pMessage);
+    return blockingProcess();
+}
+
+SMTPResult SMTPClient::send(EmailMessage* pMessage, void (*pMethod)(SMTPResult)) { //Non blocking
+    setOnResult(pMethod);
+    doSend(pMessage);
+    return SMTP_PROCESSING;
+}
+
+void SMTPClient::doSend(EmailMessage* pMessage) {
+    setup(pMessage);
+}
+
+void SMTPClient::setOnResult( void (*pMethod)(SMTPResult) ) {
+    m_pCb = pMethod;
+    m_pCbItem = NULL;
+    m_pCbMeth = NULL;
+}
+
+void SMTPClient::setTimeout(int ms) {
+    m_timeout = ms;
+}
+
+void SMTPClient::poll() { //Called by NetServices
+    if ( (!m_closed) && (m_watchdog.read_ms() >= m_timeout) ) {
+        onTimeout();
+    }
 }
 
-void SMTPClient::setHost(const Host& host)
-{
-  m_host = host;
+void SMTPClient::resetTimeout() {
+    m_watchdog.reset();
+    m_watchdog.start();
+}
+
+void SMTPClient::init() { //Create and setup socket if needed
+    close(); //Remove previous elements
+    if (!m_closed) //Already opened
+        return;
+    m_state = SMTP_HELLO;
+    m_pTCPSocket = new TCPSocket;
+    m_pTCPSocket->setOnEvent(this, &SMTPClient::onTCPSocketEvent);
+    m_closed = false;
+    m_posInMsg = 0;
+    m_posInCRLF = 2;
+    m_response = "";
 }
-  
-void SMTPClient::send(EmailMessage* pMessage)
-{
-  init();
-  m_posInMsg = 0;
-  m_nextState = SMTP_HELLO;
-  if( !m_pTCPSocket->connect(m_host) )
-  {
-    close();
-    onResult(SMTP_DISC);
-  }
+
+void SMTPClient::close() {
+    if (m_closed)
+        return;
+    m_state = SMTP_CLOSED;
+    m_closed = true; //Prevent recursive calling or calling on an object being destructed by someone else
+    m_watchdog.stop(); //Stop timeout
+    m_watchdog.reset();
+    m_pTCPSocket->resetOnEvent();
+    m_pTCPSocket->close();
+    delete m_pTCPSocket;
+    m_pTCPSocket = NULL;
+    if ( m_pDnsReq ) {
+        m_pDnsReq->close();
+        delete m_pDnsReq;
+        m_pDnsReq = NULL;
+    }
+}
+
+void SMTPClient::setServer(const Host& host) { //Setup request, make DNS Req if necessary
+    m_server = host;
 }
 
-void SMTPClient::init() //Create and setup socket if needed
-{
-  close(); //Remove previous elements
-  if(!m_closed) //Already opened
-    return;
-  m_nextState = SMTP_HELLO;
-  m_pTCPSocket = new TCPSocket;
-  m_pTCPSocket->setOnEvent(this, &SMTPClient::onTCPSocketEvent);
-  m_closed = false;
+void SMTPClient::setup(EmailMessage* pMessage) { //Setup request, make DNS Req if necessary
+
+    init(); //Initialize client in known state, create socket
+    m_pMessage = pMessage;
+    resetTimeout();
+
+    m_To = m_pMessage->m_lTo.begin(); // Point to first to recipient in TO list
+
+    //If port set to zero then use default port
+    if (!m_server.getPort()) {
+        m_server.setPort(SMTP_PORT);
+        DBG("Using default port %d\n", SMTP_PORT);
+    }
+
+    if (m_server.getIp().isNull()) {
+        //DNS query required
+        m_pDnsReq = new DNSRequest();
+        DBG("DNSRequest %p\r\n", m_pDnsReq);
+        m_pDnsReq->setOnReply(this, &SMTPClient::onDNSReply);
+        m_pDnsReq->resolve(&m_server);
+        return;
+    } else
+        connect();
+
+}
+
+void SMTPClient::connect() { //Start Connection
+    resetTimeout();
+    DBG("Connecting...\n");
+    m_pTCPSocket->connect(m_server);
 }
 
-void SMTPClient::close()
-{
-  if(m_closed)
-    return;
-  m_closed = true; //Prevent recursive calling or calling on an object being destructed by someone else
-  m_watchdog.detach();
-  m_pTCPSocket->resetOnEvent();
-  m_pTCPSocket->close();
-  delete m_pTCPSocket;
-  m_pTCPSocket = NULL;
-}
+void SMTPClient::onTCPSocketEvent(TCPSocketEvent e) {
+
+    DBG("Event %d in SMTPClient::onTCPSocketEvent()\n", e);
+
+    if (m_closed) {
+        DBG("WARN: Discarded\n");
+        return;
+    }
 
-int SMTPClient::rc(char* buf) //Parse return code
-{
-  int rc;
-  int len = sscanf(buf, "%d %*[^\r\n]\r\n", &rc);
-  if(len != 1)
-    return -1;
-  return rc;
+    switch (e) {
+        case TCPSOCKET_READABLE:
+            resetTimeout();
+            process(false);
+            break;
+        case TCPSOCKET_WRITEABLE:
+            resetTimeout();
+            process(true);
+            break;
+        case TCPSOCKET_CONTIMEOUT:
+        case TCPSOCKET_CONRST:
+        case TCPSOCKET_CONABRT:
+        case TCPSOCKET_ERROR:
+            DBG("Connection error in SMTP Client.\n");
+            close();
+            onResult(SMTP_DISC);
+            break;
+        case TCPSOCKET_DISCONNECTED:
+            if (m_state != SMTP_BYE) {
+                DBG("Connection error in SMTP Client.\n");
+                close();
+                onResult(SMTP_DISC);
+            }
+            break;
+    }
 }
 
-#define MIN(a,b) ((a)<(b))?(a):(b)
-void SMTPClient::process(bool moreData) //Main state-machine
-{
-  char buf[BUF_SIZE] = {0};
-  if(moreData)
-  {
-    if( m_nextState != SMTP_BODYMORE )
-    {
-      return;
+void SMTPClient::onDNSReply(DNSReply r) {
+    if (m_closed) {
+        DBG("WARN: Discarded\n");
+        return;
+    }
+
+    if ( r != DNS_FOUND ) {
+        DBG("Could not resolve hostname.\n");
+        close();
+        onResult(SMTP_DNS);
+        return;
     }
-  }
-  if(!moreData) //Receive next frame
-  {
-    m_pTCPSocket->recv(buf, BUF_SIZE - 1);
-  }
-  
-  IpAddr myIp(0,0,0,0);
-  string to;
-  int sendLen;
-  
-  DBG("In state %d", m_nextState);
+
+    DBG("DNS Resolved to %d.%d.%d.%d\n", m_server.getIp()[0], m_server.getIp()[1], m_server.getIp()[2], m_server.getIp()[3]);
+    //If no error, m_server has been updated by m_pDnsReq so we're set to go !
+    m_pDnsReq->close();
+    delete m_pDnsReq;
+    m_pDnsReq = NULL;
+    connect();
+}
+
+void SMTPClient::onResult(SMTPResult r) { //Called when exchange completed or on failure
+    if (m_pCbItem && m_pCbMeth)
+        (m_pCbItem->*m_pCbMeth)(r);
+    else if (m_pCb)
+        m_pCb(r);
+    m_blockingResult = r; //Blocking mode
+}
 
-  switch(m_nextState)
-  {
-  case SMTP_HELLO:
-    if( rc(buf) != 220 )
-      { close(); onResult(SMTP_PRTCL); return; }
-    myIp = Net::getDefaultIf()->getIp();
-    sprintf(buf, "HELO %d.%d.%d.%d\r\n", myIp[0], myIp[1], myIp[2], myIp[3]);
-    m_nextState = SMTP_FROM;
-    break;
-  case SMTP_FROM:
-    if( rc(buf) != 250 )
-      { close(); onResult(SMTP_PRTCL); return; }
-    sprintf(buf, "MAIL FROM:<%s>\r\n", m_pMessage->m_from.c_str());
-    break;
-  case SMTP_TO:
-    if( rc(buf) != 250 )
-      { close(); onResult(SMTP_PRTCL); return; }
-    to = m_pMessage->m_lTo.front();
-    sprintf(buf, "RCPT TO:<%s>\r\n", to.c_str());
-    m_pMessage->m_lTo.pop();
-    if(m_pMessage->m_lTo.empty())
-    {
-      m_nextState = SMTP_DATA;
-    }
-    break;  
-  case SMTP_DATA:
-    if( rc(buf) != 250 )
-      { close(); onResult(SMTP_PRTCL); return; }
-    sprintf(buf, "DATA\r\n");
-    break;
-  case SMTP_BODY:
-    if( rc(buf) != 354 )
-      { close(); onResult(SMTP_PRTCL); return; }  
-    m_nextState = SMTP_BODYMORE;
-  case SMTP_BODYMORE:
-    sendLen = 0;
-    if( m_posInMsg < m_pMessage->m_content.length() )
-    {
-      sendLen = MIN( (m_pMessage->m_content.length() - m_posInMsg), CHUNK_SIZE );
-      m_pTCPSocket->send( m_pMessage->m_content.c_str() + m_posInMsg, sendLen );
-      m_posInMsg += sendLen;
-    }
-    if( m_posInMsg == m_pMessage->m_content.length() )
-    {
-      sprintf(buf, "\r\n.\r\n"); //EOF
-      m_nextState = SMTP_EOF;
-    }
-    break;
-  case SMTP_EOF:
-    if( rc(buf) != 250 )
-      { close(); onResult(SMTP_PRTCL); return; }
-    sprintf(buf, "QUIT\r\n");
-    m_nextState = SMTP_BYE;
-    break;
-  case SMTP_BYE:
-    if( rc(buf) != 221 )
-      { close(); onResult(SMTP_PRTCL); return; }
+void SMTPClient::onTimeout() { //Connection has timed out
+    DBG("Timed out.\n");
     close();
-    onResult(SMTP_OK);
-    break;
-  }
-  
- if( m_nextState != SMTP_BODYMORE )
- {
-   m_pTCPSocket->send( buf, strlen(buf) );
- }
+    onResult(SMTP_TIMEOUT);
+}
+
+SMTPResult SMTPClient::blockingProcess() { //Called in blocking mode, calls Net::poll() until return code is available
+    //Disable callbacks
+    m_pCb = NULL;
+    m_pCbItem = NULL;
+    m_pCbMeth = NULL;
+    m_blockingResult = SMTP_PROCESSING;
+    do {
+        Net::poll();
+    } while (m_blockingResult == SMTP_PROCESSING);
+    Net::poll(); //Necessary for cleanup
+    return m_blockingResult;
+}
+
+int SMTPClient::rc(char* buf) { //Parse return code
+    int rc;
+    int len = sscanf(buf, "%d %*[^\r\n]\r\n", &rc);
+    if (len != 1)
+        return -1;
+    return rc;
+}
+
+bool SMTPClient::okPostAuthentication(int code) {
+    return (code == 250) || (code == 235);
 }
 
-void SMTPClient::setTimeout(int ms)
-{
-  m_timeout = 1000*ms;
-  resetTimeout();
-}
+void SMTPClient::process(bool writeable) { //Main state-machine
+
+    DBG("In state %d, writeable %d\n", m_state, writeable);
+
+    // If writeable but nothing to write then return
+    if (writeable && (m_state != SMTP_BODYMORE))
+        return;
+
+    // If not writeable then read
+    char buf[BUF_SIZE] = {0};
+    int responseCode = -1;
+    if (!writeable) {
+        bool firstBuf = true;
+        int read;
+        do { // read until nothing left but only process the response from first buffer
+            read = m_pTCPSocket->recv(buf, BUF_SIZE - 1);
+            if (firstBuf) {
+                m_response = string(buf);
+                responseCode = rc(buf);
+                firstBuf = false;
+                DBG("Response %d %d | %s", read, responseCode, buf);
+            }
+        } while (read > 0);
+    }
 
-void SMTPClient::resetTimeout()
-{
-  m_watchdog.detach();
-  m_watchdog.attach_us<SMTPClient>(this, &SMTPClient::onTimeout, m_timeout);
+    switch (m_state) {
+        case SMTP_HELLO:
+            if ( responseCode != 220 ) {
+                close();
+                onResult(SMTP_PRTCL);
+                return;
+            }
+            char* helloCommand;
+            if (m_auth == SMTP_AUTH_NONE) {
+                helloCommand = "HELO";
+                m_state = SMTP_FROM;
+            } else {
+                helloCommand = "EHLO";
+                m_state = SMTP_AUTH;
+            }
+            snprintf(buf, BUF_SIZE, "%s %s\r\n", helloCommand, m_heloDomain.c_str());
+            break;
+        case SMTP_AUTH:
+            if ( responseCode != 250 ) {
+                close();
+                onResult(SMTP_PRTCL);
+                return;
+            }
+            snprintf(buf, BUF_SIZE, "%s\r\n", encodePlainAuth().c_str());
+            m_state = SMTP_FROM;
+            break;
+        case SMTP_FROM:
+            if (!okPostAuthentication(responseCode)) {
+                close();
+                onResult(SMTP_PRTCL);
+                return;
+            }
+            snprintf(buf, BUF_SIZE, "MAIL FROM:<%s>\r\n", m_pMessage->m_from.c_str());
+            m_state = SMTP_TO;
+            break;
+        case SMTP_TO:
+            if ( responseCode != 250 ) {
+                close();
+                onResult(SMTP_PRTCL);
+                return;
+            }
+            snprintf(buf, BUF_SIZE, "RCPT TO:<%s>\r\n", (m_To++)->c_str());
+            if (m_To == m_pMessage->m_lTo.end())
+                m_state = SMTP_DATA;
+            break;
+        case SMTP_DATA:
+            if ( responseCode != 250 ) {
+                close();
+                onResult(SMTP_PRTCL);
+                return;
+            }
+            snprintf(buf, BUF_SIZE, "DATA\r\n");
+            m_state = SMTP_BODY;
+            break;
+        case SMTP_BODY:
+            if ( responseCode != 354 ) {
+                close();
+                onResult(SMTP_PRTCL);
+                return;
+            }
+            m_state = SMTP_BODYMORE;
+            buf[0] = '\0'; // clear buffer before carrying on into next state
+        case SMTP_BODYMORE:
+            if (strlen(buf) > 0) { // sending interrupted by a server response
+                close();
+                onResult(SMTP_PRTCL);
+                return;
+            }
+
+            if ( m_posInMsg < m_pMessage->m_content.length() ) { // if still something to send
+                int sendLen = 0;
+                while (sendLen < BUF_SIZE - 1) { // - 1 to allow room for extra dot or CR or LF
+                    char c = m_pMessage->m_content.at(m_posInMsg++);
+                    switch (c) { // thanks ExtraDotOutputStream.java (with extra check for naked CR)
+                        case '.':
+                            if (m_posInCRLF == 2) // add extra dot
+                                buf[sendLen++] = '.';
+                            m_posInCRLF = 0;
+                            break;
+                        case '\r':
+                            if (m_posInCRLF == 1) // two CR in a row, so insert an LF first
+                                buf[sendLen++] = '\n';
+                            m_posInCRLF = 1;
+                            break;
+                        case '\n':
+                            if (m_posInCRLF != 1) // convert naked LF to CRLF
+                                buf[sendLen++] = '\r';
+                            m_posInCRLF = 2;
+                            break;
+                        default:
+                            if (m_posInCRLF == 1) { // convert naked CR to CRLF
+                                buf[sendLen++] = '\n';
+                                m_posInCRLF = 2;
+                            } else
+                                m_posInCRLF = 0; // we're  no longer at the start of a line
+                            break;
+                    }
+                    buf[sendLen++] = c;
+                    if ( m_posInMsg == m_pMessage->m_content.length() )
+                        break;
+                }
+                m_pTCPSocket->send( buf, sendLen );
+                DBG("Sending %d bytes of processed message content\n", sendLen);
+            } else {
+                if (m_posInCRLF == 0)
+                    snprintf(buf, BUF_SIZE, "\r\n.\r\n");
+                else if (m_posInCRLF == 1)
+                    snprintf(buf, BUF_SIZE, "\n.\r\n");
+                else
+                    snprintf(buf, BUF_SIZE, ".\r\n");
+                m_state = SMTP_EOF;
+            }
+            break;
+        case SMTP_EOF:
+            if ( responseCode != 250 ) {
+                close();
+                onResult(SMTP_PRTCL);
+                return;
+            }
+            snprintf(buf, BUF_SIZE, "QUIT\r\n");
+            m_state = SMTP_BYE;
+            break;
+        case SMTP_BYE:
+            if ( responseCode != 221 ) {
+                close();
+                onResult(SMTP_PRTCL);
+                return;
+            }
+            close();
+            onResult(SMTP_OK);
+            return;
+    }
+
+    if ( m_state != SMTP_BODYMORE ) {
+        DBG("Sending | %s", buf);
+        m_pTCPSocket->send( buf, strlen(buf) );
+    }
+
 }
 
-void SMTPClient::onTimeout() //Connection has timed out
-{
-  close();
-  onResult(SMTP_TIMEOUT);
-}
-  
-void SMTPClient::onTCPSocketEvent(TCPSocketEvent e)
-{
-  switch(e)
-  {
-  case TCPSOCKET_READABLE:
-    resetTimeout();
-    process(false);
-    break;
-  case TCPSOCKET_WRITEABLE:
-    resetTimeout();
-    process(true);
-    break;
-  case TCPSOCKET_CONTIMEOUT:
-  case TCPSOCKET_CONRST:
-  case TCPSOCKET_CONABRT:
-  case TCPSOCKET_ERROR:
-    onResult(SMTP_DISC);
-    DBG("\r\nConnection error in SMTP Client.\r\n");
-    close();
-    break;
-  case TCPSOCKET_DISCONNECTED:
-    if(m_nextState != SMTP_BYE)
-    {
-      onResult(SMTP_DISC);
-      DBG("\r\nConnection error in SMTP Client.\r\n");
-      close();
-    }
-    break;
-  }
-}
-
-void SMTPClient::onResult(SMTPResult r) //Must be called by impl when the request completes
-{
-  if(m_pCbItem && m_pCbMeth)
-    (m_pCbItem->*m_pCbMeth)(r);
-}
-
-#endif
+string& SMTPClient::getLastResponse() { // Return last response set on result
+    return m_response;
+}
\ No newline at end of file
--- a/services/email/smtp/SMTPClient.h	Sun Nov 21 17:13:44 2010 +0000
+++ b/services/email/smtp/SMTPClient.h	Sat Nov 27 23:23:43 2010 +0000
@@ -1,17 +1,17 @@
 
 /*
-Copyright (c) 2010 Donatien Garnier (donatiengar [at] gmail [dot] com)
- 
+Copyright (c) 2010 Donatien Garnier (donatiengar [at] gmail [dot] com) y Segundo Equipo
+
 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:
- 
+
 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.
- 
+
 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@@ -21,6 +21,10 @@
 THE SOFTWARE.
 */
 
+/** \file
+SMTP Client header file
+*/
+
 #ifndef SMTP_CLIENT_H
 #define SMTP_CLIENT_H
 
@@ -28,82 +32,214 @@
 
 #include "core/net.h"
 #include "api/TCPSocket.h"
-#include "../emailMessage.h"
-
+#include "api/DNSRequest.h"
+#include "EmailMessage.h"
 #include "mbed.h"
 
-#define SMTP_REQUEST_TIMEOUT 5000
-
-enum SMTPResult
-{
-  SMTP_OK,
-  SMTP_PRTCL, //Protocol error
-  SMTP_TIMEOUT, //Connection timeout
-  SMTP_DISC //Disconnected 
+///SMTP client results
+enum SMTPResult {
+    SMTP_OK, ///<Success
+    SMTP_PROCESSING, ///<Processing
+    SMTP_DNS, ///<Could not resolve name
+    SMTP_PRTCL, ///<Protocol error
+    SMTP_TIMEOUT, ///<Connection timeout
+    SMTP_DISC ///<Disconnected
 };
 
-class SMTPClient /*: public NetService*/
-{
+///SMTP authentication
+enum SMTPAuth {
+    SMTP_AUTH_NONE, ///<No authentication
+    SMTP_AUTH_PLAIN ///<AUTH PLAIN authentication
+};
+#include "core/netservice.h"
+
+///A simple SMTP Client
+/**
+The SMTPClient is composed of:
+- The actual client (SMTPClient)
+- A class (EmailMessage) to hold the message addresses and content for sending
+*/
+class SMTPClient : protected NetService {
 public:
-  SMTPClient();
-  virtual ~SMTPClient();
-  
-  void setHost(const Host& host);
-  void send(EmailMessage* pMessage);
-  
-  class CDummy;
-  template<class T> 
-  //Linker bug : Must be defined here :(
-  void setOnResult( T* pItem, void (T::*pMethod)(SMTPResult) )
-  {
-    m_pCbItem = (CDummy*) pItem;
-    m_pCbMeth = (void (CDummy::*)(SMTPResult)) pMethod;
-  }
-  
-  void init(); //Create and setup socket if needed
-  void close();
-  
-private:
-  int rc(char* buf); //Return code
-  void process(bool moreData); //Main state-machine
+    ///Instantiates the SMTP client
+    SMTPClient();
+
+    ///Destructor for the SMTP client
+    virtual ~SMTPClient();
+
+    ///Full constructor for the SMTP client
+    /**
+    @param host : SMTP server host
+    @param heloDomain : domain name of client
+    @param user : username
+    @param password : password
+    @param auth : authentication type
+    */
+    SMTPClient(const Host& host, const char* heloDomain, const char* user, const char* password, SMTPAuth auth);
+
+    ///Set server host
+    /**
+    @param host : SMTP server host
+    */
+    void setServer(const Host& host);
+
+    ///Provides a plain authentication feature (Base64 encoded username and password)
+    /**
+    @param user : username
+    @param password : password
+    */
+    void setAuth(const char* user, const char* password); // Plain authentication
+
+    ///Turns off authentication
+    void clearAuth(); // Clear authentication
+
+    ///Set HELO domain (defaults to localhost if not set)
+    /**
+    @param heloDomain : domain name of client (strictly should be fully qualified domain name)
+    */
+    void setHeloDomain(const char* heloDomain);
+
+    //High Level setup functions
+    ///Sends the message (blocking)
+    /**
+    @param pMessage : pointer to a message
+
+    Blocks until completion
+    */
+    SMTPResult send(EmailMessage* pMessage); //Blocking
+
+    ///Sends the message (non blocking)
+    /**
+    @param pMessage : pointer to a message
+    @param pMethod : callback function
+
+    The function returns immediately and calls the callback on completion or error
+    */
+    SMTPResult send(EmailMessage* pMessage, void (*pMethod)(SMTPResult)); //Non blocking
+
+    ///Sends the message (non blocking)
+    /**
+    @param pMessage : pointer to a message
+    @param pItem : instance of class on which to execute the callback method
+    @param pMethod : callback method
+
+    The function returns immediately and calls the callback on completion or error
+    */
+    template<class T>
+    SMTPResult send(EmailMessage* pMessage, T* pItem, void (T::*pMethod)(SMTPResult)) { //Non blocking
+        setOnResult(pItem, pMethod);
+        doSend(pMessage);
+        return SMTP_PROCESSING;
+    }
+
+    ///Sends the message (non blocking)
+    /**
+    @param pMessage : pointer to a message
+
+    The function returns immediately and calls the previously set callback on completion or error
+    */
+    void doSend(EmailMessage* pMessage);
 
-  void setTimeout(int ms);
-  void resetTimeout();
-  
-  void onTimeout(); //Connection has timed out
-  void onTCPSocketEvent(TCPSocketEvent e);
-  void onResult(SMTPResult r); //Called when exchange completed or on failure
-  
-  EmailMessage* m_pMessage;
+    ///Setup the result callback
+    /**
+    @param pMethod : callback function
+    */
+    void setOnResult( void (*pMethod)(SMTPResult) );
+
+    ///Setup the result callback
+    /**
+    @param pItem : instance of class on which to execute the callback method
+    @param pMethod : callback method
+    */
+    class CDummy;
+    template<class T>
+    void setOnResult( T* pItem, void (T::*pMethod)(SMTPResult) ) {
+        m_pCb = NULL;
+        m_pCbItem = (CDummy*) pItem;
+        m_pCbMeth = (void (CDummy::*)(SMTPResult)) pMethod;
+    }
 
-  TCPSocket* m_pTCPSocket;
+    ///Setup timeout
+    /**
+    @param ms : time of connection inactivity in ms after which the request should timeout
+    */
+    void setTimeout(int ms);
+
+    ///Gets the last response from the server
+    string& getLastResponse();
+
+    virtual void poll(); //Called by NetServices
+
+protected:
+    int rc(char* buf); //Return code
+    void process(bool writeable); //Main state-machine
+
+    void resetTimeout();
+
+    void init();
+    void close();
+
+    void setup(EmailMessage* pMessage); //Setup request, make DNS Req if necessary
+    void connect(); //Start Connection
+
+    int  tryRead(); //Read data and try to feed output
+    void readData(); //Data has been read
+    void writeData(); //Data has been written & buf is free
 
-  enum SMTPStep
-  {
-    SMTP_HELLO,
-    SMTP_FROM,
-    SMTP_TO,
-    SMTP_DATA,
-    SMTP_BODY,
-    SMTP_BODYMORE,
-    SMTP_EOF,
-    SMTP_BYE
-  };
-  
-  SMTPStep m_nextState;
-  
-  CDummy* m_pCbItem;
-  void (CDummy::*m_pCbMeth)(SMTPResult);
-  
-  Timeout m_watchdog;
-  int m_timeout;
-  
-  int m_posInMsg;
-  
-  bool m_closed;
-  
-  Host m_host;
+    void onTCPSocketEvent(TCPSocketEvent e);
+    void onDNSReply(DNSReply r);
+    void onResult(SMTPResult r); //Called when exchange completed or on failure
+    void onTimeout(); //Connection has timed out
+
+    string encodePlainAuth(); // Encode plain authentication (username and password in based 64)
+    bool okPostAuthentication(int code); // True if server response is ok following authentication
+
+private:
+    SMTPResult blockingProcess(); //Called in blocking mode, calls Net::poll() until return code is available
+
+    CDummy* m_pCbItem;
+    void (CDummy::*m_pCbMeth)(SMTPResult);
+    void (*m_pCb)(SMTPResult);
+
+    TCPSocket* m_pTCPSocket;
+
+    Timer m_watchdog;
+    int m_timeout;
+
+    DNSRequest* m_pDnsReq;
+    Host m_server;
+
+    bool m_closed;
 
+    enum SMTPStep {
+        SMTP_HELLO,
+        SMTP_AUTH,
+        SMTP_FROM,
+        SMTP_TO,
+        SMTP_DATA,
+        SMTP_BODY,
+        SMTP_BODYMORE,
+        SMTP_EOF,
+        SMTP_BYE,
+        SMTP_CLOSED
+    };
+
+    SMTPStep m_state;
+
+    EmailMessage* m_pMessage;
+
+    int m_posInMsg;
+    int m_posInCRLF;
+
+    SMTPResult m_blockingResult; //Result if blocking mode
+    string m_response;
+    int m_responseCode;
+    string m_username;
+    string m_password;
+    SMTPAuth m_auth;
+    string m_heloDomain;
+
+    vector<string>::iterator m_To;
 };
 
-#endif
+#endif // SMTP_CLIENT_H
\ No newline at end of file
--- a/services/http/util/base64.cpp	Sun Nov 21 17:13:44 2010 +0000
+++ b/services/http/util/base64.cpp	Sat Nov 27 23:23:43 2010 +0000
@@ -30,7 +30,7 @@
 
 #include <string.h>
 
-unsigned int base64enc_len(const char *str) {
+unsigned int base64enc_len(const char* str) {
   return (((strlen(str)-1)/3)+1)<<2;
 }
 
--- a/services/http/util/base64.h	Sun Nov 21 17:13:44 2010 +0000
+++ b/services/http/util/base64.h	Sat Nov 27 23:23:43 2010 +0000
@@ -33,7 +33,7 @@
 
 //Originaly from Rolf's iputil.h
 
-unsigned int base64enc_len(const char *str);
+unsigned int base64enc_len(const char* str);
 
 void base64enc(const char *input, unsigned int length, char *output);
 
@@ -44,9 +44,14 @@
 class Base64
 {
 public:
+  static unsigned int base64enc_len(const string& str)
+  {
+    return (((str.length()-1)/3)+1)<<2;
+  }
+
   static string encode(const string& str)
   {
-    char* out = new char[ base64enc_len(str.c_str()) ];
+    char* out = new char[ base64enc_len(str) ];
     base64enc(str.c_str(), str.length(), out);
     string res(out);
     delete[] out;