diff options
author | Vadim Dashevskiy <watcherhd@gmail.com> | 2012-06-06 20:17:58 +0000 |
---|---|---|
committer | Vadim Dashevskiy <watcherhd@gmail.com> | 2012-06-06 20:17:58 +0000 |
commit | ab92c2a5cd5427bf8a33d06afdb64b88d2d640ed (patch) | |
tree | fc82f068ad7bf8e141b6148f2ff191eab56e1f5a /protocols/Twitter | |
parent | 441daff7dfc4cd80075cfbec3345192aab4353b5 (diff) |
Twitter updated
git-svn-id: http://svn.miranda-ng.org/main/trunk@337 1316c22d-e87f-b044-9b9b-93d7a3e3ba9c
Diffstat (limited to 'protocols/Twitter')
92 files changed, 14339 insertions, 1599 deletions
diff --git a/protocols/Twitter/Base64Coder.cpp b/protocols/Twitter/Base64Coder.cpp new file mode 100644 index 0000000000..4944034c3e --- /dev/null +++ b/protocols/Twitter/Base64Coder.cpp @@ -0,0 +1,319 @@ +// Base64Coder.cpp: implementation of the Base64Coder class.
+// http://support.microsoft.com/kb/191239
+//////////////////////////////////////////////////////////////////////
+
+#include "Base64Coder.h"
+
+// Digits...
+static char Base64Digits[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
+
+BOOL Base64Coder::m_Init = FALSE;
+char Base64Coder::m_DecodeTable[256];
+
+#ifndef PAGESIZE
+#define PAGESIZE 4096
+#endif
+
+#ifndef ROUNDTOPAGE
+#define ROUNDTOPAGE(a) (((a/4096)+1)*4096)
+#endif
+
+//////////////////////////////////////////////////////////////////////
+// Construction/Destruction
+//////////////////////////////////////////////////////////////////////
+
+Base64Coder::Base64Coder()
+: m_pDBuffer(NULL),
+ m_pEBuffer(NULL),
+ m_nDBufLen(0),
+ m_nEBufLen(0)
+{
+
+}
+
+Base64Coder::~Base64Coder()
+{
+ if(m_pDBuffer != NULL)
+ delete [] m_pDBuffer;
+
+ if(m_pEBuffer != NULL)
+ delete [] m_pEBuffer;
+}
+
+LPCSTR Base64Coder::DecodedMessage() const
+{
+ return (LPCSTR) m_pDBuffer;
+}
+
+LPCSTR Base64Coder::EncodedMessage() const
+{
+ return (LPCSTR) m_pEBuffer;
+}
+
+void Base64Coder::AllocEncode(DWORD nSize)
+{
+ if(m_nEBufLen < nSize)
+ {
+ if(m_pEBuffer != NULL)
+ delete [] m_pEBuffer;
+
+ m_nEBufLen = ROUNDTOPAGE(nSize);
+ m_pEBuffer = new BYTE[m_nEBufLen];
+ }
+
+ ::ZeroMemory(m_pEBuffer, m_nEBufLen);
+ m_nEDataLen = 0;
+}
+
+void Base64Coder::AllocDecode(DWORD nSize)
+{
+ if(m_nDBufLen < nSize)
+ {
+ if(m_pDBuffer != NULL)
+ delete [] m_pDBuffer;
+
+ m_nDBufLen = ROUNDTOPAGE(nSize);
+ m_pDBuffer = new BYTE[m_nDBufLen];
+ }
+
+ ::ZeroMemory(m_pDBuffer, m_nDBufLen);
+ m_nDDataLen = 0;
+}
+
+void Base64Coder::SetEncodeBuffer(const PBYTE pBuffer, DWORD nBufLen)
+{
+ DWORD i = 0;
+
+ AllocEncode(nBufLen);
+ while(i < nBufLen)
+ {
+ if(!_IsBadMimeChar(pBuffer[i]))
+ {
+ m_pEBuffer[m_nEDataLen] = pBuffer[i];
+ m_nEDataLen++;
+ }
+
+ i++;
+ }
+}
+
+void Base64Coder::SetDecodeBuffer(const PBYTE pBuffer, DWORD nBufLen)
+{
+ AllocDecode(nBufLen);
+ ::CopyMemory(m_pDBuffer, pBuffer, nBufLen);
+ m_nDDataLen = nBufLen;
+}
+
+void Base64Coder::Encode(const PBYTE pBuffer, DWORD nBufLen)
+{
+ SetDecodeBuffer(pBuffer, nBufLen);
+ AllocEncode(nBufLen * 2);
+
+ TempBucket Raw;
+ DWORD nIndex = 0;
+
+ while((nIndex + 3) <= nBufLen)
+ {
+ Raw.Clear();
+ ::CopyMemory(&Raw, m_pDBuffer + nIndex, 3);
+ Raw.nSize = 3;
+ _EncodeToBuffer(Raw, m_pEBuffer + m_nEDataLen);
+ nIndex += 3;
+ m_nEDataLen += 4;
+ }
+
+ if(nBufLen > nIndex)
+ {
+ Raw.Clear();
+ Raw.nSize = (BYTE) (nBufLen - nIndex);
+ ::CopyMemory(&Raw, m_pDBuffer + nIndex, nBufLen - nIndex);
+ _EncodeToBuffer(Raw, m_pEBuffer + m_nEDataLen);
+ m_nEDataLen += 4;
+ }
+}
+
+/*void Base64Coder::Encode(LPCSTR szMessage)
+{
+ if(szMessage != NULL)
+ Base64Coder::Encode((const PBYTE)szMessage, strlen(szMessage));
+}*/
+
+void Base64Coder::Decode(const PBYTE pBuffer, DWORD dwBufLen)
+{
+ if(!Base64Coder::m_Init)
+ _Init();
+
+ SetEncodeBuffer(pBuffer, dwBufLen);
+
+ AllocDecode(dwBufLen);
+
+ TempBucket Raw;
+
+ DWORD nIndex = 0;
+
+ while((nIndex + 4) <= m_nEDataLen)
+ {
+ Raw.Clear();
+ Raw.nData[0] = Base64Coder::m_DecodeTable[m_pEBuffer[nIndex]];
+ Raw.nData[1] = Base64Coder::m_DecodeTable[m_pEBuffer[nIndex + 1]];
+ Raw.nData[2] = Base64Coder::m_DecodeTable[m_pEBuffer[nIndex + 2]];
+ Raw.nData[3] = Base64Coder::m_DecodeTable[m_pEBuffer[nIndex + 3]];
+
+ if(Raw.nData[2] == 255)
+ Raw.nData[2] = 0;
+ if(Raw.nData[3] == 255)
+ Raw.nData[3] = 0;
+
+ Raw.nSize = 4;
+ _DecodeToBuffer(Raw, m_pDBuffer + m_nDDataLen);
+ nIndex += 4;
+ m_nDDataLen += 3;
+ }
+
+ // If nIndex < m_nEDataLen, then we got a decode message without padding.
+ // We may want to throw some kind of warning here, but we are still required
+ // to handle the decoding as if it was properly padded.
+ if(nIndex < m_nEDataLen)
+ {
+ Raw.Clear();
+ for(DWORD i = nIndex; i < m_nEDataLen; i++)
+ {
+ Raw.nData[i - nIndex] = Base64Coder::m_DecodeTable[m_pEBuffer[i]];
+ Raw.nSize++;
+ if(Raw.nData[i - nIndex] == 255)
+ Raw.nData[i - nIndex] = 0;
+ }
+
+ _DecodeToBuffer(Raw, m_pDBuffer + m_nDDataLen);
+ m_nDDataLen += (m_nEDataLen - nIndex);
+ }
+}
+
+/*void Base64Coder::Decode(LPCSTR szMessage)
+{
+ if(szMessage != NULL)
+ Base64Coder::Decode((const PBYTE)szMessage, strlen(szMessage));
+}*/
+
+DWORD Base64Coder::_DecodeToBuffer(const TempBucket &Decode, PBYTE pBuffer)
+{
+ TempBucket Data;
+ DWORD nCount = 0;
+
+ _DecodeRaw(Data, Decode);
+
+ for(int i = 0; i < 3; i++)
+ {
+ pBuffer[i] = Data.nData[i];
+ if(pBuffer[i] != 255)
+ nCount++;
+ }
+
+ return nCount;
+}
+
+
+void Base64Coder::_EncodeToBuffer(const TempBucket &Decode, PBYTE pBuffer)
+{
+ TempBucket Data;
+
+ _EncodeRaw(Data, Decode);
+
+ for(int i = 0; i < 4; i++)
+ pBuffer[i] = Base64Digits[Data.nData[i]];
+
+ switch(Decode.nSize)
+ {
+ case 1:
+ pBuffer[2] = '=';
+ case 2:
+ pBuffer[3] = '=';
+ }
+}
+
+void Base64Coder::_DecodeRaw(TempBucket &Data, const TempBucket &Decode)
+{
+ BYTE nTemp;
+
+ Data.nData[0] = Decode.nData[0];
+ Data.nData[0] <<= 2;
+
+ nTemp = Decode.nData[1];
+ nTemp >>= 4;
+ nTemp &= 0x03;
+ Data.nData[0] |= nTemp;
+
+ Data.nData[1] = Decode.nData[1];
+ Data.nData[1] <<= 4;
+
+ nTemp = Decode.nData[2];
+ nTemp >>= 2;
+ nTemp &= 0x0F;
+ Data.nData[1] |= nTemp;
+
+ Data.nData[2] = Decode.nData[2];
+ Data.nData[2] <<= 6;
+ nTemp = Decode.nData[3];
+ nTemp &= 0x3F;
+ Data.nData[2] |= nTemp;
+}
+
+void Base64Coder::_EncodeRaw(TempBucket &Data, const TempBucket &Decode)
+{
+ BYTE nTemp;
+
+ Data.nData[0] = Decode.nData[0];
+ Data.nData[0] >>= 2;
+
+ Data.nData[1] = Decode.nData[0];
+ Data.nData[1] <<= 4;
+ nTemp = Decode.nData[1];
+ nTemp >>= 4;
+ Data.nData[1] |= nTemp;
+ Data.nData[1] &= 0x3F;
+
+ Data.nData[2] = Decode.nData[1];
+ Data.nData[2] <<= 2;
+
+ nTemp = Decode.nData[2];
+ nTemp >>= 6;
+
+ Data.nData[2] |= nTemp;
+ Data.nData[2] &= 0x3F;
+
+ Data.nData[3] = Decode.nData[2];
+ Data.nData[3] &= 0x3F;
+}
+
+BOOL Base64Coder::_IsBadMimeChar(BYTE nData)
+{
+ switch(nData)
+ {
+ case '\r': case '\n': case '\t': case ' ' :
+ case '\b': case '\a': case '\f': case '\v':
+ return TRUE;
+ default:
+ return FALSE;
+ }
+}
+
+void Base64Coder::_Init()
+{ // Initialize Decoding table.
+
+ int i;
+
+ for(i = 0; i < 256; i++)
+ Base64Coder::m_DecodeTable[i] = -2;
+
+ for(i = 0; i < 64; i++)
+ {
+ Base64Coder::m_DecodeTable[Base64Digits[i]] = i;
+ Base64Coder::m_DecodeTable[Base64Digits[i]|0x80] = i;
+ }
+
+ Base64Coder::m_DecodeTable['='] = -1;
+ Base64Coder::m_DecodeTable['='|0x80] = -1;
+
+ Base64Coder::m_Init = TRUE;
+}
+
diff --git a/protocols/Twitter/Base64Coder.h b/protocols/Twitter/Base64Coder.h new file mode 100644 index 0000000000..d65868070e --- /dev/null +++ b/protocols/Twitter/Base64Coder.h @@ -0,0 +1,69 @@ +// Base64Coder.h: interface for the Base64Coder class.
+// http://support.microsoft.com/kb/191239
+//////////////////////////////////////////////////////////////////////
+
+#if !defined(AFX_BASE64CODER_H__B2E45717_0625_11D2_A80A_00C04FB6794C__INCLUDED_)
+#define AFX_BASE64CODER_H__B2E45717_0625_11D2_A80A_00C04FB6794C__INCLUDED_
+
+#if _MSC_VER >= 1000
+#pragma once
+#endif // _MSC_VER >= 1000
+
+#ifdef _AFXDLL
+ #include <afx.h>
+ typedef CString String;
+#else
+ #include <windows.h>
+ #include <string>
+ typedef std::string String;
+#endif
+
+class Base64Coder
+{
+ // Internal bucket class.
+ class TempBucket
+ {
+ public:
+ BYTE nData[4];
+ BYTE nSize;
+ void Clear() { ::ZeroMemory(nData, 4); nSize = 0; };
+ };
+
+ PBYTE m_pDBuffer;
+ PBYTE m_pEBuffer;
+ DWORD m_nDBufLen;
+ DWORD m_nEBufLen;
+ DWORD m_nDDataLen;
+ DWORD m_nEDataLen;
+
+public:
+ Base64Coder();
+ virtual ~Base64Coder();
+
+public:
+ virtual void Encode(const PBYTE, DWORD);
+ virtual void Decode(const PBYTE, DWORD);
+ //virtual void Encode(LPCSTR sMessage);
+ //virtual void Decode(LPCSTR sMessage);
+
+ virtual LPCSTR DecodedMessage() const;
+ virtual LPCSTR EncodedMessage() const;
+
+ virtual void AllocEncode(DWORD);
+ virtual void AllocDecode(DWORD);
+ virtual void SetEncodeBuffer(const PBYTE pBuffer, DWORD nBufLen);
+ virtual void SetDecodeBuffer(const PBYTE pBuffer, DWORD nBufLen);
+
+protected:
+ virtual void _EncodeToBuffer(const TempBucket &Decode, PBYTE pBuffer);
+ virtual ULONG _DecodeToBuffer(const TempBucket &Decode, PBYTE pBuffer);
+ virtual void _EncodeRaw(TempBucket &, const TempBucket &);
+ virtual void _DecodeRaw(TempBucket &, const TempBucket &);
+ virtual BOOL _IsBadMimeChar(BYTE);
+
+ static char m_DecodeTable[256];
+ static BOOL m_Init;
+ void _Init();
+};
+
+#endif // !defined(AFX_BASE64CODER_H__B2E45717_0625_11D2_A80A_00C04FB6794C__INCLUDED_)
diff --git a/protocols/Twitter/Debug.c b/protocols/Twitter/Debug.c new file mode 100644 index 0000000000..cfc5c7fd4f --- /dev/null +++ b/protocols/Twitter/Debug.c @@ -0,0 +1,129 @@ +/*
+
+Copyright (c) 2010 Brook Miles
+
+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.
+
+*/
+
+#define WIN32_LEAN_AND_MEAN
+#include <tchar.h>
+#include <windows.h>
+#include <strsafe.h>
+#include <stdlib.h>
+
+#include "Debug.h"
+
+#define MESSAGEBOXFMT_BUF_SIZE 256
+
+#define DEBUG_REPORT_BUF_SIZE 128
+#define DEBUG_ABORT_CODE 0xBADD061E
+
+#define DEBUG_TRACE_BUF_SIZE 1024
+#define DEBUG_TRACE_FMT_SIZE 128
+
+#define SIZEOF(x) (sizeof(x)/sizeof(*x))
+
+UINT MessageBoxFmt(HWND hwnd, LPCTSTR pszTextFmt, LPCTSTR pszTitle, UINT uType, ...)
+{
+ TCHAR buf[MESSAGEBOXFMT_BUF_SIZE];
+ va_list args;
+ va_start(args, uType);
+ _vsntprintf_s(buf, SIZEOF(buf), _TRUNCATE, pszTextFmt, args);
+ va_end(args);
+ return MessageBox(hwnd, buf, pszTitle, uType);
+}
+
+#if defined(_DEBUG)
+/////////////////////////////////////////////////////////////////////////////
+// _DebugReport is used by the ASSERTE macro. Since the preprocessor
+// constants __FILE__ and __LINE__ are always ANSI, it takes LPCSTR
+// instead of LPCTSTR, and then converts to wide strings.
+//
+
+int _DebugReport(LPCSTR pszFile, int iLine, LPCSTR pszExpr, UINT gle, BOOL bConsoleOnly)
+{
+ char buf[DEBUG_REPORT_BUF_SIZE];
+ wchar_t wbuf[DEBUG_REPORT_BUF_SIZE];
+ wchar_t wbufTitle[DEBUG_REPORT_BUF_SIZE];
+ UINT ret;
+
+ size_t tmp = 0;
+
+ _snprintf_s(buf, DEBUG_REPORT_BUF_SIZE, _TRUNCATE, "Assertion Failed! (0x%08X)", gle);
+ mbstowcs_s(&tmp, wbufTitle, SIZEOF(wbufTitle), buf, _TRUNCATE);
+
+ _snprintf_s(buf, DEBUG_REPORT_BUF_SIZE, _TRUNCATE, "%s:%d\r\n%s",
+ strrchr(pszFile, '\\') + 1, iLine, pszExpr);
+ mbstowcs_s(&tmp, wbuf, SIZEOF(wbuf), buf, _TRUNCATE);
+
+ OutputDebugString(wbufTitle);
+ OutputDebugString(_T("\r\n"));
+ OutputDebugString(wbuf);
+ OutputDebugString(_T("\r\n"));
+
+ if(!bConsoleOnly)
+ {
+ ret = MessageBox(NULL, wbuf, wbufTitle, MB_ICONERROR | MB_ABORTRETRYIGNORE);
+ if(ret == IDABORT)
+ ExitThread(DEBUG_ABORT_CODE);
+ return (ret == IDRETRY);
+ }
+ else
+ {
+ return TRUE;
+ }
+}
+
+void _TRACE(LPCSTR fmt, ...)
+{
+ int len;
+ TCHAR buf[DEBUG_TRACE_BUF_SIZE + 3] = _T("");
+ va_list va;
+
+#ifndef UNICODE
+ char* tfmt = fmt;
+#else
+ wchar_t tfmt[DEBUG_TRACE_FMT_SIZE];
+ size_t tmp = 0;
+ mbstowcs_s(&tmp, tfmt, SIZEOF(tfmt), fmt, _TRUNCATE);
+#endif
+
+ va_start(va, fmt);
+ len = _vsntprintf_s(buf, SIZEOF(buf), _TRUNCATE, tfmt, va);
+ va_end(va);
+
+ if(len >= -1)
+ {
+ if(len == -1)
+ {
+ len = DEBUG_TRACE_BUF_SIZE;
+ }
+ _tcscpy_s(&buf[len], SIZEOF(buf) - len, _T("\r\n"));
+ }
+ else
+ {
+ _tcscpy_s(buf, SIZEOF(buf), _T("_DEBUG FORMATTING ERROR\r\n"));
+ }
+
+ //_tprintf(buf);
+ OutputDebugString(buf);
+}
+
+#endif//defined(_DEBUG)
\ No newline at end of file diff --git a/protocols/Twitter/Debug.h b/protocols/Twitter/Debug.h new file mode 100644 index 0000000000..b8814193f5 --- /dev/null +++ b/protocols/Twitter/Debug.h @@ -0,0 +1,75 @@ +/*
+
+Copyright (c) 2010 Brook Miles
+
+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 _DEBUG_H_INCLUDED_
+#define _DEBUG_H_INCLUDED_
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/////////////////////////////////////////////////////////////////////////////
+// MessageBoxFmt
+
+UINT MessageBoxFmt(HWND hwnd, LPCTSTR pszTextFmt, LPCTSTR pszTitle, UINT uType, ...);
+
+/////////////////////////////////////////////////////////////////////////////
+// DebugReport
+
+#ifdef _DEBUG
+ #ifdef ASSERT_NO_BREAK
+ int _DebugReport(LPCSTR pszFile, int iLine, LPCSTR pszExpr, UINT gle, BOOL bConsoleOnly);
+ #ifdef _ASSERTE
+ #undef _ASSERTE
+ #endif
+ #define _ASSERTE(x) if(!(x) && _DebugReport(__FILE__, __LINE__, #x, GetLastError(), true)) while(0)
+ #define _ASSERTC(x) if(!(x) && _DebugReport(__FILE__, __LINE__, #x, GetLastError(), true)) while(0)
+ #else
+ int _DebugReport(LPCSTR pszFile, int iLine, LPCSTR pszExpr, UINT gle, BOOL bConsoleOnly);
+ #ifdef _ASSERTE
+ #undef _ASSERTE
+ #endif
+ #define _ASSERTE(x) if(!(x) && _DebugReport(__FILE__, __LINE__, #x, GetLastError(), false)) DebugBreak()
+ #define _ASSERTC(x) if(!(x) && _DebugReport(__FILE__, __LINE__, #x, GetLastError(), true)) DebugBreak()
+ #endif
+#else
+ #ifndef _ASSERTE
+ #define _ASSERTE(x)
+ #endif
+ #define _ASSERTC(x)
+#endif
+
+/////////////////////////////////////////////////////////////////////////////
+// DebugTrace
+
+#if defined(_DEBUG)
+ void _TRACE(LPCSTR fmt, ...);
+#else
+ __inline void _TRACE(LPCSTR fmt, ...) {}
+#endif//defined(_DEBUG)
+
+
+#ifdef __cplusplus
+}
+#endif
+#endif//_DEBUG_H_INCLUDED_
diff --git a/protocols/Twitter/StringConv.cpp b/protocols/Twitter/StringConv.cpp new file mode 100644 index 0000000000..c0e4f9221c --- /dev/null +++ b/protocols/Twitter/StringConv.cpp @@ -0,0 +1,87 @@ +/*
+
+Copyright (c) 2010 Brook Miles
+
+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 <windows.h>
+#include <string>
+#include "StringConv.h"
+
+std::string WideToMB(const std::wstring& str, UINT codePage)
+{
+ std::string ret;
+ if(str.length() > 0)
+ {
+ DWORD mbChars = WideCharToMultiByte(codePage, 0, str.c_str(), -1, NULL, 0, NULL, NULL);
+ _ASSERTE(mbChars > 0);
+ if(mbChars > 0)
+ {
+ char* buf = new char[mbChars];
+ _ASSERTE( buf != NULL );
+ if( buf != NULL )
+ {
+ ZeroMemory(buf, mbChars);
+
+ DWORD charsConverted = WideCharToMultiByte(codePage, 0, str.c_str(), -1, buf, mbChars, NULL, NULL);
+ _ASSERTE( charsConverted > 0 );
+ _ASSERTE( charsConverted <= mbChars );
+
+ buf[mbChars - 1] = 0;
+ ret = buf;
+
+ delete[] buf;
+ }
+ }
+ }
+ return ret;
+}
+
+std::wstring MBToWide(const std::string& str, UINT codePage)
+{
+ std::wstring ret;
+ if(str.length() > 0)
+ {
+ DWORD wChars = MultiByteToWideChar(codePage, 0, str.c_str(), -1, NULL, 0);
+ _ASSERTE(wChars > 0);
+ if(wChars > 0)
+ {
+ wchar_t* buf = new wchar_t[wChars];
+ _ASSERTE( buf != NULL );
+ if( buf != NULL )
+ {
+ size_t bytesNeeded = sizeof(wchar_t)*wChars;
+ ZeroMemory(buf, bytesNeeded);
+
+ DWORD charsConverted = MultiByteToWideChar(codePage, 0, str.c_str(), -1, buf, wChars);
+ _ASSERTE( charsConverted > 0 );
+ _ASSERTE( charsConverted <= wChars );
+
+ buf[wChars - 1] = 0;
+ ret = buf;
+
+ delete[] buf;
+ }
+ }
+ }
+ return ret;
+}
+
diff --git a/protocols/Twitter/StringConv.h b/protocols/Twitter/StringConv.h new file mode 100644 index 0000000000..c5266f574d --- /dev/null +++ b/protocols/Twitter/StringConv.h @@ -0,0 +1,58 @@ +/*
+
+Copyright (c) 2010 Brook Miles
+
+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 <windows.h>
+
+#ifndef StringConv_h__
+#define StringConv_h__
+
+#pragma once
+
+
+std::string WideToMB(const std::wstring& str, UINT codePage = CP_ACP);
+std::wstring MBToWide(const std::string& str, UINT codePage = CP_ACP);
+
+inline std::string WideToUTF8(const std::wstring& str) { return WideToMB(str, CP_UTF8); }
+inline std::wstring UTF8ToWide(const std::string& str) { return MBToWide(str, CP_UTF8); }
+
+inline std::string ANSIToUTF8(const std::string& str, UINT codePage = CP_ACP) { return WideToUTF8(MBToWide(str, codePage)); }
+inline std::string UTF8ToANSI(const std::string& str, UINT codePage = CP_ACP) { return WideToMB(UTF8ToWide(str), codePage); }
+
+#ifdef _UNICODE
+#define TCHARToUTF8 WideToUTF8
+#define UTF8ToTCHAR UTF8ToWide
+#define TCHARToWide
+#define WideToTCHAR
+#define TCHARToMB WideToMB
+#define MBToTCHAR MBToWide
+#else
+#define TCHARToUTF8 ANSIToUTF8
+#define UTF8ToTCHAR UTF8ToANSI
+#define TCHARToWide MBToWide
+#define WideToTCHAR WideToMB
+#define TCHARToMB
+#define MBToTCHAR
+#endif
+
+#endif // StringConv_h__
diff --git a/protocols/Twitter/StringUtil.cpp b/protocols/Twitter/StringUtil.cpp new file mode 100644 index 0000000000..a395b67fa7 --- /dev/null +++ b/protocols/Twitter/StringUtil.cpp @@ -0,0 +1,111 @@ +/*
+
+Copyright (c) 2010 Brook Miles
+
+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 "stdafx.h"
+
+void Split(const tstring& str, std::vector<tstring>& out, TCHAR sep, bool includeEmpty)
+{
+ unsigned start = 0;
+ unsigned end = 0;
+
+ while(true)
+ {
+ if(end == str.size() || str[end] == sep)
+ {
+ if(end > start || includeEmpty)
+ {
+ out.push_back(str.substr(start, end - start));
+ }
+
+ if(end == str.size())
+ {
+ break;
+ }
+
+ ++end;
+ start = end;
+ }
+ else
+ {
+ ++end;
+ }
+ }
+}
+
+tstring GetWord(const tstring& str, unsigned index, bool getRest)
+{
+ unsigned start = 0;
+ unsigned end = 0;
+
+ unsigned count = 0;
+
+ while(true)
+ {
+ if(end == str.size() || str[end] == _T(' '))
+ {
+ if(end > start)
+ {
+ if(count == index)
+ {
+ if(getRest)
+ {
+ return str.substr(start);
+ }
+ else
+ {
+ return str.substr(start, end - start);
+ }
+ }
+ ++count;
+ }
+
+ if(end == str.size())
+ {
+ break;
+ }
+
+ ++end;
+ start = end;
+ }
+ else
+ {
+ ++end;
+ }
+ }
+ return _T("");
+}
+
+// takes a pointer to a string, and does an inplace replace of all the characters "from" found
+// within the string with "to". returns the pointer to the string which is kinda silly IMO
+std::string& replaceAll(std::string& context, const std::string& from, const std::string& to)
+{
+ size_t lookHere = 0;
+ size_t foundHere;
+ while((foundHere = context.find(from, lookHere)) != std::string::npos)
+ {
+ context.replace(foundHere, from.size(), to);
+ lookHere = foundHere + to.size();
+ }
+ return context;
+}
diff --git a/protocols/Twitter/StringUtil.h b/protocols/Twitter/StringUtil.h new file mode 100644 index 0000000000..902e262c02 --- /dev/null +++ b/protocols/Twitter/StringUtil.h @@ -0,0 +1,39 @@ +/*
+
+Copyright (c) 2010 Brook Miles
+
+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 _STRINGUTIL_H_INCLUDED_
+#define _STRINGUTIL_H_INCLUDED_
+
+void Split(const tstring& str, std::vector<tstring>& out, TCHAR sep, bool includeEmpty);
+tstring GetWord(const tstring& str, unsigned index, bool getRest = false);
+
+std::string& replaceAll(std::string& context, const std::string& from, const std::string& to);
+
+
+inline bool Compare(const tstring& one, const tstring& two, bool caseSensitive)
+{
+ return caseSensitive ? (one == two) : (_tcsicmp(one.c_str(), two.c_str()) == 0);
+}
+
+#endif//_STRINGUTIL_H_INCLUDED_
diff --git a/protocols/Twitter/betaVersion.html b/protocols/Twitter/betaVersion.html new file mode 100644 index 0000000000..13f1601e8e --- /dev/null +++ b/protocols/Twitter/betaVersion.html @@ -0,0 +1 @@ +Twitter 1.0.0.0
\ No newline at end of file diff --git a/protocols/Twitter/changelog.html b/protocols/Twitter/changelog.html new file mode 100644 index 0000000000..44a157bd7a --- /dev/null +++ b/protocols/Twitter/changelog.html @@ -0,0 +1,40 @@ +<html>
+ <head>
+ <title>Miranda Twitter Changelog!</title>
+ </head>
+ <body>
+ <h2>0.0.9.7</h2>
+ - Major options cleanup<br>
+ - Default group now has a GUI in the options/accounts<br>
+ - stopped twitter from going offline so much (needs 3 network fails in a row before it will go offline)<br>
+ - open source! code is super messy. please feel free to post if you have any questions. the open source code will not compile with the official OAUTH keys!<br>
+ - added code to stop tweets becoming messages. you will need to add a "tweetToMsg" variable as type BYTE to the db, and set to 0 if you want tweets to NOT become messages.<br>
+ - fixed single % signs from disappearing in the group chat, and also stopped "%" becoming "%%" if you typed it into the group chat input area to tweet.<br>
+ - fixed long native retweets from being truncated<br>
+ - code cleanup, minor fixes<br>
+ <h2>0.0.9.6</h2>
+ - Updater now working<br>
+ - Basic "auto" group support. If you want to have twitter contacts auto added to a group, before you connect to twitter (but after you create the account in miranda) create a "DefaultGroup" string key in the database and make the value the group you want twitter contacts to be automatically added to. This won't copy existing contacts to the group, just newly added ones.<br>
+ - Other minor fixes<br>
+ <h2>0.0.9.5</h2>
+- Retweets will now appear in the timeline!<br>
+- Fixed group chat highlighting when YOU make a tweet<br>
+- Stopped self contact joining the clist<br>
+<h2>0.0.9.4</h2>
+- Fixed duplicate contacts<br>
+<h2>0.0.9.3</h2>
+- Fixed connection problems<br>
+- Hopefully fixed unicode problems, please let me know!<br>
+- Cleaned up some code, got rid of the password input field as this isn't required with OAuth. If you're security conscious feel free to delete the password field from the database. i'll add some code to do this automatically next time.<br>
+<h2>0.0.9.2</h2>
+- DMs now actually work.<br>
+- your username should appear in the chat window now.. thx Thief<br>
+<h2>0.0.9.1</h2>
+- Tweeting (and posting DMs?) now works (thanks Borkra!)<br>
+- Removed dependencies on WinInet, so this now an actual Release build. yay<br>
+- seem to have broken proxy support.. which is weird. working on it.<br>
+<h2>0.0.9.0</h2>
+- OAuth used for authorisation now<br>
+- I have broken many things, and desecrated Dentist's once beautiful code. i think at one point i added a "2" to a variable name because i couldn't think of a better name. So sorry :(<br>
+</body>
+</html>
diff --git a/protocols/Twitter/chat.cpp b/protocols/Twitter/chat.cpp index 4e659c2aa8..8117f4371c 100644 --- a/protocols/Twitter/chat.cpp +++ b/protocols/Twitter/chat.cpp @@ -3,19 +3,18 @@ Copyright © 2009 Jim Porter This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
-the Free Software Foundation, either version 2 of the License, or
+the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
-This program is distributed in the hope that it will be useful,
+This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
-along with this program. If not, see <http://www.gnu.org/licenses/>.
+along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
-#include "common.h"
#include "proto.h"
#include <set>
@@ -31,42 +30,65 @@ void TwitterProto::UpdateChat(const twitter_user &update) gce.pDest = &gcd;
gce.dwFlags = GC_TCHAR|GCEF_ADDTOLOG;
gce.pDest = &gcd;
- gce.ptszUID = mir_a2t( update.username.c_str());
+ gce.ptszUID = mir_a2t(update.username.c_str());
gce.bIsMe = (update.username == twit_.get_username());
- gce.ptszText = ( TCHAR* )update.status.text.c_str();
+ //TODO: write code here to replace % with %% in update.status.text (which is a std::string)
+
+ std::string chatText = update.status.text;
+
+ replaceAll(chatText, "%", "%%");
+
+ gce.ptszText = mir_a2t_cp(chatText.c_str(),CP_UTF8);
+ //gce.ptszText = mir_a2t_cp(update.status.text.c_str(),CP_UTF8);
gce.time = static_cast<DWORD>(update.status.time);
DBVARIANT nick;
- HANDLE hContact = UsernameToHContact( _A2T(update.username.c_str()));
- if (hContact && !DBGetContactSettingTString(hContact, "CList", "MyHandle", &nick)) {
- gce.ptszNick = mir_tstrdup( nick.ptszVal );
+ HANDLE hContact = UsernameToHContact(update.username.c_str());
+ if(hContact && !DBGetContactSettingString(hContact,"CList","MyHandle",&nick) )
+ {
+ gce.ptszNick = mir_a2t(nick.pszVal);
DBFreeVariant(&nick);
}
- else gce.ptszNick = mir_a2t( update.username.c_str());
+ else
+ gce.ptszNick = mir_a2t(update.username.c_str());
- CallServiceSync(MS_GC_EVENT, 0, reinterpret_cast<LPARAM>(&gce));
+ CallServiceSync(MS_GC_EVENT,0,reinterpret_cast<LPARAM>(&gce));
mir_free(const_cast<TCHAR*>(gce.ptszNick));
mir_free(const_cast<TCHAR*>(gce.ptszUID));
mir_free(const_cast<TCHAR*>(gce.ptszText));
}
-int TwitterProto::OnChatOutgoing(WPARAM wParam, LPARAM lParam)
+int TwitterProto::OnChatOutgoing(WPARAM wParam,LPARAM lParam)
{
GCHOOK *hook = reinterpret_cast<GCHOOK*>(lParam);
- if (strcmp(hook->pDest->pszModule, m_szModuleName))
+ char *text;
+
+ if(strcmp(hook->pDest->pszModule,m_szModuleName))
return 0;
- TCHAR *text;
- switch(hook->pDest->iType) {
- case GC_USER_MESSAGE:
- text = mir_tstrdup(hook->ptszText);
- ForkThread(&TwitterProto::SendTweetWorker, this, text);
+ switch(hook->pDest->iType)
+ {
+ case GC_USER_MESSAGE: {
+ text = mir_t2a_cp(hook->ptszText,CP_UTF8);
+ LOG("**Chat - Outgoing message: %s", text);
+
+ std::string tweet(text);
+ replaceAll(tweet, "%%", "%"); // the chat plugin will turn "%" into "%%", so we have to change it back :/
+
+ LOG("**Chat - Outgoing message after replace: %s", tweet);
+
+ char * varTweet;
+ varTweet = mir_utf8encode(tweet.c_str());
+ //strncpy(varTweet, tweet.c_str(), tweet.length()+1);
+
+ ForkThread(&TwitterProto::SendTweetWorker, this,varTweet);
break;
-
+ }
case GC_USER_PRIVMESS:
- text = mir_tstrdup(hook->ptszUID);
- CallService(MS_MSG_SENDMESSAGE, reinterpret_cast<WPARAM>( UsernameToHContact(text)), 0);
+ text = mir_t2a(hook->ptszUID);
+ CallService(MS_MSG_SENDMESSAGE,reinterpret_cast<WPARAM>(
+ UsernameToHContact(text) ),0);
mir_free(text);
break;
}
@@ -75,7 +97,7 @@ int TwitterProto::OnChatOutgoing(WPARAM wParam, LPARAM lParam) }
// TODO: remove nick?
-void TwitterProto::AddChatContact(const TCHAR *name, const TCHAR *nick)
+void TwitterProto::AddChatContact(const char *name,const char *nick)
{
GCDEST gcd = { m_szModuleName };
gcd.ptszID = const_cast<TCHAR*>(m_tszUserName);
@@ -84,15 +106,18 @@ void TwitterProto::AddChatContact(const TCHAR *name, const TCHAR *nick) GCEVENT gce = {sizeof(gce)};
gce.pDest = &gcd;
gce.dwFlags = GC_TCHAR;
- gce.ptszNick = nick ? nick:name;
- gce.ptszUID = name;
+ gce.ptszNick = mir_a2t(nick ? nick:name);
+ gce.ptszUID = mir_a2t(name);
gce.bIsMe = false;
gce.ptszStatus = _T("Normal");
gce.time = static_cast<DWORD>(time(0));
- CallServiceSync(MS_GC_EVENT, 0, reinterpret_cast<LPARAM>(&gce));
+ CallServiceSync(MS_GC_EVENT,0,reinterpret_cast<LPARAM>(&gce));
+
+ mir_free(const_cast<TCHAR*>(gce.ptszNick));
+ mir_free(const_cast<TCHAR*>(gce.ptszUID));
}
-void TwitterProto::DeleteChatContact(const TCHAR *name)
+void TwitterProto::DeleteChatContact(const char *name)
{
GCDEST gcd = { m_szModuleName };
gcd.ptszID = const_cast<TCHAR*>(m_tszUserName);
@@ -101,15 +126,15 @@ void TwitterProto::DeleteChatContact(const TCHAR *name) GCEVENT gce = {sizeof(gce)};
gce.pDest = &gcd;
gce.dwFlags = GC_TCHAR;
- gce.ptszNick = name;
+ gce.ptszNick = mir_a2t(name);
gce.ptszUID = gce.ptszNick;
gce.time = static_cast<DWORD>(time(0));
- CallServiceSync(MS_GC_EVENT, 0, reinterpret_cast<LPARAM>(&gce));
+ CallServiceSync(MS_GC_EVENT,0,reinterpret_cast<LPARAM>(&gce));
mir_free(const_cast<TCHAR*>(gce.ptszNick));
}
-int TwitterProto::OnJoinChat(WPARAM, LPARAM suppress)
+int TwitterProto::OnJoinChat(WPARAM,LPARAM suppress)
{
GCSESSION gcw = {sizeof(gcw)};
@@ -119,9 +144,9 @@ int TwitterProto::OnJoinChat(WPARAM, LPARAM suppress) gcw.pszModule = m_szModuleName;
gcw.ptszName = m_tszUserName;
gcw.ptszID = m_tszUserName;
- CallServiceSync(MS_GC_NEWSESSION, 0, (LPARAM)&gcw);
+ CallServiceSync(MS_GC_NEWSESSION, 0, (LPARAM)&gcw);
- if (m_iStatus != ID_STATUS_ONLINE)
+ if(m_iStatus != ID_STATUS_ONLINE)
return 0;
// ***** Create a group
@@ -134,20 +159,20 @@ int TwitterProto::OnJoinChat(WPARAM, LPARAM suppress) gcd.iType = GC_EVENT_ADDGROUP;
gce.ptszStatus = _T("Normal");
- CallServiceSync(MS_GC_EVENT, 0, reinterpret_cast<LPARAM>(&gce));
+ CallServiceSync(MS_GC_EVENT,0,reinterpret_cast<LPARAM>(&gce));
// ***** Hook events
- HookProtoEvent(ME_GC_EVENT, &TwitterProto::OnChatOutgoing, this);
+ HookProtoEvent(ME_GC_EVENT,&TwitterProto::OnChatOutgoing,this);
- // Note: Initialization will finish up in SetChatStatus, called separately
- if (!suppress)
+ // Note: Initialization will finish up in SetChatStatus, called separately
+ if(!suppress)
SetChatStatus(m_iStatus);
in_chat_ = true;
return 0;
}
-int TwitterProto::OnLeaveChat(WPARAM, LPARAM)
+int TwitterProto::OnLeaveChat(WPARAM,LPARAM)
{
in_chat_ = false;
@@ -159,8 +184,8 @@ int TwitterProto::OnLeaveChat(WPARAM, LPARAM) gce.dwFlags = GC_TCHAR;
gce.pDest = &gcd;
- CallServiceSync(MS_GC_EVENT, SESSION_OFFLINE, reinterpret_cast<LPARAM>(&gce));
- CallServiceSync(MS_GC_EVENT, SESSION_TERMINATE, reinterpret_cast<LPARAM>(&gce));
+ CallServiceSync(MS_GC_EVENT,SESSION_OFFLINE, reinterpret_cast<LPARAM>(&gce));
+ CallServiceSync(MS_GC_EVENT,SESSION_TERMINATE,reinterpret_cast<LPARAM>(&gce));
return 0;
}
@@ -175,32 +200,34 @@ void TwitterProto::SetChatStatus(int status) gce.dwFlags = GC_TCHAR;
gce.pDest = &gcd;
- if (status == ID_STATUS_ONLINE) {
+ if(status == ID_STATUS_ONLINE)
+ {
// Add all friends to contact list
- for(HANDLE hContact = (HANDLE)CallService(MS_DB_CONTACT_FINDFIRST, 0, 0);
+ for(HANDLE hContact = (HANDLE)CallService(MS_DB_CONTACT_FINDFIRST,0,0);
hContact;
- hContact = (HANDLE)CallService(MS_DB_CONTACT_FINDNEXT, (WPARAM)hContact, 0))
+ hContact = (HANDLE)CallService(MS_DB_CONTACT_FINDNEXT,(WPARAM)hContact,0) )
{
- if (!IsMyContact(hContact))
+ if(!IsMyContact(hContact))
continue;
- DBVARIANT uid, nick;
- if ( DBGetContactSettingTString(hContact, m_szModuleName, TWITTER_KEY_UN, &uid))
+ DBVARIANT uid,nick;
+ if( DBGetContactSettingString(hContact,m_szModuleName,TWITTER_KEY_UN,&uid) )
continue;
- if ( !DBGetContactSettingTString(hContact, "CList", "MyHandle", &nick))
- AddChatContact(uid.ptszVal, nick.ptszVal);
+ if( !DBGetContactSettingString(hContact,"CList","MyHandle",&nick) )
+ AddChatContact(uid.pszVal,nick.pszVal);
else
- AddChatContact(uid.ptszVal);
+ AddChatContact(uid.pszVal);
DBFreeVariant(&nick);
DBFreeVariant(&uid);
}
- // For some reason, I have to send an INITDONE message, even if I'm not actually
+ // For some reason, I have to send an INITDONE message, even if I'm not actually
// initializing the room...
- CallServiceSync(MS_GC_EVENT, SESSION_INITDONE, reinterpret_cast<LPARAM>(&gce));
- CallServiceSync(MS_GC_EVENT, SESSION_ONLINE, reinterpret_cast<LPARAM>(&gce));
+ CallServiceSync(MS_GC_EVENT,SESSION_INITDONE,reinterpret_cast<LPARAM>(&gce));
+ CallServiceSync(MS_GC_EVENT,SESSION_ONLINE, reinterpret_cast<LPARAM>(&gce));
}
- else CallServiceSync(MS_GC_EVENT, SESSION_OFFLINE, reinterpret_cast<LPARAM>(&gce));
+ else
+ CallServiceSync(MS_GC_EVENT,SESSION_OFFLINE,reinterpret_cast<LPARAM>(&gce));
}
\ No newline at end of file diff --git a/protocols/Twitter/common.h b/protocols/Twitter/common.h index 751c1d22d6..675d1ec1be 100644 --- a/protocols/Twitter/common.h +++ b/protocols/Twitter/common.h @@ -17,6 +17,20 @@ along with this program. If not, see <http://www.gnu.org/licenses/>. #pragma once
+#define MIRANDA_VER 0x800
+
+#include <string>
+using std::string;
+using std::wstring;
+#include <map>
+using std::map;
+#include <vector>
+using std::vector;
+#include <list>
+using std::list;
+#include <algorithm>
+using std::min;
+
#include <windows.h>
#include "resource.h"
@@ -31,6 +45,7 @@ along with this program. If not, see <http://www.gnu.org/licenses/>. #include <m_clist.h>
#include <m_clistint.h>
#include <m_clui.h>
+//#include "m_cluiframes.h"
#include <m_database.h>
#include <m_history.h>
#include <m_idle.h>
@@ -45,7 +60,6 @@ along with this program. If not, see <http://www.gnu.org/licenses/>. #include <m_skin.h>
#include <statusmodes.h>
#include <m_system.h>
-#include <m_system_cpp.h>
#include <m_userinfo.h>
#include <m_addcontact.h>
#include <m_icolib.h>
@@ -57,11 +71,18 @@ along with this program. If not, see <http://www.gnu.org/licenses/>. extern HINSTANCE g_hInstance;
+#define TWITTER_KEY_NICK "Nick" // we need one called Nick for the chat thingo to work
#define TWITTER_KEY_UN "Username"
#define TWITTER_KEY_PASS "Password"
+#define TWITTER_KEY_OAUTH_PIN "OAuthPIN"
+#define TWITTER_KEY_OAUTH_TOK "OAuthToken"
+#define TWITTER_KEY_OAUTH_TOK_SECRET "OAuthTokenSecret"
+#define TWITTER_KEY_OAUTH_ACCESS_TOK "OAuthAccessToken"
+#define TWITTER_KEY_OAUTH_ACCESS_TOK_SECRET "OAuthAccessTokenSecret"
#define TWITTER_KEY_BASEURL "BaseURL"
#define TWITTER_KEY_CHATFEED "ChatFeed"
#define TWITTER_KEY_POLLRATE "PollRate"
+#define TWITTER_KEY_GROUP "DefaultGroup"
#define TWITTER_KEY_POPUP_SHOW "Popup/Show"
#define TWITTER_KEY_POPUP_SIGNON "Popup/Signon"
@@ -69,6 +90,8 @@ extern HINSTANCE g_hInstance; #define TWITTER_KEY_POPUP_COLTEXT "Popup/ColorText"
#define TWITTER_KEY_POPUP_TIMEOUT "Popup/Timeout"
+#define TWITTER_KEY_TWEET_TO_MSG "TweetToMsg"
+
#define TWITTER_KEY_SINCEID "SinceID"
#define TWITTER_KEY_DMSINCEID "DMSinceID"
#define TWITTER_KEY_NEW "NewAcc"
@@ -77,4 +100,4 @@ extern HINSTANCE g_hInstance; #define TWITTER_DB_EVENT_TYPE_TWEET 2718
-#define WM_SETREPLY WM_APP+10
\ No newline at end of file +#define WM_SETREPLY WM_APP+10
diff --git a/protocols/Twitter/connection.cpp b/protocols/Twitter/connection.cpp index 83660a8256..b32ceb5cea 100644 --- a/protocols/Twitter/connection.cpp +++ b/protocols/Twitter/connection.cpp @@ -3,20 +3,21 @@ Copyright © 2009 Jim Porter This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
-the Free Software Foundation, either version 2 of the License, or
+the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
-This program is distributed in the hope that it will be useful,
+This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
-along with this program. If not, see <http://www.gnu.org/licenses/>.
+along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
-#include "common.h"
#include "proto.h"
+//#include "tc2.h"
+#include "twitter.h"
void CALLBACK TwitterProto::APC_callback(ULONG_PTR p)
{
@@ -24,7 +25,7 @@ void CALLBACK TwitterProto::APC_callback(ULONG_PTR p) }
template<typename T>
-inline static T db_pod_get(HANDLE hContact, const char *module, const char *setting,
+inline static T db_pod_get(HANDLE hContact,const char *module,const char *setting,
T errorValue)
{
DBVARIANT dbv;
@@ -33,20 +34,20 @@ inline static T db_pod_get(HANDLE hContact, const char *module, const char *sett cgs.szModule = module;
cgs.szSetting = setting;
cgs.pValue = &dbv;
- if (CallService(MS_DB_CONTACT_GETSETTING, (WPARAM)hContact, (LPARAM)&cgs))
+ if(CallService(MS_DB_CONTACT_GETSETTING,(WPARAM)hContact,(LPARAM)&cgs))
return errorValue;
- // TODO: remove this, it's just a temporary workaround
- if (dbv.type == DBVT_DWORD)
+ // TODO: remove this, it's just a temporary workaround
+ if(dbv.type == DBVT_DWORD)
return dbv.dVal;
- if (dbv.cpbVal != sizeof(T))
+ if(dbv.cpbVal != sizeof(T))
return errorValue;
return *reinterpret_cast<T*>(dbv.pbVal);
}
template<typename T>
-inline static INT_PTR db_pod_set(HANDLE hContact, const char *module, const char *setting,
+inline static INT_PTR db_pod_set(HANDLE hContact,const char *module,const char *setting,
T val)
{
DBCONTACTWRITESETTING cws;
@@ -56,30 +57,32 @@ inline static INT_PTR db_pod_set(HANDLE hContact, const char *module, const char cws.value.type = DBVT_BLOB;
cws.value.cpbVal = sizeof(T);
cws.value.pbVal = reinterpret_cast<BYTE*>(&val);
- return CallService(MS_DB_CONTACT_WRITESETTING, (WPARAM)hContact, (LPARAM)&cws);
+ return CallService(MS_DB_CONTACT_WRITESETTING,(WPARAM)hContact,(LPARAM)&cws);
}
void TwitterProto::SignOn(void*)
{
LOG("***** Beginning SignOn process");
- WaitForSingleObject(&signon_lock_, INFINITE);
+ WaitForSingleObject(&signon_lock_,INFINITE);
// Kill the old thread if it's still around
- if (hMsgLoop_)
+ // this doesn't seem to work.. should we wait infinitely?
+ if(hMsgLoop_)
{
LOG("***** Requesting MessageLoop to exit");
- QueueUserAPC(APC_callback, hMsgLoop_, (ULONG_PTR)this);
+ QueueUserAPC(APC_callback,hMsgLoop_,(ULONG_PTR)this);
LOG("***** Waiting for old MessageLoop to exit");
- WaitForSingleObject(hMsgLoop_, INFINITE);
+ //WaitForSingleObject(hMsgLoop_,INFINITE);
+ WaitForSingleObject(hMsgLoop_,180000);
CloseHandle(hMsgLoop_);
}
- if (NegotiateConnection()) // Could this be? The legendary Go Time??
+ if(NegotiateConnection()) // Could this be? The legendary Go Time??
{
- if (!in_chat_ && db_byte_get(0, m_szModuleName, TWITTER_KEY_CHATFEED, 0))
- OnJoinChat(0, true);
+ if(!in_chat_ && db_byte_get(0,m_szModuleName,TWITTER_KEY_CHATFEED,0))
+ OnJoinChat(0,true);
SetAllContactStatuses(ID_STATUS_ONLINE);
- hMsgLoop_ = ForkThreadEx(&TwitterProto::MessageLoop, this);
+ hMsgLoop_ = ForkThreadEx(&TwitterProto::MessageLoop,this);
}
ReleaseMutex(signon_lock_);
@@ -89,22 +92,210 @@ void TwitterProto::SignOn(void*) bool TwitterProto::NegotiateConnection()
{
LOG("***** Negotiating connection with Twitter");
+ disconnectionCount = 0;
+ // saving the current status to a temp var
int old_status = m_iStatus;
- std::string user, pass;
DBVARIANT dbv;
- if ( !DBGetContactSettingString(0, m_szModuleName, TWITTER_KEY_UN, &dbv)) {
- user = dbv.pszVal;
+ wstring oauthToken;
+ wstring oauthTokenSecret;
+ wstring oauthAccessToken;
+ wstring oauthAccessTokenSecret;
+ string screenName;
+
+ int dbTOK = DBGetContactSettingWString(0,m_szModuleName,TWITTER_KEY_OAUTH_TOK,&dbv);
+ if (!dbTOK) {
+ oauthToken = dbv.pwszVal;
+ DBFreeVariant(&dbv);
+ //WLOG("**NegotiateConnection - we have an oauthToken already in the db - %s", oauthToken);
+ }
+
+ int dbTOKSec = DBGetContactSettingWString(0,m_szModuleName,TWITTER_KEY_OAUTH_TOK_SECRET,&dbv);
+ if (!dbTOKSec) {
+ oauthTokenSecret = dbv.pwszVal;
+ DBFreeVariant(&dbv);
+ //WLOG("**NegotiateConnection - we have an oauthTokenSecret already in the db - %s", oauthTokenSecret);
+ }
+
+ int dbName = DBGetContactSettingString(0,m_szModuleName,TWITTER_KEY_NICK,&dbv);
+ if (!dbName) {
+ screenName = dbv.pszVal;
DBFreeVariant(&dbv);
+ //WLOG("**NegotiateConnection - we have a username already in the db - %s", screenName);
}
else {
- ShowPopup(TranslateT("Please enter a username."));
- return false;
+ dbName = DBGetContactSettingString(0,m_szModuleName,TWITTER_KEY_UN,&dbv);
+ if (!dbName) {
+ screenName = dbv.pszVal;
+ DBWriteContactSettingString(0,m_szModuleName,TWITTER_KEY_NICK,dbv.pszVal);
+ //WLOG("**NegotiateConnection - we have a username already in the db - %s", screenName);
+ }
+ DBFreeVariant(&dbv);
+ }
+
+
+ if((oauthToken.size() <= 1) || (oauthTokenSecret.size() <= 1) ) {
+ // first, reset all the keys so we can start fresh
+ resetOAuthKeys();
+ LOG("**NegotiateConnection - Reset OAuth Keys");
+
+ //twit_.set_credentials(ConsumerKey, ConsumerSecret, oauthAccessToken, oauthAccessTokenSecret, L"", false);
+ // i think i was doin the wrong thing here.. i was setting the credentials as oauthAccessToken instead of oauthToken
+ // have to test..
+ LOG("**NegotiateConnection - Setting Consumer Keys...");
+ /*WLOG("**NegotiateConnection - sending set_cred: consumerKey is %s", ConsumerKey);
+ WLOG("**NegotiateConnection - sending set_cred: consumerSecret is %s", ConsumerSecret);
+ WLOG("**NegotiateConnection - sending set_cred: oauthToken is %s", oauthToken);
+ WLOG("**NegotiateConnection - sending set_cred: oauthTokenSecret is %s", oauthTokenSecret);
+ LOG("**NegotiateConnection - sending set_cred: no pin");*/
+ twit_.set_credentials("", ConsumerKey, ConsumerSecret, oauthToken, oauthTokenSecret, L"", false);
+ LOG("**NegotiateConnection - Requesting oauthTokens");
+ http::response resp = twit_.request_token();
+
+ //wstring rdata_WSTR(resp.data.length(),L' ');
+ //std::copy(resp.data.begin(), resp.data.end(), rdata_WSTR.begin());
+ wstring rdata_WSTR = UTF8ToWide(resp.data);
+
+ //WLOG("**NegotiateConnection - REQUEST TOKEN IS %s", rdata_WSTR);
+ OAuthParameters response = twit_.ParseQueryString(rdata_WSTR);
+ oauthToken = response[L"oauth_token"];
+ oauthTokenSecret = response[L"oauth_token_secret"];
+ //WLOG("**NegotiateConnection - oauthToken is %s", oauthToken);
+ //WLOG("**NegotiateConnection - oauthTokenSecret is %s", oauthTokenSecret);
+
+ if (oauthToken.length() < 1) {
+ ShowPopup("OAuth Tokens not received, check your internet connection?", 1);
+ LOG("**NegotiateConnection - OAuth tokens not received, stopping before we open the web browser..");
+ return false;
+ }
+
+ //write those bitches to the db foe latta
+ DBWriteContactSettingWString(0,m_szModuleName,TWITTER_KEY_OAUTH_TOK,oauthToken.c_str());
+ DBWriteContactSettingWString(0,m_szModuleName,TWITTER_KEY_OAUTH_TOK_SECRET,oauthTokenSecret.c_str());
+
+ // this looks like bad code.. can someone clean this up please? or confirm that it's ok
+ wchar_t buf[1024] = {};
+ swprintf_s(buf, SIZEOF(buf), AuthorizeUrl.c_str(), oauthToken.c_str());
+
+ WLOG("**NegotiateConnection - Launching %s", buf);
+ ShellExecute(NULL, L"open", buf, NULL, NULL, SW_SHOWNORMAL);
+
+ ShowPinDialog();
+ }
+
+ if (!DBGetContactSettingTString(NULL,m_szModuleName,TWITTER_KEY_GROUP,&dbv)) {
+ CallService( MS_CLIST_GROUPCREATE, 0, (LPARAM)dbv.ptszVal );
+ DBFreeVariant(&dbv);
+ }
+
+ bool realAccessTok = false;
+ bool realAccessTokSecret = false;
+
+ // remember, dbTOK is 0 (false) if the db setting has returned something
+ dbTOK = DBGetContactSettingWString(0,m_szModuleName,TWITTER_KEY_OAUTH_ACCESS_TOK,&dbv);
+ if (!dbTOK) {
+ oauthAccessToken = dbv.pwszVal;
+ DBFreeVariant(&dbv);
+ // this bit is saying "if we have found the db key, but it contains no data, then set dbTOK to 1"
+ if (oauthAccessToken.size() > 1) {
+ realAccessTok = true;
+ //WLOG("**NegotiateConnection - we have an oauthAccessToken already in the db - %s", oauthAccessToken);
+ }
+ else { LOG("**NegotiateConnection - oauthAccesToken too small? this is.. weird."); }
+ }
+
+ dbTOKSec = DBGetContactSettingWString(0,m_szModuleName,TWITTER_KEY_OAUTH_ACCESS_TOK_SECRET,&dbv);
+ if (!dbTOKSec) {
+ oauthAccessTokenSecret = dbv.pwszVal;
+ DBFreeVariant(&dbv);
+ if (oauthAccessTokenSecret.size() > 1) {
+ realAccessTokSecret = true;
+ //WLOG("**NegotiateConnection - we have an oauthAccessTokenSecret already in the db - %s", oauthAccessTokenSecret);
+ }
+ else { LOG("**NegotiateConnection - oauthAccessTokenSecret too small? weird"); }
+ }
+
+ if (!realAccessTok || !realAccessTokSecret) { // if we don't have one of these beasties then lets go get 'em!
+ wstring pin;
+ LOG("**NegotiateConnection - either the accessToken or accessTokenSecret was not there..");
+ if (!DBGetContactSettingWString(0,m_szModuleName,TWITTER_KEY_OAUTH_PIN,&dbv)) {
+ pin = dbv.pwszVal;
+ //WLOG("**NegotiateConnection - we have an pin already in the db - %s", pin);
+ DBFreeVariant(&dbv);
+ }
+ else {
+ ShowPopup(TranslateT("OAuth variables are out of sequence, they have been reset. Please reconnect and reauthorise Miranda to Twitter.com (do the PIN stuff again)"));
+ LOG("**NegotiateConnection - We don't have a PIN? this doesn't make sense. Resetting OAuth keys and setting offline.");
+ resetOAuthKeys();
+
+ ProtoBroadcastAck(m_szModuleName,0,ACKTYPE_STATUS,ACKRESULT_FAILED,
+ (HANDLE)old_status,m_iStatus);
+
+ // Set to offline
+ old_status = m_iStatus;
+ m_iDesiredStatus = m_iStatus = ID_STATUS_OFFLINE;
+ ProtoBroadcastAck(m_szModuleName,0,ACKTYPE_STATUS,ACKRESULT_SUCCESS,
+ (HANDLE)old_status,m_iStatus);
+
+ return false;
+ }
+
+ LOG("**NegotiateConnection - Setting Consumer Keys and PIN...");
+ /*WLOG("**NegotiateConnection - sending set_cred: consumerKey is %s", ConsumerKey);
+ WLOG("**NegotiateConnection - sending set_cred: consumerSecret is %s", ConsumerSecret);
+ WLOG("**NegotiateConnection - sending set_cred: oauthToken is %s", oauthToken);
+ WLOG("**NegotiateConnection - sending set_cred: oauthTokenSecret is %s", oauthTokenSecret);
+ WLOG("**NegotiateConnection - sending set_cred: pin is %s", pin);*/
+
+ twit_.set_credentials("", ConsumerKey, ConsumerSecret, oauthToken, oauthTokenSecret, pin, false);
+
+ LOG("**NegotiateConnection - requesting access tokens...");
+ http::response accessResp = twit_.request_access_tokens();
+ if (accessResp.code != 200) {
+ LOG("**NegotiateConnection - Failed to get Access Tokens, HTTP response code is: %d", accessResp.code);
+ ShowPopup(TranslateT("Failed to get Twitter Access Tokens, please go offline and try again. If this keeps happening, check your internet connection."));
+
+ resetOAuthKeys();
+
+ ProtoBroadcastAck(m_szModuleName,0,ACKTYPE_STATUS,ACKRESULT_FAILED,
+ (HANDLE)old_status,m_iStatus);
+
+ // Set to offline
+ old_status = m_iStatus;
+ m_iDesiredStatus = m_iStatus = ID_STATUS_OFFLINE;
+ ProtoBroadcastAck(m_szModuleName,0,ACKTYPE_STATUS,ACKRESULT_SUCCESS,
+ (HANDLE)old_status,m_iStatus);
+
+ return false;
+ }
+ else {
+ LOG("**NegotiateConnection - Successfully retrieved Access Tokens");
+
+ wstring rdata_WSTR2 = UTF8ToWide(accessResp.data);
+ //WLOG("**NegotiateConnection - accessToken STring is %s", rdata_WSTR2);
+
+ OAuthParameters accessTokenParameters = twit_.ParseQueryString(rdata_WSTR2);
+
+ oauthAccessToken = accessTokenParameters[L"oauth_token"];
+ //WLOG("**NegotiateConnection - oauthAccessToken is %s", oauthAccessToken);
+
+ oauthAccessTokenSecret = accessTokenParameters[L"oauth_token_secret"];
+ //WLOG("**NegotiateConnection - oauthAccessTokenSecret is %s", oauthAccessTokenSecret);
+
+ screenName = WideToUTF8(accessTokenParameters[L"screen_name"]);
+ LOG("**NegotiateConnection - screen name is %s", screenName.c_str());
+
+ //save em
+ DBWriteContactSettingWString(0,m_szModuleName,TWITTER_KEY_OAUTH_ACCESS_TOK,oauthAccessToken.c_str());
+ DBWriteContactSettingWString(0,m_szModuleName,TWITTER_KEY_OAUTH_ACCESS_TOK_SECRET,oauthAccessTokenSecret.c_str());
+ DBWriteContactSettingString(0,m_szModuleName,TWITTER_KEY_NICK,screenName.c_str());
+ DBWriteContactSettingString(0,m_szModuleName,TWITTER_KEY_UN,screenName.c_str());
+ }
}
- if ( !DBGetContactSettingString(0, m_szModuleName, TWITTER_KEY_PASS, &dbv)) {
- CallService(MS_DB_CRYPT_DECODESTRING, strlen(dbv.pszVal)+1,
+/* if( !DBGetContactSettingString(0,m_szModuleName,TWITTER_KEY_PASS,&dbv) ) {
+ CallService(MS_DB_CRYPT_DECODESTRING,strlen(dbv.pszVal)+1,
reinterpret_cast<LPARAM>(dbv.pszVal));
pass = dbv.pszVal;
DBFreeVariant(&dbv);
@@ -112,37 +303,57 @@ bool TwitterProto::NegotiateConnection() else {
ShowPopup(TranslateT("Please enter a password."));
return false;
- }
+ }*/
- if ( !DBGetContactSettingString(0, m_szModuleName, TWITTER_KEY_BASEURL, &dbv)) {
+ if( !DBGetContactSettingString(0,m_szModuleName,TWITTER_KEY_BASEURL,&dbv) )
+ {
ScopedLock s(twitter_lock_);
twit_.set_base_url(dbv.pszVal);
DBFreeVariant(&dbv);
}
+ LOG("**NegotiateConnection - Setting Consumer Keys and verifying creds...");
+ /*WLOG("**NegotiateConnection - sending set_cred: consumerKey is %s", ConsumerKey);
+ WLOG("**NegotiateConnection - sending set_cred: consumerSecret is %s", ConsumerSecret);
+ WLOG("**NegotiateConnection - sending set_cred: oauthAccessToken is %s", oauthAccessToken);
+ WLOG("**NegotiateConnection - sending set_cred: oauthAccessTokenSecret is %s", oauthAccessTokenSecret);
+ LOG("**NegotiateConnection - sending set_cred: no pin");*/
+
+ if (screenName.empty()) {
+ ShowPopup(TranslateT("You're missing the Nick key in the database. This isn't really a big deal, but you'll notice some minor quirks (self contact in list, no group chat outgoing message highlighting, etc). To fix it either add it manually or reset your twitter account in the miranda account options"));
+ LOG("**NegotiateConnection - Missing the Nick key in the database. Everything will still work, but it's nice to have");
+ }
+
bool success;
- {
+ {
ScopedLock s(twitter_lock_);
- success = twit_.set_credentials(user, pass);
+
+ success = twit_.set_credentials(screenName, ConsumerKey, ConsumerSecret, oauthAccessToken, oauthAccessTokenSecret, L"", true);
}
- if (!success) {
- ShowPopup(TranslateT("Your username/password combination was incorrect."));
- ProtoBroadcastAck(m_szModuleName, 0, ACKTYPE_STATUS, ACKRESULT_FAILED,
- (HANDLE)old_status, m_iStatus);
+ if(!success) {
+ //ShowPopup(TranslateT("Something went wrong with authorisation, OAuth keys have been reset. Please try to reconnect. If problems persist, please se your doctor"));
+ LOG("**NegotiateConnection - Verifying credentials failed! No internet maybe?");
+
+ //resetOAuthKeys();
+ ProtoBroadcastAck(m_szModuleName,0,ACKTYPE_STATUS,ACKRESULT_FAILED,
+ (HANDLE)old_status,m_iStatus);
// Set to offline
old_status = m_iStatus;
m_iDesiredStatus = m_iStatus = ID_STATUS_OFFLINE;
- ProtoBroadcastAck(m_szModuleName, 0, ACKTYPE_STATUS, ACKRESULT_SUCCESS,
- (HANDLE)old_status, m_iStatus);
+ ProtoBroadcastAck(m_szModuleName,0,ACKTYPE_STATUS,ACKRESULT_SUCCESS,
+ (HANDLE)old_status,m_iStatus);
return false;
}
-
- m_iStatus = m_iDesiredStatus;
- ProtoBroadcastAck(m_szModuleName, 0, ACKTYPE_STATUS, ACKRESULT_SUCCESS, (HANDLE)old_status, m_iStatus);
- return true;
+ else {
+ m_iStatus = m_iDesiredStatus;
+
+ ProtoBroadcastAck(m_szModuleName,0,ACKTYPE_STATUS,ACKRESULT_SUCCESS,
+ (HANDLE)old_status,m_iStatus);
+ return true;
+ }
}
@@ -150,39 +361,43 @@ void TwitterProto::MessageLoop(void*) {
LOG("***** Entering Twitter::MessageLoop");
- since_id_ = db_pod_get<twitter_id>(0, m_szModuleName, TWITTER_KEY_SINCEID, 0);
- dm_since_id_ = db_pod_get<twitter_id>(0, m_szModuleName, TWITTER_KEY_DMSINCEID, 0);
+ since_id_ = db_pod_get<twitter_id>(0,m_szModuleName,TWITTER_KEY_SINCEID,0);
+ dm_since_id_ = db_pod_get<twitter_id>(0,m_szModuleName,TWITTER_KEY_DMSINCEID,0);
+
+ bool new_account = db_byte_get(0,m_szModuleName,TWITTER_KEY_NEW,1) != 0;
+ bool popups = db_byte_get(0,m_szModuleName,TWITTER_KEY_POPUP_SIGNON,1) != 0;
- bool new_account = db_byte_get(0, m_szModuleName, TWITTER_KEY_NEW, 1) != 0;
- bool popups = db_byte_get(0, m_szModuleName, TWITTER_KEY_POPUP_SIGNON, 1) != 0;
+ // if this isn't set, it will automatically not turn a tweet into a msg. probably should make the default that it does turn a tweet into a message
+ bool tweetToMsg = db_byte_get(0,m_szModuleName,TWITTER_KEY_TWEET_TO_MSG,0) != 0;
- int poll_rate = db_dword_get(0, m_szModuleName, TWITTER_KEY_POLLRATE, 80);
+ int poll_rate = db_dword_get(0,m_szModuleName,TWITTER_KEY_POLLRATE,80);
for(unsigned int i=0;;i++)
{
- if (m_iStatus != ID_STATUS_ONLINE)
+
+ if(m_iStatus != ID_STATUS_ONLINE)
goto exit;
- if (i%4 == 0)
+ if(i%4 == 0)
UpdateFriends();
- if (m_iStatus != ID_STATUS_ONLINE)
+ if(m_iStatus != ID_STATUS_ONLINE)
goto exit;
- UpdateStatuses(new_account, popups);
+ UpdateStatuses(new_account,popups, tweetToMsg);
- if (m_iStatus != ID_STATUS_ONLINE)
+ if(m_iStatus != ID_STATUS_ONLINE)
goto exit;
UpdateMessages(new_account);
- if (new_account) // Not anymore!
+ if(new_account) // Not anymore!
{
new_account = false;
- DBWriteContactSettingByte(0, m_szModuleName, TWITTER_KEY_NEW, 0);
+ DBWriteContactSettingByte(0,m_szModuleName,TWITTER_KEY_NEW,0);
}
- if (m_iStatus != ID_STATUS_ONLINE)
+ if(m_iStatus != ID_STATUS_ONLINE)
goto exit;
LOG("***** TwitterProto::MessageLoop going to sleep...");
- if (SleepEx(poll_rate*1000, true) == WAIT_IO_COMPLETION)
+ if(SleepEx(poll_rate*1000,true) == WAIT_IO_COMPLETION)
goto exit;
LOG("***** TwitterProto::MessageLoop waking up...");
@@ -192,26 +407,26 @@ void TwitterProto::MessageLoop(void*) exit:
{
ScopedLock s(twitter_lock_);
- twit_.set_credentials("", "", false);
+ twit_.set_credentials("",L"",L"",L"",L"",L"", false);
}
LOG("***** Exiting TwitterProto::MessageLoop");
}
struct update_avatar
{
- update_avatar(HANDLE hContact, const std::string &url) : hContact(hContact), url(url) {}
+ update_avatar(HANDLE hContact,const std::string &url) : hContact(hContact),url(url) {}
HANDLE hContact;
std::string url;
};
void TwitterProto::UpdateAvatarWorker(void *p)
{
- if (p == 0)
+ if(p == 0)
return;
- std::auto_ptr<update_avatar> data( static_cast<update_avatar*>(p));
+ std::auto_ptr<update_avatar> data( static_cast<update_avatar*>(p) );
DBVARIANT dbv;
- if (DBGetContactSettingTString(data->hContact, m_szModuleName, TWITTER_KEY_UN, &dbv))
+ if(DBGetContactSettingString(data->hContact,m_szModuleName,TWITTER_KEY_UN,&dbv))
return;
std::string ext = data->url.substr(data->url.rfind('.'));
@@ -221,55 +436,61 @@ void TwitterProto::UpdateAvatarWorker(void *p) PROTO_AVATAR_INFORMATION ai = {sizeof(ai)};
ai.hContact = data->hContact;
ai.format = ext_to_format(ext);
- strncpy(ai.filename, filename.c_str(), MAX_PATH);
- LOG("***** Updating avatar: %s", data->url.c_str());
- WaitForSingleObjectEx(avatar_lock_, INFINITE, true);
- if (CallService(MS_SYSTEM_TERMINATED, 0, 0))
+ if (ai.format == PA_FORMAT_UNKNOWN) {
+ LOG("***** Update avatar: Terminated for this contact, extension format unknown for %s", data->url.c_str());
+ return; // lets just ignore unknown formats... if not it crashes miranda. should probably speak to borkra about this.
+ }
+
+ strncpy(ai.filename,filename.c_str(),MAX_PATH);
+
+ LOG("***** Updating avatar: %s",data->url.c_str());
+ WaitForSingleObjectEx(avatar_lock_,INFINITE,true);
+ if(CallService(MS_SYSTEM_TERMINATED,0,0))
{
- LOG("***** Terminating avatar update early: %s", data->url.c_str());
+ LOG("***** Terminating avatar update early: %s",data->url.c_str());
return;
}
- if (save_url(hAvatarNetlib_, data->url, filename))
+ if(save_url(hAvatarNetlib_,data->url,filename))
{
- DBWriteContactSettingString(data->hContact, m_szModuleName, TWITTER_KEY_AV_URL,
+ DBWriteContactSettingString(data->hContact,m_szModuleName,TWITTER_KEY_AV_URL,
data->url.c_str());
- ProtoBroadcastAck(m_szModuleName, data->hContact, ACKTYPE_AVATAR,
- ACKRESULT_SUCCESS, &ai, 0);
+ ProtoBroadcastAck(m_szModuleName,data->hContact,ACKTYPE_AVATAR,
+ ACKRESULT_SUCCESS,&ai,0);
}
else
- ProtoBroadcastAck(m_szModuleName, data->hContact, ACKTYPE_AVATAR,
- ACKRESULT_FAILED, &ai, 0);
+ ProtoBroadcastAck(m_szModuleName,data->hContact,ACKTYPE_AVATAR,
+ ACKRESULT_FAILED, &ai,0);
ReleaseMutex(avatar_lock_);
- LOG("***** Done avatar: %s", data->url.c_str());
+ LOG("***** Done avatar: %s",data->url.c_str());
}
-void TwitterProto::UpdateAvatar(HANDLE hContact, const std::string &url, bool force)
+void TwitterProto::UpdateAvatar(HANDLE hContact,const std::string &url,bool force)
{
DBVARIANT dbv;
- if ( !force &&
- ( !DBGetContactSettingString(hContact, m_szModuleName, TWITTER_KEY_AV_URL, &dbv) &&
- url == dbv.pszVal))
+ if( !force &&
+ ( !DBGetContactSettingString(hContact,m_szModuleName,TWITTER_KEY_AV_URL,&dbv) &&
+ url == dbv.pszVal) )
{
- LOG("***** Avatar already up-to-date: %s", url.c_str());
+ LOG("***** Avatar already up-to-date: %s",url.c_str());
}
else
{
// TODO: more defaults (configurable?)
- if (url == "http://static.twitter.com/images/default_profile_normal.png")
+ if(url == "http://static.twitter.com/images/default_profile_normal.png")
{
- PROTO_AVATAR_INFORMATION ai = {sizeof(ai), hContact};
+ PROTO_AVATAR_INFORMATION ai = {sizeof(ai),hContact};
- db_string_set(hContact, m_szModuleName, TWITTER_KEY_AV_URL, url.c_str());
- ProtoBroadcastAck(m_szModuleName, hContact, ACKTYPE_AVATAR,
- ACKRESULT_SUCCESS, &ai, 0);
+ db_string_set(hContact,m_szModuleName,TWITTER_KEY_AV_URL,url.c_str());
+ ProtoBroadcastAck(m_szModuleName,hContact,ACKTYPE_AVATAR,
+ ACKRESULT_SUCCESS,&ai,0);
}
else
{
- ForkThread(&TwitterProto::UpdateAvatarWorker, this,
- new update_avatar(hContact, url));
+ ForkThread(&TwitterProto::UpdateAvatarWorker, this,
+ new update_avatar(hContact,url));
}
}
@@ -283,108 +504,127 @@ void TwitterProto::UpdateFriends() ScopedLock s(twitter_lock_);
std::vector<twitter_user> friends = twit_.get_friends();
s.Unlock();
-
- for(std::vector<twitter_user>::iterator i=friends.begin(); i!=friends.end(); ++i) {
- if (i->username == twit_.get_username())
+ for(std::vector<twitter_user>::iterator i=friends.begin(); i!=friends.end(); ++i)
+ {
+ if(i->username == twit_.get_username())
continue;
- HANDLE hContact = AddToClientList( _A2T(i->username.c_str()), i->status.text.c_str());
- UpdateAvatar(hContact, i->profile_image_url);
+ HANDLE hContact = AddToClientList(i->username.c_str(),i->status.text.c_str());
+ UpdateAvatar(hContact,i->profile_image_url);
}
+ disconnectionCount = 0;
LOG("***** Friends list updated");
}
catch(const bad_response &)
{
- LOG("***** Bad response from server, signing off");
- SetStatus(ID_STATUS_OFFLINE);
+ ++disconnectionCount;
+ LOG("***** UpdateFriends - Bad response from server, this has happened %d time(s)", disconnectionCount);
+ if (disconnectionCount > 2) {
+ LOG("***** UpdateFriends - Too many bad responses from the server, signing off");
+ SetStatus(ID_STATUS_OFFLINE);
+ }
}
catch(const std::exception &e)
{
- ShowPopup( (std::string("While updating friends list, an error occurred: ")
- +e.what()).c_str());
- LOG("***** Error updating friends list: %s", e.what());
+ ShowPopup( (std::string("While updating friends list, an error occurred: ")
+ +e.what()).c_str() );
+ LOG("***** Error updating friends list: %s",e.what());
}
}
-void TwitterProto::ShowContactPopup(HANDLE hContact, const std::tstring &text)
+void TwitterProto::ShowContactPopup(HANDLE hContact,const std::string &text)
{
- if (!ServiceExists(MS_POPUP_ADDPOPUPT) || DBGetContactSettingByte(0, m_szModuleName, TWITTER_KEY_POPUP_SHOW, 0) == 0)
+ if(!ServiceExists(MS_POPUP_ADDPOPUPT) || DBGetContactSettingByte(0,
+ m_szModuleName,TWITTER_KEY_POPUP_SHOW,0) == 0)
+ {
return;
+ }
POPUPDATAT popup = {};
popup.lchContact = hContact;
- popup.iSeconds = db_dword_get(0, m_szModuleName, TWITTER_KEY_POPUP_TIMEOUT, 0);
+ popup.iSeconds = db_dword_get(0,m_szModuleName,TWITTER_KEY_POPUP_TIMEOUT,0);
- popup.colorBack = db_dword_get(0, m_szModuleName, TWITTER_KEY_POPUP_COLBACK, 0);
- if (popup.colorBack == 0xFFFFFFFF)
+ popup.colorBack = db_dword_get(0,m_szModuleName,TWITTER_KEY_POPUP_COLBACK,0);
+ if(popup.colorBack == 0xFFFFFFFF)
popup.colorBack = GetSysColor(COLOR_WINDOW);
- popup.colorText = db_dword_get(0, m_szModuleName, TWITTER_KEY_POPUP_COLTEXT, 0);
- if (popup.colorBack == 0xFFFFFFFF)
+ popup.colorText = db_dword_get(0,m_szModuleName,TWITTER_KEY_POPUP_COLTEXT,0);
+ if(popup.colorBack == 0xFFFFFFFF)
popup.colorBack = GetSysColor(COLOR_WINDOWTEXT);
DBVARIANT dbv;
- if ( !DBGetContactSettingString(hContact, "CList", "MyHandle", &dbv) ||
- !DBGetContactSettingString(hContact, m_szModuleName, TWITTER_KEY_UN, &dbv))
+ if( !DBGetContactSettingString(hContact,"CList","MyHandle",&dbv) ||
+ !DBGetContactSettingString(hContact,m_szModuleName,TWITTER_KEY_UN,&dbv) )
{
- mbcs_to_tcs(CP_UTF8, dbv.pszVal, popup.lptzContactName, MAX_CONTACTNAME);
+ mbcs_to_tcs(CP_UTF8,dbv.pszVal,popup.lptzContactName,MAX_CONTACTNAME);
DBFreeVariant(&dbv);
}
- CallService(MS_POPUP_ADDPOPUPT, reinterpret_cast<WPARAM>(text.c_str()), 0);
+ mbcs_to_tcs(CP_UTF8,text.c_str(),popup.lptzText,MAX_SECONDLINE);
+ CallService(MS_POPUP_ADDPOPUPT,reinterpret_cast<WPARAM>(&popup),0);
}
-void TwitterProto::UpdateStatuses(bool pre_read, bool popups)
+void TwitterProto::UpdateStatuses(bool pre_read, bool popups, bool tweetToMsg)
{
try
{
ScopedLock s(twitter_lock_);
- twitter::status_list updates = twit_.get_statuses(200, since_id_);
+ twitter::status_list updates = twit_.get_statuses(200,since_id_);
s.Unlock();
-
- if (!updates.empty())
- since_id_ = std::max(since_id_, updates[0].status.id);
+ if(!updates.empty()) {
+ since_id_ = std::max(since_id_, updates[0].status.id);
+ }
for(twitter::status_list::reverse_iterator i=updates.rbegin(); i!=updates.rend(); ++i)
{
- if (!pre_read && in_chat_)
+
+ if(!pre_read && in_chat_)
UpdateChat(*i);
- if (i->username == twit_.get_username())
+ if(i->username == twit_.get_username())
continue;
- HANDLE hContact = AddToClientList( _A2T(i->username.c_str()), _T(""));
+ HANDLE hContact = AddToClientList(i->username.c_str(),"");
- DBEVENTINFO dbei = {sizeof(dbei)};
+ // i think we maybe should just do that DBEF_READ line instead of stopping ALL this code. have to test.
+ if (tweetToMsg) {
+ DBEVENTINFO dbei = {sizeof(dbei)};
- dbei.pBlob = (BYTE*)(i->status.text.c_str());
- dbei.cbBlob = i->status.text.size()+1;
- dbei.eventType = TWITTER_DB_EVENT_TYPE_TWEET;
- dbei.flags = DBEF_UTF;
- //dbei.flags = DBEF_READ;
- dbei.timestamp = static_cast<DWORD>(i->status.time);
- dbei.szModule = m_szModuleName;
- CallService(MS_DB_EVENT_ADD, (WPARAM)hContact, (LPARAM)&dbei);
-
- DBWriteContactSettingTString(hContact, "CList", "StatusMsg", i->status.text.c_str());
-
- if ( !pre_read && popups )
- ShowContactPopup(hContact, i->status.text);
+ dbei.pBlob = (BYTE*)(i->status.text.c_str());
+ dbei.cbBlob = i->status.text.size()+1;
+ dbei.eventType = TWITTER_DB_EVENT_TYPE_TWEET;
+ dbei.flags = DBEF_UTF;
+ dbei.flags = DBEF_READ; // i had commented this line out.. can't remember why :( might need to do it again, uncommented for mrQQ for testing
+ dbei.timestamp = static_cast<DWORD>(i->status.time);
+ dbei.szModule = m_szModuleName;
+ CallService(MS_DB_EVENT_ADD, (WPARAM)hContact, (LPARAM)&dbei);
+ }
+
+ DBWriteContactSettingUTF8String(hContact,"CList","StatusMsg",
+ i->status.text.c_str());
+
+ if(!pre_read && popups)
+ ShowContactPopup(hContact,i->status.text);
}
- db_pod_set(0, m_szModuleName, TWITTER_KEY_SINCEID, since_id_);
+ db_pod_set(0,m_szModuleName,TWITTER_KEY_SINCEID,since_id_);
+ disconnectionCount = 0;
LOG("***** Status messages updated");
}
catch(const bad_response &)
{
- LOG("***** Bad response from server, signing off");
- SetStatus(ID_STATUS_OFFLINE);
+ ++disconnectionCount;
+ LOG("***** UpdateStatuses - Bad response from server, this has happened %d time(s)", disconnectionCount);
+ if (disconnectionCount > 2) {
+ LOG("***** UpdateStatuses - Too many bad responses from the server, signing off");
+ SetStatus(ID_STATUS_OFFLINE);
+ }
}
catch(const std::exception &e)
{
- ShowPopup( (std::string("While updating status messages, an error occurred: ")
- +e.what()).c_str());
- LOG("***** Error updating status messages: %s", e.what());
+ ShowPopup( (std::string("While updating status messages, an error occurred: ")
+ +e.what()).c_str() );
+ LOG("***** Error updating status messages: %s",e.what());
}
}
@@ -396,40 +636,54 @@ void TwitterProto::UpdateMessages(bool pre_read) twitter::status_list messages = twit_.get_direct(dm_since_id_);
s.Unlock();
- if (messages.size())
- dm_since_id_ = std::max(dm_since_id_, messages[0].status.id);
+ if(messages.size())
+ dm_since_id_ = std::max(dm_since_id_, messages[0].status.id);
- for(twitter::status_list::reverse_iterator i=messages.rbegin(); i!=messages.rend(); ++i) {
- HANDLE hContact = AddToClientList( _A2T(i->username.c_str()), _T(""));
+ for(twitter::status_list::reverse_iterator i=messages.rbegin(); i!=messages.rend(); ++i)
+ {
+ HANDLE hContact = AddToClientList(i->username.c_str(),"");
PROTORECVEVENT recv = {};
CCSDATA ccs = {};
- recv.flags = PREF_TCHAR;
- if (pre_read)
+ recv.flags = PREF_UTF;
+ if(pre_read)
recv.flags |= PREF_CREATEREAD;
- recv.szMessage = ( char* )i->status.text.c_str();
+ recv.szMessage = const_cast<char*>(i->status.text.c_str());
recv.timestamp = static_cast<DWORD>(i->status.time);
ccs.hContact = hContact;
ccs.szProtoService = PSR_MESSAGE;
ccs.wParam = ID_STATUS_ONLINE;
ccs.lParam = reinterpret_cast<LPARAM>(&recv);
- CallService(MS_PROTO_CHAINRECV, 0, reinterpret_cast<LPARAM>(&ccs));
+ CallService(MS_PROTO_CHAINRECV,0,reinterpret_cast<LPARAM>(&ccs));
}
- db_pod_set(0, m_szModuleName, TWITTER_KEY_DMSINCEID, dm_since_id_);
+ db_pod_set(0,m_szModuleName,TWITTER_KEY_DMSINCEID,dm_since_id_);
+ disconnectionCount = 0;
LOG("***** Direct messages updated");
}
catch(const bad_response &)
{
- LOG("***** Bad response from server, signing off");
- SetStatus(ID_STATUS_OFFLINE);
+ ++disconnectionCount;
+ LOG("***** UpdateMessages - Bad response from server, this has happened %d time(s)", disconnectionCount);
+ if (disconnectionCount > 2) {
+ LOG("***** UpdateMessages - Too many bad responses from the server, signing off");
+ SetStatus(ID_STATUS_OFFLINE);
+ }
}
catch(const std::exception &e)
{
- ShowPopup( (std::string("While updating direct messages, an error occurred: ")
- +e.what()).c_str());
- LOG("***** Error updating direct messages: %s", e.what());
+ ShowPopup( (std::string("While updating direct messages, an error occurred: ")
+ +e.what()).c_str() );
+ LOG("***** Error updating direct messages: %s",e.what());
}
+}
+
+void TwitterProto::resetOAuthKeys() {
+ DBDeleteContactSetting(0,m_szModuleName,TWITTER_KEY_OAUTH_ACCESS_TOK);
+ DBDeleteContactSetting(0,m_szModuleName,TWITTER_KEY_OAUTH_ACCESS_TOK_SECRET);
+ DBDeleteContactSetting(0,m_szModuleName,TWITTER_KEY_OAUTH_TOK);
+ DBDeleteContactSetting(0,m_szModuleName,TWITTER_KEY_OAUTH_TOK_SECRET);
+ DBDeleteContactSetting(0,m_szModuleName,TWITTER_KEY_OAUTH_PIN);
}
\ No newline at end of file diff --git a/protocols/Twitter/contacts.cpp b/protocols/Twitter/contacts.cpp index 03aad22601..9ab2f65905 100644 --- a/protocols/Twitter/contacts.cpp +++ b/protocols/Twitter/contacts.cpp @@ -6,7 +6,7 @@ it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
-This program is distributed in the hope that it will be useful,
+This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
@@ -15,16 +15,15 @@ You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
-#include "common.h"
#include "proto.h"
void TwitterProto::AddToListWorker(void *p)
{
// TODO: what happens if there is an error?
- if (p == 0)
+ if(p == 0)
return;
- TCHAR *name = static_cast<TCHAR*>(p);
+ char *name = static_cast<char*>(p);
try
{
@@ -33,24 +32,24 @@ void TwitterProto::AddToListWorker(void *p) s.Unlock();
HANDLE hContact = UsernameToHContact(name);
- UpdateAvatar(hContact, user.profile_image_url);
+ UpdateAvatar(hContact,user.profile_image_url);
}
catch(const std::exception &e)
{
ShowPopup((std::string("While adding a friend, an error occurred: ")
+e.what()).c_str());
- LOG("***** Error adding friend: %s", e.what());
+ LOG("***** Error adding friend: %s",e.what());
}
mir_free(name);
}
-HANDLE TwitterProto::AddToList(int flags, PROTOSEARCHRESULT *result)
+HANDLE TwitterProto::AddToList(int flags,PROTOSEARCHRESULT *result)
{
- if (m_iStatus != ID_STATUS_ONLINE)
+ if(m_iStatus != ID_STATUS_ONLINE)
return 0;
- ForkThread(&TwitterProto::AddToListWorker, this, mir_tstrdup(result->nick));
- return AddToClientList(result->nick, _T(""));
+ ForkThread(&TwitterProto::AddToListWorker,this,mir_strdup(result->nick));
+ return AddToClientList(result->nick,"");
}
// *************************
@@ -58,12 +57,12 @@ HANDLE TwitterProto::AddToList(int flags, PROTOSEARCHRESULT *result) void TwitterProto::UpdateInfoWorker(void *hContact)
{
twitter_user user;
- std::tstring username;
+ std::string username;
DBVARIANT dbv;
- if ( !DBGetContactSettingTString(hContact, m_szModuleName, TWITTER_KEY_UN, &dbv))
+ if( !DBGetContactSettingString(hContact,m_szModuleName,TWITTER_KEY_UN,&dbv) )
{
- username = dbv.ptszVal;
+ username = dbv.pszVal;
DBFreeVariant(&dbv);
}
else
@@ -71,24 +70,24 @@ void TwitterProto::UpdateInfoWorker(void *hContact) {
ScopedLock s(twitter_lock_);
- twit_.get_info(username, &user);
+ twit_.get_info(username,&user);
}
- UpdateAvatar(hContact, user.profile_image_url, true);
- ProtoBroadcastAck(m_szModuleName, hContact, ACKTYPE_GETINFO, ACKRESULT_SUCCESS, 0, 0);
+ UpdateAvatar(hContact,user.profile_image_url,true);
+ ProtoBroadcastAck(m_szModuleName,hContact,ACKTYPE_GETINFO,ACKRESULT_SUCCESS,0,0);
}
-int TwitterProto::GetInfo(HANDLE hContact, int info_type)
+int TwitterProto::GetInfo(HANDLE hContact,int info_type)
{
- if (m_iStatus != ID_STATUS_ONLINE)
+ if(m_iStatus != ID_STATUS_ONLINE)
return 1;
- if (!IsMyContact(hContact)) // Do nothing for chat rooms
+ if(!IsMyContact(hContact)) // Do nothing for chat rooms
return 1;
- if (info_type == 0) // From clicking "Update" in the Userinfo dialog
+ if(info_type == 0) // From clicking "Update" in the Userinfo dialog
{
- ForkThread(&TwitterProto::UpdateInfoWorker, this, hContact);
+ ForkThread(&TwitterProto::UpdateInfoWorker,this,hContact);
return 0;
}
@@ -99,15 +98,15 @@ int TwitterProto::GetInfo(HANDLE hContact, int info_type) struct search_query
{
- search_query(const std::tstring &query, bool by_email) : query(query), by_email(by_email)
+ search_query(const std::string &query,bool by_email) : query(query),by_email(by_email)
{}
- std::tstring query;
+ std::string query;
bool by_email;
};
void TwitterProto::DoSearch(void *p)
{
- if (p == 0)
+ if(p == 0)
return;
search_query *query = static_cast<search_query*>(p);
@@ -118,44 +117,44 @@ void TwitterProto::DoSearch(void *p) try
{
ScopedLock s(twitter_lock_);
- if (query->by_email)
- found = twit_.get_info_by_email(query->query, &info);
+ if(query->by_email)
+ found = twit_.get_info_by_email(query->query,&info);
else
- found = twit_.get_info(query->query, &info);
+ found = twit_.get_info(query->query,&info);
}
catch(const std::exception &e)
{
ShowPopup( (std::string("While searching for contacts, an error occurred: ")
- +e.what()).c_str());
- LOG("***** Error searching for contacts: %s", e.what());
+ +e.what()).c_str() );
+ LOG("***** Error searching for contacts: %s",e.what());
}
- if (found)
+ if(found)
{
- psr.nick = ( TCHAR* )info.username. c_str();
- psr.firstName = ( TCHAR* )info.real_name.c_str();
+ psr.nick = const_cast<char*>( info.username. c_str() );
+ psr.firstName = const_cast<char*>( info.real_name.c_str() );
- ProtoBroadcastAck(m_szModuleName, 0, ACKTYPE_SEARCH, ACKRESULT_DATA, (HANDLE)1,
+ ProtoBroadcastAck(m_szModuleName,0,ACKTYPE_SEARCH,ACKRESULT_DATA,(HANDLE)1,
(LPARAM)&psr);
- ProtoBroadcastAck(m_szModuleName, 0, ACKTYPE_SEARCH, ACKRESULT_SUCCESS, (HANDLE)1, 0);
+ ProtoBroadcastAck(m_szModuleName,0,ACKTYPE_SEARCH,ACKRESULT_SUCCESS,(HANDLE)1,0);
}
else
{
- ProtoBroadcastAck(m_szModuleName, 0, ACKTYPE_SEARCH, ACKRESULT_SUCCESS, (HANDLE)1, 0);
+ ProtoBroadcastAck(m_szModuleName,0,ACKTYPE_SEARCH,ACKRESULT_SUCCESS,(HANDLE)1,0);
}
delete query;
}
-HANDLE TwitterProto::SearchBasic(const TCHAR *username)
+HANDLE TwitterProto::SearchBasic(const char *username)
{
- ForkThread(&TwitterProto::DoSearch, this, new search_query(username, false));
+ ForkThread(&TwitterProto::DoSearch,this,new search_query(username,false));
return (HANDLE)1;
}
-HANDLE TwitterProto::SearchByEmail(const TCHAR *email)
+HANDLE TwitterProto::SearchByEmail(const char *email)
{
- ForkThread(&TwitterProto::DoSearch, this, new search_query(email, true));
+ ForkThread(&TwitterProto::DoSearch,this,new search_query(email,true));
return (HANDLE)1;
}
@@ -163,40 +162,47 @@ HANDLE TwitterProto::SearchByEmail(const TCHAR *email) void TwitterProto::GetAwayMsgWorker(void *hContact)
{
- if (hContact == 0)
+ if(hContact == 0)
return;
DBVARIANT dbv;
- if ( !DBGetContactSettingTString(hContact, "CList", "StatusMsg", &dbv)) {
- ProtoBroadcastAck(m_szModuleName, hContact, ACKTYPE_AWAYMSG, ACKRESULT_SUCCESS, (HANDLE)1, (LPARAM)dbv.ptszVal);
+ if( !DBGetContactSettingString(hContact,"CList","StatusMsg",&dbv) )
+ {
+ ProtoBroadcastAck(m_szModuleName,hContact,ACKTYPE_AWAYMSG,ACKRESULT_SUCCESS,
+ (HANDLE)1,(LPARAM)dbv.pszVal);
DBFreeVariant(&dbv);
}
- else ProtoBroadcastAck(m_szModuleName, hContact, ACKTYPE_AWAYMSG, ACKRESULT_FAILED, (HANDLE)1, 0);
+ else
+ {
+ ProtoBroadcastAck(m_szModuleName,hContact,ACKTYPE_AWAYMSG,ACKRESULT_FAILED,
+ (HANDLE)1,(LPARAM)0);
+ }
}
HANDLE TwitterProto::GetAwayMsg(HANDLE hContact)
{
- ForkThread(&TwitterProto::GetAwayMsgWorker, this, hContact);
+ ForkThread(&TwitterProto::GetAwayMsgWorker, this,hContact);
return (HANDLE)1;
}
-int TwitterProto::OnContactDeleted(WPARAM wParam, LPARAM lParam)
+int TwitterProto::OnContactDeleted(WPARAM wParam,LPARAM lParam)
{
- if (m_iStatus != ID_STATUS_ONLINE)
+ if(m_iStatus != ID_STATUS_ONLINE)
return 0;
const HANDLE hContact = reinterpret_cast<HANDLE>(wParam);
- if (!IsMyContact(hContact))
+ if(!IsMyContact(hContact))
return 0;
DBVARIANT dbv;
- if ( !DBGetContactSettingTString(hContact, m_szModuleName, TWITTER_KEY_UN, &dbv)) {
- if ( in_chat_ )
- DeleteChatContact(dbv.ptszVal);
+ if( !DBGetContactSettingString(hContact,m_szModuleName,TWITTER_KEY_UN,&dbv) )
+ {
+ if(in_chat_)
+ DeleteChatContact(dbv.pszVal);
ScopedLock s(twitter_lock_);
- twit_.remove_friend(dbv.ptszVal); // Be careful about this until Miranda is fixed
+ twit_.remove_friend(dbv.pszVal); // Be careful about this until Miranda is fixed
DBFreeVariant(&dbv);
}
return 0;
@@ -204,69 +210,82 @@ int TwitterProto::OnContactDeleted(WPARAM wParam, LPARAM lParam) // *************************
-bool TwitterProto::IsMyContact(HANDLE hContact, bool include_chat)
+bool TwitterProto::IsMyContact(HANDLE hContact,bool include_chat)
{
- const char *proto = reinterpret_cast<char*>( CallService(MS_PROTO_GETCONTACTBASEPROTO,
- reinterpret_cast<WPARAM>(hContact), 0));
+ const char *proto = reinterpret_cast<char*>( CallService(MS_PROTO_GETCONTACTBASEPROTO,
+ reinterpret_cast<WPARAM>(hContact),0) );
- if (proto && strcmp(m_szModuleName, proto) == 0)
+ if(proto && strcmp(m_szModuleName,proto) == 0)
{
- if (include_chat)
+ if(include_chat)
return true;
else
- return DBGetContactSettingByte(hContact, m_szModuleName, "ChatRoom", 0) == 0;
+ return DBGetContactSettingByte(hContact,m_szModuleName,"ChatRoom",0) == 0;
}
else
return false;
}
-HANDLE TwitterProto::UsernameToHContact(const TCHAR *name)
+HANDLE TwitterProto::UsernameToHContact(const char *name)
{
- for(HANDLE hContact = (HANDLE)CallService(MS_DB_CONTACT_FINDFIRST, 0, 0);
+ for(HANDLE hContact = (HANDLE)CallService(MS_DB_CONTACT_FINDFIRST,0,0);
hContact;
- hContact = (HANDLE)CallService(MS_DB_CONTACT_FINDNEXT, (WPARAM)hContact, 0))
+ hContact = (HANDLE)CallService(MS_DB_CONTACT_FINDNEXT,(WPARAM)hContact,0) )
{
- if (!IsMyContact(hContact))
+ if(!IsMyContact(hContact))
continue;
DBVARIANT dbv;
- if ( !DBGetContactSettingTString(hContact, m_szModuleName, TWITTER_KEY_UN, &dbv)) {
- if ( lstrcmp(name, dbv.ptszVal) == 0) {
+ if( !DBGetContactSettingString(hContact,m_szModuleName,TWITTER_KEY_UN,&dbv) )
+ {
+ if(strcmp(name,dbv.pszVal) == 0)
+ {
DBFreeVariant(&dbv);
return hContact;
}
- DBFreeVariant(&dbv);
+ else
+ DBFreeVariant(&dbv);
}
}
return 0;
}
-HANDLE TwitterProto::AddToClientList(const TCHAR *name, const TCHAR *status)
+HANDLE TwitterProto::AddToClientList(const char *name,const char *status)
{
// First, check if this contact exists
HANDLE hContact = UsernameToHContact(name);
- if (hContact)
+ if(hContact)
return hContact;
- if (in_chat_)
+ if(in_chat_)
AddChatContact(name);
// If not, make a new contact!
hContact = (HANDLE)CallService(MS_DB_CONTACT_ADD, 0, 0);
- if (hContact ) {
- if (CallService(MS_PROTO_ADDTOCONTACT, (WPARAM)hContact, (LPARAM)m_szModuleName) == 0) {
- DBWriteContactSettingTString(hContact, m_szModuleName, TWITTER_KEY_UN, name);
- DBWriteContactSettingWord(hContact, m_szModuleName, "Status", ID_STATUS_ONLINE);
- DBWriteContactSettingTString(hContact, "CList", "StatusMsg", status);
+ if(hContact)
+ {
+ if(CallService(MS_PROTO_ADDTOCONTACT,(WPARAM)hContact,(LPARAM)m_szModuleName) == 0)
+ {
+ DBWriteContactSettingString (hContact,m_szModuleName,TWITTER_KEY_UN,name);
+ DBWriteContactSettingWord (hContact,m_szModuleName,"Status",ID_STATUS_ONLINE);
+ DBWriteContactSettingUTF8String(hContact,"CList","StatusMsg",status);
+
+ std::string url = profile_base_url(twit_.get_base_url())+http::url_encode(name);
+ DBWriteContactSettingString (hContact,m_szModuleName,"Homepage",url.c_str());
+
+ DBVARIANT dbv;
+ if( !DBGetContactSettingTString(NULL,m_szModuleName,TWITTER_KEY_GROUP,&dbv) )
+ {
+ DBWriteContactSettingTString(hContact,"CList","Group",dbv.ptszVal);
+ DBFreeVariant(&dbv);
+ }
- std::string url = profile_base_url(twit_.get_base_url()) + http::url_encode((char*)_T2A(name));
- DBWriteContactSettingString(hContact, m_szModuleName, "Homepage", url.c_str());
return hContact;
}
-
- CallService(MS_DB_CONTACT_DELETE, (WPARAM)hContact, 0);
+ else
+ CallService(MS_DB_CONTACT_DELETE,(WPARAM)hContact,0);
}
return 0;
@@ -274,14 +293,14 @@ HANDLE TwitterProto::AddToClientList(const TCHAR *name, const TCHAR *status) void TwitterProto::SetAllContactStatuses(int status)
{
- for(HANDLE hContact = (HANDLE)CallService(MS_DB_CONTACT_FINDFIRST, 0, 0);
+ for(HANDLE hContact = (HANDLE)CallService(MS_DB_CONTACT_FINDFIRST,0,0);
hContact;
- hContact = (HANDLE)CallService(MS_DB_CONTACT_FINDNEXT, (WPARAM)hContact, 0))
+ hContact = (HANDLE)CallService(MS_DB_CONTACT_FINDNEXT,(WPARAM)hContact,0) )
{
- if (!IsMyContact(hContact))
+ if(!IsMyContact(hContact))
continue;
- DBWriteContactSettingWord(hContact, m_szModuleName, "Status", status);
+ DBWriteContactSettingWord(hContact,m_szModuleName,"Status",status);
}
SetChatStatus(status);
diff --git a/protocols/Twitter/LICENSE.txt b/protocols/Twitter/docs/LICENSE.txt index 818433ecc0..94a9ed024d 100644 --- a/protocols/Twitter/LICENSE.txt +++ b/protocols/Twitter/docs/LICENSE.txt @@ -1,674 +1,674 @@ - GNU GENERAL PUBLIC LICENSE
- Version 3, 29 June 2007
-
- Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
- Everyone is permitted to copy and distribute verbatim copies
- of this license document, but changing it is not allowed.
-
- Preamble
-
- The GNU General Public License is a free, copyleft license for
-software and other kinds of works.
-
- The licenses for most software and other practical works are designed
-to take away your freedom to share and change the works. By contrast,
-the GNU General Public License is intended to guarantee your freedom to
-share and change all versions of a program--to make sure it remains free
-software for all its users. We, the Free Software Foundation, use the
-GNU General Public License for most of our software; it applies also to
-any other work released this way by its authors. You can apply it to
-your programs, too.
-
- When we speak of free software, we are referring to freedom, not
-price. Our General Public Licenses are designed to make sure that you
-have the freedom to distribute copies of free software (and charge for
-them if you wish), that you receive source code or can get it if you
-want it, that you can change the software or use pieces of it in new
-free programs, and that you know you can do these things.
-
- To protect your rights, we need to prevent others from denying you
-these rights or asking you to surrender the rights. Therefore, you have
-certain responsibilities if you distribute copies of the software, or if
-you modify it: responsibilities to respect the freedom of others.
-
- For example, if you distribute copies of such a program, whether
-gratis or for a fee, you must pass on to the recipients the same
-freedoms that you received. You must make sure that they, too, receive
-or can get the source code. And you must show them these terms so they
-know their rights.
-
- Developers that use the GNU GPL protect your rights with two steps:
-(1) assert copyright on the software, and (2) offer you this License
-giving you legal permission to copy, distribute and/or modify it.
-
- For the developers' and authors' protection, the GPL clearly explains
-that there is no warranty for this free software. For both users' and
-authors' sake, the GPL requires that modified versions be marked as
-changed, so that their problems will not be attributed erroneously to
-authors of previous versions.
-
- Some devices are designed to deny users access to install or run
-modified versions of the software inside them, although the manufacturer
-can do so. This is fundamentally incompatible with the aim of
-protecting users' freedom to change the software. The systematic
-pattern of such abuse occurs in the area of products for individuals to
-use, which is precisely where it is most unacceptable. Therefore, we
-have designed this version of the GPL to prohibit the practice for those
-products. If such problems arise substantially in other domains, we
-stand ready to extend this provision to those domains in future versions
-of the GPL, as needed to protect the freedom of users.
-
- Finally, every program is threatened constantly by software patents.
-States should not allow patents to restrict development and use of
-software on general-purpose computers, but in those that do, we wish to
-avoid the special danger that patents applied to a free program could
-make it effectively proprietary. To prevent this, the GPL assures that
-patents cannot be used to render the program non-free.
-
- The precise terms and conditions for copying, distribution and
-modification follow.
-
- TERMS AND CONDITIONS
-
- 0. Definitions.
-
- "This License" refers to version 3 of the GNU General Public License.
-
- "Copyright" also means copyright-like laws that apply to other kinds of
-works, such as semiconductor masks.
-
- "The Program" refers to any copyrightable work licensed under this
-License. Each licensee is addressed as "you". "Licensees" and
-"recipients" may be individuals or organizations.
-
- To "modify" a work means to copy from or adapt all or part of the work
-in a fashion requiring copyright permission, other than the making of an
-exact copy. The resulting work is called a "modified version" of the
-earlier work or a work "based on" the earlier work.
-
- A "covered work" means either the unmodified Program or a work based
-on the Program.
-
- To "propagate" a work means to do anything with it that, without
-permission, would make you directly or secondarily liable for
-infringement under applicable copyright law, except executing it on a
-computer or modifying a private copy. Propagation includes copying,
-distribution (with or without modification), making available to the
-public, and in some countries other activities as well.
-
- To "convey" a work means any kind of propagation that enables other
-parties to make or receive copies. Mere interaction with a user through
-a computer network, with no transfer of a copy, is not conveying.
-
- An interactive user interface displays "Appropriate Legal Notices"
-to the extent that it includes a convenient and prominently visible
-feature that (1) displays an appropriate copyright notice, and (2)
-tells the user that there is no warranty for the work (except to the
-extent that warranties are provided), that licensees may convey the
-work under this License, and how to view a copy of this License. If
-the interface presents a list of user commands or options, such as a
-menu, a prominent item in the list meets this criterion.
-
- 1. Source Code.
-
- The "source code" for a work means the preferred form of the work
-for making modifications to it. "Object code" means any non-source
-form of a work.
-
- A "Standard Interface" means an interface that either is an official
-standard defined by a recognized standards body, or, in the case of
-interfaces specified for a particular programming language, one that
-is widely used among developers working in that language.
-
- The "System Libraries" of an executable work include anything, other
-than the work as a whole, that (a) is included in the normal form of
-packaging a Major Component, but which is not part of that Major
-Component, and (b) serves only to enable use of the work with that
-Major Component, or to implement a Standard Interface for which an
-implementation is available to the public in source code form. A
-"Major Component", in this context, means a major essential component
-(kernel, window system, and so on) of the specific operating system
-(if any) on which the executable work runs, or a compiler used to
-produce the work, or an object code interpreter used to run it.
-
- The "Corresponding Source" for a work in object code form means all
-the source code needed to generate, install, and (for an executable
-work) run the object code and to modify the work, including scripts to
-control those activities. However, it does not include the work's
-System Libraries, or general-purpose tools or generally available free
-programs which are used unmodified in performing those activities but
-which are not part of the work. For example, Corresponding Source
-includes interface definition files associated with source files for
-the work, and the source code for shared libraries and dynamically
-linked subprograms that the work is specifically designed to require,
-such as by intimate data communication or control flow between those
-subprograms and other parts of the work.
-
- The Corresponding Source need not include anything that users
-can regenerate automatically from other parts of the Corresponding
-Source.
-
- The Corresponding Source for a work in source code form is that
-same work.
-
- 2. Basic Permissions.
-
- All rights granted under this License are granted for the term of
-copyright on the Program, and are irrevocable provided the stated
-conditions are met. This License explicitly affirms your unlimited
-permission to run the unmodified Program. The output from running a
-covered work is covered by this License only if the output, given its
-content, constitutes a covered work. This License acknowledges your
-rights of fair use or other equivalent, as provided by copyright law.
-
- You may make, run and propagate covered works that you do not
-convey, without conditions so long as your license otherwise remains
-in force. You may convey covered works to others for the sole purpose
-of having them make modifications exclusively for you, or provide you
-with facilities for running those works, provided that you comply with
-the terms of this License in conveying all material for which you do
-not control copyright. Those thus making or running the covered works
-for you must do so exclusively on your behalf, under your direction
-and control, on terms that prohibit them from making any copies of
-your copyrighted material outside their relationship with you.
-
- Conveying under any other circumstances is permitted solely under
-the conditions stated below. Sublicensing is not allowed; section 10
-makes it unnecessary.
-
- 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
-
- No covered work shall be deemed part of an effective technological
-measure under any applicable law fulfilling obligations under article
-11 of the WIPO copyright treaty adopted on 20 December 1996, or
-similar laws prohibiting or restricting circumvention of such
-measures.
-
- When you convey a covered work, you waive any legal power to forbid
-circumvention of technological measures to the extent such circumvention
-is effected by exercising rights under this License with respect to
-the covered work, and you disclaim any intention to limit operation or
-modification of the work as a means of enforcing, against the work's
-users, your or third parties' legal rights to forbid circumvention of
-technological measures.
-
- 4. Conveying Verbatim Copies.
-
- You may convey verbatim copies of the Program's source code as you
-receive it, in any medium, provided that you conspicuously and
-appropriately publish on each copy an appropriate copyright notice;
-keep intact all notices stating that this License and any
-non-permissive terms added in accord with section 7 apply to the code;
-keep intact all notices of the absence of any warranty; and give all
-recipients a copy of this License along with the Program.
-
- You may charge any price or no price for each copy that you convey,
-and you may offer support or warranty protection for a fee.
-
- 5. Conveying Modified Source Versions.
-
- You may convey a work based on the Program, or the modifications to
-produce it from the Program, in the form of source code under the
-terms of section 4, provided that you also meet all of these conditions:
-
- a) The work must carry prominent notices stating that you modified
- it, and giving a relevant date.
-
- b) The work must carry prominent notices stating that it is
- released under this License and any conditions added under section
- 7. This requirement modifies the requirement in section 4 to
- "keep intact all notices".
-
- c) You must license the entire work, as a whole, under this
- License to anyone who comes into possession of a copy. This
- License will therefore apply, along with any applicable section 7
- additional terms, to the whole of the work, and all its parts,
- regardless of how they are packaged. This License gives no
- permission to license the work in any other way, but it does not
- invalidate such permission if you have separately received it.
-
- d) If the work has interactive user interfaces, each must display
- Appropriate Legal Notices; however, if the Program has interactive
- interfaces that do not display Appropriate Legal Notices, your
- work need not make them do so.
-
- A compilation of a covered work with other separate and independent
-works, which are not by their nature extensions of the covered work,
-and which are not combined with it such as to form a larger program,
-in or on a volume of a storage or distribution medium, is called an
-"aggregate" if the compilation and its resulting copyright are not
-used to limit the access or legal rights of the compilation's users
-beyond what the individual works permit. Inclusion of a covered work
-in an aggregate does not cause this License to apply to the other
-parts of the aggregate.
-
- 6. Conveying Non-Source Forms.
-
- You may convey a covered work in object code form under the terms
-of sections 4 and 5, provided that you also convey the
-machine-readable Corresponding Source under the terms of this License,
-in one of these ways:
-
- a) Convey the object code in, or embodied in, a physical product
- (including a physical distribution medium), accompanied by the
- Corresponding Source fixed on a durable physical medium
- customarily used for software interchange.
-
- b) Convey the object code in, or embodied in, a physical product
- (including a physical distribution medium), accompanied by a
- written offer, valid for at least three years and valid for as
- long as you offer spare parts or customer support for that product
- model, to give anyone who possesses the object code either (1) a
- copy of the Corresponding Source for all the software in the
- product that is covered by this License, on a durable physical
- medium customarily used for software interchange, for a price no
- more than your reasonable cost of physically performing this
- conveying of source, or (2) access to copy the
- Corresponding Source from a network server at no charge.
-
- c) Convey individual copies of the object code with a copy of the
- written offer to provide the Corresponding Source. This
- alternative is allowed only occasionally and noncommercially, and
- only if you received the object code with such an offer, in accord
- with subsection 6b.
-
- d) Convey the object code by offering access from a designated
- place (gratis or for a charge), and offer equivalent access to the
- Corresponding Source in the same way through the same place at no
- further charge. You need not require recipients to copy the
- Corresponding Source along with the object code. If the place to
- copy the object code is a network server, the Corresponding Source
- may be on a different server (operated by you or a third party)
- that supports equivalent copying facilities, provided you maintain
- clear directions next to the object code saying where to find the
- Corresponding Source. Regardless of what server hosts the
- Corresponding Source, you remain obligated to ensure that it is
- available for as long as needed to satisfy these requirements.
-
- e) Convey the object code using peer-to-peer transmission, provided
- you inform other peers where the object code and Corresponding
- Source of the work are being offered to the general public at no
- charge under subsection 6d.
-
- A separable portion of the object code, whose source code is excluded
-from the Corresponding Source as a System Library, need not be
-included in conveying the object code work.
-
- A "User Product" is either (1) a "consumer product", which means any
-tangible personal property which is normally used for personal, family,
-or household purposes, or (2) anything designed or sold for incorporation
-into a dwelling. In determining whether a product is a consumer product,
-doubtful cases shall be resolved in favor of coverage. For a particular
-product received by a particular user, "normally used" refers to a
-typical or common use of that class of product, regardless of the status
-of the particular user or of the way in which the particular user
-actually uses, or expects or is expected to use, the product. A product
-is a consumer product regardless of whether the product has substantial
-commercial, industrial or non-consumer uses, unless such uses represent
-the only significant mode of use of the product.
-
- "Installation Information" for a User Product means any methods,
-procedures, authorization keys, or other information required to install
-and execute modified versions of a covered work in that User Product from
-a modified version of its Corresponding Source. The information must
-suffice to ensure that the continued functioning of the modified object
-code is in no case prevented or interfered with solely because
-modification has been made.
-
- If you convey an object code work under this section in, or with, or
-specifically for use in, a User Product, and the conveying occurs as
-part of a transaction in which the right of possession and use of the
-User Product is transferred to the recipient in perpetuity or for a
-fixed term (regardless of how the transaction is characterized), the
-Corresponding Source conveyed under this section must be accompanied
-by the Installation Information. But this requirement does not apply
-if neither you nor any third party retains the ability to install
-modified object code on the User Product (for example, the work has
-been installed in ROM).
-
- The requirement to provide Installation Information does not include a
-requirement to continue to provide support service, warranty, or updates
-for a work that has been modified or installed by the recipient, or for
-the User Product in which it has been modified or installed. Access to a
-network may be denied when the modification itself materially and
-adversely affects the operation of the network or violates the rules and
-protocols for communication across the network.
-
- Corresponding Source conveyed, and Installation Information provided,
-in accord with this section must be in a format that is publicly
-documented (and with an implementation available to the public in
-source code form), and must require no special password or key for
-unpacking, reading or copying.
-
- 7. Additional Terms.
-
- "Additional permissions" are terms that supplement the terms of this
-License by making exceptions from one or more of its conditions.
-Additional permissions that are applicable to the entire Program shall
-be treated as though they were included in this License, to the extent
-that they are valid under applicable law. If additional permissions
-apply only to part of the Program, that part may be used separately
-under those permissions, but the entire Program remains governed by
-this License without regard to the additional permissions.
-
- When you convey a copy of a covered work, you may at your option
-remove any additional permissions from that copy, or from any part of
-it. (Additional permissions may be written to require their own
-removal in certain cases when you modify the work.) You may place
-additional permissions on material, added by you to a covered work,
-for which you have or can give appropriate copyright permission.
-
- Notwithstanding any other provision of this License, for material you
-add to a covered work, you may (if authorized by the copyright holders of
-that material) supplement the terms of this License with terms:
-
- a) Disclaiming warranty or limiting liability differently from the
- terms of sections 15 and 16 of this License; or
-
- b) Requiring preservation of specified reasonable legal notices or
- author attributions in that material or in the Appropriate Legal
- Notices displayed by works containing it; or
-
- c) Prohibiting misrepresentation of the origin of that material, or
- requiring that modified versions of such material be marked in
- reasonable ways as different from the original version; or
-
- d) Limiting the use for publicity purposes of names of licensors or
- authors of the material; or
-
- e) Declining to grant rights under trademark law for use of some
- trade names, trademarks, or service marks; or
-
- f) Requiring indemnification of licensors and authors of that
- material by anyone who conveys the material (or modified versions of
- it) with contractual assumptions of liability to the recipient, for
- any liability that these contractual assumptions directly impose on
- those licensors and authors.
-
- All other non-permissive additional terms are considered "further
-restrictions" within the meaning of section 10. If the Program as you
-received it, or any part of it, contains a notice stating that it is
-governed by this License along with a term that is a further
-restriction, you may remove that term. If a license document contains
-a further restriction but permits relicensing or conveying under this
-License, you may add to a covered work material governed by the terms
-of that license document, provided that the further restriction does
-not survive such relicensing or conveying.
-
- If you add terms to a covered work in accord with this section, you
-must place, in the relevant source files, a statement of the
-additional terms that apply to those files, or a notice indicating
-where to find the applicable terms.
-
- Additional terms, permissive or non-permissive, may be stated in the
-form of a separately written license, or stated as exceptions;
-the above requirements apply either way.
-
- 8. Termination.
-
- You may not propagate or modify a covered work except as expressly
-provided under this License. Any attempt otherwise to propagate or
-modify it is void, and will automatically terminate your rights under
-this License (including any patent licenses granted under the third
-paragraph of section 11).
-
- However, if you cease all violation of this License, then your
-license from a particular copyright holder is reinstated (a)
-provisionally, unless and until the copyright holder explicitly and
-finally terminates your license, and (b) permanently, if the copyright
-holder fails to notify you of the violation by some reasonable means
-prior to 60 days after the cessation.
-
- Moreover, your license from a particular copyright holder is
-reinstated permanently if the copyright holder notifies you of the
-violation by some reasonable means, this is the first time you have
-received notice of violation of this License (for any work) from that
-copyright holder, and you cure the violation prior to 30 days after
-your receipt of the notice.
-
- Termination of your rights under this section does not terminate the
-licenses of parties who have received copies or rights from you under
-this License. If your rights have been terminated and not permanently
-reinstated, you do not qualify to receive new licenses for the same
-material under section 10.
-
- 9. Acceptance Not Required for Having Copies.
-
- You are not required to accept this License in order to receive or
-run a copy of the Program. Ancillary propagation of a covered work
-occurring solely as a consequence of using peer-to-peer transmission
-to receive a copy likewise does not require acceptance. However,
-nothing other than this License grants you permission to propagate or
-modify any covered work. These actions infringe copyright if you do
-not accept this License. Therefore, by modifying or propagating a
-covered work, you indicate your acceptance of this License to do so.
-
- 10. Automatic Licensing of Downstream Recipients.
-
- Each time you convey a covered work, the recipient automatically
-receives a license from the original licensors, to run, modify and
-propagate that work, subject to this License. You are not responsible
-for enforcing compliance by third parties with this License.
-
- An "entity transaction" is a transaction transferring control of an
-organization, or substantially all assets of one, or subdividing an
-organization, or merging organizations. If propagation of a covered
-work results from an entity transaction, each party to that
-transaction who receives a copy of the work also receives whatever
-licenses to the work the party's predecessor in interest had or could
-give under the previous paragraph, plus a right to possession of the
-Corresponding Source of the work from the predecessor in interest, if
-the predecessor has it or can get it with reasonable efforts.
-
- You may not impose any further restrictions on the exercise of the
-rights granted or affirmed under this License. For example, you may
-not impose a license fee, royalty, or other charge for exercise of
-rights granted under this License, and you may not initiate litigation
-(including a cross-claim or counterclaim in a lawsuit) alleging that
-any patent claim is infringed by making, using, selling, offering for
-sale, or importing the Program or any portion of it.
-
- 11. Patents.
-
- A "contributor" is a copyright holder who authorizes use under this
-License of the Program or a work on which the Program is based. The
-work thus licensed is called the contributor's "contributor version".
-
- A contributor's "essential patent claims" are all patent claims
-owned or controlled by the contributor, whether already acquired or
-hereafter acquired, that would be infringed by some manner, permitted
-by this License, of making, using, or selling its contributor version,
-but do not include claims that would be infringed only as a
-consequence of further modification of the contributor version. For
-purposes of this definition, "control" includes the right to grant
-patent sublicenses in a manner consistent with the requirements of
-this License.
-
- Each contributor grants you a non-exclusive, worldwide, royalty-free
-patent license under the contributor's essential patent claims, to
-make, use, sell, offer for sale, import and otherwise run, modify and
-propagate the contents of its contributor version.
-
- In the following three paragraphs, a "patent license" is any express
-agreement or commitment, however denominated, not to enforce a patent
-(such as an express permission to practice a patent or covenant not to
-sue for patent infringement). To "grant" such a patent license to a
-party means to make such an agreement or commitment not to enforce a
-patent against the party.
-
- If you convey a covered work, knowingly relying on a patent license,
-and the Corresponding Source of the work is not available for anyone
-to copy, free of charge and under the terms of this License, through a
-publicly available network server or other readily accessible means,
-then you must either (1) cause the Corresponding Source to be so
-available, or (2) arrange to deprive yourself of the benefit of the
-patent license for this particular work, or (3) arrange, in a manner
-consistent with the requirements of this License, to extend the patent
-license to downstream recipients. "Knowingly relying" means you have
-actual knowledge that, but for the patent license, your conveying the
-covered work in a country, or your recipient's use of the covered work
-in a country, would infringe one or more identifiable patents in that
-country that you have reason to believe are valid.
-
- If, pursuant to or in connection with a single transaction or
-arrangement, you convey, or propagate by procuring conveyance of, a
-covered work, and grant a patent license to some of the parties
-receiving the covered work authorizing them to use, propagate, modify
-or convey a specific copy of the covered work, then the patent license
-you grant is automatically extended to all recipients of the covered
-work and works based on it.
-
- A patent license is "discriminatory" if it does not include within
-the scope of its coverage, prohibits the exercise of, or is
-conditioned on the non-exercise of one or more of the rights that are
-specifically granted under this License. You may not convey a covered
-work if you are a party to an arrangement with a third party that is
-in the business of distributing software, under which you make payment
-to the third party based on the extent of your activity of conveying
-the work, and under which the third party grants, to any of the
-parties who would receive the covered work from you, a discriminatory
-patent license (a) in connection with copies of the covered work
-conveyed by you (or copies made from those copies), or (b) primarily
-for and in connection with specific products or compilations that
-contain the covered work, unless you entered into that arrangement,
-or that patent license was granted, prior to 28 March 2007.
-
- Nothing in this License shall be construed as excluding or limiting
-any implied license or other defenses to infringement that may
-otherwise be available to you under applicable patent law.
-
- 12. No Surrender of Others' Freedom.
-
- If conditions are imposed on you (whether by court order, agreement or
-otherwise) that contradict the conditions of this License, they do not
-excuse you from the conditions of this License. If you cannot convey a
-covered work so as to satisfy simultaneously your obligations under this
-License and any other pertinent obligations, then as a consequence you may
-not convey it at all. For example, if you agree to terms that obligate you
-to collect a royalty for further conveying from those to whom you convey
-the Program, the only way you could satisfy both those terms and this
-License would be to refrain entirely from conveying the Program.
-
- 13. Use with the GNU Affero General Public License.
-
- Notwithstanding any other provision of this License, you have
-permission to link or combine any covered work with a work licensed
-under version 3 of the GNU Affero General Public License into a single
-combined work, and to convey the resulting work. The terms of this
-License will continue to apply to the part which is the covered work,
-but the special requirements of the GNU Affero General Public License,
-section 13, concerning interaction through a network will apply to the
-combination as such.
-
- 14. Revised Versions of this License.
-
- The Free Software Foundation may publish revised and/or new versions of
-the GNU General Public License from time to time. Such new versions will
-be similar in spirit to the present version, but may differ in detail to
-address new problems or concerns.
-
- Each version is given a distinguishing version number. If the
-Program specifies that a certain numbered version of the GNU General
-Public License "or any later version" applies to it, you have the
-option of following the terms and conditions either of that numbered
-version or of any later version published by the Free Software
-Foundation. If the Program does not specify a version number of the
-GNU General Public License, you may choose any version ever published
-by the Free Software Foundation.
-
- If the Program specifies that a proxy can decide which future
-versions of the GNU General Public License can be used, that proxy's
-public statement of acceptance of a version permanently authorizes you
-to choose that version for the Program.
-
- Later license versions may give you additional or different
-permissions. However, no additional obligations are imposed on any
-author or copyright holder as a result of your choosing to follow a
-later version.
-
- 15. Disclaimer of Warranty.
-
- THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
-APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
-HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
-OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
-THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
-PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
-IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
-ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
-
- 16. Limitation of Liability.
-
- IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
-WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
-THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
-GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
-USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
-DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
-PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
-EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
-SUCH DAMAGES.
-
- 17. Interpretation of Sections 15 and 16.
-
- If the disclaimer of warranty and limitation of liability provided
-above cannot be given local legal effect according to their terms,
-reviewing courts shall apply local law that most closely approximates
-an absolute waiver of all civil liability in connection with the
-Program, unless a warranty or assumption of liability accompanies a
-copy of the Program in return for a fee.
-
- END OF TERMS AND CONDITIONS
-
- How to Apply These Terms to Your New Programs
-
- If you develop a new program, and you want it to be of the greatest
-possible use to the public, the best way to achieve this is to make it
-free software which everyone can redistribute and change under these terms.
-
- To do so, attach the following notices to the program. It is safest
-to attach them to the start of each source file to most effectively
-state the exclusion of warranty; and each file should have at least
-the "copyright" line and a pointer to where the full notice is found.
-
- <one line to give the program's name and a brief idea of what it does.>
- Copyright (C) <year> <name of author>
-
- This program is free software: you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with this program. If not, see <http://www.gnu.org/licenses/>.
-
-Also add information on how to contact you by electronic and paper mail.
-
- If the program does terminal interaction, make it output a short
-notice like this when it starts in an interactive mode:
-
- <program> Copyright (C) <year> <name of author>
- This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
- This is free software, and you are welcome to redistribute it
- under certain conditions; type `show c' for details.
-
-The hypothetical commands `show w' and `show c' should show the appropriate
-parts of the General Public License. Of course, your program's commands
-might be different; for a GUI interface, you would use an "about box".
-
- You should also get your employer (if you work as a programmer) or school,
-if any, to sign a "copyright disclaimer" for the program, if necessary.
-For more information on this, and how to apply and follow the GNU GPL, see
-<http://www.gnu.org/licenses/>.
-
- The GNU General Public License does not permit incorporating your program
-into proprietary programs. If your program is a subroutine library, you
-may consider it more useful to permit linking proprietary applications with
-the library. If this is what you want to do, use the GNU Lesser General
-Public License instead of this License. But first, please read
-<http://www.gnu.org/philosophy/why-not-lgpl.html>.
+ GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + <one line to give the program's name and a brief idea of what it does.> + Copyright (C) <year> <name of author> + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + <program> Copyright (C) <year> <name of author> + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +<http://www.gnu.org/licenses/>. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +<http://www.gnu.org/philosophy/why-not-lgpl.html>. diff --git a/protocols/Twitter/README.txt b/protocols/Twitter/docs/README.txt index b229b10796..32b34ea93d 100644 --- a/protocols/Twitter/README.txt +++ b/protocols/Twitter/docs/README.txt @@ -1,10 +1,10 @@ -Miranda-Twitter
----------------
-
-Warning! I'm not maintaining this code anymore! It's still around for people who
-want to work on it, but that's it; I make no promises that it even works
-(indeed, without updates, it almost certainly won't pass Twitter's auth).
-
-To compile this code, you'll want to check out the Miranda IM header files and
-install them into <source>\miranda:
-<https://miranda.svn.sourceforge.net/svnroot/miranda/trunk/miranda/include>
+Miranda-Twitter +--------------- + +Warning! I'm not maintaining this code anymore! It's still around for people who +want to work on it, but that's it; I make no promises that it even works +(indeed, without updates, it almost certainly won't pass Twitter's auth). + +To compile this code, you'll want to check out the Miranda IM header files and +install them into <source>\miranda: +<https://miranda.svn.sourceforge.net/svnroot/miranda/trunk/miranda/include> diff --git a/protocols/Twitter/docs/changelog.html b/protocols/Twitter/docs/changelog.html new file mode 100644 index 0000000000..6da6b1d409 --- /dev/null +++ b/protocols/Twitter/docs/changelog.html @@ -0,0 +1,31 @@ +<html>
+ <head>
+ <title>Miranda Twitter Changelog!</title>
+ </head>
+ <body>
+ <h2>0.0.9.6</h2>
+ - Updater now working
+ - Basic "auto" group support. If you want to have twitter contacts auto added to a group, before you connect to twitter (but after you create the account in miranda) create a "DefaultGroup" string key in the database and make the value the group you want twitter contacts to be automatically added to. This won't copy existing contacts to the group, just newly added ones.
+ - Other minor fixes
+ <h2>0.0.9.5</h2>
+- Retweets will now appear in the timeline!<br>
+- Fixed group chat highlighting when YOU make a tweet<br>
+- Stopped self contact joining the clist<br>
+<h2>0.0.9.4</h2>
+- Fixed duplicate contacts<br>
+<h2>0.0.9.3</h2>
+- Fixed connection problems<br>
+- Hopefully fixed unicode problems, please let me know!<br>
+- Cleaned up some code, got rid of the password input field as this isn't required with OAuth. If you're security conscious feel free to delete the password field from the database. i'll add some code to do this automatically next time.<br>
+<h2>0.0.9.2</h2>
+- DMs now actually work.<br>
+- your username should appear in the chat window now.. thx Thief<br>
+<h2>0.0.9.1</h2>
+- Tweeting (and posting DMs?) now works (thanks Borkra!)<br>
+- Removed dependencies on WinInet, so this now an actual Release build. yay<br>
+- seem to have broken proxy support.. which is weird. working on it.<br>
+<h2>0.0.9.0</h2>
+- OAuth used for authorisation now<br>
+- I have broken many things, and desecrated Dentist's once beautiful code. i think at one point i added a "2" to a variable name because i couldn't think of a better name. So sorry :(<br>
+</body>
+</html>
diff --git a/protocols/Twitter/http.cpp b/protocols/Twitter/http.cpp index 63218ca616..ef295f4ab0 100644 --- a/protocols/Twitter/http.cpp +++ b/protocols/Twitter/http.cpp @@ -15,23 +15,16 @@ You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
-#include "common.h"
#include "http.h"
-std::string http::url_encode(const std::string &s)
-{
- char *encoded = (char*)CallService( MS_NETLIB_URLENCODE, 0, ( LPARAM )s.c_str());
- std::string ret = encoded;
- HeapFree(GetProcessHeap(),0,encoded);
+#include <windows.h>
+#include <newpluginapi.h>
+#include <m_netlib.h>
- return ret;
-}
-
-std::string http::url_encode(const std::wstring &s)
+std::string http::url_encode(const std::string &s)
{
- char* data = mir_u2a( s.c_str());
- char *encoded = (char*)CallService( MS_NETLIB_URLENCODE, 0, ( LPARAM )data);
- mir_free( data );
+ char *encoded = reinterpret_cast<char*>(CallService( MS_NETLIB_URLENCODE,
+ 0,reinterpret_cast<LPARAM>(s.c_str()) ));
std::string ret = encoded;
HeapFree(GetProcessHeap(),0,encoded);
diff --git a/protocols/Twitter/http.h b/protocols/Twitter/http.h index 04f5468b30..65ef5af407 100644 --- a/protocols/Twitter/http.h +++ b/protocols/Twitter/http.h @@ -35,5 +35,4 @@ namespace http };
std::string url_encode(const std::string &);
- std::string url_encode(const std::wstring &);
}
\ No newline at end of file diff --git a/protocols/Twitter/icons/twitter.ico b/protocols/Twitter/icons/twitter.ico Binary files differindex 2b6eaa1eae..e9f61fb6c5 100644 --- a/protocols/Twitter/icons/twitter.ico +++ b/protocols/Twitter/icons/twitter.ico diff --git a/protocols/Twitter/main.cpp b/protocols/Twitter/main.cpp index d28cc30b65..70bf202fc0 100644 --- a/protocols/Twitter/main.cpp +++ b/protocols/Twitter/main.cpp @@ -28,7 +28,6 @@ MD5_INTERFACE md5i; MM_INTERFACE mmi;
UTF8_INTERFACE utfi;
LIST_INTERFACE li;
-int hLangpack = 0;
CLIST_INTERFACE* pcli;
@@ -39,10 +38,10 @@ PLUGININFOEX pluginInfo={ "Twitter Plugin",
__VERSION_DWORD,
"Provides basic support for Twitter protocol. [Built: "__DATE__" "__TIME__"]",
- "dentist",
+ "dentist, omniwolf, Thief",
"",
- "© 2009-2010 dentist",
- "http://github.com/dentist/miranda-twitter",
+ "© 2009-2010 dentist, 2010-2011 omniwolf and Thief",
+ "http://code.google.com/p/miranda-twitter-oauth/",
UNICODE_AWARE, //not transient
0, //doesn't replace anything built-in
//{BC09A71B-B86E-4d33-B18D-82D30451DD3C}
@@ -66,6 +65,17 @@ DWORD WINAPI DllMain(HINSTANCE hInstance,DWORD,LPVOID) extern "C" __declspec(dllexport) PLUGININFOEX* MirandaPluginInfoEx(DWORD mirandaVersion)
{
+ if(mirandaVersion < PLUGIN_MAKE_VERSION(0,8,0,29))
+ {
+ MessageBox(0,_T("The Twitter protocol plugin cannot be loaded. ")
+ _T("It requires Miranda IM 0.9.4 or later."),_T("Miranda"),
+ MB_OK|MB_ICONWARNING|MB_SETFOREGROUND|MB_TOPMOST);
+ return NULL;
+ }
+
+ /*unsigned long mv=_htonl(mirandaVersion);
+ memcpy(&AIM_CAP_MIRANDA[8],&mv,sizeof(DWORD));
+ memcpy(&AIM_CAP_MIRANDA[12],AIM_OSCAR_VERSION,sizeof(DWORD));*/
return &pluginInfo;
}
@@ -73,7 +83,6 @@ extern "C" __declspec(dllexport) PLUGININFOEX* MirandaPluginInfoEx(DWORD miranda // Interface information
static const MUUID interfaces[] = {MIID_PROTOCOL, MIID_LAST};
-
extern "C" __declspec(dllexport) const MUUID* MirandaPluginInterfaces(void)
{
return interfaces;
@@ -97,7 +106,7 @@ static int protoUninit(PROTO_INTERFACE *proto) int OnModulesLoaded(WPARAM,LPARAM)
{
- if (ServiceExists(MS_UPDATE_REGISTER))
+ if(ServiceExists(MS_UPDATE_REGISTER))
{
Update upd = {sizeof(upd)};
char curr_version[30];
@@ -106,18 +115,18 @@ int OnModulesLoaded(WPARAM,LPARAM) upd.szUpdateURL = UPDATER_AUTOREGISTER;
- upd.szBetaVersionURL = "http://www.teamboxel.com/update/twitter/version";
- upd.szBetaChangelogURL = "http://code.google.com/p/miranda-twitter/wiki/Changes";
+ upd.szBetaVersionURL = "http://twosx.net/mim/twitter/updater/version.html";
+ upd.szBetaChangelogURL = "http://twosx.net/mim/twitter/updater/changelog.html";
upd.pbBetaVersionPrefix = reinterpret_cast<BYTE*>("Twitter ");
upd.cpbBetaVersionPrefix = strlen(reinterpret_cast<char*>(upd.pbBetaVersionPrefix));
#ifdef UNICODE
- upd.szBetaUpdateURL = "http://www.teamboxel.com/update/twitter";
+ upd.szBetaUpdateURL = "http://twosx.net/mim/twitter/updater/twitter.zip";
#else
upd.szBetaUpdateURL = "http://www.teamboxel.com/update/twitter/ansi";
#endif
upd.pbVersion = reinterpret_cast<BYTE*>( CreateVersionStringPlugin(
- reinterpret_cast<PLUGININFO*>(&pluginInfo),curr_version));
+ reinterpret_cast<PLUGININFO*>(&pluginInfo),curr_version) );
upd.cpbVersion = strlen(reinterpret_cast<char*>(upd.pbVersion));
CallService(MS_UPDATE_REGISTER,0,(LPARAM)&upd);
@@ -135,10 +144,9 @@ extern "C" int __declspec(dllexport) Load(PLUGINLINK *link) mir_getMD5I(&md5i);
mir_getUTFI(&utfi);
mir_getLI(&li);
- mir_getLP(&pluginInfo);
pcli = reinterpret_cast<CLIST_INTERFACE*>( CallService(
- MS_CLIST_RETRIEVE_INTERFACE,0,reinterpret_cast<LPARAM>(g_hInstance)));
+ MS_CLIST_RETRIEVE_INTERFACE,0,reinterpret_cast<LPARAM>(g_hInstance)) );
PROTOCOLDESCRIPTOR pd = {sizeof(pd)};
pd.szName = "Twitter";
@@ -165,4 +173,4 @@ extern "C" int __declspec(dllexport) Unload(void) UnhookEvent(g_hEvents[i]);
return 0;
-}
+}
\ No newline at end of file diff --git a/protocols/Twitter/oauth.cpp b/protocols/Twitter/oauth.cpp new file mode 100644 index 0000000000..d67ec4ce22 --- /dev/null +++ b/protocols/Twitter/oauth.cpp @@ -0,0 +1,670 @@ +/* aww whatup? this is all the oauth functions, at the moment
+ * they're all part of the twitter class.. i think this is the
+ * best way?
+ */
+
+#include "twitter.h"
+//#include "tc2.h"
+#include "utility.h"
+#include "stdafx.h"
+#include "common.h"
+
+OAuthParameters mir_twitter::BuildSignedOAuthParameters( const OAuthParameters& requestParameters,
+ const std::wstring& url,
+ const std::wstring& httpMethod,
+ const OAuthParameters *postData,
+ const std::wstring& consumerKey,
+ const std::wstring& consumerSecret,
+ const std::wstring& requestToken = L"",
+ const std::wstring& requestTokenSecret = L"",
+ const std::wstring& pin = L"" )
+{
+ wstring timestamp = OAuthCreateTimestamp();
+ wstring nonce = OAuthCreateNonce();
+
+ // create oauth requestParameters
+ OAuthParameters oauthParameters;
+
+ oauthParameters[L"oauth_timestamp"] = timestamp;
+ oauthParameters[L"oauth_nonce"] = nonce;
+ oauthParameters[L"oauth_version"] = L"1.0";
+ oauthParameters[L"oauth_signature_method"] = L"HMAC-SHA1";
+ oauthParameters[L"oauth_consumer_key"] = consumerKey;
+
+ // add the request token if found
+ if (!requestToken.empty())
+ {
+ oauthParameters[L"oauth_token"] = requestToken; /*WLOG("requestToken not empty: %s", requestToken);*/
+ }
+
+ // add the authorization pin if found
+ if (!pin.empty())
+ {
+ oauthParameters[L"oauth_verifier"] = pin;
+ }
+
+ // create a parameter list containing both oauth and original parameters
+ // this will be used to create the parameter signature
+ OAuthParameters allParameters = requestParameters;
+
+ if(Compare(httpMethod, L"POST", false) && postData) {
+ //LOG("in post section of buildOAuthParams");
+ allParameters.insert(postData->begin(), postData->end());
+ }
+
+ allParameters.insert(oauthParameters.begin(), oauthParameters.end());
+
+ // prepare a signature base, a carefully formatted string containing
+ // all of the necessary information needed to generate a valid signature
+ wstring normalUrl = OAuthNormalizeUrl(url);
+ //WLOG("normalURL is %s", normalUrl);
+ wstring normalizedParameters = OAuthNormalizeRequestParameters(allParameters);
+ //WLOG("normalisedparams is %s", normalizedParameters);
+ wstring signatureBase = OAuthConcatenateRequestElements(httpMethod, normalUrl, normalizedParameters);
+ //WLOG("sigBase is %s", signatureBase);
+
+ // obtain a signature and add it to header requestParameters
+ wstring signature = OAuthCreateSignature(signatureBase, consumerSecret, requestTokenSecret);
+ //WLOG("**BuildSignedOAuthParameters - sig is %s", signature);
+ oauthParameters[L"oauth_signature"] = signature;
+
+ return oauthParameters;
+}
+
+wstring mir_twitter::UrlGetQuery( const wstring& url )
+{
+ wstring query;
+ /*
+ URL_COMPONENTS components = {sizeof(URL_COMPONENTS)};
+
+ wchar_t buf[1024*4] = {};
+
+ components.lpszExtraInfo = buf;
+ components.dwExtraInfoLength = SIZEOF(buf);
+
+ BOOL crackUrlOk = InternetCrackUrl(url.c_str(), url.size(), 0, &components);
+ _ASSERTE(crackUrlOk);
+ if(crackUrlOk)
+ {*/
+
+ map<wstring, wstring> brokenURL = CrackURL(url);
+
+ query = brokenURL[L"extraInfo"];
+ //WLOG("inside crack, url is %s", url);
+ wstring::size_type q = query.find_first_of(L'?');
+ if(q != wstring::npos)
+ {
+ query = query.substr(q + 1);
+ }
+
+ wstring::size_type h = query.find_first_of(L'#');
+ if(h != wstring::npos)
+ {
+ query = query.substr(0, h);
+ }
+ //}
+ return query;
+}
+
+// OAuthWebRequest used for all OAuth related queries
+//
+// consumerKey and consumerSecret - must be provided for every call, they identify the application
+// oauthToken and oauthTokenSecret - need to be provided for every call, except for the first token request before authorizing
+// pin - only used during authorization, when the user enters the PIN they received from the twitter website
+wstring mir_twitter::OAuthWebRequestSubmit(
+ const wstring& url,
+ const wstring& httpMethod,
+ const OAuthParameters *postData,
+ const wstring& consumerKey,
+ const wstring& consumerSecret,
+ const wstring& oauthToken,
+ const wstring& oauthTokenSecret,
+ const wstring& pin
+ )
+{
+ //WLOG("URL is %s", url);
+ wstring query = UrlGetQuery(url);
+ //WLOG("query is %s", query);
+ OAuthParameters originalParameters = ParseQueryString(query);
+
+ OAuthParameters oauthSignedParameters = BuildSignedOAuthParameters(
+ originalParameters,
+ url,
+ httpMethod, postData,
+ consumerKey, consumerSecret,
+ oauthToken, oauthTokenSecret,
+ pin );
+ return OAuthWebRequestSubmit(oauthSignedParameters, url);
+}
+
+wstring mir_twitter::OAuthWebRequestSubmit(
+ const OAuthParameters& parameters,
+ const wstring& url
+ )
+{
+ //WLOG("OAuthWebRequestSubmit(%s)", url);
+
+ //wstring oauthHeader = L"Authorization: OAuth ";
+ wstring oauthHeader = L"OAuth ";
+
+ for(OAuthParameters::const_iterator it = parameters.begin();
+ it != parameters.end();
+ ++it)
+ {
+ //WLOG("%s = ", it->first);
+ //WLOG("%s", it->second);
+ //LOG("---------");
+
+ if(it != parameters.begin())
+ {
+ oauthHeader += L",";
+ }
+
+ wstring pair;
+ pair += it->first + L"=\"" + it->second + L"\"";
+ oauthHeader += pair;
+ }
+
+ //WLOG("oauthheader is %s", oauthHeader);
+
+ return oauthHeader;
+}
+
+// parameters must already be URL encoded before calling BuildQueryString
+std::wstring mir_twitter::BuildQueryString( const OAuthParameters ¶meters )
+{
+ wstring query;
+ //LOG("do we ever get here?");
+ for(OAuthParameters::const_iterator it = parameters.begin();
+ it != parameters.end();
+ ++it)
+ {
+ //LOG("aww como ONNNNNN");
+ //LOG("%s = %s", it->first.c_str(), it->second.c_str());
+ //WLOG("in buildqueryString bit, first is %s", it->first);
+
+ if(it != parameters.begin())
+ {
+ query += L"&";
+ }
+
+ wstring pair;
+ pair += it->first + L"=" + it->second + L"";
+ query += pair;
+ }
+ return query;
+}
+
+wstring mir_twitter::OAuthConcatenateRequestElements( const wstring& httpMethod, wstring url, const wstring& parameters )
+{
+ wstring escapedUrl = UrlEncode(url);
+ //WLOG("before OAUTHConcat, params are %s", parameters);
+ wstring escapedParameters = UrlEncode(parameters);
+ //LOG(")))))))))))))))))))))))))))))))))))))))))))))))");
+ //WLOG("after url encode, its %s", escapedParameters);
+ wstring ret = httpMethod + L"&" + escapedUrl + L"&" + escapedParameters;
+ return ret;
+}
+
+/* CrackURL.. just basically pulls apart a url into a map of wstrings:
+ * scheme, domain, port, path, extraInfo, explicitPort
+ * explicitPort will be 0 or 1, 0 if there was no actual port in the url,
+ * and 1 if it was explicitely specified.
+ * eg "http://twitter.com/blah.htm" will give:
+ * http, twitter.com, 80, blah.htm, "", 0
+ * "https://twitter.com:989/blah.htm?boom" will give:
+ * https, twitter.com, 989, blah.htm?boom, ?boom, 1
+ */
+map<wstring, wstring> mir_twitter::CrackURL(wstring url) {
+
+ wstring scheme1, domain1, port1, path1, extraInfo, explicitPort;
+ vector<wstring> urlToks, urlToks2, extraInfoToks;
+
+ Split(url, urlToks, L':', false);
+ //WLOG("**CRACK - URL to split is %s", url);
+
+ scheme1 = urlToks[0];
+ //WLOG("**CRACK - scheme is %s", scheme1);
+
+ if (urlToks.size() == 2) { // if there is only 1 ":" in the url
+ if (Compare(scheme1, L"http", false)) {
+ port1 = L"80";
+ }
+ else {
+ port1 = L"443";
+ }
+
+ //WLOG("**CRACK::2 - port is %s", port1);
+
+ Split(urlToks[1], urlToks2, L'/', false);
+ domain1 = urlToks2[0];
+ //WLOG("**CRACK::2 - domain is %s", domain1);
+ explicitPort = L"0";
+ }
+ else if (urlToks.size() == 3) { // if there are 2 ":"s in the URL, ie a port is explicitly set
+ domain1 = urlToks[1].substr(2, urlToks[1].size());
+ //WLOG("**CRACK::3 - domain is %s", domain1);
+ Split(urlToks[2], urlToks2, L'/', false);
+ port1 = urlToks2[0];
+ //WLOG("**CRACK::3 - port is %s", port1);
+ explicitPort = L"1";
+ }
+ else {
+ WLOG("**CRACK - not a proper URL? doesn't have a colon. URL is %s", url);
+
+ }
+
+ for (size_t i = 1; i < urlToks2.size(); ++i) {
+ if (i > 1) {
+ path1 += L"/";
+ }
+ path1 += urlToks2[i];
+ }
+ //WLOG("**CRACK - path is %s", path1);
+
+ wstring::size_type foundHash = path1.find(L"#");
+ wstring::size_type foundQ = path1.find(L"?");
+
+ if ((foundHash != wstring::npos) || (foundQ != wstring::npos)) { // if we've found a # or a ?...
+ if (foundHash == wstring::npos) { // if we didn't find a #, we must have found a ?
+ extraInfo = path1.substr(foundQ);
+ }
+ else if (foundQ == wstring::npos) { // if we didn't find a ?, we must have found a #
+ extraInfo = path1.substr(foundHash);
+ }
+ else { // we found both a # and a ?, whichever came first we grab the sub string from there
+ if (foundQ < foundHash) {
+ extraInfo = path1.substr(foundQ);
+ }
+ else {
+ extraInfo = path1.substr(foundHash);
+ }
+ }
+ }
+ else { // we have no # or ? in the path...
+ extraInfo = L"";
+ }
+
+ //WLOG("**CRACK - extraInfo is %s", extraInfo);
+
+ map<wstring, wstring> result;
+ result[L"scheme"] = scheme1;
+ result[L"domain"] = domain1;
+ result[L"port"] = port1;
+ result[L"path"] = path1;
+ result[L"extraInfo"] = extraInfo;
+ result[L"explicitPort"] = explicitPort;
+
+ return result;
+}
+
+wstring mir_twitter::OAuthNormalizeUrl( const wstring& url )
+{
+ /*wchar_t scheme[1024*4] = {};
+ wchar_t host[1024*4] = {};
+ wchar_t path[1024*4] = {};
+
+ URL_COMPONENTS components = { sizeof(URL_COMPONENTS) };
+
+ components.lpszScheme = scheme;
+ components.dwSchemeLength = SIZEOF(scheme);
+
+ components.lpszHostName = host;
+ components.dwHostNameLength = SIZEOF(host);
+
+ components.lpszUrlPath = path;
+ components.dwUrlPathLength = SIZEOF(path);
+
+ BOOL crackUrlOk = InternetCrackUrl(url.c_str(), url.size(), 0, &components);*/
+
+ wstring normalUrl = url;
+ map<wstring, wstring> brokenURL = CrackURL(url);
+
+ /*_ASSERTE(crackUrlOk);
+ if(crackUrlOk)
+ {*/
+ wchar_t port[10] = {};
+
+ // The port number must only be included if it is non-standard
+ if(Compare(brokenURL[L"scheme"], L"http", false) && !(Compare(brokenURL[L"port"], L"80", false)) ||
+ (Compare(brokenURL[L"scheme"], L"https", false) && !(Compare(brokenURL[L"port"], L"443", false))))
+ {
+ swprintf_s(port, SIZEOF(port), L":%s", brokenURL[L"port"]);
+ }
+
+ // InternetCrackUrl includes ? and # elements in the path,
+ // which we need to strip off
+ wstring pathOnly = brokenURL[L"path"];
+ wstring::size_type q = pathOnly.find_first_of(L"#?");
+ if(q != wstring::npos)
+ {
+ pathOnly = pathOnly.substr(0, q);
+ }
+
+ normalUrl = brokenURL[L"scheme"] + L"://" + brokenURL[L"domain"] + port + L"/" + pathOnly;
+ //WLOG("**OAuthNOrmailseURL - normalUrl is %s", normalUrl);
+ //}
+ return normalUrl;
+}
+
+wstring mir_twitter::OAuthNormalizeRequestParameters( const OAuthParameters& requestParameters )
+{
+ list<wstring> sorted;
+ for(OAuthParameters::const_iterator it = requestParameters.begin();
+ it != requestParameters.end();
+ ++it)
+ {
+ wstring param = it->first + L"=" + it->second;
+ sorted.push_back(param);
+ }
+ sorted.sort();
+
+ wstring params;
+ for(list<wstring>::iterator it = sorted.begin(); it != sorted.end(); ++it)
+ {
+ if(params.size() > 0)
+ {
+ params += L"&";
+ }
+ params += *it;
+ }
+
+ return params;
+}
+
+OAuthParameters mir_twitter::ParseQueryString( const wstring& url )
+{
+ OAuthParameters ret;
+
+ vector<wstring> queryParams;
+ Split(url, queryParams, L'&', false);
+
+ for(size_t i = 0; i < queryParams.size(); ++i)
+ {
+ vector<wstring> paramElements;
+ Split(queryParams[i], paramElements, L'=', true);
+ _ASSERTE(paramElements.size() == 2);
+ if(paramElements.size() == 2)
+ {
+ ret[paramElements[0]] = paramElements[1];
+ }
+ }
+ return ret;
+}
+
+wstring mir_twitter::OAuthCreateNonce()
+{
+ wchar_t ALPHANUMERIC[] = L"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
+ wstring nonce;
+
+ for(int i = 0; i <= 16; ++i)
+ {
+ nonce += ALPHANUMERIC[rand() % (SIZEOF(ALPHANUMERIC) - 1)]; // don't count null terminator in array
+ }
+ return nonce;
+}
+
+wstring mir_twitter::OAuthCreateTimestamp()
+{
+ __time64_t utcNow;
+ __time64_t ret = _time64(&utcNow);
+ _ASSERTE(ret != -1);
+
+ wchar_t buf[100] = {};
+ swprintf_s(buf, SIZEOF(buf), L"%I64u", utcNow);
+
+ return buf;
+}
+
+string mir_twitter::HMACSHA1( const string& keyBytes, const string& data )
+{
+ // based on http://msdn.microsoft.com/en-us/library/aa382379%28v=VS.85%29.aspx
+
+ string hash;
+
+ //--------------------------------------------------------------------
+ // Declare variables.
+ //
+ // hProv: Handle to a cryptographic service provider (CSP).
+ // This example retrieves the default provider for
+ // the PROV_RSA_FULL provider type.
+ // hHash: Handle to the hash object needed to create a hash.
+ // hKey: Handle to a symmetric key. This example creates a
+ // key for the RC4 algorithm.
+ // hHmacHash: Handle to an HMAC hash.
+ // pbHash: Pointer to the hash.
+ // dwDataLen: Length, in bytes, of the hash.
+ // Data1: Password string used to create a symmetric key.
+ // Data2: Message string to be hashed.
+ // HmacInfo: Instance of an HMAC_INFO structure that contains
+ // information about the HMAC hash.
+ //
+ HCRYPTPROV hProv = NULL;
+ HCRYPTHASH hHash = NULL;
+ HCRYPTKEY hKey = NULL;
+ HCRYPTHASH hHmacHash = NULL;
+ PBYTE pbHash = NULL;
+ DWORD dwDataLen = 0;
+ //BYTE Data1[] = {0x70,0x61,0x73,0x73,0x77,0x6F,0x72,0x64};
+ //BYTE Data2[] = {0x6D,0x65,0x73,0x73,0x61,0x67,0x65};
+ HMAC_INFO HmacInfo;
+
+ //--------------------------------------------------------------------
+ // Zero the HMAC_INFO structure and use the SHA1 algorithm for
+ // hashing.
+
+ ZeroMemory(&HmacInfo, sizeof(HmacInfo));
+ HmacInfo.HashAlgid = CALG_SHA1;
+
+ //--------------------------------------------------------------------
+ // Acquire a handle to the default RSA cryptographic service provider.
+
+ if (!CryptAcquireContext(
+ &hProv, // handle of the CSP
+ NULL, // key container name
+ NULL, // CSP name
+ PROV_RSA_FULL, // provider type
+ CRYPT_VERIFYCONTEXT)) // no key access is requested
+ {
+ _TRACE(" Error in AcquireContext 0x%08x \n",
+ GetLastError());
+ goto ErrorExit;
+ }
+
+ //--------------------------------------------------------------------
+ // Derive a symmetric key from a hash object by performing the
+ // following steps:
+ // 1. Call CryptCreateHash to retrieve a handle to a hash object.
+ // 2. Call CryptHashData to add a text string (password) to the
+ // hash object.
+ // 3. Call CryptDeriveKey to create the symmetric key from the
+ // hashed password derived in step 2.
+ // You will use the key later to create an HMAC hash object.
+
+ if (!CryptCreateHash(
+ hProv, // handle of the CSP
+ CALG_SHA1, // hash algorithm to use
+ 0, // hash key
+ 0, // reserved
+ &hHash)) // address of hash object handle
+ {
+ _TRACE("Error in CryptCreateHash 0x%08x \n",
+ GetLastError());
+ goto ErrorExit;
+ }
+
+ if (!CryptHashData(
+ hHash, // handle of the hash object
+ (BYTE*)keyBytes.c_str(), // password to hash
+ keyBytes.size(), // number of bytes of data to add
+ 0)) // flags
+ {
+ _TRACE("Error in CryptHashData 0x%08x \n",
+ GetLastError());
+ goto ErrorExit;
+ }
+
+ // key creation based on
+ // http://mirror.leaseweb.com/NetBSD/NetBSD-release-5-0/src/dist/wpa/src/crypto/crypto_cryptoapi.c
+ struct {
+ BLOBHEADER hdr;
+ DWORD len;
+ BYTE key[1024]; // TODO might want to dynamically allocate this, Should Be Fine though
+ } key_blob;
+
+ key_blob.hdr.bType = PLAINTEXTKEYBLOB;
+ key_blob.hdr.bVersion = CUR_BLOB_VERSION;
+ key_blob.hdr.reserved = 0;
+ /*
+ * Note: RC2 is not really used, but that can be used to
+ * import HMAC keys of up to 16 byte long.
+ * CRYPT_IPSEC_HMAC_KEY flag for CryptImportKey() is needed to
+ * be able to import longer keys (HMAC-SHA1 uses 20-byte key).
+ */
+ key_blob.hdr.aiKeyAlg = CALG_RC2;
+ key_blob.len = keyBytes.size();
+ ZeroMemory(key_blob.key, sizeof(key_blob.key));
+
+ _ASSERTE(keyBytes.size() <= SIZEOF(key_blob.key));
+ CopyMemory(key_blob.key, keyBytes.c_str(), min(keyBytes.size(), SIZEOF(key_blob.key)));
+
+ if (!CryptImportKey(
+ hProv,
+ (BYTE *)&key_blob,
+ sizeof(key_blob),
+ 0,
+ CRYPT_IPSEC_HMAC_KEY,
+ &hKey))
+ {
+ _TRACE("Error in CryptImportKey 0x%08x \n", GetLastError());
+ goto ErrorExit;
+ }
+
+ //--------------------------------------------------------------------
+ // Create an HMAC by performing the following steps:
+ // 1. Call CryptCreateHash to create a hash object and retrieve
+ // a handle to it.
+ // 2. Call CryptSetHashParam to set the instance of the HMAC_INFO
+ // structure into the hash object.
+ // 3. Call CryptHashData to compute a hash of the message.
+ // 4. Call CryptGetHashParam to retrieve the size, in bytes, of
+ // the hash.
+ // 5. Call malloc to allocate memory for the hash.
+ // 6. Call CryptGetHashParam again to retrieve the HMAC hash.
+
+ if (!CryptCreateHash(
+ hProv, // handle of the CSP.
+ CALG_HMAC, // HMAC hash algorithm ID
+ hKey, // key for the hash (see above)
+ 0, // reserved
+ &hHmacHash)) // address of the hash handle
+ {
+ _TRACE("Error in CryptCreateHash 0x%08x \n",
+ GetLastError());
+ goto ErrorExit;
+ }
+
+ if (!CryptSetHashParam(
+ hHmacHash, // handle of the HMAC hash object
+ HP_HMAC_INFO, // setting an HMAC_INFO object
+ (BYTE*)&HmacInfo, // the HMAC_INFO object
+ 0)) // reserved
+ {
+ _TRACE("Error in CryptSetHashParam 0x%08x \n",
+ GetLastError());
+ goto ErrorExit;
+ }
+
+ if (!CryptHashData(
+ hHmacHash, // handle of the HMAC hash object
+ (BYTE*)data.c_str(), // message to hash
+ data.size(), // number of bytes of data to add
+ 0)) // flags
+ {
+ _TRACE("Error in CryptHashData 0x%08x \n",
+ GetLastError());
+ goto ErrorExit;
+ }
+
+ //--------------------------------------------------------------------
+ // Call CryptGetHashParam twice. Call it the first time to retrieve
+ // the size, in bytes, of the hash. Allocate memory. Then call
+ // CryptGetHashParam again to retrieve the hash value.
+
+ if (!CryptGetHashParam(
+ hHmacHash, // handle of the HMAC hash object
+ HP_HASHVAL, // query on the hash value
+ NULL, // filled on second call
+ &dwDataLen, // length, in bytes, of the hash
+ 0))
+ {
+ _TRACE("Error in CryptGetHashParam 0x%08x \n",
+ GetLastError());
+ goto ErrorExit;
+ }
+
+ pbHash = (BYTE*)malloc(dwDataLen);
+ if(NULL == pbHash)
+ {
+ _TRACE("unable to allocate memory\n");
+ goto ErrorExit;
+ }
+
+ if (!CryptGetHashParam(
+ hHmacHash, // handle of the HMAC hash object
+ HP_HASHVAL, // query on the hash value
+ pbHash, // pointer to the HMAC hash value
+ &dwDataLen, // length, in bytes, of the hash
+ 0))
+ {
+ _TRACE("Error in CryptGetHashParam 0x%08x \n", GetLastError());
+ goto ErrorExit;
+ }
+
+ for(DWORD i = 0 ; i < dwDataLen ; i++)
+ {
+ hash.push_back((char)pbHash[i]);
+ }
+
+ // Free resources.
+ // lol goto
+ErrorExit:
+ if(hHmacHash)
+ CryptDestroyHash(hHmacHash);
+ if(hKey)
+ CryptDestroyKey(hKey);
+ if(hHash)
+ CryptDestroyHash(hHash);
+ if(hProv)
+ CryptReleaseContext(hProv, 0);
+ if(pbHash)
+ free(pbHash);
+
+ return hash;
+}
+
+wstring mir_twitter::Base64String( const string& hash )
+{
+ Base64Coder coder;
+ coder.Encode((BYTE*)hash.c_str(), hash.size());
+ wstring encoded = UTF8ToWide(coder.EncodedMessage());
+ return encoded;
+}
+
+wstring mir_twitter::OAuthCreateSignature( const wstring& signatureBase, const wstring& consumerSecret, const wstring& requestTokenSecret )
+{
+ // URL encode key elements
+ wstring escapedConsumerSecret = UrlEncode(consumerSecret);
+ wstring escapedTokenSecret = UrlEncode(requestTokenSecret);
+
+ wstring key = escapedConsumerSecret + L"&" + escapedTokenSecret;
+ string keyBytes = WideToUTF8(key);
+
+ string data = WideToUTF8(signatureBase);
+ string hash = HMACSHA1(keyBytes, data);
+ wstring signature = Base64String(hash);
+
+ // URL encode the returned signature
+ signature = UrlEncode(signature);
+ return signature;
+}
diff --git a/protocols/Twitter/oauth.dev.h b/protocols/Twitter/oauth.dev.h new file mode 100644 index 0000000000..13c383b3ab --- /dev/null +++ b/protocols/Twitter/oauth.dev.h @@ -0,0 +1,2 @@ +#define OAUTH_CONSUMER_KEY L"AwSuQV9A7uXpat81MQB48g"
+#define OAUTH_CONSUMER_SECRET L"x8pPGCCV5wFs26euODb9gv4VQ4kiuxTp3ed2P8Of4"
\ No newline at end of file diff --git a/protocols/Twitter/oauth/AUTHORS b/protocols/Twitter/oauth/AUTHORS new file mode 100644 index 0000000000..43ba1244f2 --- /dev/null +++ b/protocols/Twitter/oauth/AUTHORS @@ -0,0 +1,36 @@ +Robin Gareus <robin@gareus.org> has written and is maintaining liboauth. + +The base64 code is used with permission from Jan-Henrik +Haukeland <hauk@tildeslash.com>. + +escape_url() contains code from curl by Daniel Stenberg <daniel@haxx.se> + +cheers to Arjan <arjan@scherpenisse.net> for using and testing this code; and +Ralph Meijer <ralphm@ik.nu> for fixing the debian package and quality control. + +Kudos to Marc Worrel - http://www.marcworrell.com/ - for an introduction +to the OAuth API and helping to get this project alive. And last but not +standing ovations to the http://oauth.net team who made it possible in i +the first place. + +Marc Powell suggested minor changes and contributed patches to make this +library more usable. + +Stephen Paul Weber <singpolyma@singpolyma.net> sent patches for the +initial Debian package. + +Dave Gamble <davegamble@gmail.com> has jumped on board. Writing a lightweight +c-api for soundcloud, he sent fixes for windows MSVC support and added the +oauth_curl_post_data_with_callback() function. + +Emil A Eklund provided a patch for CURLOPT_TIMEOUT to avoid problems with +HTTP timeouts. + +Many thanks to Diego Elio Pettenò who sent patches for the build-system and +packages liboauth for Gentoo. Likewise Tom Parker for Debian, as well as +Paul Wise who metorered Bilal Akhtar on debian-mentors. All of which provided +valuable feedback. + +Last but not least, Jeff Squyres inspired the '-Wl,--as-needed' linker flags +check. + diff --git a/protocols/Twitter/oauth/COPYING b/protocols/Twitter/oauth/COPYING new file mode 100644 index 0000000000..8bc1249e7f --- /dev/null +++ b/protocols/Twitter/oauth/COPYING @@ -0,0 +1,2 @@ +if configured with '--enable-gpl' see COPYING.GPL and LICENSE.OpenSSL +otherwise read COPYING.MIT and the README diff --git a/protocols/Twitter/oauth/COPYING.GPL b/protocols/Twitter/oauth/COPYING.GPL new file mode 100644 index 0000000000..60549be514 --- /dev/null +++ b/protocols/Twitter/oauth/COPYING.GPL @@ -0,0 +1,340 @@ + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc. + 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Library General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + <one line to give the program's name and a brief idea of what it does.> + Copyright (C) 19yy <name of author> + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) 19yy name of author + Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + <signature of Ty Coon>, 1 April 1989 + Ty Coon, President of Vice + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Library General +Public License instead of this License. diff --git a/protocols/Twitter/oauth/COPYING.MIT b/protocols/Twitter/oauth/COPYING.MIT new file mode 100644 index 0000000000..fc366e9708 --- /dev/null +++ b/protocols/Twitter/oauth/COPYING.MIT @@ -0,0 +1,21 @@ +Copyright 2007, 2008 Robin Gareus <robin@gareus.org> + +Unless otherwise indicated, Source Code is licensed under MIT license. + +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. diff --git a/protocols/Twitter/oauth/ChangeLog b/protocols/Twitter/oauth/ChangeLog new file mode 100644 index 0000000000..3150adb91e --- /dev/null +++ b/protocols/Twitter/oauth/ChangeLog @@ -0,0 +1,226 @@ +version 0.9.7 (unreleased) + - fixed tiny memory leak when oauth_curl_get() fails + +version 0.9.6 + - fixed typo, do not print a separator before first parameter + when serializing url for auth-header. + +version 0.9.5 + - added "built-in" hmac-sha1 hashing (no RSA). + - added some CURL options available via enviroment variables + - fixed issue with decoding already encoded characters + in the base-URL (not parameters). + reported by L. Alberto Giménez + +version 0.9.4 + - fixed possible memory corrution in oauth_curl_get + thanks to Bruce Rosen for reporting this issue + +version 0.9.3 + - yet more build-system fixes: + - allow to override HASH_LIBS and CURL_LIBS using envoronment variables + - include them in .pc and tests/Makefile.am + +version 0.9.2 + - fixed typo in build-system (LDFLAGS, -Wl,--as-needed detection) + +version 0.9.1 + - fixed typo in API: + oauth_time_indepenent_equals[_n] is now deprecated in favor of + oauth_time_independent_equals[_n] + - added check for 'Wl,--as-needed' linker flag. + +version 0.9.0 + - fixed typo in pkg-config file. + +version 0.8.9 + - added constant-time string compare function motivated by + http://rdist.root.org/2010/01/07/timing-independent-array-comparison/ + - updated the build-system + - avoid indirect linking (curl, ssl) + - AS_IF expansion for PKG_PROG_PKG_CONFIG + - only build tests when running `make check` + +version 0.8.8 + minor changes to the build-system + - allow to overrice HASH_LIBS/CFLAGS (NSS, SpenSSL) + - fixes for static linking in src/Makefile.am + +version 0.8.7 + fixed whitespace in interface revision number + fixed test-build system: + - unhardcode -lssl + - add CFLAGS_CURL + +version 0.8.6 + removed non-posix prototypes + +version 0.8.5 + cleaned up man-page & added logo to html doc. + +version 0.8.4 + fixed pkgconfig dependencies (OpenSSL vs NSS) + +version 0.8.3 + added an interface to generate an OAuth HTTP Authorization header + and oauth_http_[get|post]2 to preform such requests, + as well as example code 'oauthtest2' to do so. + +version 0.8.2 + fixed potential NULL pointer exception when sorting + duplicate URL parameters without value. + It's a extremly rare edge-case - there's no practial + use for duplicate empty URL parameters - but it could + be used as a DOS attack-vector. + +version 0.8.1 + replaced a few forgotten mallocs with xmalloc. + +version 0.8.0 + replaced xmalloc with custom MIT-licensed version. + removed --enable-gpl configure option. + minor updates to README, documentation, etc. + +version 0.7.2 + added NSS as alternative to OpenSSL. + use OpenSSL or NSS random number generator for nonce. + +version 0.7.1 + proper naming: replaced oAuth -> OAuth. + fixed a few typos in the documentation. + +version 0.7.0 + resolved licensing issues: + * xmalloc = GPL + * openSSL & GPL exemption + +version 0.6.3 + also use curl timeout for commandline curl + renamed --with-libcurl-timeout to --with-curl-timeout + +version 0.6.2 + added CURLOPT_TIMEOUT option. + available at compile time with configure --with-libcurl-timeout=<int> + +version 0.6.1 + added oauth_curl_send_data_with_callback + to use HTTP-methods other than GET&POST with libcurl. + +version 0.6.0 + configure options to disable curl & libcurl + replaced tabs with spaces in source + +version 0.5.4 + added oauth_post_data_with_callback() and + fixes for MSVC/WIN32 platform + by Dave Gamble + +version 0.5.3 + added oauth_body_hash calulation + support for HTTP Posting data from memory. + +version 0.5.2 + added support for HTTP request methods other than GET & POST. + +version 0.5.1 + added oauth_sign_array() function - which allows to modify the parameters + before siging them. + fixed url-splitting to url-decode parameters when generating the parameter + array. + +version 0.5.0 + fixed debian package liboauth -> liboauth0 + minor fixes in the manual + else unchanged it's 0.4.5 after six month of stress tests in production + +version 0.4.5 + fixed dependencies in pkgconfig pc.in + +version 0.4.4 + libtool interface version number + +version 0.4.3 + added oauth_url_unescape() + +version 0.4.2 + fixed escaping of PLAINTEXT signature. + +version 0.4.1 + added oauth_serialize_url_sep() + and OAUTH_VERSION defines in header file. + +version 0.4.0 + release on googlecode under MIT license + and on sourceforge/debian under LGPL + +version 0.3.4 + allow to configure MIT only or LGPL licensed code (xmalloc) + reorganized tests + removed mixed declarations and code + +version 0.3.3 + added Eran's test-cases. + removing ':80' portnumber from URL before signing + when splitting URL parameters: use '\001' as request param value as alias for ampersand ('&') + +version 0.3.2 + added NULL uri check to oauth_split_post_paramters() + testcode comment updates. + +version 0.3.1 + added #ifndef _OAUTH_H to header - avoid double include errors + fixed some typos in the doc. + +version 0.3.0 + prefixed all public oauth.h functions with "oauth_" + added RSA-SHA1 signature support + +version 0.2.4 + detect absoluteURI by ":/" (it was /^http/) - used to detect empty abs_path + added shell escape for (bash like) `sh` to invoke curl/wget + cleaned up example code and doc a bit. + +version 0.2.3 + fixed '?' in GET URL¶meter concatenation + added cURL HTTP-GET function and test/example code + test/example code using http://term.ie/oauth/example/ + +version 0.2.2 + fixed "empty HTTP Paths" see http://wiki.oauth.net/TestCases and + http://groups.google.com/group/oauth/browse_thread/thread/c44b6f061bfd98c?hl=en + fixed some compiler warnings + made signature function args 'const char *' + and mem-zero some possibly sensitive strings before free()ing them. + +version 0.2.1 + prepared for MIT license + all c sources and headers by Robin Gareus are now MIT licensed. + +version 0.2.0 + updated documentation + fixed configure.ac + +version 0.1.3 + removed getpid() on random-number initialization for win. + moving to sourceforge. + +version 0.1.2 + different handlers for POST and GET query string. Get escapes '+' to ' '. + oauth_sign_url() returns escaped query string. + added oauth_curl_post_file - preparing for xoauth_body_signature. + updated test code. + +version 0.1.1 + fixed parameter normalization and sorting for some edge cases. + added Test Cases from http://wiki.oauth.net/TestCases + added simple HTTP POST using libcurl or a command-line HTTP client. + +version 0.1.0 + added xmalloc - removed NULL checks after [re|m|c]alloc. + libtoolized and prepared packaging. + fixed a couple of typos + added a some more documentation. + +version 0.0.1 + first public release + oAuth parameter escape and URL request signing functions. diff --git a/protocols/Twitter/oauth/Doxyfile.in b/protocols/Twitter/oauth/Doxyfile.in new file mode 100644 index 0000000000..eb4c284c5f --- /dev/null +++ b/protocols/Twitter/oauth/Doxyfile.in @@ -0,0 +1,1631 @@ +# Doxyfile 1.7.1 + +# This file describes the settings to be used by the documentation system +# doxygen (www.doxygen.org) for a project +# +# All text after a hash (#) is considered a comment and will be ignored +# The format is: +# TAG = value [value, ...] +# For lists items can also be appended using: +# TAG += value [value, ...] +# Values that contain spaces should be placed between quotes (" ") + +#--------------------------------------------------------------------------- +# Project related configuration options +#--------------------------------------------------------------------------- + +# This tag specifies the encoding used for all characters in the config file +# that follow. The default is UTF-8 which is also the encoding used for all +# text before the first occurrence of this tag. Doxygen uses libiconv (or the +# iconv built into libc) for the transcoding. See +# http://www.gnu.org/software/libiconv for the list of possible encodings. + +DOXYFILE_ENCODING = UTF-8 + +# The PROJECT_NAME tag is a single word (or a sequence of words surrounded +# by quotes) that should identify the project. + +PROJECT_NAME = "OAuth library functions" + +# The PROJECT_NUMBER tag can be used to enter a project or revision number. +# This could be handy for archiving the generated documentation or +# if some version control system is used. + +PROJECT_NUMBER = @VERSION@ + +# The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute) +# base path where the generated documentation will be put. +# If a relative path is entered, it will be relative to the location +# where doxygen was started. If left blank the current directory will be used. + +OUTPUT_DIRECTORY = doc + +# If the CREATE_SUBDIRS tag is set to YES, then doxygen will create +# 4096 sub-directories (in 2 levels) under the output directory of each output +# format and will distribute the generated files over these directories. +# Enabling this option can be useful when feeding doxygen a huge amount of +# source files, where putting all generated files in the same directory would +# otherwise cause performance problems for the file system. + +CREATE_SUBDIRS = NO + +# The OUTPUT_LANGUAGE tag is used to specify the language in which all +# documentation generated by doxygen is written. Doxygen will use this +# information to generate all constant output in the proper language. +# The default language is English, other supported languages are: +# Afrikaans, Arabic, Brazilian, Catalan, Chinese, Chinese-Traditional, +# Croatian, Czech, Danish, Dutch, Esperanto, Farsi, Finnish, French, German, +# Greek, Hungarian, Italian, Japanese, Japanese-en (Japanese with English +# messages), Korean, Korean-en, Lithuanian, Norwegian, Macedonian, Persian, +# Polish, Portuguese, Romanian, Russian, Serbian, Serbian-Cyrilic, Slovak, +# Slovene, Spanish, Swedish, Ukrainian, and Vietnamese. + +OUTPUT_LANGUAGE = English + +# If the BRIEF_MEMBER_DESC tag is set to YES (the default) Doxygen will +# include brief member descriptions after the members that are listed in +# the file and class documentation (similar to JavaDoc). +# Set to NO to disable this. + +BRIEF_MEMBER_DESC = YES + +# If the REPEAT_BRIEF tag is set to YES (the default) Doxygen will prepend +# the brief description of a member or function before the detailed description. +# Note: if both HIDE_UNDOC_MEMBERS and BRIEF_MEMBER_DESC are set to NO, the +# brief descriptions will be completely suppressed. + +REPEAT_BRIEF = YES + +# This tag implements a quasi-intelligent brief description abbreviator +# that is used to form the text in various listings. Each string +# in this list, if found as the leading text of the brief description, will be +# stripped from the text and the result after processing the whole list, is +# used as the annotated text. Otherwise, the brief description is used as-is. +# If left blank, the following values are used ("$name" is automatically +# replaced with the name of the entity): "The $name class" "The $name widget" +# "The $name file" "is" "provides" "specifies" "contains" +# "represents" "a" "an" "the" + +ABBREVIATE_BRIEF = + +# If the ALWAYS_DETAILED_SEC and REPEAT_BRIEF tags are both set to YES then +# Doxygen will generate a detailed section even if there is only a brief +# description. + +ALWAYS_DETAILED_SEC = NO + +# If the INLINE_INHERITED_MEMB tag is set to YES, doxygen will show all +# inherited members of a class in the documentation of that class as if those +# members were ordinary class members. Constructors, destructors and assignment +# operators of the base classes will not be shown. + +INLINE_INHERITED_MEMB = NO + +# If the FULL_PATH_NAMES tag is set to YES then Doxygen will prepend the full +# path before files name in the file list and in the header files. If set +# to NO the shortest path that makes the file name unique will be used. + +FULL_PATH_NAMES = YES + +# If the FULL_PATH_NAMES tag is set to YES then the STRIP_FROM_PATH tag +# can be used to strip a user-defined part of the path. Stripping is +# only done if one of the specified strings matches the left-hand part of +# the path. The tag can be used to show relative paths in the file list. +# If left blank the directory from which doxygen is run is used as the +# path to strip. + +STRIP_FROM_PATH = + +# The STRIP_FROM_INC_PATH tag can be used to strip a user-defined part of +# the path mentioned in the documentation of a class, which tells +# the reader which header file to include in order to use a class. +# If left blank only the name of the header file containing the class +# definition is used. Otherwise one should specify the include paths that +# are normally passed to the compiler using the -I flag. + +STRIP_FROM_INC_PATH = + +# If the SHORT_NAMES tag is set to YES, doxygen will generate much shorter +# (but less readable) file names. This can be useful is your file systems +# doesn't support long names like on DOS, Mac, or CD-ROM. + +SHORT_NAMES = NO + +# If the JAVADOC_AUTOBRIEF tag is set to YES then Doxygen +# will interpret the first line (until the first dot) of a JavaDoc-style +# comment as the brief description. If set to NO, the JavaDoc +# comments will behave just like regular Qt-style comments +# (thus requiring an explicit @brief command for a brief description.) + +JAVADOC_AUTOBRIEF = YES + +# If the QT_AUTOBRIEF tag is set to YES then Doxygen will +# interpret the first line (until the first dot) of a Qt-style +# comment as the brief description. If set to NO, the comments +# will behave just like regular Qt-style comments (thus requiring +# an explicit \brief command for a brief description.) + +QT_AUTOBRIEF = YES + +# The MULTILINE_CPP_IS_BRIEF tag can be set to YES to make Doxygen +# treat a multi-line C++ special comment block (i.e. a block of //! or /// +# comments) as a brief description. This used to be the default behaviour. +# The new default is to treat a multi-line C++ comment block as a detailed +# description. Set this tag to YES if you prefer the old behaviour instead. + +MULTILINE_CPP_IS_BRIEF = NO + +# If the INHERIT_DOCS tag is set to YES (the default) then an undocumented +# member inherits the documentation from any documented member that it +# re-implements. + +INHERIT_DOCS = YES + +# If the SEPARATE_MEMBER_PAGES tag is set to YES, then doxygen will produce +# a new page for each member. If set to NO, the documentation of a member will +# be part of the file/class/namespace that contains it. + +SEPARATE_MEMBER_PAGES = NO + +# The TAB_SIZE tag can be used to set the number of spaces in a tab. +# Doxygen uses this value to replace tabs by spaces in code fragments. + +TAB_SIZE = 2 + +# This tag can be used to specify a number of aliases that acts +# as commands in the documentation. An alias has the form "name=value". +# For example adding "sideeffect=\par Side Effects:\n" will allow you to +# put the command \sideeffect (or @sideeffect) in the documentation, which +# will result in a user-defined paragraph with heading "Side Effects:". +# You can put \n's in the value part of an alias to insert newlines. + +ALIASES = + +# Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C +# sources only. Doxygen will then generate output that is more tailored for C. +# For instance, some of the names that are used will be different. The list +# of all members will be omitted, etc. + +OPTIMIZE_OUTPUT_FOR_C = YES + +# Set the OPTIMIZE_OUTPUT_JAVA tag to YES if your project consists of Java +# sources only. Doxygen will then generate output that is more tailored for +# Java. For instance, namespaces will be presented as packages, qualified +# scopes will look different, etc. + +OPTIMIZE_OUTPUT_JAVA = NO + +# Set the OPTIMIZE_FOR_FORTRAN tag to YES if your project consists of Fortran +# sources only. Doxygen will then generate output that is more tailored for +# Fortran. + +OPTIMIZE_FOR_FORTRAN = NO + +# Set the OPTIMIZE_OUTPUT_VHDL tag to YES if your project consists of VHDL +# sources. Doxygen will then generate output that is tailored for +# VHDL. + +OPTIMIZE_OUTPUT_VHDL = NO + +# Doxygen selects the parser to use depending on the extension of the files it +# parses. With this tag you can assign which parser to use for a given extension. +# Doxygen has a built-in mapping, but you can override or extend it using this +# tag. The format is ext=language, where ext is a file extension, and language +# is one of the parsers supported by doxygen: IDL, Java, Javascript, CSharp, C, +# C++, D, PHP, Objective-C, Python, Fortran, VHDL, C, C++. For instance to make +# doxygen treat .inc files as Fortran files (default is PHP), and .f files as C +# (default is Fortran), use: inc=Fortran f=C. Note that for custom extensions +# you also need to set FILE_PATTERNS otherwise the files are not read by doxygen. + +EXTENSION_MAPPING = + +# If you use STL classes (i.e. std::string, std::vector, etc.) but do not want +# to include (a tag file for) the STL sources as input, then you should +# set this tag to YES in order to let doxygen match functions declarations and +# definitions whose arguments contain STL classes (e.g. func(std::string); v.s. +# func(std::string) {}). This also make the inheritance and collaboration +# diagrams that involve STL classes more complete and accurate. + +BUILTIN_STL_SUPPORT = NO + +# If you use Microsoft's C++/CLI language, you should set this option to YES to +# enable parsing support. + +CPP_CLI_SUPPORT = NO + +# Set the SIP_SUPPORT tag to YES if your project consists of sip sources only. +# Doxygen will parse them like normal C++ but will assume all classes use public +# instead of private inheritance when no explicit protection keyword is present. + +SIP_SUPPORT = NO + +# For Microsoft's IDL there are propget and propput attributes to indicate getter +# and setter methods for a property. Setting this option to YES (the default) +# will make doxygen to replace the get and set methods by a property in the +# documentation. This will only work if the methods are indeed getting or +# setting a simple type. If this is not the case, or you want to show the +# methods anyway, you should set this option to NO. + +IDL_PROPERTY_SUPPORT = YES + +# If member grouping is used in the documentation and the DISTRIBUTE_GROUP_DOC +# tag is set to YES, then doxygen will reuse the documentation of the first +# member in the group (if any) for the other members of the group. By default +# all members of a group must be documented explicitly. + +DISTRIBUTE_GROUP_DOC = NO + +# Set the SUBGROUPING tag to YES (the default) to allow class member groups of +# the same type (for instance a group of public functions) to be put as a +# subgroup of that type (e.g. under the Public Functions section). Set it to +# NO to prevent subgrouping. Alternatively, this can be done per class using +# the \nosubgrouping command. + +SUBGROUPING = YES + +# When TYPEDEF_HIDES_STRUCT is enabled, a typedef of a struct, union, or enum +# is documented as struct, union, or enum with the name of the typedef. So +# typedef struct TypeS {} TypeT, will appear in the documentation as a struct +# with name TypeT. When disabled the typedef will appear as a member of a file, +# namespace, or class. And the struct will be named TypeS. This can typically +# be useful for C code in case the coding convention dictates that all compound +# types are typedef'ed and only the typedef is referenced, never the tag name. + +TYPEDEF_HIDES_STRUCT = NO + +# The SYMBOL_CACHE_SIZE determines the size of the internal cache use to +# determine which symbols to keep in memory and which to flush to disk. +# When the cache is full, less often used symbols will be written to disk. +# For small to medium size projects (<1000 input files) the default value is +# probably good enough. For larger projects a too small cache size can cause +# doxygen to be busy swapping symbols to and from disk most of the time +# causing a significant performance penality. +# If the system has enough physical memory increasing the cache will improve the +# performance by keeping more symbols in memory. Note that the value works on +# a logarithmic scale so increasing the size by one will rougly double the +# memory usage. The cache size is given by this formula: +# 2^(16+SYMBOL_CACHE_SIZE). The valid range is 0..9, the default is 0, +# corresponding to a cache size of 2^16 = 65536 symbols + +SYMBOL_CACHE_SIZE = 0 + +#--------------------------------------------------------------------------- +# Build related configuration options +#--------------------------------------------------------------------------- + +# If the EXTRACT_ALL tag is set to YES doxygen will assume all entities in +# documentation are documented, even if no documentation was available. +# Private class members and static file members will be hidden unless +# the EXTRACT_PRIVATE and EXTRACT_STATIC tags are set to YES + +EXTRACT_ALL = YES + +# If the EXTRACT_PRIVATE tag is set to YES all private members of a class +# will be included in the documentation. + +EXTRACT_PRIVATE = NO + +# If the EXTRACT_STATIC tag is set to YES all static members of a file +# will be included in the documentation. + +EXTRACT_STATIC = NO + +# If the EXTRACT_LOCAL_CLASSES tag is set to YES classes (and structs) +# defined locally in source files will be included in the documentation. +# If set to NO only classes defined in header files are included. + +EXTRACT_LOCAL_CLASSES = YES + +# This flag is only useful for Objective-C code. When set to YES local +# methods, which are defined in the implementation section but not in +# the interface are included in the documentation. +# If set to NO (the default) only methods in the interface are included. + +EXTRACT_LOCAL_METHODS = NO + +# If this flag is set to YES, the members of anonymous namespaces will be +# extracted and appear in the documentation as a namespace called +# 'anonymous_namespace{file}', where file will be replaced with the base +# name of the file that contains the anonymous namespace. By default +# anonymous namespace are hidden. + +EXTRACT_ANON_NSPACES = NO + +# If the HIDE_UNDOC_MEMBERS tag is set to YES, Doxygen will hide all +# undocumented members of documented classes, files or namespaces. +# If set to NO (the default) these members will be included in the +# various overviews, but no documentation section is generated. +# This option has no effect if EXTRACT_ALL is enabled. + +HIDE_UNDOC_MEMBERS = NO + +# If the HIDE_UNDOC_CLASSES tag is set to YES, Doxygen will hide all +# undocumented classes that are normally visible in the class hierarchy. +# If set to NO (the default) these classes will be included in the various +# overviews. This option has no effect if EXTRACT_ALL is enabled. + +HIDE_UNDOC_CLASSES = NO + +# If the HIDE_FRIEND_COMPOUNDS tag is set to YES, Doxygen will hide all +# friend (class|struct|union) declarations. +# If set to NO (the default) these declarations will be included in the +# documentation. + +HIDE_FRIEND_COMPOUNDS = NO + +# If the HIDE_IN_BODY_DOCS tag is set to YES, Doxygen will hide any +# documentation blocks found inside the body of a function. +# If set to NO (the default) these blocks will be appended to the +# function's detailed documentation block. + +HIDE_IN_BODY_DOCS = NO + +# The INTERNAL_DOCS tag determines if documentation +# that is typed after a \internal command is included. If the tag is set +# to NO (the default) then the documentation will be excluded. +# Set it to YES to include the internal documentation. + +INTERNAL_DOCS = NO + +# If the CASE_SENSE_NAMES tag is set to NO then Doxygen will only generate +# file names in lower-case letters. If set to YES upper-case letters are also +# allowed. This is useful if you have classes or files whose names only differ +# in case and if your file system supports case sensitive file names. Windows +# and Mac users are advised to set this option to NO. + +CASE_SENSE_NAMES = YES + +# If the HIDE_SCOPE_NAMES tag is set to NO (the default) then Doxygen +# will show members with their full class and namespace scopes in the +# documentation. If set to YES the scope will be hidden. + +HIDE_SCOPE_NAMES = NO + +# If the SHOW_INCLUDE_FILES tag is set to YES (the default) then Doxygen +# will put a list of the files that are included by a file in the documentation +# of that file. + +SHOW_INCLUDE_FILES = YES + +# If the FORCE_LOCAL_INCLUDES tag is set to YES then Doxygen +# will list include files with double quotes in the documentation +# rather than with sharp brackets. + +FORCE_LOCAL_INCLUDES = NO + +# If the INLINE_INFO tag is set to YES (the default) then a tag [inline] +# is inserted in the documentation for inline members. + +INLINE_INFO = YES + +# If the SORT_MEMBER_DOCS tag is set to YES (the default) then doxygen +# will sort the (detailed) documentation of file and class members +# alphabetically by member name. If set to NO the members will appear in +# declaration order. + +SORT_MEMBER_DOCS = YES + +# If the SORT_BRIEF_DOCS tag is set to YES then doxygen will sort the +# brief documentation of file, namespace and class members alphabetically +# by member name. If set to NO (the default) the members will appear in +# declaration order. + +SORT_BRIEF_DOCS = NO + +# If the SORT_MEMBERS_CTORS_1ST tag is set to YES then doxygen +# will sort the (brief and detailed) documentation of class members so that +# constructors and destructors are listed first. If set to NO (the default) +# the constructors will appear in the respective orders defined by +# SORT_MEMBER_DOCS and SORT_BRIEF_DOCS. +# This tag will be ignored for brief docs if SORT_BRIEF_DOCS is set to NO +# and ignored for detailed docs if SORT_MEMBER_DOCS is set to NO. + +SORT_MEMBERS_CTORS_1ST = NO + +# If the SORT_GROUP_NAMES tag is set to YES then doxygen will sort the +# hierarchy of group names into alphabetical order. If set to NO (the default) +# the group names will appear in their defined order. + +SORT_GROUP_NAMES = NO + +# If the SORT_BY_SCOPE_NAME tag is set to YES, the class list will be +# sorted by fully-qualified names, including namespaces. If set to +# NO (the default), the class list will be sorted only by class name, +# not including the namespace part. +# Note: This option is not very useful if HIDE_SCOPE_NAMES is set to YES. +# Note: This option applies only to the class list, not to the +# alphabetical list. + +SORT_BY_SCOPE_NAME = NO + +# The GENERATE_TODOLIST tag can be used to enable (YES) or +# disable (NO) the todo list. This list is created by putting \todo +# commands in the documentation. + +GENERATE_TODOLIST = YES + +# The GENERATE_TESTLIST tag can be used to enable (YES) or +# disable (NO) the test list. This list is created by putting \test +# commands in the documentation. + +GENERATE_TESTLIST = YES + +# The GENERATE_BUGLIST tag can be used to enable (YES) or +# disable (NO) the bug list. This list is created by putting \bug +# commands in the documentation. + +GENERATE_BUGLIST = YES + +# The GENERATE_DEPRECATEDLIST tag can be used to enable (YES) or +# disable (NO) the deprecated list. This list is created by putting +# \deprecated commands in the documentation. + +GENERATE_DEPRECATEDLIST= YES + +# The ENABLED_SECTIONS tag can be used to enable conditional +# documentation sections, marked by \if sectionname ... \endif. + +ENABLED_SECTIONS = + +# The MAX_INITIALIZER_LINES tag determines the maximum number of lines +# the initial value of a variable or define consists of for it to appear in +# the documentation. If the initializer consists of more lines than specified +# here it will be hidden. Use a value of 0 to hide initializers completely. +# The appearance of the initializer of individual variables and defines in the +# documentation can be controlled using \showinitializer or \hideinitializer +# command in the documentation regardless of this setting. + +MAX_INITIALIZER_LINES = 30 + +# Set the SHOW_USED_FILES tag to NO to disable the list of files generated +# at the bottom of the documentation of classes and structs. If set to YES the +# list will mention the files that were used to generate the documentation. + +SHOW_USED_FILES = YES + +# If the sources in your project are distributed over multiple directories +# then setting the SHOW_DIRECTORIES tag to YES will show the directory hierarchy +# in the documentation. The default is NO. + +SHOW_DIRECTORIES = NO + +# Set the SHOW_FILES tag to NO to disable the generation of the Files page. +# This will remove the Files entry from the Quick Index and from the +# Folder Tree View (if specified). The default is YES. + +SHOW_FILES = YES + +# Set the SHOW_NAMESPACES tag to NO to disable the generation of the +# Namespaces page. +# This will remove the Namespaces entry from the Quick Index +# and from the Folder Tree View (if specified). The default is YES. + +SHOW_NAMESPACES = YES + +# The FILE_VERSION_FILTER tag can be used to specify a program or script that +# doxygen should invoke to get the current version for each file (typically from +# the version control system). Doxygen will invoke the program by executing (via +# popen()) the command <command> <input-file>, where <command> is the value of +# the FILE_VERSION_FILTER tag, and <input-file> is the name of an input file +# provided by doxygen. Whatever the program writes to standard output +# is used as the file version. See the manual for examples. + +FILE_VERSION_FILTER = + +# The LAYOUT_FILE tag can be used to specify a layout file which will be parsed +# by doxygen. The layout file controls the global structure of the generated +# output files in an output format independent way. The create the layout file +# that represents doxygen's defaults, run doxygen with the -l option. +# You can optionally specify a file name after the option, if omitted +# DoxygenLayout.xml will be used as the name of the layout file. + +LAYOUT_FILE = + +#--------------------------------------------------------------------------- +# configuration options related to warning and progress messages +#--------------------------------------------------------------------------- + +# The QUIET tag can be used to turn on/off the messages that are generated +# by doxygen. Possible values are YES and NO. If left blank NO is used. + +QUIET = YES + +# The WARNINGS tag can be used to turn on/off the warning messages that are +# generated by doxygen. Possible values are YES and NO. If left blank +# NO is used. + +WARNINGS = YES + +# If WARN_IF_UNDOCUMENTED is set to YES, then doxygen will generate warnings +# for undocumented members. If EXTRACT_ALL is set to YES then this flag will +# automatically be disabled. + +WARN_IF_UNDOCUMENTED = YES + +# If WARN_IF_DOC_ERROR is set to YES, doxygen will generate warnings for +# potential errors in the documentation, such as not documenting some +# parameters in a documented function, or documenting parameters that +# don't exist or using markup commands wrongly. + +WARN_IF_DOC_ERROR = YES + +# This WARN_NO_PARAMDOC option can be abled to get warnings for +# functions that are documented, but have no documentation for their parameters +# or return value. If set to NO (the default) doxygen will only warn about +# wrong or incomplete parameter documentation, but not about the absence of +# documentation. + +WARN_NO_PARAMDOC = NO + +# The WARN_FORMAT tag determines the format of the warning messages that +# doxygen can produce. The string should contain the $file, $line, and $text +# tags, which will be replaced by the file and line number from which the +# warning originated and the warning text. Optionally the format may contain +# $version, which will be replaced by the version of the file (if it could +# be obtained via FILE_VERSION_FILTER) + +WARN_FORMAT = "$file:$line: $text" + +# The WARN_LOGFILE tag can be used to specify a file to which warning +# and error messages should be written. If left blank the output is written +# to stderr. + +WARN_LOGFILE = + +#--------------------------------------------------------------------------- +# configuration options related to the input files +#--------------------------------------------------------------------------- + +# The INPUT tag can be used to specify the files and/or directories that contain +# documented source files. You may enter file names like "myfile.cpp" or +# directories like "/usr/src/myproject". Separate the files or directories +# with spaces. + +INPUT = src/oauth.h \ + doc/mainpage.dox + +# This tag can be used to specify the character encoding of the source files +# that doxygen parses. Internally doxygen uses the UTF-8 encoding, which is +# also the default input encoding. Doxygen uses libiconv (or the iconv built +# into libc) for the transcoding. See http://www.gnu.org/software/libiconv for +# the list of possible encodings. + +INPUT_ENCODING = UTF-8 + +# If the value of the INPUT tag contains directories, you can use the +# FILE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp +# and *.h) to filter out the source-files in the directories. If left +# blank the following patterns are tested: +# *.c *.cc *.cxx *.cpp *.c++ *.java *.ii *.ixx *.ipp *.i++ *.inl *.h *.hh *.hxx +# *.hpp *.h++ *.idl *.odl *.cs *.php *.php3 *.inc *.m *.mm *.py *.f90 + +FILE_PATTERNS = + +# The RECURSIVE tag can be used to turn specify whether or not subdirectories +# should be searched for input files as well. Possible values are YES and NO. +# If left blank NO is used. + +RECURSIVE = NO + +# The EXCLUDE tag can be used to specify files and/or directories that should +# excluded from the INPUT source files. This way you can easily exclude a +# subdirectory from a directory tree whose root is specified with the INPUT tag. + +EXCLUDE = + +# The EXCLUDE_SYMLINKS tag can be used select whether or not files or +# directories that are symbolic links (a Unix filesystem feature) are excluded +# from the input. + +EXCLUDE_SYMLINKS = NO + +# If the value of the INPUT tag contains directories, you can use the +# EXCLUDE_PATTERNS tag to specify one or more wildcard patterns to exclude +# certain files from those directories. Note that the wildcards are matched +# against the file with absolute path, so to exclude all test directories +# for example use the pattern */test/* + +EXCLUDE_PATTERNS = + +# The EXCLUDE_SYMBOLS tag can be used to specify one or more symbol names +# (namespaces, classes, functions, etc.) that should be excluded from the +# output. The symbol name can be a fully qualified name, a word, or if the +# wildcard * is used, a substring. Examples: ANamespace, AClass, +# AClass::ANamespace, ANamespace::*Test + +EXCLUDE_SYMBOLS = + +# The EXAMPLE_PATH tag can be used to specify one or more files or +# directories that contain example code fragments that are included (see +# the \include command). + +EXAMPLE_PATH = tests/ + +# If the value of the EXAMPLE_PATH tag contains directories, you can use the +# EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp +# and *.h) to filter out the source-files in the directories. If left +# blank all files are included. + +EXAMPLE_PATTERNS = *.c + +# If the EXAMPLE_RECURSIVE tag is set to YES then subdirectories will be +# searched for input files to be used with the \include or \dontinclude +# commands irrespective of the value of the RECURSIVE tag. +# Possible values are YES and NO. If left blank NO is used. + +EXAMPLE_RECURSIVE = NO + +# The IMAGE_PATH tag can be used to specify one or more files or +# directories that contain image that are included in the documentation (see +# the \image command). + +IMAGE_PATH = doc/ + +# The INPUT_FILTER tag can be used to specify a program that doxygen should +# invoke to filter for each input file. Doxygen will invoke the filter program +# by executing (via popen()) the command <filter> <input-file>, where <filter> +# is the value of the INPUT_FILTER tag, and <input-file> is the name of an +# input file. Doxygen will then use the output that the filter program writes +# to standard output. +# If FILTER_PATTERNS is specified, this tag will be +# ignored. + +INPUT_FILTER = + +# The FILTER_PATTERNS tag can be used to specify filters on a per file pattern +# basis. +# Doxygen will compare the file name with each pattern and apply the +# filter if there is a match. +# The filters are a list of the form: +# pattern=filter (like *.cpp=my_cpp_filter). See INPUT_FILTER for further +# info on how filters are used. If FILTER_PATTERNS is empty, INPUT_FILTER +# is applied to all files. + +FILTER_PATTERNS = + +# If the FILTER_SOURCE_FILES tag is set to YES, the input filter (if set using +# INPUT_FILTER) will be used to filter the input files when producing source +# files to browse (i.e. when SOURCE_BROWSER is set to YES). + +FILTER_SOURCE_FILES = NO + +#--------------------------------------------------------------------------- +# configuration options related to source browsing +#--------------------------------------------------------------------------- + +# If the SOURCE_BROWSER tag is set to YES then a list of source files will +# be generated. Documented entities will be cross-referenced with these sources. +# Note: To get rid of all source code in the generated output, make sure also +# VERBATIM_HEADERS is set to NO. + +SOURCE_BROWSER = YES + +# Setting the INLINE_SOURCES tag to YES will include the body +# of functions and classes directly in the documentation. + +INLINE_SOURCES = NO + +# Setting the STRIP_CODE_COMMENTS tag to YES (the default) will instruct +# doxygen to hide any special comment blocks from generated source code +# fragments. Normal C and C++ comments will always remain visible. + +STRIP_CODE_COMMENTS = YES + +# If the REFERENCED_BY_RELATION tag is set to YES +# then for each documented function all documented +# functions referencing it will be listed. + +REFERENCED_BY_RELATION = YES + +# If the REFERENCES_RELATION tag is set to YES +# then for each documented function all documented entities +# called/used by that function will be listed. + +REFERENCES_RELATION = YES + +# If the REFERENCES_LINK_SOURCE tag is set to YES (the default) +# and SOURCE_BROWSER tag is set to YES, then the hyperlinks from +# functions in REFERENCES_RELATION and REFERENCED_BY_RELATION lists will +# link to the source code. +# Otherwise they will link to the documentation. + +REFERENCES_LINK_SOURCE = YES + +# If the USE_HTAGS tag is set to YES then the references to source code +# will point to the HTML generated by the htags(1) tool instead of doxygen +# built-in source browser. The htags tool is part of GNU's global source +# tagging system (see http://www.gnu.org/software/global/global.html). You +# will need version 4.8.6 or higher. + +USE_HTAGS = NO + +# If the VERBATIM_HEADERS tag is set to YES (the default) then Doxygen +# will generate a verbatim copy of the header file for each class for +# which an include is specified. Set to NO to disable this. + +VERBATIM_HEADERS = YES + +#--------------------------------------------------------------------------- +# configuration options related to the alphabetical class index +#--------------------------------------------------------------------------- + +# If the ALPHABETICAL_INDEX tag is set to YES, an alphabetical index +# of all compounds will be generated. Enable this if the project +# contains a lot of classes, structs, unions or interfaces. + +ALPHABETICAL_INDEX = NO + +# If the alphabetical index is enabled (see ALPHABETICAL_INDEX) then +# the COLS_IN_ALPHA_INDEX tag can be used to specify the number of columns +# in which this list will be split (can be a number in the range [1..20]) + +COLS_IN_ALPHA_INDEX = 5 + +# In case all classes in a project start with a common prefix, all +# classes will be put under the same header in the alphabetical index. +# The IGNORE_PREFIX tag can be used to specify one or more prefixes that +# should be ignored while generating the index headers. + +IGNORE_PREFIX = + +#--------------------------------------------------------------------------- +# configuration options related to the HTML output +#--------------------------------------------------------------------------- + +# If the GENERATE_HTML tag is set to YES (the default) Doxygen will +# generate HTML output. + +GENERATE_HTML = YES + +# The HTML_OUTPUT tag is used to specify where the HTML docs will be put. +# If a relative path is entered the value of OUTPUT_DIRECTORY will be +# put in front of it. If left blank `html' will be used as the default path. + +HTML_OUTPUT = html + +# The HTML_FILE_EXTENSION tag can be used to specify the file extension for +# each generated HTML page (for example: .htm,.php,.asp). If it is left blank +# doxygen will generate files with .html extension. + +HTML_FILE_EXTENSION = .html + +# The HTML_HEADER tag can be used to specify a personal HTML header for +# each generated HTML page. If it is left blank doxygen will generate a +# standard header. + +HTML_HEADER = + +# The HTML_FOOTER tag can be used to specify a personal HTML footer for +# each generated HTML page. If it is left blank doxygen will generate a +# standard footer. + +HTML_FOOTER = + +# The HTML_STYLESHEET tag can be used to specify a user-defined cascading +# style sheet that is used by each HTML page. It can be used to +# fine-tune the look of the HTML output. If the tag is left blank doxygen +# will generate a default style sheet. Note that doxygen will try to copy +# the style sheet file to the HTML output directory, so don't put your own +# stylesheet in the HTML output directory as well, or it will be erased! + +HTML_STYLESHEET = + +# The HTML_COLORSTYLE_HUE tag controls the color of the HTML output. +# Doxygen will adjust the colors in the stylesheet and background images +# according to this color. Hue is specified as an angle on a colorwheel, +# see http://en.wikipedia.org/wiki/Hue for more information. +# For instance the value 0 represents red, 60 is yellow, 120 is green, +# 180 is cyan, 240 is blue, 300 purple, and 360 is red again. +# The allowed range is 0 to 359. + +HTML_COLORSTYLE_HUE = 220 + +# The HTML_COLORSTYLE_SAT tag controls the purity (or saturation) of +# the colors in the HTML output. For a value of 0 the output will use +# grayscales only. A value of 255 will produce the most vivid colors. + +HTML_COLORSTYLE_SAT = 100 + +# The HTML_COLORSTYLE_GAMMA tag controls the gamma correction applied to +# the luminance component of the colors in the HTML output. Values below +# 100 gradually make the output lighter, whereas values above 100 make +# the output darker. The value divided by 100 is the actual gamma applied, +# so 80 represents a gamma of 0.8, The value 220 represents a gamma of 2.2, +# and 100 does not change the gamma. + +HTML_COLORSTYLE_GAMMA = 80 + +# If the HTML_TIMESTAMP tag is set to YES then the footer of each generated HTML +# page will contain the date and time when the page was generated. Setting +# this to NO can help when comparing the output of multiple runs. + +HTML_TIMESTAMP = YES + +# If the HTML_ALIGN_MEMBERS tag is set to YES, the members of classes, +# files or namespaces will be aligned in HTML using tables. If set to +# NO a bullet list will be used. + +HTML_ALIGN_MEMBERS = YES + +# If the HTML_DYNAMIC_SECTIONS tag is set to YES then the generated HTML +# documentation will contain sections that can be hidden and shown after the +# page has loaded. For this to work a browser that supports +# JavaScript and DHTML is required (for instance Mozilla 1.0+, Firefox +# Netscape 6.0+, Internet explorer 5.0+, Konqueror, or Safari). + +HTML_DYNAMIC_SECTIONS = NO + +# If the GENERATE_DOCSET tag is set to YES, additional index files +# will be generated that can be used as input for Apple's Xcode 3 +# integrated development environment, introduced with OSX 10.5 (Leopard). +# To create a documentation set, doxygen will generate a Makefile in the +# HTML output directory. Running make will produce the docset in that +# directory and running "make install" will install the docset in +# ~/Library/Developer/Shared/Documentation/DocSets so that Xcode will find +# it at startup. +# See http://developer.apple.com/tools/creatingdocsetswithdoxygen.html +# for more information. + +GENERATE_DOCSET = NO + +# When GENERATE_DOCSET tag is set to YES, this tag determines the name of the +# feed. A documentation feed provides an umbrella under which multiple +# documentation sets from a single provider (such as a company or product suite) +# can be grouped. + +DOCSET_FEEDNAME = "Doxygen generated docs" + +# When GENERATE_DOCSET tag is set to YES, this tag specifies a string that +# should uniquely identify the documentation set bundle. This should be a +# reverse domain-name style string, e.g. com.mycompany.MyDocSet. Doxygen +# will append .docset to the name. + +DOCSET_BUNDLE_ID = org.doxygen.Project + +# When GENERATE_PUBLISHER_ID tag specifies a string that should uniquely identify +# the documentation publisher. This should be a reverse domain-name style +# string, e.g. com.mycompany.MyDocSet.documentation. + +DOCSET_PUBLISHER_ID = org.doxygen.Publisher + +# The GENERATE_PUBLISHER_NAME tag identifies the documentation publisher. + +DOCSET_PUBLISHER_NAME = Publisher + +# If the GENERATE_HTMLHELP tag is set to YES, additional index files +# will be generated that can be used as input for tools like the +# Microsoft HTML help workshop to generate a compiled HTML help file (.chm) +# of the generated HTML documentation. + +GENERATE_HTMLHELP = NO + +# If the GENERATE_HTMLHELP tag is set to YES, the CHM_FILE tag can +# be used to specify the file name of the resulting .chm file. You +# can add a path in front of the file if the result should not be +# written to the html output directory. + +CHM_FILE = + +# If the GENERATE_HTMLHELP tag is set to YES, the HHC_LOCATION tag can +# be used to specify the location (absolute path including file name) of +# the HTML help compiler (hhc.exe). If non-empty doxygen will try to run +# the HTML help compiler on the generated index.hhp. + +HHC_LOCATION = + +# If the GENERATE_HTMLHELP tag is set to YES, the GENERATE_CHI flag +# controls if a separate .chi index file is generated (YES) or that +# it should be included in the master .chm file (NO). + +GENERATE_CHI = NO + +# If the GENERATE_HTMLHELP tag is set to YES, the CHM_INDEX_ENCODING +# is used to encode HtmlHelp index (hhk), content (hhc) and project file +# content. + +CHM_INDEX_ENCODING = + +# If the GENERATE_HTMLHELP tag is set to YES, the BINARY_TOC flag +# controls whether a binary table of contents is generated (YES) or a +# normal table of contents (NO) in the .chm file. + +BINARY_TOC = NO + +# The TOC_EXPAND flag can be set to YES to add extra items for group members +# to the contents of the HTML help documentation and to the tree view. + +TOC_EXPAND = NO + +# If the GENERATE_QHP tag is set to YES and both QHP_NAMESPACE and +# QHP_VIRTUAL_FOLDER are set, an additional index file will be generated +# that can be used as input for Qt's qhelpgenerator to generate a +# Qt Compressed Help (.qch) of the generated HTML documentation. + +GENERATE_QHP = NO + +# If the QHG_LOCATION tag is specified, the QCH_FILE tag can +# be used to specify the file name of the resulting .qch file. +# The path specified is relative to the HTML output folder. + +QCH_FILE = + +# The QHP_NAMESPACE tag specifies the namespace to use when generating +# Qt Help Project output. For more information please see +# http://doc.trolltech.com/qthelpproject.html#namespace + +QHP_NAMESPACE = org.doxygen.Project + +# The QHP_VIRTUAL_FOLDER tag specifies the namespace to use when generating +# Qt Help Project output. For more information please see +# http://doc.trolltech.com/qthelpproject.html#virtual-folders + +QHP_VIRTUAL_FOLDER = doc + +# If QHP_CUST_FILTER_NAME is set, it specifies the name of a custom filter to +# add. For more information please see +# http://doc.trolltech.com/qthelpproject.html#custom-filters + +QHP_CUST_FILTER_NAME = + +# The QHP_CUST_FILT_ATTRS tag specifies the list of the attributes of the +# custom filter to add. For more information please see +# <a href="http://doc.trolltech.com/qthelpproject.html#custom-filters"> +# Qt Help Project / Custom Filters</a>. + +QHP_CUST_FILTER_ATTRS = + +# The QHP_SECT_FILTER_ATTRS tag specifies the list of the attributes this +# project's +# filter section matches. +# <a href="http://doc.trolltech.com/qthelpproject.html#filter-attributes"> +# Qt Help Project / Filter Attributes</a>. + +QHP_SECT_FILTER_ATTRS = + +# If the GENERATE_QHP tag is set to YES, the QHG_LOCATION tag can +# be used to specify the location of Qt's qhelpgenerator. +# If non-empty doxygen will try to run qhelpgenerator on the generated +# .qhp file. + +QHG_LOCATION = + +# If the GENERATE_ECLIPSEHELP tag is set to YES, additional index files +# will be generated, which together with the HTML files, form an Eclipse help +# plugin. To install this plugin and make it available under the help contents +# menu in Eclipse, the contents of the directory containing the HTML and XML +# files needs to be copied into the plugins directory of eclipse. The name of +# the directory within the plugins directory should be the same as +# the ECLIPSE_DOC_ID value. After copying Eclipse needs to be restarted before +# the help appears. + +GENERATE_ECLIPSEHELP = NO + +# A unique identifier for the eclipse help plugin. When installing the plugin +# the directory name containing the HTML and XML files should also have +# this name. + +ECLIPSE_DOC_ID = org.doxygen.Project + +# The DISABLE_INDEX tag can be used to turn on/off the condensed index at +# top of each HTML page. The value NO (the default) enables the index and +# the value YES disables it. + +DISABLE_INDEX = NO + +# This tag can be used to set the number of enum values (range [1..20]) +# that doxygen will group on one line in the generated HTML documentation. + +ENUM_VALUES_PER_LINE = 4 + +# The GENERATE_TREEVIEW tag is used to specify whether a tree-like index +# structure should be generated to display hierarchical information. +# If the tag value is set to YES, a side panel will be generated +# containing a tree-like index structure (just like the one that +# is generated for HTML Help). For this to work a browser that supports +# JavaScript, DHTML, CSS and frames is required (i.e. any modern browser). +# Windows users are probably better off using the HTML help feature. + +GENERATE_TREEVIEW = NO + +# By enabling USE_INLINE_TREES, doxygen will generate the Groups, Directories, +# and Class Hierarchy pages using a tree view instead of an ordered list. + +USE_INLINE_TREES = NO + +# If the treeview is enabled (see GENERATE_TREEVIEW) then this tag can be +# used to set the initial width (in pixels) of the frame in which the tree +# is shown. + +TREEVIEW_WIDTH = 250 + +# When the EXT_LINKS_IN_WINDOW option is set to YES doxygen will open +# links to external symbols imported via tag files in a separate window. + +EXT_LINKS_IN_WINDOW = NO + +# Use this tag to change the font size of Latex formulas included +# as images in the HTML documentation. The default is 10. Note that +# when you change the font size after a successful doxygen run you need +# to manually remove any form_*.png images from the HTML output directory +# to force them to be regenerated. + +FORMULA_FONTSIZE = 10 + +# Use the FORMULA_TRANPARENT tag to determine whether or not the images +# generated for formulas are transparent PNGs. Transparent PNGs are +# not supported properly for IE 6.0, but are supported on all modern browsers. +# Note that when changing this option you need to delete any form_*.png files +# in the HTML output before the changes have effect. + +FORMULA_TRANSPARENT = YES + +# When the SEARCHENGINE tag is enabled doxygen will generate a search box +# for the HTML output. The underlying search engine uses javascript +# and DHTML and should work on any modern browser. Note that when using +# HTML help (GENERATE_HTMLHELP), Qt help (GENERATE_QHP), or docsets +# (GENERATE_DOCSET) there is already a search function so this one should +# typically be disabled. For large projects the javascript based search engine +# can be slow, then enabling SERVER_BASED_SEARCH may provide a better solution. + +SEARCHENGINE = NO + +# When the SERVER_BASED_SEARCH tag is enabled the search engine will be +# implemented using a PHP enabled web server instead of at the web client +# using Javascript. Doxygen will generate the search PHP script and index +# file to put on the web server. The advantage of the server +# based approach is that it scales better to large projects and allows +# full text search. The disadvances is that it is more difficult to setup +# and does not have live searching capabilities. + +SERVER_BASED_SEARCH = NO + +#--------------------------------------------------------------------------- +# configuration options related to the LaTeX output +#--------------------------------------------------------------------------- + +# If the GENERATE_LATEX tag is set to YES (the default) Doxygen will +# generate Latex output. + +GENERATE_LATEX = NO + +# The LATEX_OUTPUT tag is used to specify where the LaTeX docs will be put. +# If a relative path is entered the value of OUTPUT_DIRECTORY will be +# put in front of it. If left blank `latex' will be used as the default path. + +LATEX_OUTPUT = latex + +# The LATEX_CMD_NAME tag can be used to specify the LaTeX command name to be +# invoked. If left blank `latex' will be used as the default command name. +# Note that when enabling USE_PDFLATEX this option is only used for +# generating bitmaps for formulas in the HTML output, but not in the +# Makefile that is written to the output directory. + +LATEX_CMD_NAME = latex + +# The MAKEINDEX_CMD_NAME tag can be used to specify the command name to +# generate index for LaTeX. If left blank `makeindex' will be used as the +# default command name. + +MAKEINDEX_CMD_NAME = makeindex + +# If the COMPACT_LATEX tag is set to YES Doxygen generates more compact +# LaTeX documents. This may be useful for small projects and may help to +# save some trees in general. + +COMPACT_LATEX = NO + +# The PAPER_TYPE tag can be used to set the paper type that is used +# by the printer. Possible values are: a4, a4wide, letter, legal and +# executive. If left blank a4wide will be used. + +PAPER_TYPE = a4wide + +# The EXTRA_PACKAGES tag can be to specify one or more names of LaTeX +# packages that should be included in the LaTeX output. + +EXTRA_PACKAGES = + +# The LATEX_HEADER tag can be used to specify a personal LaTeX header for +# the generated latex document. The header should contain everything until +# the first chapter. If it is left blank doxygen will generate a +# standard header. Notice: only use this tag if you know what you are doing! + +LATEX_HEADER = + +# If the PDF_HYPERLINKS tag is set to YES, the LaTeX that is generated +# is prepared for conversion to pdf (using ps2pdf). The pdf file will +# contain links (just like the HTML output) instead of page references +# This makes the output suitable for online browsing using a pdf viewer. + +PDF_HYPERLINKS = NO + +# If the USE_PDFLATEX tag is set to YES, pdflatex will be used instead of +# plain latex in the generated Makefile. Set this option to YES to get a +# higher quality PDF documentation. + +USE_PDFLATEX = NO + +# If the LATEX_BATCHMODE tag is set to YES, doxygen will add the \\batchmode. +# command to the generated LaTeX files. This will instruct LaTeX to keep +# running if errors occur, instead of asking the user for help. +# This option is also used when generating formulas in HTML. + +LATEX_BATCHMODE = NO + +# If LATEX_HIDE_INDICES is set to YES then doxygen will not +# include the index chapters (such as File Index, Compound Index, etc.) +# in the output. + +LATEX_HIDE_INDICES = NO + +# If LATEX_SOURCE_CODE is set to YES then doxygen will include +# source code with syntax highlighting in the LaTeX output. +# Note that which sources are shown also depends on other settings +# such as SOURCE_BROWSER. + +LATEX_SOURCE_CODE = NO + +#--------------------------------------------------------------------------- +# configuration options related to the RTF output +#--------------------------------------------------------------------------- + +# If the GENERATE_RTF tag is set to YES Doxygen will generate RTF output +# The RTF output is optimized for Word 97 and may not look very pretty with +# other RTF readers or editors. + +GENERATE_RTF = NO + +# The RTF_OUTPUT tag is used to specify where the RTF docs will be put. +# If a relative path is entered the value of OUTPUT_DIRECTORY will be +# put in front of it. If left blank `rtf' will be used as the default path. + +RTF_OUTPUT = rtf + +# If the COMPACT_RTF tag is set to YES Doxygen generates more compact +# RTF documents. This may be useful for small projects and may help to +# save some trees in general. + +COMPACT_RTF = NO + +# If the RTF_HYPERLINKS tag is set to YES, the RTF that is generated +# will contain hyperlink fields. The RTF file will +# contain links (just like the HTML output) instead of page references. +# This makes the output suitable for online browsing using WORD or other +# programs which support those fields. +# Note: wordpad (write) and others do not support links. + +RTF_HYPERLINKS = NO + +# Load stylesheet definitions from file. Syntax is similar to doxygen's +# config file, i.e. a series of assignments. You only have to provide +# replacements, missing definitions are set to their default value. + +RTF_STYLESHEET_FILE = + +# Set optional variables used in the generation of an rtf document. +# Syntax is similar to doxygen's config file. + +RTF_EXTENSIONS_FILE = + +#--------------------------------------------------------------------------- +# configuration options related to the man page output +#--------------------------------------------------------------------------- + +# If the GENERATE_MAN tag is set to YES (the default) Doxygen will +# generate man pages + +GENERATE_MAN = YES + +# The MAN_OUTPUT tag is used to specify where the man pages will be put. +# If a relative path is entered the value of OUTPUT_DIRECTORY will be +# put in front of it. If left blank `man' will be used as the default path. + +MAN_OUTPUT = man + +# The MAN_EXTENSION tag determines the extension that is added to +# the generated man pages (default is the subroutine's section .3) + +MAN_EXTENSION = .3 + +# If the MAN_LINKS tag is set to YES and Doxygen generates man output, +# then it will generate one additional man file for each entity +# documented in the real man page(s). These additional files +# only source the real man page, but without them the man command +# would be unable to find the correct page. The default is NO. + +MAN_LINKS = NO + +#--------------------------------------------------------------------------- +# configuration options related to the XML output +#--------------------------------------------------------------------------- + +# If the GENERATE_XML tag is set to YES Doxygen will +# generate an XML file that captures the structure of +# the code including all documentation. + +GENERATE_XML = NO + +# The XML_OUTPUT tag is used to specify where the XML pages will be put. +# If a relative path is entered the value of OUTPUT_DIRECTORY will be +# put in front of it. If left blank `xml' will be used as the default path. + +XML_OUTPUT = xml + +# The XML_SCHEMA tag can be used to specify an XML schema, +# which can be used by a validating XML parser to check the +# syntax of the XML files. + +XML_SCHEMA = + +# The XML_DTD tag can be used to specify an XML DTD, +# which can be used by a validating XML parser to check the +# syntax of the XML files. + +XML_DTD = + +# If the XML_PROGRAMLISTING tag is set to YES Doxygen will +# dump the program listings (including syntax highlighting +# and cross-referencing information) to the XML output. Note that +# enabling this will significantly increase the size of the XML output. + +XML_PROGRAMLISTING = YES + +#--------------------------------------------------------------------------- +# configuration options for the AutoGen Definitions output +#--------------------------------------------------------------------------- + +# If the GENERATE_AUTOGEN_DEF tag is set to YES Doxygen will +# generate an AutoGen Definitions (see autogen.sf.net) file +# that captures the structure of the code including all +# documentation. Note that this feature is still experimental +# and incomplete at the moment. + +GENERATE_AUTOGEN_DEF = NO + +#--------------------------------------------------------------------------- +# configuration options related to the Perl module output +#--------------------------------------------------------------------------- + +# If the GENERATE_PERLMOD tag is set to YES Doxygen will +# generate a Perl module file that captures the structure of +# the code including all documentation. Note that this +# feature is still experimental and incomplete at the +# moment. + +GENERATE_PERLMOD = NO + +# If the PERLMOD_LATEX tag is set to YES Doxygen will generate +# the necessary Makefile rules, Perl scripts and LaTeX code to be able +# to generate PDF and DVI output from the Perl module output. + +PERLMOD_LATEX = NO + +# If the PERLMOD_PRETTY tag is set to YES the Perl module output will be +# nicely formatted so it can be parsed by a human reader. +# This is useful +# if you want to understand what is going on. +# On the other hand, if this +# tag is set to NO the size of the Perl module output will be much smaller +# and Perl will parse it just the same. + +PERLMOD_PRETTY = YES + +# The names of the make variables in the generated doxyrules.make file +# are prefixed with the string contained in PERLMOD_MAKEVAR_PREFIX. +# This is useful so different doxyrules.make files included by the same +# Makefile don't overwrite each other's variables. + +PERLMOD_MAKEVAR_PREFIX = + +#--------------------------------------------------------------------------- +# Configuration options related to the preprocessor +#--------------------------------------------------------------------------- + +# If the ENABLE_PREPROCESSING tag is set to YES (the default) Doxygen will +# evaluate all C-preprocessor directives found in the sources and include +# files. + +ENABLE_PREPROCESSING = YES + +# If the MACRO_EXPANSION tag is set to YES Doxygen will expand all macro +# names in the source code. If set to NO (the default) only conditional +# compilation will be performed. Macro expansion can be done in a controlled +# way by setting EXPAND_ONLY_PREDEF to YES. + +MACRO_EXPANSION = NO + +# If the EXPAND_ONLY_PREDEF and MACRO_EXPANSION tags are both set to YES +# then the macro expansion is limited to the macros specified with the +# PREDEFINED and EXPAND_AS_DEFINED tags. + +EXPAND_ONLY_PREDEF = NO + +# If the SEARCH_INCLUDES tag is set to YES (the default) the includes files +# in the INCLUDE_PATH (see below) will be search if a #include is found. + +SEARCH_INCLUDES = YES + +# The INCLUDE_PATH tag can be used to specify one or more directories that +# contain include files that are not input files but should be processed by +# the preprocessor. + +INCLUDE_PATH = + +# You can use the INCLUDE_FILE_PATTERNS tag to specify one or more wildcard +# patterns (like *.h and *.hpp) to filter out the header-files in the +# directories. If left blank, the patterns specified with FILE_PATTERNS will +# be used. + +INCLUDE_FILE_PATTERNS = + +# The PREDEFINED tag can be used to specify one or more macro names that +# are defined before the preprocessor is started (similar to the -D option of +# gcc). The argument of the tag is a list of macros of the form: name +# or name=definition (no spaces). If the definition and the = are +# omitted =1 is assumed. To prevent a macro definition from being +# undefined via #undef or recursively expanded use the := operator +# instead of the = operator. + +PREDEFINED = DOXYGEN_IGNORE + +# If the MACRO_EXPANSION and EXPAND_ONLY_PREDEF tags are set to YES then +# this tag can be used to specify a list of macro names that should be expanded. +# The macro definition that is found in the sources will be used. +# Use the PREDEFINED tag if you want to use a different macro definition. + +EXPAND_AS_DEFINED = + +# If the SKIP_FUNCTION_MACROS tag is set to YES (the default) then +# doxygen's preprocessor will remove all function-like macros that are alone +# on a line, have an all uppercase name, and do not end with a semicolon. Such +# function macros are typically used for boiler-plate code, and will confuse +# the parser if not removed. + +SKIP_FUNCTION_MACROS = YES + +#--------------------------------------------------------------------------- +# Configuration::additions related to external references +#--------------------------------------------------------------------------- + +# The TAGFILES option can be used to specify one or more tagfiles. +# Optionally an initial location of the external documentation +# can be added for each tagfile. The format of a tag file without +# this location is as follows: +# +# TAGFILES = file1 file2 ... +# Adding location for the tag files is done as follows: +# +# TAGFILES = file1=loc1 "file2 = loc2" ... +# where "loc1" and "loc2" can be relative or absolute paths or +# URLs. If a location is present for each tag, the installdox tool +# does not have to be run to correct the links. +# Note that each tag file must have a unique name +# (where the name does NOT include the path) +# If a tag file is not located in the directory in which doxygen +# is run, you must also specify the path to the tagfile here. + +TAGFILES = + +# When a file name is specified after GENERATE_TAGFILE, doxygen will create +# a tag file that is based on the input files it reads. + +GENERATE_TAGFILE = + +# If the ALLEXTERNALS tag is set to YES all external classes will be listed +# in the class index. If set to NO only the inherited external classes +# will be listed. + +ALLEXTERNALS = NO + +# If the EXTERNAL_GROUPS tag is set to YES all external groups will be listed +# in the modules index. If set to NO, only the current project's groups will +# be listed. + +EXTERNAL_GROUPS = YES + +# The PERL_PATH should be the absolute path and name of the perl script +# interpreter (i.e. the result of `which perl'). + +PERL_PATH = @PERL@ + +#--------------------------------------------------------------------------- +# Configuration options related to the dot tool +#--------------------------------------------------------------------------- + +# If the CLASS_DIAGRAMS tag is set to YES (the default) Doxygen will +# generate a inheritance diagram (in HTML, RTF and LaTeX) for classes with base +# or super classes. Setting the tag to NO turns the diagrams off. Note that +# this option is superseded by the HAVE_DOT option below. This is only a +# fallback. It is recommended to install and use dot, since it yields more +# powerful graphs. + +CLASS_DIAGRAMS = YES + +# You can define message sequence charts within doxygen comments using the \msc +# command. Doxygen will then run the mscgen tool (see +# http://www.mcternan.me.uk/mscgen/) to produce the chart and insert it in the +# documentation. The MSCGEN_PATH tag allows you to specify the directory where +# the mscgen tool resides. If left empty the tool is assumed to be found in the +# default search path. + +MSCGEN_PATH = + +# If set to YES, the inheritance and collaboration graphs will hide +# inheritance and usage relations if the target is undocumented +# or is not a class. + +HIDE_UNDOC_RELATIONS = YES + +# If you set the HAVE_DOT tag to YES then doxygen will assume the dot tool is +# available from the path. This tool is part of Graphviz, a graph visualization +# toolkit from AT&T and Lucent Bell Labs. The other options in this section +# have no effect if this option is set to NO (the default) + +HAVE_DOT = @HAVEDOT@ + +# The DOT_NUM_THREADS specifies the number of dot invocations doxygen is +# allowed to run in parallel. When set to 0 (the default) doxygen will +# base this on the number of processors available in the system. You can set it +# explicitly to a value larger than 0 to get control over the balance +# between CPU load and processing speed. + +DOT_NUM_THREADS = 0 + +# By default doxygen will write a font called FreeSans.ttf to the output +# directory and reference it in all dot files that doxygen generates. This +# font does not include all possible unicode characters however, so when you need +# these (or just want a differently looking font) you can specify the font name +# using DOT_FONTNAME. You need need to make sure dot is able to find the font, +# which can be done by putting it in a standard location or by setting the +# DOTFONTPATH environment variable or by setting DOT_FONTPATH to the directory +# containing the font. + +DOT_FONTNAME = FreeSans.ttf + +# The DOT_FONTSIZE tag can be used to set the size of the font of dot graphs. +# The default size is 10pt. + +DOT_FONTSIZE = 10 + +# By default doxygen will tell dot to use the output directory to look for the +# FreeSans.ttf font (which doxygen will put there itself). If you specify a +# different font using DOT_FONTNAME you can set the path where dot +# can find it using this tag. + +DOT_FONTPATH = + +# If the CLASS_GRAPH and HAVE_DOT tags are set to YES then doxygen +# will generate a graph for each documented class showing the direct and +# indirect inheritance relations. Setting this tag to YES will force the +# the CLASS_DIAGRAMS tag to NO. + +CLASS_GRAPH = YES + +# If the COLLABORATION_GRAPH and HAVE_DOT tags are set to YES then doxygen +# will generate a graph for each documented class showing the direct and +# indirect implementation dependencies (inheritance, containment, and +# class references variables) of the class with other documented classes. + +COLLABORATION_GRAPH = YES + +# If the GROUP_GRAPHS and HAVE_DOT tags are set to YES then doxygen +# will generate a graph for groups, showing the direct groups dependencies + +GROUP_GRAPHS = YES + +# If the UML_LOOK tag is set to YES doxygen will generate inheritance and +# collaboration diagrams in a style similar to the OMG's Unified Modeling +# Language. + +UML_LOOK = NO + +# If set to YES, the inheritance and collaboration graphs will show the +# relations between templates and their instances. + +TEMPLATE_RELATIONS = NO + +# If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDE_GRAPH, and HAVE_DOT +# tags are set to YES then doxygen will generate a graph for each documented +# file showing the direct and indirect include dependencies of the file with +# other documented files. + +INCLUDE_GRAPH = NO + +# If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDED_BY_GRAPH, and +# HAVE_DOT tags are set to YES then doxygen will generate a graph for each +# documented header file showing the documented files that directly or +# indirectly include this file. + +INCLUDED_BY_GRAPH = YES + +# If the CALL_GRAPH and HAVE_DOT options are set to YES then +# doxygen will generate a call dependency graph for every global function +# or class method. Note that enabling this option will significantly increase +# the time of a run. So in most cases it will be better to enable call graphs +# for selected functions only using the \callgraph command. + +CALL_GRAPH = NO + +# If the CALLER_GRAPH and HAVE_DOT tags are set to YES then +# doxygen will generate a caller dependency graph for every global function +# or class method. Note that enabling this option will significantly increase +# the time of a run. So in most cases it will be better to enable caller +# graphs for selected functions only using the \callergraph command. + +CALLER_GRAPH = NO + +# If the GRAPHICAL_HIERARCHY and HAVE_DOT tags are set to YES then doxygen +# will graphical hierarchy of all classes instead of a textual one. + +GRAPHICAL_HIERARCHY = YES + +# If the DIRECTORY_GRAPH, SHOW_DIRECTORIES and HAVE_DOT tags are set to YES +# then doxygen will show the dependencies a directory has on other directories +# in a graphical way. The dependency relations are determined by the #include +# relations between the files in the directories. + +DIRECTORY_GRAPH = YES + +# The DOT_IMAGE_FORMAT tag can be used to set the image format of the images +# generated by dot. Possible values are png, jpg, or gif +# If left blank png will be used. + +DOT_IMAGE_FORMAT = png + +# The tag DOT_PATH can be used to specify the path where the dot tool can be +# found. If left blank, it is assumed the dot tool can be found in the path. + +DOT_PATH = @DOTPATH@ + +# The DOTFILE_DIRS tag can be used to specify one or more directories that +# contain dot files that are included in the documentation (see the +# \dotfile command). + +DOTFILE_DIRS = + +# The DOT_GRAPH_MAX_NODES tag can be used to set the maximum number of +# nodes that will be shown in the graph. If the number of nodes in a graph +# becomes larger than this value, doxygen will truncate the graph, which is +# visualized by representing a node as a red box. Note that doxygen if the +# number of direct children of the root node in a graph is already larger than +# DOT_GRAPH_MAX_NODES then the graph will not be shown at all. Also note +# that the size of a graph can be further restricted by MAX_DOT_GRAPH_DEPTH. + +DOT_GRAPH_MAX_NODES = 50 + +# The MAX_DOT_GRAPH_DEPTH tag can be used to set the maximum depth of the +# graphs generated by dot. A depth value of 3 means that only nodes reachable +# from the root by following a path via at most 3 edges will be shown. Nodes +# that lay further from the root node will be omitted. Note that setting this +# option to 1 or 2 may greatly reduce the computation time needed for large +# code bases. Also note that the size of a graph can be further restricted by +# DOT_GRAPH_MAX_NODES. Using a depth of 0 means no depth restriction. + +MAX_DOT_GRAPH_DEPTH = 0 + +# Set the DOT_TRANSPARENT tag to YES to generate images with a transparent +# background. This is disabled by default, because dot on Windows does not +# seem to support this out of the box. Warning: Depending on the platform used, +# enabling this option may lead to badly anti-aliased labels on the edges of +# a graph (i.e. they become hard to read). + +DOT_TRANSPARENT = YES + +# Set the DOT_MULTI_TARGETS tag to YES allow dot to generate multiple output +# files in one run (i.e. multiple -o and -T options on the command line). This +# makes dot run faster, but since only newer versions of dot (>1.8.10) +# support this, this feature is disabled by default. + +DOT_MULTI_TARGETS = NO + +# If the GENERATE_LEGEND tag is set to YES (the default) Doxygen will +# generate a legend page explaining the meaning of the various boxes and +# arrows in the dot generated graphs. + +GENERATE_LEGEND = YES + +# If the DOT_CLEANUP tag is set to YES (the default) Doxygen will +# remove the intermediate dot files that are used to generate +# the various graphs. + +DOT_CLEANUP = YES diff --git a/protocols/Twitter/oauth/INSTALL b/protocols/Twitter/oauth/INSTALL new file mode 100644 index 0000000000..7d1c323bea --- /dev/null +++ b/protocols/Twitter/oauth/INSTALL @@ -0,0 +1,365 @@ +Installation Instructions +************************* + +Copyright (C) 1994, 1995, 1996, 1999, 2000, 2001, 2002, 2004, 2005, +2006, 2007, 2008, 2009 Free Software Foundation, Inc. + + Copying and distribution of this file, with or without modification, +are permitted in any medium without royalty provided the copyright +notice and this notice are preserved. This file is offered as-is, +without warranty of any kind. + +Basic Installation +================== + + Briefly, the shell commands `./configure; make; make install' should +configure, build, and install this package. The following +more-detailed instructions are generic; see the `README' file for +instructions specific to this package. Some packages provide this +`INSTALL' file but do not implement all of the features documented +below. The lack of an optional feature in a given package is not +necessarily a bug. More recommendations for GNU packages can be found +in *note Makefile Conventions: (standards)Makefile Conventions. + + The `configure' shell script attempts to guess correct values for +various system-dependent variables used during compilation. It uses +those values to create a `Makefile' in each directory of the package. +It may also create one or more `.h' files containing system-dependent +definitions. Finally, it creates a shell script `config.status' that +you can run in the future to recreate the current configuration, and a +file `config.log' containing compiler output (useful mainly for +debugging `configure'). + + It can also use an optional file (typically called `config.cache' +and enabled with `--cache-file=config.cache' or simply `-C') that saves +the results of its tests to speed up reconfiguring. Caching is +disabled by default to prevent problems with accidental use of stale +cache files. + + If you need to do unusual things to compile the package, please try +to figure out how `configure' could check whether to do them, and mail +diffs or instructions to the address given in the `README' so they can +be considered for the next release. If you are using the cache, and at +some point `config.cache' contains results you don't want to keep, you +may remove or edit it. + + The file `configure.ac' (or `configure.in') is used to create +`configure' by a program called `autoconf'. You need `configure.ac' if +you want to change it or regenerate `configure' using a newer version +of `autoconf'. + + The simplest way to compile this package is: + + 1. `cd' to the directory containing the package's source code and type + `./configure' to configure the package for your system. + + Running `configure' might take a while. While running, it prints + some messages telling which features it is checking for. + + 2. Type `make' to compile the package. + + 3. Optionally, type `make check' to run any self-tests that come with + the package, generally using the just-built uninstalled binaries. + + 4. Type `make install' to install the programs and any data files and + documentation. When installing into a prefix owned by root, it is + recommended that the package be configured and built as a regular + user, and only the `make install' phase executed with root + privileges. + + 5. Optionally, type `make installcheck' to repeat any self-tests, but + this time using the binaries in their final installed location. + This target does not install anything. Running this target as a + regular user, particularly if the prior `make install' required + root privileges, verifies that the installation completed + correctly. + + 6. You can remove the program binaries and object files from the + source code directory by typing `make clean'. To also remove the + files that `configure' created (so you can compile the package for + a different kind of computer), type `make distclean'. There is + also a `make maintainer-clean' target, but that is intended mainly + for the package's developers. If you use it, you may have to get + all sorts of other programs in order to regenerate files that came + with the distribution. + + 7. Often, you can also type `make uninstall' to remove the installed + files again. In practice, not all packages have tested that + uninstallation works correctly, even though it is required by the + GNU Coding Standards. + + 8. Some packages, particularly those that use Automake, provide `make + distcheck', which can by used by developers to test that all other + targets like `make install' and `make uninstall' work correctly. + This target is generally not run by end users. + +Compilers and Options +===================== + + Some systems require unusual options for compilation or linking that +the `configure' script does not know about. Run `./configure --help' +for details on some of the pertinent environment variables. + + You can give `configure' initial values for configuration parameters +by setting variables in the command line or in the environment. Here +is an example: + + ./configure CC=c99 CFLAGS=-g LIBS=-lposix + + *Note Defining Variables::, for more details. + +Compiling For Multiple Architectures +==================================== + + You can compile the package for more than one kind of computer at the +same time, by placing the object files for each architecture in their +own directory. To do this, you can use GNU `make'. `cd' to the +directory where you want the object files and executables to go and run +the `configure' script. `configure' automatically checks for the +source code in the directory that `configure' is in and in `..'. This +is known as a "VPATH" build. + + With a non-GNU `make', it is safer to compile the package for one +architecture at a time in the source code directory. After you have +installed the package for one architecture, use `make distclean' before +reconfiguring for another architecture. + + On MacOS X 10.5 and later systems, you can create libraries and +executables that work on multiple system types--known as "fat" or +"universal" binaries--by specifying multiple `-arch' options to the +compiler but only a single `-arch' option to the preprocessor. Like +this: + + ./configure CC="gcc -arch i386 -arch x86_64 -arch ppc -arch ppc64" \ + CXX="g++ -arch i386 -arch x86_64 -arch ppc -arch ppc64" \ + CPP="gcc -E" CXXCPP="g++ -E" + + This is not guaranteed to produce working output in all cases, you +may have to build one architecture at a time and combine the results +using the `lipo' tool if you have problems. + +Installation Names +================== + + By default, `make install' installs the package's commands under +`/usr/local/bin', include files under `/usr/local/include', etc. You +can specify an installation prefix other than `/usr/local' by giving +`configure' the option `--prefix=PREFIX', where PREFIX must be an +absolute file name. + + You can specify separate installation prefixes for +architecture-specific files and architecture-independent files. If you +pass the option `--exec-prefix=PREFIX' to `configure', the package uses +PREFIX as the prefix for installing programs and libraries. +Documentation and other data files still use the regular prefix. + + In addition, if you use an unusual directory layout you can give +options like `--bindir=DIR' to specify different values for particular +kinds of files. Run `configure --help' for a list of the directories +you can set and what kinds of files go in them. In general, the +default for these options is expressed in terms of `${prefix}', so that +specifying just `--prefix' will affect all of the other directory +specifications that were not explicitly provided. + + The most portable way to affect installation locations is to pass the +correct locations to `configure'; however, many packages provide one or +both of the following shortcuts of passing variable assignments to the +`make install' command line to change installation locations without +having to reconfigure or recompile. + + The first method involves providing an override variable for each +affected directory. For example, `make install +prefix=/alternate/directory' will choose an alternate location for all +directory configuration variables that were expressed in terms of +`${prefix}'. Any directories that were specified during `configure', +but not in terms of `${prefix}', must each be overridden at install +time for the entire installation to be relocated. The approach of +makefile variable overrides for each directory variable is required by +the GNU Coding Standards, and ideally causes no recompilation. +However, some platforms have known limitations with the semantics of +shared libraries that end up requiring recompilation when using this +method, particularly noticeable in packages that use GNU Libtool. + + The second method involves providing the `DESTDIR' variable. For +example, `make install DESTDIR=/alternate/directory' will prepend +`/alternate/directory' before all installation names. The approach of +`DESTDIR' overrides is not required by the GNU Coding Standards, and +does not work on platforms that have drive letters. On the other hand, +it does better at avoiding recompilation issues, and works well even +when some directory options were not specified in terms of `${prefix}' +at `configure' time. + +Optional Features +================= + + If the package supports it, you can cause programs to be installed +with an extra prefix or suffix on their names by giving `configure' the +option `--program-prefix=PREFIX' or `--program-suffix=SUFFIX'. + + Some packages pay attention to `--enable-FEATURE' options to +`configure', where FEATURE indicates an optional part of the package. +They may also pay attention to `--with-PACKAGE' options, where PACKAGE +is something like `gnu-as' or `x' (for the X Window System). The +`README' should mention any `--enable-' and `--with-' options that the +package recognizes. + + For packages that use the X Window System, `configure' can usually +find the X include and library files automatically, but if it doesn't, +you can use the `configure' options `--x-includes=DIR' and +`--x-libraries=DIR' to specify their locations. + + Some packages offer the ability to configure how verbose the +execution of `make' will be. For these packages, running `./configure +--enable-silent-rules' sets the default to minimal output, which can be +overridden with `make V=1'; while running `./configure +--disable-silent-rules' sets the default to verbose, which can be +overridden with `make V=0'. + +Particular systems +================== + + On HP-UX, the default C compiler is not ANSI C compatible. If GNU +CC is not installed, it is recommended to use the following options in +order to use an ANSI C compiler: + + ./configure CC="cc -Ae -D_XOPEN_SOURCE=500" + +and if that doesn't work, install pre-built binaries of GCC for HP-UX. + + On OSF/1 a.k.a. Tru64, some versions of the default C compiler cannot +parse its `<wchar.h>' header file. The option `-nodtk' can be used as +a workaround. If GNU CC is not installed, it is therefore recommended +to try + + ./configure CC="cc" + +and if that doesn't work, try + + ./configure CC="cc -nodtk" + + On Solaris, don't put `/usr/ucb' early in your `PATH'. This +directory contains several dysfunctional programs; working variants of +these programs are available in `/usr/bin'. So, if you need `/usr/ucb' +in your `PATH', put it _after_ `/usr/bin'. + + On Haiku, software installed for all users goes in `/boot/common', +not `/usr/local'. It is recommended to use the following options: + + ./configure --prefix=/boot/common + +Specifying the System Type +========================== + + There may be some features `configure' cannot figure out +automatically, but needs to determine by the type of machine the package +will run on. Usually, assuming the package is built to be run on the +_same_ architectures, `configure' can figure that out, but if it prints +a message saying it cannot guess the machine type, give it the +`--build=TYPE' option. TYPE can either be a short name for the system +type, such as `sun4', or a canonical name which has the form: + + CPU-COMPANY-SYSTEM + +where SYSTEM can have one of these forms: + + OS + KERNEL-OS + + See the file `config.sub' for the possible values of each field. If +`config.sub' isn't included in this package, then this package doesn't +need to know the machine type. + + If you are _building_ compiler tools for cross-compiling, you should +use the option `--target=TYPE' to select the type of system they will +produce code for. + + If you want to _use_ a cross compiler, that generates code for a +platform different from the build platform, you should specify the +"host" platform (i.e., that on which the generated programs will +eventually be run) with `--host=TYPE'. + +Sharing Defaults +================ + + If you want to set default values for `configure' scripts to share, +you can create a site shell script called `config.site' that gives +default values for variables like `CC', `cache_file', and `prefix'. +`configure' looks for `PREFIX/share/config.site' if it exists, then +`PREFIX/etc/config.site' if it exists. Or, you can set the +`CONFIG_SITE' environment variable to the location of the site script. +A warning: not all `configure' scripts look for a site script. + +Defining Variables +================== + + Variables not defined in a site shell script can be set in the +environment passed to `configure'. However, some packages may run +configure again during the build, and the customized values of these +variables may be lost. In order to avoid this problem, you should set +them in the `configure' command line, using `VAR=value'. For example: + + ./configure CC=/usr/local2/bin/gcc + +causes the specified `gcc' to be used as the C compiler (unless it is +overridden in the site shell script). + +Unfortunately, this technique does not work for `CONFIG_SHELL' due to +an Autoconf bug. Until the bug is fixed you can use this workaround: + + CONFIG_SHELL=/bin/bash /bin/bash ./configure CONFIG_SHELL=/bin/bash + +`configure' Invocation +====================== + + `configure' recognizes the following options to control how it +operates. + +`--help' +`-h' + Print a summary of all of the options to `configure', and exit. + +`--help=short' +`--help=recursive' + Print a summary of the options unique to this package's + `configure', and exit. The `short' variant lists options used + only in the top level, while the `recursive' variant lists options + also present in any nested packages. + +`--version' +`-V' + Print the version of Autoconf used to generate the `configure' + script, and exit. + +`--cache-file=FILE' + Enable the cache: use and save the results of the tests in FILE, + traditionally `config.cache'. FILE defaults to `/dev/null' to + disable caching. + +`--config-cache' +`-C' + Alias for `--cache-file=config.cache'. + +`--quiet' +`--silent' +`-q' + Do not print messages saying which checks are being made. To + suppress all normal output, redirect it to `/dev/null' (any error + messages will still be shown). + +`--srcdir=DIR' + Look for the package's source code in directory DIR. Usually + `configure' can determine that directory automatically. + +`--prefix=DIR' + Use DIR as the installation prefix. *note Installation Names:: + for more details, including other options available for fine-tuning + the installation locations. + +`--no-create' +`-n' + Run the configure checks, but stop before creating any output + files. + +`configure' also accepts some other, not widely useful, options. Run +`configure --help' for more details. + diff --git a/protocols/Twitter/oauth/LICENSE.OpenSSL b/protocols/Twitter/oauth/LICENSE.OpenSSL new file mode 100644 index 0000000000..bf6b4b9453 --- /dev/null +++ b/protocols/Twitter/oauth/LICENSE.OpenSSL @@ -0,0 +1,137 @@ +Certain source files in this program permit linking with the OpenSSL +library (http://www.openssl.org), which otherwise wouldn't be allowed +under the GPL. For purposes of identifying OpenSSL, most source files +giving this permission limit it to versions of OpenSSL having a license +identical to that listed in this file (LICENSE.OpenSSL). It is not +necessary for the copyright years to match between this file and the +OpenSSL version in question. However, note that because this file is +an extension of the license statements of these source files, this file +may not be changed except with permission from all copyright holders +of source files in this program which reference this file. + + + LICENSE ISSUES + ============== + + The OpenSSL toolkit stays under a dual license, i.e. both the conditions of + the OpenSSL License and the original SSLeay license apply to the toolkit. + See below for the actual license texts. Actually both licenses are BSD-style + Open Source licenses. In case of any license issues related to OpenSSL + please contact openssl-core@openssl.org. + + OpenSSL License + --------------- + +/* ==================================================================== + * Copyright (c) 1998-2001 The OpenSSL Project. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. All advertising materials mentioning features or use of this + * software must display the following acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit. (http://www.openssl.org/)" + * + * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to + * endorse or promote products derived from this software without + * prior written permission. For written permission, please contact + * openssl-core@openssl.org. + * + * 5. Products derived from this software may not be called "OpenSSL" + * nor may "OpenSSL" appear in their names without prior written + * permission of the OpenSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit (http://www.openssl.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY + * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * ==================================================================== + * + * This product includes cryptographic software written by Eric Young + * (eay@cryptsoft.com). This product includes software written by Tim + * Hudson (tjh@cryptsoft.com). + * + */ + + Original SSLeay License + ----------------------- + +/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) + * All rights reserved. + * + * This package is an SSL implementation written + * by Eric Young (eay@cryptsoft.com). + * The implementation was written so as to conform with Netscapes SSL. + * + * This library is free for commercial and non-commercial use as long as + * the following conditions are aheared to. The following conditions + * apply to all code found in this distribution, be it the RC4, RSA, + * lhash, DES, etc., code; not just the SSL code. The SSL documentation + * included with this distribution is covered by the same copyright terms + * except that the holder is Tim Hudson (tjh@cryptsoft.com). + * + * Copyright remains Eric Young's, and as such any Copyright notices in + * the code are not to be removed. + * If this package is used in a product, Eric Young should be given attribution + * as the author of the parts of the library used. + * This can be in the form of a textual message at program startup or + * in documentation (online or textual) provided with the package. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * "This product includes cryptographic software written by + * Eric Young (eay@cryptsoft.com)" + * The word 'cryptographic' can be left out if the rouines from the library + * being used are not cryptographic related :-). + * 4. If you include any Windows specific code (or a derivative thereof) from + * the apps directory (application code) you must include an acknowledgement: + * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" + * + * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * The licence and distribution terms for any publically available version or + * derivative of this code cannot be changed. i.e. this code cannot simply be + * copied and put under another distribution licence + * [including the GNU Public Licence.] + */ diff --git a/protocols/Twitter/oauth/Makefile.am b/protocols/Twitter/oauth/Makefile.am new file mode 100644 index 0000000000..bacc32a25f --- /dev/null +++ b/protocols/Twitter/oauth/Makefile.am @@ -0,0 +1,39 @@ +ACLOCAL_AMFLAGS= -I m4 +SUBDIRS = @subdirs@ + +EXTRA_DIST=liboauth.lsm.in oauth.pc.in Doxyfile.in \ + COPYING.GPL COPYING.MIT LICENSE.OpenSSL \ + m4 + +pkgconfigdir = $(libdir)/pkgconfig +pkgconfig_DATA = oauth.pc + +TESTS=tests/tcwiki@EXESUF@ tests/tceran@EXESUF@ tests/tcother@EXESUF@ + +CLEANFILES = stamp-doxygen stamp-doc + +MAINTAINERCLEANFILES = \ + src/Makefile.in \ + tests/Makefile.in \ + tests/atconfig \ + doc/Makefile.in \ + Makefile.in \ + aclocal.m4 \ + compile \ + config.guess \ + config.h.in \ + config.sub \ + configure \ + depcomp \ + install-sh \ + missing + +dox: stamp-doxygen + +stamp-doxygen: src/oauth.h doc/mainpage.dox + $(DOXYGEN) Doxyfile && touch stamp-doxygen + cp doc/man/man3/oauth.h.3 doc/oauth.3 + sed 's/ -\([qsdU]\)/ \\-\1/g' doc/man/man3/oauth.h.3 \ + | sed 's/ -1 / \\-1 /' \ + | sed 's/--/\\-\\-/' \ + > doc/oauth.3 diff --git a/protocols/Twitter/oauth/NEWS b/protocols/Twitter/oauth/NEWS new file mode 100644 index 0000000000..e69de29bb2 --- /dev/null +++ b/protocols/Twitter/oauth/NEWS diff --git a/protocols/Twitter/oauth/README b/protocols/Twitter/oauth/README new file mode 100644 index 0000000000..ad28f1a4f2 --- /dev/null +++ b/protocols/Twitter/oauth/README @@ -0,0 +1,63 @@ +liboauth is a collection of c functions implementing the http://oauth.net API. + +liboauth provides functions to escape and encode stings according to +OAuth specifications and offers high-level functionality built on top to sign +requests or verify signatures using either NSS or OpenSSL for calculating +the hash/signatures. + +The included documentation in the doc/ folder and example code from tests/ +can also be found online at http://liboauth.sourceforge.net/ + +Send bug-reports, patches or suggestions to robin@gareus.org. +or inquire information at http://groups.google.com/group/oauth/ + + == License and Notes == + +The source-code of liboauth can be distributed under MIT License, +or at your option: in terms of the the GNU General Public License. +see COPYING.MIT or COPYING.GPL for details. + +Note: OpenSSL is not strictly compatible with the GPL license. +An exemption (to the GPL) allowing to link and redistribute +liboauth with the OpenSSL library is is included in the source files. +for more information, see LICENSE.OpenSSL and +http://lists.debian.org/debian-legal/2004/05/msg00595.html + +You can avoid this whole issue by using NSS instead of OpenSSL; +configure with '--enable-nss'. + +The Debian packaging that comes with the source-code is licensed under +the GNU General Public License. + + == Test and Example Code == + +After compilation `make check` can be used to perform a off-line self-test. + +There is also example code to perform and verify OAuth requests online, +but they are not run automatically. + + + tests/oauthexample.c - CONNECTS TO INTERNET + walk-though http://term.ie/oauth/example + + tests/oauthtest.c - CONNECTS TO INTERNET + gets a request-token from http://term.ie test-server + + tests/oauthtest2.c - CONNECTS TO INTERNET + gets a request-token from http://term.ie test-server + using OAuth HTTP Authorization header: + see http://oauth.net/core/1.0a/#auth_header + and http://oauth.net/core/1.0a/#consumer_req_param + + tests/selftest_wiki.c + tests/selftest_eran.c + Test-Cases for parameter encoding, signatures, etc + + tests/commontest.c + Common Test-Case functions exercising the low-level API used by self-tests. + + tests/oauthdatapost.c - CONNECTS TO INTERNET + Experimental code to sign data uploads + Note: The example keys have since been deleted from the test-server. + Code remains for inspiration/example purposes. + diff --git a/protocols/Twitter/oauth/configure.ac b/protocols/Twitter/oauth/configure.ac new file mode 100644 index 0000000000..c4b30d8d45 --- /dev/null +++ b/protocols/Twitter/oauth/configure.ac @@ -0,0 +1,256 @@ +AC_PREREQ(2.57) +AC_INIT([liboauth], [-], [robin AT gareus DOT org], [], [http://liboauth.sourceforge.net/]) +#AM_MAINTAINER_MODE + +AC_PATH_PROG(SED, sed, "", $PATH:/bin:/usr/bin:/usr/local/bin) +if test -z "$SED"; then + AC_MSG_WARN([sed was not found]) +fi + +AC_MSG_CHECKING([liboauth version]) +VERSION=`$SED -ne 's/^#define LIBOAUTH_VERSION "\(.*\)"/\1/p' ${srcdir}/src/oauth.h 2>/dev/null` +AC_MSG_RESULT($VERSION) +if test -z "$VERSION"; then + AC_MSG_ERROR([version number can not be retrieved from src/oauth.h]) +fi + +VERSION_CUR=`$SED -ne 's/^#define LIBOAUTH_CUR *\([0-9]*\)/\1/p' ${srcdir}/src/oauth.h 2>/dev/null` +VERSION_REV=`$SED -ne 's/^#define LIBOAUTH_REV *\([0-9]*\)/\1/p' ${srcdir}/src/oauth.h 2>/dev/null` +VERSION_AGE=`$SED -ne 's/^#define LIBOAUTH_AGE *\([0-9]*\)/\1/p' ${srcdir}/src/oauth.h 2>/dev/null` +VERSION_INFO=${VERSION_CUR}:${VERSION_REV}:${VERSION_AGE} + +AC_CONFIG_SRCDIR([src/oauth.c]) +AC_CONFIG_TESTDIR([tests]) +AC_CANONICAL_TARGET([]) +AC_COPYRIGHT([Copyright (C) Robin Gareus 2007-2011]) +AM_INIT_AUTOMAKE(liboauth,$VERSION) + +AM_CONFIG_HEADER(src/config.h) + +AC_SUBST(VERSION) +AC_SUBST(VERSION_INFO) +ISODATE=`date +%Y-%m-%d` +AC_SUBST(ISODATE) + +AC_CANONICAL_HOST + +AC_PROG_INSTALL +AC_PROG_CC +AC_PROG_MAKE_SET +AC_PROG_LN_S +AC_PROG_LIBTOOL +AM_PROG_LIBTOOL +AM_PROG_CC_C_O +AC_LIBTOOL_WIN32_DLL +AC_CONFIG_MACRO_DIR([m4]) + +AC_HEADER_STDC +AC_CHECK_HEADERS(unistd.h time.h string.h alloca.h stdio.h stdarg.h math.h) + +AC_HEADER_MAJOR +AC_FUNC_ALLOCA +AC_STRUCT_TM +AC_STRUCT_ST_BLOCKS +AC_FUNC_CLOSEDIR_VOID + +AH_TEMPLATE([HAVE_CURL], [Define as 1 if you have libcurl]) +AH_TEMPLATE([USE_BUILTIN_HASH], [Define to use neither NSS nor OpenSSL]) +AH_TEMPLATE([USE_NSS], [Define to use NSS instead of OpenSSL]) +AH_TEMPLATE([HAVE_SHELL_CURL], [Define if you can invoke curl via a shell command. This is only used if HAVE_CURL is not defined.]) +AH_TEMPLATE([OAUTH_CURL_TIMEOUT], [Define the number of seconds for the HTTP request to timeout; if not defined no timeout (or libcurl default) is used.]) + +EXESUF= +TEST_UNICODE=-DTEST_UNICODE + +dnl *** Target specific settings *** +case $target_os in + *darwin*) + ;; + *mingw32*|*win*) + EXESUF=.exe + TEST_UNICODE= + ;; + *) + ;; +esac +AC_SUBST(TEST_UNICODE) +AC_SUBST(EXESUF) + +dnl *** misc complier/linker flags *** +LIBOAUTH_CFLAGS="-Wall" +LIBOAUTH_LDFLAGS="${LIBOAUTH_CFLAGS} -export-symbols-regex '^oauth_.*'" +#LIBOAUTH_CFLAGS="${LIBOAUTH_CFLAGS} -g -posix -std=c99 -pedantic" + +AC_MSG_CHECKING([if -Wl,--as-needed works]) +LDFLAGS_save=$LDFLAGS +LDFLAGS="$LDFLAGS -Wl,--as-needed" +AC_TRY_LINK([], [], + [ + AC_MSG_RESULT([yes]) + LIBOAUTH_LDFLAGS="$LIBOAUTH_LDFLAGS -Wl,--as-needed" + ], + [AC_MSG_RESULT([no])]) +LDFLAGS=$LDFLAGS_save + +AC_SUBST(LIBOAUTH_CFLAGS) +AC_SUBST(LIBOAUTH_LDFLAGS) + + +dnl *** PKGconfig oauth.pc.in *** +PC_REQ="" +PC_LIB="" + +dnl *** configuration options *** +AC_ARG_ENABLE(curl, AC_HELP_STRING([--disable-curl],[do not use (command-line) curl])) +AC_ARG_ENABLE(libcurl, AC_HELP_STRING([--disable-libcurl],[do not use libcurl])) +AC_ARG_ENABLE(builtinhash, AC_HELP_STRING([--enable-builtinhash],[do use neither NSS nor OpenSSL: only HMAC/SHA1 signatures - no RSA/PK11])) +AC_ARG_ENABLE(nss, AC_HELP_STRING([--enable-nss],[use NSS instead of OpenSSL])) +AC_ARG_WITH([curltimeout], AC_HELP_STRING([--with-curltimeout@<:@=<int>@:>@],[use CURLOPT_TIMEOUT with libcurl HTTP requests. Timeout is given in seconds (default=60). Note: using this option also sets CURLOPT_NOSIGNAL. see http://curl.haxx.se/libcurl/c/curl_easy_setopt.html#CURLOPTTIMEOUT])) + +report_curl="no" +dnl ** check for commandline executable curl +if test "${enable_curl}" != "no"; then + AC_PATH_PROG(CURLCMD, curl, no, $PATH:/bin:/usr/bin:/usr/local/bin) + if test "$CURLCMD" != "no"; then + AC_DEFINE(HAVE_SHELL_CURL, 1) + report_curl="shell command" + fi +fi + +dnl ** check for libcurl +AS_IF([test "${enable_libcurl}" != "no"], [ + PKG_CHECK_MODULES(CURL, libcurl, + [ AC_DEFINE(HAVE_CURL, 1) HAVE_CURL=1 PC_REQ="$PC_REQ libcurl" PC_LIB="$PC_LIB ${CURL_LIBS}" report_curl="libcurl" ] , + [ + AC_CHECK_HEADERS(curl/curl.h) + AC_CHECK_LIB([curl], [curl_global_init], + [AC_DEFINE(HAVE_CURL, 1) HAVE_CURL=1 PC_REQ="$PC_REQ libcurl" PC_LIB="$PC_LIB -lcurl" report_curl="libcurl" ] + ) + ] + ) +]) + +report_curltimeout="-" +if test -n "${with_curltimeout}"; then + if test "${with_curltimeout}" == "yes"; then + AC_DEFINE(OAUTH_CURL_TIMEOUT, 60) + report_curltimeout="60" + else + if test "${with_curltimeout}" -gt 0; then + AC_DEFINE_UNQUOTED(OAUTH_CURL_TIMEOUT, [${with_curltimeout}]) + report_curltimeout=${with_curltimeout} + fi + fi +fi + +AC_SUBST(CURL_CFLAGS) +AC_SUBST(CURL_LIBS) + +dnl ** crypto/hash lib (OpenSSL or NSS) +AS_IF([test "${enable_builtinhash}" == "yes"], [ + AC_DEFINE(USE_BUILTIN_HASH, 1) USE_BUILTIN_HASH=1 + HASH_LIBS="" + HASH_CFLAGS="" + report_hash="built-in HMAC/SHA1 - no RSA" + AC_MSG_NOTICE([ + using built-in HMAC/SHA1 hash algorithm without RSA/PK11 support. + This option is not recommended for general use and should only + be used on small devices (AVR, mircocontrollers) where neither + NSS nor OpenSSL is available. + ]) +], [ + AS_IF([test "${enable_nss}" == "yes"], [ + PKG_CHECK_MODULES(NSS, nss, [ AC_DEFINE(USE_NSS, 1) USE_NSS=1 PC_REQ="$PC_REQ nss" ]) + HASH_LIBS=${NSS_LIBS} + HASH_CFLAGS=${NSS_CFLAGS} + report_hash="NSS" + ], [ + AC_CHECK_HEADERS(openssl/hmac.h) + if test -z "${HASH_LIBS}"; then + HASH_LIBS="-lcrypto" + fi + if test -z "${HASH_CFLAGS}"; then + HASH_CFLAGS="" + fi + report_hash="OpenSSL" + PC_LIB="$PC_LIB ${HASH_LIBS}" + PC_REQ="$PC_REQ libcrypto" + AC_MSG_NOTICE([ + + NOTE: OpenSSL is not compatible with GPL applications. + Even if only linked with GPL code you are not allowed to distibute your app. + However liboauth provides an exeption (to the GPL) to circumvent this issue + (see README, src/hash.c). Nevertheless, double-check your licensing. + + liboauth itself is licensed under MIT license and comatible with the GPL. + + Either way, you are probably better off using NSS (configure --enable-nss); + future versions of liboauth will default to the Mozilla NSS. + + see http://people.gnome.org/~markmc/openssl-and-the-gpl.html + ]) + ]) +]) + +AC_SUBST(HASH_LIBS) +AC_SUBST(HASH_CFLAGS) + +dnl *** doxygen *** +AC_ARG_VAR(DOXYGEN, Doxygen) +AC_PATH_PROG(DOXYGEN, doxygen, no) + +if test "$DOXYGEN" != "no"; then + DOXMAKE='run "make dox" to generate API html reference: doc/html/index.html' +fi + +dnl *** graphviz *** +dnl (needed for Doxyfile.in) +AC_ARG_VAR(DOT, The 'dot' program from graphviz) +AC_PATH_PROG(DOT, dot, no) +if test "$DOT" != "no"; then + HAVEDOT=YES + DOTPATH=$( dirname "$DOT" ) +else + HAVEDOT=NO +fi +AC_SUBST(HAVEDOT) +AC_SUBST(DOTPATH) + + +dnl *** perl *** +dnl (needed for Doxyfile.in) +AC_ARG_VAR(PERL, Perl) +AC_PATH_PROG(PERL, perl, no) +if test "$PERL" == "no"; then + AC_MSG_WARN([dude, where's your perl? doxygen will not like this!)]) +fi + +# PKGconfig oauth.pc.in +AC_SUBST(PC_REQ) +AC_SUBST(PC_LIB) + + +dnl *** output *** +subdirs="src doc tests" +AC_SUBST(subdirs) + +AC_OUTPUT(Makefile src/Makefile doc/Makefile tests/Makefile liboauth.lsm oauth.pc Doxyfile doc/mainpage.dox) + +AC_MSG_NOTICE([ + + liboauth configured: + ----------------------- + + version: $VERSION + interface revision: $VERSION_INFO + hash/signature: $report_hash + http integration: $report_curl + libcurl-timeout: $report_curltimeout + generate documentation: $DOXYGEN + installation prefix: $prefix + CFLAGS: $LIBOAUTH_CFLAGS $CFLAGS + LDFLAGS: $LIBOAUTH_LDFLAGS $LDFLAGS + + type "make" followed my "make install" as root. + $DOXMAKE +]) diff --git a/protocols/Twitter/oauth/debian/changelog b/protocols/Twitter/oauth/debian/changelog new file mode 100644 index 0000000000..f9423af21d --- /dev/null +++ b/protocols/Twitter/oauth/debian/changelog @@ -0,0 +1,204 @@ +liboauth (0.9.6-1) unstable; urgency=low + * new upstream release + -- Robin Gareus <robin@gareus.org> Tue, 13 Dec 2011 01:38:29 +0100 + +liboauth (0.9.5-1) unstable; urgency=low + * new upstream release + -- Robin Gareus <robin@gareus.org> Thu, 22 Sep 2011 12:24:17 +0200 + +liboauth (0.9.4-1) unstable; urgency=low + * new upstream release + -- Robin Gareus <robin@gareus.org> Wed, 26 Jan 2011 17:00:31 +0100 + +liboauth (0.9.3-1) unstable; urgency=low + * new upstream release + -- Robin Gareus <robin@gareus.org> Tue, 18 Jan 2011 17:44:45 +0100 + +liboauth (0.9.2-1) unstable; urgency=low + * new upstream release + -- Robin Gareus <robin@gareus.org> Thu, 13 Jan 2011 00:27:02 +0100 + +liboauth (0.9.1-1) unstable; urgency=low + * new upstream release + -- Robin Gareus <robin@gareus.org> Mon, 13 Sep 2010 14:10:35 +0200 + +liboauth (0.9.0-1) unstable; urgency=low + * new upstream release + -- Robin Gareus <robin@gareus.org> Tue, 07 Sep 2010 02:10:50 +0200 + +liboauth (0.8.9-1) unstable; urgency=low + * new upstream release + -- Robin Gareus <robin@gareus.org> Mon, 30 Aug 2010 17:34:36 +0200 + +liboauth (0.8.8-1) unstable; urgency=low + * new upstream release + -- Robin Gareus <robin@gareus.org> Tue, 08 Jun 2010 15:24:45 +0200 + +liboauth (0.8.7-1) unstable; urgency=low + * new upstream release + -- Robin Gareus <robin@gareus.org> Wed, 02 Jun 2010 17:49:10 +0200 + +liboauth (0.8.6-1) unstable; urgency=low + * new upstream release + -- Robin Gareus <robin@gareus.org> Tue, 01 Jun 2010 04:40:51 +0200 + +liboauth (0.8.5-1) unstable; urgency=low + * new upstream release + -- Robin Gareus <robin@gareus.org> Sun, 23 May 2010 16:32:51 +0200 + +liboauth (0.8.4-1) unstable; urgency=low + * new upstream release + -- Robin Gareus <robin@gareus.org> Sat, 22 May 2010 18:56:32 +0200 + +liboauth (0.8.3-1) unstable; urgency=low + * new upstream release + -- Robin Gareus <robin@gareus.org> Sat, 22 May 2010 17:15:29 +0200 + +liboauth (0.8.2-1) unstable; urgency=low + * new upstream release + -- Robin Gareus <robin@gareus.org> Sat, 22 May 2010 02:02:48 +0200 + +liboauth (0.8.1-1) unstable; urgency=low + * new upstream release + -- Robin Gareus <robin@gareus.org> Sat, 22 May 2010 01:24:53 +0200 + +liboauth (0.8.0-1) unstable; urgency=low + * new upstream release + -- Robin Gareus <robin@gareus.org> Fri, 21 May 2010 22:35:34 +0200 + +liboauth (0.7.2-1) unstable; urgency=low + * new upstream release + -- Robin Gareus <robin@gareus.org> Fri, 21 May 2010 15:46:15 +0200 + +liboauth (0.7.1-1) unstable; urgency=low + * new upstream release + -- Robin Gareus <robin@gareus.org> Fri, 21 May 2010 15:33:25 +0200 + +liboauth (0.7.0-1) unstable; urgency=low + * new upstream release + -- Robin Gareus <robin@gareus.org> Thu, 20 May 2010 17:14:33 +0200 + +liboauth (0.6.3-1) unstable; urgency=low + * new upstream release + -- Robin Gareus <robin@gareus.org> Sun, 16 May 2010 18:34:47 +0200 + +liboauth (0.6.2-1) unstable; urgency=low + * new upstream release + -- Robin Gareus <robin@gareus.org> Sun, 16 May 2010 16:39:32 +0200 + +liboauth (0.6.1-1) unstable; urgency=low + * new upstream release + -- Robin Gareus <robin@gareus.org> Fri, 18 Sep 2009 14:57:58 +0200 + +liboauth (0.6.0-1) unstable; urgency=low + * new upstream release + -- Robin Gareus <robin@gareus.org> Fri, 04 Sep 2009 13:51:55 +0200 + +liboauth (0.5.4-1) unstable; urgency=low + * new upstream release + -- Robin Gareus <robin@gareus.org> Mon, 24 Aug 2009 22:27:15 +0200 + +liboauth (0.5.3-1) unstable; urgency=low + * new upstream release + -- Robin Gareus <robin@gareus.org> Mon, 17 Aug 2009 14:37:36 +0200 + +liboauth (0.5.2-1) unstable; urgency=low + * new upstream release + -- Robin Gareus <robin@gareus.org> Thu, 06 Aug 2009 12:56:58 +0200 + +liboauth (0.5.1-1) unstable; urgency=low + * new upstream release + -- Robin Gareus <robin@gareus.org> Tue, 02 Jun 2009 13:33:16 +0200 + +liboauth (0.5.0-1) unstable; urgency=low + * new upstream release + -- Robin Gareus <robin@gareus.org> Sun, 15 Feb 2009 00:06:47 +0100 + +liboauth (0.4.5-1) unstable; urgency=low + * new upstream release + -- Robin Gareus <robin@gareus.org> Sun, 19 Oct 2008 14:21:13 +0200 + +liboauth (0.4.4-1) unstable; urgency=low + * new upstream release + -- Robin Gareus <robin@gareus.org> Sun, 19 Oct 2008 14:01:52 +0200 + +liboauth (0.4.3-1) unstable; urgency=low + * new upstream release + -- Robin Gareus <robin@gareus.org> Sat, 18 Oct 2008 00:17:35 +0200 + +liboauth (0.4.2-1) unstable; urgency=low + * new upstream release + -- Robin Gareus <robin@gareus.org> Fri, 17 Oct 2008 22:22:06 +0200 + +liboauth (0.4.1-1) unstable; urgency=low + * new upstream release + -- Robin Gareus <robin@gareus.org> Thu, 16 Oct 2008 22:45:10 +0200 + +liboauth (0.4.0-1) unstable; urgency=low + * new upstream release + -- Robin Gareus <robin@gareus.org> Wed, 17 Sep 2008 14:07:12 +0200 + +liboauth (0.3.4-1) unstable; urgency=low + * new upstream release + -- Robin Gareus <robin@gareus.org> Wed, 17 Sep 2008 11:07:07 +0200 + +liboauth (0.3.3-1) unstable; urgency=low + * new upstream release + -- Robin Gareus <robin@gareus.org> Fri, 12 Sep 2008 13:47:17 +0200 + +liboauth (0.3.2-1) unstable; urgency=low + * new upstream release + -- Robin Gareus <robin@gareus.org> Fri, 29 Aug 2008 21:36:14 +0200 + +liboauth (0.3.1-1) unstable; urgency=low + * new upstream release + -- Robin Gareus <robin@gareus.org> Thu, 28 Aug 2008 01:11:37 +0200 + +liboauth (0.3.0-1) unstable; urgency=low + * new upstream release + -- Robin Gareus <robin@gareus.org> Sun, 24 Aug 2008 22:33:44 +0200 + +liboauth (0.2.4-1) unstable; urgency=low + * new upstream release + -- Robin Gareus <robin@gareus.org> Sun, 24 Aug 2008 14:21:37 +0200 + +liboauth (0.2.3-2) unstable; urgency=low + * new upstream release + -- Robin Gareus <robin@gareus.org> Sun, 24 Aug 2008 12:10:10 +0200 + +liboauth (0.2.3-1) unstable; urgency=low + * new upstream release + -- Robin Gareus <robin@gareus.org> Sun, 24 Aug 2008 10:54:52 +0200 + +liboauth (0.2.2-1) unstable; urgency=low + * new upstream release + -- Robin Gareus <robin@gareus.org> Sat, 23 Aug 2008 17:34:41 +0200 + +liboauth (0.2.1-1) unstable; urgency=low + * new upstream release + -- Robin Gareus <robin@gareus.org> Wed, 13 Aug 2008 16:11:25 +0200 + +liboauth (0.2.0-1) unstable; urgency=low + * new upstream release + -- Robin Gareus <robin@gareus.org> Sat, 09 Aug 2008 19:02:05 +0200 + +liboauth (0.1.3-1) unstable; urgency=low + * new upstream release + -- Robin Gareus <robin@gareus.org> Wed, 23 Jul 2008 21:51:11 +0200 + +liboauth (0.1.2-1) unstable; urgency=low + * new upstream release + + -- Robin Gareus <robin@mediamatic.nl> Thu, 31 Jan 2008 14:46:33 +0100 + +liboauth (0.1.1-1) unstable; urgency=low + * new upstream release + + -- Robin Gareus <robin@mediamatic.nl> Mon, 07 Jan 2008 23:57:20 +0100 + +liboauth (0.1.0-1) unstable; urgency=low + + * Initial release + + -- Robin Gareus <robin@mediamatic.nl> Sun, 09 Dec 2007 22:01:34 +0100 + diff --git a/protocols/Twitter/oauth/debian/compat b/protocols/Twitter/oauth/debian/compat new file mode 100644 index 0000000000..7ed6ff82de --- /dev/null +++ b/protocols/Twitter/oauth/debian/compat @@ -0,0 +1 @@ +5 diff --git a/protocols/Twitter/oauth/debian/control b/protocols/Twitter/oauth/debian/control new file mode 100644 index 0000000000..f1df758cb5 --- /dev/null +++ b/protocols/Twitter/oauth/debian/control @@ -0,0 +1,29 @@ +Source: liboauth +Section: libs +Priority: optional +Maintainer: Robin Gareus <robin@gareus.org> +Build-Depends: debhelper (>= 5), autotools-dev, automake, libnss3-dev, libtool, autoconf +Standards-Version: 3.8.4 +Homepage: http://liboauth.sourceforge.net/ +Vcs-Git: git://rg42.org/liboauth + +Package: liboauth-dev +Section: libdevel +Architecture: any +Depends: liboauth0 (= ${binary:Version}), ${misc:Depends} +Description: Development files for liboauth + OAuth - secure authentication for desktop and web applications. + http://liboauth.sf.net/ is a collection of c functions implementing the + OAuth Core 1.0 standard API (RFC 5849). liboauth provides functions to escape + and encode parameters according to OAuth specfication and offers high-level + functionality to sign requests or verify signatures. + +Package: liboauth0 +Section: libs +Architecture: any +Depends: ${shlibs:Depends}, ${misc:Depends} +Description: OAuth - secure authentication for desktop and web applications + http://liboauth.sf.net/ is a collection of c functions implementing the + OAuth Core 1.0 standard API (RFC 5849). liboauth provides functions to escape + and encode parameters according to OAuth specification and offers high-level + functionality to sign requests or verify signatures. diff --git a/protocols/Twitter/oauth/debian/copyright b/protocols/Twitter/oauth/debian/copyright new file mode 100644 index 0000000000..ceb24bdb94 --- /dev/null +++ b/protocols/Twitter/oauth/debian/copyright @@ -0,0 +1,38 @@ +This package was debianized by Robin Gareus <robin@gareus.org> on +Sun, 09 Dec 2007 22:01:34 +0100. + +It was downloaded from: + + http://liboauth.sourceforge.net/pool/liboauth-0.8.0.tar.gz + +Upstream Author: + + Robin Gareus <robin@gareus.org> + +Copyright: + + Copyright (C) 2007, 2008, 2010 Robin Gareus <robin@gareus.org> + +License: + + This package is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This package is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this package; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + +On Debian systems, the complete text of the GNU General +Public License can be found in `/usr/share/common-licenses/GPL'. + +The Debian packaging is (C) 2007, Robin Gareus <robin@gareus.org> and +is licensed under the GPL, see `/usr/share/common-licenses/GPL'. + +Note that liboauth without packaging can be distributed under ther MIT license. diff --git a/protocols/Twitter/oauth/debian/docs b/protocols/Twitter/oauth/debian/docs new file mode 100644 index 0000000000..5a67db1a7c --- /dev/null +++ b/protocols/Twitter/oauth/debian/docs @@ -0,0 +1,2 @@ +tests/oauthexample.c +tests/oauthtest.c diff --git a/protocols/Twitter/oauth/debian/liboauth-dev.install b/protocols/Twitter/oauth/debian/liboauth-dev.install new file mode 100644 index 0000000000..e803e928ee --- /dev/null +++ b/protocols/Twitter/oauth/debian/liboauth-dev.install @@ -0,0 +1,6 @@ +usr/include/* +usr/lib/pkgconfig/* +usr/share/man/man3/oauth.3 +usr/lib/lib*.a +usr/lib/lib*.so +usr/lib/lib*.la diff --git a/protocols/Twitter/oauth/debian/liboauth0.install b/protocols/Twitter/oauth/debian/liboauth0.install new file mode 100644 index 0000000000..d0dbfd18ac --- /dev/null +++ b/protocols/Twitter/oauth/debian/liboauth0.install @@ -0,0 +1 @@ +usr/lib/lib*.so.* diff --git a/protocols/Twitter/oauth/debian/rules b/protocols/Twitter/oauth/debian/rules new file mode 100644 index 0000000000..6521376426 --- /dev/null +++ b/protocols/Twitter/oauth/debian/rules @@ -0,0 +1,104 @@ +#!/usr/bin/make -f +# -*- makefile -*- +# Sample debian/rules that uses debhelper. +# This file was originally written by Joey Hess and Craig Small. +# As a special exception, when this file is copied by dh-make into a +# dh-make output file, you may use that output file without restriction. +# This special exception was added by Craig Small in version 0.37 of dh-make. + +# Uncomment this to turn on verbose mode. +#export DH_VERBOSE=1 + + +# These are used for cross-compiling and for saving the configure script +# from having to guess our platform (since we know it already) +DEB_HOST_GNU_TYPE ?= $(shell dpkg-architecture -qDEB_HOST_GNU_TYPE) +DEB_BUILD_GNU_TYPE ?= $(shell dpkg-architecture -qDEB_BUILD_GNU_TYPE) + + +# shared library versions, option 1 +version=2.0.5 +major=2 +# option 2, assuming the library is created as src/.libs/libfoo.so.2.0.5 or so +version=`ls src/.libs/lib*.so.* | \ + awk '{if (match($$0,/[0-9]+\.[0-9]+\.[0-9]+$$/)) print substr($$0,RSTART)}'` +major=`ls src/.libs/lib*.so.* | \ + awk '{if (match($$0,/\.so\.[0-9]+$$/)) print substr($$0,RSTART+4)}'` + +configure: + aclocal + autoheader + libtoolize --copy + autoconf + automake --gnu --add-missing --copy + +config.status: configure + dh_testdir + # Add here commands to configure the package. + ./configure --host=$(DEB_HOST_GNU_TYPE) --build=$(DEB_BUILD_GNU_TYPE) --prefix=/usr --mandir=\$${prefix}/share/man --infodir=\$${prefix}/share/info CFLAGS="$(CFLAGS)" LDFLAGS="-Wl,-z,defs" --enable-nss --with-curltimeout=120 + + +build: build-stamp +build-stamp: config.status + dh_testdir + + $(MAKE) + + touch $@ + +clean: + dh_testdir + dh_testroot + rm -f build-stamp + + [ ! -f Makefile ] || $(MAKE) distclean + rm -f configure config.sub config.guess + + dh_clean -a + +install: build + dh_testdir + dh_testroot + dh_clean -k -a + dh_installdirs + + $(MAKE) DESTDIR=$(CURDIR)/debian/tmp install + + +# Build architecture-independent files here. +binary-indep: build install +# We have nothing to do by default. + +# Build architecture-dependent files here. +binary-arch: build install + dh_testdir + dh_testroot + dh_install -a --sourcedir=debian/tmp --list-missing + dh_installdocs -a + dh_installchangelogs -a ChangeLog + dh_installexamples -a +# dh_installmenu +# dh_installdebconf +# dh_installlogrotate +# dh_installemacsen +# dh_installpam +# dh_installmime +# dh_installinit +# dh_installcron +# dh_installinfo + dh_installman -a + dh_link -a + dh_strip -a + dh_compress -a + dh_fixperms -a +# dh_perl -a +# dh_python -a + dh_makeshlibs -a + dh_installdeb -a + dh_shlibdeps -a + dh_gencontrol -a + dh_md5sums -a + dh_builddeb -a + +binary: binary-indep binary-arch +.PHONY: build clean binary-indep binary-arch binary install diff --git a/protocols/Twitter/oauth/doc/Makefile.am b/protocols/Twitter/oauth/doc/Makefile.am new file mode 100644 index 0000000000..ff535f9dba --- /dev/null +++ b/protocols/Twitter/oauth/doc/Makefile.am @@ -0,0 +1,7 @@ +ACLOCAL_AMFLAGS= -I m4 +man_MANS=oauth.3 + +EXTRA_DIST=oauth.3 mainpage.dox libOAuth.png + +clean: + rm -rf html man diff --git a/protocols/Twitter/oauth/doc/libOAuth.png b/protocols/Twitter/oauth/doc/libOAuth.png Binary files differnew file mode 100644 index 0000000000..854c89d7c7 --- /dev/null +++ b/protocols/Twitter/oauth/doc/libOAuth.png diff --git a/protocols/Twitter/oauth/doc/mainpage.dox.in b/protocols/Twitter/oauth/doc/mainpage.dox.in new file mode 100644 index 0000000000..d798236c55 --- /dev/null +++ b/protocols/Twitter/oauth/doc/mainpage.dox.in @@ -0,0 +1,112 @@ +/** +@mainpage OAuth library functions + +\image html libOAuth.png "libOAuth" + +@section intro Introduction + + liboauth is a collection of POSIX-c functions implementing the <a href="http://oauth.net/">OAuth</a> Core <a href="http://tools.ietf.org/html/rfc5849">RFC 5849</a> standard. + liboauth provides functions to escape and encode parameters according to OAuth specification and offers high-level functionality to sign requests or verify OAuth signatures as well as perform HTTP requests. + + liboauth depends on either on the <a href="http://openssl.org/">OpenSSL</a> library or on + <a href="http://www.mozilla.org/projects/security/pki/nss/">NSS</a> (Mozilla's Network Security Services) + , which are used for generating the hash/signature, and optionally <a href="http://curl.haxx.se/libcurl/c/">libcurl</a> for issuing HTTP requests. + + The source includes example code and a self-tests based on <a href="http://wiki.oauth.net/TestCases">http://wiki.oauth.net/TestCases</a>. The library has been tested against the http://oauth-sandbox.mediamatic.nl (now offline) and http://term.ie/oauth/example test servers using commandline-cURL, libcurl and a QT4.3.2 QHttp C++ application on win32 (mingw), gnu/Linux and Mac/OSX. + +@section installation Installation + The source is debianized. On Debian systems <tt>debian-buildpackage</tt> can be used to compile and <tt>dpkg -i</tt> to install <em>liboauth</em> and <em>liboauth-dev</em> packages. + + liboauth uses autotools and libtools. The tar.gz package includes the <tt>configure</tt> script, but if you get the source from the repository, you first need to generate the build environment with something alike: + <tt>aclocal; autoheader; libtoolize --copy; autoconf; automake --gnu --add-missing --copy</tt>. (<i>OSX users use <tt>glibtoolize</tt></i>). + + run <tt>./configure</tt> and build liboauth with <tt>make</tt>. see the INSTALL file for further instructions on gnu autotools. + + run <tt>./configure --help</tt> for information on optional features (<tt>--disable-curl</tt>, <tt>--disable-libcurl</tt>, <tt>--enable-nss</tt>, <tt>--with-curltimeout[=<int>]</tt>). + + If <a href="http://www.stack.nl/~dimitri/doxygen/">Doxygen</a> is available, the documentation can be rendered from the source by calling <tt>make dox</tt>. The http://wiki.oauth.net/TestCases scenarios in the example code can be run with <tt>make check</tt>. + +@section usage Usage + Consult \ref oauth.h for a detailed reference of available functions. This documentation is also available as unix manual page: <tt>man 3 oauth</tt>. + + See <tt>tests/oauthtest.c</tt> for the self-test code and example. <tt>tests/oauthexample.c</tt> implements a simple hardcoded OAuth-consumer. + If you simply want to calculate the OAuth-signature, all you need is \ref oauth_sign_url. + Future releases might include more elaborate usage information: Feel free to ask questions. + + <a href="http://rg42.org/oss/oauth/">oauth-utils</a> includes a command-line OAuth-consumer and signature-verification tool using liboauth. + +@section download Download + + Download Source: <a href="http://sourceforge.net/projects/liboauth/files/liboauth-@VERSION@.tar.gz/download">liboauth-@VERSION@.tar.gz</a> + <a href="http://liboauth.svn.sourceforge.net/viewvc/liboauth/trunk/ChangeLog?revision=HEAD&view=markup">Changelog</a>. + + liboauth is maintained at sourceforge subversion repositories: + <a href="http://liboauth.svn.sourceforge.net/viewvc/liboauth/">Browse Web SVN</a> URL: <tt>https://liboauth.svn.sourceforge.net/svnroot/liboauth/</tt>, and mirrored at the <a href="http://oauth.googlecode.com/svn/code/c/liboauth/">OAuth googlecode repository</a>. + + <!-- + The development branch is available from <tt>git://rg42.org/liboauth</tt> or download a <a href="http://rg42.org/gitweb/?p=liboauth.git;a=snapshot;h=head">snapshot</a>. + !--> + +@section bug Bugs + Send bug reports, patches or suggestions to robin @ gareus . org. + + Ask the <a href="http://oauth.net/community/">oauth-community</a> or join the <a href="http://groups.google.com/group/oauth/">mailing list</a> for discussion. + +@section license License + The source-code of liboauth can be distributed under <a href="http://www.opensource.org/licenses/mit-license.php">MIT License</a>, + or at your option in terms of the the <a href="http://www.gnu.org/licenses/old-licenses/gpl-2.0.html">GNU General Public License</a>. + + Note: OpenSSL is not strictly compatible with the GPL license. + An exemption (to the GPL) allowing to link and redistribute liboauth with the OpenSSL library is is included in the source files. + More information is available in the + <a href="http://liboauth.svn.sourceforge.net/viewvc/liboauth/trunk/README?revision=HEAD&view=markup">README</a>. + You can avoid this whole issue by using NSS instead of OpenSSL, configuring liboauth with <tt>--enable-nss</tt>. + + The Debian packaging that comes with the source-code is licensed under the GNU General Public License. + +MIT License (source-code): +<pre> + Copyright 2007-2010 Robin Gareus + + 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. +</pre> + +GPL (Debian packaging and alternative source-code license): +<pre> + This package is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This package is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this package; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +</pre> + +\example tests/oauthtest.c +\example tests/oauthtest2.c +\example tests/oauthexample.c +\example tests/oauthbodyhash.c +\example tests/selftest_wiki.c +*/ diff --git a/protocols/Twitter/oauth/doc/oauth.3 b/protocols/Twitter/oauth/doc/oauth.3 new file mode 100644 index 0000000000..3e8dbcf630 --- /dev/null +++ b/protocols/Twitter/oauth/doc/oauth.3 @@ -0,0 +1,1042 @@ +.TH "src/oauth.h" 3 "Tue Dec 13 2011" "Version 0.9.6" "OAuth library functions" \" -*- nroff -*- +.ad l +.nh +.SH NAME +src/oauth.h \- +.PP +OAuth.net implementation in POSIX-C. + +.SH SYNOPSIS +.br +.PP +.SS "Defines" + +.in +1c +.ti -1c +.RI "#define \fBOA_GCC_VERSION_AT_LEAST\fP(x, y) 0" +.br +.ti -1c +.RI "#define \fBattribute_deprecated\fP" +.br +.in -1c +.SS "Enumerations" + +.in +1c +.ti -1c +.RI "enum \fBOAuthMethod\fP { \fBOA_HMAC\fP = 0, \fBOA_RSA\fP, \fBOA_PLAINTEXT\fP }" +.br +.RI "\fIsignature method to used for signing the request. \fP" +.in -1c +.SS "Functions" + +.in +1c +.ti -1c +.RI "char * \fBoauth_encode_base64\fP (int size, const unsigned char *src)" +.br +.RI "\fIBase64 encode and return size data in 'src'. \fP" +.ti -1c +.RI "int \fBoauth_decode_base64\fP (unsigned char *dest, const char *src)" +.br +.RI "\fIDecode the base64 encoded string 'src' into the memory pointed to by 'dest'. \fP" +.ti -1c +.RI "char * \fBoauth_url_escape\fP (const char *string)" +.br +.RI "\fIEscape 'string' according to RFC3986 and http://oauth.net/core/1.0/#encoding_parameters. \fP" +.ti -1c +.RI "char * \fBoauth_url_unescape\fP (const char *string, size_t *olen)" +.br +.RI "\fIParse RFC3986 encoded 'string' back to unescaped version. \fP" +.ti -1c +.RI "char * \fBoauth_sign_hmac_sha1\fP (const char *m, const char *k)" +.br +.RI "\fIreturns base64 encoded HMAC-SHA1 signature for given message and key. \fP" +.ti -1c +.RI "char * \fBoauth_sign_hmac_sha1_raw\fP (const char *m, const size_t ml, const char *k, const size_t kl)" +.br +.RI "\fIsame as \fBoauth_sign_hmac_sha1\fP but allows to specify length of message and key (in case they contain null chars). \fP" +.ti -1c +.RI "char * \fBoauth_sign_plaintext\fP (const char *m, const char *k)" +.br +.RI "\fIreturns plaintext signature for the given key. \fP" +.ti -1c +.RI "char * \fBoauth_sign_rsa_sha1\fP (const char *m, const char *k)" +.br +.RI "\fIreturns RSA-SHA1 signature for given data. \fP" +.ti -1c +.RI "int \fBoauth_verify_rsa_sha1\fP (const char *m, const char *c, const char *s)" +.br +.RI "\fIverify RSA-SHA1 signature. \fP" +.ti -1c +.RI "char * \fBoauth_catenc\fP (int len,...)" +.br +.RI "\fIurl-escape strings and concatenate with '&' separator. \fP" +.ti -1c +.RI "int \fBoauth_split_url_parameters\fP (const char *url, char ***argv)" +.br +.RI "\fIsplits the given url into a parameter array. \fP" +.ti -1c +.RI "int \fBoauth_split_post_paramters\fP (const char *url, char ***argv, short qesc)" +.br +.RI "\fIsplits the given url into a parameter array. \fP" +.ti -1c +.RI "char * \fBoauth_serialize_url\fP (int argc, int start, char **argv)" +.br +.RI "\fIbuild a url query string from an array. \fP" +.ti -1c +.RI "char * \fBoauth_serialize_url_sep\fP (int argc, int start, char **argv, char *sep, int mod)" +.br +.RI "\fIencode query parameters from an array. \fP" +.ti -1c +.RI "char * \fBoauth_serialize_url_parameters\fP (int argc, char **argv)" +.br +.RI "\fIbuild a query parameter string from an array. \fP" +.ti -1c +.RI "char * \fBoauth_gen_nonce\fP ()" +.br +.RI "\fIgenerate a random string between 15 and 32 chars length and return a pointer to it. \fP" +.ti -1c +.RI "int \fBoauth_cmpstringp\fP (const void *p1, const void *p2)" +.br +.RI "\fIstring compare function for oauth parameters. \fP" +.ti -1c +.RI "int \fBoauth_param_exists\fP (char **argv, int argc, char *key)" +.br +.RI "\fIsearch array for parameter key. \fP" +.ti -1c +.RI "void \fBoauth_add_param_to_array\fP (int *argcp, char ***argvp, const char *addparam)" +.br +.RI "\fIadd query parameter to array \fP" +.ti -1c +.RI "void \fBoauth_free_array\fP (int *argcp, char ***argvp)" +.br +.RI "\fIfree array args \fP" +.ti -1c +.RI "int \fBoauth_time_independent_equals_n\fP (const char *a, const char *b, size_t len_a, size_t len_b)" +.br +.RI "\fIcompare two strings in constant-time (as to not let an attacker guess how many leading chars are correct: http://rdist.root.org/2010/01/07/timing-independent-array-comparison/ ) \fP" +.ti -1c +.RI "int \fBoauth_time_indepenent_equals_n\fP (const char *a, const char *b, size_t len_a, size_t len_b) attribute_deprecated" +.br +.ti -1c +.RI "int \fBoauth_time_independent_equals\fP (const char *a, const char *b)" +.br +.RI "\fIcompare two strings in constant-time. \fP" +.ti -1c +.RI "int \fBoauth_time_indepenent_equals\fP (const char *a, const char *b) attribute_deprecated" +.br +.ti -1c +.RI "char * \fBoauth_sign_url2\fP (const char *url, char **postargs, \fBOAuthMethod\fP method, const char *http_method, const char *c_key, const char *c_secret, const char *t_key, const char *t_secret)" +.br +.RI "\fIcalculate OAuth-signature for a given HTTP request URL, parameters and oauth-tokens. \fP" +.ti -1c +.RI "char * \fBoauth_sign_url\fP (const char *url, char **postargs, \fBOAuthMethod\fP method, const char *c_key, const char *c_secret, const char *t_key, const char *t_secret) attribute_deprecated" +.br +.ti -1c +.RI "void \fBoauth_sign_array2_process\fP (int *argcp, char ***argvp, char **postargs, \fBOAuthMethod\fP method, const char *http_method, const char *c_key, const char *c_secret, const char *t_key, const char *t_secret)" +.br +.RI "\fIthe back-end behind by /ref oauth_sign_array2. \fP" +.ti -1c +.RI "char * \fBoauth_sign_array2\fP (int *argcp, char ***argvp, char **postargs, \fBOAuthMethod\fP method, const char *http_method, const char *c_key, const char *c_secret, const char *t_key, const char *t_secret)" +.br +.RI "\fIsame as /ref oauth_sign_url with the url already split into parameter array \fP" +.ti -1c +.RI "char * \fBoauth_sign_array\fP (int *argcp, char ***argvp, char **postargs, \fBOAuthMethod\fP method, const char *c_key, const char *c_secret, const char *t_key, const char *t_secret) attribute_deprecated" +.br +.ti -1c +.RI "char * \fBoauth_body_hash_file\fP (char *filename)" +.br +.RI "\fIcalculate body hash (sha1sum) of given file and return a oauth_body_hash=xxxx parameter to be added to the request. \fP" +.ti -1c +.RI "char * \fBoauth_body_hash_data\fP (size_t length, const char *data)" +.br +.RI "\fIcalculate body hash (sha1sum) of given data and return a oauth_body_hash=xxxx parameter to be added to the request. \fP" +.ti -1c +.RI "char * \fBoauth_body_hash_encode\fP (size_t len, unsigned char *digest)" +.br +.RI "\fIbase64 encode digest, free it and return a URL parameter with the oauth_body_hash. \fP" +.ti -1c +.RI "char * \fBoauth_sign_xmpp\fP (const char *xml, \fBOAuthMethod\fP method, const char *c_secret, const char *t_secret)" +.br +.RI "\fIxep-0235 - TODO \fP" +.ti -1c +.RI "char * \fBoauth_http_get\fP (const char *u, const char *q)" +.br +.RI "\fIdo a HTTP GET request, wait for it to finish and return the content of the reply. \fP" +.ti -1c +.RI "char * \fBoauth_http_get2\fP (const char *u, const char *q, const char *customheader)" +.br +.RI "\fIdo a HTTP GET request, wait for it to finish and return the content of the reply. \fP" +.ti -1c +.RI "char * \fBoauth_http_post\fP (const char *u, const char *p)" +.br +.RI "\fIdo a HTTP POST request, wait for it to finish and return the content of the reply. \fP" +.ti -1c +.RI "char * \fBoauth_http_post2\fP (const char *u, const char *p, const char *customheader)" +.br +.RI "\fIdo a HTTP POST request, wait for it to finish and return the content of the reply. \fP" +.ti -1c +.RI "char * \fBoauth_post_file\fP (const char *u, const char *fn, const size_t len, const char *customheader)" +.br +.RI "\fIhttp post raw data from file. \fP" +.ti -1c +.RI "char * \fBoauth_post_data\fP (const char *u, const char *data, size_t len, const char *customheader)" +.br +.RI "\fIhttp post raw data the returned string needs to be freed by the caller (requires libcurl) \fP" +.ti -1c +.RI "char * \fBoauth_post_data_with_callback\fP (const char *u, const char *data, size_t len, const char *customheader, void(*callback)(void *, int, size_t, size_t), void *callback_data)" +.br +.RI "\fIhttp post raw data, with callback. \fP" +.ti -1c +.RI "char * \fBoauth_send_data\fP (const char *u, const char *data, size_t len, const char *customheader, const char *httpMethod)" +.br +.RI "\fIhttp send raw data. \fP" +.ti -1c +.RI "char * \fBoauth_send_data_with_callback\fP (const char *u, const char *data, size_t len, const char *customheader, void(*callback)(void *, int, size_t, size_t), void *callback_data, const char *httpMethod)" +.br +.RI "\fIhttp post raw data, with callback. \fP" +.in -1c +.SH "Detailed Description" +.PP +OAuth.net implementation in POSIX-C. + +\fBAuthor:\fP +.RS 4 +Robin Gareus <robin@gareus.org> +.RE +.PP +Copyright 2007-2011 Robin Gareus <robin@gareus.org> +.PP +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: +.PP +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. +.PP +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. +.PP +Definition in file \fBoauth.h\fP. +.SH "Define Documentation" +.PP +.SS "#define attribute_deprecated" +.PP +Definition at line 54 of file oauth.h. +.SS "#define OA_GCC_VERSION_AT_LEAST(x, y) 0" +.PP +Definition at line 47 of file oauth.h. +.SH "Enumeration Type Documentation" +.PP +.SS "enum \fBOAuthMethod\fP" +.PP +signature method to used for signing the request. +.PP +\fBEnumerator: \fP +.in +1c +.TP +\fB\fIOA_HMAC \fP\fP +use HMAC-SHA1 request signing method +.TP +\fB\fIOA_RSA \fP\fP +use RSA signature +.TP +\fB\fIOA_PLAINTEXT \fP\fP +use plain text signature (for testing only) +.PP +Definition at line 65 of file oauth.h. +.SH "Function Documentation" +.PP +.SS "void oauth_add_param_to_array (int * argcp, char *** argvp, const char * addparam)" +.PP +add query parameter to array \fBParameters:\fP +.RS 4 +\fIargcp\fP pointer to array length int +.br +\fIargvp\fP pointer to array values +.br +\fIaddparam\fP parameter to add (eg. 'foo=bar') +.RE +.PP + +.SS "char* oauth_body_hash_data (size_t length, const char * data)" +.PP +calculate body hash (sha1sum) of given data and return a oauth_body_hash=xxxx parameter to be added to the request. The returned string needs to be freed by the calling function. The returned string is not yet url-escaped and suitable to be passed as argument to \fBoauth_catenc\fP. +.PP +see http://oauth.googlecode.com/svn/spec/ext/body_hash/1.0/oauth-bodyhash.html +.PP +\fBParameters:\fP +.RS 4 +\fIlength\fP length of the data parameter in bytes +.br +\fIdata\fP to calculate the hash for +.RE +.PP +\fBReturns:\fP +.RS 4 +URL oauth_body_hash parameter string +.RE +.PP + +.PP +\fBExamples: \fP +.in +1c +\fBtests/oauthbodyhash.c\fP. +.SS "char* oauth_body_hash_encode (size_t len, unsigned char * digest)" +.PP +base64 encode digest, free it and return a URL parameter with the oauth_body_hash. The returned hash needs to be freed by the calling function. The returned string is not yet url-escaped and thus suitable to be passed to \fBoauth_catenc\fP. +.PP +\fBParameters:\fP +.RS 4 +\fIlen\fP length of the digest to encode +.br +\fIdigest\fP hash value to encode +.RE +.PP +\fBReturns:\fP +.RS 4 +URL oauth_body_hash parameter string +.RE +.PP + +.SS "char* oauth_body_hash_file (char * filename)" +.PP +calculate body hash (sha1sum) of given file and return a oauth_body_hash=xxxx parameter to be added to the request. The returned string needs to be freed by the calling function. +.PP +see http://oauth.googlecode.com/svn/spec/ext/body_hash/1.0/oauth-bodyhash.html +.PP +\fBParameters:\fP +.RS 4 +\fIfilename\fP the filename to calculate the hash for +.RE +.PP +\fBReturns:\fP +.RS 4 +URL oauth_body_hash parameter string +.RE +.PP + +.PP +\fBExamples: \fP +.in +1c +\fBtests/oauthbodyhash.c\fP. +.SS "char* oauth_catenc (int len, ...)" +.PP +url-escape strings and concatenate with '&' separator. The number of strings to be concatenated must be given as first argument. all arguments thereafter must be of type (char *) +.PP +\fBParameters:\fP +.RS 4 +\fIlen\fP the number of arguments to follow this parameter +.RE +.PP +\fBReturns:\fP +.RS 4 +pointer to memory holding the concatenated strings - needs to be free(d) by the caller. or NULL in case we ran out of memory. +.RE +.PP + +.PP +\fBExamples: \fP +.in +1c +\fBtests/oauthbodyhash.c\fP. +.SS "int oauth_cmpstringp (const void * p1, const void * p2)" +.PP +string compare function for oauth parameters. used with qsort. needed to normalize request parameters. see http://oauth.net/core/1.0/#anchor14 +.PP +\fBExamples: \fP +.in +1c +\fBtests/oauthexample.c\fP, \fBtests/oauthtest.c\fP, and \fBtests/oauthtest2.c\fP. +.SS "int oauth_decode_base64 (unsigned char * dest, const char * src)" +.PP +Decode the base64 encoded string 'src' into the memory pointed to by 'dest'. \fBParameters:\fP +.RS 4 +\fIdest\fP Pointer to memory for holding the decoded string. Must be large enough to receive the decoded string. +.br +\fIsrc\fP A base64 encoded string. +.RE +.PP +\fBReturns:\fP +.RS 4 +the length of the decoded string if decode succeeded otherwise 0. +.RE +.PP + +.SS "char* oauth_encode_base64 (int size, const unsigned char * src)" +.PP +Base64 encode and return size data in 'src'. The caller must free the returned string. +.PP +\fBParameters:\fP +.RS 4 +\fIsize\fP The size of the data in src +.br +\fIsrc\fP The data to be base64 encode +.RE +.PP +\fBReturns:\fP +.RS 4 +encoded string otherwise NULL +.RE +.PP + +.SS "void oauth_free_array (int * argcp, char *** argvp)" +.PP +free array args \fBParameters:\fP +.RS 4 +\fIargcp\fP pointer to array length int +.br +\fIargvp\fP pointer to array values to be free()d +.RE +.PP + +.PP +\fBExamples: \fP +.in +1c +\fBtests/oauthtest2.c\fP. +.SS "char* oauth_gen_nonce ()" +.PP +generate a random string between 15 and 32 chars length and return a pointer to it. The value needs to be freed by the caller +.PP +\fBReturns:\fP +.RS 4 +zero terminated random string. +.RE +.PP + +.SS "char* oauth_http_get (const char * u, const char * q)" +.PP +do a HTTP GET request, wait for it to finish and return the content of the reply. (requires libcurl or a command-line HTTP client) +.PP +If compiled \fBwithout\fP libcurl this function calls a command-line executable defined in the environment variable OAUTH_HTTP_GET_CMD - it defaults to \fCcurl \-sA 'liboauth-agent/0.1' '%u'\fP where %u is replaced with the URL and query parameters. +.PP +bash & wget example: \fCexport OAUTH_HTTP_CMD='wget \-q \-U 'liboauth-agent/0.1' '%u' '\fP +.PP +WARNING: this is a tentative function. it's convenient and handy for testing or developing OAuth code. But don't rely on this function to become a stable part of this API. It does not do much error checking or handling for one thing.. +.PP +NOTE: \fIu\fP and \fIq\fP are just concatenated with a '?' in between, unless \fIq\fP is NULL. in which case only \fIu\fP will be used. +.PP +\fBParameters:\fP +.RS 4 +\fIu\fP base url to get +.br +\fIq\fP query string to send along with the HTTP request or NULL. +.RE +.PP +\fBReturns:\fP +.RS 4 +In case of an error NULL is returned; otherwise a pointer to the replied content from HTTP server. latter needs to be freed by caller. +.RE +.PP + +.PP +\fBExamples: \fP +.in +1c +\fBtests/oauthexample.c\fP, and \fBtests/oauthtest.c\fP. +.SS "char* oauth_http_get2 (const char * u, const char * q, const char * customheader)" +.PP +do a HTTP GET request, wait for it to finish and return the content of the reply. (requires libcurl) +.PP +This is equivalent to /ref oauth_http_get but allows to specifiy a custom HTTP header and has has no support for commandline-curl. +.PP +If liboauth is compiled \fBwithout\fP libcurl this function always returns NULL. +.PP +\fBParameters:\fP +.RS 4 +\fIu\fP base url to get +.br +\fIq\fP query string to send along with the HTTP request or NULL. +.br +\fIcustomheader\fP specify custom HTTP header (or NULL for none) Multiple header elements can be passed separating them with '\\r\\n' +.RE +.PP +\fBReturns:\fP +.RS 4 +In case of an error NULL is returned; otherwise a pointer to the replied content from HTTP server. latter needs to be freed by caller. +.RE +.PP + +.PP +\fBExamples: \fP +.in +1c +\fBtests/oauthtest2.c\fP. +.SS "char* oauth_http_post (const char * u, const char * p)" +.PP +do a HTTP POST request, wait for it to finish and return the content of the reply. (requires libcurl or a command-line HTTP client) +.PP +If compiled \fBwithout\fP libcurl this function calls a command-line executable defined in the environment variable OAUTH_HTTP_CMD - it defaults to \fCcurl \-sA 'liboauth-agent/0.1' \-d '%p' '%u'\fP where %p is replaced with the postargs and %u is replaced with the URL. +.PP +bash & wget example: \fCexport OAUTH_HTTP_CMD='wget \-q \-U 'liboauth-agent/0.1' \-\-post-data='%p' '%u' '\fP +.PP +NOTE: This function uses the curl's default HTTP-POST Content-Type: application/x-www-form-urlencoded which is the only option allowed by oauth core 1.0 spec. Experimental code can use the Environment variable to transmit custom HTTP headers or parameters. +.PP +WARNING: this is a tentative function. it's convenient and handy for testing or developing OAuth code. But don't rely on this function to become a stable part of this API. It does not do much error checking for one thing.. +.PP +\fBParameters:\fP +.RS 4 +\fIu\fP url to query +.br +\fIp\fP postargs to send along with the HTTP request. +.RE +.PP +\fBReturns:\fP +.RS 4 +replied content from HTTP server. needs to be freed by caller. +.RE +.PP + +.PP +\fBExamples: \fP +.in +1c +\fBtests/oauthexample.c\fP, and \fBtests/oauthtest.c\fP. +.SS "char* oauth_http_post2 (const char * u, const char * p, const char * customheader)" +.PP +do a HTTP POST request, wait for it to finish and return the content of the reply. (requires libcurl) +.PP +It's equivalent to /ref oauth_http_post, but offers the possibility to specify a custom HTTP header and has no support for commandline-curl. +.PP +If liboauth is compiled \fBwithout\fP libcurl this function always returns NULL. +.PP +\fBParameters:\fP +.RS 4 +\fIu\fP url to query +.br +\fIp\fP postargs to send along with the HTTP request. +.br +\fIcustomheader\fP specify custom HTTP header (or NULL for none) Multiple header elements can be passed separating them with '\\r\\n' +.RE +.PP +\fBReturns:\fP +.RS 4 +replied content from HTTP server. needs to be freed by caller. +.RE +.PP + +.SS "int oauth_param_exists (char ** argv, int argc, char * key)" +.PP +search array for parameter key. \fBParameters:\fP +.RS 4 +\fIargv\fP length of array to search +.br +\fIargc\fP parameter array to search +.br +\fIkey\fP key of parameter to check. +.RE +.PP +\fBReturns:\fP +.RS 4 +FALSE (0) if array does not contain a parameter with given key, TRUE (1) otherwise. +.RE +.PP + +.SS "char* oauth_post_data (const char * u, const char * data, size_t len, const char * customheader)" +.PP +http post raw data the returned string needs to be freed by the caller (requires libcurl) see dislaimer: /ref oauth_http_post +.PP +\fBParameters:\fP +.RS 4 +\fIu\fP url to retrieve +.br +\fIdata\fP data to post +.br +\fIlen\fP length of the data in bytes. +.br +\fIcustomheader\fP specify custom HTTP header (or NULL for default) Multiple header elements can be passed separating them with '\\r\\n' +.RE +.PP +\fBReturns:\fP +.RS 4 +returned HTTP reply or NULL on error +.RE +.PP + +.PP +\fBExamples: \fP +.in +1c +\fBtests/oauthbodyhash.c\fP. +.SS "char* oauth_post_data_with_callback (const char * u, const char * data, size_t len, const char * customheader, void(*)(void *, int, size_t, size_t) callback, void * callback_data)" +.PP +http post raw data, with callback. the returned string needs to be freed by the caller (requires libcurl) +.PP +Invokes the callback - in no particular order - when HTTP-request status updates occur. The callback is called with: void * callback_data: supplied on function call. int type: 0=data received, 1=data sent. size_t size: amount of data received or amount of data sent so far size_t totalsize: original amount of data to send, or amount of data received +.PP +\fBParameters:\fP +.RS 4 +\fIu\fP url to retrieve +.br +\fIdata\fP data to post along +.br +\fIlen\fP length of the file in bytes. set to '0' for autodetection +.br +\fIcustomheader\fP specify custom HTTP header (or NULL for default) Multiple header elements can be passed separating them with '\\r\\n' +.br +\fIcallback\fP specify the callback function +.br +\fIcallback_data\fP specify data to pass to the callback function +.RE +.PP +\fBReturns:\fP +.RS 4 +returned HTTP reply or NULL on error +.RE +.PP + +.SS "char* oauth_post_file (const char * u, const char * fn, const size_t len, const char * customheader)" +.PP +http post raw data from file. the returned string needs to be freed by the caller (requires libcurl) +.PP +see dislaimer: /ref oauth_http_post +.PP +\fBParameters:\fP +.RS 4 +\fIu\fP url to retrieve +.br +\fIfn\fP filename of the file to post along +.br +\fIlen\fP length of the file in bytes. set to '0' for autodetection +.br +\fIcustomheader\fP specify custom HTTP header (or NULL for default). Multiple header elements can be passed separating them with '\\r\\n' +.RE +.PP +\fBReturns:\fP +.RS 4 +returned HTTP reply or NULL on error +.RE +.PP + +.SS "char* oauth_send_data (const char * u, const char * data, size_t len, const char * customheader, const char * httpMethod)" +.PP +http send raw data. similar to /ref oauth_http_post but provides for specifying the HTTP request method. +.PP +the returned string needs to be freed by the caller (requires libcurl) +.PP +see dislaimer: /ref oauth_http_post +.PP +\fBParameters:\fP +.RS 4 +\fIu\fP url to retrieve +.br +\fIdata\fP data to post +.br +\fIlen\fP length of the data in bytes. +.br +\fIcustomheader\fP specify custom HTTP header (or NULL for default) Multiple header elements can be passed separating them with '\\r\\n' +.br +\fIhttpMethod\fP specify http verb ('GET'/'POST'/'PUT'/'DELETE') to be used. if httpMethod is NULL, a POST is executed. +.RE +.PP +\fBReturns:\fP +.RS 4 +returned HTTP reply or NULL on error +.RE +.PP + +.SS "char* oauth_send_data_with_callback (const char * u, const char * data, size_t len, const char * customheader, void(*)(void *, int, size_t, size_t) callback, void * callback_data, const char * httpMethod)" +.PP +http post raw data, with callback. the returned string needs to be freed by the caller (requires libcurl) +.PP +Invokes the callback - in no particular order - when HTTP-request status updates occur. The callback is called with: void * callback_data: supplied on function call. int type: 0=data received, 1=data sent. size_t size: amount of data received or amount of data sent so far size_t totalsize: original amount of data to send, or amount of data received +.PP +\fBParameters:\fP +.RS 4 +\fIu\fP url to retrieve +.br +\fIdata\fP data to post along +.br +\fIlen\fP length of the file in bytes. set to '0' for autodetection +.br +\fIcustomheader\fP specify custom HTTP header (or NULL for default) Multiple header elements can be passed separating them with '\\r\\n' +.br +\fIcallback\fP specify the callback function +.br +\fIcallback_data\fP specify data to pass to the callback function +.br +\fIhttpMethod\fP specify http verb ('GET'/'POST'/'PUT'/'DELETE') to be used. +.RE +.PP +\fBReturns:\fP +.RS 4 +returned HTTP reply or NULL on error +.RE +.PP + +.SS "char* oauth_serialize_url (int argc, int start, char ** argv)" +.PP +build a url query string from an array. \fBParameters:\fP +.RS 4 +\fIargc\fP the total number of elements in the array +.br +\fIstart\fP element in the array at which to start concatenating. +.br +\fIargv\fP parameter-array to concatenate. +.RE +.PP +\fBReturns:\fP +.RS 4 +url string needs to be freed by the caller. +.RE +.PP + +.SS "char* oauth_serialize_url_parameters (int argc, char ** argv)" +.PP +build a query parameter string from an array. This function is a shortcut for \fBoauth_serialize_url\fP (argc, 1, argv). It strips the leading host/path, which is usually the first element when using oauth_split_url_parameters on an URL. +.PP +\fBParameters:\fP +.RS 4 +\fIargc\fP the total number of elements in the array +.br +\fIargv\fP parameter-array to concatenate. +.RE +.PP +\fBReturns:\fP +.RS 4 +url string needs to be freed by the caller. +.RE +.PP + +.SS "char* oauth_serialize_url_sep (int argc, int start, char ** argv, char * sep, int mod)" +.PP +encode query parameters from an array. \fBParameters:\fP +.RS 4 +\fIargc\fP the total number of elements in the array +.br +\fIstart\fP element in the array at which to start concatenating. +.br +\fIargv\fP parameter-array to concatenate. +.br +\fIsep\fP separator for parameters (usually '&') +.br +\fImod\fP - bitwise modifiers: 1: skip all values that start with 'oauth_' 2: skip all values that don't start with 'oauth_' 4: double quotation marks are added around values (use with sep ', ' for HTTP Authorization header). +.RE +.PP +\fBReturns:\fP +.RS 4 +url string needs to be freed by the caller. +.RE +.PP + +.PP +\fBExamples: \fP +.in +1c +\fBtests/oauthtest2.c\fP. +.SS "char* oauth_sign_array (int * argcp, char *** argvp, char ** postargs, \fBOAuthMethod\fP method, const char * c_key, const char * c_secret, const char * t_key, const char * t_secret)"\fBDeprecated\fP +.RS 4 +Use \fBoauth_sign_array2()\fP instead. +.RE +.PP + +.SS "char* oauth_sign_array2 (int * argcp, char *** argvp, char ** postargs, \fBOAuthMethod\fP method, const char * http_method, const char * c_key, const char * c_secret, const char * t_key, const char * t_secret)" +.PP +same as /ref oauth_sign_url with the url already split into parameter array \fBParameters:\fP +.RS 4 +\fIargcp\fP pointer to array length int +.br +\fIargvp\fP pointer to array values (argv[0]='http://example.org:80/' argv[1]='first=QueryParamater' .. the array is modified: fi. oauth_ parameters are added) These arrays can be generated with /ref oauth_split_url_parameters or /ref oauth_split_post_paramters. +.br +\fIpostargs\fP This parameter points to an area where the return value is stored. If 'postargs' is NULL, no value is stored. +.br +\fImethod\fP specify the signature method to use. It is of type \fBOAuthMethod\fP and most likely \fBOA_HMAC\fP. +.br +\fIhttp_method\fP The HTTP request method to use (ie 'GET', 'PUT',..) If NULL is given as 'http_method' this defaults to 'GET' when 'postargs' is also NULL and when postargs is not NULL 'POST' is used. +.br +\fIc_key\fP consumer key +.br +\fIc_secret\fP consumer secret +.br +\fIt_key\fP token key +.br +\fIt_secret\fP token secret +.RE +.PP +\fBReturns:\fP +.RS 4 +the signed url or NULL if an error occurred. +.RE +.PP + +.SS "void oauth_sign_array2_process (int * argcp, char *** argvp, char ** postargs, \fBOAuthMethod\fP method, const char * http_method, const char * c_key, const char * c_secret, const char * t_key, const char * t_secret)" +.PP +the back-end behind by /ref oauth_sign_array2. however it does not serialize the signed URL again. The user needs to call /ref oauth_serialize_url (oA) and /ref oauth_free_array to do so. +.PP +This allows to split parts of the URL to be used for OAuth HTTP Authorization header: see http://oauth.net/core/1.0a/#consumer_req_param the oauthtest2 example code does so. +.PP +\fBParameters:\fP +.RS 4 +\fIargcp\fP pointer to array length int +.br +\fIargvp\fP pointer to array values (argv[0]='http://example.org:80/' argv[1]='first=QueryParamater' .. the array is modified: fi. oauth_ parameters are added) These arrays can be generated with /ref oauth_split_url_parameters or /ref oauth_split_post_paramters. +.br +\fIpostargs\fP This parameter points to an area where the return value is stored. If 'postargs' is NULL, no value is stored. +.br +\fImethod\fP specify the signature method to use. It is of type \fBOAuthMethod\fP and most likely \fBOA_HMAC\fP. +.br +\fIhttp_method\fP The HTTP request method to use (ie 'GET', 'PUT',..) If NULL is given as 'http_method' this defaults to 'GET' when 'postargs' is also NULL and when postargs is not NULL 'POST' is used. +.br +\fIc_key\fP consumer key +.br +\fIc_secret\fP consumer secret +.br +\fIt_key\fP token key +.br +\fIt_secret\fP token secret +.RE +.PP +\fBReturns:\fP +.RS 4 +void +.RE +.PP + +.PP +\fBExamples: \fP +.in +1c +\fBtests/oauthtest2.c\fP. +.SS "char* oauth_sign_hmac_sha1 (const char * m, const char * k)" +.PP +returns base64 encoded HMAC-SHA1 signature for given message and key. both data and key need to be urlencoded. +.PP +the returned string needs to be freed by the caller +.PP +\fBParameters:\fP +.RS 4 +\fIm\fP message to be signed +.br +\fIk\fP key used for signing +.RE +.PP +\fBReturns:\fP +.RS 4 +signature string. +.RE +.PP + +.PP +\fBExamples: \fP +.in +1c +\fBtests/selftest_wiki.c\fP. +.SS "char* oauth_sign_hmac_sha1_raw (const char * m, const size_t ml, const char * k, const size_t kl)" +.PP +same as \fBoauth_sign_hmac_sha1\fP but allows to specify length of message and key (in case they contain null chars). \fBParameters:\fP +.RS 4 +\fIm\fP message to be signed +.br +\fIml\fP length of message +.br +\fIk\fP key used for signing +.br +\fIkl\fP length of key +.RE +.PP +\fBReturns:\fP +.RS 4 +signature string. +.RE +.PP + +.SS "char* oauth_sign_plaintext (const char * m, const char * k)" +.PP +returns plaintext signature for the given key. the returned string needs to be freed by the caller +.PP +\fBParameters:\fP +.RS 4 +\fIm\fP message to be signed +.br +\fIk\fP key used for signing +.RE +.PP +\fBReturns:\fP +.RS 4 +signature string +.RE +.PP + +.SS "char* oauth_sign_rsa_sha1 (const char * m, const char * k)" +.PP +returns RSA-SHA1 signature for given data. the returned signature needs to be freed by the caller. +.PP +\fBParameters:\fP +.RS 4 +\fIm\fP message to be signed +.br +\fIk\fP private-key PKCS and Base64-encoded +.RE +.PP +\fBReturns:\fP +.RS 4 +base64 encoded signature string. +.RE +.PP + +.PP +\fBExamples: \fP +.in +1c +\fBtests/selftest_wiki.c\fP. +.SS "char* oauth_sign_url (const char * url, char ** postargs, \fBOAuthMethod\fP method, const char * c_key, const char * c_secret, const char * t_key, const char * t_secret)"\fBDeprecated\fP +.RS 4 +Use \fBoauth_sign_url2()\fP instead. +.RE +.PP + +.SS "char* oauth_sign_url2 (const char * url, char ** postargs, \fBOAuthMethod\fP method, const char * http_method, const char * c_key, const char * c_secret, const char * t_key, const char * t_secret)" +.PP +calculate OAuth-signature for a given HTTP request URL, parameters and oauth-tokens. if 'postargs' is NULL a 'GET' request is signed and the signed URL is returned. Else this fn will modify 'postargs' to point to memory that contains the signed POST-variables and returns the base URL. +.PP +both, the return value and (if given) 'postargs' need to be freed by the caller. +.PP +\fBParameters:\fP +.RS 4 +\fIurl\fP The request URL to be signed. append all GET or POST query-parameters separated by either '?' or '&' to this parameter. +.br +\fIpostargs\fP This parameter points to an area where the return value is stored. If 'postargs' is NULL, no value is stored. +.br +\fImethod\fP specify the signature method to use. It is of type \fBOAuthMethod\fP and most likely \fBOA_HMAC\fP. +.br +\fIhttp_method\fP The HTTP request method to use (ie 'GET', 'PUT',..) If NULL is given as 'http_method' this defaults to 'GET' when 'postargs' is also NULL and when postargs is not NULL 'POST' is used. +.br +\fIc_key\fP consumer key +.br +\fIc_secret\fP consumer secret +.br +\fIt_key\fP token key +.br +\fIt_secret\fP token secret +.RE +.PP +\fBReturns:\fP +.RS 4 +the signed url or NULL if an error occurred. +.RE +.PP + +.PP +\fBExamples: \fP +.in +1c +\fBtests/oauthbodyhash.c\fP, \fBtests/oauthexample.c\fP, and \fBtests/oauthtest.c\fP. +.SS "char* oauth_sign_xmpp (const char * xml, \fBOAuthMethod\fP method, const char * c_secret, const char * t_secret)" +.PP +xep-0235 - TODO +.SS "int oauth_split_post_paramters (const char * url, char *** argv, short qesc)" +.PP +splits the given url into a parameter array. (see \fBoauth_serialize_url\fP and \fBoauth_serialize_url_parameters\fP for the reverse) +.PP +\fBParameters:\fP +.RS 4 +\fIurl\fP the url or query-string to parse. +.br +\fIargv\fP pointer to a (char *) array where the results are stored. The array is re-allocated to match the number of parameters and each parameter-string is allocated with strdup. - The memory needs to be freed by the caller. +.br +\fIqesc\fP use query parameter escape (vs post-param-escape) - if set to 1 all '+' are treated as spaces ' ' +.RE +.PP +\fBReturns:\fP +.RS 4 +number of parameter(s) in array. +.RE +.PP + +.SS "int oauth_split_url_parameters (const char * url, char *** argv)" +.PP +splits the given url into a parameter array. (see \fBoauth_serialize_url\fP and \fBoauth_serialize_url_parameters\fP for the reverse) (see \fBoauth_split_post_paramters\fP for a more generic version) +.PP +\fBParameters:\fP +.RS 4 +\fIurl\fP the url or query-string to parse; may be NULL +.br +\fIargv\fP pointer to a (char *) array where the results are stored. The array is re-allocated to match the number of parameters and each parameter-string is allocated with strdup. - The memory needs to be freed by the caller. +.RE +.PP +\fBReturns:\fP +.RS 4 +number of parameter(s) in array. +.RE +.PP + +.PP +\fBExamples: \fP +.in +1c +\fBtests/oauthexample.c\fP, \fBtests/oauthtest.c\fP, and \fBtests/oauthtest2.c\fP. +.SS "int oauth_time_independent_equals (const char * a, const char * b)" +.PP +compare two strings in constant-time. wrapper to \fBoauth_time_independent_equals_n\fP which calls strlen() for each argument. +.PP +\fBParameters:\fP +.RS 4 +\fIa\fP string to compare +.br +\fIb\fP string to compare +.RE +.PP +returns 0 (false) if strings are not equal, and 1 (true) if strings are equal. +.SS "int oauth_time_independent_equals_n (const char * a, const char * b, size_t len_a, size_t len_b)" +.PP +compare two strings in constant-time (as to not let an attacker guess how many leading chars are correct: http://rdist.root.org/2010/01/07/timing-independent-array-comparison/ ) \fBParameters:\fP +.RS 4 +\fIa\fP string to compare +.br +\fIb\fP string to compare +.br +\fIlen_a\fP length of string a +.br +\fIlen_b\fP length of string b +.RE +.PP +returns 0 (false) if strings are not equal, and 1 (true) if strings are equal. +.SS "int oauth_time_indepenent_equals (const char * a, const char * b)"\fBDeprecated\fP +.RS 4 +Use \fBoauth_time_independent_equals()\fP instead. +.RE +.PP + +.SS "int oauth_time_indepenent_equals_n (const char * a, const char * b, size_t len_a, size_t len_b)"\fBDeprecated\fP +.RS 4 +Use \fBoauth_time_independent_equals_n()\fP instead. +.RE +.PP + +.SS "char* oauth_url_escape (const char * string)" +.PP +Escape 'string' according to RFC3986 and http://oauth.net/core/1.0/#encoding_parameters. \fBParameters:\fP +.RS 4 +\fIstring\fP The data to be encoded +.RE +.PP +\fBReturns:\fP +.RS 4 +encoded string otherwise NULL The caller must free the returned string. +.RE +.PP + +.SS "char* oauth_url_unescape (const char * string, size_t * olen)" +.PP +Parse RFC3986 encoded 'string' back to unescaped version. \fBParameters:\fP +.RS 4 +\fIstring\fP The data to be unescaped +.br +\fIolen\fP unless NULL the length of the returned string is stored there. +.RE +.PP +\fBReturns:\fP +.RS 4 +decoded string or NULL The caller must free the returned string. +.RE +.PP + +.SS "int oauth_verify_rsa_sha1 (const char * m, const char * c, const char * s)" +.PP +verify RSA-SHA1 signature. returns the output of EVP_VerifyFinal() for a given message, cert/pubkey and signature. +.PP +\fBParameters:\fP +.RS 4 +\fIm\fP message to be verified +.br +\fIc\fP public-key or x509 certificate +.br +\fIs\fP base64 encoded signature +.RE +.PP +\fBReturns:\fP +.RS 4 +1 for a correct signature, 0 for failure and \-1 if some other error occurred +.RE +.PP + +.PP +\fBExamples: \fP +.in +1c +\fBtests/selftest_wiki.c\fP. +.SH "Author" +.PP +Generated automatically by Doxygen for OAuth library functions from the source code. diff --git a/protocols/Twitter/oauth/liboauth.lsm.in b/protocols/Twitter/oauth/liboauth.lsm.in new file mode 100644 index 0000000000..7cb1f7d786 --- /dev/null +++ b/protocols/Twitter/oauth/liboauth.lsm.in @@ -0,0 +1,19 @@ +Begin3 +Title: liboauth +Version: @VERSION@ +Entered-date: @ISODATE@ +Description: OAuth - secure authentication for web applications + @configure_input@ + liboauth implements request signing and url escape functions + according to the OAuth standard. see http://oauth.net/ +Keywords: OAuth +Author: robin@gareus.org (Robin Gareus) +Maintained-by: robin@gareus.org (Robin Gareus) +Primary-site: liboauth.sf.net /pool/ + 384k liboauth-@VERSION@.tar.gz + 500 liboauth.lsm +Alternate-site: +Original-site: +Platforms: +Copying-policy: GNU copyleft +End diff --git a/protocols/Twitter/oauth/oauth.pc.in b/protocols/Twitter/oauth/oauth.pc.in new file mode 100644 index 0000000000..a7fb8ad62e --- /dev/null +++ b/protocols/Twitter/oauth/oauth.pc.in @@ -0,0 +1,12 @@ +prefix=@prefix@ +exec_prefix=@exec_prefix@ +libdir=@libdir@ +includedir=@includedir@ + +Name: oauth +Description: OAuth - server to server secure API authentication +Requires.private: @PC_REQ@ +Version: @VERSION@ +Libs: -L${libdir} -loauth +Libs.private: -lm @PC_LIB@ +Cflags: -I${includedir} diff --git a/protocols/Twitter/oauth/src/Makefile.am b/protocols/Twitter/oauth/src/Makefile.am new file mode 100644 index 0000000000..b59c7c71df --- /dev/null +++ b/protocols/Twitter/oauth/src/Makefile.am @@ -0,0 +1,8 @@ +ACLOCAL_AMFLAGS= -I m4 +lib_LTLIBRARIES = liboauth.la +include_HEADERS = oauth.h + +liboauth_la_SOURCES=oauth.c config.h hash.c xmalloc.c xmalloc.h oauth_http.c +liboauth_la_LDFLAGS=@LIBOAUTH_LDFLAGS@ -version-info @VERSION_INFO@ +liboauth_la_LIBADD=@HASH_LIBS@ @CURL_LIBS@ +liboauth_la_CFLAGS=@LIBOAUTH_CFLAGS@ @HASH_CFLAGS@ @CURL_CFLAGS@ diff --git a/protocols/Twitter/oauth/src/hash.c b/protocols/Twitter/oauth/src/hash.c new file mode 100644 index 0000000000..ca00adaa8c --- /dev/null +++ b/protocols/Twitter/oauth/src/hash.c @@ -0,0 +1,492 @@ +/* + * hash algorithms used in OAuth + * + * Copyright 2007-2010 Robin Gareus <robin@gareus.org> + * + * 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. + * + */ + +#if HAVE_CONFIG_H +# include <config.h> +#endif + +#if USE_BUILTIN_HASH // built-in / AVR -- TODO: check license of sha1.c +#include <stdio.h> +#include "oauth.h" // oauth_encode_base64 +#include "xmalloc.h" + +#include "sha1.c" // TODO: sha1.h ; Makefile.am: add sha1.c + +/* API */ +char *oauth_sign_hmac_sha1_raw (const char *m, const size_t ml, const char *k, const size_t kl) { + sha1nfo s; + sha1_initHmac(&s, (const uint8_t*) k, kl); + sha1_write(&s, m, ml); + unsigned char *digest = sha1_resultHmac(&s); + return oauth_encode_base64(HASH_LENGTH, digest); +} + +char *oauth_sign_hmac_sha1 (const char *m, const char *k) { + return(oauth_sign_hmac_sha1_raw (m, strlen(m), k, strlen(k))); +} + +char *oauth_body_hash_file(char *filename) { + FILE *F= fopen(filename, "r"); + if (!F) return NULL; + + size_t len=0; + char fb[BUFSIZ]; + sha1nfo s; + sha1_init(&s); + + while (!feof(F) && (len=fread(fb,sizeof(char),BUFSIZ, F))>0) { + sha1_write(&s, fb, len); + } + fclose(F); + + unsigned char *dgst = xmalloc(HASH_LENGTH*sizeof(char)); // oauth_body_hash_encode frees the digest.. + memcpy(dgst, sha1_result(&s), HASH_LENGTH); + return oauth_body_hash_encode(HASH_LENGTH, dgst); +} + +char *oauth_body_hash_data(size_t length, const char *data) { + sha1nfo s; + sha1_init(&s); + for (;length--;) sha1_writebyte(&s, *data++); + + unsigned char *dgst = xmalloc(HASH_LENGTH*sizeof(char)); // oauth_body_hash_encode frees the digest.. + memcpy(dgst, sha1_result(&s), HASH_LENGTH); + return oauth_body_hash_encode(HASH_LENGTH, dgst); +} + +char *oauth_sign_rsa_sha1 (const char *m, const char *k) { + /* NOT RSA/PK11 support */ + return xstrdup("---RSA/PK11-is-not-supported-by-this-version-of-liboauth---"); +} + +int oauth_verify_rsa_sha1 (const char *m, const char *c, const char *sig) { + /* NOT RSA/PK11 support */ + return -1; // mismatch , error +} + +#elif defined (USE_NSS) +/* use http://www.mozilla.org/projects/security/pki/nss/ for hash/sign */ + +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include "xmalloc.h" +#include "oauth.h" // oauth base64 encode fn's. + +// NSS includes +#include "pk11pub.h" +#include "nss.h" +#include "base64.h" +#include "keyhi.h" +#include "cryptohi.h" +#include "cert.h" + +#if 1 // work-around compiler-warning + // see http://bugzilla.mozilla.org/show_bug.cgi?id=243245#c3 + extern CERTCertificate * + __CERT_DecodeDERCertificate (SECItem *derSignedCert, PRBool copyDER, char *nickname); +#endif + +static const char NS_CERT_HEADER[] = "-----BEGIN CERTIFICATE-----"; +static const char NS_CERT_TRAILER[] = "-----END CERTIFICATE-----"; +static const char NS_PRIV_HEADER[] = "-----BEGIN PRIVATE KEY-----"; +static const char NS_PRIV_TRAILER[] = "-----END PRIVATE KEY-----"; + +void oauth_init_nss() { + static short nss_initialized = 0; + if (!nss_initialized) { NSS_NoDB_Init("."); nss_initialized=1;} +} + +/** + * Removes heading & trailing strings; used only internally. + * similar to NSS-source/nss/lib/pkcs7/certread.c + * + * the returned string (if not NULL) needs to be freed by the caller + */ +char *oauth_strip_pkcs(const char *txt, const char *h, const char *t) { + char *start, *end, *rv; + size_t len; + if ((start=strstr(txt, h))==NULL) return NULL; + start+=strlen(h); + while (*start=='\r' || *start=='\n') start++; + if ((end=strstr(start, t))==NULL) return NULL; + end--; + while (*end=='\r' || *end=='\n') end--; + len = end-start+2; + rv = xmalloc(len*sizeof(char)); + memcpy(rv,start,len); + rv[len-1]='\0'; + return rv; +} + +char *oauth_sign_hmac_sha1 (const char *m, const char *k) { + return(oauth_sign_hmac_sha1_raw (m, strlen(m), k, strlen(k))); +} + +char *oauth_sign_hmac_sha1_raw (const char *m, const size_t ml, const char *k, const size_t kl) { + PK11SlotInfo *slot = NULL; + PK11SymKey *pkey = NULL; + PK11Context *context = NULL; + unsigned char digest[20]; // Is there a way to tell how large the output is? + unsigned int len; + SECStatus s; + SECItem keyItem, noParams; + char *rv=NULL; + + keyItem.type = siBuffer; + keyItem.data = (unsigned char*) k; + keyItem.len = kl; + + noParams.type = siBuffer; + noParams.data = NULL; + noParams.len = 0; + + oauth_init_nss(); + + slot = PK11_GetInternalKeySlot(); + if (!slot) goto looser; + pkey = PK11_ImportSymKey(slot, CKM_SHA_1_HMAC, PK11_OriginUnwrap, CKA_SIGN, &keyItem, NULL); + if (!pkey) goto looser; + context = PK11_CreateContextBySymKey(CKM_SHA_1_HMAC, CKA_SIGN, pkey, &noParams); + if (!context) goto looser; + + s = PK11_DigestBegin(context); + if (s != SECSuccess) goto looser; + s = PK11_DigestOp(context, (unsigned char*) m, ml); + if (s != SECSuccess) goto looser; + s = PK11_DigestFinal(context, digest, &len, sizeof digest); + if (s != SECSuccess) goto looser; + + rv=oauth_encode_base64(len, digest); + +looser: + if (context) PK11_DestroyContext(context, PR_TRUE); + if (pkey) PK11_FreeSymKey(pkey); + if (slot) PK11_FreeSlot(slot); + return rv; +} + +char *oauth_sign_rsa_sha1 (const char *m, const char *k) { + PK11SlotInfo *slot = NULL; + SECKEYPrivateKey *pkey = NULL; + SECItem signature; + SECStatus s; + SECItem der; + char *rv=NULL; + + char *key = oauth_strip_pkcs(k, NS_PRIV_HEADER, NS_PRIV_TRAILER); + if (!key) return NULL; + + oauth_init_nss(); + + slot = PK11_GetInternalKeySlot(); + if (!slot) goto looser; + s = ATOB_ConvertAsciiToItem(&der, key); + if (s != SECSuccess) goto looser; + s = PK11_ImportDERPrivateKeyInfoAndReturnKey(slot, &der, NULL, NULL, PR_FALSE, PR_TRUE, KU_ALL, &pkey, NULL); + SECITEM_FreeItem(&der, PR_FALSE); + if (s != SECSuccess) goto looser; + if (!pkey) goto looser; + if (pkey->keyType != rsaKey) goto looser; + s = SEC_SignData(&signature, (unsigned char*) m, strlen(m), pkey, SEC_OID_ISO_SHA1_WITH_RSA_SIGNATURE); + if (s != SECSuccess) goto looser; + + rv=oauth_encode_base64(signature.len, signature.data); + SECITEM_FreeItem(&signature, PR_FALSE); + +looser: + if (pkey) SECKEY_DestroyPrivateKey(pkey); + if (slot) PK11_FreeSlot(slot); + free(key); + return rv; +} + +int oauth_verify_rsa_sha1 (const char *m, const char *c, const char *sig) { + PK11SlotInfo *slot = NULL; + SECKEYPublicKey *pkey = NULL; + CERTCertificate *cert = NULL; + SECItem signature; + SECStatus s; + SECItem der; + int rv=0; + + char *key = oauth_strip_pkcs(c, NS_CERT_HEADER, NS_CERT_TRAILER); + if (!key) return 0; + + oauth_init_nss(); + + s = ATOB_ConvertAsciiToItem(&signature, (char*) sig); // XXX cast (const char*) -> (char*) + if (s != SECSuccess) goto looser; + slot = PK11_GetInternalKeySlot(); + if (!slot) goto looser; + s = ATOB_ConvertAsciiToItem(&der, key); + if (s != SECSuccess) goto looser; + cert = __CERT_DecodeDERCertificate(&der, PR_TRUE, NULL); + SECITEM_FreeItem(&der, PR_FALSE); + if (!cert) goto looser; + pkey = CERT_ExtractPublicKey(cert); + if (!pkey) goto looser; + if (pkey->keyType != rsaKey) goto looser; + + s = VFY_VerifyData((unsigned char*) m, strlen(m), pkey, &signature, SEC_OID_ISO_SHA1_WITH_RSA_SIGNATURE, NULL); + if (s == SECSuccess) rv=1; +#if 0 + else if (PR_GetError()!= SEC_ERROR_BAD_SIGNATURE) rv=-1; +#endif + +looser: + if (pkey) SECKEY_DestroyPublicKey(pkey); + if (slot) PK11_FreeSlot(slot); + free(key); + return rv; +} + +char *oauth_body_hash_file(char *filename) { + PK11SlotInfo *slot = NULL; + PK11Context *context = NULL; + unsigned char digest[20]; // Is there a way to tell how large the output is? + unsigned int len; + SECStatus s; + char *rv=NULL; + size_t bl; + unsigned char fb[BUFSIZ]; + + FILE *F= fopen(filename, "r"); + if (!F) return NULL; + + oauth_init_nss(); + + slot = PK11_GetInternalKeySlot(); + if (!slot) goto looser; + context = PK11_CreateDigestContext(SEC_OID_SHA1); + if (!context) goto looser; + + s = PK11_DigestBegin(context); + if (s != SECSuccess) goto looser; + while (!feof(F) && (bl=fread(fb,sizeof(char),BUFSIZ, F))>0) { + s = PK11_DigestOp(context, (unsigned char*) fb, bl); + if (s != SECSuccess) goto looser; + } + s = PK11_DigestFinal(context, digest, &len, sizeof digest); + if (s != SECSuccess) goto looser; + + unsigned char *dgst = xmalloc(len*sizeof(char)); // oauth_body_hash_encode frees the digest.. + memcpy(dgst, digest, len); + rv=oauth_body_hash_encode(len, dgst); + +looser: + fclose(F); + if (context) PK11_DestroyContext(context, PR_TRUE); + if (slot) PK11_FreeSlot(slot); + return rv; +} + +char *oauth_body_hash_data(size_t length, const char *data) { + PK11SlotInfo *slot = NULL; + PK11Context *context = NULL; + unsigned char digest[20]; // Is there a way to tell how large the output is? + unsigned int len; + SECStatus s; + char *rv=NULL; + + oauth_init_nss(); + + slot = PK11_GetInternalKeySlot(); + if (!slot) goto looser; + context = PK11_CreateDigestContext(SEC_OID_SHA1); + if (!context) goto looser; + + s = PK11_DigestBegin(context); + if (s != SECSuccess) goto looser; + s = PK11_DigestOp(context, (unsigned char*) data, length); + if (s != SECSuccess) goto looser; + s = PK11_DigestFinal(context, digest, &len, sizeof digest); + if (s != SECSuccess) goto looser; + + unsigned char *dgst = xmalloc(len*sizeof(char)); // oauth_body_hash_encode frees the digest.. + memcpy(dgst, digest, len); + rv=oauth_body_hash_encode(len, dgst); + +looser: + if (context) PK11_DestroyContext(context, PR_TRUE); + if (slot) PK11_FreeSlot(slot); + return rv; +} + +#else +/* use http://www.openssl.org/ for hash/sign */ + +#ifdef _GNU_SOURCE +/* + * In addition, as a special exception, the copyright holders give + * permission to link the code of portions of this program with the + * OpenSSL library under certain conditions as described in each + * individual source file, and distribute linked combinations + * including the two. + * You must obey the GNU General Public License in all respects + * for all of the code used other than OpenSSL. If you modify + * file(s) with this exception, you may extend this exception to your + * version of the file(s), but you are not obligated to do so. If you + * do not wish to do so, delete this exception statement from your + * version. If you delete this exception statement from all source + * files in the program, then also delete it here. + */ +#endif + +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include "xmalloc.h" +#include "oauth.h" // base64 encode fn's. +#include <openssl/hmac.h> + +char *oauth_sign_hmac_sha1 (const char *m, const char *k) { + return(oauth_sign_hmac_sha1_raw (m, strlen(m), k, strlen(k))); +} + +char *oauth_sign_hmac_sha1_raw (const char *m, const size_t ml, const char *k, const size_t kl) { + unsigned char result[EVP_MAX_MD_SIZE]; + unsigned int resultlen = 0; + + HMAC(EVP_sha1(), k, kl, + (unsigned char*) m, ml, + result, &resultlen); + + return(oauth_encode_base64(resultlen, result)); +} + +#include <openssl/evp.h> +#include <openssl/x509.h> +#include <openssl/x509v3.h> +#include <openssl/ssl.h> + +char *oauth_sign_rsa_sha1 (const char *m, const char *k) { + unsigned char *sig = NULL; + unsigned char *passphrase = NULL; + unsigned int len=0; + EVP_MD_CTX md_ctx; + + EVP_PKEY *pkey; + BIO *in; + in = BIO_new_mem_buf((unsigned char*) k, strlen(k)); + pkey = PEM_read_bio_PrivateKey(in, NULL, 0, passphrase); // generate sign + BIO_free(in); + + if (pkey == NULL) { + //fprintf(stderr, "liboauth/OpenSSL: can not read private key\n"); + return xstrdup("liboauth/OpenSSL: can not read private key"); + } + + len = EVP_PKEY_size(pkey); + sig = (unsigned char*)xmalloc((len+1)*sizeof(char)); + + EVP_SignInit(&md_ctx, EVP_sha1()); + EVP_SignUpdate(&md_ctx, m, strlen(m)); + if (EVP_SignFinal (&md_ctx, sig, &len, pkey)) { + char *tmp; + sig[len] = '\0'; + tmp = oauth_encode_base64(len,sig); + OPENSSL_free(sig); + EVP_PKEY_free(pkey); + return tmp; + } + return xstrdup("liboauth/OpenSSL: rsa-sha1 signing failed"); +} + +int oauth_verify_rsa_sha1 (const char *m, const char *c, const char *s) { + EVP_MD_CTX md_ctx; + EVP_PKEY *pkey; + BIO *in; + X509 *cert = NULL; + unsigned char *b64d; + int slen, err; + + in = BIO_new_mem_buf((unsigned char*)c, strlen(c)); + cert = PEM_read_bio_X509(in, NULL, 0, NULL); + if (cert) { + pkey = (EVP_PKEY *) X509_get_pubkey(cert); + X509_free(cert); + } else { + pkey = PEM_read_bio_PUBKEY(in, NULL, 0, NULL); + } + BIO_free(in); + if (pkey == NULL) { + //fprintf(stderr, "could not read cert/pubkey.\n"); + return -2; + } + + b64d= (unsigned char*) xmalloc(sizeof(char)*strlen(s)); + slen = oauth_decode_base64(b64d, s); + + EVP_VerifyInit(&md_ctx, EVP_sha1()); + EVP_VerifyUpdate(&md_ctx, m, strlen(m)); + err = EVP_VerifyFinal(&md_ctx, b64d, slen, pkey); + EVP_MD_CTX_cleanup(&md_ctx); + EVP_PKEY_free(pkey); + free(b64d); + return (err); +} + + +/** + * http://oauth.googlecode.com/svn/spec/ext/body_hash/1.0/oauth-bodyhash.html + */ +char *oauth_body_hash_file(char *filename) { + unsigned char fb[BUFSIZ]; + EVP_MD_CTX ctx; + size_t len=0; + unsigned char *md; + FILE *F= fopen(filename, "r"); + if (!F) return NULL; + + EVP_MD_CTX_init(&ctx); + EVP_DigestInit(&ctx,EVP_sha1()); + while (!feof(F) && (len=fread(fb,sizeof(char),BUFSIZ, F))>0) { + EVP_DigestUpdate(&ctx, fb, len); + } + fclose(F); + len=0; + md=(unsigned char*) xcalloc(EVP_MD_size(EVP_sha1()),sizeof(unsigned char)); + EVP_DigestFinal(&ctx, md,(unsigned int*) &len); + EVP_MD_CTX_cleanup(&ctx); + return oauth_body_hash_encode(len, md); +} + +char *oauth_body_hash_data(size_t length, const char *data) { + EVP_MD_CTX ctx; + size_t len=0; + unsigned char *md; + md=(unsigned char*) xcalloc(EVP_MD_size(EVP_sha1()),sizeof(unsigned char)); + EVP_MD_CTX_init(&ctx); + EVP_DigestInit(&ctx,EVP_sha1()); + EVP_DigestUpdate(&ctx, data, length); + EVP_DigestFinal(&ctx, md,(unsigned int*) &len); + EVP_MD_CTX_cleanup(&ctx); + return oauth_body_hash_encode(len, md); +} + +#endif + +// vi: sts=2 sw=2 ts=2 diff --git a/protocols/Twitter/oauth/src/oauth.c b/protocols/Twitter/oauth/src/oauth.c new file mode 100644 index 0000000000..0f205572dd --- /dev/null +++ b/protocols/Twitter/oauth/src/oauth.c @@ -0,0 +1,921 @@ +/* + * OAuth string functions in POSIX-C. + * + * Copyright 2007-2011 Robin Gareus <robin@gareus.org> + * + * The base64 functions are by Jan-Henrik Haukeland, <hauk@tildeslash.com> + * and un/escape_url() was inspired by libcurl's curl_escape under ISC-license + * many thanks to Daniel Stenberg <daniel@haxx.se>. + * + * 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. + * + */ +#if HAVE_CONFIG_H +# include <config.h> +#endif + +#define WIPE_MEMORY ///< overwrite sensitve data before free()ing it. + +#include <stdio.h> +#include <stdarg.h> +#include <stdlib.h> +#include <string.h> +#include <time.h> +#include <math.h> +#include <ctype.h> // isxdigit + +#include "xmalloc.h" +#include "oauth.h" + +#ifndef WIN32 // getpid() on POSIX systems +#include <sys/types.h> +#include <unistd.h> +#else +#define snprintf _snprintf +#define strncasecmp strnicmp +#endif + +/** + * Base64 encode one byte + */ +char oauth_b64_encode(unsigned char u) { + if(u < 26) return 'A'+u; + if(u < 52) return 'a'+(u-26); + if(u < 62) return '0'+(u-52); + if(u == 62) return '+'; + return '/'; +} + +/** + * Decode a single base64 character. + */ +unsigned char oauth_b64_decode(char c) { + if(c >= 'A' && c <= 'Z') return(c - 'A'); + if(c >= 'a' && c <= 'z') return(c - 'a' + 26); + if(c >= '0' && c <= '9') return(c - '0' + 52); + if(c == '+') return 62; + return 63; +} + +/** + * Return TRUE if 'c' is a valid base64 character, otherwise FALSE + */ +int oauth_b64_is_base64(char c) { + if((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || + (c >= '0' && c <= '9') || (c == '+') || + (c == '/') || (c == '=')) { + return 1; + } + return 0; +} + +/** + * Base64 encode and return size data in 'src'. The caller must free the + * returned string. + * + * @param size The size of the data in src + * @param src The data to be base64 encode + * @return encoded string otherwise NULL + */ +char *oauth_encode_base64(int size, const unsigned char *src) { + int i; + char *out, *p; + + if(!src) return NULL; + if(!size) size= strlen((char *)src); + out= (char*) xcalloc(sizeof(char), size*4/3+4); + p= out; + + for(i=0; i<size; i+=3) { + unsigned char b1=0, b2=0, b3=0, b4=0, b5=0, b6=0, b7=0; + b1= src[i]; + if(i+1<size) b2= src[i+1]; + if(i+2<size) b3= src[i+2]; + + b4= b1>>2; + b5= ((b1&0x3)<<4)|(b2>>4); + b6= ((b2&0xf)<<2)|(b3>>6); + b7= b3&0x3f; + + *p++= oauth_b64_encode(b4); + *p++= oauth_b64_encode(b5); + + if(i+1<size) *p++= oauth_b64_encode(b6); + else *p++= '='; + + if(i+2<size) *p++= oauth_b64_encode(b7); + else *p++= '='; + } + return out; +} + +/** + * Decode the base64 encoded string 'src' into the memory pointed to by + * 'dest'. + * + * @param dest Pointer to memory for holding the decoded string. + * Must be large enough to receive the decoded string. + * @param src A base64 encoded string. + * @return the length of the decoded string if decode + * succeeded otherwise 0. + */ +int oauth_decode_base64(unsigned char *dest, const char *src) { + if(src && *src) { + unsigned char *p= dest; + int k, l= strlen(src)+1; + unsigned char *buf= (unsigned char*) xcalloc(sizeof(unsigned char), l); + + /* Ignore non base64 chars as per the POSIX standard */ + for(k=0, l=0; src[k]; k++) { + if(oauth_b64_is_base64(src[k])) { + buf[l++]= src[k]; + } + } + + for(k=0; k<l; k+=4) { + char c1='A', c2='A', c3='A', c4='A'; + unsigned char b1=0, b2=0, b3=0, b4=0; + c1= buf[k]; + + if(k+1<l) c2= buf[k+1]; + if(k+2<l) c3= buf[k+2]; + if(k+3<l) c4= buf[k+3]; + + b1= oauth_b64_decode(c1); + b2= oauth_b64_decode(c2); + b3= oauth_b64_decode(c3); + b4= oauth_b64_decode(c4); + + *p++=((b1<<2)|(b2>>4) ); + + if(c3 != '=') *p++=(((b2&0xf)<<4)|(b3>>2) ); + if(c4 != '=') *p++=(((b3&0x3)<<6)|b4 ); + } + free(buf); + dest[p-dest]='\0'; + return(p-dest); + } + return 0; +} + +/** + * Escape 'string' according to RFC3986 and + * http://oauth.net/core/1.0/#encoding_parameters. + * + * @param string The data to be encoded + * @return encoded string otherwise NULL + * The caller must free the returned string. + */ +char *oauth_url_escape(const char *string) { + size_t alloc, newlen; + char *ns = NULL, *testing_ptr = NULL; + unsigned char in; + size_t strindex=0; + size_t length; + + if (!string) return xstrdup(""); + + alloc = strlen(string)+1; + newlen = alloc; + + ns = (char*) xmalloc(alloc); + + length = alloc-1; + while(length--) { + in = *string; + + switch(in){ + case '0': case '1': case '2': case '3': case '4': + case '5': case '6': case '7': case '8': case '9': + case 'a': case 'b': case 'c': case 'd': case 'e': + case 'f': case 'g': case 'h': case 'i': case 'j': + case 'k': case 'l': case 'm': case 'n': case 'o': + case 'p': case 'q': case 'r': case 's': case 't': + case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': + case 'A': case 'B': case 'C': case 'D': case 'E': + case 'F': case 'G': case 'H': case 'I': case 'J': + case 'K': case 'L': case 'M': case 'N': case 'O': + case 'P': case 'Q': case 'R': case 'S': case 'T': + case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': + case '_': case '~': case '.': case '-': + ns[strindex++]=in; + break; + default: + newlen += 2; /* this'll become a %XX */ + if(newlen > alloc) { + alloc *= 2; + testing_ptr = (char*) xrealloc(ns, alloc); + ns = testing_ptr; + } + snprintf(&ns[strindex], 4, "%%%02X", in); + strindex+=3; + break; + } + string++; + } + ns[strindex]=0; + return ns; +} + +#ifndef ISXDIGIT +# define ISXDIGIT(x) (isxdigit((int) ((unsigned char)x))) +#endif + +/** + * Parse RFC3986 encoded 'string' back to unescaped version. + * + * @param string The data to be unescaped + * @param olen unless NULL the length of the returned string is stored there. + * @return decoded string or NULL + * The caller must free the returned string. + */ +char *oauth_url_unescape(const char *string, size_t *olen) { + size_t alloc, strindex=0; + char *ns = NULL; + unsigned char in; + long hex; + + if (!string) return NULL; + alloc = strlen(string)+1; + ns = (char*) xmalloc(alloc); + + while(--alloc > 0) { + in = *string; + if(('%' == in) && ISXDIGIT(string[1]) && ISXDIGIT(string[2])) { + char hexstr[3]; // '%XX' + hexstr[0] = string[1]; + hexstr[1] = string[2]; + hexstr[2] = 0; + hex = strtol(hexstr, NULL, 16); + in = (unsigned char)hex; /* hex is always < 256 */ + string+=2; + alloc-=2; + } + ns[strindex++] = in; + string++; + } + ns[strindex]=0; + if(olen) *olen = strindex; + return ns; +} + +/** + * returns plaintext signature for the given key. + * + * the returned string needs to be freed by the caller + * + * @param m message to be signed + * @param k key used for signing + * @return signature string + */ +char *oauth_sign_plaintext (const char *m, const char *k) { + return(oauth_url_escape(k)); +} + +/** + * encode strings and concatenate with '&' separator. + * The number of strings to be concatenated must be + * given as first argument. + * all arguments thereafter must be of type (char *) + * + * @param len the number of arguments to follow this parameter + * @param ... string to escape and added (may be NULL) + * + * @return pointer to memory holding the concatenated + * strings - needs to be free(d) by the caller. or NULL + * in case we ran out of memory. + */ +char *oauth_catenc(int len, ...) { + va_list va; + int i; + char *rv = (char*) xmalloc(sizeof(char)); + *rv='\0'; + va_start(va, len); + for(i=0;i<len;i++) { + char *arg = va_arg(va, char *); + char *enc; + int len; + enc = oauth_url_escape(arg); + if(!enc) break; + len = strlen(enc) + 1 + ((i>0)?1:0); + if(rv) len+=strlen(rv); + rv=(char*) xrealloc(rv,len*sizeof(char)); + + if(i>0) strcat(rv, "&"); + strcat(rv, enc); + free(enc); + } + va_end(va); + return(rv); +} + +/** + * splits the given url into a parameter array. + * (see \ref oauth_serialize_url and \ref oauth_serialize_url_parameters for the reverse) + * + * NOTE: Request-parameters-values may include an ampersand character. + * However if unescaped this function will use them as parameter delimiter. + * If you need to make such a request, this function since version 0.3.5 allows + * to use the ASCII SOH (0x01) character as alias for '&' (0x26). + * (the motivation is convenience: SOH is /untypeable/ and much more + * unlikely to appear than '&' - If you plan to sign fancy URLs you + * should not split a query-string, but rather provide the parameter array + * directly to \ref oauth_serialize_url) + * + * @param url the url or query-string to parse. + * @param argv pointer to a (char *) array where the results are stored. + * The array is re-allocated to match the number of parameters and each + * parameter-string is allocated with strdup. - The memory needs to be freed + * by the caller. + * @param qesc use query parameter escape (vs post-param-escape) - if set + * to 1 all '+' are treated as spaces ' ' + * + * @return number of parameter(s) in array. + */ +int oauth_split_post_paramters(const char *url, char ***argv, short qesc) { + int argc=0; + char *token, *tmp, *t1; + if (!argv) return 0; + if (!url) return 0; + t1=xstrdup(url); + + // '+' represents a space, in a URL query string + while ((qesc&1) && (tmp=strchr(t1,'+'))) *tmp=' '; + + tmp=t1; + while((token=strtok(tmp,"&?"))) { + if(!strncasecmp("oauth_signature=",token,16)) continue; + (*argv)=(char**) xrealloc(*argv,sizeof(char*)*(argc+1)); + while (!(qesc&2) && (tmp=strchr(token,'\001'))) *tmp='&'; + if (argc>0 || (qesc&4)) + (*argv)[argc]=oauth_url_unescape(token, NULL); + else + (*argv)[argc]=xstrdup(token); + if (argc==0 && strstr(token, ":/")) { + // HTTP does not allow empty absolute paths, so the URL + // 'http://example.com' is equivalent to 'http://example.com/' and should + // be treated as such for the purposes of OAuth signing (rfc2616, section 3.2.1) + // see http://groups.google.com/group/oauth/browse_thread/thread/c44b6f061bfd98c?hl=en + char *slash=strstr(token, ":/"); + while (slash && *(++slash) == '/') ; // skip slashes eg /xxx:[\/]*/ +#if 0 + // skip possibly unescaped slashes in the userinfo - they're not allowed by RFC2396 but have been seen. + // the hostname/IP may only contain alphanumeric characters - so we're safe there. + if (slash && strchr(slash,'@')) slash=strchr(slash,'@'); +#endif + if (slash && !strchr(slash,'/')) { +#ifdef DEBUG_OAUTH + fprintf(stderr, "\nliboauth: added trailing slash to URL: '%s'\n\n", token); +#endif + free((*argv)[argc]); + (*argv)[argc]= (char*) xmalloc(sizeof(char)*(2+strlen(token))); + strcpy((*argv)[argc],token); + strcat((*argv)[argc],"/"); + } + } + if (argc==0 && (tmp=strstr((*argv)[argc],":80/"))) { + memmove(tmp, tmp+3, strlen(tmp+2)); + } + tmp=NULL; + argc++; + } + + free(t1); + return argc; +} + +int oauth_split_url_parameters(const char *url, char ***argv) { + return oauth_split_post_paramters(url, argv, 1); +} + +/** + * build a url query string from an array. + * + * @param argc the total number of elements in the array + * @param start element in the array at which to start concatenating. + * @param argv parameter-array to concatenate. + * @return url string needs to be freed by the caller. + * + */ +char *oauth_serialize_url (int argc, int start, char **argv) { + return oauth_serialize_url_sep( argc, start, argv, "&", 0); +} + +/** + * encode query parameters from an array. + * + * @param argc the total number of elements in the array + * @param start element in the array at which to start concatenating. + * @param argv parameter-array to concatenate. + * @param sep separator for parameters (usually "&") + * @param mod - bitwise modifiers: + * 1: skip all values that start with "oauth_" + * 2: skip all values that don't start with "oauth_" + * 4: add double quotation marks around values (use with sep=", " to generate HTTP Authorization header). + * @return url string needs to be freed by the caller. + */ +char *oauth_serialize_url_sep (int argc, int start, char **argv, char *sep, int mod) { + char *tmp, *t1; + int i; + int first=1; + int seplen=strlen(sep); + char *query = (char*) xmalloc(sizeof(char)); + *query='\0'; + for(i=start; i< argc; i++) { + int len = 0; + if ((mod&1)==1 && (strncmp(argv[i],"oauth_",6) == 0 || strncmp(argv[i],"x_oauth_",8) == 0) ) continue; + if ((mod&2)==2 && (strncmp(argv[i],"oauth_",6) != 0 && strncmp(argv[i],"x_oauth_",8) != 0) && i!=0) continue; + + if (query) len+=strlen(query); + + if (i==start && i==0 && strstr(argv[i], ":/")) { + tmp=xstrdup(argv[i]); +#if 1 // encode white-space in the base-url + while ((t1=strchr(tmp,' '))) { +# if 0 + *t1='+'; +# else + size_t off = t1-tmp; + char *t2 = (char*) xmalloc(sizeof(char)*(3+strlen(tmp))); + strcpy(t2, tmp); + strcpy(t2+off+2, tmp+off); + *(t2+off)='%'; *(t2+off+1)='2'; *(t2+off+2)='0'; + free(tmp); + tmp=t2; +# endif +#endif + } + len+=strlen(tmp); + } else if(!(t1=strchr(argv[i], '='))) { + // see http://oauth.net/core/1.0/#anchor14 + // escape parameter names and arguments but not the '=' + tmp=xstrdup(argv[i]); + tmp=(char*) xrealloc(tmp,(strlen(tmp)+2)*sizeof(char)); + strcat(tmp,"="); + len+=strlen(tmp); + } else { + *t1=0; + tmp = oauth_url_escape(argv[i]); + *t1='='; + t1 = oauth_url_escape((t1+1)); + tmp=(char*) xrealloc(tmp,(strlen(tmp)+strlen(t1)+2+(mod&4?2:0))*sizeof(char)); + strcat(tmp,"="); + if (mod&4) strcat(tmp,"\""); + strcat(tmp,t1); + if (mod&4) strcat(tmp,"\""); + free(t1); + len+=strlen(tmp); + } + len+=seplen+1; + query=(char*) xrealloc(query,len*sizeof(char)); + strcat(query, ((i==start||first)?"":sep)); + first=0; + strcat(query, tmp); + if (i==start && i==0 && strstr(tmp, ":/")) { + strcat(query, "?"); + first=1; + } + free(tmp); + } + return (query); +} + +/** + * build a query parameter string from an array. + * + * This function is a shortcut for \ref oauth_serialize_url (argc, 1, argv). + * It strips the leading host/path, which is usually the first + * element when using oauth_split_url_parameters on an URL. + * + * @param argc the total number of elements in the array + * @param argv parameter-array to concatenate. + * @return url string needs to be freed by the caller. + */ +char *oauth_serialize_url_parameters (int argc, char **argv) { + return oauth_serialize_url(argc, 1, argv); +} + +/** + * generate a random string between 15 and 32 chars length + * and return a pointer to it. The value needs to be freed by the + * caller + * + * @return zero terminated random string. + */ +#if !defined HAVE_OPENSSL_HMAC_H && !defined USE_NSS +/* pre liboauth-0.7.2 and possible future versions that don't use OpenSSL or NSS */ +char *oauth_gen_nonce() { + char *nc; + static int rndinit = 1; + const char *chars = "abcdefghijklmnopqrstuvwxyz" + "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "0123456789_"; + unsigned int max = strlen( chars ); + int i, len; + + if(rndinit) {srand(time(NULL) +#ifndef WIN32 // quick windows check. + * getpid() +#endif + ); rndinit=0;} // seed random number generator - FIXME: we can do better ;) + + len=15+floor(rand()*16.0/(double)RAND_MAX); + nc = (char*) xmalloc((len+1)*sizeof(char)); + for(i=0;i<len; i++) { + nc[i] = chars[ rand() % max ]; + } + nc[i]='\0'; + return (nc); +} +#else // OpenSSL or NSS random number generator +#ifdef USE_NSS + void oauth_init_nss(); //decladed in hash.c +# include "pk11pub.h" +# define MY_RAND PK11_GenerateRandom +# define MY_SRAND oauth_init_nss(); +#else +# ifdef _GNU_SOURCE +/* Note: the OpenSSL/GPL exemption stated + * verbosely in hash.c applies to this code as well. */ +# endif +# include <openssl/rand.h> +# define MY_RAND RAND_bytes +# define MY_SRAND ; +#endif +char *oauth_gen_nonce() { + char *nc; + unsigned char buf; + const char *chars = "abcdefghijklmnopqrstuvwxyz" + "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "0123456789_"; + unsigned int max = strlen(chars); + int i, len; + + MY_SRAND + MY_RAND(&buf, 1); + len=15+(((short)buf)&0x0f); + nc = (char*) xmalloc((len+1)*sizeof(char)); + for(i=0;i<len; i++) { + MY_RAND(&buf, 1); + nc[i] = chars[ ((short)buf) % max ]; + } + nc[i]='\0'; + return (nc); +} +#endif + +/** + * string compare function for oauth parameters. + * + * used with qsort. needed to normalize request parameters. + * see http://oauth.net/core/1.0/#anchor14 + */ +int oauth_cmpstringp(const void *p1, const void *p2) { + char *v1,*v2; + char *t1,*t2; + int rv; + // TODO: this is not fast - we should escape the + // array elements (once) before sorting. + v1=oauth_url_escape(* (char * const *)p1); + v2=oauth_url_escape(* (char * const *)p2); + + // '=' signs are not "%3D" ! + if ((t1=strstr(v1,"%3D"))) { + t1[0]='\0'; t1[1]='='; t1[2]='='; + } + if ((t2=strstr(v2,"%3D"))) { + t2[0]='\0'; t2[1]='='; t2[2]='='; + } + + // compare parameter names + rv=strcmp(v1,v2); + if (rv!=0) { + if (v1) free(v1); + if (v2) free(v2); + return rv; + } + + // if parameter names are equal, sort by value. + if (t1) t1[0]='='; + if (t2) t2[0]='='; + if (t1 && t2) rv=strcmp(t1,t2); + else if (!t1 && !t2) rv=0; + else if (!t1) rv=-1; + else rv=1; + + if (v1) free(v1); + if (v2) free(v2); + return rv; +} + +/** + * search array for parameter key. + * @param argv length of array to search + * @param argc parameter array to search + * @param key key of parameter to check. + * + * @return FALSE (0) if array does not contain a parameter with given key, TRUE (1) otherwise. + */ +int oauth_param_exists(char **argv, int argc, char *key) { + int i; + size_t l= strlen(key); + for (i=0;i<argc;i++) + if (strlen(argv[i])>l && !strncmp(argv[i],key,l) && argv[i][l] == '=') return 1; + return 0; +} + +/** + * add query parameter to array + * + * @param argcp pointer to array length int + * @param argvp pointer to array values + * @param addparam parameter to add (eg. "foo=bar") + */ +void oauth_add_param_to_array(int *argcp, char ***argvp, const char *addparam) { + (*argvp)=(char**) xrealloc(*argvp,sizeof(char*)*((*argcp)+1)); + (*argvp)[(*argcp)++]= (char*) xstrdup(addparam); +} + +/** + * + */ +void oauth_add_protocol(int *argcp, char ***argvp, + OAuthMethod method, + const char *c_key, //< consumer key - posted plain text + const char *t_key //< token key - posted plain text in URL + ){ + char oarg[1024]; + + // add OAuth specific arguments + if (!oauth_param_exists(*argvp,*argcp,"oauth_nonce")) { + char *tmp; + snprintf(oarg, 1024, "oauth_nonce=%s", (tmp=oauth_gen_nonce())); + oauth_add_param_to_array(argcp, argvp, oarg); + free(tmp); + } + + if (!oauth_param_exists(*argvp,*argcp,"oauth_timestamp")) { + snprintf(oarg, 1024, "oauth_timestamp=%li", (long int) time(NULL)); + oauth_add_param_to_array(argcp, argvp, oarg); + } + + if (t_key) { + snprintf(oarg, 1024, "oauth_token=%s", t_key); + oauth_add_param_to_array(argcp, argvp, oarg); + } + + snprintf(oarg, 1024, "oauth_consumer_key=%s", c_key); + oauth_add_param_to_array(argcp, argvp, oarg); + + snprintf(oarg, 1024, "oauth_signature_method=%s", + method==0?"HMAC-SHA1":method==1?"RSA-SHA1":"PLAINTEXT"); + oauth_add_param_to_array(argcp, argvp, oarg); + + if (!oauth_param_exists(*argvp,*argcp,"oauth_version")) { + snprintf(oarg, 1024, "oauth_version=1.0"); + oauth_add_param_to_array(argcp, argvp, oarg); + } + +#if 0 // oauth_version 1.0 Rev A + if (!oauth_param_exists(argv,argc,"oauth_callback")) { + snprintf(oarg, 1024, "oauth_callback=oob"); + oauth_add_param_to_array(argcp, argvp, oarg); + } +#endif + +} + +char *oauth_sign_url (const char *url, char **postargs, + OAuthMethod method, + const char *c_key, //< consumer key - posted plain text + const char *c_secret, //< consumer secret - used as 1st part of secret-key + const char *t_key, //< token key - posted plain text in URL + const char *t_secret //< token secret - used as 2st part of secret-key + ) { + return oauth_sign_url2(url, postargs, + method, NULL, + c_key, c_secret, + t_key, t_secret); +} + +char *oauth_sign_url2 (const char *url, char **postargs, + OAuthMethod method, + const char *http_method, //< HTTP request method + const char *c_key, //< consumer key - posted plain text + const char *c_secret, //< consumer secret - used as 1st part of secret-key + const char *t_key, //< token key - posted plain text in URL + const char *t_secret //< token secret - used as 2st part of secret-key + ) { + int argc; + char **argv = NULL; + char *rv; + + if (postargs) + argc = oauth_split_post_paramters(url, &argv, 0); + else + argc = oauth_split_url_parameters(url, &argv); + + rv=oauth_sign_array2(&argc, &argv, postargs, + method, http_method, + c_key, c_secret, t_key, t_secret); + + oauth_free_array(&argc, &argv); + return(rv); +} + +char *oauth_sign_array (int *argcp, char***argvp, + char **postargs, + OAuthMethod method, + const char *c_key, //< consumer key - posted plain text + const char *c_secret, //< consumer secret - used as 1st part of secret-key + const char *t_key, //< token key - posted plain text in URL + const char *t_secret //< token secret - used as 2st part of secret-key + ) { + return oauth_sign_array2 (argcp, argvp, + postargs, method, + NULL, + c_key, c_secret, + t_key, t_secret); +} + +void oauth_sign_array2_process (int *argcp, char***argvp, + char **postargs, + OAuthMethod method, + const char *http_method, //< HTTP request method + const char *c_key, //< consumer key - posted plain text + const char *c_secret, //< consumer secret - used as 1st part of secret-key + const char *t_key, //< token key - posted plain text in URL + const char *t_secret //< token secret - used as 2st part of secret-key + ) { + char oarg[1024]; + char *query; + char *okey, *odat, *sign; + char *http_request_method; + + if (!http_method) { + http_request_method = xstrdup(postargs?"POST":"GET"); + } else { + int i; + http_request_method = xstrdup(http_method); + for (i=0;i<strlen(http_request_method);i++) + http_request_method[i]=toupper(http_request_method[i]); + } + + // add required OAuth protocol parameters + oauth_add_protocol(argcp, argvp, method, c_key, t_key); + + // sort parameters + qsort(&(*argvp)[1], (*argcp)-1, sizeof(char *), oauth_cmpstringp); + + // serialize URL - base-url + query= oauth_serialize_url_parameters(*argcp, *argvp); + + // generate signature + okey = oauth_catenc(2, c_secret, t_secret); + odat = oauth_catenc(3, http_request_method, (*argvp)[0], query); // base-string + free(http_request_method); +#ifdef DEBUG_OAUTH + fprintf (stderr, "\nliboauth: data to sign='%s'\n\n", odat); + fprintf (stderr, "\nliboauth: key='%s'\n\n", okey); +#endif + switch(method) { + case OA_RSA: + sign = oauth_sign_rsa_sha1(odat,okey); // XXX okey needs to be RSA key! + break; + case OA_PLAINTEXT: + sign = oauth_sign_plaintext(odat,okey); + break; + default: + sign = oauth_sign_hmac_sha1(odat,okey); + } +#ifdef WIPE_MEMORY + memset(okey,0, strlen(okey)); + memset(odat,0, strlen(odat)); +#endif + free(odat); + free(okey); + + // append signature to query args. + snprintf(oarg, 1024, "oauth_signature=%s",sign); + oauth_add_param_to_array(argcp, argvp, oarg); + free(sign); + if(query) free(query); +} + +char *oauth_sign_array2 (int *argcp, char***argvp, + char **postargs, + OAuthMethod method, + const char *http_method, //< HTTP request method + const char *c_key, //< consumer key - posted plain text + const char *c_secret, //< consumer secret - used as 1st part of secret-key + const char *t_key, //< token key - posted plain text in URL + const char *t_secret //< token secret - used as 2st part of secret-key + ) { + + char *result; + oauth_sign_array2_process(argcp, argvp, postargs, method, http_method, c_key, c_secret, t_key, t_secret); + + // build URL params + result = oauth_serialize_url(*argcp, (postargs?1:0), *argvp); + + if(postargs) { + *postargs = result; + result = xstrdup((*argvp)[0]); + } + + return result; +} + + +/** + * free array args + * + * @param argcp pointer to array length int + * @param argvp pointer to array values to be free()d + */ +void oauth_free_array(int *argcp, char ***argvp) { + int i; + for (i=0;i<(*argcp);i++) { + free((*argvp)[i]); + } + if(*argvp) free(*argvp); +} + +/** + * base64 encode digest, free it and return a URL parameter + * with the oauth_body_hash + */ +char *oauth_body_hash_encode(size_t len, unsigned char *digest) { + char *sign=oauth_encode_base64(len,digest); + char *sig_url = (char*)xmalloc(17+strlen(sign)); + sprintf(sig_url,"oauth_body_hash=%s", sign); + free(sign); + free(digest); + return sig_url; +} + + +/** + * compare two strings in constant-time (as to not let an + * attacker guess how many leading chars are correct: + * http://rdist.root.org/2010/01/07/timing-independent-array-comparison/ ) + * + * @param a string to compare + * @param b string to compare + * @param len_a length of string a + * @param len_b length of string b + * + * returns 0 (false) if strings are not equal, and 1 (true) if strings are equal. + */ +int oauth_time_independent_equals_n(const char* a, const char* b, size_t len_a, size_t len_b) { + int diff, i, j; + if (a == NULL) return (b == NULL); + else if (b == NULL) return 0; + else if (len_b == 0) return (len_a == 0); + diff = len_a ^ len_b; + j=0; + for (i=0; i<len_a; ++i) { + diff |= a[i] ^ b[j]; + j = (j+1) % len_b; + } + return diff == 0; +} +int oauth_time_indepenent_equals_n(const char* a, const char* b, size_t len_a, size_t len_b) { + return oauth_time_independent_equals_n(a, b, len_a, len_b); +} + +int oauth_time_independent_equals(const char* a, const char* b) { + return oauth_time_independent_equals_n (a, b, a?strlen(a):0, b?strlen(b):0); +} + +int oauth_time_indepenent_equals(const char* a, const char* b) { + return oauth_time_independent_equals_n (a, b, a?strlen(a):0, b?strlen(b):0); +} + +/** + * xep-0235 - TODO + */ +char *oauth_sign_xmpp (const char *xml, + OAuthMethod method, + const char *c_secret, //< consumer secret - used as 1st part of secret-key + const char *t_secret //< token secret - used as 2st part of secret-key + ) { + + return NULL; +} + +// vi: sts=2 sw=2 ts=2 diff --git a/protocols/Twitter/oauth/src/oauth.h b/protocols/Twitter/oauth/src/oauth.h new file mode 100644 index 0000000000..4efb472fc8 --- /dev/null +++ b/protocols/Twitter/oauth/src/oauth.h @@ -0,0 +1,764 @@ +/** + * @brief OAuth.net implementation in POSIX-C. + * @file oauth.h + * @author Robin Gareus <robin@gareus.org> + * + * Copyright 2007-2011 Robin Gareus <robin@gareus.org> + * + * 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 _OAUTH_H +#define _OAUTH_H 1 + +#ifndef DOXYGEN_IGNORE +// liboauth version +#define LIBOAUTH_VERSION "0.9.6" +#define LIBOAUTH_VERSION_MAJOR 0 +#define LIBOAUTH_VERSION_MINOR 9 +#define LIBOAUTH_VERSION_MICRO 6 + +//interface revision number +//http://www.gnu.org/software/libtool/manual/html_node/Updating-version-info.html +#define LIBOAUTH_CUR 8 +#define LIBOAUTH_REV 3 +#define LIBOAUTH_AGE 8 +#endif + +#ifdef __GNUC__ +# define OA_GCC_VERSION_AT_LEAST(x,y) (__GNUC__ > x || __GNUC__ == x && __GNUC_MINOR__ >= y) +#else +# define OA_GCC_VERSION_AT_LEAST(x,y) 0 +#endif + +#ifndef attribute_deprecated +#if OA_GCC_VERSION_AT_LEAST(3,1) +# define attribute_deprecated __attribute__((deprecated)) +#else +# define attribute_deprecated +#endif +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +/** \enum OAuthMethod + * signature method to used for signing the request. + */ +typedef enum { + OA_HMAC=0, ///< use HMAC-SHA1 request signing method + OA_RSA, ///< use RSA signature + OA_PLAINTEXT ///< use plain text signature (for testing only) + } OAuthMethod; + +/** + * Base64 encode and return size data in 'src'. The caller must free the + * returned string. + * + * @param size The size of the data in src + * @param src The data to be base64 encode + * @return encoded string otherwise NULL + */ +char *oauth_encode_base64(int size, const unsigned char *src); + +/** + * Decode the base64 encoded string 'src' into the memory pointed to by + * 'dest'. + * + * @param dest Pointer to memory for holding the decoded string. + * Must be large enough to receive the decoded string. + * @param src A base64 encoded string. + * @return the length of the decoded string if decode + * succeeded otherwise 0. + */ +int oauth_decode_base64(unsigned char *dest, const char *src); + +/** + * Escape 'string' according to RFC3986 and + * http://oauth.net/core/1.0/#encoding_parameters. + * + * @param string The data to be encoded + * @return encoded string otherwise NULL + * The caller must free the returned string. + */ +char *oauth_url_escape(const char *string); + +/** + * Parse RFC3986 encoded 'string' back to unescaped version. + * + * @param string The data to be unescaped + * @param olen unless NULL the length of the returned string is stored there. + * @return decoded string or NULL + * The caller must free the returned string. + */ +char *oauth_url_unescape(const char *string, size_t *olen); + + +/** + * returns base64 encoded HMAC-SHA1 signature for + * given message and key. + * both data and key need to be urlencoded. + * + * the returned string needs to be freed by the caller + * + * @param m message to be signed + * @param k key used for signing + * @return signature string. + */ +char *oauth_sign_hmac_sha1 (const char *m, const char *k); + +/** + * same as \ref oauth_sign_hmac_sha1 but allows + * to specify length of message and key (in case they contain null chars). + * + * @param m message to be signed + * @param ml length of message + * @param k key used for signing + * @param kl length of key + * @return signature string. + */ +char *oauth_sign_hmac_sha1_raw (const char *m, const size_t ml, const char *k, const size_t kl); + +/** + * returns plaintext signature for the given key. + * + * the returned string needs to be freed by the caller + * + * @param m message to be signed + * @param k key used for signing + * @return signature string + */ +char *oauth_sign_plaintext (const char *m, const char *k); + +/** + * returns RSA-SHA1 signature for given data. + * the returned signature needs to be freed by the caller. + * + * @param m message to be signed + * @param k private-key PKCS and Base64-encoded + * @return base64 encoded signature string. + */ +char *oauth_sign_rsa_sha1 (const char *m, const char *k); + +/** + * verify RSA-SHA1 signature. + * + * returns the output of EVP_VerifyFinal() for a given message, + * cert/pubkey and signature. + * + * @param m message to be verified + * @param c public-key or x509 certificate + * @param s base64 encoded signature + * @return 1 for a correct signature, 0 for failure and -1 if some other error occurred + */ +int oauth_verify_rsa_sha1 (const char *m, const char *c, const char *s); + +/** + * url-escape strings and concatenate with '&' separator. + * The number of strings to be concatenated must be + * given as first argument. + * all arguments thereafter must be of type (char *) + * + * @param len the number of arguments to follow this parameter + * + * @return pointer to memory holding the concatenated + * strings - needs to be free(d) by the caller. or NULL + * in case we ran out of memory. + */ +char *oauth_catenc(int len, ...); + +/** + * splits the given url into a parameter array. + * (see \ref oauth_serialize_url and \ref oauth_serialize_url_parameters for the reverse) + * (see \ref oauth_split_post_paramters for a more generic version) + * + * @param url the url or query-string to parse; may be NULL + * @param argv pointer to a (char *) array where the results are stored. + * The array is re-allocated to match the number of parameters and each + * parameter-string is allocated with strdup. - The memory needs to be freed + * by the caller. + * + * @return number of parameter(s) in array. + */ +int oauth_split_url_parameters(const char *url, char ***argv); + +/** + * splits the given url into a parameter array. + * (see \ref oauth_serialize_url and \ref oauth_serialize_url_parameters for the reverse) + * + * @param url the url or query-string to parse. + * @param argv pointer to a (char *) array where the results are stored. + * The array is re-allocated to match the number of parameters and each + * parameter-string is allocated with strdup. - The memory needs to be freed + * by the caller. + * @param qesc use query parameter escape (vs post-param-escape) - if set + * to 1 all '+' are treated as spaces ' ' + * + * @return number of parameter(s) in array. + */ +int oauth_split_post_paramters(const char *url, char ***argv, short qesc); + +/** + * build a url query string from an array. + * + * @param argc the total number of elements in the array + * @param start element in the array at which to start concatenating. + * @param argv parameter-array to concatenate. + * @return url string needs to be freed by the caller. + * + */ +char *oauth_serialize_url (int argc, int start, char **argv); + +/** + * encode query parameters from an array. + * + * @param argc the total number of elements in the array + * @param start element in the array at which to start concatenating. + * @param argv parameter-array to concatenate. + * @param sep separator for parameters (usually "&") + * @param mod - bitwise modifiers: + * 1: skip all values that start with "oauth_" + * 2: skip all values that don't start with "oauth_" + * 4: double quotation marks are added around values (use with sep ", " for HTTP Authorization header). + * @return url string needs to be freed by the caller. + */ +char *oauth_serialize_url_sep (int argc, int start, char **argv, char *sep, int mod); + +/** + * build a query parameter string from an array. + * + * This function is a shortcut for \ref oauth_serialize_url (argc, 1, argv). + * It strips the leading host/path, which is usually the first + * element when using oauth_split_url_parameters on an URL. + * + * @param argc the total number of elements in the array + * @param argv parameter-array to concatenate. + * @return url string needs to be freed by the caller. + */ +char *oauth_serialize_url_parameters (int argc, char **argv); + +/** + * generate a random string between 15 and 32 chars length + * and return a pointer to it. The value needs to be freed by the + * caller + * + * @return zero terminated random string. + */ +char *oauth_gen_nonce(); + +/** + * string compare function for oauth parameters. + * + * used with qsort. needed to normalize request parameters. + * see http://oauth.net/core/1.0/#anchor14 + */ +int oauth_cmpstringp(const void *p1, const void *p2); + + +/** + * search array for parameter key. + * @param argv length of array to search + * @param argc parameter array to search + * @param key key of parameter to check. + * + * @return FALSE (0) if array does not contain a parameter with given key, TRUE (1) otherwise. + */ +int oauth_param_exists(char **argv, int argc, char *key); + +/** + * add query parameter to array + * + * @param argcp pointer to array length int + * @param argvp pointer to array values + * @param addparam parameter to add (eg. "foo=bar") + */ +void oauth_add_param_to_array(int *argcp, char ***argvp, const char *addparam); + +/** + * free array args + * + * @param argcp pointer to array length int + * @param argvp pointer to array values to be free()d + */ +void oauth_free_array(int *argcp, char ***argvp); + +/** + * compare two strings in constant-time (as to not let an + * attacker guess how many leading chars are correct: + * http://rdist.root.org/2010/01/07/timing-independent-array-comparison/ ) + * + * @param a string to compare + * @param b string to compare + * @param len_a length of string a + * @param len_b length of string b + * + * returns 0 (false) if strings are not equal, and 1 (true) if strings are equal. + */ +int oauth_time_independent_equals_n(const char* a, const char* b, size_t len_a, size_t len_b); + +/** + * @deprecated Use oauth_time_independent_equals_n() instead. + */ +int oauth_time_indepenent_equals_n(const char* a, const char* b, size_t len_a, size_t len_b) attribute_deprecated; + +/** + * compare two strings in constant-time. + * wrapper to \ref oauth_time_independent_equals_n + * which calls strlen() for each argument. + * + * @param a string to compare + * @param b string to compare + * + * returns 0 (false) if strings are not equal, and 1 (true) if strings are equal. + */ +int oauth_time_independent_equals(const char* a, const char* b); + +/** + * @deprecated Use oauth_time_independent_equals() instead. + */ +int oauth_time_indepenent_equals(const char* a, const char* b) attribute_deprecated; + +/** + * calculate OAuth-signature for a given HTTP request URL, parameters and oauth-tokens. + * + * if 'postargs' is NULL a "GET" request is signed and the + * signed URL is returned. Else this fn will modify 'postargs' + * to point to memory that contains the signed POST-variables + * and returns the base URL. + * + * both, the return value and (if given) 'postargs' need to be freed + * by the caller. + * + * @param url The request URL to be signed. append all GET or POST + * query-parameters separated by either '?' or '&' to this parameter. + * + * @param postargs This parameter points to an area where the return value + * is stored. If 'postargs' is NULL, no value is stored. + * + * @param method specify the signature method to use. It is of type + * \ref OAuthMethod and most likely \ref OA_HMAC. + * + * @param http_method The HTTP request method to use (ie "GET", "PUT",..) + * If NULL is given as 'http_method' this defaults to "GET" when + * 'postargs' is also NULL and when postargs is not NULL "POST" is used. + * + * @param c_key consumer key + * @param c_secret consumer secret + * @param t_key token key + * @param t_secret token secret + * + * @return the signed url or NULL if an error occurred. + * + */ +char *oauth_sign_url2 (const char *url, char **postargs, + OAuthMethod method, + const char *http_method, //< HTTP request method + const char *c_key, //< consumer key - posted plain text + const char *c_secret, //< consumer secret - used as 1st part of secret-key + const char *t_key, //< token key - posted plain text in URL + const char *t_secret //< token secret - used as 2st part of secret-key + ); + +/** + * @deprecated Use oauth_sign_url2() instead. + */ +char *oauth_sign_url (const char *url, char **postargs, + OAuthMethod method, + const char *c_key, //< consumer key - posted plain text + const char *c_secret, //< consumer secret - used as 1st part of secret-key + const char *t_key, //< token key - posted plain text in URL + const char *t_secret //< token secret - used as 2st part of secret-key + ) attribute_deprecated; + + +/** + * the back-end behind by /ref oauth_sign_array2. + * however it does not serialize the signed URL again. + * The user needs to call /ref oauth_serialize_url (oA) + * and /ref oauth_free_array to do so. + * + * This allows to split parts of the URL to be used for + * OAuth HTTP Authorization header: + * see http://oauth.net/core/1.0a/#consumer_req_param + * the oauthtest2 example code does so. + * + * + * @param argcp pointer to array length int + * @param argvp pointer to array values + * (argv[0]="http://example.org:80/" argv[1]="first=QueryParamater" .. + * the array is modified: fi. oauth_ parameters are added) + * These arrays can be generated with /ref oauth_split_url_parameters + * or /ref oauth_split_post_paramters. + * + * @param postargs This parameter points to an area where the return value + * is stored. If 'postargs' is NULL, no value is stored. + * + * @param method specify the signature method to use. It is of type + * \ref OAuthMethod and most likely \ref OA_HMAC. + * + * @param http_method The HTTP request method to use (ie "GET", "PUT",..) + * If NULL is given as 'http_method' this defaults to "GET" when + * 'postargs' is also NULL and when postargs is not NULL "POST" is used. + * + * @param c_key consumer key + * @param c_secret consumer secret + * @param t_key token key + * @param t_secret token secret + * + * @return void + * + */ +void oauth_sign_array2_process (int *argcp, char***argvp, + char **postargs, + OAuthMethod method, + const char *http_method, //< HTTP request method + const char *c_key, //< consumer key - posted plain text + const char *c_secret, //< consumer secret - used as 1st part of secret-key + const char *t_key, //< token key - posted plain text in URL + const char *t_secret //< token secret - used as 2st part of secret-key + ); + +/** + * same as /ref oauth_sign_url + * with the url already split into parameter array + * + * @param argcp pointer to array length int + * @param argvp pointer to array values + * (argv[0]="http://example.org:80/" argv[1]="first=QueryParamater" .. + * the array is modified: fi. oauth_ parameters are added) + * These arrays can be generated with /ref oauth_split_url_parameters + * or /ref oauth_split_post_paramters. + * + * @param postargs This parameter points to an area where the return value + * is stored. If 'postargs' is NULL, no value is stored. + * + * @param method specify the signature method to use. It is of type + * \ref OAuthMethod and most likely \ref OA_HMAC. + * + * @param http_method The HTTP request method to use (ie "GET", "PUT",..) + * If NULL is given as 'http_method' this defaults to "GET" when + * 'postargs' is also NULL and when postargs is not NULL "POST" is used. + * + * @param c_key consumer key + * @param c_secret consumer secret + * @param t_key token key + * @param t_secret token secret + * + * @return the signed url or NULL if an error occurred. + */ +char *oauth_sign_array2 (int *argcp, char***argvp, + char **postargs, + OAuthMethod method, + const char *http_method, //< HTTP request method + const char *c_key, //< consumer key - posted plain text + const char *c_secret, //< consumer secret - used as 1st part of secret-key + const char *t_key, //< token key - posted plain text in URL + const char *t_secret //< token secret - used as 2st part of secret-key + ); + +/** + * @deprecated Use oauth_sign_array2() instead. + */ +char *oauth_sign_array (int *argcp, char***argvp, + char **postargs, + OAuthMethod method, + const char *c_key, //< consumer key - posted plain text + const char *c_secret, //< consumer secret - used as 1st part of secret-key + const char *t_key, //< token key - posted plain text in URL + const char *t_secret //< token secret - used as 2st part of secret-key + ) attribute_deprecated; + + +/** + * calculate body hash (sha1sum) of given file and return + * a oauth_body_hash=xxxx parameter to be added to the request. + * The returned string needs to be freed by the calling function. + * + * see + * http://oauth.googlecode.com/svn/spec/ext/body_hash/1.0/oauth-bodyhash.html + * + * @param filename the filename to calculate the hash for + * + * @return URL oauth_body_hash parameter string + */ +char *oauth_body_hash_file(char *filename); + +/** + * calculate body hash (sha1sum) of given data and return + * a oauth_body_hash=xxxx parameter to be added to the request. + * The returned string needs to be freed by the calling function. + * The returned string is not yet url-escaped and suitable to be + * passed as argument to \ref oauth_catenc. + * + * see + * http://oauth.googlecode.com/svn/spec/ext/body_hash/1.0/oauth-bodyhash.html + * + * @param length length of the data parameter in bytes + * @param data to calculate the hash for + * + * @return URL oauth_body_hash parameter string + */ +char *oauth_body_hash_data(size_t length, const char *data); + +/** + * base64 encode digest, free it and return a URL parameter + * with the oauth_body_hash. The returned hash needs to be freed by the + * calling function. The returned string is not yet url-escaped and + * thus suitable to be passed to \ref oauth_catenc. + * + * @param len length of the digest to encode + * @param digest hash value to encode + * + * @return URL oauth_body_hash parameter string + */ +char *oauth_body_hash_encode(size_t len, unsigned char *digest); + +/** + * xep-0235 - TODO + */ +char *oauth_sign_xmpp (const char *xml, + OAuthMethod method, + const char *c_secret, //< consumer secret - used as 1st part of secret-key + const char *t_secret //< token secret - used as 2st part of secret-key + ); + +/** + * do a HTTP GET request, wait for it to finish + * and return the content of the reply. + * (requires libcurl or a command-line HTTP client) + * + * If compiled <b>without</b> libcurl this function calls + * a command-line executable defined in the environment variable + * OAUTH_HTTP_GET_CMD - it defaults to + * <tt>curl -sA 'liboauth-agent/0.1' '%%u'</tt> + * where %%u is replaced with the URL and query parameters. + * + * bash & wget example: + * <tt>export OAUTH_HTTP_CMD="wget -q -U 'liboauth-agent/0.1' '%u' "</tt> + * + * WARNING: this is a tentative function. it's convenient and handy for testing + * or developing OAuth code. But don't rely on this function + * to become a stable part of this API. It does not do + * much error checking or handling for one thing.. + * + * NOTE: \a u and \a q are just concatenated with a '?' in between, + * unless \a q is NULL. in which case only \a u will be used. + * + * @param u base url to get + * @param q query string to send along with the HTTP request or NULL. + * @return In case of an error NULL is returned; otherwise a pointer to the + * replied content from HTTP server. latter needs to be freed by caller. + */ +char *oauth_http_get (const char *u, const char *q); + +/** + * do a HTTP GET request, wait for it to finish + * and return the content of the reply. + * + * (requires libcurl) + * + * This is equivalent to /ref oauth_http_get but allows to + * specifiy a custom HTTP header and has + * has no support for commandline-curl. + * + * If liboauth is compiled <b>without</b> libcurl this function + * always returns NULL. + * + * @param u base url to get + * @param q query string to send along with the HTTP request or NULL. + * @param customheader specify custom HTTP header (or NULL for none) + * Multiple header elements can be passed separating them with "\r\n" + * @return In case of an error NULL is returned; otherwise a pointer to the + * replied content from HTTP server. latter needs to be freed by caller. + */ +char *oauth_http_get2 (const char *u, const char *q, const char *customheader); + + +/** + * do a HTTP POST request, wait for it to finish + * and return the content of the reply. + * (requires libcurl or a command-line HTTP client) + * + * If compiled <b>without</b> libcurl this function calls + * a command-line executable defined in the environment variable + * OAUTH_HTTP_CMD - it defaults to + * <tt>curl -sA 'liboauth-agent/0.1' -d '%%p' '%%u'</tt> + * where %%p is replaced with the postargs and %%u is replaced with + * the URL. + * + * bash & wget example: + * <tt>export OAUTH_HTTP_CMD="wget -q -U 'liboauth-agent/0.1' --post-data='%p' '%u' "</tt> + * + * NOTE: This function uses the curl's default HTTP-POST Content-Type: + * application/x-www-form-urlencoded which is the only option allowed + * by oauth core 1.0 spec. Experimental code can use the Environment variable + * to transmit custom HTTP headers or parameters. + * + * WARNING: this is a tentative function. it's convenient and handy for testing + * or developing OAuth code. But don't rely on this function + * to become a stable part of this API. It does not do + * much error checking for one thing.. + * + * @param u url to query + * @param p postargs to send along with the HTTP request. + * @return replied content from HTTP server. needs to be freed by caller. + */ +char *oauth_http_post (const char *u, const char *p); + +/** + * do a HTTP POST request, wait for it to finish + * and return the content of the reply. + * (requires libcurl) + * + * It's equivalent to /ref oauth_http_post, but offers + * the possibility to specify a custom HTTP header and + * has no support for commandline-curl. + * + * If liboauth is compiled <b>without</b> libcurl this function + * always returns NULL. + * + * @param u url to query + * @param p postargs to send along with the HTTP request. + * @param customheader specify custom HTTP header (or NULL for none) + * Multiple header elements can be passed separating them with "\r\n" + * @return replied content from HTTP server. needs to be freed by caller. + */ +char *oauth_http_post2 (const char *u, const char *p, const char *customheader); + + +/** + * http post raw data from file. + * the returned string needs to be freed by the caller + * (requires libcurl) + * + * see dislaimer: /ref oauth_http_post + * + * @param u url to retrieve + * @param fn filename of the file to post along + * @param len length of the file in bytes. set to '0' for autodetection + * @param customheader specify custom HTTP header (or NULL for default). + * Multiple header elements can be passed separating them with "\r\n" + * @return returned HTTP reply or NULL on error + */ +char *oauth_post_file (const char *u, const char *fn, const size_t len, const char *customheader); + +/** + * http post raw data + * the returned string needs to be freed by the caller + * (requires libcurl) + * + * see dislaimer: /ref oauth_http_post + * + * @param u url to retrieve + * @param data data to post + * @param len length of the data in bytes. + * @param customheader specify custom HTTP header (or NULL for default) + * Multiple header elements can be passed separating them with "\r\n" + * @return returned HTTP reply or NULL on error + */ +char *oauth_post_data (const char *u, const char *data, size_t len, const char *customheader); + +/** + * http post raw data, with callback. + * the returned string needs to be freed by the caller + * (requires libcurl) + * + * Invokes the callback - in no particular order - when HTTP-request status updates occur. + * The callback is called with: + * void * callback_data: supplied on function call. + * int type: 0=data received, 1=data sent. + * size_t size: amount of data received or amount of data sent so far + * size_t totalsize: original amount of data to send, or amount of data received + * + * @param u url to retrieve + * @param data data to post along + * @param len length of the file in bytes. set to '0' for autodetection + * @param customheader specify custom HTTP header (or NULL for default) + * Multiple header elements can be passed separating them with "\r\n" + * @param callback specify the callback function + * @param callback_data specify data to pass to the callback function + * @return returned HTTP reply or NULL on error + */ +char *oauth_post_data_with_callback (const char *u, + const char *data, + size_t len, + const char *customheader, + void (*callback)(void*,int,size_t,size_t), + void *callback_data); + +/** + * http send raw data. similar to /ref oauth_http_post but provides + * for specifying the HTTP request method. + * + * the returned string needs to be freed by the caller + * (requires libcurl) + * + * see dislaimer: /ref oauth_http_post + * + * @param u url to retrieve + * @param data data to post + * @param len length of the data in bytes. + * @param customheader specify custom HTTP header (or NULL for default) + * Multiple header elements can be passed separating them with "\r\n" + * @param httpMethod specify http verb ("GET"/"POST"/"PUT"/"DELETE") to be used. if httpMethod is NULL, a POST is executed. + * @return returned HTTP reply or NULL on error + */ +char *oauth_send_data (const char *u, + const char *data, + size_t len, + const char *customheader, + const char *httpMethod); + +/** + * http post raw data, with callback. + * the returned string needs to be freed by the caller + * (requires libcurl) + * + * Invokes the callback - in no particular order - when HTTP-request status updates occur. + * The callback is called with: + * void * callback_data: supplied on function call. + * int type: 0=data received, 1=data sent. + * size_t size: amount of data received or amount of data sent so far + * size_t totalsize: original amount of data to send, or amount of data received + * + * @param u url to retrieve + * @param data data to post along + * @param len length of the file in bytes. set to '0' for autodetection + * @param customheader specify custom HTTP header (or NULL for default) + * Multiple header elements can be passed separating them with "\r\n" + * @param callback specify the callback function + * @param callback_data specify data to pass to the callback function + * @param httpMethod specify http verb ("GET"/"POST"/"PUT"/"DELETE") to be used. + * @return returned HTTP reply or NULL on error + */ +char *oauth_send_data_with_callback (const char *u, + const char *data, + size_t len, + const char *customheader, + void (*callback)(void*,int,size_t,size_t), + void *callback_data, + const char *httpMethod); + +#ifdef __cplusplus +} /* extern "C" */ +#endif /* __cplusplus */ + +#endif +/* vi:set ts=8 sts=2 sw=2: */ diff --git a/protocols/Twitter/oauth/src/oauth_http.c b/protocols/Twitter/oauth/src/oauth_http.c new file mode 100644 index 0000000000..0e06b10dae --- /dev/null +++ b/protocols/Twitter/oauth/src/oauth_http.c @@ -0,0 +1,728 @@ +/* + * OAuth http functions in POSIX-C. + * + * Copyright 2007, 2008, 2009, 2010 Robin Gareus <robin@gareus.org> + * + * 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. + * + */ +#if HAVE_CONFIG_H +# include <config.h> +#endif + +#include <stdio.h> +#include <stdarg.h> +#include <stdlib.h> +#include <string.h> + +#ifdef WIN32 +# define snprintf _snprintf +#endif + +#include "xmalloc.h" +#include "oauth.h" + +#define OAUTH_USER_AGENT "liboauth-agent/" VERSION + +#ifdef HAVE_CURL /* HTTP requests via libcurl */ +#include <curl/curl.h> +#include <sys/stat.h> + +# define GLOBAL_CURL_ENVIROMENT_OPTIONS \ + if (getenv("CURLOPT_PROXYAUTH")){ \ + curl_easy_setopt(curl, CURLOPT_PROXYAUTH, CURLAUTH_ANY); \ + } \ + if (getenv("CURLOPT_SSL_VERIFYPEER")){ \ + curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, (long) atol(getenv("CURLOPT_SSL_VERIFYPEER")) ); \ + } \ + if (getenv("CURLOPT_CAINFO")){ \ + curl_easy_setopt(curl, CURLOPT_CAINFO, getenv("CURLOPT_CAINFO") ); \ + } \ + if (getenv("CURLOPT_FOLLOWLOCATION")){ \ + curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, (long) atol(getenv("CURLOPT_FOLLOWLOCATION")) ); \ + } \ + if (getenv("CURLOPT_FAILONERROR")){ \ + curl_easy_setopt(curl, CURLOPT_FAILONERROR, (long) atol(getenv("CURLOPT_FAILONERROR")) ); \ + } + +struct MemoryStruct { + char *data; + size_t size; //< bytes remaining (r), bytes accumulated (w) + + size_t start_size; //< only used with ..AndCall() + void (*callback)(void*,int,size_t,size_t); //< only used with ..AndCall() + void *callback_data; //< only used with ..AndCall() +}; + +static size_t +WriteMemoryCallback(void *ptr, size_t size, size_t nmemb, void *data) { + size_t realsize = size * nmemb; + struct MemoryStruct *mem = (struct MemoryStruct *)data; + + mem->data = (char *)xrealloc(mem->data, mem->size + realsize + 1); + if (mem->data) { + memcpy(&(mem->data[mem->size]), ptr, realsize); + mem->size += realsize; + mem->data[mem->size] = 0; + } + return realsize; +} + +static size_t +ReadMemoryCallback(void *ptr, size_t size, size_t nmemb, void *data) { + struct MemoryStruct *mem = (struct MemoryStruct *)data; + size_t realsize = size * nmemb; + if (realsize > mem->size) realsize = mem->size; + memcpy(ptr, mem->data, realsize); + mem->size -= realsize; + mem->data += realsize; + return realsize; +} + +static size_t +WriteMemoryCallbackAndCall(void *ptr, size_t size, size_t nmemb, void *data) { + struct MemoryStruct *mem = (struct MemoryStruct *)data; + size_t ret=WriteMemoryCallback(ptr,size,nmemb,data); + mem->callback(mem->callback_data,0,mem->size,mem->size); + return ret; +} + +static size_t +ReadMemoryCallbackAndCall(void *ptr, size_t size, size_t nmemb, void *data) { + struct MemoryStruct *mem = (struct MemoryStruct *)data; + size_t ret=ReadMemoryCallback(ptr,size,nmemb,data); + mem->callback(mem->callback_data,1,mem->start_size-mem->size,mem->start_size); + return ret; +} + +/** + * cURL http post function. + * the returned string (if not NULL) needs to be freed by the caller + * + * @param u url to retrieve + * @param p post parameters + * @param customheader specify custom HTTP header (or NULL for none) + * @return returned HTTP + */ +char *oauth_curl_post (const char *u, const char *p, const char *customheader) { + CURL *curl; + CURLcode res; + struct curl_slist *slist=NULL; + + struct MemoryStruct chunk; + chunk.data=NULL; + chunk.size = 0; + + curl = curl_easy_init(); + if(!curl) return NULL; + curl_easy_setopt(curl, CURLOPT_URL, u); + curl_easy_setopt(curl, CURLOPT_POSTFIELDS, p); + curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&chunk); + curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteMemoryCallback); + if (customheader) { + slist = curl_slist_append(slist, customheader); + curl_easy_setopt(curl, CURLOPT_HTTPHEADER, slist); + } + curl_easy_setopt(curl, CURLOPT_USERAGENT, OAUTH_USER_AGENT); +#ifdef OAUTH_CURL_TIMEOUT + curl_easy_setopt(curl, CURLOPT_TIMEOUT, OAUTH_CURL_TIMEOUT); + curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1); +#endif + GLOBAL_CURL_ENVIROMENT_OPTIONS; + res = curl_easy_perform(curl); + curl_slist_free_all(slist); + if (res) { + return NULL; + } + + curl_easy_cleanup(curl); + return (chunk.data); +} + +/** + * cURL http get function. + * the returned string (if not NULL) needs to be freed by the caller + * + * @param u url to retrieve + * @param q optional query parameters + * @param customheader specify custom HTTP header (or NULL for none) + * @return returned HTTP + */ +char *oauth_curl_get (const char *u, const char *q, const char *customheader) { + CURL *curl; + CURLcode res; + struct curl_slist *slist=NULL; + char *t1=NULL; + struct MemoryStruct chunk; + + if (q) { + t1=(char*)xmalloc(sizeof(char)*(strlen(u)+strlen(q)+2)); + strcpy(t1,u); strcat(t1,"?"); strcat(t1,q); + } + + chunk.data=NULL; + chunk.size = 0; + + curl = curl_easy_init(); + if(!curl) return NULL; + curl_easy_setopt(curl, CURLOPT_URL, q?t1:u); + curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&chunk); + curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteMemoryCallback); + if (customheader) { + slist = curl_slist_append(slist, customheader); + curl_easy_setopt(curl, CURLOPT_HTTPHEADER, slist); + } +#if 0 // TODO - support request methods.. + if (0) + curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "HEAD"); + else if (0) + curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "DELETE"); +#endif + curl_easy_setopt(curl, CURLOPT_USERAGENT, OAUTH_USER_AGENT); +#ifdef OAUTH_CURL_TIMEOUT + curl_easy_setopt(curl, CURLOPT_TIMEOUT, OAUTH_CURL_TIMEOUT); + curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1); +#endif + GLOBAL_CURL_ENVIROMENT_OPTIONS; + res = curl_easy_perform(curl); + curl_slist_free_all(slist); + if (q) free(t1); + curl_easy_cleanup(curl); + + if (res) { + return NULL; + } + return (chunk.data); +} + +/** + * cURL http post raw data from file. + * the returned string needs to be freed by the caller + * + * @param u url to retrieve + * @param fn filename of the file to post along + * @param len length of the file in bytes. set to '0' for autodetection + * @param customheader specify custom HTTP header (or NULL for default) + * @return returned HTTP or NULL on error + */ +char *oauth_curl_post_file (const char *u, const char *fn, size_t len, const char *customheader) { + CURL *curl; + CURLcode res; + struct curl_slist *slist=NULL; + struct MemoryStruct chunk; + FILE *f; + + chunk.data=NULL; + chunk.size=0; + + if (customheader) + slist = curl_slist_append(slist, customheader); + else + slist = curl_slist_append(slist, "Content-Type: image/jpeg;"); + + if (!len) { + struct stat statbuf; + if (stat(fn, &statbuf) == -1) return(NULL); + len = statbuf.st_size; + } + + f = fopen(fn,"r"); + if (!f) return NULL; + + curl = curl_easy_init(); + if(!curl) return NULL; + curl_easy_setopt(curl, CURLOPT_URL, u); + curl_easy_setopt(curl, CURLOPT_POST, 1); + curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, len); + curl_easy_setopt(curl, CURLOPT_HTTPHEADER, slist); + curl_easy_setopt(curl, CURLOPT_READDATA, f); + curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&chunk); + curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteMemoryCallback); + curl_easy_setopt(curl, CURLOPT_USERAGENT, OAUTH_USER_AGENT); +#ifdef OAUTH_CURL_TIMEOUT + curl_easy_setopt(curl, CURLOPT_TIMEOUT, OAUTH_CURL_TIMEOUT); + curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1); +#endif + GLOBAL_CURL_ENVIROMENT_OPTIONS; + res = curl_easy_perform(curl); + curl_slist_free_all(slist); + if (res) { + // error + return NULL; + } + fclose(f); + + curl_easy_cleanup(curl); + return (chunk.data); +} + +/** + * http send raw data, with callback. + * the returned string needs to be freed by the caller + * + * more documentation in oauth.h + * + * @param u url to retrieve + * @param data data to post along + * @param len length of the file in bytes. set to '0' for autodetection + * @param customheader specify custom HTTP header (or NULL for default) + * @param callback specify the callback function + * @param callback_data specify data to pass to the callback function + * @return returned HTTP reply or NULL on error + */ +char *oauth_curl_send_data_with_callback (const char *u, const char *data, size_t len, const char *customheader, void (*callback)(void*,int,size_t,size_t), void *callback_data, const char *httpMethod) { + CURL *curl; + CURLcode res; + struct curl_slist *slist=NULL; + struct MemoryStruct chunk; + struct MemoryStruct rdnfo; + + chunk.data=NULL; + chunk.size=0; + chunk.start_size=0; + chunk.callback=callback; + chunk.callback_data=callback_data; + rdnfo.data=(char *)data; + rdnfo.size=len; + rdnfo.start_size=len; + rdnfo.callback=callback; + rdnfo.callback_data=callback_data; + + if (customheader) + slist = curl_slist_append(slist, customheader); + else + slist = curl_slist_append(slist, "Content-Type: image/jpeg;"); + + curl = curl_easy_init(); + if(!curl) return NULL; + curl_easy_setopt(curl, CURLOPT_URL, u); + curl_easy_setopt(curl, CURLOPT_POST, 1); + if (httpMethod) curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, httpMethod); + curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, len); + curl_easy_setopt(curl, CURLOPT_HTTPHEADER, slist); + curl_easy_setopt(curl, CURLOPT_READDATA, (void *)&rdnfo); + if (callback) + curl_easy_setopt(curl, CURLOPT_READFUNCTION, ReadMemoryCallbackAndCall); + else + curl_easy_setopt(curl, CURLOPT_READFUNCTION, ReadMemoryCallback); + curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&chunk); + if (callback) + curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteMemoryCallbackAndCall); + else + curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteMemoryCallback); + curl_easy_setopt(curl, CURLOPT_USERAGENT, OAUTH_USER_AGENT); +#ifdef OAUTH_CURL_TIMEOUT + curl_easy_setopt(curl, CURLOPT_TIMEOUT, OAUTH_CURL_TIMEOUT); + curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1); +#endif + GLOBAL_CURL_ENVIROMENT_OPTIONS; + res = curl_easy_perform(curl); + curl_slist_free_all(slist); + if (res) { + // error + return NULL; + } + + curl_easy_cleanup(curl); + return (chunk.data); +} + +/** + * http post raw data. + * the returned string needs to be freed by the caller + * + * more documentation in oauth.h + * + * @param u url to retrieve + * @param data data to post along + * @param len length of the file in bytes. set to '0' for autodetection + * @param customheader specify custom HTTP header (or NULL for default) + * @return returned HTTP reply or NULL on error + */ +char *oauth_curl_post_data(const char *u, const char *data, size_t len, const char *customheader) { + return oauth_curl_send_data_with_callback(u, data, len, customheader, NULL, NULL, NULL); +} + +char *oauth_curl_send_data (const char *u, const char *data, size_t len, const char *customheader, const char *httpMethod) { + return oauth_curl_send_data_with_callback(u, data, len, customheader, NULL, NULL, httpMethod); +} + +char *oauth_curl_post_data_with_callback (const char *u, const char *data, size_t len, const char *customheader, void (*callback)(void*,int,size_t,size_t), void *callback_data) { + return oauth_curl_send_data_with_callback(u, data, len, customheader, callback, callback_data, NULL); +} + +#endif // libcURL. + + +#ifdef HAVE_SHELL_CURL /* HTTP requests via command-line curl */ + +// command line presets and ENV variable name +#define _OAUTH_ENV_HTTPCMD "OAUTH_HTTP_CMD" +#define _OAUTH_ENV_HTTPGET "OAUTH_HTTP_GET_CMD" + +#ifdef OAUTH_CURL_TIMEOUT + +#define cpxstr(s) cpstr(s) +#define cpstr(s) #s + +#ifndef _OAUTH_DEF_HTTPCMD +# define _OAUTH_DEF_HTTPCMD "curl -sA '"OAUTH_USER_AGENT"' -m "cpxstr(OAUTH_CURL_TIMEOUT)" -d '%p' '%u' " +//alternative: "wget -q -U 'liboauth-agent/0.1' --post-data='%p' '%u' " +#endif + +#ifndef _OAUTH_DEF_HTTPGET +# define _OAUTH_DEF_HTTPGET "curl -sA '"OAUTH_USER_AGENT"' -m "cpxstr(OAUTH_CURL_TIMEOUT)" '%u' " +//alternative: "wget -q -U 'liboauth-agent/0.1' '%u' " +#endif + +#else // no timeout + +#ifndef _OAUTH_DEF_HTTPCMD +# define _OAUTH_DEF_HTTPCMD "curl -sA '"OAUTH_USER_AGENT"' -d '%p' '%u' " +//alternative: "wget -q -U 'liboauth-agent/0.1' --post-data='%p' '%u' " +#endif + +#ifndef _OAUTH_DEF_HTTPGET +# define _OAUTH_DEF_HTTPGET "curl -sA '"OAUTH_USER_AGENT"' '%u' " +//alternative: "wget -q -U 'liboauth-agent/0.1' '%u' " +#endif + +#endif + +#include <stdio.h> + +/** + * escape URL for use in String Quotes (aka shell single quotes). + * the returned string needs to be free()d by the calling function + * + * WARNING: this function only escapes single-quotes (') + * + * + * RFC2396 defines the following + * reserved = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" | "$" | "," + * besides alphanum the following are allowed as unreserved: + * mark = "-" | "_" | "." | "!" | "~" | "*" | "'" | "(" | ")" + * + * checking `echo '-_.!~*()'` it seems we + * just need to escape the tick (') itself from "'" to "'\''" + * + * In C shell, the "!" character may need a backslash before it. + * It depends on the characters next to it. If it is surrounded by spaces, + * you don't need to use a backslash. + * (here: we'd always need to escape it for c shell) + * @todo: escape '!' for c-shell curl/wget commandlines + * + * @param cmd URI string or parameter to be escaped + * @return escaped parameter + */ +char *oauth_escape_shell (const char *cmd) { + char *esc = xstrdup(cmd); + char *tmp = esc; + int idx; + while ((tmp=strchr(tmp,'\''))) { + idx = tmp-esc; + esc=(char*)xrealloc(esc,(strlen(esc)+5)*sizeof(char)); + memmove(esc+idx+4,esc+idx+1, strlen(esc+idx)); + esc[idx+1]='\\'; esc[idx+2]='\''; esc[idx+3]='\''; + tmp=esc+(idx+4); + } + +// TODO escape '!' if CSHELL ?! + + return esc; +} + +/** + * execute command via shell and return it's output. + * This is used to call 'curl' or 'wget'. + * the command is uses <em>as is</em> and needs to be propery escaped. + * + * @param cmd the commandline to execute + * @return stdout string that needs to be freed or NULL if there's no output + */ +char *oauth_exec_shell (const char *cmd) { +#ifdef DEBUG_OAUTH + printf("DEBUG: executing: %s\n",cmd); +#endif + FILE *in = popen (cmd, "r"); + size_t len = 0; + size_t alloc = 0; + char *data = NULL; + int rcv = 1; + while (in && rcv > 0 && !feof(in)) { + alloc +=1024; + data = (char*)xrealloc(data, alloc * sizeof(char)); + rcv = fread(data + (alloc-1024), sizeof(char), 1024, in); + len += rcv; + } + pclose(in); +#ifdef DEBUG_OAUTH + printf("DEBUG: read %i bytes\n",len); +#endif + data[len]=0; +#ifdef DEBUG_OAUTH + if (data) printf("DEBUG: return: %s\n",data); + else printf("DEBUG: NULL data\n"); +#endif + return (data); +} + +/** + * send POST via a command line HTTP client, wait for it to finish + * and return the content of the reply. requires a command-line HTTP client + * + * see \ref oauth_http_post + * + * @param u url to query + * @param p postargs to send along with the HTTP request. + * @return In case of an error NULL is returned; otherwise a pointer to the + * replied content from HTTP server. latter needs to be freed by caller. + */ +char *oauth_exec_post (const char *u, const char *p) { + char cmd[BUFSIZ]; + char *t1,*t2; + char *cmdtpl = getenv(_OAUTH_ENV_HTTPCMD); + if (!cmdtpl) cmdtpl = xstrdup (_OAUTH_DEF_HTTPCMD); + else cmdtpl = xstrdup (cmdtpl); // clone getenv() string. + + // add URL and post param - error if no '%p' or '%u' present in definition + t1=strstr(cmdtpl, "%p"); + t2=strstr(cmdtpl, "%u"); + if (!t1 || !t2) { + fprintf(stderr, "\nliboauth: invalid HTTP command. set the '%s' environment variable.\n\n",_OAUTH_ENV_HTTPCMD); + return(NULL); + } + // TODO: check if there are exactly two '%' in cmdtpl + *(++t1)= 's'; *(++t2)= 's'; + if (t1>t2) { + t1=oauth_escape_shell(u); + t2=oauth_escape_shell(p); + } else { + t1=oauth_escape_shell(p); + t2=oauth_escape_shell(u); + } + snprintf(cmd, BUFSIZ, cmdtpl, t1, t2); + free(cmdtpl); + free(t1); free(t2); + return oauth_exec_shell(cmd); +} + +/** + * send GET via a command line HTTP client + * and return the content of the reply.. + * requires a command-line HTTP client. + * + * Note: u and q are just concatenated with a '?' in between unless q is NULL. in which case only u will be used. + * + * see \ref oauth_http_get + * + * @param u base url to get + * @param q query string to send along with the HTTP request. + * @return In case of an error NULL is returned; otherwise a pointer to the + * replied content from HTTP server. latter needs to be freed by caller. + */ +char *oauth_exec_get (const char *u, const char *q) { + char cmd[BUFSIZ]; + char *cmdtpl, *t1, *e1; + + if (!u) return (NULL); + + cmdtpl = getenv(_OAUTH_ENV_HTTPGET); + if (!cmdtpl) cmdtpl = xstrdup (_OAUTH_DEF_HTTPGET); + else cmdtpl = xstrdup (cmdtpl); // clone getenv() string. + + // add URL and post param - error if no '%p' or '%u' present in definition + t1=strstr(cmdtpl, "%u"); + if (!t1) { + fprintf(stderr, "\nliboauth: invalid HTTP command. set the '%s' environment variable.\n\n",_OAUTH_ENV_HTTPGET); + return(NULL); + } + *(++t1)= 's'; + + e1 = oauth_escape_shell(u); + if (q) { + char *e2; + e2 = oauth_escape_shell(q); + t1=(char*)xmalloc(sizeof(char)*(strlen(e1)+strlen(e2)+2)); + strcpy(t1,e1); strcat(t1,"?"); strcat(t1,e2); + free(e2); + } + snprintf(cmd, BUFSIZ, cmdtpl, q?t1:e1); + free(cmdtpl); + free(e1); + if (q) free(t1); + return oauth_exec_shell(cmd); +} +#endif // command-line curl. + +/* wrapper functions */ + +/** + * do a HTTP GET request, wait for it to finish + * and return the content of the reply. + * (requires libcurl or a command-line HTTP client) + * + * more documentation in oauth.h + * + * @param u base url to get + * @param q query string to send along with the HTTP request or NULL. + * @return In case of an error NULL is returned; otherwise a pointer to the + * replied content from HTTP server. latter needs to be freed by caller. + */ +char *oauth_http_get (const char *u, const char *q) { +#ifdef HAVE_CURL + return oauth_curl_get(u,q,NULL); +#elif defined(HAVE_SHELL_CURL) + return oauth_exec_get(u,q); +#else + return NULL; +#endif +} + +/** + * do a HTTP GET request, wait for it to finish + * and return the content of the reply. + * (requires libcurl) + * + * @param u base url to get + * @param q query string to send along with the HTTP request or NULL. + * @param customheader specify custom HTTP header (or NULL for none) + * @return In case of an error NULL is returned; otherwise a pointer to the + * replied content from HTTP server. latter needs to be freed by caller. + */ +char *oauth_http_get2 (const char *u, const char *q, const char *customheader) { +#ifdef HAVE_CURL + return oauth_curl_get(u,q,customheader); +#else + return NULL; +#endif +} + +/** + * do a HTTP POST request, wait for it to finish + * and return the content of the reply. + * (requires libcurl or a command-line HTTP client) + * + * more documentation in oauth.h + * + * @param u url to query + * @param p postargs to send along with the HTTP request. + * @return In case of an error NULL is returned; otherwise a pointer to the + * replied content from HTTP server. latter needs to be freed by caller. + */ +char *oauth_http_post (const char *u, const char *p) { +#ifdef HAVE_CURL + return oauth_curl_post(u,p,NULL); +#elif defined(HAVE_SHELL_CURL) + return oauth_exec_post(u,p); +#else + return NULL; +#endif +} + + +/** + * do a HTTP POST request, wait for it to finish + * and return the content of the reply. + * (requires libcurl) + * + * more documentation in oauth.h + * + * @param u url to query + * @param p postargs to send along with the HTTP request. + * @param customheader specify custom HTTP header (or NULL for none) + * @return In case of an error NULL is returned; otherwise a pointer to the + * replied content from HTTP server. latter needs to be freed by caller. + */ +char *oauth_http_post2 (const char *u, const char *p, const char *customheader) { +#ifdef HAVE_CURL + return oauth_curl_post(u,p,customheader); +#else + return NULL; +#endif +} + +/** + * http post raw data from file. + * the returned string needs to be freed by the caller + * + * more documentation in oauth.h + * + * @param u url to retrieve + * @param fn filename of the file to post along + * @param len length of the file in bytes. set to '0' for autodetection + * @param customheader specify custom HTTP header (or NULL for default) + * @return returned HTTP reply or NULL on error + */ +char *oauth_post_file (const char *u, const char *fn, const size_t len, const char *customheader){ +#ifdef HAVE_CURL + return oauth_curl_post_file (u, fn, len, customheader); +#elif defined(HAVE_SHELL_CURL) + fprintf(stderr, "\nliboauth: oauth_post_file requires libcurl. libcurl is not available.\n\n"); + return NULL; +#else + return NULL; +#endif +} + +/** + * http post raw data. + * the returned string needs to be freed by the caller + * + * more documentation in oauth.h + * + * @param u url to retrieve + * @param data data to post along + * @param len length of the file in bytes. set to '0' for autodetection + * @param customheader specify custom HTTP header (or NULL for default) + * @return returned HTTP reply or NULL on error + */ +char *oauth_post_data (const char *u, const char *data, size_t len, const char *customheader) { +#ifdef HAVE_CURL + return oauth_curl_post_data (u, data, len, customheader); +#elif defined(HAVE_SHELL_CURL) + fprintf(stderr, "\nliboauth: oauth_post_file requires libcurl. libcurl is not available.\n\n"); + return NULL; +#else + return (NULL); +#endif +} + +char *oauth_send_data (const char *u, const char *data, size_t len, const char *customheader, const char *httpMethod) { +#ifdef HAVE_CURL + return oauth_curl_send_data (u, data, len, customheader, httpMethod); +#elif defined(HAVE_SHELL_CURL) + fprintf(stderr, "\nliboauth: oauth_send_file requires libcurl. libcurl is not available.\n\n"); + return NULL; +#else + return (NULL); +#endif +} + +char *oauth_post_data_with_callback (const char *u, const char *data, size_t len, const char *customheader, void (*callback)(void*,int,size_t,size_t), void *callback_data) { +#ifdef HAVE_CURL + return oauth_curl_post_data_with_callback(u, data, len, customheader, callback, callback_data); +#elif defined(HAVE_SHELL_CURL) + fprintf(stderr, "\nliboauth: oauth_post_data_with_callback requires libcurl.\n\n"); + return NULL; +#else + return (NULL); +#endif +} +/* vi:set ts=8 sts=2 sw=2: */ diff --git a/protocols/Twitter/oauth/src/sha1.c b/protocols/Twitter/oauth/src/sha1.c new file mode 100644 index 0000000000..c3189008ac --- /dev/null +++ b/protocols/Twitter/oauth/src/sha1.c @@ -0,0 +1,317 @@ +/* This code is public-domain - it is based on libcrypt + * placed in the public domain by Wei Dai and other contributors. + */ +// gcc -Wall -DSHA1TEST -o sha1test sha1.c && ./sha1test + +#include <stdint.h> +#include <string.h> + +/* header */ + +#define HASH_LENGTH 20 +#define BLOCK_LENGTH 64 + +union _buffer { + uint8_t b[BLOCK_LENGTH]; + uint32_t w[BLOCK_LENGTH/4]; +}; + +union _state { + uint8_t b[HASH_LENGTH]; + uint32_t w[HASH_LENGTH/4]; +}; + +typedef struct sha1nfo { + union _buffer buffer; + uint8_t bufferOffset; + union _state state; + uint32_t byteCount; + uint8_t keyBuffer[BLOCK_LENGTH]; + uint8_t innerHash[HASH_LENGTH]; +} sha1nfo; + +/* public API - prototypes - TODO: doxygen*/ + +/** + */ +void sha1_init(sha1nfo *s); +/** + */ +void sha1_writebyte(sha1nfo *s, uint8_t data); +/** + */ +void sha1_write(sha1nfo *s, const char *data, size_t len); +/** + */ +uint8_t* sha1_result(sha1nfo *s); +/** + */ +void sha1_initHmac(sha1nfo *s, const uint8_t* key, int keyLength); +/** + */ +uint8_t* sha1_resultHmac(sha1nfo *s); + + +/* code */ +#define SHA1_K0 0x5a827999 +#define SHA1_K20 0x6ed9eba1 +#define SHA1_K40 0x8f1bbcdc +#define SHA1_K60 0xca62c1d6 + +const uint8_t sha1InitState[] = { + 0x01,0x23,0x45,0x67, // H0 + 0x89,0xab,0xcd,0xef, // H1 + 0xfe,0xdc,0xba,0x98, // H2 + 0x76,0x54,0x32,0x10, // H3 + 0xf0,0xe1,0xd2,0xc3 // H4 +}; + +void sha1_init(sha1nfo *s) { + memcpy(s->state.b,sha1InitState,HASH_LENGTH); + s->byteCount = 0; + s->bufferOffset = 0; +} + +uint32_t sha1_rol32(uint32_t number, uint8_t bits) { + return ((number << bits) | (number >> (32-bits))); +} + +void sha1_hashBlock(sha1nfo *s) { + uint8_t i; + uint32_t a,b,c,d,e,t; + + a=s->state.w[0]; + b=s->state.w[1]; + c=s->state.w[2]; + d=s->state.w[3]; + e=s->state.w[4]; + for (i=0; i<80; i++) { + if (i>=16) { + t = s->buffer.w[(i+13)&15] ^ s->buffer.w[(i+8)&15] ^ s->buffer.w[(i+2)&15] ^ s->buffer.w[i&15]; + s->buffer.w[i&15] = sha1_rol32(t,1); + } + if (i<20) { + t = (d ^ (b & (c ^ d))) + SHA1_K0; + } else if (i<40) { + t = (b ^ c ^ d) + SHA1_K20; + } else if (i<60) { + t = ((b & c) | (d & (b | c))) + SHA1_K40; + } else { + t = (b ^ c ^ d) + SHA1_K60; + } + t+=sha1_rol32(a,5) + e + s->buffer.w[i&15]; + e=d; + d=c; + c=sha1_rol32(b,30); + b=a; + a=t; + } + s->state.w[0] += a; + s->state.w[1] += b; + s->state.w[2] += c; + s->state.w[3] += d; + s->state.w[4] += e; +} + +void sha1_addUncounted(sha1nfo *s, uint8_t data) { + s->buffer.b[s->bufferOffset ^ 3] = data; + s->bufferOffset++; + if (s->bufferOffset == BLOCK_LENGTH) { + sha1_hashBlock(s); + s->bufferOffset = 0; + } +} + +void sha1_writebyte(sha1nfo *s, uint8_t data) { + ++s->byteCount; + sha1_addUncounted(s, data); +} + +void sha1_write(sha1nfo *s, const char *data, size_t len) { + for (;len--;) sha1_writebyte(s, (uint8_t) *data++); +} + +void sha1_pad(sha1nfo *s) { + // Implement SHA-1 padding (fips180-2 §5.1.1) + + // Pad with 0x80 followed by 0x00 until the end of the block + sha1_addUncounted(s, 0x80); + while (s->bufferOffset != 56) sha1_addUncounted(s, 0x00); + + // Append length in the last 8 bytes + sha1_addUncounted(s, 0); // We're only using 32 bit lengths + sha1_addUncounted(s, 0); // But SHA-1 supports 64 bit lengths + sha1_addUncounted(s, 0); // So zero pad the top bits + sha1_addUncounted(s, s->byteCount >> 29); // Shifting to multiply by 8 + sha1_addUncounted(s, s->byteCount >> 21); // as SHA-1 supports bitstreams as well as + sha1_addUncounted(s, s->byteCount >> 13); // byte. + sha1_addUncounted(s, s->byteCount >> 5); + sha1_addUncounted(s, s->byteCount << 3); +} + +uint8_t* sha1_result(sha1nfo *s) { + int i; + // Pad to complete the last block + sha1_pad(s); + + // Swap byte order back + for (i=0; i<5; i++) { + uint32_t a,b; + a=s->state.w[i]; + b=a<<24; + b|=(a<<8) & 0x00ff0000; + b|=(a>>8) & 0x0000ff00; + b|=a>>24; + s->state.w[i]=b; + } + + // Return pointer to hash (20 characters) + return s->state.b; +} + +#define HMAC_IPAD 0x36 +#define HMAC_OPAD 0x5c + +void sha1_initHmac(sha1nfo *s, const uint8_t* key, int keyLength) { + uint8_t i; + memset(s->keyBuffer, 0, BLOCK_LENGTH); + if (keyLength > BLOCK_LENGTH) { + // Hash long keys + sha1_init(s); + for (;keyLength--;) sha1_writebyte(s, *key++); + memcpy(s->keyBuffer, sha1_result(s), HASH_LENGTH); + } else { + // Block length keys are used as is + memcpy(s->keyBuffer, key, keyLength); + } + // Start inner hash + sha1_init(s); + for (i=0; i<BLOCK_LENGTH; i++) { + sha1_writebyte(s, s->keyBuffer[i] ^ HMAC_IPAD); + } +} + +uint8_t* sha1_resultHmac(sha1nfo *s) { + uint8_t i; + // Complete inner hash + memcpy(s->innerHash,sha1_result(s),HASH_LENGTH); + // Calculate outer hash + sha1_init(s); + for (i=0; i<BLOCK_LENGTH; i++) sha1_writebyte(s, s->keyBuffer[i] ^ HMAC_OPAD); + for (i=0; i<HASH_LENGTH; i++) sha1_writebyte(s, s->innerHash[i]); + return sha1_result(s); +} + +/* self-test */ + +#if SHA1TEST +#include <stdio.h> + +uint8_t hmacKey1[]={ + 0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0a,0x0b,0x0c,0x0d,0x0e,0x0f, + 0x10,0x11,0x12,0x13,0x14,0x15,0x16,0x17,0x18,0x19,0x1a,0x1b,0x1c,0x1d,0x1e,0x1f, + 0x20,0x21,0x22,0x23,0x24,0x25,0x26,0x27,0x28,0x29,0x2a,0x2b,0x2c,0x2d,0x2e,0x2f, + 0x30,0x31,0x32,0x33,0x34,0x35,0x36,0x37,0x38,0x39,0x3a,0x3b,0x3c,0x3d,0x3e,0x3f +}; +uint8_t hmacKey2[]={ + 0x30,0x31,0x32,0x33,0x34,0x35,0x36,0x37,0x38,0x39,0x3a,0x3b,0x3c,0x3d,0x3e,0x3f, + 0x40,0x41,0x42,0x43 +}; +uint8_t hmacKey3[]={ + 0x50,0x51,0x52,0x53,0x54,0x55,0x56,0x57,0x58,0x59,0x5a,0x5b,0x5c,0x5d,0x5e,0x5f, + 0x60,0x61,0x62,0x63,0x64,0x65,0x66,0x67,0x68,0x69,0x6a,0x6b,0x6c,0x6d,0x6e,0x6f, + 0x70,0x71,0x72,0x73,0x74,0x75,0x76,0x77,0x78,0x79,0x7a,0x7b,0x7c,0x7d,0x7e,0x7f, + 0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8a,0x8b,0x8c,0x8d,0x8e,0x8f, + 0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9a,0x9b,0x9c,0x9d,0x9e,0x9f, + 0xa0,0xa1,0xa2,0xa3,0xa4,0xa5,0xa6,0xa7,0xa8,0xa9,0xaa,0xab,0xac,0xad,0xae,0xaf, + 0xb0,0xb1,0xb2,0xb3 +}; +uint8_t hmacKey4[]={ + 0x70,0x71,0x72,0x73,0x74,0x75,0x76,0x77,0x78,0x79,0x7a,0x7b,0x7c,0x7d,0x7e,0x7f, + 0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8a,0x8b,0x8c,0x8d,0x8e,0x8f, + 0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9a,0x9b,0x9c,0x9d,0x9e,0x9f, + 0xa0 +}; + +void printHash(uint8_t* hash) { + int i; + for (i=0; i<20; i++) { + printf("%02x", hash[i]); + } + printf("\n"); +} + + +int main (int argc, char **argv) { + uint32_t a; + sha1nfo s; + + // SHA tests + printf("Test: FIPS 180-2 C.1 and RFC3174 7.3 TEST1\n"); + printf("Expect:a9993e364706816aba3e25717850c26c9cd0d89d\n"); + printf("Result:"); + sha1_init(&s); + sha1_write(&s, "abc", 3); + printHash(sha1_result(&s)); + printf("\n\n"); + + printf("Test: FIPS 180-2 C.2 and RFC3174 7.3 TEST2\n"); + printf("Expect:84983e441c3bd26ebaae4aa1f95129e5e54670f1\n"); + printf("Result:"); + sha1_init(&s); + sha1_write(&s, "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq", 56); + printHash(sha1_result(&s)); + printf("\n\n"); + + printf("Test: RFC3174 7.3 TEST4\n"); + printf("Expect:dea356a2cddd90c7a7ecedc5ebb563934f460452\n"); + printf("Result:"); + sha1_init(&s); + for (a=0; a<80; a++) sha1_write(&s, "01234567", 8); + printHash(sha1_result(&s)); + printf("\n\n"); + + // HMAC tests + printf("Test: FIPS 198a A.1\n"); + printf("Expect:4f4ca3d5d68ba7cc0a1208c9c61e9c5da0403c0a\n"); + printf("Result:"); + sha1_initHmac(&s, hmacKey1, 64); + sha1_write(&s, "Sample #1",9); + printHash(sha1_resultHmac(&s)); + printf("\n\n"); + + printf("Test: FIPS 198a A.2\n"); + printf("Expect:0922d3405faa3d194f82a45830737d5cc6c75d24\n"); + printf("Result:"); + sha1_initHmac(&s, hmacKey2, 20); + sha1_write(&s, "Sample #2", 9); + printHash(sha1_resultHmac(&s)); + printf("\n\n"); + + printf("Test: FIPS 198a A.3\n"); + printf("Expect:bcf41eab8bb2d802f3d05caf7cb092ecf8d1a3aa\n"); + printf("Result:"); + sha1_initHmac(&s, hmacKey3,100); + sha1_write(&s, "Sample #3", 9); + printHash(sha1_resultHmac(&s)); + printf("\n\n"); + + printf("Test: FIPS 198a A.4\n"); + printf("Expect:9ea886efe268dbecce420c7524df32e0751a2a26\n"); + printf("Result:"); + sha1_initHmac(&s, hmacKey4,49); + sha1_write(&s, "Sample #4", 9); + printHash(sha1_resultHmac(&s)); + printf("\n\n"); + + // Long tests + printf("Test: FIPS 180-2 C.3 and RFC3174 7.3 TEST3\n"); + printf("Expect:34aa973cd4c4daa4f61eeb2bdbad27316534016f\n"); + printf("Result:"); + sha1_init(&s); + for (a=0; a<1000000; a++) sha1_writebyte(&s, 'a'); + printHash(sha1_result(&s)); + + return 0; +} +#endif /* self-test */ diff --git a/protocols/Twitter/oauth/src/xmalloc.c b/protocols/Twitter/oauth/src/xmalloc.c new file mode 100644 index 0000000000..f831e13895 --- /dev/null +++ b/protocols/Twitter/oauth/src/xmalloc.c @@ -0,0 +1,60 @@ +/* xmalloc.c -- memory allocation including 'out of memory' checks + * + * Copyright 2010 Robin Gareus <robin@gareus.org> + * + * 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 <stdio.h> +#include <sys/types.h> +#include <string.h> +#include <stdlib.h> + +static void *xmalloc_fatal(size_t size) { + if (size==0) return NULL; + fprintf(stderr, "Out of memory."); + exit(1); +} + +void *xmalloc (size_t size) { + void *ptr = malloc (size); + if (ptr == NULL) return xmalloc_fatal(size); + return ptr; +} + +void *xcalloc (size_t nmemb, size_t size) { + void *ptr = calloc (nmemb, size); + if (ptr == NULL) return xmalloc_fatal(nmemb*size); + return ptr; +} + +void *xrealloc (void *ptr, size_t size) { + void *p = realloc (ptr, size); + if (p == NULL) return xmalloc_fatal(size); + return p; +} + +char *xstrdup (const char *s) { + void *ptr = xmalloc(strlen(s)+1); + strcpy (ptr, s); + return (char*) ptr; +} + +// vi: sts=2 sw=2 ts=2 diff --git a/protocols/Twitter/oauth/src/xmalloc.h b/protocols/Twitter/oauth/src/xmalloc.h new file mode 100644 index 0000000000..7ec9b61fdd --- /dev/null +++ b/protocols/Twitter/oauth/src/xmalloc.h @@ -0,0 +1,10 @@ +#ifndef _OAUTH_XMALLOC_H +#define _OAUTH_XMALLOC_H 1 + +/* Prototypes for functions defined in xmalloc.c */ +void *xmalloc (size_t size); +void *xcalloc (size_t nmemb, size_t size); +void *xrealloc (void *ptr, size_t size); +char *xstrdup (const char *s); + +#endif diff --git a/protocols/Twitter/oauth/tests/Makefile.am b/protocols/Twitter/oauth/tests/Makefile.am new file mode 100644 index 0000000000..55330a19ac --- /dev/null +++ b/protocols/Twitter/oauth/tests/Makefile.am @@ -0,0 +1,44 @@ +check_PROGRAMS = oauthexample oauthdatapost tcwiki tceran tcother oauthtest oauthtest2 oauthsign oauthbodyhash +ACLOCAL_AMFLAGS= -I m4 + +OAUTHDIR =../src +INCLUDES = -I$(srcdir)/$(OAUTHDIR) +MYCFLAGS = @LIBOAUTH_CFLAGS@ @HASH_CFLAGS@ @CURL_CFLAGS@ +MYLDADD = $(OAUTHDIR)/liboauth.la +LIBS = -lm @HASH_LIBS@ @CURL_LIBS@ @LIBS@ + +tcwiki_SOURCES = selftest_wiki.c commontest.c commontest.h +tcwiki_LDADD = $(MYLDADD) +tcwiki_CFLAGS = $(MYCFLAGS) @TEST_UNICODE@ + +tceran_SOURCES = selftest_eran.c commontest.c commontest.h +tceran_LDADD = $(MYLDADD) +tceran_CFLAGS = $(MYCFLAGS) @TEST_UNICODE@ + +tcother_SOURCES = selftest_other.c commontest.c commontest.h +tcother_LDADD = $(MYLDADD) +tcother_CFLAGS = $(MYCFLAGS) + +oauthtest_SOURCES = oauthtest.c +oauthtest_LDADD = $(MYLDADD) +oauthtest_CFLAGS = $(MYCFLAGS) + +oauthtest2_SOURCES = oauthtest2.c +oauthtest2_LDADD = $(MYLDADD) +oauthtest2_CFLAGS = $(MYCFLAGS) + +oauthexample_SOURCES = oauthexample.c +oauthexample_LDADD = $(MYLDADD) +oauthexample_CFLAGS = $(MYCFLAGS) + +oauthsign_SOURCES = oauthsign.c +oauthsign_LDADD = $(MYLDADD) +oauthsign_CFLAGS = $(MYCFLAGS) + +oauthdatapost_SOURCES = oauthdatapost.c +oauthdatapost_LDADD = $(MYLDADD) +oauthdatapost_CFLAGS = $(MYCFLAGS) + +oauthbodyhash_SOURCES = oauthbodyhash.c +oauthbodyhash_LDADD = $(MYLDADD) +oauthbodyhash_CFLAGS = $(MYCFLAGS) diff --git a/protocols/Twitter/oauth/tests/commontest.c b/protocols/Twitter/oauth/tests/commontest.c new file mode 100644 index 0000000000..fb5d891381 --- /dev/null +++ b/protocols/Twitter/oauth/tests/commontest.c @@ -0,0 +1,155 @@ +/** + * @brief test and example code for liboauth. + * @file commontest.c + * @author Robin Gareus <robin@gareus.org> + * + * Copyright 2007, 2008 Robin Gareus <robin@gareus.org> + * + * 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. + */ + +#ifdef TEST_UNICODE +#include <locale.h> +#endif + +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <oauth.h> + +#include "commontest.h" + +extern int loglevel; //< report each successful test + +/* + * test parameter encoding + */ +int test_encoding(char *param, char *expected) { + int rv=0; + char *testcase=NULL; + testcase = oauth_url_escape(param); + if (strcmp(testcase,expected)) { + rv=1; + printf("parameter encoding test for '%s' failed.\n" + " got: '%s' expected: '%s'\n", param, testcase, expected); + } + else if (loglevel) printf("parameter encoding ok. ('%s')\n", testcase); + if (testcase) free(testcase); + return (rv); +} + +#ifdef TEST_UNICODE +/* + * test unicode paramter encoding + */ +int test_uniencoding(wchar_t *src, char *expected) { + size_t n; + char *dst; +// check unicode: http://www.thescripts.com/forum/thread223350.html + const char *encoding = "en_US.UTF-8"; // or try en_US.ISO-8859-1 etc. + //wchar_t src[] = {0x0080, 0}; + + if(setlocale(LC_CTYPE, encoding) == NULL) { + printf("requested encoding unavailable\n"); + return -1; + } + + n = wcstombs(NULL, src, 0); + dst = malloc(n + 1); + if(dst == NULL) { + printf("memory allocation failed\n"); + return -2; + } + if(wcstombs(dst, src, n + 1) != n) { + printf("conversion failed\n"); + free(dst); + return -3; + } + return test_encoding(dst, expected); +} +#endif + +/* + * test request normalization + */ +int test_normalize(char *param, char *expected) { + int rv=2; + int i, argc; + char **argv = NULL; + char *testcase; + + argc = oauth_split_url_parameters(param, &argv); + qsort(argv, argc, sizeof(char *), oauth_cmpstringp); + testcase= oauth_serialize_url(argc,0, argv); + + rv=strcmp(testcase,expected); + if (rv) { + printf("parameter normalization test failed for: '%s'.\n" + " got: '%s' expected: '%s'\n", param, testcase, expected); + } + else if (loglevel) printf("parameter normalization ok. ('%s')\n", testcase); + for (i=0;i<argc;i++) free(argv[i]); + if (argv) free(argv); + if (testcase) free(testcase); + return (rv); +} + +/* + * test request concatenation + */ +int test_request(char *http_method, char *request, char *expected) { + int rv=2; + int i, argc; + char **argv = NULL; + char *query, *testcase; + + argc = oauth_split_url_parameters(request, &argv); + qsort(&argv[1], argc-1, sizeof(char *), oauth_cmpstringp); + query= oauth_serialize_url(argc,1, argv); + testcase = oauth_catenc(3, http_method, argv[0], query); + + rv=strcmp(testcase,expected); + if (rv) { + printf("request concatenation test failed for: '%s'.\n" + " got: '%s'\n expected: '%s'\n", request, testcase, expected); + } + else if (loglevel) printf("request concatenation ok.\n"); + for (i=0;i<argc;i++) free(argv[i]); + if (argv) free(argv); + if (query) free(query); + if (testcase) free(testcase); + return (rv); +} + +/* + * test hmac-sha1 checksum + */ +int test_sha1(char *c_secret, char *t_secret, char *base, char *expected) { + int rv=0; + char *okey = oauth_catenc(2, c_secret, t_secret); + char *b64d = oauth_sign_hmac_sha1(base, okey); + if (strcmp(b64d,expected)) { + printf("HMAC-SHA1 invalid. base:'%s' secrets:'%s'\n" + " got: '%s' expected: '%s'\n", base, okey, b64d, expected); + rv=1; + } else if (loglevel) printf("HMAC-SHA1 test sucessful.\n"); + free(b64d); + free(okey); + return (rv); +} diff --git a/protocols/Twitter/oauth/tests/commontest.h b/protocols/Twitter/oauth/tests/commontest.h new file mode 100644 index 0000000000..d90d381569 --- /dev/null +++ b/protocols/Twitter/oauth/tests/commontest.h @@ -0,0 +1,7 @@ +int test_encoding(char *param, char *expected); +#ifdef TEST_UNICODE +int test_uniencoding(wchar_t *src, char *expected); +#endif +int test_normalize(char *param, char *expected); +int test_request(char *http_method, char *request, char *expected); +int test_sha1(char *c_secret, char *t_secret, char *base, char *expected); diff --git a/protocols/Twitter/oauth/tests/oauthbodyhash.c b/protocols/Twitter/oauth/tests/oauthbodyhash.c new file mode 100644 index 0000000000..eb3ff3fbb9 --- /dev/null +++ b/protocols/Twitter/oauth/tests/oauthbodyhash.c @@ -0,0 +1,90 @@ +/** + * @brief experimental code to sign data uploads + * @file oauthbodysign.c + * @author Robin Gareus <robin@gareus.org> + * + * Copyright 2009 Robin Gareus <robin@gareus.org> + * + * 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 <string.h> +#include <stdio.h> +#include <stdlib.h> +#include <oauth.h> + +int my_data_post(char *url, char *data) { + const char *c_key = "key"; //< consumer key + const char *c_secret = "secret"; //< consumer secret + char *t_key = "tkey"; //< access token key + char *t_secret = "tsecret"; //< access token secret + + char *postarg = NULL; + char *req_url = NULL; + char *reply = NULL; + char *bh; + char *uh; + char *sig_url; + + bh=oauth_body_hash_data(strlen(data), data); + uh = oauth_catenc(2, url, bh); + req_url = oauth_sign_url2(uh, &postarg, OA_HMAC, NULL, c_key, c_secret, t_key, t_secret); + printf("POST: %s?%s\n", req_url, postarg); + if (uh) free(uh); + + sig_url = malloc(2+strlen(req_url)+strlen(postarg)); + sprintf(sig_url,"%s?%s",req_url, postarg); + reply = oauth_post_data(sig_url, data, strlen(data), "Content-Type: application/json"); + if(sig_url) free(sig_url); + + printf("REPLY: %s\n", reply); + if(reply) free(reply); + return 0; +} + +int main (int argc, char **argv) { + char *base_url = "http://localhost/oauthtest.php"; + char *teststring="Hello World!"; + + /* TEST_BODY_HASH_FILE and TEST_BODY_HASH_DATA are only + * here as examples and for testing during development. + * + * the my_data_post() function above uses oauth_body_hash_data() + */ + +#if defined TEST_BODY_HASH_FILE || defined TEST_BODY_HASH_DATA + char *bh=NULL; +#endif + +#ifdef TEST_BODY_HASH_FILE // example hash file + char *filename="/tmp/test"; + bh=oauth_body_hash_file(filename); + if (bh) printf("%s\n", bh); + if (bh) free(bh); +#endif + +#ifdef TEST_BODY_HASH_DATA // example hash data + bh=oauth_body_hash_data(strlen(teststring), teststring); + if (bh) printf("%s\n", bh); + if (bh) free(bh); +#endif + + my_data_post(base_url, teststring); + return(0); +} diff --git a/protocols/Twitter/oauth/tests/oauthdatapost.c b/protocols/Twitter/oauth/tests/oauthdatapost.c new file mode 100644 index 0000000000..9bd2e1d20f --- /dev/null +++ b/protocols/Twitter/oauth/tests/oauthdatapost.c @@ -0,0 +1,166 @@ +/** + * @brief experimental code to sign data uploads + * @file oauthimageupload.c + * @author Robin Gareus <robin@gareus.org> + * + * Copyright 2008 Robin Gareus <robin@gareus.org> + * + * 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 <string.h> +#include <stdio.h> +#include <stdlib.h> +#include <oauth.h> + +#ifdef USE_MMAP +#include <sys/mman.h> +#endif + +/** + * example oauth body signature and HTTP-POST. + * WARNING: <b> This is request type is not part of the + * oauth core 1.0</b>. + * + * This is an experimental extension. + */ +int oauth_image_post(char *filename, char *url) { + const char *c_key = "key"; //< consumer key + const char *c_secret = "secret"; //< consumer secret + char *t_key = NULL; //< access token key + char *t_secret = NULL; //< access token secret + + char *postarg = NULL; + char *req_url = NULL; + char *reply = NULL; + + char *filedata = NULL; + size_t filelen = 0; + + FILE *F; + + char *okey, *sign; + char *sig_url; + + // get acces token - see oautexample.c + t_key = strdup("key"); //< access token key + t_secret = strdup("secret"); //< access token secret + + // read raw data to sign and send from file. + F= fopen(filename, "r"); + if (!F) return 1; + fseek(F, 0L, SEEK_END); + filelen= ftell(F); + rewind(F); + + #ifdef USE_MMAP + filedata=mmap(NULL,filelen,PROT_READ,MAP_SHARED,fileno(F),0L); + #else + filedata=malloc(filelen*sizeof(char)); + if (filelen != fread(filedata,sizeof(char), filelen, F)) { + fclose(F); + return 2; + } + fclose(F); + #endif + + // sign the body + okey = oauth_catenc(2, c_secret, t_secret); + sign = oauth_sign_hmac_sha1_raw(filedata,filelen,okey,strlen(okey)); + free(okey); + sig_url = malloc(63+strlen(url)+strlen(sign)); + sprintf(sig_url,"%s&xoauth_body_signature=%s&xoauth_body_signature_method=HMAC_SHA1",url, sign); + + // sign a POST request + req_url = oauth_sign_url2(sig_url, &postarg, OA_HMAC, NULL, c_key, c_secret, t_key, t_secret); + free(sig_url); + + // append the oauth [post] parameters to the request-URL!! + sig_url = malloc(2+strlen(req_url)+strlen(postarg)); + sprintf(sig_url,"%s?%s",req_url, postarg); + + printf("POST:'%s'\n",sig_url); + //reply = oauth_post_file(sig_url,filename,filelen,"Content-Type: image/jpeg;"); + printf("reply:'%s'\n",reply); + + if(req_url) free(req_url); + if(postarg) free(postarg); + if(reply) free(reply); + if(t_key) free(t_key); + if(t_secret) free(t_secret); + + #ifdef USE_MMAP + munmap(filedata,filelen); + fclose(F); + #else + if(filedata) free(filedata); + #endif + return(0); +} + + +/** + * Main Test and Example Code. + * + * compile: + * gcc -lssl -loauth -o oauthdatapost oauthdatapost.c + */ + +int main (int argc, char **argv) { + char *base_url = "http://mms06.test.mediamatic.nl"; + char *filename = "/tmp/test.jpg"; + int anyid = 18704; + char *title = "test"; + char *url; + + if (argc>4) base_url = argv[4]; + if (argc>3) title = argv[3]; + if (argc>2) anyid = atoi(argv[2]); + if (argc>1) filename = argv[1]; + + // TODO check if file exists; also read oauth-params from args or file + + // anyMeta.nl image-post module URL + url = malloc(1024*sizeof(char)); + if (anyid<1 && !title) + sprintf(url,"%s/module/ImagePost/",base_url); + else if (anyid>0 && !title) + sprintf(url,"%s/module/ImagePost/%i?echoid=1",base_url,anyid); + else if (anyid<1 && title) { + char *tp = oauth_url_escape(title); + sprintf(url,"%s/module/ImagePost/?title=%s",base_url,tp); + free(tp); + } + else if (anyid>0 && title) { + char *tp = oauth_url_escape(title); + sprintf(url,"%s/module/ImagePost/%i?echoid=1&title=%s",base_url,anyid,tp); + free(tp); + } + + // doit + switch(oauth_image_post(filename, url)) { + case 0: + printf("request ok.\n"); + break; + default: + printf("upload failed.\n"); + break; + } + return(0); +} diff --git a/protocols/Twitter/oauth/tests/oauthexample.c b/protocols/Twitter/oauth/tests/oauthexample.c new file mode 100644 index 0000000000..fb5915dc53 --- /dev/null +++ b/protocols/Twitter/oauth/tests/oauthexample.c @@ -0,0 +1,161 @@ +/** + * @brief example code for liboauth using http://term.ie/oauth/example + * @file oauthexample.c + * @author Robin Gareus <robin@gareus.org> + * + * Copyright 2008 Robin Gareus <robin@gareus.org> + * + * 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 <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <oauth.h> + +/** + * split and parse URL parameters replied by the test-server + * into <em>oauth_token</em> and <em>oauth_token_secret</em>. + */ +int parse_reply(const char *reply, char **token, char **secret) { + int rc; + int ok=1; + char **rv = NULL; + rc = oauth_split_url_parameters(reply, &rv); + qsort(rv, rc, sizeof(char *), oauth_cmpstringp); + if( rc==2 + && !strncmp(rv[0],"oauth_token=",11) + && !strncmp(rv[1],"oauth_token_secret=",18) ) { + ok=0; + if (token) *token =strdup(&(rv[0][12])); + if (secret) *secret=strdup(&(rv[1][19])); + printf("key: '%s'\nsecret: '%s'\n",*token, *secret); // XXX token&secret may be NULL. + } + if(rv) free(rv); + return ok; +} + +/** + * an example requesting a request-token from an OAuth service-provider + * exchaning it with an access token + * and make an example request. + * exercising either the oauth-HTTP GET or POST function. + */ +int oauth_consumer_example(int use_post) { + const char *request_token_uri = "http://term.ie/oauth/example/request_token.php"; + const char *access_token_uri = "http://term.ie/oauth/example/access_token.php"; + const char *test_call_uri = "http://term.ie/oauth/example/echo_api.php?method=foo%20bar&bar=baz"; + const char *c_key = "key"; //< consumer key + const char *c_secret = "secret"; //< consumer secret + + char *t_key = NULL; //< access token key + char *t_secret = NULL; //< access token secret + + char *req_url = NULL; + char *postarg = NULL; + char *reply = NULL; + + printf("Request token..\n"); + if (use_post) { // HTTP POST + req_url = oauth_sign_url2(request_token_uri, &postarg, OA_HMAC, NULL, c_key, c_secret, NULL, NULL); + reply = oauth_http_post(req_url,postarg); + } else { // HTTP GET + req_url = oauth_sign_url2(request_token_uri, NULL, OA_HMAC, NULL, c_key, c_secret, NULL, NULL); + reply = oauth_http_get(req_url,postarg); + } + if (req_url) free(req_url); + if (postarg) free(postarg); + if (!reply) return(1); + if (parse_reply(reply, &t_key, &t_secret)) return(2); + free(reply); + + // The Request Token provided above is already authorized, for this test server + // so we may use it to request an Access Token right away. + + printf("Access token..\n"); + + if (use_post) { + req_url = oauth_sign_url2(access_token_uri, &postarg, OA_HMAC, NULL, c_key, c_secret, t_key, t_secret); + reply = oauth_http_post(req_url,postarg); + } else { + req_url = oauth_sign_url2(access_token_uri, NULL, OA_HMAC, NULL, c_key, c_secret, t_key, t_secret); + reply = oauth_http_get(req_url,postarg); + } + if (req_url) free(req_url); + if (postarg) free(postarg); + if (!reply) return(3); + if(t_key) free(t_key); + if(t_secret) free(t_secret); + if (parse_reply(reply, &t_key, &t_secret)) return(4); + free(reply); + + printf("make some request..\n"); + + if (use_post) { + req_url = oauth_sign_url2(test_call_uri, &postarg, OA_HMAC, NULL, c_key, c_secret, t_key, t_secret); + reply = oauth_http_post(req_url,postarg); + } else { + req_url = oauth_sign_url2(test_call_uri, NULL, OA_HMAC, NULL, c_key, c_secret, t_key, t_secret); + reply = oauth_http_get(req_url,postarg); + } + printf("query:'%s'\n",req_url); + printf("reply:'%s'\n",reply); + if(req_url) free(req_url); + if(postarg) free(postarg); + + if (strcmp(reply,"bar=baz&method=foo+bar")) return (5); + + if(reply) free(reply); + if(t_key) free(t_key); + if(t_secret) free(t_secret); + + return(0); +} + + +/** + * Main Test and Example Code. + * + * compile: + * gcc -lssl -loauth -o oauthexample oauthexample.c + */ + +int main (int argc, char **argv) { + switch(oauth_consumer_example(0)) { + case 1: + printf("HTTP request for an oauth request-token failed.\n"); + break; + case 2: + printf("did not receive a request-token.\n"); + break; + case 3: + printf("HTTP request for an oauth access-token failed.\n"); + break; + case 4: + printf("did not receive an access-token.\n"); + break; + case 5: + printf("test call 'echo-api' did not respond correctly.\n"); + break; + default: + printf("request ok.\n"); + break; + } + return(0); +} diff --git a/protocols/Twitter/oauth/tests/oauthsign.c b/protocols/Twitter/oauth/tests/oauthsign.c new file mode 100644 index 0000000000..e52d62c8b7 --- /dev/null +++ b/protocols/Twitter/oauth/tests/oauthsign.c @@ -0,0 +1,75 @@ +#include <stdio.h> +#include <stdlib.h> +#include <oauth.h> +#include <strings.h> + +static void usage (char *program_name) { + printf(" usage: %s mode url ckey tkey csec tsec\n", program_name); + exit (1); +} + +/** + * + * compile: + * gcc -loauth -o oauthsign oauthsign.c + */ +int main (int argc, char **argv) { + + char *url; //< the url to sign + char *c_key; //< consumer key + char *c_secret; //< consumer secret + char *t_key; //< token key + char *t_secret ; //< token secret + + int mode = 0; //< mode: 0=GET 1=POST + + // TODO: use getopt to parse parameters + + // FIXME: read secrets from stdin - they show up in ps(1) + // also overwrite memory of secrets before freeing it. + + if (argc !=7) usage(argv[0]); + + if ( atoi(argv[1]) > 0 ) mode=atoi(argv[1]);// questionable numeric shortcut + else if (!strcasecmp(argv[1],"GET")) mode=1; + else if (!strcasecmp(argv[1],"POST")) mode=2; + else if (!strcasecmp(argv[1],"POSTREQUEST")) mode=4; + else usage(argv[0]); + + url = argv[2]; + c_key = argv[3]; + t_key = argv[4]; + c_secret = argv[5]; + t_secret = argv[6]; + + if (mode==1) { // GET + char *geturl = NULL; + geturl = oauth_sign_url2(url, NULL, OA_HMAC, NULL, c_key, c_secret, t_key, t_secret); + if(geturl) { + printf("%s\n", geturl); + free(geturl); + } + } else { // POST + char *postargs = NULL, *post = NULL; + post = oauth_sign_url2(url, &postargs, OA_HMAC, NULL, c_key, c_secret, t_key, t_secret); + if (!post || !postargs) { + return (1); + } + if (mode==2) { // print postargs only + if (postargs) printf("%s\n", postargs); + } else if (mode==3) { // print url and postargs + if (post && postargs) printf("%s\n%s\n", post, postargs); + } else if (post && postargs) { + char *reply = oauth_http_post(post,postargs); + if(reply){ + //write(STDOUT, reply, strlen(reply)) + printf("%s\n", reply); + free(reply); + } + } + if(post) free(post); + if(postargs) free(postargs); + } + + return (0); +} diff --git a/protocols/Twitter/oauth/tests/oauthtest.c b/protocols/Twitter/oauth/tests/oauthtest.c new file mode 100644 index 0000000000..e06cb30b9e --- /dev/null +++ b/protocols/Twitter/oauth/tests/oauthtest.c @@ -0,0 +1,191 @@ +/** + * @brief self-test and example code for liboauth + * @file oauthtest.c + * @author Robin Gareus <robin@gareus.org> + * + * Copyright 2007, 2008 Robin Gareus <robin@gareus.org> + * + * 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 <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <oauth.h> + +/* + * a example requesting and parsing a request-token from an OAuth service-provider + * excercising the oauth-HTTP GET function. - it is almost the same as + * \ref request_token_example_post below. + */ +void request_token_example_get(void) { +#if 0 + const char *request_token_uri = "http://oauth-sandbox.mediamatic.nl/module/OAuth/request_token"; + const char *req_c_key = "17b09ea4c9a4121145936f0d7d8daa28047583796"; //< consumer key + const char *req_c_secret = "942295b08ffce77b399419ee96ac65be"; //< consumer secret +#else + const char *request_token_uri = "http://term.ie/oauth/example/request_token.php"; + const char *req_c_key = "key"; //< consumer key + const char *req_c_secret = "secret"; //< consumer secret +#endif + char *res_t_key = NULL; //< replied key + char *res_t_secret = NULL; //< replied secret + + char *req_url = NULL; + char *reply; + + req_url = oauth_sign_url2(request_token_uri, NULL, OA_HMAC, NULL, req_c_key, req_c_secret, NULL, NULL); + + printf("request URL:%s\n\n", req_url); + reply = oauth_http_get(req_url,NULL); + if (!reply) + printf("HTTP request for an oauth request-token failed.\n"); + else { + // parse reply - example: + //"oauth_token=2a71d1c73d2771b00f13ca0acb9836a10477d3c56&oauth_token_secret=a1b5c00c1f3e23fb314a0aa22e990266" + int rc; + char **rv = NULL; + + printf("HTTP-reply: %s\n", reply); + rc = oauth_split_url_parameters(reply, &rv); + qsort(rv, rc, sizeof(char *), oauth_cmpstringp); + if( rc==2 + && !strncmp(rv[0],"oauth_token=",11) + && !strncmp(rv[1],"oauth_token_secret=",18) ){ + res_t_key=strdup(&(rv[0][12])); + res_t_secret=strdup(&(rv[1][19])); + printf("key: '%s'\nsecret: '%s'\n",res_t_key, res_t_secret); + } + if(rv) free(rv); + } + + if(req_url) free(req_url); + if(reply) free(reply); + if(res_t_key) free(res_t_key); + if(res_t_secret) free(res_t_secret); +} + +/* + * a example requesting and parsing a request-token from an OAuth service-provider + * using the oauth-HTTP POST function. + */ +void request_token_example_post(void) { +#if 0 + const char *request_token_uri = "http://oauth-sandbox.mediamatic.nl/module/OAuth/request_token"; + const char *req_c_key = "17b09ea4c9a4121145936f0d7d8daa28047583796"; //< consumer key + const char *req_c_secret = "942295b08ffce77b399419ee96ac65be"; //< consumer secret +#else + const char *request_token_uri = "http://term.ie/oauth/example/request_token.php"; + const char *req_c_key = "key"; //< consumer key + const char *req_c_secret = "secret"; //< consumer secret +#endif + char *res_t_key = NULL; //< replied key + char *res_t_secret = NULL; //< replied secret + + char *postarg = NULL; + char *req_url; + char *reply; + + req_url = oauth_sign_url2(request_token_uri, &postarg, OA_HMAC, NULL, req_c_key, req_c_secret, NULL, NULL); + + printf("request URL:%s\n\n", req_url); + reply = oauth_http_post(req_url,postarg); + if (!reply) + printf("HTTP request for an oauth request-token failed.\n"); + else { + //parse reply - example: + //"oauth_token=2a71d1c73d2771b00f13ca0acb9836a10477d3c56&oauth_token_secret=a1b5c00c1f3e23fb314a0aa22e990266" + int rc; + char **rv = NULL; + printf("HTTP-reply: %s\n", reply); + rc = oauth_split_url_parameters(reply, &rv); + qsort(rv, rc, sizeof(char *), oauth_cmpstringp); + if( rc==2 + && !strncmp(rv[0],"oauth_token=",11) + && !strncmp(rv[1],"oauth_token_secret=",18) ){ + res_t_key=strdup(&(rv[0][12])); + res_t_secret=strdup(&(rv[1][19])); + printf("key: '%s'\nsecret: '%s'\n",res_t_key, res_t_secret); + } + if(rv) free(rv); + } + + if(req_url) free(req_url); + if(postarg) free(postarg); + if(reply) free(reply); + if(res_t_key) free(res_t_key); + if(res_t_secret) free(res_t_secret); +} + + +/* + * Main Test and Example Code. + * + * compile: + * gcc -lssl -loauth -o oauthtest oauthtest.c + */ +int main (int argc, char **argv) { + int fail=0; + + const char *url = "http://base.url/&just=append?post=or_get_parameters" + "&arguments=will_be_formatted_automatically?&dont_care" + "=about_separators"; + //< the url to sign + const char *c_key = "1234567890abcdef1234567890abcdef123456789"; + //< consumer key + const char *c_secret = "01230123012301230123012301230123"; + //< consumer secret + const char *t_key = "0987654321fedcba0987654321fedcba098765432"; + //< token key + const char *t_secret = "66666666666666666666666666666666"; + //< token secret + +#if 1 // example sign GET request and print the signed request URL + { + char *geturl = NULL; + geturl = oauth_sign_url2(url, NULL, OA_HMAC, NULL, c_key, c_secret, t_key, t_secret); + printf("GET: URL:%s\n\n", geturl); + if(geturl) free(geturl); + } +#endif + +#if 1 // sign POST ;) example + { + char *postargs = NULL, *post = NULL; + post = oauth_sign_url2(url, &postargs, OA_HMAC, NULL, c_key, c_secret, t_key, t_secret); + printf("POST: URL:%s\n PARAM:%s\n\n", post, postargs); + if(post) free(post); + if(postargs) free(postargs); + } +#endif + + printf(" *** sending HTTP request *** \n\n"); + +// These two will perform a HTTP request, requesting an access token. +// it's intended both as test (verify signature) +// and example code. +#if 1 // POST a request-token request + request_token_example_post(); +#endif +#if 1 // GET a request-token + request_token_example_get(); +#endif + + return (fail?1:0); +} diff --git a/protocols/Twitter/oauth/tests/oauthtest2.c b/protocols/Twitter/oauth/tests/oauthtest2.c new file mode 100644 index 0000000000..fe4cbbbebd --- /dev/null +++ b/protocols/Twitter/oauth/tests/oauthtest2.c @@ -0,0 +1,133 @@ +/** + * @brief self-test and example code for liboauth using + * HTTP Authorization header. + * @file oauthtest.c + * @author Robin Gareus <robin@gareus.org> + * + * Copyright 2010 Robin Gareus <robin@gareus.org> + * + * 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 <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <oauth.h> + +/* + * a example requesting and parsing a request-token from an OAuth service-provider + * using OAuth HTTP Authorization header: + * see http://oauth.net/core/1.0a/#auth_header + * and http://oauth.net/core/1.0a/#consumer_req_param + */ +void request_token_example_get(void) { +#if 0 + const char *request_token_uri = "http://localhost/oauthtest.php?test=test"; + const char *req_c_key = "17b09ea4c9a4121145936f0d7d8daa28047583796"; //< consumer key + const char *req_c_secret = "942295b08ffce77b399419ee96ac65be"; //< consumer secret +#else + const char *request_token_uri = "http://term.ie/oauth/example/request_token.php"; + const char *req_c_key = "key"; //< consumer key + const char *req_c_secret = "secret"; //< consumer secret +#endif + char *res_t_key = NULL; //< replied key + char *res_t_secret = NULL; //< replied secret + + char *req_url = NULL; + char *req_hdr = NULL; + char *http_hdr= NULL; + char *reply; + + + //req_url = oauth_sign_url2(request_token_uri, NULL, OA_HMAC, NULL, req_c_key, req_c_secret, NULL, NULL); + + // oauth_sign_url2 (see oauth.h) in steps + int argc; + char **argv = NULL; + + argc = oauth_split_url_parameters(request_token_uri, &argv); + if (1) { + int i; + for (i=0;i<argc; i++) + printf("%d:%s\n", i, argv[i]); + } + + oauth_sign_array2_process(&argc, &argv, + NULL, //< postargs (unused) + OA_HMAC, + NULL, //< HTTP method (defaults to "GET") + req_c_key, req_c_secret, NULL, NULL); + + // 'default' oauth_sign_url2 would do: + // req_url = oauth_serialize_url(argc, 0, argv); + + // we split [x_]oauth_ parameters (for use in HTTP Authorization header) + req_hdr = oauth_serialize_url_sep(argc, 1, argv, ", ", 6); + // and other URL parameters + req_url = oauth_serialize_url_sep(argc, 0, argv, "&", 1); + + oauth_free_array(&argc, &argv); + + // done with OAuth stuff, now perform the HTTP request. + http_hdr = malloc(strlen(req_hdr) + 55); + + // Note that (optional) 'realm' is not to be + // included in the oauth signed parameters and thus only added here. + // see 9.1.1 in http://oauth.net/core/1.0/#anchor14 + sprintf(http_hdr, "Authorization: OAuth realm=\"http://example.org/\", %s", req_hdr); + + printf("request URL=%s\n", req_url); + printf("request header=%s\n\n", http_hdr); + reply = oauth_http_get2(req_url,NULL, http_hdr); + if (!reply) + printf("HTTP request for an oauth request-token failed.\n"); + else { + // parse reply - example: + //"oauth_token=2a71d1c73d2771b00f13ca0acb9836a10477d3c56&oauth_token_secret=a1b5c00c1f3e23fb314a0aa22e990266" + int rc; + char **rv = NULL; + + printf("HTTP-reply: %s\n", reply); + rc = oauth_split_url_parameters(reply, &rv); + qsort(rv, rc, sizeof(char *), oauth_cmpstringp); + if( rc==2 + && !strncmp(rv[0],"oauth_token=",11) + && !strncmp(rv[1],"oauth_token_secret=",18) ){ + res_t_key=strdup(&(rv[0][12])); + res_t_secret=strdup(&(rv[1][19])); + printf("key: '%s'\nsecret: '%s'\n",res_t_key, res_t_secret); + } + if(rv) free(rv); + } + + if(req_url) free(req_url); + if(req_hdr) free(req_hdr); + if(http_hdr)free(http_hdr); + if(reply) free(reply); + if(res_t_key) free(res_t_key); + if(res_t_secret) free(res_t_secret); +} + +/* + * Main Test and Example Code. + */ +int main (int argc, char **argv) { + request_token_example_get(); + return (0); +} diff --git a/protocols/Twitter/oauth/tests/selftest_eran.c b/protocols/Twitter/oauth/tests/selftest_eran.c new file mode 100644 index 0000000000..7e118d48ba --- /dev/null +++ b/protocols/Twitter/oauth/tests/selftest_eran.c @@ -0,0 +1,98 @@ +/** + * @brief self-test for liboauth. + * @file selftest.c + * @author Robin Gareus <robin@gareus.org> + * + * This code contains examples provided by Eran Hammer-Lahav + * on the oauth.net mailing list. + * + * Copyright 2008 Robin Gareus <robin@gareus.org> + * + * 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. + */ + +#ifdef TEST_UNICODE +#include <locale.h> +#endif + +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <oauth.h> + +#include "commontest.h" + +int loglevel = 1; //< report each successful test + +int main (int argc, char **argv) { + int fail=0; + char *tmptst; + + if (loglevel) printf("\n *** testing liboauth against Eran's Test cases ***\n http://groups.google.com/group/oauth/browse_frm/thread/243f4da439fd1f51?hl=en\n"); + + // Eran's test-cases - http://groups.google.com/group/oauth/browse_frm/thread/243f4da439fd1f51?hl=en + fail|=test_encoding("1234=asdf=4567","1234%3Dasdf%3D4567"); + fail|=test_encoding("asdf-4354=asew-5698","asdf-4354%3Dasew-5698"); + fail|=test_encoding("erks823*43=asd&123ls%23","erks823%2A43%3Dasd%26123ls%2523"); + fail|=test_encoding("dis9$#$Js009%==","dis9%24%23%24Js009%25%3D%3D"); + fail|=test_encoding("3jd834jd9","3jd834jd9"); + fail|=test_encoding("12303202302","12303202302"); + fail|=test_encoding("taken with a 30% orange filter","taken%20with%20a%2030%25%20orange%20filter"); + fail|=test_encoding("mountain & water view","mountain%20%26%20water%20view"); + + fail|=test_request("GET", "http://example.com:80/photo" "?" + "oauth_version=1.0" + "&oauth_consumer_key=1234=asdf=4567" + "&oauth_timestamp=12303202302" + "&oauth_nonce=3jd834jd9" + "&oauth_token=asdf-4354=asew-5698" + "&oauth_signature_method=HMAC-SHA1" + "&title=taken with a 30% orange filter" + "&file=mountain \001 water view" + "&format=jpeg" + "&include=date" + "&include=aperture", + "GET&http%3A%2F%2Fexample.com%2Fphoto&file%3Dmountain%2520%2526%2520water%2520view%26format%3Djpeg%26include%3Daperture%26include%3Ddate%26oauth_consumer_key%3D1234%253Dasdf%253D4567%26oauth_nonce%3D3jd834jd9%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D12303202302%26oauth_token%3Dasdf-4354%253Dasew-5698%26oauth_version%3D1.0%26title%3Dtaken%2520with%2520a%252030%2525%2520orange%2520filter" ); + + tmptst = oauth_sign_url2( + "http://example.com:80/photo" "?" + "oauth_version=1.0" + "&oauth_timestamp=12303202302" + "&oauth_nonce=3jd834jd9" + "&title=taken with a 30% orange filter" + "&file=mountain \001 water view" + "&format=jpeg" + "&include=date" + "&include=aperture", + NULL, OA_HMAC, NULL, "1234=asdf=4567", "erks823*43=asd&123ls%23", "asdf-4354=asew-5698", "dis9$#$Js009%=="); + if (strcmp(tmptst,"http://example.com/photo?file=mountain%20%26%20water%20view&format=jpeg&include=aperture&include=date&oauth_consumer_key=1234%3Dasdf%3D4567&oauth_nonce=3jd834jd9&oauth_signature_method=HMAC-SHA1&oauth_timestamp=12303202302&oauth_token=asdf-4354%3Dasew-5698&oauth_version=1.0&title=taken%20with%20a%2030%25%20orange%20filter&oauth_signature=jMdUSR1vOr3SzNv3gZ5DDDuGirA%3D")) { + printf(" got '%s'\n expected: '%s'\n",tmptst, "http://example.com/photo?file=mountain%20%26%20water%20view&format=jpeg&include=aperture&include=date&oauth_consumer_key=1234%3Dasdf%3D4567&oauth_nonce=3jd834jd9&oauth_signature_method=HMAC-SHA1&oauth_timestamp=12303202302&oauth_token=asdf-4354%3Dasew-5698&oauth_version=1.0&title=taken%20with%20a%2030%25%20orange%20filter&oauth_signature=jMdUSR1vOr3SzNv3gZ5DDDuGirA%3D"); + fail|=1; + } else if (loglevel) printf("request signature ok.\n"); + if(tmptst) free(tmptst); + + // report + if (fail) { + printf("\n !!! One or more of Eran's Test Cases failed.\n\n"); + } else { + printf(" *** Eran's Test-Cases verified sucessfully.\n"); + } + + return (fail?1:0); +} diff --git a/protocols/Twitter/oauth/tests/selftest_other.c b/protocols/Twitter/oauth/tests/selftest_other.c new file mode 100644 index 0000000000..0bb9c714a0 --- /dev/null +++ b/protocols/Twitter/oauth/tests/selftest_other.c @@ -0,0 +1,83 @@ +/** + * @brief self-test for liboauth. + * @file selftest.c + * @author Robin Gareus <robin@gareus.org> + * + * Copyright 2009 Robin Gareus <robin@gareus.org> + * + * 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 <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <oauth.h> + +#include "commontest.h" + +int loglevel = 1; //< report each successful test + +int main (int argc, char **argv) { + int fail=0; + + if (loglevel) printf("\n *** Testing query parameter array encoding.\n"); + + fail|=test_request("GET", "http://example.com" + "?k1=v1" + "&a1[ak1]=av1" + "&a1[aa1][aak2]=aav2" + "&a1[aa1][aak1]=aav1" + "&k2=v2" + "&a1[ak2]=av2", + "GET&http%3A%2F%2Fexample.com%2F&a1%255Baa1%255D%255Baak1%255D%3Daav1%26a1%255Baa1%255D%255Baak2%255D%3Daav2%26a1%255Bak1%255D%3Dav1%26a1%255Bak2%255D%3Dav2%26k1%3Dv1%26k2%3Dv2"); + + if (loglevel) printf("\n *** Testing http://tools.ietf.org/html/rfc5849 example.\n"); + + fail|=test_request("GET", "http://example.com" + "/request?b5=%3D%253D&a3=a&c%40=&a2=r%20b" + "&c2&a3=2+q" + "&oauth_consumer_key=9djdj82h48djs9d2" + "&oauth_token=kkk9d7dh3k39sjv7" + "&oauth_signature_method=HMAC-SHA1" + "&oauth_timestamp=137131201" + "&oauth_nonce=7d8f3e4a" + "&oauth_signature=djosJKDKJSD8743243%2Fjdk33klY%3D", + "GET&http%3A%2F%2Fexample.com%2Frequest&a2%3Dr%2520b%26a3%3D2%2520q%26a3%3Da%26b5%3D%253D%25253D%26c%2540%3D%26c2%3D%26oauth_consumer_key%3D9djdj82h48djs9d2%26oauth_nonce%3D7d8f3e4a%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D137131201%26oauth_token%3Dkkk9d7dh3k39sjv7"); + + if (loglevel) printf("\n *** Testing body hash calculation.\n"); + + char *bh; + const char *teststring="Hello World!"; + bh=oauth_body_hash_data(strlen(teststring), teststring); + if (bh) { + if (strcmp(bh,"oauth_body_hash=Lve95gjOVATpfV8EL5X4nxwjKHE=")) fail|=1; + free(bh); + } else { + fail|=1; + } + + // report + if (fail) { + printf("\n !!! One or more test cases failed.\n\n"); + } else { + printf(" *** Test cases verified sucessfully.\n"); + } + + return (fail?1:0); +} diff --git a/protocols/Twitter/oauth/tests/selftest_wiki.c b/protocols/Twitter/oauth/tests/selftest_wiki.c new file mode 100644 index 0000000000..b54409b198 --- /dev/null +++ b/protocols/Twitter/oauth/tests/selftest_wiki.c @@ -0,0 +1,183 @@ +/** + * @brief self-test for liboauth. + * @file selftest.c + * @author Robin Gareus <robin@gareus.org> + * + * Copyright 2007, 2008 Robin Gareus <robin@gareus.org> + * + * This code contains examples from http://wiki.oauth.net/ may they be blessed. + * + * 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. + */ + +#ifdef TEST_UNICODE +#include <locale.h> +#endif + +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <oauth.h> + +#include "commontest.h" + +int loglevel = 1; //< report each successful test + +int main (int argc, char **argv) { + int fail=0; + char *b64d; + char *testurl, *testkey; + #ifdef TEST_UNICODE + wchar_t src[] = {0x000A, 0}; + #endif + + if (loglevel) printf("\n *** testing liboauth against http://wiki.oauth.net/TestCases (july 2008) ***\n"); + + // http://wiki.oauth.net/TestCases + fail|=test_encoding("abcABC123","abcABC123"); + fail|=test_encoding("-._~","-._~"); + fail|=test_encoding("%","%25"); + fail|=test_encoding("+","%2B"); + fail|=test_encoding("&=*","%26%3D%2A"); + + #ifdef TEST_UNICODE + src[0] = 0x000A; fail|=test_uniencoding(src,"%0A"); + src[0] = 0x0020; fail|=test_uniencoding(src,"%20"); + src[0] = 0x007F; fail|=test_uniencoding(src,"%7F"); + src[0] = 0x0080; fail|=test_uniencoding(src,"%C2%80"); + src[0] = 0x3001; fail|=test_uniencoding(src,"%E3%80%81"); + #endif + + fail|=test_normalize("name", "name="); + fail|=test_normalize("a=b", "a=b"); + fail|=test_normalize("a=b&c=d", "a=b&c=d"); + fail|=test_normalize("a=x!y&a=x+y", "a=x%20y&a=x%21y"); + fail|=test_normalize("x!y=a&x=a", "x=a&x%21y=a"); + + fail|=test_request("GET", "http://example.com/" "?" + "n=v", + // expect: + "GET&http%3A%2F%2Fexample.com%2F&n%3Dv"); + + fail|=test_request("GET", "http://example.com" "?" + "n=v", + // expect: + "GET&http%3A%2F%2Fexample.com%2F&n%3Dv"); + + fail|=test_request("POST", "https://photos.example.net/request_token" "?" + "oauth_version=1.0" + "&oauth_consumer_key=dpf43f3p2l4k3l03" + "&oauth_timestamp=1191242090" + "&oauth_nonce=hsu94j3884jdopsl" + "&oauth_signature_method=PLAINTEXT" + "&oauth_signature=ignored", + // expect: + "POST&https%3A%2F%2Fphotos.example.net%2Frequest_token&oauth_consumer_key%3Ddpf43f3p2l4k3l03%26oauth_nonce%3Dhsu94j3884jdopsl%26oauth_signature_method%3DPLAINTEXT%26oauth_timestamp%3D1191242090%26oauth_version%3D1.0"); + + fail|=test_request("GET", "http://photos.example.net/photos" "?" + "file=vacation.jpg&size=original" + "&oauth_version=1.0" + "&oauth_consumer_key=dpf43f3p2l4k3l03" + "&oauth_token=nnch734d00sl2jdk" + "&oauth_timestamp=1191242096" + "&oauth_nonce=kllo9940pd9333jh" + "&oauth_signature=ignored" + "&oauth_signature_method=HMAC-SHA1", + // expect: + "GET&http%3A%2F%2Fphotos.example.net%2Fphotos&file%3Dvacation.jpg%26oauth_consumer_key%3Ddpf43f3p2l4k3l03%26oauth_nonce%3Dkllo9940pd9333jh%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1191242096%26oauth_token%3Dnnch734d00sl2jdk%26oauth_version%3D1.0%26size%3Doriginal"); + + fail|=test_sha1("cs","","bs","egQqG5AJep5sJ7anhXju1unge2I="); + fail|=test_sha1("cs","ts","bs","VZVjXceV7JgPq/dOTnNmEfO0Fv8="); + fail|=test_sha1("kd94hf93k423kf44","pfkkdhi9sl3r4s00","GET&http%3A%2F%2Fphotos.example.net%2Fphotos&file%3Dvacation.jpg%26oauth_consumer_key%3Ddpf43f3p2l4k3l03%26oauth_nonce%3Dkllo9940pd9333jh%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1191242096%26oauth_token%3Dnnch734d00sl2jdk%26oauth_version%3D1.0%26size%3Doriginal","tR3+Ty81lMeYAr/Fid0kMTYa/WM="); + + // HMAC-SHA1 selftest. + // see http://oauth.net/core/1.0/#anchor25 + testurl = "GET&http%3A%2F%2Fphotos.example.net%2Fphotos&file%3D" + "vacation.jpg%26oauth_consumer_key%3Ddpf43f3p2l4k3l03%26oauth_nonce" + "%3Dkllo9940pd9333jh%26oauth_signature_method%3DHMAC-SHA1%26o" + "auth_timestamp%3D1191242096%26oauth_token%3Dnnch734d00sl2jdk" + "%26oauth_version%3D1.0%26size%3Doriginal"; + + testkey = "kd94hf93k423kf44&pfkkdhi9sl3r4s00"; + b64d = oauth_sign_hmac_sha1(testurl , testkey); + if (strcmp(b64d,"tR3+Ty81lMeYAr/Fid0kMTYa/WM=")) { + printf("HMAC-SHA1 signature test failed.\n"); + fail|=1; + } else if (loglevel) + printf("HMAC-SHA1 signature test successful.\n"); + free(b64d); + + // rsa-signature based on http://wiki.oauth.net/TestCases example + b64d = oauth_sign_rsa_sha1( + "GET&http%3A%2F%2Fphotos.example.net%2Fphotos&file%3Dvacaction.jpg%26oauth_consumer_key%3Ddpf43f3p2l4k3l03%26oauth_nonce%3D13917289812797014437%26oauth_signature_method%3DRSA-SHA1%26oauth_timestamp%3D1196666512%26oauth_version%3D1.0%26size%3Doriginal", + + "-----BEGIN PRIVATE KEY-----\n" + "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBALRiMLAh9iimur8V\n" + "A7qVvdqxevEuUkW4K+2KdMXmnQbG9Aa7k7eBjK1S+0LYmVjPKlJGNXHDGuy5Fw/d\n" + "7rjVJ0BLB+ubPK8iA/Tw3hLQgXMRRGRXXCn8ikfuQfjUS1uZSatdLB81mydBETlJ\n" + "hI6GH4twrbDJCR2Bwy/XWXgqgGRzAgMBAAECgYBYWVtleUzavkbrPjy0T5FMou8H\n" + "X9u2AC2ry8vD/l7cqedtwMPp9k7TubgNFo+NGvKsl2ynyprOZR1xjQ7WgrgVB+mm\n" + "uScOM/5HVceFuGRDhYTCObE+y1kxRloNYXnx3ei1zbeYLPCHdhxRYW7T0qcynNmw\n" + "rn05/KO2RLjgQNalsQJBANeA3Q4Nugqy4QBUCEC09SqylT2K9FrrItqL2QKc9v0Z\n" + "zO2uwllCbg0dwpVuYPYXYvikNHHg+aCWF+VXsb9rpPsCQQDWR9TT4ORdzoj+Nccn\n" + "qkMsDmzt0EfNaAOwHOmVJ2RVBspPcxt5iN4HI7HNeG6U5YsFBb+/GZbgfBT3kpNG\n" + "WPTpAkBI+gFhjfJvRw38n3g/+UeAkwMI2TJQS4n8+hid0uus3/zOjDySH3XHCUno\n" + "cn1xOJAyZODBo47E+67R4jV1/gzbAkEAklJaspRPXP877NssM5nAZMU0/O/NGCZ+\n" + "3jPgDUno6WbJn5cqm8MqWhW1xGkImgRk+fkDBquiq4gPiT898jusgQJAd5Zrr6Q8\n" + "AO/0isr/3aa6O6NLQxISLKcPDk2NOccAfS/xOtfOz4sJYM3+Bs4Io9+dZGSDCA54\n" + "Lw03eHTNQghS0A==\n" + "-----END PRIVATE KEY-----"); + + if (strcmp(b64d,"jvTp/wX1TYtByB1m+Pbyo0lnCOLIsyGCH7wke8AUs3BpnwZJtAuEJkvQL2/9n4s5wUmUl4aCI4BwpraNx4RtEXMe5qg5T1LVTGliMRpKasKsW//e+RinhejgCuzoH26dyF8iY2ZZ/5D1ilgeijhV/vBka5twt399mXwaYdCwFYE=")) { + printf("RSA-SHA1 signature test failed.\n"); + fail|=1; + } else if (loglevel) + printf("RSA-SHA1 signature test successful.\n"); + free(b64d); + + if (oauth_verify_rsa_sha1( + "GET&http%3A%2F%2Fphotos.example.net%2Fphotos&file%3Dvacaction.jpg%26oauth_consumer_key%3Ddpf43f3p2l4k3l03%26oauth_nonce%3D13917289812797014437%26oauth_signature_method%3DRSA-SHA1%26oauth_timestamp%3D1196666512%26oauth_version%3D1.0%26size%3Doriginal", + + "-----BEGIN CERTIFICATE-----\n" + "MIIBpjCCAQ+gAwIBAgIBATANBgkqhkiG9w0BAQUFADAZMRcwFQYDVQQDDA5UZXN0\n" + "IFByaW5jaXBhbDAeFw03MDAxMDEwODAwMDBaFw0zODEyMzEwODAwMDBaMBkxFzAV\n" + "BgNVBAMMDlRlc3QgUHJpbmNpcGFsMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKB\n" + "gQC0YjCwIfYoprq/FQO6lb3asXrxLlJFuCvtinTF5p0GxvQGu5O3gYytUvtC2JlY\n" + "zypSRjVxwxrsuRcP3e641SdASwfrmzyvIgP08N4S0IFzEURkV1wp/IpH7kH41Etb\n" + "mUmrXSwfNZsnQRE5SYSOhh+LcK2wyQkdgcMv11l4KoBkcwIDAQABMA0GCSqGSIb3\n" + "DQEBBQUAA4GBAGZLPEuJ5SiJ2ryq+CmEGOXfvlTtEL2nuGtr9PewxkgnOjZpUy+d\n" + "4TvuXJbNQc8f4AMWL/tO9w0Fk80rWKp9ea8/df4qMq5qlFWlx6yOLQxumNOmECKb\n" + "WpkUQDIDJEoFUzKMVuJf4KO/FJ345+BNLGgbJ6WujreoM1X/gYfdnJ/J\n" + "-----END CERTIFICATE-----\n", + "jvTp/wX1TYtByB1m+Pbyo0lnCOLIsyGCH7wke8AUs3BpnwZJtAuEJkvQL2/9n4s5wUmUl4aCI4BwpraNx4RtEXMe5qg5T1LVTGliMRpKasKsW//e+RinhejgCuzoH26dyF8iY2ZZ/5D1ilgeijhV/vBka5twt399mXwaYdCwFYE=") + != 1) { + printf("RSA-SHA1 verify-signature test failed.\n"); + fail|=1; + } else if (loglevel) + printf("RSA-SHA1 verify-signature test successful.\n"); + + // report + if (fail) { + printf("\n !!! One or more tests from http://wiki.oauth.net/TestCases failed.\n\n"); + } else { + printf(" *** http://wiki.oauth.net/TestCases verified sucessfully.\n"); + } + + return (fail?1:0); +} diff --git a/protocols/Twitter/proto.cpp b/protocols/Twitter/proto.cpp index 44bd6a3ebc..a65ddf978b 100644 --- a/protocols/Twitter/proto.cpp +++ b/protocols/Twitter/proto.cpp @@ -3,19 +3,18 @@ Copyright © 2009 Jim Porter This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
-the Free Software Foundation, either version 2 of the License, or
+the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
-This program is distributed in the hope that it will be useful,
+This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
-along with this program. If not, see <http://www.gnu.org/licenses/>.
+along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
-#include "common.h"
#include "proto.h"
#include "utility.h"
@@ -30,31 +29,31 @@ along with this program. If not, see <http://www.gnu.org/licenses/>. #include <ctime>
#include <direct.h>
-TwitterProto::TwitterProto(const char *proto_name, const TCHAR *username)
+TwitterProto::TwitterProto(const char *proto_name,const TCHAR *username)
{
m_szProtoName = mir_strdup (proto_name);
m_szModuleName = mir_strdup (proto_name);
m_tszUserName = mir_tstrdup(username);
- CreateProtoService(m_szModuleName, PS_CREATEACCMGRUI,
- &TwitterProto::SvcCreateAccMgrUI, this);
- CreateProtoService(m_szModuleName, PS_GETNAME, &TwitterProto::GetName, this);
- CreateProtoService(m_szModuleName, PS_GETSTATUS, &TwitterProto::GetStatus, this);
+ CreateProtoService(m_szModuleName,PS_CREATEACCMGRUI,
+ &TwitterProto::SvcCreateAccMgrUI,this);
+ CreateProtoService(m_szModuleName,PS_GETNAME, &TwitterProto::GetName, this);
+ CreateProtoService(m_szModuleName,PS_GETSTATUS,&TwitterProto::GetStatus, this);
- CreateProtoService(m_szModuleName, PS_JOINCHAT, &TwitterProto::OnJoinChat, this);
- CreateProtoService(m_szModuleName, PS_LEAVECHAT, &TwitterProto::OnLeaveChat, this);
+ CreateProtoService(m_szModuleName,PS_JOINCHAT, &TwitterProto::OnJoinChat, this);
+ CreateProtoService(m_szModuleName,PS_LEAVECHAT,&TwitterProto::OnLeaveChat,this);
- CreateProtoService(m_szModuleName, PS_GETMYAVATAR, &TwitterProto::GetAvatar, this);
- CreateProtoService(m_szModuleName, PS_SETMYAVATAR, &TwitterProto::SetAvatar, this);
+ CreateProtoService(m_szModuleName,PS_GETMYAVATAR,&TwitterProto::GetAvatar,this);
+ CreateProtoService(m_szModuleName,PS_SETMYAVATAR,&TwitterProto::SetAvatar,this);
- HookProtoEvent(ME_DB_CONTACT_DELETED, &TwitterProto::OnContactDeleted, this);
- HookProtoEvent(ME_CLIST_PREBUILDSTATUSMENU, &TwitterProto::OnBuildStatusMenu, this);
- HookProtoEvent(ME_OPT_INITIALISE, &TwitterProto::OnOptionsInit, this);
+ HookProtoEvent(ME_DB_CONTACT_DELETED, &TwitterProto::OnContactDeleted, this);
+ HookProtoEvent(ME_CLIST_PREBUILDSTATUSMENU, &TwitterProto::OnBuildStatusMenu, this);
+ HookProtoEvent(ME_OPT_INITIALISE, &TwitterProto::OnOptionsInit, this);
char *profile = Utils_ReplaceVars("%miranda_avatarcache%");
def_avatar_folder_ = std::string(profile)+"\\"+m_szModuleName;
mir_free(profile);
- hAvatarFolder_ = FoldersRegisterCustomPath(m_szModuleName, "Avatars",
+ hAvatarFolder_ = FoldersRegisterCustomPath(m_szModuleName,"Avatars",
def_avatar_folder_.c_str());
// Initialize hotkeys
@@ -65,19 +64,41 @@ TwitterProto::TwitterProto(const char *proto_name, const TCHAR *username) hkd.pszService = text;
hkd.pszSection = m_szModuleName; // Section title; TODO: use username?
- mir_snprintf(text, SIZEOF(text), "%s/Tweet", m_szModuleName);
+ mir_snprintf(text,SIZEOF(text),"%s/Tweet",m_szModuleName);
hkd.pszDescription = "Send Tweet";
- CallService(MS_HOTKEY_REGISTER, 0, (LPARAM)&hkd);
+ CallService(MS_HOTKEY_REGISTER, 0, (LPARAM)&hkd);
- signon_lock_ = CreateMutex(0, false, 0);
- avatar_lock_ = CreateMutex(0, false, 0);
- twitter_lock_ = CreateMutex(0, false, 0);
+ signon_lock_ = CreateMutex(0,false,0);
+ avatar_lock_ = CreateMutex(0,false,0);
+ twitter_lock_ = CreateMutex(0,false,0);
SetAllContactStatuses(ID_STATUS_OFFLINE); // In case we crashed last time
+
+ // set Tokens and stuff
+
+ //mirandas keys
+ ConsumerKey = OAUTH_CONSUMER_KEY;
+ ConsumerSecret = OAUTH_CONSUMER_SECRET;
+
+ //codebrook's keys
+ //wstring ConsumerKey = L"T6XLGzrkfsJAgU59dbIjSA";
+ //wstring ConsumerSecret = L"xsvm2NAksjsJGw63RMWAtec3Lz5uiBusfVt48gbdKLg";
+
+ AccessUrl = L"http://twitter.com/oauth/access_token";
+ AuthorizeUrl = L"http://twitter.com/oauth/authorize?oauth_token=%s";
+ RequestUrl = L"http://twitter.com/oauth/request_token?some_other_parameter=hello&another_one=goodbye#meep"; // threw in some parameters for fun, and to test UrlGetQuery
+ UserTimelineUrl = L"http://twitter.com/statuses/user_timeline.json";
}
TwitterProto::~TwitterProto()
{
+ twit_.Disconnect();
+
+ if(hNetlib_)
+ Netlib_CloseHandle(hNetlib_);
+ if(hAvatarNetlib_)
+ Netlib_CloseHandle(hAvatarNetlib_);
+
CloseHandle(twitter_lock_);
CloseHandle(avatar_lock_);
CloseHandle(signon_lock_);
@@ -85,16 +106,11 @@ TwitterProto::~TwitterProto() mir_free(m_szProtoName);
mir_free(m_szModuleName);
mir_free(m_tszUserName);
-
- if (hNetlib_)
- Netlib_CloseHandle(hNetlib_);
- if (hAvatarNetlib_)
- Netlib_CloseHandle(hAvatarNetlib_);
}
// *************************
-DWORD TwitterProto::GetCaps(int type, HANDLE hContact)
+DWORD TwitterProto::GetCaps(int type,HANDLE hContact)
{
switch(type)
{
@@ -108,7 +124,7 @@ DWORD TwitterProto::GetCaps(int type, HANDLE hContact) case PFLAGNUM_4:
return PF4_NOCUSTOMAUTH | PF4_IMSENDUTF | PF4_AVATARS;
case PFLAG_MAXLENOFMESSAGE:
- return 140;
+ return 159; // 140 + <max length of a users name (15 apparently)> + 4 ("RT @"). this allows for the new style retweets
case PFLAG_UNIQUEIDTEXT:
return (int) "Username";
case PFLAG_UNIQUEIDSETTING:
@@ -119,9 +135,9 @@ DWORD TwitterProto::GetCaps(int type, HANDLE hContact) HICON TwitterProto::GetIcon(int index)
{
- if (LOWORD(index) == PLI_PROTOCOL)
+ if(LOWORD(index) == PLI_PROTOCOL)
{
- HICON ico = (HICON)CallService(MS_SKIN2_GETICON, 0, (LPARAM)"Twitter_twitter");
+ HICON ico = (HICON)CallService(MS_SKIN2_GETICON,0,(LPARAM)"Twitter_twitter");
return CopyIcon(ico);
}
else
@@ -130,48 +146,47 @@ HICON TwitterProto::GetIcon(int index) // *************************
-int TwitterProto::RecvMsg(HANDLE hContact, PROTORECVEVENT *pre)
+int TwitterProto::RecvMsg(HANDLE hContact,PROTORECVEVENT *pre)
{
- CCSDATA ccs = { hContact, PSR_MESSAGE, 0, reinterpret_cast<LPARAM>(pre) };
- return CallService(MS_PROTO_RECVMSG, 0, reinterpret_cast<LPARAM>(&ccs));
+ CCSDATA ccs = { hContact,PSR_MESSAGE,0,reinterpret_cast<LPARAM>(pre) };
+ return CallService(MS_PROTO_RECVMSG,0,reinterpret_cast<LPARAM>(&ccs));
}
// *************************
struct send_direct
{
- send_direct(HANDLE hContact, const std::tstring &msg) : hContact(hContact), msg(msg) {}
+ send_direct(HANDLE hContact,const std::string &msg) : hContact(hContact),msg(msg) {}
HANDLE hContact;
- std::tstring msg;
+ std::string msg;
};
void TwitterProto::SendSuccess(void *p)
{
- if (p == 0)
+ if(p == 0)
return;
send_direct *data = static_cast<send_direct*>(p);
DBVARIANT dbv;
- if ( !DBGetContactSettingTString(data->hContact, m_szModuleName, TWITTER_KEY_UN, &dbv))
+ if( !DBGetContactSettingString(data->hContact,m_szModuleName,TWITTER_KEY_UN,&dbv) )
{
ScopedLock s(twitter_lock_);
- twit_.send_direct(dbv.ptszVal, data->msg);
+ twit_.send_direct(dbv.pszVal,data->msg);
- ProtoBroadcastAck(m_szModuleName, data->hContact, ACKTYPE_MESSAGE, ACKRESULT_SUCCESS,
- (HANDLE)1, 0);
+ ProtoBroadcastAck(m_szModuleName,data->hContact,ACKTYPE_MESSAGE,ACKRESULT_SUCCESS,
+ (HANDLE)1,0);
DBFreeVariant(&dbv);
}
delete data;
}
-int TwitterProto::SendMsg(HANDLE hContact, int flags, const char *msg)
+int TwitterProto::SendMsg(HANDLE hContact,int flags,const char *msg)
{
- if (m_iStatus != ID_STATUS_ONLINE)
+ if(m_iStatus != ID_STATUS_ONLINE)
return 0;
- std::tstring tMsg = _A2T(msg);
- ForkThread(&TwitterProto::SendSuccess, this, new send_direct(hContact, tMsg));
+ ForkThread(&TwitterProto::SendSuccess, this,new send_direct(hContact,msg));
return 1;
}
@@ -180,29 +195,40 @@ int TwitterProto::SendMsg(HANDLE hContact, int flags, const char *msg) int TwitterProto::SetStatus(int new_status)
{
int old_status = m_iStatus;
- if (new_status == m_iStatus)
+ if(new_status == m_iStatus)
return 0;
m_iDesiredStatus = new_status;
-
- if (new_status == ID_STATUS_ONLINE)
+ // 40072 - 40080 are the "online" statuses, basically every status except offline. see statusmodes.h
+ if(new_status >= 40072 && new_status <= 40080)
{
- if (old_status == ID_STATUS_CONNECTING)
+
+ m_iDesiredStatus = ID_STATUS_ONLINE; //i think i have to set this so it forces the twitter proto to be online (and not away, DND, etc)
+
+ // if we're already connecting and they want to go online, BAIL! we're already trying to connect you dumbass
+ if(old_status == ID_STATUS_CONNECTING)
return 0;
+ // if we're already connected, and we change to another connected status, don't try and reconnect!
+ if (old_status >= 40072 && old_status <= 40080)
+ return 0;
+
+ // i think here we tell the proto interface struct that we're connecting, just so it knows
m_iStatus = ID_STATUS_CONNECTING;
- ProtoBroadcastAck(m_szModuleName, 0, ACKTYPE_STATUS, ACKRESULT_SUCCESS,
- (HANDLE)old_status, m_iStatus);
+ // ok.. here i think we're telling the core that this protocol something.. but why?
+ ProtoBroadcastAck(m_szModuleName,0,ACKTYPE_STATUS,ACKRESULT_SUCCESS,
+ (HANDLE)old_status,m_iStatus);
- ForkThread(&TwitterProto::SignOn, this);
+ ForkThread(&TwitterProto::SignOn,this);
}
- else if (new_status == ID_STATUS_OFFLINE)
+ else if(new_status == ID_STATUS_OFFLINE)
{
+ twit_.Disconnect();
m_iStatus = m_iDesiredStatus;
SetAllContactStatuses(ID_STATUS_OFFLINE);
- ProtoBroadcastAck(m_szModuleName, 0, ACKTYPE_STATUS, ACKRESULT_SUCCESS,
- (HANDLE)old_status, m_iStatus);
+ ProtoBroadcastAck(m_szModuleName,0,ACKTYPE_STATUS,ACKRESULT_SUCCESS,
+ (HANDLE)old_status,m_iStatus);
}
return 0;
@@ -210,13 +236,13 @@ int TwitterProto::SetStatus(int new_status) // *************************
-int TwitterProto::OnEvent(PROTOEVENTTYPE event, WPARAM wParam, LPARAM lParam)
+int TwitterProto::OnEvent(PROTOEVENTTYPE event,WPARAM wParam,LPARAM lParam)
{
switch(event)
{
- case EV_PROTO_ONLOAD: return OnModulesLoaded(wParam, lParam);
- case EV_PROTO_ONEXIT: return OnPreShutdown (wParam, lParam);
- case EV_PROTO_ONOPTIONS: return OnOptionsInit (wParam, lParam);
+ case EV_PROTO_ONLOAD: return OnModulesLoaded(wParam,lParam);
+ case EV_PROTO_ONEXIT: return OnPreShutdown (wParam,lParam);
+ case EV_PROTO_ONOPTIONS: return OnOptionsInit (wParam,lParam);
}
return 1;
@@ -224,58 +250,63 @@ int TwitterProto::OnEvent(PROTOEVENTTYPE event, WPARAM wParam, LPARAM lParam) // *************************
-int TwitterProto::SvcCreateAccMgrUI(WPARAM wParam, LPARAM lParam)
+int TwitterProto::SvcCreateAccMgrUI(WPARAM wParam,LPARAM lParam)
{
- return (int)CreateDialogParam(g_hInstance, MAKEINTRESOURCE(IDD_TWITTERACCOUNT),
- (HWND)lParam, first_run_dialog, (LPARAM)this );
+ return (int)CreateDialogParam(g_hInstance,MAKEINTRESOURCE(IDD_TWITTERACCOUNT),
+ (HWND)lParam, first_run_dialog, (LPARAM)this );
}
-int TwitterProto::GetName(WPARAM wParam, LPARAM lParam)
+int TwitterProto::GetName(WPARAM wParam,LPARAM lParam)
{
- lstrcpynA(reinterpret_cast<char*>(lParam), m_szProtoName, wParam);
+ lstrcpynA(reinterpret_cast<char*>(lParam),m_szProtoName,wParam);
return 0;
}
-int TwitterProto::GetStatus(WPARAM wParam, LPARAM lParam)
+int TwitterProto::GetStatus(WPARAM wParam,LPARAM lParam)
{
return m_iStatus;
}
-int TwitterProto::ReplyToTweet(WPARAM wParam, LPARAM lParam)
+int TwitterProto::ReplyToTweet(WPARAM wParam,LPARAM lParam)
{
// TODO: support replying to tweets instead of just users
HANDLE hContact = reinterpret_cast<HANDLE>(wParam);
- HWND hDlg = CreateDialogParam(g_hInstance, MAKEINTRESOURCE(IDD_TWEET),
- (HWND)0, tweet_proc, reinterpret_cast<LPARAM>(this));
+ HWND hDlg = CreateDialogParam(g_hInstance,MAKEINTRESOURCE(IDD_TWEET),
+ (HWND)0,tweet_proc,reinterpret_cast<LPARAM>(this));
DBVARIANT dbv;
- if ( !DBGetContactSettingTString(hContact, m_szModuleName, TWITTER_KEY_UN, &dbv)) {
- SendMessage(hDlg, WM_SETREPLY, reinterpret_cast<WPARAM>(dbv.ptszVal), 0);
+ if( !DBGetContactSettingString(hContact,m_szModuleName,TWITTER_KEY_UN,&dbv) )
+ {
+ SendMessage(hDlg,WM_SETREPLY,reinterpret_cast<WPARAM>(dbv.pszVal),0);
DBFreeVariant(&dbv);
}
- ShowWindow(hDlg, SW_SHOW);
+ ShowWindow(hDlg,SW_SHOW);
return 0;
}
-int TwitterProto::VisitHomepage(WPARAM wParam, LPARAM lParam)
+int TwitterProto::VisitHomepage(WPARAM wParam,LPARAM lParam)
{
HANDLE hContact = reinterpret_cast<HANDLE>(wParam);
DBVARIANT dbv;
- if ( !DBGetContactSettingString(hContact, m_szModuleName, "Homepage", &dbv)) {
- CallService(MS_UTILS_OPENURL, 1, reinterpret_cast<LPARAM>(dbv.pszVal));
+ if( !DBGetContactSettingString(hContact,m_szModuleName,"Homepage",&dbv) )
+ {
+ CallService(MS_UTILS_OPENURL,1,reinterpret_cast<LPARAM>(dbv.pszVal));
DBFreeVariant(&dbv);
}
- else {
+ else
+ {
// TODO: remove this
- if ( !DBGetContactSettingString(hContact, m_szModuleName, TWITTER_KEY_UN, &dbv)) {
- std::string url = profile_base_url(twit_.get_base_url()) + http::url_encode(dbv.pszVal);
- DBWriteContactSettingString(hContact, m_szModuleName, "Homepage", url.c_str());
+ if( !DBGetContactSettingString(hContact,m_szModuleName,TWITTER_KEY_UN,&dbv) )
+ {
+ std::string url = profile_base_url(twit_.get_base_url())+
+ http::url_encode(dbv.pszVal);
+ DBWriteContactSettingString(hContact,m_szModuleName,"Homepage",url.c_str());
- CallService(MS_UTILS_OPENURL, 1, reinterpret_cast<LPARAM>(url.c_str()));
+ CallService(MS_UTILS_OPENURL,1,reinterpret_cast<LPARAM>(url.c_str()));
DBFreeVariant(&dbv);
}
}
@@ -285,7 +316,7 @@ int TwitterProto::VisitHomepage(WPARAM wParam, LPARAM lParam) // *************************
-int TwitterProto::OnBuildStatusMenu(WPARAM wParam, LPARAM lParam)
+int TwitterProto::OnBuildStatusMenu(WPARAM wParam,LPARAM lParam)
{
HGENMENU hRoot = pcli->pfnGetProtocolMenu(m_szModuleName);
if (hRoot == NULL)
@@ -294,7 +325,7 @@ int TwitterProto::OnBuildStatusMenu(WPARAM wParam, LPARAM lParam) CLISTMENUITEM mi = {sizeof(mi)};
char text[200];
- strcpy(text, m_szModuleName);
+ strcpy(text,m_szModuleName);
char *tDest = text+strlen(text);
mi.pszService = text;
@@ -303,21 +334,22 @@ int TwitterProto::OnBuildStatusMenu(WPARAM wParam, LPARAM lParam) mi.position = 1001;
HANDLE m_hMenuRoot = reinterpret_cast<HGENMENU>( CallService(
- MS_CLIST_ADDSTATUSMENUITEM, 0, reinterpret_cast<LPARAM>(&mi)));
+ MS_CLIST_ADDSTATUSMENUITEM,0,reinterpret_cast<LPARAM>(&mi)) );
+ // TODO: Disable this menu item when offline
// "Send Tweet..."
- CreateProtoService(m_szModuleName, "/Tweet", &TwitterProto::OnTweet, this);
- strcpy(tDest, "/Tweet");
+ CreateProtoService(m_szModuleName,"/Tweet",&TwitterProto::OnTweet,this);
+ strcpy(tDest,"/Tweet");
mi.pszName = LPGEN("Send Tweet...");
mi.popupPosition = 200001;
mi.icolibItem = GetIconHandle("tweet");
HANDLE m_hMenuBookmarks = reinterpret_cast<HGENMENU>( CallService(
- MS_CLIST_ADDSTATUSMENUITEM, 0, reinterpret_cast<LPARAM>(&mi)));
+ MS_CLIST_ADDSTATUSMENUITEM,0,reinterpret_cast<LPARAM>(&mi)) );
return 0;
}
-int TwitterProto::OnOptionsInit(WPARAM wParam, LPARAM lParam)
+int TwitterProto::OnOptionsInit(WPARAM wParam,LPARAM lParam)
{
OPTIONSDIALOGPAGE odp = {sizeof(odp)};
odp.position = 271828;
@@ -330,31 +362,31 @@ int TwitterProto::OnOptionsInit(WPARAM wParam, LPARAM lParam) odp.ptszTab = LPGENT("Basic");
odp.pszTemplate = MAKEINTRESOURCEA(IDD_OPTIONS);
odp.pfnDlgProc = options_proc;
- CallService(MS_OPT_ADDPAGE, wParam, (LPARAM)&odp);
+ CallService(MS_OPT_ADDPAGE,wParam,(LPARAM)&odp);
- if (ServiceExists(MS_POPUP_ADDPOPUPT))
+ if(ServiceExists(MS_POPUP_ADDPOPUPT))
{
odp.ptszTab = LPGENT("Popups");
odp.pszTemplate = MAKEINTRESOURCEA(IDD_OPTIONS_POPUPS);
odp.pfnDlgProc = popup_options_proc;
- CallService(MS_OPT_ADDPAGE, wParam, (LPARAM)&odp);
+ CallService(MS_OPT_ADDPAGE,wParam,(LPARAM)&odp);
}
return 0;
}
-int TwitterProto::OnTweet(WPARAM wParam, LPARAM lParam)
+int TwitterProto::OnTweet(WPARAM wParam,LPARAM lParam)
{
- if (m_iStatus != ID_STATUS_ONLINE)
+ if(m_iStatus != ID_STATUS_ONLINE)
return 1;
- HWND hDlg = CreateDialogParam(g_hInstance, MAKEINTRESOURCE(IDD_TWEET),
- (HWND)0, tweet_proc, reinterpret_cast<LPARAM>(this));
- ShowWindow(hDlg, SW_SHOW);
+ HWND hDlg = CreateDialogParam(g_hInstance,MAKEINTRESOURCE(IDD_TWEET),
+ (HWND)0,tweet_proc,reinterpret_cast<LPARAM>(this));
+ ShowWindow(hDlg,SW_SHOW);
return 0;
}
-int TwitterProto::OnModulesLoaded(WPARAM wParam, LPARAM lParam)
+int TwitterProto::OnModulesLoaded(WPARAM wParam,LPARAM lParam)
{
TCHAR descr[512];
NETLIBUSER nlu = {sizeof(nlu)};
@@ -362,29 +394,29 @@ int TwitterProto::OnModulesLoaded(WPARAM wParam, LPARAM lParam) nlu.szSettingsModule = m_szModuleName;
// Create standard network connection
- mir_sntprintf(descr, SIZEOF(descr), TranslateT("%s server connection"), m_tszUserName);
+ mir_sntprintf(descr,SIZEOF(descr),TranslateT("%s server connection"),m_tszUserName);
nlu.ptszDescriptiveName = descr;
- hNetlib_ = (HANDLE)CallService(MS_NETLIB_REGISTERUSER, 0, (LPARAM)&nlu);
- if (hNetlib_ == 0)
- MessageBoxA(0, "Unable to get Netlib connection for Twitter", "", 0);
+ hNetlib_ = (HANDLE)CallService(MS_NETLIB_REGISTERUSER,0,(LPARAM)&nlu);
+ if(hNetlib_ == 0)
+ MessageBoxA(0,"Unable to get Netlib connection for Twitter","",0);
// Create avatar network connection (TODO: probably remove this)
char module[512];
- mir_snprintf(module, SIZEOF(module), "%sAv", m_szModuleName);
+ mir_snprintf(module,SIZEOF(module),"%sAv",m_szModuleName);
nlu.szSettingsModule = module;
- mir_sntprintf(descr, SIZEOF(descr), TranslateT("%s avatar connection"), m_tszUserName);
+ mir_sntprintf(descr,SIZEOF(descr),TranslateT("%s avatar connection"),m_tszUserName);
nlu.ptszDescriptiveName = descr;
- hAvatarNetlib_ = (HANDLE)CallService(MS_NETLIB_REGISTERUSER, 0, (LPARAM)&nlu);
- if (hAvatarNetlib_ == 0)
- MessageBoxA(0, "Unable to get avatar Netlib connection for Twitter", "", 0);
+ hAvatarNetlib_ = (HANDLE)CallService(MS_NETLIB_REGISTERUSER,0,(LPARAM)&nlu);
+ if(hAvatarNetlib_ == 0)
+ MessageBoxA(0,"Unable to get avatar Netlib connection for Twitter","",0);
twit_.set_handle(hNetlib_);
GCREGISTER gcr = {sizeof(gcr)};
gcr.pszModule = m_szModuleName;
gcr.pszModuleDispName = m_szModuleName;
- gcr.iMaxText = 140;
- CallService(MS_GC_REGISTER, 0, reinterpret_cast<LPARAM>(&gcr));
+ gcr.iMaxText = 159;
+ CallService(MS_GC_REGISTER,0,reinterpret_cast<LPARAM>(&gcr));
if (ServiceExists(MS_HISTORYEVENTS_REGISTER))
{
@@ -399,7 +431,7 @@ int TwitterProto::OnModulesLoaded(WPARAM wParam, LPARAM lParam) | HISTORYEVENTS_FLAG_EXPECT_CONTACT_NAME_BEFORE
// Not sure: | HISTORYEVENTS_FLAG_FLASH_MSG_WINDOW
| HISTORYEVENTS_REGISTERED_IN_ICOLIB;
- CallService(MS_HISTORYEVENTS_REGISTER, (WPARAM) &heh, 0);
+ CallService(MS_HISTORYEVENTS_REGISTER, (WPARAM) &heh, 0);
}
else
{
@@ -408,74 +440,110 @@ int TwitterProto::OnModulesLoaded(WPARAM wParam, LPARAM lParam) evt.module = m_szModuleName;
evt.descr = "Tweet";
evt.flags = DETF_HISTORY | DETF_MSGWINDOW;
- CallService(MS_DB_EVENT_REGISTERTYPE, 0, reinterpret_cast<LPARAM>(&evt));
+ CallService(MS_DB_EVENT_REGISTERTYPE,0,reinterpret_cast<LPARAM>(&evt));
}
return 0;
}
-int TwitterProto::OnPreShutdown(WPARAM wParam, LPARAM lParam)
+int TwitterProto::OnPreShutdown(WPARAM wParam,LPARAM lParam)
{
Netlib_Shutdown(hNetlib_);
Netlib_Shutdown(hAvatarNetlib_);
return 0;
}
-int TwitterProto::OnPrebuildContactMenu(WPARAM wParam, LPARAM lParam)
+int TwitterProto::OnPrebuildContactMenu(WPARAM wParam,LPARAM lParam)
{
HANDLE hContact = reinterpret_cast<HANDLE>(wParam);
- if (IsMyContact(hContact))
+ if(IsMyContact(hContact))
ShowContactMenus(true);
return 0;
}
-void TwitterProto::ShowPopup(const wchar_t *text)
+int TwitterProto::ShowPinDialog()
+{
+ HWND hDlg = (HWND)DialogBoxParam(g_hInstance,MAKEINTRESOURCE(IDD_TWITTERPIN),
+ (HWND)0,pin_proc,reinterpret_cast<LPARAM>(this));
+ ShowWindow(hDlg,SW_SHOW);
+ return 0;
+}
+
+void TwitterProto::ShowPopup(const wchar_t *text, int Error)
{
POPUPDATAT popup = {};
- _sntprintf(popup.lptzContactName, MAX_CONTACTNAME, TranslateT("%s Protocol"), m_tszUserName);
- wcs_to_tcs(CP_UTF8, text, popup.lptzText, MAX_SECONDLINE);
+ _sntprintf(popup.lptzContactName,MAX_CONTACTNAME,TranslateT("%s Protocol"),m_tszUserName);
+ wcs_to_tcs(CP_UTF8,text,popup.lptzText,MAX_SECONDLINE);
+
+ if (Error) {
+ popup.iSeconds = -1;
+ popup.colorBack = 0x000000FF;
+ popup.colorText = 0x00FFFFFF;
+ }
- if (ServiceExists(MS_POPUP_ADDPOPUPT))
- CallService(MS_POPUP_ADDPOPUPT, reinterpret_cast<WPARAM>(&popup), 0);
+ if(ServiceExists(MS_POPUP_ADDPOPUPT))
+ CallService(MS_POPUP_ADDPOPUPT,reinterpret_cast<WPARAM>(&popup),0);
else
- MessageBox(0, popup.lptzText, popup.lptzContactName, 0);
+ MessageBox(0,popup.lptzText,popup.lptzContactName,0);
}
-void TwitterProto::ShowPopup(const char *text)
+void TwitterProto::ShowPopup(const char *text, int Error)
{
POPUPDATAT popup = {};
- _sntprintf(popup.lptzContactName, MAX_CONTACTNAME, TranslateT("%s Protocol"), m_tszUserName);
- mbcs_to_tcs(CP_UTF8, text, popup.lptzText, MAX_SECONDLINE);
+ _sntprintf(popup.lptzContactName,MAX_CONTACTNAME,TranslateT("%s Protocol"),m_tszUserName);
+ mbcs_to_tcs(CP_UTF8,text,popup.lptzText,MAX_SECONDLINE);
+ if (Error) {
+ popup.iSeconds = -1;
+ popup.colorBack = 0x000000FF;
+ popup.colorText = 0x00FFFFFF;
+ }
- if (ServiceExists(MS_POPUP_ADDPOPUPT))
- CallService(MS_POPUP_ADDPOPUPT, reinterpret_cast<WPARAM>(&popup), 0);
+ if(ServiceExists(MS_POPUP_ADDPOPUPT))
+ CallService(MS_POPUP_ADDPOPUPT,reinterpret_cast<WPARAM>(&popup),0);
else
- MessageBox(0, popup.lptzText, popup.lptzContactName, 0);
+ MessageBox(0,popup.lptzText,popup.lptzContactName,0);
}
-int TwitterProto::LOG(const char *fmt, ...)
+int TwitterProto::LOG(const char *fmt,...)
{
va_list va;
char text[1024];
if (!hNetlib_)
return 0;
- va_start(va, fmt);
- mir_vsnprintf(text, sizeof(text), fmt, va);
+ va_start(va,fmt);
+ mir_vsnprintf(text,sizeof(text),fmt,va);
va_end(va);
- return CallService(MS_NETLIB_LOG, (WPARAM)hNetlib_, (LPARAM)text);
+ return CallService(MS_NETLIB_LOG,(WPARAM)hNetlib_,(LPARAM)text);
+}
+
+int TwitterProto::WLOG(const char* first, const wstring last)
+{
+ char *str1 = new char[1024*96];
+ sprintf(str1,"%ls", last.c_str());
+
+ return LOG(first, str1);
}
-// TODO: the more I think about it, the more I think all twit.* methods should
+// TODO: the more I think about it, the more I think all twit.* methods should
// be in MessageLoop
void TwitterProto::SendTweetWorker(void *p)
{
- if (p == 0)
+ if(p == 0)
return;
+ char *text = static_cast<char*>(p);
- TCHAR *text = static_cast<TCHAR*>(p);
+
+
+ if (strlen(text) > 140) { // looks like the chat max outgoing msg thing doesn't work, so i'll do it here.
+ char * errorPopup = new char[280]; // i hate c strings ... i should use std::string here. why did i use char* ??? need to delete[] or use std::String
+ sprintf(errorPopup, "Don't be crazy! Everyone knows the max tweet size is 140, and you're trying to fit %d chars in there?", strlen(text));
+ ShowPopup(errorPopup, 1);
+ delete[] errorPopup;
+ return;
+ }
ScopedLock s(twitter_lock_);
twit_.set_status(text);
@@ -485,25 +553,25 @@ void TwitterProto::SendTweetWorker(void *p) void TwitterProto::UpdateSettings()
{
- if (db_byte_get(0, m_szModuleName, TWITTER_KEY_CHATFEED, 0))
+ if(db_byte_get(0,m_szModuleName,TWITTER_KEY_CHATFEED,0))
{
- if (!in_chat_)
- OnJoinChat(0, 0);
+ if(!in_chat_)
+ OnJoinChat(0,0);
}
else
{
- if (in_chat_)
- OnLeaveChat(0, 0);
+ if(in_chat_)
+ OnLeaveChat(0,0);
- for(HANDLE hContact = (HANDLE)CallService(MS_DB_CONTACT_FINDFIRST, 0, 0);
+ for(HANDLE hContact = (HANDLE)CallService(MS_DB_CONTACT_FINDFIRST,0,0);
hContact;
- hContact = (HANDLE)CallService(MS_DB_CONTACT_FINDNEXT, (WPARAM)hContact, 0))
+ hContact = (HANDLE)CallService(MS_DB_CONTACT_FINDNEXT,(WPARAM)hContact,0) )
{
- if (!IsMyContact(hContact, true))
+ if(!IsMyContact(hContact,true))
continue;
- if (db_byte_get(hContact, m_szModuleName, "ChatRoom", 0))
- CallService(MS_DB_CONTACT_DELETE, reinterpret_cast<WPARAM>(hContact), 0);
+ if(db_byte_get(hContact,m_szModuleName,"ChatRoom",0))
+ CallService(MS_DB_CONTACT_DELETE,reinterpret_cast<WPARAM>(hContact),0);
}
}
}
@@ -511,18 +579,18 @@ void TwitterProto::UpdateSettings() std::string TwitterProto::GetAvatarFolder()
{
char path[MAX_PATH];
- if (hAvatarFolder_ && FoldersGetCustomPath(hAvatarFolder_, path, sizeof(path), "") == 0)
+ if(hAvatarFolder_ && FoldersGetCustomPath(hAvatarFolder_,path,sizeof(path), "") == 0)
return path;
else
return def_avatar_folder_;
}
-int TwitterProto::GetAvatar(WPARAM, LPARAM)
+int TwitterProto::GetAvatar(WPARAM,LPARAM)
{
return 0;
}
-int TwitterProto::SetAvatar(WPARAM, LPARAM)
+int TwitterProto::SetAvatar(WPARAM,LPARAM)
{
return 0;
}
\ No newline at end of file diff --git a/protocols/Twitter/proto.h b/protocols/Twitter/proto.h index af7a43d321..e7353b5dfe 100644 --- a/protocols/Twitter/proto.h +++ b/protocols/Twitter/proto.h @@ -3,33 +3,37 @@ Copyright © 2009 Jim Porter This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
-the Free Software Foundation, either version 2 of the License, or
+the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
-This program is distributed in the hope that it will be useful,
+This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
-along with this program. If not, see <http://www.gnu.org/licenses/>.
+along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
+#include "common.h"
#include "utility.h"
+//#include "tc2.h"
+#include "stdafx.h"
+#include "oauth.h"
#include <m_protoint.h>
class TwitterProto : public PROTO_INTERFACE
{
public:
- TwitterProto(const char *, const TCHAR *);
+ TwitterProto(const char *,const TCHAR *);
~TwitterProto();
__inline void* operator new(size_t size)
{
- return calloc(1, size);
+ return calloc(1,size);
}
__inline void operator delete(void *p)
{
@@ -43,75 +47,75 @@ public: //PROTO_INTERFACE
- virtual HANDLE __cdecl AddToList(int, PROTOSEARCHRESULT *);
- virtual HANDLE __cdecl AddToListByEvent(int, int, HANDLE);
+ virtual HANDLE __cdecl AddToList(int,PROTOSEARCHRESULT *);
+ virtual HANDLE __cdecl AddToListByEvent(int,int,HANDLE);
virtual int __cdecl Authorize(HANDLE);
- virtual int __cdecl AuthDeny(HANDLE, const TCHAR *);
- virtual int __cdecl AuthRecv(HANDLE, PROTORECVEVENT *);
- virtual int __cdecl AuthRequest(HANDLE, const TCHAR *);
+ virtual int __cdecl AuthDeny(HANDLE,const char *);
+ virtual int __cdecl AuthRecv(HANDLE,PROTORECVEVENT *);
+ virtual int __cdecl AuthRequest(HANDLE,const char *);
- virtual HANDLE __cdecl ChangeInfo(int, void *);
+ virtual HANDLE __cdecl ChangeInfo(int,void *);
- virtual HANDLE __cdecl FileAllow(HANDLE, HANDLE, const TCHAR *);
- virtual int __cdecl FileCancel(HANDLE, HANDLE);
- virtual int __cdecl FileDeny(HANDLE, HANDLE, const TCHAR *);
- virtual int __cdecl FileResume(HANDLE, int *, const TCHAR **);
+ virtual HANDLE __cdecl FileAllow(HANDLE,HANDLE,const char *);
+ virtual int __cdecl FileCancel(HANDLE,HANDLE);
+ virtual int __cdecl FileDeny(HANDLE,HANDLE,const char *);
+ virtual int __cdecl FileResume(HANDLE,int *,const char **);
- virtual DWORD __cdecl GetCaps(int, HANDLE = 0);
+ virtual DWORD __cdecl GetCaps(int,HANDLE = 0);
virtual HICON __cdecl GetIcon(int);
- virtual int __cdecl GetInfo(HANDLE, int);
+ virtual int __cdecl GetInfo(HANDLE,int);
- virtual HANDLE __cdecl SearchBasic(const TCHAR *);
- virtual HANDLE __cdecl SearchByEmail(const TCHAR *);
- virtual HANDLE __cdecl SearchByName(const TCHAR *, const TCHAR *, const TCHAR *);
+ virtual HANDLE __cdecl SearchBasic(const char *);
+ virtual HANDLE __cdecl SearchByEmail(const char *);
+ virtual HANDLE __cdecl SearchByName(const char *,const char *,const char *);
virtual HWND __cdecl SearchAdvanced(HWND);
virtual HWND __cdecl CreateExtendedSearchUI(HWND);
- virtual int __cdecl RecvContacts(HANDLE, PROTORECVEVENT *);
- virtual int __cdecl RecvFile(HANDLE, PROTORECVFILET *);
- virtual int __cdecl RecvMsg(HANDLE, PROTORECVEVENT *);
- virtual int __cdecl RecvUrl(HANDLE, PROTORECVEVENT *);
+ virtual int __cdecl RecvContacts(HANDLE,PROTORECVEVENT *);
+ virtual int __cdecl RecvFile(HANDLE,PROTORECVFILE *);
+ virtual int __cdecl RecvMsg(HANDLE,PROTORECVEVENT *);
+ virtual int __cdecl RecvUrl(HANDLE,PROTORECVEVENT *);
- virtual int __cdecl SendContacts(HANDLE, int, int, HANDLE *);
- virtual HANDLE __cdecl SendFile(HANDLE, const TCHAR *, TCHAR **);
- virtual int __cdecl SendMsg(HANDLE, int, const char *);
- virtual int __cdecl SendUrl(HANDLE, int, const char *);
+ virtual int __cdecl SendContacts(HANDLE,int,int,HANDLE *);
+ virtual HANDLE __cdecl SendFile(HANDLE,const char *,char **);
+ virtual int __cdecl SendMsg(HANDLE,int,const char *);
+ virtual int __cdecl SendUrl(HANDLE,int,const char *);
- virtual int __cdecl SetApparentMode(HANDLE, int);
+ virtual int __cdecl SetApparentMode(HANDLE,int);
virtual int __cdecl SetStatus(int);
virtual HANDLE __cdecl GetAwayMsg(HANDLE);
- virtual int __cdecl RecvAwayMsg(HANDLE, int, PROTORECVEVENT *);
- virtual int __cdecl SendAwayMsg(HANDLE, HANDLE, const char *);
- virtual int __cdecl SetAwayMsg(int, const TCHAR *);
+ virtual int __cdecl RecvAwayMsg(HANDLE,int,PROTORECVEVENT *);
+ virtual int __cdecl SendAwayMsg(HANDLE,HANDLE,const char *);
+ virtual int __cdecl SetAwayMsg(int,const char *);
- virtual int __cdecl UserIsTyping(HANDLE, int);
+ virtual int __cdecl UserIsTyping(HANDLE,int);
- virtual int __cdecl OnEvent(PROTOEVENTTYPE, WPARAM, LPARAM);
+ virtual int __cdecl OnEvent(PROTOEVENTTYPE,WPARAM,LPARAM);
void UpdateSettings();
// Services
- int __cdecl SvcCreateAccMgrUI(WPARAM, LPARAM);
- int __cdecl GetName(WPARAM, LPARAM);
- int __cdecl GetStatus(WPARAM, LPARAM);
- int __cdecl ReplyToTweet(WPARAM, LPARAM);
- int __cdecl VisitHomepage(WPARAM, LPARAM);
- int __cdecl GetAvatar(WPARAM, LPARAM);
- int __cdecl SetAvatar(WPARAM, LPARAM);
+ int __cdecl SvcCreateAccMgrUI(WPARAM,LPARAM);
+ int __cdecl GetName(WPARAM,LPARAM);
+ int __cdecl GetStatus(WPARAM,LPARAM);
+ int __cdecl ReplyToTweet(WPARAM,LPARAM);
+ int __cdecl VisitHomepage(WPARAM,LPARAM);
+ int __cdecl GetAvatar(WPARAM,LPARAM);
+ int __cdecl SetAvatar(WPARAM,LPARAM);
// Events
- int __cdecl OnContactDeleted(WPARAM, LPARAM);
- int __cdecl OnBuildStatusMenu(WPARAM, LPARAM);
- int __cdecl OnOptionsInit(WPARAM, LPARAM);
- int __cdecl OnTweet(WPARAM, LPARAM);
- int __cdecl OnModulesLoaded(WPARAM, LPARAM);
- int __cdecl OnPreShutdown(WPARAM, LPARAM);
- int __cdecl OnPrebuildContactMenu(WPARAM, LPARAM);
- int __cdecl OnChatOutgoing(WPARAM, LPARAM);
- int __cdecl OnJoinChat(WPARAM, LPARAM);
- int __cdecl OnLeaveChat(WPARAM, LPARAM);
+ int __cdecl OnContactDeleted(WPARAM,LPARAM);
+ int __cdecl OnBuildStatusMenu(WPARAM,LPARAM);
+ int __cdecl OnOptionsInit(WPARAM,LPARAM);
+ int __cdecl OnTweet(WPARAM,LPARAM);
+ int __cdecl OnModulesLoaded(WPARAM,LPARAM);
+ int __cdecl OnPreShutdown(WPARAM,LPARAM);
+ int __cdecl OnPrebuildContactMenu(WPARAM,LPARAM);
+ int __cdecl OnChatOutgoing(WPARAM,LPARAM);
+ int __cdecl OnJoinChat(WPARAM,LPARAM);
+ int __cdecl OnLeaveChat(WPARAM,LPARAM);
void __cdecl SendTweetWorker(void *);
private:
@@ -126,28 +130,34 @@ private: void __cdecl UpdateInfoWorker(void *);
bool NegotiateConnection();
- void UpdateStatuses(bool pre_read, bool popups);
+
+ void UpdateStatuses(bool pre_read,bool popups, bool tweetToMsg);
void UpdateMessages(bool pre_read);
void UpdateFriends();
- void UpdateAvatar(HANDLE, const std::string &, bool force=false);
+ void UpdateAvatar(HANDLE,const std::string &,bool force=false);
- void ShowPopup(const wchar_t *);
- void ShowPopup(const char *);
- void ShowContactPopup(HANDLE, const std::tstring &);
+ int ShowPinDialog();
+ void ShowPopup(const wchar_t *, int Error = 0);
+ void ShowPopup(const char *, int Error = 0);
+ void ShowContactPopup(HANDLE,const std::string &);
- bool IsMyContact(HANDLE, bool include_chat = false);
- HANDLE UsernameToHContact(const TCHAR *);
- HANDLE AddToClientList(const TCHAR *, const TCHAR *);
+ bool IsMyContact(HANDLE,bool include_chat = false);
+ HANDLE UsernameToHContact(const char *);
+ HANDLE AddToClientList(const char *,const char *);
void SetAllContactStatuses(int);
- int LOG(const char *fmt, ...);
+ int LOG(const char *fmt,...);
+ int WLOG(const char* first, const wstring last);
static void CALLBACK APC_callback(ULONG_PTR p);
void UpdateChat(const twitter_user &update);
- void AddChatContact(const TCHAR *name, const TCHAR *nick=0);
- void DeleteChatContact(const TCHAR *name);
+ void AddChatContact(const char *name,const char *nick=0);
+ void DeleteChatContact(const char *name);
void SetChatStatus(int);
+ void TwitterProto::resetOAuthKeys();
+
+
std::string GetAvatarFolder();
HANDLE signon_lock_;
@@ -166,14 +176,26 @@ private: HANDLE hAvatarFolder_;
bool in_chat_;
+
+ int disconnectionCount;
+
+ //mirandas keys
+ wstring ConsumerKey;
+ wstring ConsumerSecret;
+
+ // various twitter api URLs
+ wstring AccessUrl;
+ wstring AuthorizeUrl;
+ wstring RequestUrl;
+ wstring UserTimelineUrl;
};
// TODO: remove this
inline std::string profile_base_url(const std::string &url)
{
size_t x = url.find("://");
- if (x == std::string::npos)
- return url.substr(0, url.find('/')+1);
+ if(x == std::string::npos)
+ return url.substr(0,url.find('/')+1);
else
- return url.substr(0, url.find('/', x+3)+1);
+ return url.substr(0,url.find('/',x+3)+1);
}
\ No newline at end of file diff --git a/protocols/Twitter/resource.h b/protocols/Twitter/resource.h index 21fc21c049..909c859e88 100644 --- a/protocols/Twitter/resource.h +++ b/protocols/Twitter/resource.h @@ -7,6 +7,7 @@ #define IDD_TWEET 103
#define IDD_OPTIONS 104
#define IDD_OPTIONS_POPUPS 107
+#define IDD_TWITTERPIN 109
#define IDC_NEWACCOUNTLINK 1001
#define IDC_UN 1002
#define IDC_PW 1003
@@ -27,21 +28,23 @@ #define IDC_COL_WINDOWS 1018
#define IDC_COL_POPUP 1019
#define IDC_COL_CUSTOM 1020
-#define IDC_POPUPS_ENABLE 1021
#define IDC_SHOWPOPUPS 1021
#define IDC_PREVIEW 1022
#define IDC_NOSIGNONPOPUPS 1023
#define IDC_RECONNECT 1024
-#define IDC_COMBO1 1025
#define IDC_SERVER 1025
+#define IDC_PIN 1026
+#define IDC_GROUP 1027
+#define IDC_USERNAME 1028
+#define IDC_TWEET_MSG 1029
// Next default values for new objects
//
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS
-#define _APS_NEXT_RESOURCE_VALUE 108
+#define _APS_NEXT_RESOURCE_VALUE 110
#define _APS_NEXT_COMMAND_VALUE 40001
-#define _APS_NEXT_CONTROL_VALUE 1026
+#define _APS_NEXT_CONTROL_VALUE 1030
#define _APS_NEXT_SYMED_VALUE 101
#endif
#endif
diff --git a/protocols/Twitter/stdafx.h b/protocols/Twitter/stdafx.h new file mode 100644 index 0000000000..6e216fce33 --- /dev/null +++ b/protocols/Twitter/stdafx.h @@ -0,0 +1,33 @@ +// stdafx.h : include file for standard system include files,
+// or project specific include files that are used frequently, but
+// are changed infrequently
+//
+
+#pragma once
+
+#include "targetver.h"
+
+#include <Windows.h>
+//#include <WinInet.h>
+#include <Shlwapi.h>
+#include <Wincrypt.h>
+#include <stdio.h>
+#include <tchar.h>
+#include <time.h>
+
+#include <string>
+#include <list>
+#include <vector>
+#include <map>
+#include <fstream>
+
+typedef std::basic_string<TCHAR> tstring;
+//#define SIZEOF(x) (sizeof(x)/sizeof(*x))
+
+#include "StringConv.h"
+#include "StringUtil.h"
+#include "Base64Coder.h"
+
+#include "Debug.h"
+
+#include "win2k.h"
diff --git a/protocols/Twitter/stubs.cpp b/protocols/Twitter/stubs.cpp index 331a4cdeac..79ee2e7c9d 100644 --- a/protocols/Twitter/stubs.cpp +++ b/protocols/Twitter/stubs.cpp @@ -15,7 +15,6 @@ You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
-#include "common.h"
#include "proto.h"
HANDLE TwitterProto::AddToListByEvent(int flags,int iContact,HANDLE hDbEvent)
@@ -28,7 +27,7 @@ int TwitterProto::Authorize(HANDLE hContact) return 0;
}
-int TwitterProto::AuthDeny(HANDLE hContact,const TCHAR *reason)
+int TwitterProto::AuthDeny(HANDLE hContact,const char *reason)
{
return 0;
}
@@ -38,7 +37,7 @@ int TwitterProto::AuthRecv(HANDLE hContact,PROTORECVEVENT *) return 0;
}
-int TwitterProto::AuthRequest(HANDLE hContact,const TCHAR *message)
+int TwitterProto::AuthRequest(HANDLE hContact,const char *message)
{
return 0;
}
@@ -49,7 +48,7 @@ HANDLE TwitterProto::ChangeInfo(int type,void *info_data) return 0;
}
-HANDLE TwitterProto::FileAllow(HANDLE hContact,HANDLE hTransfer,const TCHAR *path)
+HANDLE TwitterProto::FileAllow(HANDLE hContact,HANDLE hTransfer,const char *path)
{
return 0;
}
@@ -59,17 +58,18 @@ int TwitterProto::FileCancel(HANDLE hContact,HANDLE hTransfer) return 0;
}
-int TwitterProto::FileDeny(HANDLE hContact,HANDLE hTransfer,const TCHAR *reason)
+int TwitterProto::FileDeny(HANDLE hContact,HANDLE hTransfer,const char *reason)
{
return 0;
}
-int TwitterProto::FileResume(HANDLE hTransfer,int *action,const TCHAR **filename)
+int TwitterProto::FileResume(HANDLE hTransfer,int *action,const char **filename)
{
return 0;
}
-HANDLE TwitterProto::SearchByName(const TCHAR *nick,const TCHAR *first_name, const TCHAR *last_name)
+HANDLE TwitterProto::SearchByName(const char *nick,const char *first_name,
+ const char *last_name)
{
return 0;
}
@@ -89,7 +89,7 @@ int TwitterProto::RecvContacts(HANDLE hContact,PROTORECVEVENT *) return 0;
}
-int TwitterProto::RecvFile(HANDLE hContact,PROTORECVFILET *)
+int TwitterProto::RecvFile(HANDLE hContact,PROTORECVFILE *)
{
return 0;
}
@@ -104,7 +104,7 @@ int TwitterProto::SendContacts(HANDLE hContact,int flags,int nContacts,HANDLE *h return 0;
}
-HANDLE TwitterProto::SendFile(HANDLE hContact,const TCHAR *desc, TCHAR **files)
+HANDLE TwitterProto::SendFile(HANDLE hContact,const char *desc, char **files)
{
return 0;
}
@@ -129,7 +129,7 @@ int TwitterProto::SendAwayMsg(HANDLE hContact,HANDLE hProcess,const char *msg) return 0;
}
-int TwitterProto::SetAwayMsg(int status,const TCHAR *msg)
+int TwitterProto::SetAwayMsg(int status,const char *msg)
{
return 0;
}
diff --git a/protocols/Twitter/targetver.h b/protocols/Twitter/targetver.h new file mode 100644 index 0000000000..a38195a4ef --- /dev/null +++ b/protocols/Twitter/targetver.h @@ -0,0 +1,13 @@ +#pragma once
+
+// The following macros define the minimum required platform. The minimum required platform
+// is the earliest version of Windows, Internet Explorer etc. that has the necessary features to run
+// your application. The macros work by enabling all features available on platform versions up to and
+// including the version specified.
+
+// Modify the following defines if you have to target a platform prior to the ones specified below.
+// Refer to MSDN for the latest info on corresponding values for different platforms.
+#ifndef _WIN32_WINNT // Specifies that the minimum required platform is Windows Vista.
+#define _WIN32_WINNT 0x0600 // Change this to the appropriate value to target other versions of Windows.
+#endif
+
diff --git a/protocols/Twitter/tc2.cpp b/protocols/Twitter/tc2.cpp new file mode 100644 index 0000000000..6348e2703a --- /dev/null +++ b/protocols/Twitter/tc2.cpp @@ -0,0 +1,805 @@ +/*
+
+Copyright (c) 2010 Brook Miles
+
+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 "stdafx.h"
+#include "tc2.h"
+#include "proto.h"
+
+//mirandas keys
+wstring ConsumerKey = L"AygxrTNGti27uVMz0hAbA";
+wstring ConsumerSecret = L"kjM8gL7oqPXya2rhI8dSoZW0RPyPOD1GxgYj6wA";
+
+//codebrook's keys
+//wstring ConsumerKey = L"T6XLGzrkfsJAgU59dbIjSA";
+//wstring ConsumerSecret = L"xsvm2NAksjsJGw63RMWAtec3Lz5uiBusfVt48gbdKLg";
+
+const wstring HostName = L"http://twitter.com";
+const wstring AccessUrl = L"http://twitter.com/oauth/access_token";
+const wstring AuthorizeUrl = L"http://twitter.com/oauth/authorize?oauth_token=%s";
+const wstring RequestUrl = L"http://twitter.com/oauth/request_token?some_other_parameter=hello&another_one=goodbye#meep"; // threw in some parameters for fun, and to test UrlGetQuery
+const wstring UserTimelineUrl = L"http://twitter.com/statuses/user_timeline.json";
+
+const wstring AuthFileName = L"tc2_saved.txt";
+
+
+using namespace std;
+
+// ConsumerKey and ConsumerSecret uniquely identify your application
+// TODO Go to http://twitter.com/oauth_clients/new and register your own Client application.
+// TODO Then replace the ConsumerKey and ConsumerSecret in the values below.
+
+wstring getHostName() { return HostName; }
+wstring getAccessUrl() { return AccessUrl; }
+wstring getAuthorizeUrl() { return AuthorizeUrl; }
+wstring getRequestUrl() { return RequestUrl; }
+wstring getUserTimelineUrl() { return UserTimelineUrl; }
+wstring getConsumerKey() { return ConsumerKey; }
+wstring getConsumerSecret() { return ConsumerSecret; }
+
+
+typedef std::map<wstring, wstring> OAuthParameters;
+
+/*wstring UrlGetQuery( const wstring& url )
+{
+ wstring query;
+ URL_COMPONENTS components = {sizeof(URL_COMPONENTS)};
+
+ wchar_t buf[1024*4] = {};
+
+ components.lpszExtraInfo = buf;
+ components.dwExtraInfoLength = SIZEOF(buf);
+
+ BOOL crackUrlOk = InternetCrackUrl(url.c_str(), url.size(), 0, &components);
+ _ASSERTE(crackUrlOk);
+ if(crackUrlOk)
+ {
+ query = components.lpszExtraInfo;
+
+ wstring::size_type q = query.find_first_of(L'?');
+ if(q != wstring::npos)
+ {
+ query = query.substr(q + 1);
+ }
+
+ wstring::size_type h = query.find_first_of(L'#');
+ if(h != wstring::npos)
+ {
+ query = query.substr(0, h);
+ }
+ }
+ return query;
+}*/
+
+OAuthParameters ParseQueryString( const wstring& url )
+{
+ OAuthParameters ret;
+
+ vector<wstring> queryParams;
+ Split(url, queryParams, L'&', false);
+
+ for(size_t i = 0; i < queryParams.size(); ++i)
+ {
+ vector<wstring> paramElements;
+ Split(queryParams[i], paramElements, L'=', true);
+ _ASSERTE(paramElements.size() == 2);
+ if(paramElements.size() == 2)
+ {
+ ret[paramElements[0]] = paramElements[1];
+ }
+ }
+ return ret;
+}
+
+wstring OAuthCreateNonce()
+{
+ wchar_t ALPHANUMERIC[] = L"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
+ wstring nonce;
+
+ for(int i = 0; i <= 16; ++i)
+ {
+ nonce += ALPHANUMERIC[rand() % (SIZEOF(ALPHANUMERIC) - 1)]; // don't count null terminator in array
+ }
+ return nonce;
+}
+
+wstring OAuthCreateTimestamp()
+{
+ __time64_t utcNow;
+ __time64_t ret = _time64(&utcNow);
+ _ASSERTE(ret != -1);
+
+ wchar_t buf[100] = {};
+ swprintf_s(buf, SIZEOF(buf), L"%I64u", utcNow);
+
+ return buf;
+}
+
+string HMACSHA1( const string& keyBytes, const string& data )
+{
+ // based on http://msdn.microsoft.com/en-us/library/aa382379%28v=VS.85%29.aspx
+
+ string hash;
+
+ //--------------------------------------------------------------------
+ // Declare variables.
+ //
+ // hProv: Handle to a cryptographic service provider (CSP).
+ // This example retrieves the default provider for
+ // the PROV_RSA_FULL provider type.
+ // hHash: Handle to the hash object needed to create a hash.
+ // hKey: Handle to a symmetric key. This example creates a
+ // key for the RC4 algorithm.
+ // hHmacHash: Handle to an HMAC hash.
+ // pbHash: Pointer to the hash.
+ // dwDataLen: Length, in bytes, of the hash.
+ // Data1: Password string used to create a symmetric key.
+ // Data2: Message string to be hashed.
+ // HmacInfo: Instance of an HMAC_INFO structure that contains
+ // information about the HMAC hash.
+ //
+ HCRYPTPROV hProv = NULL;
+ HCRYPTHASH hHash = NULL;
+ HCRYPTKEY hKey = NULL;
+ HCRYPTHASH hHmacHash = NULL;
+ PBYTE pbHash = NULL;
+ DWORD dwDataLen = 0;
+ //BYTE Data1[] = {0x70,0x61,0x73,0x73,0x77,0x6F,0x72,0x64};
+ //BYTE Data2[] = {0x6D,0x65,0x73,0x73,0x61,0x67,0x65};
+ HMAC_INFO HmacInfo;
+
+ //--------------------------------------------------------------------
+ // Zero the HMAC_INFO structure and use the SHA1 algorithm for
+ // hashing.
+
+ ZeroMemory(&HmacInfo, sizeof(HmacInfo));
+ HmacInfo.HashAlgid = CALG_SHA1;
+
+ //--------------------------------------------------------------------
+ // Acquire a handle to the default RSA cryptographic service provider.
+
+ if (!CryptAcquireContext(
+ &hProv, // handle of the CSP
+ NULL, // key container name
+ NULL, // CSP name
+ PROV_RSA_FULL, // provider type
+ CRYPT_VERIFYCONTEXT)) // no key access is requested
+ {
+ _TRACE(" Error in AcquireContext 0x%08x \n",
+ GetLastError());
+ goto ErrorExit;
+ }
+
+ //--------------------------------------------------------------------
+ // Derive a symmetric key from a hash object by performing the
+ // following steps:
+ // 1. Call CryptCreateHash to retrieve a handle to a hash object.
+ // 2. Call CryptHashData to add a text string (password) to the
+ // hash object.
+ // 3. Call CryptDeriveKey to create the symmetric key from the
+ // hashed password derived in step 2.
+ // You will use the key later to create an HMAC hash object.
+
+ if (!CryptCreateHash(
+ hProv, // handle of the CSP
+ CALG_SHA1, // hash algorithm to use
+ 0, // hash key
+ 0, // reserved
+ &hHash)) // address of hash object handle
+ {
+ _TRACE("Error in CryptCreateHash 0x%08x \n",
+ GetLastError());
+ goto ErrorExit;
+ }
+
+ if (!CryptHashData(
+ hHash, // handle of the hash object
+ (BYTE*)keyBytes.c_str(), // password to hash
+ keyBytes.size(), // number of bytes of data to add
+ 0)) // flags
+ {
+ _TRACE("Error in CryptHashData 0x%08x \n",
+ GetLastError());
+ goto ErrorExit;
+ }
+
+ // key creation based on
+ // http://mirror.leaseweb.com/NetBSD/NetBSD-release-5-0/src/dist/wpa/src/crypto/crypto_cryptoapi.c
+ struct {
+ BLOBHEADER hdr;
+ DWORD len;
+ BYTE key[1024]; // TODO might want to dynamically allocate this, Should Be Fine though
+ } key_blob;
+
+ key_blob.hdr.bType = PLAINTEXTKEYBLOB;
+ key_blob.hdr.bVersion = CUR_BLOB_VERSION;
+ key_blob.hdr.reserved = 0;
+ /*
+ * Note: RC2 is not really used, but that can be used to
+ * import HMAC keys of up to 16 byte long.
+ * CRYPT_IPSEC_HMAC_KEY flag for CryptImportKey() is needed to
+ * be able to import longer keys (HMAC-SHA1 uses 20-byte key).
+ */
+ key_blob.hdr.aiKeyAlg = CALG_RC2;
+ key_blob.len = keyBytes.size();
+ ZeroMemory(key_blob.key, sizeof(key_blob.key));
+
+ _ASSERTE(keyBytes.size() <= SIZEOF(key_blob.key));
+ CopyMemory(key_blob.key, keyBytes.c_str(), min(keyBytes.size(), SIZEOF(key_blob.key)));
+
+ if (!CryptImportKey(
+ hProv,
+ (BYTE *)&key_blob,
+ sizeof(key_blob),
+ 0,
+ CRYPT_IPSEC_HMAC_KEY,
+ &hKey))
+ {
+ _TRACE("Error in CryptImportKey 0x%08x \n", GetLastError());
+ goto ErrorExit;
+ }
+
+ //--------------------------------------------------------------------
+ // Create an HMAC by performing the following steps:
+ // 1. Call CryptCreateHash to create a hash object and retrieve
+ // a handle to it.
+ // 2. Call CryptSetHashParam to set the instance of the HMAC_INFO
+ // structure into the hash object.
+ // 3. Call CryptHashData to compute a hash of the message.
+ // 4. Call CryptGetHashParam to retrieve the size, in bytes, of
+ // the hash.
+ // 5. Call malloc to allocate memory for the hash.
+ // 6. Call CryptGetHashParam again to retrieve the HMAC hash.
+
+ if (!CryptCreateHash(
+ hProv, // handle of the CSP.
+ CALG_HMAC, // HMAC hash algorithm ID
+ hKey, // key for the hash (see above)
+ 0, // reserved
+ &hHmacHash)) // address of the hash handle
+ {
+ _TRACE("Error in CryptCreateHash 0x%08x \n",
+ GetLastError());
+ goto ErrorExit;
+ }
+
+ if (!CryptSetHashParam(
+ hHmacHash, // handle of the HMAC hash object
+ HP_HMAC_INFO, // setting an HMAC_INFO object
+ (BYTE*)&HmacInfo, // the HMAC_INFO object
+ 0)) // reserved
+ {
+ _TRACE("Error in CryptSetHashParam 0x%08x \n",
+ GetLastError());
+ goto ErrorExit;
+ }
+
+ if (!CryptHashData(
+ hHmacHash, // handle of the HMAC hash object
+ (BYTE*)data.c_str(), // message to hash
+ data.size(), // number of bytes of data to add
+ 0)) // flags
+ {
+ _TRACE("Error in CryptHashData 0x%08x \n",
+ GetLastError());
+ goto ErrorExit;
+ }
+
+ //--------------------------------------------------------------------
+ // Call CryptGetHashParam twice. Call it the first time to retrieve
+ // the size, in bytes, of the hash. Allocate memory. Then call
+ // CryptGetHashParam again to retrieve the hash value.
+
+ if (!CryptGetHashParam(
+ hHmacHash, // handle of the HMAC hash object
+ HP_HASHVAL, // query on the hash value
+ NULL, // filled on second call
+ &dwDataLen, // length, in bytes, of the hash
+ 0))
+ {
+ _TRACE("Error in CryptGetHashParam 0x%08x \n",
+ GetLastError());
+ goto ErrorExit;
+ }
+
+ pbHash = (BYTE*)malloc(dwDataLen);
+ if(NULL == pbHash)
+ {
+ _TRACE("unable to allocate memory\n");
+ goto ErrorExit;
+ }
+
+ if (!CryptGetHashParam(
+ hHmacHash, // handle of the HMAC hash object
+ HP_HASHVAL, // query on the hash value
+ pbHash, // pointer to the HMAC hash value
+ &dwDataLen, // length, in bytes, of the hash
+ 0))
+ {
+ _TRACE("Error in CryptGetHashParam 0x%08x \n", GetLastError());
+ goto ErrorExit;
+ }
+
+ for(DWORD i = 0 ; i < dwDataLen ; i++)
+ {
+ hash.push_back((char)pbHash[i]);
+ }
+
+ // Free resources.
+ // lol goto
+ErrorExit:
+ if(hHmacHash)
+ CryptDestroyHash(hHmacHash);
+ if(hKey)
+ CryptDestroyKey(hKey);
+ if(hHash)
+ CryptDestroyHash(hHash);
+ if(hProv)
+ CryptReleaseContext(hProv, 0);
+ if(pbHash)
+ free(pbHash);
+
+ return hash;
+}
+
+wstring Base64String( const string& hash )
+{
+ Base64Coder coder;
+ coder.Encode((BYTE*)hash.c_str(), hash.size());
+ wstring encoded = UTF8ToWide(coder.EncodedMessage());
+ return encoded;
+}
+
+// char2hex and urlencode from http://www.zedwood.com/article/111/cpp-urlencode-function
+// modified according to http://oauth.net/core/1.0a/#encoding_parameters
+//
+//5.1. Parameter Encoding
+//
+//All parameter names and values are escaped using the [RFC3986]
+//percent-encoding (%xx) mechanism. Characters not in the unreserved character set
+//MUST be encoded. Characters in the unreserved character set MUST NOT be encoded.
+//Hexadecimal characters in encodings MUST be upper case.
+//Text names and values MUST be encoded as UTF-8
+// octets before percent-encoding them per [RFC3629].
+//
+// unreserved = ALPHA, DIGIT, '-', '.', '_', '~'
+
+string char2hex( char dec )
+{
+ char dig1 = (dec&0xF0)>>4;
+ char dig2 = (dec&0x0F);
+ if ( 0<= dig1 && dig1<= 9) dig1+=48; //0,48 in ascii
+ if (10<= dig1 && dig1<=15) dig1+=65-10; //A,65 in ascii
+ if ( 0<= dig2 && dig2<= 9) dig2+=48;
+ if (10<= dig2 && dig2<=15) dig2+=65-10;
+
+ string r;
+ r.append( &dig1, 1);
+ r.append( &dig2, 1);
+ return r;
+}
+
+string urlencode(const string &c)
+{
+
+ string escaped;
+ int max = c.length();
+ for(int i=0; i<max; i++)
+ {
+ if ( (48 <= c[i] && c[i] <= 57) ||//0-9
+ (65 <= c[i] && c[i] <= 90) ||//ABC...XYZ
+ (97 <= c[i] && c[i] <= 122) || //abc...xyz
+ (c[i]=='~' || c[i]=='-' || c[i]=='_' || c[i]=='.')
+ )
+ {
+ escaped.append( &c[i], 1);
+ }
+ else
+ {
+ escaped.append("%");
+ escaped.append( char2hex(c[i]) );//converts char 255 to string "FF"
+ }
+ }
+ return escaped;
+}
+
+
+wstring UrlEncode( const wstring& url )
+{
+ // multiple encodings r sux
+ return UTF8ToWide(urlencode(WideToUTF8(url)));
+}
+
+wstring OAuthCreateSignature( const wstring& signatureBase, const wstring& consumerSecret, const wstring& requestTokenSecret )
+{
+ // URL encode key elements
+ wstring escapedConsumerSecret = UrlEncode(consumerSecret);
+ wstring escapedTokenSecret = UrlEncode(requestTokenSecret);
+
+ wstring key = escapedConsumerSecret + L"&" + escapedTokenSecret;
+ string keyBytes = WideToUTF8(key);
+
+ string data = WideToUTF8(signatureBase);
+ string hash = HMACSHA1(keyBytes, data);
+ wstring signature = Base64String(hash);
+
+ // URL encode the returned signature
+ signature = UrlEncode(signature);
+ return signature;
+}
+
+
+/*wstring OAuthConcatenateRequestElements( const wstring& httpMethod, wstring url, const wstring& parameters )
+{
+ wstring escapedUrl = UrlEncode(url);
+ WLOG("before OAUTHConcat, params are %s", parameters);
+ wstring escapedParameters = UrlEncode(parameters);
+ LOG(")))))))))))))))))))))))))))))))))))))))))))))))");
+ WLOG("after url encode, its %s", escapedParameters);
+ wstring ret = httpMethod + L"&" + escapedUrl + L"&" + escapedParameters;
+ return ret;
+}*/
+
+/*wstring OAuthNormalizeRequestParameters( const OAuthParameters& requestParameters )
+{
+ list<wstring> sorted;
+ for(OAuthParameters::const_iterator it = requestParameters.begin();
+ it != requestParameters.end();
+ ++it)
+ {
+ wstring param = it->first + L"=" + it->second;
+ sorted.push_back(param);
+ }
+ sorted.sort();
+
+ wstring params;
+ for(list<wstring>::iterator it = sorted.begin(); it != sorted.end(); ++it)
+ {
+ if(params.size() > 0)
+ {
+ params += L"&";
+ }
+ params += *it;
+ }
+
+ return params;
+}*/
+
+/*wstring OAuthNormalizeUrl( const wstring& url )
+{
+ wchar_t scheme[1024*4] = {};
+ wchar_t host[1024*4] = {};
+ wchar_t path[1024*4] = {};
+
+ URL_COMPONENTS components = { sizeof(URL_COMPONENTS) };
+
+ components.lpszScheme = scheme;
+ components.dwSchemeLength = SIZEOF(scheme);
+
+ components.lpszHostName = host;
+ components.dwHostNameLength = SIZEOF(host);
+
+ components.lpszUrlPath = path;
+ components.dwUrlPathLength = SIZEOF(path);
+
+ wstring normalUrl = url;
+
+ BOOL crackUrlOk = InternetCrackUrl(url.c_str(), url.size(), 0, &components);
+ _ASSERTE(crackUrlOk);
+ if(crackUrlOk)
+ {
+ wchar_t port[10] = {};
+
+ // The port number must only be included if it is non-standard
+ if((Compare(scheme, L"http", false) && components.nPort != 80) ||
+ (Compare(scheme, L"https", false) && components.nPort != 443))
+ {
+ swprintf_s(port, SIZEOF(port), L":%u", components.nPort);
+ }
+
+ // InternetCrackUrl includes ? and # elements in the path,
+ // which we need to strip off
+ wstring pathOnly = path;
+ wstring::size_type q = pathOnly.find_first_of(L"#?");
+ if(q != wstring::npos)
+ {
+ pathOnly = pathOnly.substr(0, q);
+ }
+
+ normalUrl = wstring(scheme) + L"://" + host + port + pathOnly;
+ }
+ return normalUrl;
+}*/
+
+/*OAuthParameters BuildSignedOAuthParameters( const OAuthParameters& requestParameters,
+ const wstring& url,
+ const wstring& httpMethod,
+ const wstring& consumerKey,
+ const wstring& consumerSecret,
+ const wstring& requestToken = L"",
+ const wstring& requestTokenSecret = L"",
+ const wstring& pin = L"" )
+{
+ wstring timestamp = OAuthCreateTimestamp();
+ wstring nonce = OAuthCreateNonce();
+
+ // create oauth requestParameters
+ OAuthParameters oauthParameters;
+
+ oauthParameters[L"oauth_timestamp"] = timestamp;
+ oauthParameters[L"oauth_nonce"] = nonce;
+ oauthParameters[L"oauth_version"] = L"1.0";
+ oauthParameters[L"oauth_signature_method"] = L"HMAC-SHA1";
+ oauthParameters[L"oauth_consumer_key"] = consumerKey;
+
+ // add the request token if found
+ if (!requestToken.empty())
+ {
+ oauthParameters[L"oauth_token"] = requestToken;
+ }
+
+ // add the authorization pin if found
+ if (!pin.empty())
+ {
+ oauthParameters[L"oauth_verifier"] = pin;
+ }
+
+ // create a parameter list containing both oauth and original parameters
+ // this will be used to create the parameter signature
+ OAuthParameters allParameters = requestParameters;
+ allParameters.insert(oauthParameters.begin(), oauthParameters.end());
+
+ // prepare a signature base, a carefully formatted string containing
+ // all of the necessary information needed to generate a valid signature
+ wstring normalUrl = OAuthNormalizeUrl(url);
+ wstring normalizedParameters = OAuthNormalizeRequestParameters(allParameters);
+ wstring signatureBase = OAuthConcatenateRequestElements(httpMethod, normalUrl, normalizedParameters);
+
+ // obtain a signature and add it to header requestParameters
+ wstring signature = OAuthCreateSignature(signatureBase, consumerSecret, requestTokenSecret);
+ oauthParameters[L"oauth_signature"] = signature;
+
+ return oauthParameters;
+}*/
+
+/*wstring OAuthWebRequestSubmit(
+ const OAuthParameters& parameters,
+ const wstring& url
+ )
+{
+ _TRACE("OAuthWebRequestSubmit(%s)", url.c_str());
+
+ wstring oauthHeader = L"Authorization: OAuth ";
+
+ for(OAuthParameters::const_iterator it = parameters.begin();
+ it != parameters.end();
+ ++it)
+ {
+ _TRACE("%s = %s", it->first.c_str(), it->second.c_str());
+
+ if(it != parameters.begin())
+ {
+ oauthHeader += L",";
+ }
+
+ wstring pair;
+ pair += it->first + L"=\"" + it->second + L"\"";
+ oauthHeader += pair;
+ }
+ oauthHeader += L"\r\n";
+
+ _TRACE("%s", oauthHeader.c_str());
+
+ wchar_t host[1024*4] = {};
+ wchar_t path[1024*4] = {};
+
+ URL_COMPONENTS components = { sizeof(URL_COMPONENTS) };
+
+ components.lpszHostName = host;
+ components.dwHostNameLength = SIZEOF(host);
+
+ components.lpszUrlPath = path;
+ components.dwUrlPathLength = SIZEOF(path);
+
+ wstring normalUrl = url;
+
+ BOOL crackUrlOk = InternetCrackUrl(url.c_str(), url.size(), 0, &components);
+ _ASSERTE(crackUrlOk);
+
+ wstring result;
+
+ // TODO you'd probably want to InternetOpen only once at app initialization
+ HINTERNET hINet = InternetOpen(L"tc2/1.0",
+ INTERNET_OPEN_TYPE_PRECONFIG,
+ NULL,
+ NULL,
+ 0 );
+ _ASSERTE( hINet != NULL );
+ if ( hINet != NULL )
+ {
+ // TODO add support for HTTPS requests
+ HINTERNET hConnection = InternetConnect(
+ hINet,
+ host,
+ components.nPort,
+ NULL,
+ NULL,
+ INTERNET_SERVICE_HTTP,
+ 0, 0 );
+ _ASSERTE(hConnection != NULL);
+ if ( hConnection != NULL)
+ {
+ // TODO add support for handling POST requests
+ HINTERNET hData = HttpOpenRequest( hConnection,
+ L"GET",
+ path,
+ NULL,
+ NULL,
+ NULL,
+ INTERNET_FLAG_KEEP_CONNECTION | INTERNET_FLAG_NO_CACHE_WRITE | INTERNET_FLAG_NO_AUTH | INTERNET_FLAG_RELOAD,
+ 0 );
+ _ASSERTE(hData != NULL);
+ if ( hData != NULL )
+ {
+ BOOL addHeadersOk = HttpAddRequestHeaders(hData,
+ oauthHeader.c_str(),
+ oauthHeader.size(),
+ 0);
+ _ASSERTE(addHeadersOk);
+
+ BOOL sendOk = HttpSendRequest( hData, NULL, 0, NULL, 0);
+ _ASSERTE(sendOk);
+
+ // TODO dynamically allocate return buffer
+ BYTE buffer[1024*32] = {};
+ DWORD dwRead = 0;
+ while(
+ InternetReadFile( hData, buffer, SIZEOF(buffer) - 1, &dwRead ) &&
+ dwRead > 0
+ )
+ {
+ buffer[dwRead] = 0;
+ result += UTF8ToWide((char*)buffer);
+ }
+
+ _TRACE("%s", result.c_str());
+
+ InternetCloseHandle(hData);
+ }
+ InternetCloseHandle(hConnection);
+ }
+ InternetCloseHandle(hINet);
+ }
+
+ return result;
+}*/
+
+// OAuthWebRequest used for all OAuth related queries
+//
+// consumerKey and consumerSecret - must be provided for every call, they identify the application
+// oauthToken and oauthTokenSecret - need to be provided for every call, except for the first token request before authorizing
+// pin - only used during authorization, when the user enters the PIN they received from the twitter website
+/*wstring OAuthWebRequestSubmit(
+ const wstring& url,
+ const wstring& httpMethod,
+ const wstring& consumerKey,
+ const wstring& consumerSecret,
+ const wstring& oauthToken,
+ const wstring& oauthTokenSecret,
+ const wstring& pin,
+ TwitterProto *proto
+ )
+{
+ wstring query = UrlGetQuery(url);
+ //Show
+ OAuthParameters originalParameters = ParseQueryString(query);
+
+ OAuthParameters oauthSignedParameters = BuildSignedOAuthParameters(
+ originalParameters,
+ url,
+ httpMethod,
+ consumerKey, consumerSecret,
+ oauthToken, oauthTokenSecret,
+ pin );
+ return OAuthWebRequestSubmit(oauthSignedParameters, url);
+}*/
+/*
+int testfunc(int argc, _TCHAR* argv[])
+{
+ CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);
+ srand(_time32(NULL));
+
+ string savedAccessTokenString;
+
+ ifstream inFile;
+ inFile.open(AuthFileName.c_str());
+ inFile >> savedAccessTokenString;
+ inFile.close();
+
+ OAuthParameters savedParameters = ParseQueryString(UTF8ToWide(savedAccessTokenString));
+
+ wstring oauthAccessToken = savedParameters[L"oauth_token"];
+ wstring oauthAccessTokenSecret = savedParameters[L"oauth_token_secret"];
+ wstring screenName = savedParameters[L"screen_name"];
+
+ if( oauthAccessToken.empty() || oauthAccessTokenSecret.empty() )
+ {
+ // Overall OAuth flow based on
+ // Professional Twitter Development: With Examples in .NET 3.5 by Daniel Crenna
+
+ wstring requestToken = OAuthWebRequestSubmit(RequestUrl, L"GET", ConsumerKey, ConsumerSecret);
+
+ OAuthParameters response = ParseQueryString(requestToken);
+ wstring oauthToken = response[L"oauth_token"];
+ wstring oauthTokenSecret = response[L"oauth_token_secret"];
+ if(!oauthToken.empty())
+ {
+ wchar_t buf[1024] = {};
+ swprintf_s(buf, SIZEOF(buf), AuthorizeUrl.c_str(), oauthToken.c_str());
+
+ wprintf(L"Launching %s\r\n", buf);
+ ShellExecute(NULL, L"open", buf, NULL, NULL, SW_SHOWNORMAL);
+ }
+
+ // TODO ok, using debug-only trace function to prompt the user isn't a great idea
+ wchar_t pin[1024] = {};
+ wprintf(L"\r\n");
+ wprintf(L"Enter the PIN you receive after authorizing this program in your web browser: ");
+ _getws_s(pin, SIZEOF(pin));
+
+ // exchange the request token for an access token
+ wstring accessTokenString = OAuthWebRequestSubmit(AccessUrl, L"GET", ConsumerKey, ConsumerSecret,
+ oauthToken, oauthTokenSecret, pin);
+
+ OAuthParameters accessTokenParameters = ParseQueryString(accessTokenString);
+ oauthAccessToken = accessTokenParameters[L"oauth_token"];
+ oauthAccessTokenSecret = accessTokenParameters[L"oauth_token_secret"];
+ screenName = accessTokenParameters[L"screen_name"];
+
+ ofstream outFile;
+ outFile.open(AuthFileName.c_str(), ios_base::out | ios_base::trunc);
+ outFile << WideToUTF8(accessTokenString);
+ outFile.close();
+ }
+
+ wprintf(L"\r\n");
+ wprintf(L"Authorized screen_name: %s\r\n", screenName.c_str());
+ wprintf(L"Your oauth_token is: %s\r\n", oauthAccessToken.c_str());
+ wprintf(L"Your oauth_token_secret is: %s\r\n", oauthAccessTokenSecret.c_str());
+ wprintf(L"\r\n");
+
+ wprintf(L"Press enter to request your time line...\r\n");
+ getchar();
+
+ // access a protected API call on Twitter using our access token
+ wstring userTimeline = OAuthWebRequestSubmit(UserTimelineUrl, L"GET", ConsumerKey, ConsumerSecret,
+ oauthAccessToken, oauthAccessTokenSecret);
+
+ wprintf(L"\r\nYour timeline:\r\n%s\r\n", userTimeline.c_str());
+
+ wprintf(L"Press enter to exit...\r\n");
+ getchar();
+
+ return 0;
+}*/
+
diff --git a/protocols/Twitter/tc2.h b/protocols/Twitter/tc2.h new file mode 100644 index 0000000000..bbf3884fd6 --- /dev/null +++ b/protocols/Twitter/tc2.h @@ -0,0 +1,83 @@ +/* aww yeah creating some crazy .h file
+
+*/
+
+#ifndef TC2_H
+#define TC2_H
+
+//#include "proto.h"
+#include "stdafx.h"
+#include "twitter.h"
+
+using namespace std;
+
+//typedef std::map<wstring, wstring> OAuthParameters;
+
+wstring getHostName();
+wstring getAccessUrl();
+wstring getAuthorizeUrl();
+wstring getRequestUrl();
+wstring getUserTimelineUrl();
+wstring getConsumerKey();
+wstring getConsumerSecret();
+
+//wstring UrlGetQuery( const wstring& url );
+
+OAuthParameters ParseQueryString( const wstring& url );
+
+wstring OAuthCreateNonce();
+
+wstring OAuthCreateTimestamp();
+
+string HMACSHA1( const string& keyBytes, const string& data );
+
+wstring Base64String( const string& hash );
+
+string char2hex( char dec );
+
+string urlencode(const string &c);
+
+wstring UrlEncode( const wstring& url );
+
+wstring OAuthCreateSignature( const wstring& signatureBase, const wstring& consumerSecret, const wstring& requestTokenSecret );
+
+wstring OAuthConcatenateRequestElements( const wstring& httpMethod, wstring url, const wstring& parameters );
+
+wstring OAuthNormalizeRequestParameters( const OAuthParameters& requestParameters );
+
+//wstring OAuthNormalizeUrl( const wstring& url );
+
+/*OAuthParameters BuildSignedOAuthParameters( const OAuthParameters& requestParameters,
+ const wstring& url,
+ const wstring& httpMethod,
+ const wstring& consumerKey,
+ const wstring& consumerSecret,
+ const wstring& requestToken,
+ const wstring& requestTokenSecret,
+ const wstring& pin );*/
+
+/*wstring OAuthWebRequestSubmit(
+ const OAuthParameters& parameters,
+ const wstring& url
+ );*/
+
+// OAuthWebRequest used for all OAuth related queries
+//
+// consumerKey and consumerSecret - must be provided for every call, they identify the application
+// oauthToken and oauthTokenSecret - need to be provided for every call, except for the first token request before authorizing
+// pin - only used during authorization, when the user enters the PIN they received from the twitter website
+/*wstring OAuthWebRequestSubmit(
+ const wstring& url,
+ const wstring& httpMethod,
+ const wstring& consumerKey,
+ const wstring& consumerSecret,
+ const wstring& oauthToken = L"",
+ const wstring& oauthTokenSecret = L"",
+ const wstring& pin = L""
+ );*/
+
+
+
+int testfunc(int argc, _TCHAR* argv[]);
+
+#endif
diff --git a/protocols/Twitter/theme.cpp b/protocols/Twitter/theme.cpp index f35b3a5aa1..1da3724bb2 100644 --- a/protocols/Twitter/theme.cpp +++ b/protocols/Twitter/theme.cpp @@ -15,7 +15,6 @@ You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
-#include "common.h"
#include "theme.h"
#include "proto.h"
@@ -58,7 +57,7 @@ void InitIcons(void) for (int i=0; i<SIZEOF(icons); i++)
{
- if (icons[i].defIconID)
+ if(icons[i].defIconID)
{
mir_snprintf(setting_name,sizeof(setting_name),"%s_%s","Twitter",icons[i].name);
@@ -89,7 +88,7 @@ HANDLE GetIconHandle(const char* name) {
for(size_t i=0; i<SIZEOF(icons); i++)
{
- if (strcmp(icons[i].name,name) == 0)
+ if(strcmp(icons[i].name,name) == 0)
return hIconLibItem[i];
}
return 0;
@@ -105,12 +104,12 @@ static HANDLE g_hMenuEvts[3]; static TwitterProto * GetInstanceByHContact(HANDLE hContact)
{
char *proto = reinterpret_cast<char*>( CallService(MS_PROTO_GETCONTACTBASEPROTO,
- reinterpret_cast<WPARAM>(hContact),0));
- if (!proto)
+ reinterpret_cast<WPARAM>(hContact),0) );
+ if(!proto)
return 0;
for(int i=0; i<g_Instances.getCount(); i++)
- if (!strcmp(proto,g_Instances[i].m_szModuleName))
+ if(!strcmp(proto,g_Instances[i].m_szModuleName))
return &g_Instances[i];
return 0;
@@ -146,7 +145,7 @@ void InitContactMenus() g_hMenuEvts[1] = CreateServiceFunction(mi.pszService,
GlobalService<&TwitterProto::ReplyToTweet>);
g_hMenuItems[0] = reinterpret_cast<HANDLE>(
- CallService(MS_CLIST_ADDCONTACTMENUITEM,0,(LPARAM)&mi));
+ CallService(MS_CLIST_ADDCONTACTMENUITEM,0,(LPARAM)&mi) );
mi.position=-2000006000;
mi.icolibItem = GetIconHandle("homepage");
@@ -155,7 +154,7 @@ void InitContactMenus() g_hMenuEvts[2] = CreateServiceFunction(mi.pszService,
GlobalService<&TwitterProto::VisitHomepage>);
g_hMenuItems[1] = reinterpret_cast<HANDLE>(
- CallService(MS_CLIST_ADDCONTACTMENUITEM,0,(LPARAM)&mi));
+ CallService(MS_CLIST_ADDCONTACTMENUITEM,0,(LPARAM)&mi) );
}
void UninitContactMenus()
@@ -174,7 +173,7 @@ void ShowContactMenus(bool show) {
CLISTMENUITEM item = { sizeof(item) };
item.flags = CMIM_FLAGS | CMIF_NOTOFFLINE;
- if (!show)
+ if(!show)
item.flags |= CMIF_HIDDEN;
CallService(MS_CLIST_MODIFYMENUITEM,reinterpret_cast<WPARAM>(g_hMenuItems[i]),
diff --git a/protocols/Twitter/theme.h b/protocols/Twitter/theme.h index e74f5da2e3..fd331236fe 100644 --- a/protocols/Twitter/theme.h +++ b/protocols/Twitter/theme.h @@ -17,6 +17,8 @@ along with this program. If not, see <http://www.gnu.org/licenses/>. #pragma once
+#include "common.h"
+
void InitIcons(void);
HANDLE GetIconHandle(const char *name);
diff --git a/protocols/Twitter/tinyjson.hpp b/protocols/Twitter/tinyjson.hpp index 19e1210d84..240a3503c5 100644 --- a/protocols/Twitter/tinyjson.hpp +++ b/protocols/Twitter/tinyjson.hpp @@ -67,13 +67,13 @@ namespace json {
std::string strString;
- if (iUnicode < 0x0080)
+ if(iUnicode < 0x0080)
{
// character 0x0000 - 0x007f...
strString.push_back(0x00 | ((iUnicode & 0x007f) >> 0));
}
- else if (iUnicode < 0x0800)
+ else if(iUnicode < 0x0800)
{
// character 0x0080 - 0x07ff...
@@ -138,7 +138,7 @@ namespace json {
// 2.1: if it's no escape code, just append to the resulting string...
- if (*szStart != static_cast< typename Iterator::value_type >('\\'))
+ if(*szStart != static_cast< typename Iterator::value_type >('\\'))
{
// 2.1.1: append the character...
@@ -346,7 +346,7 @@ namespace json // 1.2: is it the end of the array? if yes => break the loop...
- if (boost::any_cast< array_delimiter >(var.get()) != NULL)
+ if(boost::any_cast< array_delimiter >(var.get()) != NULL)
{
break;
}
@@ -403,7 +403,7 @@ namespace json // 1.2: is it the end of the array? if yes => break the loop...
- if (boost::any_cast< object_delimiter >(var.get()) != NULL)
+ if(boost::any_cast< object_delimiter >(var.get()) != NULL)
{
break;
}
@@ -411,7 +411,7 @@ namespace json // 1.3: if this is not a pair, we have a problem...
pair * pPair = boost::any_cast< pair >(var.get());
- if (!pPair)
+ if(!pPair)
{
/* BIG PROBLEM!! */
@@ -571,7 +571,7 @@ namespace json // 3: if the input's end wasn't reached or if there is more than one object on the stack => cancel...
- if ((pi.stop != szEnd) || (st.size() != 1))
+ if((pi.stop != szEnd) || (st.size() != 1))
{
return json::grammar< typename Iterator::value_type >::variant(new boost::any());
}
diff --git a/protocols/Twitter/twitter.cpp b/protocols/Twitter/twitter.cpp index 9512292707..ff260f9fbd 100644 --- a/protocols/Twitter/twitter.cpp +++ b/protocols/Twitter/twitter.cpp @@ -15,18 +15,20 @@ You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
-//#include "common.h"
+#include "twitter.h"
+//#include "tc2.h"
#include <windows.h>
#include <cstring>
#include <sstream>
#include <ctime>
-#include "twitter.h"
-
#include "tinyjson.hpp"
#include <boost/lexical_cast.hpp>
+//#include "boost/spirit/include/classic_core.hpp"
+//#include "boost/spirit/include/classic_loops.hpp"
+
typedef json::grammar<char> js;
// utility functions
@@ -34,7 +36,7 @@ typedef json::grammar<char> js; template <typename T>
static T cast_and_decode(boost::any &a,bool allow_null)
{
- if (allow_null && a.type() == typeid(void))
+ if(allow_null && a.type() == typeid(void))
return T();
return boost::any_cast<T>(a);
}
@@ -42,7 +44,7 @@ static T cast_and_decode(boost::any &a,bool allow_null) template <>
static std::string cast_and_decode<std::string>(boost::any &a,bool allow_null)
{
- if (allow_null && a.type() == typeid(void))
+ if(allow_null && a.type() == typeid(void))
return std::string();
std::string s = boost::any_cast<std::string>(a);
@@ -62,15 +64,15 @@ static T retrieve(const js::object &o,const std::string &key,bool allow_null = f using boost::any_cast;
js::object::const_iterator i = o.find(key);
- if (i == o.end())
- throw std::exception( ("unable to retrieve key '"+key+"'").c_str());
+ if(i == o.end())
+ throw std::exception( ("unable to retrieve key '"+key+"'").c_str() );
try
{
return cast_and_decode<T>(*i->second,allow_null);
}
catch(const boost::bad_any_cast &)
{
- throw std::exception( ("unable to cast key '"+key+"' to target type").c_str());
+ throw std::exception( ("unable to cast key '"+key+"' to target type").c_str() );
}
}
@@ -79,18 +81,30 @@ static T retrieve(const js::object &o,const std::string &key,bool allow_null = f twitter::twitter() : base_url_("https://twitter.com/")
{}
-bool twitter::set_credentials(const std::string &username,const std::string &password,
- bool test)
+bool twitter::set_credentials(const std::string &username, const std::wstring &consumerKey, const std::wstring &consumerSecret,
+ const std::wstring &oauthAccessToken, const std::wstring &oauthAccessTokenSecret, const std::wstring &pin, bool test)
{
- username_ = username;
- password_ = password;
-
- if (test)
+ username_ = username;
+ consumerKey_ = consumerKey;
+ consumerSecret_ = consumerSecret;
+ oauthAccessToken_ = oauthAccessToken;
+ oauthAccessTokenSecret_ = oauthAccessTokenSecret;
+ pin_ = pin;
+
+ if(test)
return slurp(base_url_+"account/verify_credentials.json",http::get).code == 200;
else
return true;
}
+http::response twitter::request_token() {
+ return slurp(base_url_+"oauth/request_token",http::get);
+}
+
+http::response twitter::request_access_tokens() {
+ return slurp(base_url_+"oauth/access_token", http::get);
+}
+
void twitter::set_base_url(const std::string &base_url)
{
base_url_ = base_url;
@@ -111,29 +125,29 @@ std::vector<twitter_user> twitter::get_friends() std::vector<twitter_user> friends;
http::response resp = slurp(base_url_+"statuses/friends.json",http::get);
- if (resp.code != 200)
+ if(resp.code != 200)
throw bad_response();
- const js::variant var = json::parse( resp.data.begin(),resp.data.end());
- if (var->type() != typeid(js::array))
+ const js::variant var = json::parse( resp.data.begin(),resp.data.end() );
+ if(var->type() != typeid(js::array))
throw std::exception("unable to parse response");
const js::array &list = boost::any_cast<js::array>(*var);
for(js::array::const_iterator i=list.begin(); i!=list.end(); ++i)
{
- if ((*i)->type() == typeid(js::object))
+ if((*i)->type() == typeid(js::object))
{
const js::object &one = boost::any_cast<js::object>(**i);
twitter_user user;
user.username = retrieve<std::string>(one,"screen_name");
- user.real_name = retrieve<std::tstring>(one,"name",true);
+ user.real_name = retrieve<std::string>(one,"name",true);
user.profile_image_url = retrieve<std::string>(one,"profile_image_url",true);
- if (one.find("status") != one.end())
+ if(one.find("status") != one.end())
{
js::object &status = retrieve<js::object>(one,"status");
- user.status.text = retrieve<std::tstring>(status,"text");
+ user.status.text = retrieve<std::string>(status,"text");
user.status.id = retrieve<long long>(status,"id");
@@ -148,26 +162,26 @@ std::vector<twitter_user> twitter::get_friends() return friends;
}
-bool twitter::get_info(const std::tstring &name,twitter_user *info)
+bool twitter::get_info(const std::string &name,twitter_user *info)
{
- if (!info)
+ if(!info)
return false;
std::string url = base_url_+"users/show/"+http::url_encode(name)+".json";
http::response resp = slurp(url,http::get);
- if (resp.code != 200)
+ if(resp.code != 200)
throw bad_response();
- const js::variant var = json::parse( resp.data.begin(),resp.data.end());
- if (var->type() == typeid(js::object))
+ const js::variant var = json::parse( resp.data.begin(),resp.data.end() );
+ if(var->type() == typeid(js::object))
{
const js::object &user_info = boost::any_cast<js::object>(*var);
- if (user_info.find("error") != user_info.end())
+ if(user_info.find("error") != user_info.end())
return false;
info->username = retrieve<std::string>(user_info,"screen_name");
- info->real_name = retrieve<std::tstring>(user_info,"name",true);
+ info->real_name = retrieve<std::string>(user_info,"name",true);
info->profile_image_url = retrieve<std::string>(user_info,"profile_image_url",true);
return true;
@@ -176,26 +190,26 @@ bool twitter::get_info(const std::tstring &name,twitter_user *info) return false;
}
-bool twitter::get_info_by_email(const std::tstring &email,twitter_user *info)
+bool twitter::get_info_by_email(const std::string &email,twitter_user *info)
{
- if (!info)
+ if(!info)
return false;
std::string url = base_url_+"users/show.json?email="+http::url_encode(email);
http::response resp = slurp(url,http::get);
- if (resp.code != 200)
+ if(resp.code != 200)
throw bad_response();
- js::variant var = json::parse( resp.data.begin(),resp.data.end());
- if (var->type() == typeid(js::object))
+ js::variant var = json::parse( resp.data.begin(),resp.data.end() );
+ if(var->type() == typeid(js::object))
{
const js::object &user_info = boost::any_cast<js::object>(*var);
- if (user_info.find("error") != user_info.end())
+ if(user_info.find("error") != user_info.end())
return false;
info->username = retrieve<std::string>(user_info,"screen_name");
- info->real_name = retrieve<std::tstring>(user_info,"name",true);
+ info->real_name = retrieve<std::string>(user_info,"name",true);
info->profile_image_url = retrieve<std::string>(user_info,"profile_image_url",true);
return true;
@@ -204,56 +218,65 @@ bool twitter::get_info_by_email(const std::tstring &email,twitter_user *info) return false;
}
-twitter_user twitter::add_friend(const std::tstring &name)
+twitter_user twitter::add_friend(const std::string &name)
{
std::string url = base_url_+"friendships/create/"+http::url_encode(name)+".json";
twitter_user ret;
http::response resp = slurp(url,http::post);
- if (resp.code != 200)
+ if(resp.code != 200)
throw bad_response();
- js::variant var = json::parse( resp.data.begin(),resp.data.end());
- if (var->type() != typeid(js::object))
+ js::variant var = json::parse( resp.data.begin(),resp.data.end() );
+ if(var->type() != typeid(js::object))
throw std::exception("unable to parse response");
const js::object &user_info = boost::any_cast<js::object>(*var);
ret.username = retrieve<std::string>(user_info,"screen_name");
- ret.real_name = retrieve<std::tstring>(user_info,"name",true);
+ ret.real_name = retrieve<std::string>(user_info,"name",true);
ret.profile_image_url = retrieve<std::string>(user_info,"profile_image_url",true);
- if (user_info.find("status") != user_info.end())
+ if(user_info.find("status") != user_info.end())
{
// TODO: fill in more fields
const js::object &status = retrieve<js::object>(user_info,"status");
- ret.status.text = retrieve<std::tstring>(status,"text");
+ ret.status.text = retrieve<std::string>(status,"text");
}
return ret;
}
-void twitter::remove_friend(const std::tstring &name)
+void twitter::remove_friend(const std::string &name)
{
std::string url = base_url_+"friendships/destroy/"+http::url_encode(name)+".json";
slurp(url,http::post);
}
-void twitter::set_status(const std::tstring &text)
+void twitter::set_status(const std::string &text)
{
- if (text.size())
+ if(text.size())
{
- slurp(base_url_+"statuses/update.json",http::post,
+/* slurp(base_url_+"statuses/update.json",http::post,
"status="+http::url_encode(text)+
- "&source=mirandaim");
+ "&source=mirandaim");*/
+
+ //MessageBox(NULL, UTF8ToWide(text).c_str(), NULL, MB_OK);
+ std::wstring wTweet = UTF8ToWide(text);
+ OAuthParameters postParams;
+ postParams[L"status"] = UrlEncode(wTweet);
+
+ slurp(base_url_+"statuses/update.json",http::post, postParams);
}
}
-void twitter::send_direct(const std::tstring &name,const std::tstring &text)
+void twitter::send_direct(const std::string &name,const std::string &text)
{
- slurp(base_url_+"direct_messages/new.json",http::post,
- "user=" +http::url_encode(name)+
- "&text="+http::url_encode(text));
+ std::wstring temp = UTF8ToWide(text);
+ OAuthParameters postParams;
+ postParams[L"text"] = UrlEncode(temp);
+ postParams[L"screen_name"] = UTF8ToWide(name);
+ slurp(base_url_+"direct_messages/new.json", http::post, postParams);
}
std::vector<twitter_user> twitter::get_statuses(int count,twitter_id id)
@@ -261,31 +284,45 @@ std::vector<twitter_user> twitter::get_statuses(int count,twitter_id id) using boost::lexical_cast;
std::vector<twitter_user> statuses;
- std::string url = base_url_+"statuses/friends_timeline.json?count="+
+ std::string url = base_url_+"statuses/home_timeline.json?count="+
lexical_cast<std::string>(count);
- if (id != 0)
+ if(id != 0)
url += "&since_id="+boost::lexical_cast<std::string>(id);
http::response resp = slurp(url,http::get);
- if (resp.code != 200)
+ if(resp.code != 200)
throw bad_response();
- js::variant var = json::parse( resp.data.begin(),resp.data.end());
- if (var->type() != typeid(js::array))
+ js::variant var = json::parse( resp.data.begin(),resp.data.end() );
+ if(var->type() != typeid(js::array))
throw std::exception("unable to parse response");
const js::array &list = boost::any_cast<js::array>(*var);
for(js::array::const_iterator i=list.begin(); i!=list.end(); ++i)
{
- if ((*i)->type() == typeid(js::object))
+ if((*i)->type() == typeid(js::object))
{
const js::object &one = boost::any_cast<js::object>(**i);
const js::object &user = retrieve<js::object>(one,"user");
twitter_user u;
u.username = retrieve<std::string>(user,"screen_name");
+ bool isTruncated = retrieve<bool>(one,"truncated");
+
+ if (isTruncated) { // the tweet will be truncated unless we take action. i hate you twitter API
+
+ // here we grab the "retweeted_status" um.. section? it's in here that all the info we need is
+ const js::object &Retweet = retrieve<js::object>(one,"retweeted_status");
+ const js::object &RTUser = retrieve<js::object>(Retweet,"user");
+
+ std::string retweeteesName = retrieve<std::string>(RTUser,"screen_name"); // the user that is being retweeted
+ std::string retweetText = retrieve<std::string>(Retweet,"text"); // their tweet in all it's untruncated glory
+ u.status.text = "RT @" + retweeteesName + " " + retweetText; // mash it together in some format people will understand
+ }
+ else { // if it's not truncated, then the twitter API returns the native RT correctly anyway,
+ u.status.text = retrieve<std::string>(one,"text"); // so we can just pretend it doesn't happen
+ }
- u.status.text = retrieve<std::tstring>(one,"text");
u.status.id = retrieve<long long>(one,"id");
std::string timestr = retrieve<std::string>(one,"created_at");
u.status.time = parse_time(timestr);
@@ -303,28 +340,28 @@ std::vector<twitter_user> twitter::get_direct(twitter_id id) std::vector<twitter_user> messages;
std::string url = base_url_+"direct_messages.json";
- if (id != 0)
+ if(id != 0)
url += "?since_id="+boost::lexical_cast<std::string>(id);
http::response resp = slurp(url,http::get);
- if (resp.code != 200)
+ if(resp.code != 200)
throw bad_response();
- js::variant var = json::parse( resp.data.begin(),resp.data.end());
- if (var->type() != typeid(js::array))
+ js::variant var = json::parse( resp.data.begin(),resp.data.end() );
+ if(var->type() != typeid(js::array))
throw std::exception("unable to parse response");
const js::array &list = boost::any_cast<js::array>(*var);
for(js::array::const_iterator i=list.begin(); i!=list.end(); ++i)
{
- if ((*i)->type() == typeid(js::object))
+ if((*i)->type() == typeid(js::object))
{
const js::object &one = boost::any_cast<js::object>(**i);
twitter_user u;
u.username = retrieve<std::string>(one,"sender_screen_name");
- u.status.text = retrieve<std::tstring>(one,"text");
+ u.status.text = retrieve<std::string>(one,"text");
u.status.id = retrieve<long long>(one,"id");
std::string timestr = retrieve<std::string>(one,"created_at");
u.status.time = parse_time(timestr);
@@ -337,6 +374,66 @@ std::vector<twitter_user> twitter::get_direct(twitter_id id) return messages;
}
+string twitter::urlencode(const string &c)
+{
+
+ string escaped;
+ int max = c.length();
+ for(int i=0; i<max; i++)
+ {
+ if ( (48 <= c[i] && c[i] <= 57) ||//0-9
+ (65 <= c[i] && c[i] <= 90) ||//ABC...XYZ
+ (97 <= c[i] && c[i] <= 122) || //abc...xyz
+ (c[i]=='~' || c[i]=='-' || c[i]=='_' || c[i]=='.')
+ )
+ {
+ escaped.append( &c[i], 1);
+ }
+ else
+ {
+ escaped.append("%");
+ escaped.append( char2hex(c[i]) );//converts char 255 to string "FF"
+ }
+ }
+ return escaped;
+}
+
+
+wstring twitter::UrlEncode( const wstring& url )
+{
+ // multiple encodings r sux
+ return UTF8ToWide(urlencode(WideToUTF8(url)));
+}
+
+// char2hex and urlencode from http://www.zedwood.com/article/111/cpp-urlencode-function
+// modified according to http://oauth.net/core/1.0a/#encoding_parameters
+//
+//5.1. Parameter Encoding
+//
+//All parameter names and values are escaped using the [RFC3986]
+//percent-encoding (%xx) mechanism. Characters not in the unreserved character set
+//MUST be encoded. Characters in the unreserved character set MUST NOT be encoded.
+//Hexadecimal characters in encodings MUST be upper case.
+//Text names and values MUST be encoded as UTF-8
+// octets before percent-encoding them per [RFC3629].
+//
+// unreserved = ALPHA, DIGIT, '-', '.', '_', '~'
+
+string twitter::char2hex( char dec )
+{
+ char dig1 = (dec&0xF0)>>4;
+ char dig2 = (dec&0x0F);
+ if ( 0<= dig1 && dig1<= 9) dig1+=48; //0,48 in ascii
+ if (10<= dig1 && dig1<=15) dig1+=65-10; //A,65 in ascii
+ if ( 0<= dig2 && dig2<= 9) dig2+=48;
+ if (10<= dig2 && dig2<=15) dig2+=65-10;
+
+ string r;
+ r.append( &dig1, 1);
+ r.append( &dig2, 1);
+ return r;
+}
+
// Some Unices get this, now we do too!
time_t timegm(struct tm *t)
{
@@ -354,7 +451,7 @@ int parse_month(const char *m) {
for(size_t i=0; i<12; i++)
{
- if (strcmp(month_names[i],m) == 0)
+ if(strcmp(month_names[i],m) == 0)
return i;
}
return -1;
@@ -366,13 +463,13 @@ time_t parse_time(const std::string &s) char day[4],month[4];
char plus;
int zone;
- if (sscanf(s.c_str(),"%3s %3s %d %d:%d:%d %c%d %d",
+ if(sscanf(s.c_str(),"%3s %3s %d %d:%d:%d %c%d %d",
day,month,&t.tm_mday,&t.tm_hour,&t.tm_min,&t.tm_sec,
&plus,&zone,&t.tm_year) == 9)
{
t.tm_year -= 1900;
t.tm_mon = parse_month(month);
- if (t.tm_mon == -1)
+ if(t.tm_mon == -1)
return 0;
return timegm(&t);
}
diff --git a/protocols/Twitter/twitter.h b/protocols/Twitter/twitter.h index 06f8aca954..56d8914117 100644 --- a/protocols/Twitter/twitter.h +++ b/protocols/Twitter/twitter.h @@ -21,22 +21,21 @@ along with this program. If not, see <http://www.gnu.org/licenses/>. #include <vector>
#include <string>
-#include "http.h"
-#include <tchar.h>
+using std::string;
+using std::wstring;
+using std::map;
+using std::vector;
-#if !defined(tstring)
- #ifdef _UNICODE
- #define tstring wstring
- #else
- #define tstring string
- #endif
-#endif
+#include "http.h"
+#include "StringConv.h"
+#include "stdafx.h"
typedef unsigned long long twitter_id;
+typedef std::map<std::wstring, std::wstring> OAuthParameters;
struct twitter_status
{
- std::tstring text;
+ std::string text;
twitter_id id;
time_t time;
};
@@ -44,7 +43,7 @@ struct twitter_status struct twitter_user
{
std::string username;
- std::tstring real_name;
+ std::string real_name;
std::string profile_image_url;
twitter_status status;
};
@@ -64,33 +63,49 @@ class twitter {
public:
typedef std::vector<twitter_user> status_list;
- typedef std::map<std::tstring,status_list> status_map;
+ typedef std::map<std::string,status_list> status_map;
twitter();
- bool set_credentials(const std::string &username,const std::string &password, bool test = true);
+ bool twitter::set_credentials(const std::string&, const std::wstring&, const std::wstring&,
+ const std::wstring&, const std::wstring&, const std::wstring &, bool);
+
+ http::response twitter::request_token();
+ http::response twitter::request_access_tokens();
+
+
void set_base_url(const std::string &base_url);
const std::string & get_username() const;
const std::string & get_base_url() const;
- bool get_info(const std::tstring &name,twitter_user *);
- bool get_info_by_email(const std::tstring &email,twitter_user *);
+ bool get_info(const std::string &name,twitter_user *);
+ bool get_info_by_email(const std::string &email,twitter_user *);
std::vector<twitter_user> get_friends();
- twitter_user add_friend(const std::tstring &name);
- void remove_friend(const std::tstring &name);
+ twitter_user add_friend(const std::string &name);
+ void remove_friend(const std::string &name);
- void set_status(const std::tstring &text);
+ void set_status(const std::string &text);
std::vector<twitter_user> get_statuses(int count=20,twitter_id id=0);
- void send_direct(const std::tstring &name,const std::tstring &text);
+ void send_direct(const std::string &name,const std::string &text);
std::vector<twitter_user> get_direct(twitter_id id=0);
+ std::string urlencode(const std::string &c);
+ std::wstring UrlEncode( const std::wstring& url );
+ std::string char2hex( char dec );
+
protected:
- virtual http::response slurp(const std::string &,http::method, const std::string & = "") = 0;
+ virtual http::response slurp(const std::string &,http::method,
+ OAuthParameters postParams = OAuthParameters() ) = 0;
std::string username_;
std::string password_;
std::string base_url_;
+ std::wstring consumerKey_;
+ std::wstring consumerSecret_;
+ std::wstring oauthAccessToken_;
+ std::wstring oauthAccessTokenSecret_;
+ std::wstring pin_;
};
\ No newline at end of file diff --git a/protocols/Twitter/twitter.rc b/protocols/Twitter/twitter.rc index 0c32e19b59..6040a3699a 100644 --- a/protocols/Twitter/twitter.rc +++ b/protocols/Twitter/twitter.rc @@ -13,13 +13,11 @@ #undef APSTUDIO_READONLY_SYMBOLS
/////////////////////////////////////////////////////////////////////////////
-// English (U.S.) resources
+// English (United States) resources
#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU)
-#ifdef _WIN32
LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US
#pragma code_page(1252)
-#endif //_WIN32
#ifdef APSTUDIO_INVOKED
/////////////////////////////////////////////////////////////////////////////
@@ -57,14 +55,14 @@ STYLE DS_SETFONT | DS_FIXEDSYS | WS_CHILD EXSTYLE WS_EX_CONTROLPARENT
FONT 8, "MS Shell Dlg", 0, 0, 0x0
BEGIN
- LTEXT "Username:",IDC_STATIC,0,0,53,12
- EDITTEXT IDC_UN,54,0,131,12,ES_AUTOHSCROLL
- LTEXT "Password:",IDC_STATIC,0,16,53,12
- EDITTEXT IDC_PW,54,16,131,12,ES_PASSWORD | ES_AUTOHSCROLL
- LTEXT "Server:",IDC_STATIC,0,32,53,12
- COMBOBOX IDC_SERVER,54,32,131,12,CBS_DROPDOWN | WS_VSCROLL | WS_TABSTOP
+ LTEXT "Server:",IDC_STATIC,0,27,53,12
+ COMBOBOX IDC_SERVER,54,27,131,12,CBS_DROPDOWN | WS_VSCROLL | WS_TABSTOP
CONTROL "Create a new Twitter account",IDC_NEWACCOUNTLINK,
- "Hyperlink",WS_TABSTOP,0,57,174,12
+ "Hyperlink",WS_TABSTOP,0,72,174,12
+ EDITTEXT IDC_GROUP,54,49,131,12,ES_AUTOHSCROLL
+ LTEXT "Default group:",IDC_STATIC,0,50,54,14
+ LTEXT "Username:",IDC_STATIC,0,9,51,13
+ LTEXT "[Sign in to link your twitter account]",IDC_USERNAME,55,9,122,15
END
IDD_TWEET DIALOGEX 0, 0, 186, 64
@@ -83,20 +81,16 @@ STYLE DS_SETFONT | DS_FIXEDSYS | WS_CHILD EXSTYLE WS_EX_CONTROLPARENT
FONT 8, "MS Shell Dlg", 400, 0, 0x1
BEGIN
- GROUPBOX "User Details",IDC_USERDETAILS,7,7,152,51
- LTEXT "Username:",IDC_STATIC,15,20,41,8
- EDITTEXT IDC_UN,62,18,89,14,ES_AUTOHSCROLL
- LTEXT "Password:",IDC_STATIC,15,37,41,8
- EDITTEXT IDC_PW,62,35,89,14,ES_PASSWORD | ES_AUTOHSCROLL
- GROUPBOX "Misc. Options",IDC_MISC,7,67,152,65
- CONTROL "Use group chat for Twitter feed",IDC_CHATFEED,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,15,81,133,10
- LTEXT "Base URL:",IDC_STATIC,15,96,41,8
- COMBOBOX IDC_BASEURL,62,94,89,30,CBS_DROPDOWN | CBS_AUTOHSCROLL | WS_VSCROLL | WS_TABSTOP
- LTEXT "Polling rate:",IDC_STATIC,15,113,41,8
- LTEXT "Once every",IDC_STATIC,62,113,40,8
- EDITTEXT IDC_POLLRATE,103,111,30,14,ES_AUTOHSCROLL | ES_NUMBER
- LTEXT "sec",IDC_STATIC,138,113,19,8
+ GROUPBOX "Misc. Options",IDC_MISC,17,14,269,82
+ CONTROL "Use group chat for Twitter feed",IDC_CHATFEED,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,25,28,133,10
+ LTEXT "Base URL:",IDC_STATIC,25,43,41,8
+ COMBOBOX IDC_BASEURL,72,41,89,30,CBS_DROPDOWN | CBS_AUTOHSCROLL | WS_VSCROLL | WS_TABSTOP
+ LTEXT "Polling rate:",IDC_STATIC,25,60,41,8
+ LTEXT "Once every",IDC_STATIC,72,60,40,8
+ EDITTEXT IDC_POLLRATE,113,58,30,14,ES_AUTOHSCROLL | ES_NUMBER
+ LTEXT "sec",IDC_STATIC,148,60,19,8
LTEXT "Please cycle your connection for these changes to take effect",IDC_RECONNECT,53,202,199,8,NOT WS_VISIBLE
+ CONTROL "Treat tweets as messages",IDC_TWEET_MSG,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,25,76,139,10
END
IDD_OPTIONS_POPUPS DIALOGEX 0, 0, 305, 217
@@ -124,6 +118,17 @@ BEGIN CONTROL "But not during sign-on",IDC_NOSIGNONPOPUPS,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,27,19,87,10
END
+IDD_TWITTERPIN DIALOGEX 0, 0, 254, 96
+STYLE DS_SETFONT | DS_MODALFRAME | DS_FIXEDSYS | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU
+CAPTION "Enter Twitter PIN"
+FONT 8, "MS Shell Dlg", 400, 0, 0x1
+BEGIN
+ DEFPUSHBUTTON "OK",IDOK,133,73,50,14
+ PUSHBUTTON "Cancel",IDCANCEL,192,73,50,14
+ EDITTEXT IDC_PIN,50,42,154,14,ES_CENTER | ES_AUTOHSCROLL | ES_NUMBER
+ LTEXT "Enter the PIN provided by Twitter to complete your sign in. This is a one time process until you recreate your Miranda Twitter account.",IDC_STATIC,19,14,217,23
+END
+
/////////////////////////////////////////////////////////////////////////////
//
@@ -140,8 +145,12 @@ IDI_TWITTER ICON "icons\\twitter.ico" //
#ifdef APSTUDIO_INVOKED
-GUIDELINES DESIGNINFO
+GUIDELINES DESIGNINFO
BEGIN
+ IDD_TWITTERACCOUNT, DIALOG
+ BEGIN
+ END
+
IDD_TWEET, DIALOG
BEGIN
LEFTMARGIN, 7
@@ -154,6 +163,7 @@ BEGIN BEGIN
LEFTMARGIN, 7
RIGHTMARGIN, 298
+ VERTGUIDE, 25
TOPMARGIN, 7
BOTTOMMARGIN, 210
END
@@ -166,6 +176,17 @@ BEGIN TOPMARGIN, 7
BOTTOMMARGIN, 210
END
+
+ IDD_TWITTERPIN, DIALOG
+ BEGIN
+ LEFTMARGIN, 7
+ RIGHTMARGIN, 242
+ VERTGUIDE, 50
+ VERTGUIDE, 127
+ VERTGUIDE, 204
+ TOPMARGIN, 7
+ BOTTOMMARGIN, 87
+ END
END
#endif // APSTUDIO_INVOKED
@@ -176,8 +197,8 @@ END //
VS_VERSION_INFO VERSIONINFO
- FILEVERSION 0,0,8,4
- PRODUCTVERSION 0,0,8,4
+ FILEVERSION 1,0,0,0
+ PRODUCTVERSION 1,0,0,0
FILEFLAGSMASK 0x17L
#ifdef _DEBUG
FILEFLAGS 0x1L
@@ -193,12 +214,12 @@ BEGIN BLOCK "040904b0"
BEGIN
VALUE "FileDescription", "Twitter protocol plugin for Miranda IM"
- VALUE "FileVersion", "0, 0, 8, 4"
+ VALUE "FileVersion", "1.0.0.0"
VALUE "InternalName", "twitter"
- VALUE "LegalCopyright", "Copyright © 2009"
+ VALUE "LegalCopyright", "Copyright © 2009-2011"
VALUE "OriginalFilename", "twitter.dll"
VALUE "ProductName", "Miranda-Twitter"
- VALUE "ProductVersion", "0, 0, 8, 4"
+ VALUE "ProductVersion", "1.0.0.0"
END
END
BLOCK "VarFileInfo"
@@ -207,7 +228,7 @@ BEGIN END
END
-#endif // English (U.S.) resources
+#endif // English (United States) resources
/////////////////////////////////////////////////////////////////////////////
diff --git a/protocols/Twitter/twitter.sln b/protocols/Twitter/twitter.sln index 703c57af52..8254f4b005 100644 --- a/protocols/Twitter/twitter.sln +++ b/protocols/Twitter/twitter.sln @@ -1,7 +1,7 @@ 
Microsoft Visual Studio Solution File, Format Version 11.00
# Visual Studio 2010
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "twitter", "twitter.vcxproj", "{DADE9455-DC28-465A-9604-2CA28052B9FB}"
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Twitter", "twitter.vcxproj", "{DADE9455-DC28-465A-9604-2CA28052B9FB}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
diff --git a/protocols/Twitter/twitter.vcxproj b/protocols/Twitter/twitter.vcxproj index 928dfe2fed..7be07ed059 100644 --- a/protocols/Twitter/twitter.vcxproj +++ b/protocols/Twitter/twitter.vcxproj @@ -19,7 +19,7 @@ </ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
- <ProjectGuid>{12FFF2B0-0D0B-430B-A4C6-1577CA98F598}</ProjectGuid>
+ <ProjectGuid>{DADE9455-DC28-465A-9604-2CA28052B9FB}</ProjectGuid>
<RootNamespace>twitter</RootNamespace>
<Keyword>Win32Proj</Keyword>
<ProjectName>Twitter</ProjectName>
@@ -60,7 +60,7 @@ </ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup>
- <_ProjectFileVersion>10.0.40219.1</_ProjectFileVersion>
+ <_ProjectFileVersion>10.0.30319.1</_ProjectFileVersion>
<OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)$(Configuration)\Plugins\</OutDir>
<OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(SolutionDir)$(Configuration)64\Plugins\</OutDir>
<IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)$(Configuration)\Obj\$(ProjectName)\</IntDir>
@@ -73,63 +73,74 @@ <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(SolutionDir)$(Configuration)64\Obj\$(ProjectName)\</IntDir>
<LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">false</LinkIncremental>
<LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Release|x64'">false</LinkIncremental>
+ <CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">AllRules.ruleset</CodeAnalysisRuleSet>
+ <CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">AllRules.ruleset</CodeAnalysisRuleSet>
+ <CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" />
+ <CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" />
+ <CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" />
+ <CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" />
+ <CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">AllRules.ruleset</CodeAnalysisRuleSet>
+ <CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Release|x64'">AllRules.ruleset</CodeAnalysisRuleSet>
+ <CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" />
+ <CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Release|x64'" />
+ <CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" />
+ <CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Release|x64'" />
+ <IncludePath Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">C:\code;$(IncludePath)</IncludePath>
+ <IncludePath Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">C:\code;$(IncludePath)</IncludePath>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<Optimization>Disabled</Optimization>
- <AdditionalIncludeDirectories>..\..\include;..\..\..\boost_1_49_0;..\..\plugins\ExternalAPI;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories>..\..\include;..\..\plugins\ExternalAPI;.\oauth\src;..\..\..\boost_1_49_0;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;_WINDOWS;_USRDLL;TWITTER_EXPORTS;_CRT_SECURE_NO_WARNINGS;NOMINMAX;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<MinimalRebuild>true</MinimalRebuild>
<BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
- <PrecompiledHeader>Use</PrecompiledHeader>
+ <PrecompiledHeader>
+ </PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<DebugInformationFormat>EditAndContinue</DebugInformationFormat>
- <PrecompiledHeaderFile>common.h</PrecompiledHeaderFile>
</ClCompile>
<Link>
<GenerateDebugInformation>true</GenerateDebugInformation>
<SubSystem>Windows</SubSystem>
<TargetMachine>MachineX86</TargetMachine>
+ <AdditionalDependencies>kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;wininet.lib;shlwapi.lib;%(AdditionalDependencies)</AdditionalDependencies>
+ <OutputFile>D:\Miranda IM\Plugins\$(TargetName)$(TargetExt)</OutputFile>
<ImportLibrary>$(IntDir)$(TargetName).lib</ImportLibrary>
</Link>
- <ResourceCompile>
- <AdditionalIncludeDirectories>..\..\include\msapi</AdditionalIncludeDirectories>
- </ResourceCompile>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<ClCompile>
<Optimization>Disabled</Optimization>
- <AdditionalIncludeDirectories>..\..\include;..\..\..\boost_1_49_0;..\..\plugins\ExternalAPI;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories>..\..\include;..\..\plugins\ExternalAPI;.\oauth\src;..\..\..\boost_1_49_0;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN64;_WINDOWS;_USRDLL;TWITTER_EXPORTS;_CRT_SECURE_NO_WARNINGS;NOMINMAX;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
- <PrecompiledHeader>Use</PrecompiledHeader>
+ <PrecompiledHeader>
+ </PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
- <PrecompiledHeaderFile>common.h</PrecompiledHeaderFile>
</ClCompile>
<Link>
<GenerateDebugInformation>true</GenerateDebugInformation>
<SubSystem>Windows</SubSystem>
+ <AdditionalDependencies>kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;wininet.lib;shlwapi.lib;%(AdditionalDependencies)</AdditionalDependencies>
<ImportLibrary>$(IntDir)$(TargetName).lib</ImportLibrary>
</Link>
- <ResourceCompile>
- <AdditionalIncludeDirectories>..\..\include\msapi</AdditionalIncludeDirectories>
- </ResourceCompile>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
- <AdditionalIncludeDirectories>..\..\include;..\..\..\boost_1_49_0;..\..\plugins\ExternalAPI;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories>..\..\include;..\..\plugins\ExternalAPI;.\oauth\src;..\..\..\boost_1_49_0;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;NDEBUG;_WINDOWS;_USRDLL;TWITTER_EXPORTS;_CRT_SECURE_NO_WARNINGS;NOMINMAX;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>
- <PrecompiledHeader>Use</PrecompiledHeader>
+ <PrecompiledHeader>
+ </PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
<Optimization>Full</Optimization>
+ <InlineFunctionExpansion>OnlyExplicitInline</InlineFunctionExpansion>
<FavorSizeOrSpeed>Size</FavorSizeOrSpeed>
- <StringPooling>true</StringPooling>
- <PrecompiledHeaderFile>common.h</PrecompiledHeaderFile>
</ClCompile>
<Link>
<GenerateDebugInformation>true</GenerateDebugInformation>
@@ -139,22 +150,19 @@ <TargetMachine>MachineX86</TargetMachine>
<ImportLibrary>$(IntDir)$(TargetName).lib</ImportLibrary>
</Link>
- <ResourceCompile>
- <AdditionalIncludeDirectories>..\..\include\msapi</AdditionalIncludeDirectories>
- </ResourceCompile>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<ClCompile>
- <AdditionalIncludeDirectories>..\..\include;..\..\..\boost_1_49_0;..\..\plugins\ExternalAPI;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories>..\..\include;..\..\plugins\ExternalAPI;.\oauth\src;..\..\..\boost_1_49_0;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN64;NDEBUG;_WINDOWS;_USRDLL;TWITTER_EXPORTS;_CRT_SECURE_NO_WARNINGS;NOMINMAX;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>
- <PrecompiledHeader>Use</PrecompiledHeader>
+ <PrecompiledHeader>
+ </PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
<Optimization>Full</Optimization>
+ <InlineFunctionExpansion>OnlyExplicitInline</InlineFunctionExpansion>
<FavorSizeOrSpeed>Size</FavorSizeOrSpeed>
- <StringPooling>true</StringPooling>
- <PrecompiledHeaderFile>common.h</PrecompiledHeaderFile>
</ClCompile>
<Link>
<GenerateDebugInformation>true</GenerateDebugInformation>
@@ -163,38 +171,34 @@ <EnableCOMDATFolding>true</EnableCOMDATFolding>
<ImportLibrary>$(IntDir)$(TargetName).lib</ImportLibrary>
</Link>
- <ResourceCompile>
- <AdditionalIncludeDirectories>..\..\include\msapi</AdditionalIncludeDirectories>
- </ResourceCompile>
</ItemDefinitionGroup>
<ItemGroup>
+ <ClCompile Include="Base64Coder.cpp" />
<ClCompile Include="chat.cpp" />
<ClCompile Include="connection.cpp" />
<ClCompile Include="contacts.cpp" />
<ClCompile Include="http.cpp" />
- <ClCompile Include="main.cpp">
- <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">Create</PrecompiledHeader>
- <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">Create</PrecompiledHeader>
- <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">Create</PrecompiledHeader>
- <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|x64'">Create</PrecompiledHeader>
- </ClCompile>
+ <ClCompile Include="main.cpp" />
+ <ClCompile Include="oauth.cpp" />
<ClCompile Include="proto.cpp" />
+ <ClCompile Include="StringConv.cpp" />
+ <ClCompile Include="StringUtil.cpp" />
<ClCompile Include="stubs.cpp" />
<ClCompile Include="theme.cpp" />
- <ClCompile Include="twitter.cpp">
- <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">NotUsing</PrecompiledHeader>
- <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">NotUsing</PrecompiledHeader>
- <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">NotUsing</PrecompiledHeader>
- <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|x64'">NotUsing</PrecompiledHeader>
- </ClCompile>
+ <ClCompile Include="twitter.cpp" />
<ClCompile Include="ui.cpp" />
<ClCompile Include="utility.cpp" />
</ItemGroup>
<ItemGroup>
+ <ClInclude Include="Base64Coder.h" />
<ClInclude Include="common.h" />
<ClInclude Include="http.h" />
+ <ClInclude Include="oauth.h" />
<ClInclude Include="proto.h" />
<ClInclude Include="resource.h" />
+ <ClInclude Include="stdafx.h" />
+ <ClInclude Include="StringConv.h" />
+ <ClInclude Include="StringUtil.h" />
<ClInclude Include="theme.h" />
<ClInclude Include="tinyjson.hpp" />
<ClInclude Include="twitter.h" />
diff --git a/protocols/Twitter/twitter.vcxproj.filters b/protocols/Twitter/twitter.vcxproj.filters index 70ac860513..020644005c 100644 --- a/protocols/Twitter/twitter.vcxproj.filters +++ b/protocols/Twitter/twitter.vcxproj.filters @@ -48,6 +48,18 @@ <ClCompile Include="utility.cpp">
<Filter>Source Files</Filter>
</ClCompile>
+ <ClCompile Include="Base64Coder.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="StringConv.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="StringUtil.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="oauth.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
</ItemGroup>
<ItemGroup>
<ClInclude Include="common.h">
@@ -80,6 +92,21 @@ <ClInclude Include="version.h">
<Filter>Header Files</Filter>
</ClInclude>
+ <ClInclude Include="StringUtil.h">
+ <Filter>Header Files</Filter>
+ </ClInclude>
+ <ClInclude Include="StringConv.h">
+ <Filter>Header Files</Filter>
+ </ClInclude>
+ <ClInclude Include="stdafx.h">
+ <Filter>Header Files</Filter>
+ </ClInclude>
+ <ClInclude Include="Base64Coder.h">
+ <Filter>Header Files</Filter>
+ </ClInclude>
+ <ClInclude Include="oauth.h">
+ <Filter>Header Files</Filter>
+ </ClInclude>
</ItemGroup>
<ItemGroup>
<None Include="icons\twitter.ico">
diff --git a/protocols/Twitter/ui.cpp b/protocols/Twitter/ui.cpp index b3e68542df..ab2dbfdca7 100644 --- a/protocols/Twitter/ui.cpp +++ b/protocols/Twitter/ui.cpp @@ -3,19 +3,18 @@ Copyright © 2009 Jim Porter This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
-the Free Software Foundation, either version 2 of the License, or
+the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
-This program is distributed in the hope that it will be useful,
+This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
-along with this program. If not, see <http://www.gnu.org/licenses/>.
+along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
-#include "common.h"
#include "ui.h"
#include <cstdio>
@@ -25,11 +24,11 @@ along with this program. If not, see <http://www.gnu.org/licenses/>. #include "twitter.h"
static const TCHAR *sites[] = {
- _T("https://twitter.com/"),
+ _T("https://twitter.com/"),
_T("https://identi.ca/api/")
};
-INT_PTR CALLBACK first_run_dialog(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam)
+INT_PTR CALLBACK first_run_dialog(HWND hwndDlg,UINT msg,WPARAM wParam,LPARAM lParam)
{
TwitterProto *proto;
@@ -39,74 +38,93 @@ INT_PTR CALLBACK first_run_dialog(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM TranslateDialogDefault(hwndDlg);
proto = reinterpret_cast<TwitterProto*>(lParam);
- SetWindowLong(hwndDlg, GWL_USERDATA, lParam);
+ SetWindowLong(hwndDlg,GWL_USERDATA,lParam);
DBVARIANT dbv;
- if ( !DBGetContactSettingTString(0, proto->ModuleName(), TWITTER_KEY_UN, &dbv)) {
- SetDlgItemText(hwndDlg, IDC_UN, dbv.ptszVal);
+
+ if( !DBGetContactSettingTString(0,proto->ModuleName(),TWITTER_KEY_GROUP,&dbv) )
+ {
+ SetDlgItemText(hwndDlg,IDC_GROUP,dbv.ptszVal);
DBFreeVariant(&dbv);
}
+ else
+ {
+ SetDlgItemText(hwndDlg,IDC_GROUP,L"Twitter");
+ }
- if ( !DBGetContactSettingString(0, proto->ModuleName(), TWITTER_KEY_PASS, &dbv)) {
- CallService(MS_DB_CRYPT_DECODESTRING, strlen(dbv.pszVal)+1,
- reinterpret_cast<LPARAM>(dbv.pszVal));
- SetDlgItemTextA(hwndDlg, IDC_PW, dbv.pszVal);
+ if( !DBGetContactSettingString(0,proto->ModuleName(),TWITTER_KEY_UN,&dbv) )
+ {
+ SetDlgItemTextA(hwndDlg,IDC_USERNAME,dbv.pszVal);
DBFreeVariant(&dbv);
}
+ /*if ( !DBGetContactSettingString(0,proto->ModuleName(),TWITTER_KEY_PASS,&dbv) )
+ {
+ CallService(MS_DB_CRYPT_DECODESTRING,strlen(dbv.pszVal)+1,
+ reinterpret_cast<LPARAM>(dbv.pszVal));
+ SetDlgItemTextA(hwndDlg,IDC_PW,dbv.pszVal);
+ DBFreeVariant(&dbv);
+ }*/
+
for(size_t i=0; i<SIZEOF(sites); i++)
{
- SendDlgItemMessage(hwndDlg, IDC_SERVER, CB_ADDSTRING, 0,
+ SendDlgItemMessage(hwndDlg,IDC_SERVER,CB_ADDSTRING,0,
reinterpret_cast<LPARAM>(sites[i]));
}
- if ( !DBGetContactSettingString(0, proto->ModuleName(), TWITTER_KEY_BASEURL, &dbv))
+ if( !DBGetContactSettingString(0,proto->ModuleName(),TWITTER_KEY_BASEURL,&dbv) )
{
- SetDlgItemTextA(hwndDlg, IDC_SERVER, dbv.pszVal);
+ SetDlgItemTextA(hwndDlg,IDC_SERVER,dbv.pszVal);
DBFreeVariant(&dbv);
}
else
{
- SendDlgItemMessage(hwndDlg, IDC_SERVER, CB_SETCURSEL, 0, 0);
+ SendDlgItemMessage(hwndDlg,IDC_SERVER,CB_SETCURSEL,0,0);
}
return true;
case WM_COMMAND:
- if (LOWORD(wParam) == IDC_NEWACCOUNTLINK)
+ if(LOWORD(wParam) == IDC_NEWACCOUNTLINK)
{
- CallService(MS_UTILS_OPENURL, 1, reinterpret_cast<LPARAM>
- ("http://twitter.com/signup"));
+ CallService(MS_UTILS_OPENURL,1,reinterpret_cast<LPARAM>
+ ("http://twitter.com/signup") );
return true;
}
- if (GetWindowLong(hwndDlg, GWL_USERDATA)) // Window is done initializing
+ if(GetWindowLong(hwndDlg,GWL_USERDATA)) // Window is done initializing
{
switch(HIWORD(wParam))
{
case EN_CHANGE:
case CBN_EDITCHANGE:
case CBN_SELCHANGE:
- SendMessage(GetParent(hwndDlg), PSM_CHANGED, 0, 0);
+ SendMessage(GetParent(hwndDlg),PSM_CHANGED,0,0);
}
}
break;
- case WM_NOTIFY:
- if (reinterpret_cast<NMHDR*>(lParam)->code == PSN_APPLY)
+ case WM_NOTIFY: // might be able to get rid of this bit?
+ if(reinterpret_cast<NMHDR*>(lParam)->code == PSN_APPLY)
{
- proto = reinterpret_cast<TwitterProto*>(GetWindowLong(hwndDlg, GWL_USERDATA));
+ proto = reinterpret_cast<TwitterProto*>(GetWindowLong(hwndDlg,GWL_USERDATA));
char str[128];
+ TCHAR tstr[128];
+
+ /*
+ GetDlgItemTextA(hwndDlg,IDC_UN,str,sizeof(str));
+ DBWriteContactSettingString(0,proto->ModuleName(),TWITTER_KEY_UN,str);
- GetDlgItemTextA(hwndDlg, IDC_UN, str, sizeof(str));
- DBWriteContactSettingString(0, proto->ModuleName(), TWITTER_KEY_UN, str);
+ GetDlgItemTextA(hwndDlg,IDC_PW,str,sizeof(str));
+ CallService(MS_DB_CRYPT_ENCODESTRING,sizeof(str),reinterpret_cast<LPARAM>(str));
+ DBWriteContactSettingString(0,proto->ModuleName(),TWITTER_KEY_PASS,str);
+ */
- GetDlgItemTextA(hwndDlg, IDC_PW, str, sizeof(str));
- CallService(MS_DB_CRYPT_ENCODESTRING, sizeof(str), reinterpret_cast<LPARAM>(str));
- DBWriteContactSettingString(0, proto->ModuleName(), TWITTER_KEY_PASS, str);
+ GetDlgItemTextA(hwndDlg,IDC_SERVER,str,sizeof(str)-1);
+ if(str[strlen(str)-1] != '/')
+ strncat(str,"/",sizeof(str));
+ DBWriteContactSettingString(0,proto->ModuleName(),TWITTER_KEY_BASEURL,str);
- GetDlgItemTextA(hwndDlg, IDC_SERVER, str, sizeof(str)-1);
- if (str[strlen(str)-1] != '/')
- strncat(str, "/", sizeof(str));
- DBWriteContactSettingString(0, proto->ModuleName(), TWITTER_KEY_BASEURL, str);
+ GetDlgItemText(hwndDlg,IDC_GROUP,tstr,SIZEOF(tstr));
+ DBWriteContactSettingTString(0,proto->ModuleName(),TWITTER_KEY_GROUP,tstr);
return true;
}
@@ -116,7 +134,7 @@ INT_PTR CALLBACK first_run_dialog(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM return false;
}
-INT_PTR CALLBACK tweet_proc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam)
+INT_PTR CALLBACK tweet_proc(HWND hwndDlg,UINT msg,WPARAM wParam,LPARAM lParam)
{
TwitterProto *proto;
@@ -126,42 +144,42 @@ INT_PTR CALLBACK tweet_proc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam TranslateDialogDefault(hwndDlg);
proto = reinterpret_cast<TwitterProto*>(lParam);
- SetWindowLong(hwndDlg, GWL_USERDATA, lParam);
- SendDlgItemMessage(hwndDlg, IDC_TWEETMSG, EM_LIMITTEXT, 140, 0);
- SetDlgItemText(hwndDlg, IDC_CHARACTERS, _T("140"));
+ SetWindowLong(hwndDlg,GWL_USERDATA,lParam);
+ SendDlgItemMessage(hwndDlg,IDC_TWEETMSG,EM_LIMITTEXT,140,0);
+ SetDlgItemText(hwndDlg,IDC_CHARACTERS,_T("140"));
// Set window title
TCHAR title[512];
- mir_sntprintf(title, SIZEOF(title), _T("Send Tweet for %s"), proto->m_tszUserName);
- SendMessage(hwndDlg, WM_SETTEXT, 0, (LPARAM)title);
+ mir_sntprintf(title,SIZEOF(title),_T("Send Tweet for %s"),proto->m_tszUserName);
+ SendMessage(hwndDlg,WM_SETTEXT,0,(LPARAM)title);
return true;
case WM_COMMAND:
- if (LOWORD(wParam) == IDOK)
+ if(LOWORD(wParam) == IDOK)
{
TCHAR msg[141];
- proto = reinterpret_cast<TwitterProto*>(GetWindowLong(hwndDlg, GWL_USERDATA));
+ proto = reinterpret_cast<TwitterProto*>(GetWindowLong(hwndDlg,GWL_USERDATA));
- GetDlgItemText(hwndDlg, IDC_TWEETMSG, msg, SIZEOF(msg));
- ShowWindow(hwndDlg, SW_HIDE);
+ GetDlgItemText(hwndDlg,IDC_TWEETMSG,msg,SIZEOF(msg));
+ ShowWindow(hwndDlg,SW_HIDE);
- char *narrow = mir_t2a_cp(msg, CP_UTF8);
- ForkThread(&TwitterProto::SendTweetWorker, proto, narrow);
+ char *narrow = mir_t2a_cp(msg,CP_UTF8);
+ ForkThread(&TwitterProto::SendTweetWorker, proto,narrow);
- EndDialog(hwndDlg, wParam);
+ EndDialog(hwndDlg, wParam);
return true;
}
- else if (LOWORD(wParam) == IDCANCEL)
+ else if(LOWORD(wParam) == IDCANCEL)
{
- EndDialog(hwndDlg, wParam);
+ EndDialog(hwndDlg, wParam);
return true;
}
- else if (LOWORD(wParam) == IDC_TWEETMSG && HIWORD(wParam) == EN_CHANGE)
+ else if(LOWORD(wParam) == IDC_TWEETMSG && HIWORD(wParam) == EN_CHANGE)
{
- size_t len = SendDlgItemMessage(hwndDlg, IDC_TWEETMSG, WM_GETTEXTLENGTH, 0, 0);
+ size_t len = SendDlgItemMessage(hwndDlg,IDC_TWEETMSG,WM_GETTEXTLENGTH,0,0);
char str[4];
- _snprintf(str, sizeof(str), "%d", 140-len);
- SetDlgItemTextA(hwndDlg, IDC_CHARACTERS, str);
+ _snprintf(str,sizeof(str),"%d",140-len);
+ SetDlgItemTextA(hwndDlg,IDC_CHARACTERS,str);
return true;
}
@@ -170,15 +188,15 @@ INT_PTR CALLBACK tweet_proc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam case WM_SETREPLY:
{
char foo[512];
- _snprintf(foo, sizeof(foo), "@%s ", (char*)wParam);
+ _snprintf(foo,sizeof(foo),"@%s ",(char*)wParam);
size_t len = strlen(foo);
- SetDlgItemTextA(hwndDlg, IDC_TWEETMSG, foo);
- SendDlgItemMessage(hwndDlg, IDC_TWEETMSG, EM_SETSEL, len, len);
+ SetDlgItemTextA(hwndDlg,IDC_TWEETMSG,foo);
+ SendDlgItemMessage(hwndDlg,IDC_TWEETMSG,EM_SETSEL,len,len);
char str[4];
- _snprintf(str, sizeof(str), "%d", 140-len);
- SetDlgItemTextA(hwndDlg, IDC_CHARACTERS, str);
+ _snprintf(str,sizeof(str),"%d",140-len);
+ SetDlgItemTextA(hwndDlg,IDC_CHARACTERS,str);
return true;
}
@@ -188,7 +206,7 @@ INT_PTR CALLBACK tweet_proc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam return false;
}
-INT_PTR CALLBACK options_proc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam)
+INT_PTR CALLBACK options_proc(HWND hwndDlg,UINT msg,WPARAM wParam,LPARAM lParam)
{
TwitterProto *proto;
@@ -200,52 +218,55 @@ INT_PTR CALLBACK options_proc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lPar proto = reinterpret_cast<TwitterProto*>(lParam);
DBVARIANT dbv;
- if ( !DBGetContactSettingString(0, proto->ModuleName(), TWITTER_KEY_UN, &dbv))
+ if( !DBGetContactSettingString(0,proto->ModuleName(),TWITTER_KEY_UN,&dbv) )
{
- SetDlgItemTextA(hwndDlg, IDC_UN, dbv.pszVal);
+ SetDlgItemTextA(hwndDlg,IDC_UN,dbv.pszVal);
DBFreeVariant(&dbv);
}
- if ( !DBGetContactSettingString(0, proto->ModuleName(), TWITTER_KEY_PASS, &dbv))
+ /*if( !DBGetContactSettingString(0,proto->ModuleName(),TWITTER_KEY_PASS,&dbv) )
{
- CallService(MS_DB_CRYPT_DECODESTRING, strlen(dbv.pszVal)+1,
+ CallService(MS_DB_CRYPT_DECODESTRING,strlen(dbv.pszVal)+1,
reinterpret_cast<LPARAM>(dbv.pszVal));
- SetDlgItemTextA(hwndDlg, IDC_PW, dbv.pszVal);
+ SetDlgItemTextA(hwndDlg,IDC_PW,dbv.pszVal);
DBFreeVariant(&dbv);
- }
+ }*/
- CheckDlgButton(hwndDlg, IDC_CHATFEED, DBGetContactSettingByte(0,
- proto->ModuleName(), TWITTER_KEY_CHATFEED, 0));
+ CheckDlgButton(hwndDlg,IDC_CHATFEED,DBGetContactSettingByte(0,
+ proto->ModuleName(),TWITTER_KEY_CHATFEED,0));
for(size_t i=0; i<SIZEOF(sites); i++)
{
- SendDlgItemMessage(hwndDlg, IDC_BASEURL, CB_ADDSTRING, 0,
+ SendDlgItemMessage(hwndDlg,IDC_BASEURL,CB_ADDSTRING,0,
reinterpret_cast<LPARAM>(sites[i]));
}
- if ( !DBGetContactSettingString(0, proto->ModuleName(), TWITTER_KEY_BASEURL, &dbv))
+ if( !DBGetContactSettingString(0,proto->ModuleName(),TWITTER_KEY_BASEURL,&dbv) )
{
- SetDlgItemTextA(hwndDlg, IDC_BASEURL, dbv.pszVal);
+ SetDlgItemTextA(hwndDlg,IDC_BASEURL,dbv.pszVal);
DBFreeVariant(&dbv);
}
else
{
- SendDlgItemMessage(hwndDlg, IDC_BASEURL, CB_SETCURSEL, 0, 0);
+ SendDlgItemMessage(hwndDlg,IDC_BASEURL,CB_SETCURSEL,0,0);
}
char pollrate_str[32];
- mir_snprintf(pollrate_str, sizeof(pollrate_str), "%d",
- DBGetContactSettingDword(0, proto->ModuleName(), TWITTER_KEY_POLLRATE, 80));
- SetDlgItemTextA(hwndDlg, IDC_POLLRATE, pollrate_str);
+ mir_snprintf(pollrate_str,sizeof(pollrate_str),"%d",
+ DBGetContactSettingDword(0,proto->ModuleName(),TWITTER_KEY_POLLRATE,80) );
+ SetDlgItemTextA(hwndDlg,IDC_POLLRATE,pollrate_str);
+
+ CheckDlgButton(hwndDlg,IDC_TWEET_MSG,DBGetContactSettingByte(0,
+ proto->ModuleName(),TWITTER_KEY_TWEET_TO_MSG,0));
// Do this last so that any events propagated by pre-filling the form don't
// instigate a PSM_CHANGED message
- SetWindowLong(hwndDlg, GWL_USERDATA, lParam);
+ SetWindowLong(hwndDlg,GWL_USERDATA,lParam);
break;
case WM_COMMAND:
- if (GetWindowLong(hwndDlg, GWL_USERDATA)) // Window is done initializing
+ if(GetWindowLong(hwndDlg,GWL_USERDATA)) // Window is done initializing
{
switch(HIWORD(wParam))
{
@@ -258,39 +279,42 @@ INT_PTR CALLBACK options_proc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lPar case IDC_UN:
case IDC_PW:
case IDC_BASEURL:
- ShowWindow(GetDlgItem(hwndDlg, IDC_RECONNECT), SW_SHOW);
+ ShowWindow(GetDlgItem(hwndDlg,IDC_RECONNECT),SW_SHOW);
}
- SendMessage(GetParent(hwndDlg), PSM_CHANGED, 0, 0);
+ SendMessage(GetParent(hwndDlg),PSM_CHANGED,0,0);
}
}
break;
case WM_NOTIFY:
- if (reinterpret_cast<NMHDR*>(lParam)->code == PSN_APPLY)
+ if(reinterpret_cast<NMHDR*>(lParam)->code == PSN_APPLY)
{
- proto = reinterpret_cast<TwitterProto*>(GetWindowLong(hwndDlg, GWL_USERDATA));
+ proto = reinterpret_cast<TwitterProto*>(GetWindowLong(hwndDlg,GWL_USERDATA));
char str[128];
- GetDlgItemTextA(hwndDlg, IDC_UN, str, sizeof(str));
- DBWriteContactSettingString(0, proto->ModuleName(), TWITTER_KEY_UN, str);
+ GetDlgItemTextA(hwndDlg,IDC_UN,str,sizeof(str));
+ DBWriteContactSettingString(0,proto->ModuleName(),TWITTER_KEY_UN,str);
- GetDlgItemTextA(hwndDlg, IDC_PW, str, sizeof(str));
- CallService(MS_DB_CRYPT_ENCODESTRING, sizeof(str), reinterpret_cast<LPARAM>(str));
- DBWriteContactSettingString(0, proto->ModuleName(), TWITTER_KEY_PASS, str);
+ /*GetDlgItemTextA(hwndDlg,IDC_PW,str,sizeof(str));
+ CallService(MS_DB_CRYPT_ENCODESTRING,sizeof(str),reinterpret_cast<LPARAM>(str));
+ DBWriteContactSettingString(0,proto->ModuleName(),TWITTER_KEY_PASS,str);*/
- GetDlgItemTextA(hwndDlg, IDC_BASEURL, str, sizeof(str)-1);
- if (str[strlen(str)-1] != '/')
- strncat(str, "/", sizeof(str));
- DBWriteContactSettingString(0, proto->ModuleName(), TWITTER_KEY_BASEURL, str);
+ GetDlgItemTextA(hwndDlg,IDC_BASEURL,str,sizeof(str)-1);
+ if(str[strlen(str)-1] != '/')
+ strncat(str,"/",sizeof(str));
+ DBWriteContactSettingString(0,proto->ModuleName(),TWITTER_KEY_BASEURL,str);
- DBWriteContactSettingByte(0, proto->ModuleName(), TWITTER_KEY_CHATFEED,
- IsDlgButtonChecked(hwndDlg, IDC_CHATFEED));
+ DBWriteContactSettingByte(0,proto->ModuleName(),TWITTER_KEY_CHATFEED,
+ IsDlgButtonChecked(hwndDlg,IDC_CHATFEED));
- GetDlgItemTextA(hwndDlg, IDC_POLLRATE, str, sizeof(str));
+ GetDlgItemTextA(hwndDlg,IDC_POLLRATE,str,sizeof(str));
int rate = atoi(str);
- if (rate == 0)
+ if(rate == 0)
rate = 80;
- DBWriteContactSettingDword(0, proto->ModuleName(), TWITTER_KEY_POLLRATE, rate);
+ DBWriteContactSettingDword(0,proto->ModuleName(),TWITTER_KEY_POLLRATE,rate);
+
+ DBWriteContactSettingByte(0,proto->ModuleName(),TWITTER_KEY_TWEET_TO_MSG,
+ IsDlgButtonChecked(hwndDlg,IDC_TWEET_MSG));
proto->UpdateSettings();
return true;
@@ -304,44 +328,44 @@ namespace popup_options {
static int get_timeout(HWND hwndDlg)
{
- if (IsDlgButtonChecked(hwndDlg, IDC_TIMEOUT_PERMANENT))
+ if(IsDlgButtonChecked(hwndDlg,IDC_TIMEOUT_PERMANENT))
return -1;
- else if (IsDlgButtonChecked(hwndDlg, IDC_TIMEOUT_CUSTOM))
+ else if(IsDlgButtonChecked(hwndDlg,IDC_TIMEOUT_CUSTOM))
{
char str[32];
- GetDlgItemTextA(hwndDlg, IDC_TIMEOUT, str, sizeof(str));
+ GetDlgItemTextA(hwndDlg,IDC_TIMEOUT,str,sizeof(str));
return atoi(str);
}
else // Default checked (probably)
return 0;
}
- static COLORREF get_text_color(HWND hwndDlg, bool for_db)
+ static COLORREF get_text_color(HWND hwndDlg,bool for_db)
{
- if (IsDlgButtonChecked(hwndDlg, IDC_COL_WINDOWS))
+ if(IsDlgButtonChecked(hwndDlg,IDC_COL_WINDOWS))
{
- if (for_db)
+ if(for_db)
return -1;
else
return GetSysColor(COLOR_WINDOWTEXT);
}
- else if (IsDlgButtonChecked(hwndDlg, IDC_COL_CUSTOM))
- return SendDlgItemMessage(hwndDlg, IDC_COLTEXT, CPM_GETCOLOUR, 0, 0);
+ else if(IsDlgButtonChecked(hwndDlg,IDC_COL_CUSTOM))
+ return SendDlgItemMessage(hwndDlg,IDC_COLTEXT,CPM_GETCOLOUR,0,0);
else // Default checked (probably)
return 0;
}
- static COLORREF get_back_color(HWND hwndDlg, bool for_db)
+ static COLORREF get_back_color(HWND hwndDlg,bool for_db)
{
- if (IsDlgButtonChecked(hwndDlg, IDC_COL_WINDOWS))
+ if(IsDlgButtonChecked(hwndDlg,IDC_COL_WINDOWS))
{
- if (for_db)
+ if(for_db)
return -1;
else
return GetSysColor(COLOR_WINDOW);
}
- else if (IsDlgButtonChecked(hwndDlg, IDC_COL_CUSTOM))
- return SendDlgItemMessage(hwndDlg, IDC_COLBACK, CPM_GETCOLOUR, 0, 0);
+ else if(IsDlgButtonChecked(hwndDlg,IDC_COL_CUSTOM))
+ return SendDlgItemMessage(hwndDlg,IDC_COLBACK,CPM_GETCOLOUR,0,0);
else // Default checked (probably)
return 0;
}
@@ -351,17 +375,17 @@ namespace popup_options TCHAR *name;
TCHAR *text;
} const quotes[] = {
- { _T("Dorothy Parker"), _T("If, with the literate, I am\n")
- _T("Impelled to try an epigram, \n")
+ { _T("Dorothy Parker"), _T("If, with the literate, I am\n")
+ _T("Impelled to try an epigram,\n")
_T("I never seek to take the credit;\n")
- _T("We all assume that Oscar said it.") },
- { _T("Steve Ballmer"), _T("I have never, honestly, thrown a chair in my life.") },
- { _T("James Joyce"), _T("I think I would know Nora's fart anywhere. I think ")
- _T("I could pick hers out in a roomful of farting women.") },
- { _T("Brooke Shields"), _T("Smoking kills. If you're killed, you've lost a very ")
- _T("important part of your life.") },
- { _T("Yogi Berra"), _T("Always go to other peoples' funerals, otherwise ")
- _T("they won't go to yours.") },
+ _T("We all assume that Oscar said it.") },
+ { _T("Steve Ballmer"), _T("I have never, honestly, thrown a chair in my life.") },
+ { _T("James Joyce"), _T("I think I would know Nora's fart anywhere. I think ")
+ _T("I could pick hers out in a roomful of farting women.") },
+ { _T("Brooke Shields"), _T("Smoking kills. If you're killed, you've lost a very ")
+ _T("important part of your life.") },
+ { _T("Yogi Berra"), _T("Always go to other peoples' funerals, otherwise ")
+ _T("they won't go to yours.") },
};
static void preview(HWND hwndDlg)
@@ -370,43 +394,43 @@ namespace popup_options // Pick a random contact
HANDLE hContact = 0;
- int n_contacts = CallService(MS_DB_CONTACT_GETCOUNT, 0, 0);
+ int n_contacts = CallService(MS_DB_CONTACT_GETCOUNT,0,0);
- if (n_contacts != 0)
+ if(n_contacts != 0)
{
int contact = rand() % n_contacts;
- hContact = (HANDLE)CallService(MS_DB_CONTACT_FINDFIRST, 0, 0);
+ hContact = (HANDLE)CallService(MS_DB_CONTACT_FINDFIRST,0,0);
for(int i=0; i<contact; i++)
- hContact = (HANDLE)CallService(MS_DB_CONTACT_FINDNEXT, (WPARAM)hContact, 0);
+ hContact = (HANDLE)CallService(MS_DB_CONTACT_FINDNEXT,(WPARAM)hContact,0);
}
// Pick a random quote
int q = rand() % SIZEOF(quotes);
- _tcsncpy(popup.lptzContactName, quotes[q].name, MAX_CONTACTNAME);
- _tcsncpy(popup.lptzText, quotes[q].text, MAX_SECONDLINE);
+ _tcsncpy(popup.lptzContactName,quotes[q].name,MAX_CONTACTNAME);
+ _tcsncpy(popup.lptzText, quotes[q].text,MAX_SECONDLINE);
popup.lchContact = hContact;
popup.iSeconds = get_timeout(hwndDlg);
- popup.colorText = get_text_color(hwndDlg, false);
- popup.colorBack = get_back_color(hwndDlg, false);
+ popup.colorText = get_text_color(hwndDlg,false);
+ popup.colorBack = get_back_color(hwndDlg,false);
- CallService(MS_POPUP_ADDPOPUPT, reinterpret_cast<WPARAM>(&popup), 0);
+ CallService(MS_POPUP_ADDPOPUPT,reinterpret_cast<WPARAM>(&popup),0);
}
}
-void CheckAndUpdateDlgButton(HWND hWnd, int button, BOOL check)
+void CheckAndUpdateDlgButton(HWND hWnd,int button,BOOL check)
{
- CheckDlgButton(hWnd, button, check);
- SendMessage(hWnd, WM_COMMAND, MAKELONG(button, BN_CLICKED),
- (LPARAM)GetDlgItem(hWnd, button));
+ CheckDlgButton(hWnd,button,check);
+ SendMessage(hWnd,WM_COMMAND,MAKELONG(button,BN_CLICKED),
+ (LPARAM)GetDlgItem(hWnd,button));
}
-INT_PTR CALLBACK popup_options_proc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam)
+INT_PTR CALLBACK popup_options_proc(HWND hwndDlg,UINT msg,WPARAM wParam,LPARAM lParam)
{
using namespace popup_options;
TwitterProto *proto;
- int text_color, back_color, timeout;
+ int text_color,back_color,timeout;
switch(msg)
{
@@ -415,48 +439,48 @@ INT_PTR CALLBACK popup_options_proc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARA proto = reinterpret_cast<TwitterProto*>(lParam);
- CheckAndUpdateDlgButton(hwndDlg, IDC_SHOWPOPUPS,
- db_byte_get(0, proto->ModuleName(), TWITTER_KEY_POPUP_SHOW, 0));
- CheckDlgButton(hwndDlg, IDC_NOSIGNONPOPUPS,
- !db_byte_get(0, proto->ModuleName(), TWITTER_KEY_POPUP_SIGNON, 0));
+ CheckAndUpdateDlgButton(hwndDlg,IDC_SHOWPOPUPS,
+ db_byte_get(0,proto->ModuleName(),TWITTER_KEY_POPUP_SHOW,0) );
+ CheckDlgButton(hwndDlg,IDC_NOSIGNONPOPUPS,
+ !db_byte_get(0,proto->ModuleName(),TWITTER_KEY_POPUP_SIGNON,0) );
// ***** Get color information
- back_color = db_dword_get(0, proto->ModuleName(), TWITTER_KEY_POPUP_COLBACK, 0);
- text_color = db_dword_get(0, proto->ModuleName(), TWITTER_KEY_POPUP_COLTEXT, 0);
+ back_color = db_dword_get(0,proto->ModuleName(),TWITTER_KEY_POPUP_COLBACK,0);
+ text_color = db_dword_get(0,proto->ModuleName(),TWITTER_KEY_POPUP_COLTEXT,0);
- SendDlgItemMessage(hwndDlg, IDC_COLBACK, CPM_SETCOLOUR, 0, RGB(255, 255, 255));
- SendDlgItemMessage(hwndDlg, IDC_COLTEXT, CPM_SETCOLOUR, 0, RGB( 0, 0, 0));
+ SendDlgItemMessage(hwndDlg,IDC_COLBACK,CPM_SETCOLOUR,0,RGB(255,255,255));
+ SendDlgItemMessage(hwndDlg,IDC_COLTEXT,CPM_SETCOLOUR,0,RGB( 0, 0, 0));
- if (back_color == -1 && text_color == -1) // Windows defaults
- CheckAndUpdateDlgButton(hwndDlg, IDC_COL_WINDOWS, true);
- else if (back_color == 0 && text_color == 0) // Popup defaults
- CheckAndUpdateDlgButton(hwndDlg, IDC_COL_POPUP, true);
+ if(back_color == -1 && text_color == -1) // Windows defaults
+ CheckAndUpdateDlgButton(hwndDlg,IDC_COL_WINDOWS,true);
+ else if(back_color == 0 && text_color == 0) // Popup defaults
+ CheckAndUpdateDlgButton(hwndDlg,IDC_COL_POPUP,true);
else // Custom colors
{
- CheckAndUpdateDlgButton(hwndDlg, IDC_COL_CUSTOM, true);
- SendDlgItemMessage(hwndDlg, IDC_COLBACK, CPM_SETCOLOUR, 0, back_color);
- SendDlgItemMessage(hwndDlg, IDC_COLTEXT, CPM_SETCOLOUR, 0, text_color);
+ CheckAndUpdateDlgButton(hwndDlg,IDC_COL_CUSTOM,true);
+ SendDlgItemMessage(hwndDlg,IDC_COLBACK,CPM_SETCOLOUR,0,back_color);
+ SendDlgItemMessage(hwndDlg,IDC_COLTEXT,CPM_SETCOLOUR,0,text_color);
}
// ***** Get timeout information
- timeout = db_dword_get(0, proto->ModuleName(), TWITTER_KEY_POPUP_TIMEOUT, 0);
- SetDlgItemTextA(hwndDlg, IDC_TIMEOUT, "5");
+ timeout = db_dword_get(0,proto->ModuleName(),TWITTER_KEY_POPUP_TIMEOUT,0);
+ SetDlgItemTextA(hwndDlg,IDC_TIMEOUT,"5");
- if (timeout == 0)
- CheckAndUpdateDlgButton(hwndDlg, IDC_TIMEOUT_DEFAULT, true);
- else if (timeout < 0)
- CheckAndUpdateDlgButton(hwndDlg, IDC_TIMEOUT_PERMANENT, true);
+ if(timeout == 0)
+ CheckAndUpdateDlgButton(hwndDlg,IDC_TIMEOUT_DEFAULT,true);
+ else if(timeout < 0)
+ CheckAndUpdateDlgButton(hwndDlg,IDC_TIMEOUT_PERMANENT,true);
else
{
char str[32];
- _snprintf(str, sizeof(str), "%d", timeout);
- SetDlgItemTextA(hwndDlg, IDC_TIMEOUT, str);
- CheckAndUpdateDlgButton(hwndDlg, IDC_TIMEOUT_CUSTOM, true);
+ _snprintf(str,sizeof(str),"%d",timeout);
+ SetDlgItemTextA(hwndDlg,IDC_TIMEOUT,str);
+ CheckAndUpdateDlgButton(hwndDlg,IDC_TIMEOUT_CUSTOM,true);
}
- SendDlgItemMessage(hwndDlg, IDC_TIMEOUT_SPIN, UDM_SETRANGE32, 1, INT_MAX);
- SetWindowLong(hwndDlg, GWL_USERDATA, lParam);
+ SendDlgItemMessage(hwndDlg,IDC_TIMEOUT_SPIN,UDM_SETRANGE32,1,INT_MAX);
+ SetWindowLong(hwndDlg,GWL_USERDATA,lParam);
return true;
case WM_COMMAND:
@@ -466,28 +490,28 @@ INT_PTR CALLBACK popup_options_proc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARA switch(LOWORD(wParam))
{
case IDC_SHOWPOPUPS:
- EnableWindow(GetDlgItem(hwndDlg, IDC_NOSIGNONPOPUPS),
- IsDlgButtonChecked(hwndDlg, IDC_SHOWPOPUPS));
+ EnableWindow(GetDlgItem(hwndDlg,IDC_NOSIGNONPOPUPS),
+ IsDlgButtonChecked(hwndDlg,IDC_SHOWPOPUPS) );
break;
case IDC_COL_CUSTOM:
- EnableWindow(GetDlgItem(hwndDlg, IDC_COLBACK), true);
- EnableWindow(GetDlgItem(hwndDlg, IDC_COLTEXT), true);
+ EnableWindow(GetDlgItem(hwndDlg,IDC_COLBACK),true);
+ EnableWindow(GetDlgItem(hwndDlg,IDC_COLTEXT),true);
break;
case IDC_COL_WINDOWS:
case IDC_COL_POPUP:
- EnableWindow(GetDlgItem(hwndDlg, IDC_COLBACK), false);
- EnableWindow(GetDlgItem(hwndDlg, IDC_COLTEXT), false);
+ EnableWindow(GetDlgItem(hwndDlg,IDC_COLBACK),false);
+ EnableWindow(GetDlgItem(hwndDlg,IDC_COLTEXT),false);
break;
case IDC_TIMEOUT_CUSTOM:
- EnableWindow(GetDlgItem(hwndDlg, IDC_TIMEOUT), true);
- EnableWindow(GetDlgItem(hwndDlg, IDC_TIMEOUT_SPIN), true);
+ EnableWindow(GetDlgItem(hwndDlg,IDC_TIMEOUT),true);
+ EnableWindow(GetDlgItem(hwndDlg,IDC_TIMEOUT_SPIN),true);
break;
case IDC_TIMEOUT_DEFAULT:
case IDC_TIMEOUT_PERMANENT:
- EnableWindow(GetDlgItem(hwndDlg, IDC_TIMEOUT), false);
- EnableWindow(GetDlgItem(hwndDlg, IDC_TIMEOUT_SPIN), false);
+ EnableWindow(GetDlgItem(hwndDlg,IDC_TIMEOUT),false);
+ EnableWindow(GetDlgItem(hwndDlg,IDC_TIMEOUT_SPIN),false);
break;
case IDC_PREVIEW:
@@ -496,28 +520,28 @@ INT_PTR CALLBACK popup_options_proc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARA }
case EN_CHANGE:
- if (GetWindowLong(hwndDlg, GWL_USERDATA)) // Window is done initializing
- SendMessage(GetParent(hwndDlg), PSM_CHANGED, 0, 0);
+ if(GetWindowLong(hwndDlg,GWL_USERDATA)) // Window is done initializing
+ SendMessage(GetParent(hwndDlg),PSM_CHANGED,0,0);
}
break;
case WM_NOTIFY:
- if (reinterpret_cast<NMHDR*>(lParam)->code == PSN_APPLY)
+ if(reinterpret_cast<NMHDR*>(lParam)->code == PSN_APPLY)
{
- proto = reinterpret_cast<TwitterProto*>(GetWindowLong(hwndDlg, GWL_USERDATA));
+ proto = reinterpret_cast<TwitterProto*>(GetWindowLong(hwndDlg,GWL_USERDATA));
- DBWriteContactSettingByte(0, proto->ModuleName(), TWITTER_KEY_POPUP_SHOW,
- IsDlgButtonChecked(hwndDlg, IDC_SHOWPOPUPS));
- DBWriteContactSettingByte(0, proto->ModuleName(), TWITTER_KEY_POPUP_SIGNON,
- !IsDlgButtonChecked(hwndDlg, IDC_NOSIGNONPOPUPS));
+ DBWriteContactSettingByte(0,proto->ModuleName(),TWITTER_KEY_POPUP_SHOW,
+ IsDlgButtonChecked(hwndDlg,IDC_SHOWPOPUPS));
+ DBWriteContactSettingByte(0,proto->ModuleName(),TWITTER_KEY_POPUP_SIGNON,
+ !IsDlgButtonChecked(hwndDlg,IDC_NOSIGNONPOPUPS));
// ***** Write color settings
- DBWriteContactSettingDword(0, proto->ModuleName(), TWITTER_KEY_POPUP_COLBACK,
- get_back_color(hwndDlg, true));
- DBWriteContactSettingDword(0, proto->ModuleName(), TWITTER_KEY_POPUP_COLTEXT,
- get_text_color(hwndDlg, true));
+ DBWriteContactSettingDword(0,proto->ModuleName(),TWITTER_KEY_POPUP_COLBACK,
+ get_back_color(hwndDlg,true));
+ DBWriteContactSettingDword(0,proto->ModuleName(),TWITTER_KEY_POPUP_COLTEXT,
+ get_text_color(hwndDlg,true));
// ***** Write timeout setting
- DBWriteContactSettingDword(0, proto->ModuleName(), TWITTER_KEY_POPUP_TIMEOUT,
+ DBWriteContactSettingDword(0,proto->ModuleName(),TWITTER_KEY_POPUP_TIMEOUT,
get_timeout(hwndDlg));
return true;
@@ -527,3 +551,39 @@ INT_PTR CALLBACK popup_options_proc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARA return false;
}
+
+
+INT_PTR CALLBACK pin_proc(HWND hwndDlg,UINT msg,WPARAM wParam,LPARAM lParam)
+{
+ TwitterProto *proto;
+
+ switch(msg)
+ {
+ case WM_INITDIALOG:
+ TranslateDialogDefault(hwndDlg);
+
+ SetWindowLong(hwndDlg,GWL_USERDATA,lParam);
+
+ return true;
+ case WM_COMMAND:
+ if(LOWORD(wParam) == IDOK)
+ {
+ proto = reinterpret_cast<TwitterProto*>(GetWindowLong(hwndDlg,GWL_USERDATA));
+ char str[128];
+
+ GetDlgItemTextA(hwndDlg,IDC_PIN,str,sizeof(str));
+
+ DBWriteContactSettingString(0,proto->ModuleName(),TWITTER_KEY_OAUTH_PIN,str);
+ EndDialog(hwndDlg, wParam);
+ return true;
+ }
+ else if(LOWORD(wParam) == IDCANCEL)
+ {
+ EndDialog(hwndDlg, wParam);
+ return true;
+ }
+ break;
+ }
+
+ return false;
+}
diff --git a/protocols/Twitter/ui.h b/protocols/Twitter/ui.h index f036f8d55d..f5520bba40 100644 --- a/protocols/Twitter/ui.h +++ b/protocols/Twitter/ui.h @@ -21,5 +21,6 @@ along with this program. If not, see <http://www.gnu.org/licenses/>. INT_PTR CALLBACK first_run_dialog(HWND hwndDlg,UINT msg,WPARAM wParam,LPARAM lParam);
INT_PTR CALLBACK tweet_proc(HWND hwndDlg,UINT msg,WPARAM wParam,LPARAM lParam);
+INT_PTR CALLBACK pin_proc(HWND hwndDlg,UINT msg,WPARAM wParam,LPARAM lParam);
INT_PTR CALLBACK options_proc(HWND hwndDlg,UINT msg,WPARAM wParam,LPARAM lParam);
INT_PTR CALLBACK popup_options_proc(HWND hwndDlg,UINT msg,WPARAM wParam,LPARAM lParam);
\ No newline at end of file diff --git a/protocols/Twitter/utility.cpp b/protocols/Twitter/utility.cpp index c54aa10061..0c9377d7c4 100644 --- a/protocols/Twitter/utility.cpp +++ b/protocols/Twitter/utility.cpp @@ -15,8 +15,8 @@ You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
-#include "common.h"
#include "utility.h"
+//#include "tc2.h"
#include <io.h>
@@ -34,75 +34,173 @@ std::string b64encode(const std::string &s) return ret;
}
-http::response mir_twitter::slurp(const std::string &url, http::method meth, const std::string &post_data)
+http::response mir_twitter::slurp(const std::string &url,http::method meth,
+ OAuthParameters postParams)
{
NETLIBHTTPREQUEST req = {sizeof(req)};
NETLIBHTTPREQUEST *resp;
req.requestType = (meth == http::get) ? REQUEST_GET:REQUEST_POST;
- req.szUrl = ( char* )url.c_str();
+ req.szUrl = const_cast<char*>(url.c_str());
+
+ //std::wstring url_WSTR(url.length(),L' ');
+ //std::copy(url.begin(), url.end(), url_WSTR.begin());
+ std::wstring url_WSTR = UTF8ToWide(url);
+ std::string pdata_STR;
+ std::wstring pdata_WSTR;
+
+ std::wstring auth;
+ if (meth == http::get) {
+ if (url_WSTR.size()>0) { WLOG("**SLURP::GET - we have a URL: %s", url_WSTR); }
+ if (consumerKey_.size()>0) { LOG("**SLURP::GET - we have a consumerKey"); }
+ if (consumerSecret_.size()>0) { LOG("**SLURP::GET - we have a consumerSecret"); }
+ if (oauthAccessToken_.size()>0) { LOG("**SLURP::GET - we have a oauthAccessToken"); }
+ if (oauthAccessTokenSecret_.size()>0) { LOG("**SLURP::GET - we have a oauthAccessTokenSecret"); }
+ if (pin_.size()>0) { LOG("**SLURP::GET - we have a pin"); }
+ //WLOG("consumerSEcret is %s", consumerSecret_);
+ //WLOG("oauthAccessTok is %s", oauthAccessToken_);
+ //WLOG("oautAccessTokSEc is %s", oauthAccessTokenSecret_);
+ //WLOG("pin is %s", pin_);
+
+ auth = OAuthWebRequestSubmit(url_WSTR, L"GET", NULL, consumerKey_, consumerSecret_,
+ oauthAccessToken_, oauthAccessTokenSecret_, pin_);
+ }
+ else if (meth == http::post) {
+
+ //OAuthParameters postParams;
+ if (url_WSTR.size()>0) { WLOG("**SLURP::POST - we have a URL: %s", url_WSTR); }
+ if (consumerKey_.size()>0) { LOG("**SLURP::POST - we have a consumerKey"); }
+ if (consumerSecret_.size()>0) { LOG("**SLURP::POST - we have a consumerSecret"); }
+ if (oauthAccessToken_.size()>0) { LOG("**SLURP::POST - we have a oauthAccessToken"); }
+ if (oauthAccessTokenSecret_.size()>0) { LOG("**SLURP::POST - we have a oauthAccessTokenSecret"); }
+ if (pin_.size()>0) { LOG("**SLURP::POST - we have a pin"); }
+
+ //WLOG("consumerKey is %s", consumerKey_);
+ //WLOG("consumerSEcret is %s", consumerSecret_);
+ //WLOG("oauthAccessTok is %s", oauthAccessToken_);
+ //WLOG("oautAccessTokSEc is %s", oauthAccessTokenSecret_);
+
+ //std::wstring pdata_WSTR(post_data.length(),L' ');
+ //std::copy(post_data.begin(), post_data.end(), pdata_WSTR.begin());
+
+ //postParams[L"status"] = UrlEncode(pdata_WSTR);
+ //postParams[L"source"] = L"mirandaim";
- // probably not super-efficient to do this every time, but I don't really care
- std::string auth = "Basic " + b64encode(username_ + ":" + password_);
+ pdata_WSTR = BuildQueryString(postParams);
- NETLIBHTTPHEADER hdr[2];
+ WLOG("**SLURP::POST - post data is: %s", pdata_WSTR);
+
+ auth = OAuthWebRequestSubmit(url_WSTR, L"POST", &postParams, consumerKey_, consumerSecret_,
+ oauthAccessToken_, oauthAccessTokenSecret_);
+ //WLOG("**SLURP::POST auth is %s", auth);
+ }
+ else {
+ LOG("**SLURP - There is something really wrong.. the http method was neither get or post.. WHY??");
+ }
+
+ //std::string auth_STR(auth.length(), ' ');
+ //std::copy(auth.begin(), auth.end(), auth_STR.begin());
+
+ std::string auth_STR = WideToUTF8(auth);
+
+ NETLIBHTTPHEADER hdr[3];
hdr[0].szName = "Authorization";
- hdr[0].szValue = (char*)( auth.c_str());
+ hdr[0].szValue = const_cast<char*>(auth_STR.c_str());
req.headers = hdr;
req.headersCount = 1;
- if (meth == http::post)
+ if(meth == http::post)
{
hdr[1].szName = "Content-Type";
hdr[1].szValue = "application/x-www-form-urlencoded";
+ hdr[2].szName = "Cache-Control";
+ hdr[2].szValue = "no-cache";
+
+ //char *pdata_STR = new char[pdata_WSTR.length() + 1];
+ //sprintf(pdata_STR,"%ls",pdata_WSTR.c_str());
- req.headersCount = 2;
- req.dataLength = post_data.size();
- req.pData = ( char* )post_data.c_str();
+ pdata_STR = WideToUTF8(pdata_WSTR);
+
+ req.headersCount = 3;
+ req.dataLength = pdata_STR.size();
+ req.pData = const_cast<char*>(pdata_STR.c_str());
+ LOG("**SLURP::POST - req.pdata is %s", req.pData);
}
+ req.flags = NLHRF_HTTP11 | NLHRF_PERSISTENT | NLHRF_REDIRECT;
+ req.nlc = httpPOST_;
http::response resp_data;
-
+ LOG("**SLURP - just before calling HTTPTRANSACTION");
resp = reinterpret_cast<NETLIBHTTPREQUEST*>(CallService( MS_NETLIB_HTTPTRANSACTION,
- reinterpret_cast<WPARAM>(handle_), reinterpret_cast<LPARAM>(&req)));
-
- if (resp)
+ reinterpret_cast<WPARAM>(handle_), reinterpret_cast<LPARAM>(&req) ));
+ LOG("**SLURP - HTTPTRANSACTION complete.");
+ if(resp)
{
+ LOG("**SLURP - the server has responded!");
+ httpPOST_ = resp->nlc;
resp_data.code = resp->resultCode;
resp_data.data = resp->pData ? resp->pData:"";
CallService(MS_NETLIB_FREEHTTPREQUESTSTRUCT,0,(LPARAM)resp);
}
+ else {
+ httpPOST_ = NULL;
+ LOG("SLURP - there was no response!");
+ }
return resp_data;
}
+int mir_twitter::LOG(const char *fmt,...)
+{
+ va_list va;
+ char text[1024];
+ if (!handle_)
+ return 0;
+
+ va_start(va,fmt);
+ mir_vsnprintf(text,sizeof(text),fmt,va);
+ va_end(va);
+
+ return CallService(MS_NETLIB_LOG,(WPARAM)handle_,(LPARAM)text);
+}
+
+int mir_twitter::WLOG(const char* first, const std::wstring last)
+{
+ char *str1 = new char[1024*96];
+ sprintf(str1,"%ls", last.c_str());
+ return LOG(first, str1);
+}
bool save_url(HANDLE hNetlib,const std::string &url,const std::string &filename)
{
NETLIBHTTPREQUEST req = {sizeof(req)};
NETLIBHTTPREQUEST *resp;
req.requestType = REQUEST_GET;
+ req.flags = NLHRF_HTTP11 | NLHRF_REDIRECT;
req.szUrl = const_cast<char*>(url.c_str());
resp = reinterpret_cast<NETLIBHTTPREQUEST*>(CallService( MS_NETLIB_HTTPTRANSACTION,
- reinterpret_cast<WPARAM>(hNetlib), reinterpret_cast<LPARAM>(&req)));
+ reinterpret_cast<WPARAM>(hNetlib), reinterpret_cast<LPARAM>(&req) ));
if (resp)
{
- // Create folder if necessary
- std::string dir = filename.substr(0,filename.rfind('\\'));
- if (_access(dir.c_str(),0))
- CallService(MS_UTILS_CREATEDIRTREE, 0, (LPARAM)dir.c_str());
-
- // Write to file
- FILE *f = fopen(filename.c_str(),"wb");
- fwrite(resp->pData,1,resp->dataLength,f);
- fclose(f);
+ if (resp->resultCode == 200)
+ {
+ // Create folder if necessary
+ std::string dir = filename.substr(0,filename.rfind('\\'));
+ if(_access(dir.c_str(),0))
+ CallService(MS_UTILS_CREATEDIRTREE, 0, (LPARAM)dir.c_str());
+
+ // Write to file
+ FILE *f = fopen(filename.c_str(),"wb");
+ fwrite(resp->pData,1,resp->dataLength,f);
+ fclose(f);
+ }
CallService(MS_NETLIB_FREEHTTPREQUESTSTRUCT,0,(LPARAM)resp);
- return true;
+ return resp->resultCode == 200;
}
else
return false;
@@ -125,9 +223,9 @@ int ext_to_format(const std::string &ext) {
for(size_t i=0; i<SIZEOF(formats); i++)
{
- if (ext == formats[i].ext)
+ if(ext == formats[i].ext)
return formats[i].fmt;
}
-
+
return PA_FORMAT_UNKNOWN;
}
\ No newline at end of file diff --git a/protocols/Twitter/utility.h b/protocols/Twitter/utility.h index b68a4fcb9d..c827a6d1ec 100644 --- a/protocols/Twitter/utility.h +++ b/protocols/Twitter/utility.h @@ -17,6 +17,7 @@ along with this program. If not, see <http://www.gnu.org/licenses/>. #pragma once
+#include "common.h"
#include "http.h"
#include "twitter.h"
@@ -54,12 +55,66 @@ std::string b64encode(const std::string &s); class mir_twitter : public twitter
{
public:
+ mir_twitter() : twitter(), handle_(NULL), httpPOST_(NULL) {}
void set_handle(HANDLE h)
{
handle_ = h;
}
+
+ // OAuthWebRequest used for all OAuth related queries
+ //
+ // consumerKey and consumerSecret - must be provided for every call, they identify the application
+ // oauthToken and oauthTokenSecret - need to be provided for every call, except for the first token request before authorizing
+ // pin - only used during authorization, when the user enters the PIN they received from the twitter website
+ std::wstring OAuthWebRequestSubmit(
+ const std::wstring& url,
+ const std::wstring& httpMethod,
+ const OAuthParameters *postData,
+ const std::wstring& consumerKey,
+ const std::wstring& consumerSecret,
+ const std::wstring& oauthToken = L"",
+ const std::wstring& oauthTokenSecret = L"",
+ const std::wstring& pin = L""
+ );
+
+ std::wstring OAuthWebRequestSubmit(
+ const OAuthParameters& parameters,
+ const std::wstring& url
+ );
+
+ std::wstring UrlGetQuery( const std::wstring& url );
+
+ OAuthParameters BuildSignedOAuthParameters( const OAuthParameters& requestParameters,
+ const std::wstring& url,
+ const std::wstring& httpMethod,
+ const OAuthParameters *postData,
+ const std::wstring& consumerKey,
+ const std::wstring& consumerSecret,
+ const std::wstring& requestToken,
+ const std::wstring& requestTokenSecret,
+ const std::wstring& pin );
+
+ std::wstring BuildQueryString( const OAuthParameters ¶meters ) ;
+ std::wstring OAuthConcatenateRequestElements( const std::wstring& httpMethod, std::wstring url, const std::wstring& parameters );
+ std::map<std::wstring, std::wstring> CrackURL(std::wstring );
+ std::wstring brook_httpsend(std::wstring, std::wstring, std::wstring, std::wstring);
+ void Disconnect(void) { if (httpPOST_) Netlib_CloseHandle(httpPOST_); httpPOST_ = NULL; }
+ std::wstring OAuthNormalizeUrl( const std::wstring& url );
+ std::wstring OAuthNormalizeRequestParameters( const OAuthParameters& requestParameters );
+ OAuthParameters ParseQueryString( const std::wstring& url );
+
+ std::wstring OAuthCreateNonce();
+ std::wstring OAuthCreateTimestamp();
+ std::string HMACSHA1( const std::string& keyBytes, const std::string& data );
+ std::wstring Base64String( const std::string& hash );
+ std::wstring OAuthCreateSignature( const std::wstring& signatureBase, const std::wstring& consumerSecret, const std::wstring& requestTokenSecret );
+
protected:
- http::response slurp(const std::string &,http::method,const std::string &);
+ http::response slurp(const std::string &,http::method, OAuthParameters );
+ int LOG(const char *fmt,...);
+ int WLOG(const char* first, const std::wstring last);
+
+ HANDLE httpPOST_;
HANDLE handle_;
};
@@ -77,7 +132,7 @@ inline void wcs_to_tcs(UINT code_page,const wchar_t *wstr,TCHAR *tstr,int tlen) #ifdef UNICODE
wcsncpy(tstr,wstr,tlen);
#else
- WideCharToMultiByte(code_page,0,wstr,-1,tstr,tlen,0,0);
+ WideCharToMultiByte(code_page,0,wstr,-1,tstr,tlen,0,0);
#endif
}
@@ -90,7 +145,7 @@ public: }
~ScopedLock()
{
- if (handle_)
+ if(handle_)
ReleaseMutex(handle_);
}
diff --git a/protocols/Twitter/version.h b/protocols/Twitter/version.h index b27c53811e..0196f658bb 100644 --- a/protocols/Twitter/version.h +++ b/protocols/Twitter/version.h @@ -17,4 +17,4 @@ along with this program. If not, see <http://www.gnu.org/licenses/>. #pragma once
-#define __VERSION_DWORD PLUGIN_MAKE_VERSION(0, 0, 8, 4)
\ No newline at end of file +#define __VERSION_DWORD PLUGIN_MAKE_VERSION(1, 0, 0, 0)
\ No newline at end of file diff --git a/protocols/Twitter/version.html b/protocols/Twitter/version.html new file mode 100644 index 0000000000..13f1601e8e --- /dev/null +++ b/protocols/Twitter/version.html @@ -0,0 +1 @@ +Twitter 1.0.0.0
\ No newline at end of file |