http_impl.c 39 KB

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