http_impl.c 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427
  1. /* --- BEGIN COPYRIGHT BLOCK ---
  2. * This Program is free software; you can redistribute it and/or modify it under
  3. * the terms of the GNU General Public License as published by the Free Software
  4. * Foundation; version 2 of the License.
  5. *
  6. * This Program is distributed in the hope that it will be useful, but WITHOUT
  7. * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
  8. * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  9. *
  10. * You should have received a copy of the GNU General Public License along with
  11. * this Program; if not, write to the Free Software Foundation, Inc., 59 Temple
  12. * Place, Suite 330, Boston, MA 02111-1307 USA.
  13. *
  14. * In addition, as a special exception, Red Hat, Inc. gives You the additional
  15. * right to link the code of this Program with code not covered under the GNU
  16. * General Public License ("Non-GPL Code") and to distribute linked combinations
  17. * including the two, subject to the limitations in this paragraph. Non-GPL Code
  18. * permitted under this exception must only link to the code of this Program
  19. * through those well defined interfaces identified in the file named EXCEPTION
  20. * found in the source code files (the "Approved Interfaces"). The files of
  21. * Non-GPL Code may instantiate templates or use macros or inline functions from
  22. * the Approved Interfaces without causing the resulting work to be covered by
  23. * the GNU General Public License. Only Red Hat, Inc. may make changes or
  24. * additions to the list of Approved Interfaces. You must obey the GNU General
  25. * Public License in all respects for all of the Program code and other code used
  26. * in conjunction with the Program except the Non-GPL Code covered by this
  27. * exception. If you modify this file, you may extend this exception to your
  28. * version of the file, but you are not obligated to do so. If you do not wish to
  29. * provide this exception without modification, you must delete this exception
  30. * statement from your version and license this file solely under the GPL without
  31. * exception.
  32. *
  33. *
  34. * Copyright (C) 2001 Sun Microsystems, Inc. Used by permission.
  35. * Copyright (C) 2005 Red Hat, Inc.
  36. * All rights reserved.
  37. * --- END COPYRIGHT BLOCK --- */
  38. #ifdef HAVE_CONFIG_H
  39. # include <config.h>
  40. #endif
  41. /**
  42. * Implementation of a Simple HTTP Client
  43. */
  44. #include <stdio.h>
  45. #include <string.h>
  46. #include "nspr.h"
  47. #include "nss.h"
  48. #include "pk11func.h"
  49. #include "ssl.h"
  50. #include "prprf.h"
  51. #include "plstr.h"
  52. #include "slapi-plugin.h"
  53. #include "http_client.h"
  54. #include "secerr.h"
  55. #include "sslerr.h"
  56. #include "slap.h"
  57. #include "slapi-private.h"
  58. #include "slapi-plugin-compat4.h"
  59. #include <sys/stat.h>
  60. /*** from proto-slap.h ***/
  61. int slapd_log_error_proc( char *subsystem, char *fmt, ... );
  62. char *config_get_instancedir();
  63. /*** from ldaplog.h ***/
  64. /* edited ldaplog.h for LDAPDebug()*/
  65. #ifndef _LDAPLOG_H
  66. #define _LDAPLOG_H
  67. #ifdef __cplusplus
  68. extern "C" {
  69. #endif
  70. #ifdef BUILD_STANDALONE
  71. #define slapi_log_error(a,b,c,d) printf((c),(d))
  72. #define stricmp strcasecmp
  73. #endif
  74. #define LDAP_DEBUG_TRACE 0x00001 /* 1 */
  75. #define LDAP_DEBUG_ANY 0x04000 /* 16384 */
  76. #define LDAP_DEBUG_PLUGIN 0x10000 /* 65536 */
  77. /* debugging stuff */
  78. # ifdef _WIN32
  79. extern int *module_ldap_debug;
  80. # define LDAPDebug( level, fmt, arg1, arg2, arg3 ) \
  81. { \
  82. if ( *module_ldap_debug & level ) { \
  83. slapd_log_error_proc( NULL, fmt, arg1, arg2, arg3 ); \
  84. } \
  85. }
  86. # else /* _WIN32 */
  87. extern int slapd_ldap_debug;
  88. # define LDAPDebug( level, fmt, arg1, arg2, arg3 ) \
  89. { \
  90. if ( slapd_ldap_debug & level ) { \
  91. slapd_log_error_proc( NULL, fmt, arg1, arg2, arg3 ); \
  92. } \
  93. }
  94. # endif /* Win32 */
  95. #ifdef __cplusplus
  96. }
  97. #endif
  98. #endif /* _LDAP_H */
  99. #define HTTP_PLUGIN_SUBSYSTEM "http-client-plugin" /* used for logging */
  100. #define HTTP_IMPL_SUCCESS 0
  101. #define HTTP_IMPL_FAILURE -1
  102. #define HTTP_REQ_TYPE_GET 1
  103. #define HTTP_REQ_TYPE_REDIRECT 2
  104. #define HTTP_REQ_TYPE_POST 3
  105. #define HTTP_GET "GET"
  106. #define HTTP_POST "POST"
  107. #define HTTP_PROTOCOL "HTTP/1.0"
  108. #define HTTP_CONTENT_LENGTH "Content-length:"
  109. #define HTTP_CONTENT_TYPE_URL_ENCODED "Content-type: application/x-www-form-urlencoded"
  110. #define HTTP_GET_STD_LEN 18
  111. #define HTTP_POST_STD_LEN 85
  112. #define HTTP_DEFAULT_BUFFER_SIZE 4096
  113. #define HTTP_RESPONSE_REDIRECT (retcode == 302 || retcode == 301)
  114. /**
  115. * Error strings used for logging error messages
  116. */
  117. #define HTTP_ERROR_BAD_URL " Badly formatted URL"
  118. #define HTTP_ERROR_NET_ADDR " NetAddr initialization failed"
  119. #define HTTP_ERROR_SOCKET_CREATE " Creation of socket failed"
  120. #define HTTP_ERROR_SSLSOCKET_CREATE " Creation of SSL socket failed"
  121. #define HTTP_ERROR_CONNECT_FAILED " Couldn't connect to remote host"
  122. #define HTTP_ERROR_SEND_REQ " Send request failed"
  123. #define HTTP_ERROR_BAD_RESPONSE " Invalid response from remote host"
  124. #define HTTP_PLUGIN_DN "cn=HTTP Client,cn=plugins,cn=config"
  125. #define CONFIG_DN "cn=config"
  126. #define ATTR_CONNECTION_TIME_OUT "nsHTTPConnectionTimeOut"
  127. #define ATTR_READ_TIME_OUT "nsHTTPReadTimeOut"
  128. #define ATTR_RETRY_COUNT "nsHTTPRetryCount"
  129. #define ATTR_DS_SECURITY "nsslapd-security"
  130. #define ATTR_INSTANCE_PATH "nsslapd-errorlog"
  131. /*static Slapi_ComponentId *plugin_id = NULL;*/
  132. typedef struct {
  133. int retryCount;
  134. int connectionTimeOut;
  135. int readTimeOut;
  136. int nssInitialized;
  137. char *DS_sslOn;
  138. } httpPluginConfig;
  139. httpPluginConfig *httpConfig;
  140. /**
  141. * Public functions
  142. */
  143. int http_impl_init(Slapi_ComponentId *plugin_id);
  144. int http_impl_get_text(char *url, char **data, int *bytesRead);
  145. int http_impl_get_binary(char *url, char **data, int *bytesRead);
  146. int http_impl_get_redirected_uri(char *url, char **data, int *bytesRead);
  147. int http_impl_post(char *url, httpheader **httpheaderArray, char *body, char **data, int *bytesRead);
  148. void http_impl_shutdown();
  149. /**
  150. * Http handling functions
  151. */
  152. static int doRequest(const char *url, httpheader **httpheaderArray, char *body, char **buf, int *bytesRead, int reqType);
  153. static int doRequestRetry(const char *url, httpheader **httpheaderArray, char *body, char **buf, int *bytesRead, int reqType);
  154. static void setTCPNoDelay(PRFileDesc* fd);
  155. static PRStatus sendGetReq(PRFileDesc *fd, const char *path);
  156. static PRStatus sendPostReq(PRFileDesc *fd, const char *path, httpheader **httpheaderArray, char *body);
  157. static PRStatus processResponse(PRFileDesc *fd, char **resBUF, int *bytesRead, int reqType);
  158. static PRStatus getChar(PRFileDesc *fd, char *buf);
  159. static PRInt32 http_read(PRFileDesc *fd, char *buf, int size);
  160. static PRStatus getBody(PRFileDesc *fd, char **buf, int *actualBytesRead);
  161. static PRBool isWhiteSpace(char ch);
  162. static PRStatus sendFullData( PRFileDesc *fd, char *buf, int timeOut);
  163. /**
  164. * Helper functions to parse URL
  165. */
  166. static PRStatus parseURI(const char *url, char **host, PRInt32 *port, char **path, int *sslOn);
  167. static void toLowerCase(char* str);
  168. static PRStatus parseAtPort(const char* url, PRInt32 *port, char **path);
  169. static PRStatus parseAtPath(const char *url, char **path);
  170. static PRInt32 getPort(const char* src);
  171. static PRBool isAsciiSpace(char aChar);
  172. static PRBool isAsciiDigit(char aChar);
  173. static char * isHttpReq(const char *url, int *sslOn);
  174. /*To get config from entry*/
  175. static int readConfigLDAPurl(Slapi_ComponentId *plugin_id, char *plugindn);
  176. static int parseHTTPConfigEntry(Slapi_Entry *e);
  177. static int parseConfigEntry(Slapi_Entry *e);
  178. /*SSL functions */
  179. PRFileDesc* setupSSLSocket(PRFileDesc* fd);
  180. /*SSL callback functions */
  181. SECStatus badCertHandler(void *arg, PRFileDesc *socket);
  182. SECStatus authCertificate(void *arg, PRFileDesc *socket, PRBool checksig, PRBool isServer);
  183. SECStatus getClientAuthData(void *arg, PRFileDesc *socket,struct CERTDistNamesStr *caNames, struct CERTCertificateStr **pRetCert, struct SECKEYPrivateKeyStr **pRetKey);
  184. SECStatus handshakeCallback(PRFileDesc *socket, void *arg);
  185. static int doRequestRetry(const char *url, httpheader **httpheaderArray, char *body, char **buf, int *bytesRead, int reqType)
  186. {
  187. int status = HTTP_IMPL_SUCCESS;
  188. int retrycnt = 0;
  189. int i = 1;
  190. retrycnt = httpConfig->retryCount;
  191. if (retrycnt == 0) {
  192. LDAPDebug( LDAP_DEBUG_PLUGIN, "doRequestRetry: Retry Count cannot be read. Setting to default value of 3 \n", 0,0,0);
  193. retrycnt = 3;
  194. }
  195. status = doRequest(url, httpheaderArray, body, buf, bytesRead, reqType);
  196. if (status != HTTP_IMPL_SUCCESS) {
  197. LDAPDebug( LDAP_DEBUG_PLUGIN, "doRequestRetry: Failed to perform http request \n", 0,0,0);
  198. while (retrycnt > 0) {
  199. LDAPDebug( LDAP_DEBUG_PLUGIN, "doRequestRetry: Retrying http request %d.\n", i,0,0);
  200. status = doRequest(url, httpheaderArray, body, buf, bytesRead, reqType);
  201. if (status == HTTP_IMPL_SUCCESS) {
  202. break;
  203. }
  204. retrycnt--;
  205. i++;
  206. }
  207. if (status != HTTP_IMPL_SUCCESS) {
  208. LDAPDebug( LDAP_DEBUG_ANY, "doRequestRetry: Failed to perform http request after %d attempts.\n", i,0,0);
  209. LDAPDebug( LDAP_DEBUG_ANY, "doRequestRetry: Verify plugin URI configuration and contact Directory Administrator.\n",0,0,0);
  210. }
  211. }
  212. return status;
  213. }
  214. static int doRequest(const char *url, httpheader **httpheaderArray, char *body, char **buf, int *bytesRead, int reqType)
  215. {
  216. PRStatus status = PR_SUCCESS;
  217. char *host = NULL;
  218. char *path = NULL;
  219. PRFileDesc *fd = NULL;
  220. PRNetAddr addr;
  221. PRInt32 port;
  222. PRInt32 errcode = 0;
  223. PRInt32 http_connection_time_out = 0;
  224. PRInt32 sslOn = 0;
  225. LDAPDebug( LDAP_DEBUG_PLUGIN, "--> doRequest -- BEGIN\n",0,0,0);
  226. LDAPDebug( LDAP_DEBUG_PLUGIN, "----------> url=[%s] \n",url,0,0);
  227. /* Parse the URL and initialize the host, port, path */
  228. if (parseURI(url, &host, &port, &path, &sslOn) == PR_FAILURE) {
  229. slapi_log_error( SLAPI_LOG_FATAL, HTTP_PLUGIN_SUBSYSTEM,
  230. "doRequest: %s \n", HTTP_ERROR_BAD_URL);
  231. status = PR_FAILURE;
  232. goto bail;
  233. }
  234. LDAPDebug( LDAP_DEBUG_PLUGIN, "----------> host=[%s] port[%d] path[%s] \n",host,port,path);
  235. /* Initialize the Net Addr */
  236. if (PR_StringToNetAddr(host, &addr) == PR_FAILURE) {
  237. char buf[PR_NETDB_BUF_SIZE];
  238. PRHostEnt ent;
  239. status = PR_GetIPNodeByName(host, PR_AF_INET, PR_AI_DEFAULT, buf, sizeof(buf), &ent);
  240. if (status == PR_SUCCESS) {
  241. PR_EnumerateHostEnt(0, &ent, (PRUint16)port, &addr);
  242. } else {
  243. slapi_log_error( SLAPI_LOG_FATAL, HTTP_PLUGIN_SUBSYSTEM,
  244. "doRequest: %s\n", HTTP_ERROR_NET_ADDR);
  245. status = HTTP_CLIENT_ERROR_NET_ADDR;
  246. goto bail;
  247. }
  248. } else {
  249. addr.inet.port = (PRUint16)port;
  250. }
  251. LDAPDebug( LDAP_DEBUG_PLUGIN, "----------> Successfully created NetAddr \n",0,0,0);
  252. /* open a TCP connection to the server */
  253. fd = PR_NewTCPSocket();
  254. if (!fd) {
  255. slapi_log_error( SLAPI_LOG_FATAL, HTTP_PLUGIN_SUBSYSTEM,
  256. "doRequest: %s\n", HTTP_ERROR_SOCKET_CREATE);
  257. status = HTTP_CLIENT_ERROR_SOCKET_CREATE;
  258. goto bail;
  259. }
  260. LDAPDebug( LDAP_DEBUG_PLUGIN, "----------> Successfully created New TCP Socket \n",0,0,0);
  261. /* immediately send the response */
  262. setTCPNoDelay(fd);
  263. if (sslOn) {
  264. fd = setupSSLSocket(fd);
  265. if (fd == NULL) {
  266. slapi_log_error( SLAPI_LOG_FATAL, HTTP_PLUGIN_SUBSYSTEM,
  267. "doRequest: %s\n", HTTP_ERROR_SSLSOCKET_CREATE);
  268. status = HTTP_CLIENT_ERROR_SSLSOCKET_CREATE;
  269. goto bail;
  270. }
  271. if (SSL_SetURL(fd, host) != 0) {
  272. errcode = PR_GetError();
  273. slapi_log_error( SLAPI_LOG_FATAL, HTTP_PLUGIN_SUBSYSTEM,
  274. "doRequest: SSL_SetURL -> NSPR Error code (%d) \n", errcode);
  275. status = HTTP_CLIENT_ERROR_SSLSOCKET_CREATE;
  276. goto bail;
  277. }
  278. }
  279. http_connection_time_out = httpConfig->connectionTimeOut;
  280. /* connect to the host */
  281. if (PR_Connect(fd, &addr, PR_MillisecondsToInterval(http_connection_time_out)) == PR_FAILURE) {
  282. errcode = PR_GetError();
  283. slapi_log_error( SLAPI_LOG_FATAL, HTTP_PLUGIN_SUBSYSTEM,
  284. "doRequest: %s (%s:%d) -> NSPR Error code (%d)\n",
  285. HTTP_ERROR_CONNECT_FAILED, host, addr.inet.port, errcode);
  286. status = HTTP_CLIENT_ERROR_CONNECT_FAILED;
  287. goto bail;
  288. }
  289. LDAPDebug( LDAP_DEBUG_PLUGIN, "----------> Successfully connected to host [%s] \n",host,0,0);
  290. /* send the request to the server */
  291. if (reqType == HTTP_REQ_TYPE_POST) {
  292. if (sendPostReq(fd, path, httpheaderArray, body) == PR_FAILURE) {
  293. slapi_log_error( SLAPI_LOG_FATAL, HTTP_PLUGIN_SUBSYSTEM,
  294. "doRequest-sendPostReq: %s (%s)\n", HTTP_ERROR_SEND_REQ, path);
  295. status = HTTP_CLIENT_ERROR_SEND_REQ;
  296. goto bail;
  297. }
  298. }
  299. else {
  300. if (sendGetReq(fd, path) == PR_FAILURE) {
  301. slapi_log_error( SLAPI_LOG_FATAL, HTTP_PLUGIN_SUBSYSTEM,
  302. "doRequest-sendGetReq: %s (%s)\n", HTTP_ERROR_SEND_REQ, path);
  303. status = HTTP_CLIENT_ERROR_SEND_REQ;
  304. goto bail;
  305. }
  306. }
  307. LDAPDebug( LDAP_DEBUG_PLUGIN, "----------> Successfully sent the request [%s] \n",path,0,0);
  308. /* read the response */
  309. if (processResponse(fd, buf, bytesRead, reqType) == PR_FAILURE) {
  310. slapi_log_error( SLAPI_LOG_FATAL, HTTP_PLUGIN_SUBSYSTEM,
  311. "doRequest: %s (%s)\n", HTTP_ERROR_BAD_RESPONSE, url);
  312. status = HTTP_CLIENT_ERROR_BAD_RESPONSE;
  313. goto bail;
  314. }
  315. LDAPDebug( LDAP_DEBUG_PLUGIN, "----------> Successfully read the response\n",0,0,0);
  316. bail:
  317. if (host) {
  318. PR_Free(host);
  319. }
  320. if (path) {
  321. PR_Free(path);
  322. }
  323. if (fd) {
  324. PR_Close(fd);
  325. fd = NULL;
  326. }
  327. LDAPDebug( LDAP_DEBUG_PLUGIN, "<-- doRequest -- END\n",0,0,0);
  328. return status;
  329. }
  330. static PRStatus processResponse(PRFileDesc *fd, char **resBUF, int *bytesRead, int reqType)
  331. {
  332. PRStatus status = PR_SUCCESS;
  333. char *location = NULL;
  334. char *protocol = NULL;
  335. char *statusNum = NULL;
  336. char *statusString = NULL;
  337. char *headers = NULL;
  338. char tmp[HTTP_DEFAULT_BUFFER_SIZE];
  339. int pos=0;
  340. char ch;
  341. int index;
  342. int retcode;
  343. PRBool doneParsing = PR_FALSE;
  344. PRBool isRedirect = PR_FALSE;
  345. char name[HTTP_DEFAULT_BUFFER_SIZE];
  346. char value[HTTP_DEFAULT_BUFFER_SIZE];
  347. PRBool atEOL = PR_FALSE;
  348. PRBool inName = PR_TRUE;
  349. /* PKBxxx: If we are getting a redirect and the response is more the
  350. * the HTTP_DEFAULT_BUFFER_SIZE, it will cause the server to crash. A 4k
  351. * buffer should be good enough.
  352. */
  353. LDAPDebug( LDAP_DEBUG_PLUGIN, "--> processResponse -- BEGIN\n",0,0,0);
  354. headers = (char *)PR_Calloc(1, 4 * HTTP_DEFAULT_BUFFER_SIZE);
  355. /* Get protocol string */
  356. index = 0;
  357. while (1) {
  358. status = getChar(fd, headers+pos);
  359. if (status == PR_FAILURE) {
  360. /* Error : */
  361. goto bail;
  362. }
  363. ch = (char)headers[pos];
  364. pos++;
  365. if (!isWhiteSpace(ch)) {
  366. tmp[index++] = ch;
  367. } else {
  368. break;
  369. }
  370. }
  371. tmp[index] = '\0';
  372. protocol = PL_strdup(tmp);
  373. LDAPDebug( LDAP_DEBUG_PLUGIN, "----------> protocol=[%s] \n",protocol,0,0);
  374. /* Get status num */
  375. index = 0;
  376. while (1) {
  377. status = getChar(fd, headers+pos);
  378. if (status == PR_FAILURE) {
  379. /* Error : */
  380. goto bail;
  381. }
  382. ch = (char)headers[pos];
  383. pos++;
  384. if (!isWhiteSpace(ch)) {
  385. tmp[index++] = ch;
  386. } else {
  387. break;
  388. }
  389. }
  390. tmp[index] = '\0';
  391. statusNum = PL_strdup(tmp);
  392. retcode=atoi(tmp);
  393. LDAPDebug( LDAP_DEBUG_PLUGIN, "----------> statusNum=[%s] \n",statusNum,0,0);
  394. if (HTTP_RESPONSE_REDIRECT && (reqType == HTTP_REQ_TYPE_REDIRECT)) {
  395. isRedirect = PR_TRUE;
  396. }
  397. /* Get status string */
  398. if (ch != '\r')
  399. {
  400. index = 0;
  401. while (ch != '\r') {
  402. status = getChar(fd, headers+pos);
  403. if (status == PR_FAILURE) {
  404. /* Error : */
  405. goto bail;
  406. }
  407. ch = (char)headers[pos];
  408. pos++;
  409. tmp[index++] = ch;
  410. }
  411. tmp[index] = '\0';
  412. statusString = PL_strdup(tmp);
  413. LDAPDebug( LDAP_DEBUG_PLUGIN, "----------> statusString [%s] \n",statusString,0,0);
  414. }
  415. /**
  416. * Skip CRLF
  417. */
  418. status = getChar(fd, headers+pos);
  419. if (status == PR_FAILURE) {
  420. /* Error : */
  421. goto bail;
  422. }
  423. ch = (char)headers[pos];
  424. pos++;
  425. /**
  426. * loop over response headers
  427. */
  428. index = 0;
  429. while (!doneParsing) {
  430. status = getChar(fd, headers+pos);
  431. if (status == PR_FAILURE) {
  432. /* Error : */
  433. goto bail;
  434. }
  435. ch = (char)headers[pos];
  436. pos++;
  437. switch(ch)
  438. {
  439. case ':':
  440. if (inName) {
  441. name[index] = '\0';
  442. index = 0;
  443. inName = PR_FALSE;
  444. /* skip whitespace */
  445. ch = ' ';
  446. /* status = getChar(fd, headers+pos);
  447. if (status == PR_FAILURE) {
  448. goto bail;
  449. }
  450. ch = (char)headers[pos];
  451. pos++; */
  452. while(isWhiteSpace(ch)) {
  453. status = getChar(fd, headers+pos);
  454. if (status == PR_FAILURE) {
  455. /* Error : */
  456. goto bail;
  457. }
  458. ch = (char)headers[pos];
  459. pos++;
  460. }
  461. value[index++] = ch;
  462. } else {
  463. value[index++] = ch;
  464. }
  465. break;
  466. case '\r':
  467. if (inName && !atEOL) {
  468. return PR_FALSE;
  469. }
  470. break;
  471. case '\n':
  472. if (atEOL) {
  473. doneParsing = PR_TRUE;
  474. break;
  475. }
  476. if (inName) {
  477. return PR_FALSE;
  478. }
  479. value[index] = '\0';
  480. index = 0;
  481. inName = PR_TRUE;
  482. LDAPDebug( LDAP_DEBUG_PLUGIN, "----------> name=[%s] value=[%s]\n",name,value,0);
  483. if (isRedirect && !PL_strcasecmp(name,"location")) {
  484. location = PL_strdup(value);
  485. }
  486. atEOL = PR_TRUE;
  487. break;
  488. default:
  489. atEOL = PR_FALSE;
  490. if (inName) {
  491. name[index++] = ch;
  492. } else {
  493. value[index++] = ch;
  494. }
  495. break;
  496. }
  497. }
  498. if (!isRedirect) {
  499. getBody(fd, resBUF, bytesRead);
  500. } else {
  501. *resBUF = PL_strdup(location);
  502. *bytesRead = strlen(location);
  503. }
  504. LDAPDebug( LDAP_DEBUG_PLUGIN, "----------> Response Buffer=[%s] bytesRead=[%d] \n",*resBUF,*bytesRead,0);
  505. bail:
  506. if (headers) {
  507. PR_Free(headers);
  508. }
  509. if (protocol) {
  510. PL_strfree(protocol);
  511. }
  512. if (statusNum) {
  513. PL_strfree(statusNum);
  514. }
  515. if (statusString) {
  516. PL_strfree(statusString);
  517. }
  518. if (location) {
  519. PL_strfree(location);
  520. }
  521. LDAPDebug( LDAP_DEBUG_PLUGIN, "<-- processResponse -- END\n",0,0,0);
  522. return status;
  523. }
  524. static PRStatus sendGetReq(PRFileDesc *fd, const char *path)
  525. {
  526. PRStatus status = PR_SUCCESS;
  527. char *reqBUF = NULL;
  528. PRInt32 http_connection_time_out = 0;
  529. int buflen = (HTTP_GET_STD_LEN + strlen(path));
  530. reqBUF = (char *)PR_Calloc(1, buflen);
  531. if (!reqBUF) {
  532. status = PR_FAILURE;
  533. goto out;
  534. }
  535. strcpy(reqBUF, HTTP_GET);
  536. strcat(reqBUF, " ");
  537. strcat(reqBUF, path);
  538. strcat(reqBUF, " ");
  539. strcat(reqBUF, HTTP_PROTOCOL);
  540. strcat(reqBUF, "\r\n\r\n\0");
  541. http_connection_time_out = httpConfig->connectionTimeOut;
  542. status = sendFullData( fd, reqBUF, http_connection_time_out);
  543. out:
  544. if (reqBUF) {
  545. PR_Free(reqBUF);
  546. reqBUF = 0;
  547. }
  548. return status;
  549. }
  550. static PRStatus sendFullData( PRFileDesc *fd, char *buf, int timeOut)
  551. {
  552. int dataSent = 0;
  553. int bufLen = strlen(buf);
  554. int retVal = 0;
  555. PRInt32 errcode = 0;
  556. while (dataSent < bufLen)
  557. {
  558. retVal = PR_Send(fd, buf+dataSent, bufLen-dataSent, 0, PR_MillisecondsToInterval(timeOut));
  559. if (retVal == -1 )
  560. break;
  561. dataSent += retVal;
  562. }
  563. if (dataSent == bufLen )
  564. return PR_SUCCESS;
  565. else
  566. {
  567. errcode = PR_GetError();
  568. slapi_log_error( SLAPI_LOG_FATAL, HTTP_PLUGIN_SUBSYSTEM,
  569. "sendFullData: dataSent=%d bufLen=%d -> NSPR Error code (%d)\n",
  570. dataSent, bufLen, errcode);
  571. LDAPDebug( LDAP_DEBUG_PLUGIN, "---------->NSPR Error code (%d) \n", errcode,0,0);
  572. return PR_FAILURE;
  573. }
  574. }
  575. static PRStatus sendPostReq(PRFileDesc *fd, const char *path, httpheader **httpheaderArray, char *body)
  576. {
  577. PRStatus status = PR_SUCCESS;
  578. char body_len_str[20];
  579. char *reqBUF = NULL;
  580. PRInt32 http_connection_time_out = 0;
  581. int i = 0;
  582. int body_len, buflen = 0;
  583. if (body) {
  584. body_len = strlen(body);
  585. } else {
  586. body_len = 0;
  587. }
  588. PR_snprintf(body_len_str, sizeof(body_len_str), "%d", body_len);
  589. buflen = (HTTP_POST_STD_LEN + strlen(path) + body_len + strlen(body_len_str));
  590. for (i = 0; httpheaderArray[i] != NULL; i++) {
  591. if (httpheaderArray[i]->name != NULL)
  592. {
  593. buflen += strlen(httpheaderArray[i]->name) + 2;
  594. if (httpheaderArray[i]->value != NULL)
  595. buflen += strlen(httpheaderArray[i]->value) + 2;
  596. }
  597. }
  598. reqBUF = (char *)PR_Calloc(1, buflen);
  599. if (!reqBUF) {
  600. status = PR_FAILURE;
  601. goto out;
  602. }
  603. strcpy(reqBUF, HTTP_POST);
  604. strcat(reqBUF, " ");
  605. strcat(reqBUF, path);
  606. strcat(reqBUF, " ");
  607. strcat(reqBUF, HTTP_PROTOCOL);
  608. strcat(reqBUF, "\r\n");
  609. strcat(reqBUF, HTTP_CONTENT_LENGTH);
  610. strcat(reqBUF, " ");
  611. strcat(reqBUF, body_len_str);
  612. strcat(reqBUF, "\r\n");
  613. strcat(reqBUF, HTTP_CONTENT_TYPE_URL_ENCODED);
  614. strcat(reqBUF, "\r\n");
  615. for (i = 0; httpheaderArray[i] != NULL; i++) {
  616. if (httpheaderArray[i]->name != NULL)
  617. strcat(reqBUF, httpheaderArray[i]->name);
  618. strcat(reqBUF, ": ");
  619. if (httpheaderArray[i]->value != NULL)
  620. strcat(reqBUF, httpheaderArray[i]->value);
  621. strcat(reqBUF, "\r\n");
  622. }
  623. strcat(reqBUF, "\r\n");
  624. if (body) {
  625. strcat(reqBUF, body);
  626. }
  627. strcat(reqBUF, "\0");
  628. LDAPDebug( LDAP_DEBUG_PLUGIN, "---------->reqBUF is %s \n",reqBUF,0,0);
  629. http_connection_time_out = httpConfig->connectionTimeOut;
  630. status = sendFullData( fd, reqBUF, http_connection_time_out);
  631. out:
  632. if (reqBUF) {
  633. PR_Free(reqBUF);
  634. reqBUF = 0;
  635. }
  636. return status;
  637. }
  638. static PRStatus getChar(PRFileDesc *fd, char *buf)
  639. {
  640. PRInt32 bytesRead = http_read(fd, buf, 1);
  641. if (bytesRead <=0) {
  642. PRInt32 errcode = PR_GetError();
  643. slapi_log_error( SLAPI_LOG_FATAL, HTTP_PLUGIN_SUBSYSTEM,
  644. "getChar: NSPR Error code (%d)\n", errcode);
  645. return PR_FAILURE;
  646. }
  647. return PR_SUCCESS;
  648. }
  649. static PRStatus getBody(PRFileDesc *fd, char **buf, int *actualBytesRead)
  650. {
  651. int totalBytesRead = 0;
  652. int size = 4 * HTTP_DEFAULT_BUFFER_SIZE;
  653. int bytesRead = size;
  654. char *data = (char *) PR_Calloc(1, size);
  655. while (bytesRead == size) {
  656. bytesRead = http_read(fd, (data+totalBytesRead), size);
  657. if (bytesRead <= 0) {
  658. /* Read error */
  659. return PR_FAILURE;
  660. }
  661. if (bytesRead == size) {
  662. /* more data to be read so increase the buffer */
  663. size = size * 2 ;
  664. data = (char *) PR_Realloc(data, size);
  665. }
  666. totalBytesRead += bytesRead;
  667. }
  668. *buf = data;
  669. *actualBytesRead = totalBytesRead;
  670. return PR_SUCCESS;
  671. }
  672. static PRInt32 http_read(PRFileDesc *fd, char *buf, int size)
  673. {
  674. PRInt32 http_read_time_out = 0;
  675. http_read_time_out = httpConfig->readTimeOut;
  676. return PR_Recv(fd, buf, size, 0, PR_MillisecondsToInterval(http_read_time_out));
  677. }
  678. static PRBool isWhiteSpace(char ch)
  679. {
  680. PRBool b = PR_FALSE;
  681. if (ch == ' ') {
  682. b = PR_TRUE;
  683. }
  684. return b;
  685. }
  686. static PRStatus parseURI(const char *urlstr, char **host, PRInt32 *port, char **path, int *sslOn)
  687. {
  688. PRStatus status = PR_SUCCESS;
  689. char *brk;
  690. int len;
  691. static const char delimiters[] = ":/?#";
  692. char *url = isHttpReq(urlstr, sslOn);
  693. if (*sslOn) {
  694. *port = 443;
  695. }
  696. else {
  697. *port = 80;
  698. }
  699. if (url == NULL) {
  700. /* Error : */
  701. status = PR_FAILURE;
  702. goto bail;
  703. }
  704. len = PL_strlen(url);
  705. /* Currently we do not support Ipv6 addresses */
  706. brk = PL_strpbrk(url, delimiters);
  707. if (!brk) {
  708. *host = PL_strndup(url, len);
  709. toLowerCase(*host);
  710. goto bail;
  711. }
  712. switch (*brk)
  713. {
  714. case '/' :
  715. case '?' :
  716. case '#' :
  717. /* Get the Host, the rest is Path */
  718. *host = PL_strndup(url, (brk - url));
  719. toLowerCase(*host);
  720. status = parseAtPath(brk, path);
  721. break;
  722. case ':' :
  723. /* Get the Host and process port, path */
  724. *host = PL_strndup(url, (brk - url));
  725. toLowerCase(*host);
  726. status = parseAtPort(brk+1, port, path);
  727. break;
  728. default:
  729. /* Error : HTTP_BAD_URL */
  730. break;
  731. }
  732. bail:
  733. if (url) {
  734. PR_Free(url);
  735. }
  736. return status;
  737. }
  738. static PRStatus parseAtPort(const char* url, PRInt32 *port, char **path)
  739. {
  740. PRStatus status = PR_SUCCESS;
  741. static const char delimiters[] = "/?#";
  742. char* brk = PL_strpbrk(url, delimiters);
  743. if (!brk) /* everything is a Port */
  744. {
  745. *port = getPort(url);
  746. if (*port <= 0) {
  747. /* Error : HTTP_BAD_URL */
  748. return PR_FAILURE;
  749. } else {
  750. return status;
  751. }
  752. }
  753. switch (*brk)
  754. {
  755. case '/' :
  756. case '?' :
  757. case '#' :
  758. /* Get the Port, the rest is Path */
  759. *port = getPort(url);
  760. if (*port <= 0) {
  761. /* Error : HTTP_BAD_URL */
  762. return PR_FAILURE;
  763. }
  764. status = parseAtPath(brk, path);
  765. break;
  766. default:
  767. /* Error : HTTP_BAD_URL */
  768. break;
  769. }
  770. return status;
  771. }
  772. static PRStatus parseAtPath(const char *url, char **path)
  773. {
  774. PRStatus status = PR_SUCCESS;
  775. char *dir = "%s%s";
  776. *path = (char *)PR_Calloc(1, strlen(dir) + strlen(url) + 2);
  777. if (!*path) {
  778. /* Error : HTTP_BAD_URL */
  779. status = PR_FAILURE;
  780. goto out;
  781. }
  782. /* Just write the path and check for a starting / */
  783. if ('/' != *url) {
  784. sprintf(*path, dir, "/", url);
  785. } else {
  786. strcpy(*path, url);
  787. }
  788. out:
  789. return status;
  790. }
  791. static void toLowerCase(char* str)
  792. {
  793. if (str) {
  794. char* lstr = str;
  795. PRInt8 shift = 'a' - 'A';
  796. for(; (*lstr != '\0'); ++lstr) {
  797. if ((*(lstr) <= 'Z') && (*(lstr) >= 'A')) {
  798. *(lstr) = *(lstr) + shift;
  799. }
  800. }
  801. }
  802. }
  803. static PRInt32 getPort(const char* src)
  804. {
  805. /* search for digits up to a slash or the string ends */
  806. const char* port = src;
  807. PRInt32 returnValue = -1;
  808. char c;
  809. /* skip leading white space */
  810. while (isAsciiSpace(*port))
  811. port++;
  812. while ((c = *port++) != '\0') {
  813. /* stop if slash or ? or # reached */
  814. if (c == '/' || c == '?' || c == '#')
  815. break;
  816. else if (!isAsciiDigit(c))
  817. return returnValue;
  818. }
  819. return (0 < PR_sscanf(src, "%d", &returnValue)) ? returnValue : -1;
  820. }
  821. static PRBool isAsciiSpace(char aChar)
  822. {
  823. if ((aChar == ' ') || (aChar == '\r') || (aChar == '\n') || (aChar == '\t')) {
  824. return PR_TRUE;
  825. }
  826. return PR_FALSE;
  827. }
  828. static PRBool isAsciiDigit(char aChar)
  829. {
  830. if ((aChar >= '0') && (aChar <= '9')) {
  831. return PR_TRUE;
  832. }
  833. return PR_FALSE;
  834. }
  835. static void setTCPNoDelay(PRFileDesc* fd)
  836. {
  837. PRStatus status = PR_SUCCESS;
  838. PRSocketOptionData opt;
  839. opt.option = PR_SockOpt_NoDelay;
  840. opt.value.no_delay = PR_FALSE;
  841. status = PR_GetSocketOption(fd, &opt);
  842. if (status == PR_FAILURE) {
  843. return;
  844. }
  845. opt.option = PR_SockOpt_NoDelay;
  846. opt.value.no_delay = PR_TRUE;
  847. status = PR_SetSocketOption(fd, &opt);
  848. if (status == PR_FAILURE) {
  849. return;
  850. }
  851. return;
  852. }
  853. static char * isHttpReq(const char *url, int *sslOn)
  854. {
  855. static const char http_protopol_header[] = "http://";
  856. static const char https_protopol_header[] = "https://";
  857. char *newstr = NULL;
  858. /* skip leading white space */
  859. while (isAsciiSpace(*url))
  860. url++;
  861. if (strncmp(url, http_protopol_header, strlen(http_protopol_header)) == 0) {
  862. newstr = (char *)PR_Calloc(1, (strlen(url)-strlen(http_protopol_header) + 1));
  863. strcpy(newstr, url+7);
  864. strcat(newstr,"\0");
  865. *sslOn = 0;
  866. }
  867. else if (strncmp(url, https_protopol_header, strlen(https_protopol_header)) == 0) {
  868. newstr = (char *)PR_Calloc(1, (strlen(url)-strlen(https_protopol_header) + 1));
  869. strcpy(newstr, url+8);
  870. strcat(newstr,"\0");
  871. *sslOn = 1;
  872. }
  873. return newstr;
  874. }
  875. PRFileDesc* setupSSLSocket(PRFileDesc* fd)
  876. {
  877. SECStatus secStatus;
  878. PRFileDesc* sslSocket;
  879. PRSocketOptionData socketOption;
  880. char *certNickname = NULL;
  881. socketOption.option = PR_SockOpt_Nonblocking;
  882. socketOption.value.non_blocking = PR_FALSE;
  883. if( PR_SetSocketOption(fd, &socketOption) != 0) {
  884. slapi_log_error( SLAPI_LOG_PLUGIN, HTTP_PLUGIN_SUBSYSTEM,
  885. "Cannot set socket option NSS \n");
  886. return NULL;
  887. }
  888. sslSocket = SSL_ImportFD(NULL, fd);
  889. if (!sslSocket) {
  890. slapi_log_error( SLAPI_LOG_PLUGIN, HTTP_PLUGIN_SUBSYSTEM,
  891. "setupSSLSocket: Cannot import to SSL Socket\n" );
  892. goto sslbail;
  893. }
  894. slapi_log_error( SLAPI_LOG_FATAL, HTTP_PLUGIN_SUBSYSTEM,
  895. "setupSSLSocket: setupssl socket created\n" );
  896. secStatus = SSL_OptionSet(sslSocket, SSL_SECURITY, 1);
  897. if (SECSuccess != secStatus) {
  898. slapi_log_error( SLAPI_LOG_PLUGIN, HTTP_PLUGIN_SUBSYSTEM,
  899. "setupSSLSocket: Cannot set SSL_SECURITY option\n");
  900. goto sslbail;
  901. }
  902. secStatus = SSL_OptionSet(sslSocket, SSL_HANDSHAKE_AS_CLIENT, 1);
  903. if (SECSuccess != secStatus) {
  904. slapi_log_error( SLAPI_LOG_PLUGIN, HTTP_PLUGIN_SUBSYSTEM,
  905. "setupSSLSocket: CAnnot set SSL_HANDSHAKE_AS_CLIENT option\n");
  906. goto sslbail;
  907. }
  908. /* Set SSL callback routines. */
  909. secStatus = SSL_GetClientAuthDataHook(sslSocket,
  910. (SSLGetClientAuthData) getClientAuthData,
  911. (void *)certNickname);
  912. if (secStatus != SECSuccess) {
  913. slapi_log_error( SLAPI_LOG_PLUGIN, HTTP_PLUGIN_SUBSYSTEM,
  914. "setupSSLSocket: SSL_GetClientAuthDataHook Failed\n");
  915. goto sslbail;
  916. }
  917. secStatus = SSL_AuthCertificateHook(sslSocket,
  918. (SSLAuthCertificate) authCertificate,
  919. (void *)CERT_GetDefaultCertDB());
  920. if (secStatus != SECSuccess) {
  921. slapi_log_error( SLAPI_LOG_PLUGIN, HTTP_PLUGIN_SUBSYSTEM,
  922. "setupSSLSocket: SSL_AuthCertificateHook Failed\n");
  923. goto sslbail;
  924. }
  925. secStatus = SSL_BadCertHook(sslSocket,
  926. (SSLBadCertHandler) badCertHandler, NULL);
  927. if (secStatus != SECSuccess) {
  928. slapi_log_error( SLAPI_LOG_PLUGIN, HTTP_PLUGIN_SUBSYSTEM,
  929. "setupSSLSocket: SSL_BadCertHook Failed\n");
  930. goto sslbail;
  931. }
  932. secStatus = SSL_HandshakeCallback(sslSocket,
  933. (SSLHandshakeCallback) handshakeCallback, NULL);
  934. if (secStatus != SECSuccess) {
  935. slapi_log_error( SLAPI_LOG_PLUGIN, HTTP_PLUGIN_SUBSYSTEM,
  936. "setupSSLSocket: SSL_HandshakeCallback Failed\n");
  937. goto sslbail;
  938. }
  939. return sslSocket;
  940. sslbail:
  941. PR_Close(fd);
  942. return NULL;
  943. }
  944. SECStatus
  945. authCertificate(void *arg, PRFileDesc *socket,
  946. PRBool checksig, PRBool isServer)
  947. {
  948. SECCertUsage certUsage;
  949. CERTCertificate * cert;
  950. void * pinArg;
  951. char * hostName;
  952. SECStatus secStatus;
  953. if (!arg || !socket) {
  954. slapi_log_error(SLAPI_LOG_PLUGIN, HTTP_PLUGIN_SUBSYSTEM,
  955. " authCertificate: Faulty socket in callback function \n");
  956. return SECFailure;
  957. }
  958. /* Define how the cert is being used based upon the isServer flag. */
  959. certUsage = isServer ? certUsageSSLClient : certUsageSSLServer;
  960. cert = SSL_PeerCertificate(socket);
  961. pinArg = SSL_RevealPinArg(socket);
  962. secStatus = CERT_VerifyCertNow((CERTCertDBHandle *)arg,
  963. cert,
  964. checksig,
  965. certUsage,
  966. pinArg);
  967. /* If this is a server, we're finished. */
  968. if (isServer || secStatus != SECSuccess) {
  969. return secStatus;
  970. }
  971. hostName = SSL_RevealURL(socket);
  972. if (hostName && hostName[0]) {
  973. secStatus = CERT_VerifyCertName(cert, hostName);
  974. } else {
  975. PR_SetError(SSL_ERROR_BAD_CERT_DOMAIN, 0);
  976. secStatus = SECFailure;
  977. }
  978. if (hostName)
  979. PR_Free(hostName);
  980. return secStatus;
  981. }
  982. SECStatus
  983. badCertHandler(void *arg, PRFileDesc *socket)
  984. {
  985. SECStatus secStatus = SECFailure;
  986. PRErrorCode err;
  987. /* log invalid cert here */
  988. if (!arg) {
  989. return secStatus;
  990. }
  991. *(PRErrorCode *)arg = err = PORT_GetError();
  992. switch (err) {
  993. case SEC_ERROR_INVALID_AVA:
  994. case SEC_ERROR_INVALID_TIME:
  995. case SEC_ERROR_BAD_SIGNATURE:
  996. case SEC_ERROR_EXPIRED_CERTIFICATE:
  997. case SEC_ERROR_UNKNOWN_ISSUER:
  998. case SEC_ERROR_UNTRUSTED_CERT:
  999. case SEC_ERROR_CERT_VALID:
  1000. case SEC_ERROR_EXPIRED_ISSUER_CERTIFICATE:
  1001. case SEC_ERROR_CRL_EXPIRED:
  1002. case SEC_ERROR_CRL_BAD_SIGNATURE:
  1003. case SEC_ERROR_EXTENSION_VALUE_INVALID:
  1004. case SEC_ERROR_CA_CERT_INVALID:
  1005. case SEC_ERROR_CERT_USAGES_INVALID:
  1006. case SEC_ERROR_UNKNOWN_CRITICAL_EXTENSION:
  1007. secStatus = SECSuccess;
  1008. break;
  1009. default:
  1010. secStatus = SECFailure;
  1011. break;
  1012. }
  1013. slapi_log_error(SLAPI_LOG_PLUGIN, HTTP_PLUGIN_SUBSYSTEM,
  1014. "Bad certificate: %d\n", err);
  1015. return secStatus;
  1016. }
  1017. SECStatus
  1018. getClientAuthData(void *arg,
  1019. PRFileDesc *socket,
  1020. struct CERTDistNamesStr *caNames,
  1021. struct CERTCertificateStr **pRetCert,
  1022. struct SECKEYPrivateKeyStr **pRetKey)
  1023. {
  1024. CERTCertificate * cert;
  1025. SECKEYPrivateKey * privKey = NULL;
  1026. char * chosenNickName = (char *)arg;
  1027. void * proto_win = NULL;
  1028. SECStatus secStatus = SECFailure;
  1029. proto_win = SSL_RevealPinArg(socket);
  1030. if (chosenNickName) {
  1031. cert = PK11_FindCertFromNickname(chosenNickName, proto_win);
  1032. if (cert) {
  1033. privKey = PK11_FindKeyByAnyCert(cert, proto_win);
  1034. if (privKey) {
  1035. secStatus = SECSuccess;
  1036. } else {
  1037. CERT_DestroyCertificate(cert);
  1038. }
  1039. }
  1040. } else { /* no nickname given, automatically find the right cert */
  1041. CERTCertNicknames *names;
  1042. int i;
  1043. names = CERT_GetCertNicknames(CERT_GetDefaultCertDB(),
  1044. SEC_CERT_NICKNAMES_USER, proto_win);
  1045. if (names != NULL) {
  1046. for(i = 0; i < names->numnicknames; i++ ) {
  1047. cert = PK11_FindCertFromNickname(names->nicknames[i],
  1048. proto_win);
  1049. if (!cert) {
  1050. continue;
  1051. }
  1052. /* Only check unexpired certs */
  1053. if (CERT_CheckCertValidTimes(cert, PR_Now(), PR_FALSE)
  1054. != secCertTimeValid ) {
  1055. CERT_DestroyCertificate(cert);
  1056. continue;
  1057. }
  1058. secStatus = NSS_CmpCertChainWCANames(cert, caNames);
  1059. if (secStatus == SECSuccess) {
  1060. privKey = PK11_FindKeyByAnyCert(cert, proto_win);
  1061. if (privKey) {
  1062. break;
  1063. }
  1064. secStatus = SECFailure;
  1065. break;
  1066. }
  1067. CERT_FreeNicknames(names);
  1068. } /* for loop */
  1069. }
  1070. }
  1071. if (secStatus == SECSuccess) {
  1072. *pRetCert = cert;
  1073. *pRetKey = privKey;
  1074. }
  1075. return secStatus;
  1076. }
  1077. SECStatus
  1078. handshakeCallback(PRFileDesc *socket, void *arg)
  1079. {
  1080. slapi_log_error(SLAPI_LOG_PLUGIN, HTTP_PLUGIN_SUBSYSTEM,
  1081. "----------> Handshake has completed, ready to send data securely.\n");
  1082. return SECSuccess;
  1083. }
  1084. /**
  1085. * PUBLIC FUNCTIONS IMPLEMENTATION
  1086. */
  1087. int http_impl_init(Slapi_ComponentId *plugin_id)
  1088. {
  1089. int status = HTTP_IMPL_SUCCESS;
  1090. slapi_log_error(SLAPI_LOG_PLUGIN, HTTP_PLUGIN_SUBSYSTEM,
  1091. "-> http_impl_init \n");
  1092. httpConfig = NULL;
  1093. httpConfig = (httpPluginConfig *) slapi_ch_calloc(1, sizeof(httpPluginConfig));
  1094. status = readConfigLDAPurl(plugin_id, HTTP_PLUGIN_DN);
  1095. if (status != 0) {
  1096. slapi_log_error(SLAPI_LOG_FATAL, HTTP_PLUGIN_SUBSYSTEM,
  1097. "http_impl_start: Unable to get HTTP config information \n");
  1098. return HTTP_IMPL_FAILURE;
  1099. }
  1100. status = readConfigLDAPurl(plugin_id, CONFIG_DN);
  1101. if (status != 0) {
  1102. slapi_log_error(SLAPI_LOG_FATAL, HTTP_PLUGIN_SUBSYSTEM,
  1103. "http_impl_start: Unable to get config information \n");
  1104. return HTTP_IMPL_FAILURE;
  1105. }
  1106. slapi_log_error(SLAPI_LOG_PLUGIN, HTTP_PLUGIN_SUBSYSTEM,
  1107. "<- http_impl_init \n");
  1108. return status;
  1109. }
  1110. int http_impl_get_text(char *url, char **data, int *bytesRead)
  1111. {
  1112. int status = HTTP_IMPL_SUCCESS;
  1113. status = doRequestRetry(url, NULL, NULL, data, bytesRead, HTTP_REQ_TYPE_GET);
  1114. return status;
  1115. }
  1116. int http_impl_get_binary(char *url, char **data, int *bytesRead)
  1117. {
  1118. int status = HTTP_IMPL_SUCCESS;
  1119. status = doRequestRetry(url, NULL, NULL, data, bytesRead, HTTP_REQ_TYPE_GET);
  1120. return status;
  1121. }
  1122. int http_impl_get_redirected_uri(char *url, char **data, int *bytesRead)
  1123. {
  1124. int status = HTTP_IMPL_SUCCESS;
  1125. status = doRequestRetry(url, NULL, NULL, data, bytesRead, HTTP_REQ_TYPE_REDIRECT);
  1126. return status;
  1127. }
  1128. int http_impl_post(char *url, httpheader **httpheaderArray, char *body, char **data, int *bytesRead)
  1129. {
  1130. int status = HTTP_IMPL_SUCCESS;
  1131. status = doRequestRetry(url, httpheaderArray, body, data, bytesRead, HTTP_REQ_TYPE_POST);
  1132. return status;
  1133. }
  1134. void http_impl_shutdown()
  1135. {
  1136. /**
  1137. * Put cleanup code here
  1138. */
  1139. }
  1140. static int readConfigLDAPurl(Slapi_ComponentId *plugin_id, char *plugindn) {
  1141. int rc = LDAP_SUCCESS;
  1142. Slapi_DN *sdn = NULL;
  1143. int status = HTTP_IMPL_SUCCESS;
  1144. Slapi_Entry *entry = NULL;
  1145. sdn = slapi_sdn_new_dn_byref(plugindn);
  1146. rc = slapi_search_internal_get_entry(sdn, NULL, &entry, plugin_id);
  1147. slapi_sdn_free(&sdn);
  1148. if (rc != LDAP_SUCCESS) {
  1149. slapi_log_error( SLAPI_LOG_PLUGIN, HTTP_PLUGIN_SUBSYSTEM,
  1150. "readConfigLDAPurl: Could not find entry %s (error %d)\n", plugindn, rc);
  1151. status = HTTP_IMPL_FAILURE;
  1152. return status;
  1153. }
  1154. if (NULL == entry)
  1155. {
  1156. slapi_log_error( SLAPI_LOG_PLUGIN, HTTP_PLUGIN_SUBSYSTEM,
  1157. "readConfigLDAPurl: No entries found for <%s>\n", plugindn);
  1158. status = HTTP_IMPL_FAILURE;
  1159. return status;
  1160. }
  1161. if ((PL_strcasecmp(plugindn, HTTP_PLUGIN_DN) == 0))
  1162. status = parseHTTPConfigEntry(entry);
  1163. else
  1164. status = parseConfigEntry(entry);
  1165. slapi_entry_free(entry);
  1166. return status;
  1167. }
  1168. /* Retrieves the plugin configuration info */
  1169. /* Retrieves security info as well as the path info required for the SSL
  1170. config dir */
  1171. static int parseConfigEntry(Slapi_Entry *e)
  1172. {
  1173. char *value = NULL;
  1174. value = slapi_entry_attr_get_charptr(e, ATTR_DS_SECURITY);
  1175. if (value) {
  1176. httpConfig->DS_sslOn = value;
  1177. }
  1178. return HTTP_IMPL_SUCCESS;
  1179. }
  1180. static int parseHTTPConfigEntry(Slapi_Entry *e)
  1181. {
  1182. int value = 0;
  1183. value = slapi_entry_attr_get_int(e, ATTR_RETRY_COUNT);
  1184. if (value) {
  1185. httpConfig->retryCount = value;
  1186. }
  1187. value = slapi_entry_attr_get_int(e, ATTR_CONNECTION_TIME_OUT);
  1188. if (value) {
  1189. httpConfig->connectionTimeOut = value;
  1190. }
  1191. else {
  1192. LDAPDebug( LDAP_DEBUG_PLUGIN, "parseHTTPConfigEntry: HTTP Connection Time Out cannot be read. Setting to default value of 5000 ms \n", 0,0,0);
  1193. httpConfig->connectionTimeOut = 5000;
  1194. }
  1195. value = slapi_entry_attr_get_int(e, ATTR_READ_TIME_OUT);
  1196. if (value) {
  1197. httpConfig->readTimeOut = value;
  1198. }
  1199. else {
  1200. LDAPDebug( LDAP_DEBUG_PLUGIN, "parseHTTPConfigEntry: HTTP Read Time Out cannot be read. Setting to default value of 5000 ms \n", 0,0,0);
  1201. httpConfig->readTimeOut = 5000;
  1202. }
  1203. httpConfig->nssInitialized = 0;
  1204. return HTTP_IMPL_SUCCESS;
  1205. }
  1206. /**
  1207. * Self Testing
  1208. */
  1209. #ifdef BUILD_STANDALONE
  1210. int main(int argc, char **argv)
  1211. {
  1212. PRStatus status = PR_SUCCESS;
  1213. char *buf;
  1214. int bytes;
  1215. char *host;
  1216. PRInt32 port;
  1217. char *path;
  1218. if (argc < 2) {
  1219. printf("URL missing\n");
  1220. return -1;
  1221. }
  1222. PR_Init(PR_USER_THREAD,PR_PRIORITY_NORMAL, 0);
  1223. doRequest(argv[1], &buf, &bytes, 2);
  1224. printf( "%s\n", buf );
  1225. return -1;
  1226. }
  1227. #endif