sock_uwp.cpp 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502
  1. /*
  2. * Copyright (C) 2016 Teluu Inc. (http://www.teluu.com)
  3. *
  4. * This program is free software; you can redistribute it and/or modify
  5. * it under the terms of the GNU General Public License as published by
  6. * the Free Software Foundation; either version 2 of the License, or
  7. * (at your option) any later version.
  8. *
  9. * This program is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. * GNU General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU General Public License
  15. * along with this program; if not, write to the Free Software
  16. * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  17. */
  18. #include <pj/assert.h>
  19. #include <pj/errno.h>
  20. #include <pj/math.h>
  21. #include <pj/os.h>
  22. #include <pj/compat/socket.h>
  23. #include <ppltasks.h>
  24. #include <string>
  25. #define THIS_FILE "sock_uwp.cpp"
  26. #include "sock_uwp.h"
  27. /*
  28. * Address families conversion.
  29. * The values here are indexed based on pj_addr_family.
  30. */
  31. const pj_uint16_t PJ_AF_UNSPEC = AF_UNSPEC;
  32. const pj_uint16_t PJ_AF_UNIX = AF_UNIX;
  33. const pj_uint16_t PJ_AF_INET = AF_INET;
  34. const pj_uint16_t PJ_AF_INET6 = AF_INET6;
  35. #ifdef AF_PACKET
  36. const pj_uint16_t PJ_AF_PACKET = AF_PACKET;
  37. #else
  38. const pj_uint16_t PJ_AF_PACKET = 0xFFFF;
  39. #endif
  40. #ifdef AF_IRDA
  41. const pj_uint16_t PJ_AF_IRDA = AF_IRDA;
  42. #else
  43. const pj_uint16_t PJ_AF_IRDA = 0xFFFF;
  44. #endif
  45. /*
  46. * Socket types conversion.
  47. * The values here are indexed based on pj_sock_type
  48. */
  49. const pj_uint16_t PJ_SOCK_STREAM= SOCK_STREAM;
  50. const pj_uint16_t PJ_SOCK_DGRAM = SOCK_DGRAM;
  51. const pj_uint16_t PJ_SOCK_RAW = SOCK_RAW;
  52. const pj_uint16_t PJ_SOCK_RDM = SOCK_RDM;
  53. const int PJ_SOCK_CLOEXEC = 0;
  54. /*
  55. * Socket level values.
  56. */
  57. const pj_uint16_t PJ_SOL_SOCKET = SOL_SOCKET;
  58. #ifdef SOL_IP
  59. const pj_uint16_t PJ_SOL_IP = SOL_IP;
  60. #elif (defined(PJ_WIN32) && PJ_WIN32) || (defined(PJ_WIN64) && PJ_WIN64)
  61. const pj_uint16_t PJ_SOL_IP = IPPROTO_IP;
  62. #else
  63. const pj_uint16_t PJ_SOL_IP = 0;
  64. #endif /* SOL_IP */
  65. #if defined(SOL_TCP)
  66. const pj_uint16_t PJ_SOL_TCP = SOL_TCP;
  67. #elif defined(IPPROTO_TCP)
  68. const pj_uint16_t PJ_SOL_TCP = IPPROTO_TCP;
  69. #elif (defined(PJ_WIN32) && PJ_WIN32) || (defined(PJ_WIN64) && PJ_WIN64)
  70. const pj_uint16_t PJ_SOL_TCP = IPPROTO_TCP;
  71. #else
  72. const pj_uint16_t PJ_SOL_TCP = 6;
  73. #endif /* SOL_TCP */
  74. #ifdef SOL_UDP
  75. const pj_uint16_t PJ_SOL_UDP = SOL_UDP;
  76. #elif defined(IPPROTO_UDP)
  77. const pj_uint16_t PJ_SOL_UDP = IPPROTO_UDP;
  78. #elif (defined(PJ_WIN32) && PJ_WIN32) || (defined(PJ_WIN64) && PJ_WIN64)
  79. const pj_uint16_t PJ_SOL_UDP = IPPROTO_UDP;
  80. #else
  81. const pj_uint16_t PJ_SOL_UDP = 17;
  82. #endif /* SOL_UDP */
  83. #ifdef SOL_IPV6
  84. const pj_uint16_t PJ_SOL_IPV6 = SOL_IPV6;
  85. #elif (defined(PJ_WIN32) && PJ_WIN32) || (defined(PJ_WIN64) && PJ_WIN64)
  86. # if defined(IPPROTO_IPV6) || (_WIN32_WINNT >= 0x0501)
  87. const pj_uint16_t PJ_SOL_IPV6 = IPPROTO_IPV6;
  88. # else
  89. const pj_uint16_t PJ_SOL_IPV6 = 41;
  90. # endif
  91. #else
  92. const pj_uint16_t PJ_SOL_IPV6 = 41;
  93. #endif /* SOL_IPV6 */
  94. /* IP_TOS */
  95. #ifdef IP_TOS
  96. const pj_uint16_t PJ_IP_TOS = IP_TOS;
  97. #else
  98. const pj_uint16_t PJ_IP_TOS = 1;
  99. #endif
  100. /* TOS settings (declared in netinet/ip.h) */
  101. #ifdef IPTOS_LOWDELAY
  102. const pj_uint16_t PJ_IPTOS_LOWDELAY = IPTOS_LOWDELAY;
  103. #else
  104. const pj_uint16_t PJ_IPTOS_LOWDELAY = 0x10;
  105. #endif
  106. #ifdef IPTOS_THROUGHPUT
  107. const pj_uint16_t PJ_IPTOS_THROUGHPUT = IPTOS_THROUGHPUT;
  108. #else
  109. const pj_uint16_t PJ_IPTOS_THROUGHPUT = 0x08;
  110. #endif
  111. #ifdef IPTOS_RELIABILITY
  112. const pj_uint16_t PJ_IPTOS_RELIABILITY = IPTOS_RELIABILITY;
  113. #else
  114. const pj_uint16_t PJ_IPTOS_RELIABILITY = 0x04;
  115. #endif
  116. #ifdef IPTOS_MINCOST
  117. const pj_uint16_t PJ_IPTOS_MINCOST = IPTOS_MINCOST;
  118. #else
  119. const pj_uint16_t PJ_IPTOS_MINCOST = 0x02;
  120. #endif
  121. /* optname values. */
  122. const pj_uint16_t PJ_SO_TYPE = SO_TYPE;
  123. const pj_uint16_t PJ_SO_RCVBUF = SO_RCVBUF;
  124. const pj_uint16_t PJ_SO_SNDBUF = SO_SNDBUF;
  125. const pj_uint16_t PJ_TCP_NODELAY= TCP_NODELAY;
  126. const pj_uint16_t PJ_SO_REUSEADDR= SO_REUSEADDR;
  127. #ifdef SO_NOSIGPIPE
  128. const pj_uint16_t PJ_SO_NOSIGPIPE = SO_NOSIGPIPE;
  129. #else
  130. const pj_uint16_t PJ_SO_NOSIGPIPE = 0xFFFF;
  131. #endif
  132. #if defined(SO_PRIORITY)
  133. const pj_uint16_t PJ_SO_PRIORITY = SO_PRIORITY;
  134. #else
  135. /* This is from Linux, YMMV */
  136. const pj_uint16_t PJ_SO_PRIORITY = 12;
  137. #endif
  138. /* Multicasting is not supported e.g. in PocketPC 2003 SDK */
  139. #ifdef IP_MULTICAST_IF
  140. const pj_uint16_t PJ_IP_MULTICAST_IF = IP_MULTICAST_IF;
  141. const pj_uint16_t PJ_IP_MULTICAST_TTL = IP_MULTICAST_TTL;
  142. const pj_uint16_t PJ_IP_MULTICAST_LOOP = IP_MULTICAST_LOOP;
  143. const pj_uint16_t PJ_IP_ADD_MEMBERSHIP = IP_ADD_MEMBERSHIP;
  144. const pj_uint16_t PJ_IP_DROP_MEMBERSHIP = IP_DROP_MEMBERSHIP;
  145. #else
  146. const pj_uint16_t PJ_IP_MULTICAST_IF = 0xFFFF;
  147. const pj_uint16_t PJ_IP_MULTICAST_TTL = 0xFFFF;
  148. const pj_uint16_t PJ_IP_MULTICAST_LOOP = 0xFFFF;
  149. const pj_uint16_t PJ_IP_ADD_MEMBERSHIP = 0xFFFF;
  150. const pj_uint16_t PJ_IP_DROP_MEMBERSHIP = 0xFFFF;
  151. #endif
  152. /* recv() and send() flags */
  153. const int PJ_MSG_OOB = MSG_OOB;
  154. const int PJ_MSG_PEEK = MSG_PEEK;
  155. const int PJ_MSG_DONTROUTE = MSG_DONTROUTE;
  156. using namespace Platform;
  157. using namespace Windows::Foundation;
  158. using namespace Windows::Networking;
  159. using namespace Windows::Networking::Sockets;
  160. using namespace Windows::Storage::Streams;
  161. ref class PjUwpSocketDatagramRecvHelper sealed
  162. {
  163. internal:
  164. PjUwpSocketDatagramRecvHelper(PjUwpSocket* uwp_sock_) :
  165. uwp_sock(uwp_sock_), avail_data_len(0), recv_args(nullptr)
  166. {
  167. recv_wait = CreateEventEx(nullptr, nullptr, 0, EVENT_ALL_ACCESS);
  168. event_token = uwp_sock->datagram_sock->MessageReceived +=
  169. ref new TypedEventHandler<DatagramSocket^,
  170. DatagramSocketMessageReceivedEventArgs^>
  171. (this, &PjUwpSocketDatagramRecvHelper::OnMessageReceived);
  172. }
  173. void OnMessageReceived(DatagramSocket ^sender,
  174. DatagramSocketMessageReceivedEventArgs ^args)
  175. {
  176. try {
  177. if (uwp_sock->sock_state >= SOCKSTATE_DISCONNECTED)
  178. return;
  179. recv_args = args;
  180. avail_data_len = args->GetDataReader()->UnconsumedBufferLength;
  181. if (uwp_sock->cb.on_read) {
  182. (*uwp_sock->cb.on_read)(uwp_sock, avail_data_len);
  183. }
  184. WaitForSingleObjectEx(recv_wait, INFINITE, false);
  185. } catch (...) {}
  186. }
  187. pj_status_t ReadDataIfAvailable(void *buf, pj_ssize_t *len,
  188. pj_sockaddr_t *from)
  189. {
  190. if (avail_data_len <= 0)
  191. return PJ_ENOTFOUND;
  192. if (*len < avail_data_len)
  193. return PJ_ETOOSMALL;
  194. // Read data
  195. auto reader = recv_args->GetDataReader();
  196. auto buffer = reader->ReadBuffer(avail_data_len);
  197. unsigned char *p;
  198. GetRawBufferFromIBuffer(buffer, &p);
  199. pj_memcpy((void*) buf, p, avail_data_len);
  200. *len = avail_data_len;
  201. // Get source address
  202. wstr_addr_to_sockaddr(recv_args->RemoteAddress->CanonicalName->Data(),
  203. recv_args->RemotePort->Data(), from);
  204. // finally
  205. avail_data_len = 0;
  206. SetEvent(recv_wait);
  207. return PJ_SUCCESS;
  208. }
  209. private:
  210. ~PjUwpSocketDatagramRecvHelper()
  211. {
  212. if (uwp_sock->datagram_sock)
  213. uwp_sock->datagram_sock->MessageReceived -= event_token;
  214. SetEvent(recv_wait);
  215. CloseHandle(recv_wait);
  216. }
  217. PjUwpSocket* uwp_sock;
  218. DatagramSocketMessageReceivedEventArgs^ recv_args;
  219. EventRegistrationToken event_token;
  220. HANDLE recv_wait;
  221. int avail_data_len;
  222. };
  223. ref class PjUwpSocketListenerHelper sealed
  224. {
  225. internal:
  226. PjUwpSocketListenerHelper(PjUwpSocket* uwp_sock_) :
  227. uwp_sock(uwp_sock_), conn_args(nullptr)
  228. {
  229. conn_wait = CreateEventEx(nullptr, nullptr, 0, EVENT_ALL_ACCESS);
  230. event_token = uwp_sock->listener_sock->ConnectionReceived +=
  231. ref new TypedEventHandler<StreamSocketListener^, StreamSocketListenerConnectionReceivedEventArgs^>
  232. (this, &PjUwpSocketListenerHelper::OnConnectionReceived);
  233. }
  234. void OnConnectionReceived(StreamSocketListener ^sender,
  235. StreamSocketListenerConnectionReceivedEventArgs ^args)
  236. {
  237. try {
  238. conn_args = args;
  239. if (uwp_sock->cb.on_accept) {
  240. (*uwp_sock->cb.on_accept)(uwp_sock);
  241. }
  242. WaitForSingleObjectEx(conn_wait, INFINITE, false);
  243. } catch (Exception^ e) {}
  244. }
  245. pj_status_t GetAcceptedSocket(StreamSocket^& stream_sock)
  246. {
  247. if (conn_args == nullptr)
  248. return PJ_ENOTFOUND;
  249. stream_sock = conn_args->Socket;
  250. // finally
  251. conn_args = nullptr;
  252. SetEvent(conn_wait);
  253. return PJ_SUCCESS;
  254. }
  255. private:
  256. ~PjUwpSocketListenerHelper()
  257. {
  258. if (uwp_sock->listener_sock)
  259. uwp_sock->listener_sock->ConnectionReceived -= event_token;
  260. SetEvent(conn_wait);
  261. CloseHandle(conn_wait);
  262. }
  263. PjUwpSocket* uwp_sock;
  264. StreamSocketListenerConnectionReceivedEventArgs^ conn_args;
  265. EventRegistrationToken event_token;
  266. HANDLE conn_wait;
  267. };
  268. PjUwpSocket::PjUwpSocket(int af_, int type_, int proto_) :
  269. af(af_), type(type_), proto(proto_),
  270. sock_type(SOCKTYPE_UNKNOWN),
  271. sock_state(SOCKSTATE_NULL),
  272. is_blocking(PJ_TRUE),
  273. has_pending_bind(PJ_FALSE),
  274. has_pending_send(PJ_FALSE),
  275. has_pending_recv(PJ_FALSE)
  276. {
  277. pj_sockaddr_init(pj_AF_INET(), &local_addr, NULL, 0);
  278. pj_sockaddr_init(pj_AF_INET(), &remote_addr, NULL, 0);
  279. }
  280. PjUwpSocket::~PjUwpSocket()
  281. {
  282. DeinitSocket();
  283. }
  284. PjUwpSocket* PjUwpSocket::CreateAcceptSocket(Windows::Networking::Sockets::StreamSocket^ stream_sock_)
  285. {
  286. PjUwpSocket *new_sock = new PjUwpSocket(pj_AF_INET(), pj_SOCK_STREAM(), 0);
  287. new_sock->stream_sock = stream_sock_;
  288. new_sock->sock_type = SOCKTYPE_STREAM;
  289. new_sock->sock_state = SOCKSTATE_CONNECTED;
  290. new_sock->socket_reader = ref new DataReader(new_sock->stream_sock->InputStream);
  291. new_sock->socket_writer = ref new DataWriter(new_sock->stream_sock->OutputStream);
  292. new_sock->socket_reader->InputStreamOptions = InputStreamOptions::Partial;
  293. new_sock->send_buffer = ref new Buffer(SEND_BUFFER_SIZE);
  294. new_sock->is_blocking = is_blocking;
  295. // Update local & remote address
  296. wstr_addr_to_sockaddr(stream_sock_->Information->RemoteAddress->CanonicalName->Data(),
  297. stream_sock_->Information->RemotePort->Data(),
  298. &new_sock->remote_addr);
  299. wstr_addr_to_sockaddr(stream_sock_->Information->LocalAddress->CanonicalName->Data(),
  300. stream_sock_->Information->LocalPort->Data(),
  301. &new_sock->local_addr);
  302. return new_sock;
  303. }
  304. pj_status_t PjUwpSocket::InitSocket(enum PjUwpSocketType sock_type_)
  305. {
  306. PJ_ASSERT_RETURN(sock_type_ > SOCKTYPE_UNKNOWN, PJ_EINVAL);
  307. sock_type = sock_type_;
  308. if (sock_type == SOCKTYPE_LISTENER) {
  309. listener_sock = ref new StreamSocketListener();
  310. } else if (sock_type == SOCKTYPE_STREAM) {
  311. stream_sock = ref new StreamSocket();
  312. } else if (sock_type == SOCKTYPE_DATAGRAM) {
  313. datagram_sock = ref new DatagramSocket();
  314. } else {
  315. pj_assert(!"Invalid socket type");
  316. return PJ_EINVAL;
  317. }
  318. if (sock_type == SOCKTYPE_DATAGRAM || sock_type == SOCKTYPE_STREAM) {
  319. send_buffer = ref new Buffer(SEND_BUFFER_SIZE);
  320. }
  321. sock_state = SOCKSTATE_INITIALIZED;
  322. return PJ_SUCCESS;
  323. }
  324. void PjUwpSocket::DeinitSocket()
  325. {
  326. if (stream_sock) {
  327. concurrency::create_task(stream_sock->CancelIOAsync()).wait();
  328. }
  329. if (datagram_sock && has_pending_send) {
  330. concurrency::create_task(datagram_sock->CancelIOAsync()).wait();
  331. }
  332. if (listener_sock) {
  333. concurrency::create_task(listener_sock->CancelIOAsync()).wait();
  334. }
  335. while (has_pending_recv) pj_thread_sleep(10);
  336. stream_sock = nullptr;
  337. datagram_sock = nullptr;
  338. dgram_recv_helper = nullptr;
  339. listener_sock = nullptr;
  340. listener_helper = nullptr;
  341. socket_writer = nullptr;
  342. socket_reader = nullptr;
  343. sock_state = SOCKSTATE_NULL;
  344. }
  345. pj_status_t PjUwpSocket::Bind(const pj_sockaddr_t *addr)
  346. {
  347. /* Not initialized yet, socket type is perhaps TCP, just not decided yet
  348. * whether it is a stream or a listener.
  349. */
  350. if (sock_state < SOCKSTATE_INITIALIZED) {
  351. pj_sockaddr_cp(&local_addr, addr);
  352. has_pending_bind = PJ_TRUE;
  353. return PJ_SUCCESS;
  354. }
  355. PJ_ASSERT_RETURN(sock_state == SOCKSTATE_INITIALIZED, PJ_EINVALIDOP);
  356. if (sock_type != SOCKTYPE_DATAGRAM && sock_type != SOCKTYPE_LISTENER)
  357. return PJ_EINVALIDOP;
  358. if (has_pending_bind) {
  359. has_pending_bind = PJ_FALSE;
  360. if (!addr)
  361. addr = &local_addr;
  362. }
  363. /* If no bound address is set, just return */
  364. if (!pj_sockaddr_has_addr(addr) && !pj_sockaddr_get_port(addr))
  365. return PJ_SUCCESS;
  366. if (addr != &local_addr)
  367. pj_sockaddr_cp(&local_addr, addr);
  368. HRESULT err = 0;
  369. concurrency::create_task([this, addr, &err]() {
  370. HostName ^host;
  371. int port;
  372. sockaddr_to_hostname_port(addr, host, &port);
  373. if (pj_sockaddr_has_addr(addr)) {
  374. if (sock_type == SOCKTYPE_DATAGRAM)
  375. return datagram_sock->BindEndpointAsync(host, port.ToString());
  376. else
  377. return listener_sock->BindEndpointAsync(host, port.ToString());
  378. } else /* if (pj_sockaddr_get_port(addr) != 0) */ {
  379. if (sock_type == SOCKTYPE_DATAGRAM)
  380. return datagram_sock->BindServiceNameAsync(port.ToString());
  381. else
  382. return listener_sock->BindServiceNameAsync(port.ToString());
  383. }
  384. }).then([this, &err](concurrency::task<void> t)
  385. {
  386. try {
  387. if (!err)
  388. t.get();
  389. } catch (Exception^ e) {
  390. err = e->HResult;
  391. }
  392. }).get();
  393. return (err? PJ_RETURN_OS_ERROR(err) : PJ_SUCCESS);
  394. }
  395. pj_status_t PjUwpSocket::SendImp(const void *buf, pj_ssize_t *len)
  396. {
  397. if (has_pending_send)
  398. return PJ_RETURN_OS_ERROR(PJ_BLOCKING_ERROR_VAL);
  399. if (*len > (pj_ssize_t)send_buffer->Capacity)
  400. return PJ_ETOOBIG;
  401. CopyToIBuffer((unsigned char*)buf, *len, send_buffer);
  402. send_buffer->Length = *len;
  403. socket_writer->WriteBuffer(send_buffer);
  404. /* Blocking version */
  405. if (is_blocking) {
  406. pj_status_t status = PJ_SUCCESS;
  407. concurrency::cancellation_token_source cts;
  408. auto cts_token = cts.get_token();
  409. auto t = concurrency::create_task(socket_writer->StoreAsync(),
  410. cts_token);
  411. *len = cancel_after_timeout(t, cts, (unsigned int)WRITE_TIMEOUT).
  412. then([cts_token, &status](concurrency::task<unsigned int> t_)
  413. {
  414. int sent = 0;
  415. try {
  416. if (cts_token.is_canceled())
  417. status = PJ_ETIMEDOUT;
  418. else
  419. sent = t_.get();
  420. } catch (Exception^ e) {
  421. status = PJ_RETURN_OS_ERROR(e->HResult);
  422. }
  423. return sent;
  424. }).get();
  425. return status;
  426. }
  427. /* Non-blocking version */
  428. has_pending_send = PJ_TRUE;
  429. concurrency::create_task(socket_writer->StoreAsync()).
  430. then([this](concurrency::task<unsigned int> t_)
  431. {
  432. try {
  433. unsigned int l = t_.get();
  434. has_pending_send = PJ_FALSE;
  435. // invoke callback
  436. if (cb.on_write) {
  437. (*cb.on_write)(this, l);
  438. }
  439. } catch (...) {
  440. has_pending_send = PJ_FALSE;
  441. sock_state = SOCKSTATE_ERROR;
  442. DeinitSocket();
  443. // invoke callback
  444. if (cb.on_write) {
  445. (*cb.on_write)(this, -PJ_EUNKNOWN);
  446. }
  447. }
  448. });
  449. return PJ_SUCCESS;
  450. }
  451. pj_status_t PjUwpSocket::Send(const void *buf, pj_ssize_t *len)
  452. {
  453. if ((sock_type!=SOCKTYPE_STREAM && sock_type!=SOCKTYPE_DATAGRAM) ||
  454. (sock_state!=SOCKSTATE_CONNECTED))
  455. {
  456. return PJ_EINVALIDOP;
  457. }
  458. /* Sending for SOCKTYPE_DATAGRAM is implemented in pj_sock_sendto() */
  459. if (sock_type == SOCKTYPE_DATAGRAM) {
  460. return SendTo(buf, len, &remote_addr);
  461. }
  462. return SendImp(buf, len);
  463. }
  464. pj_status_t PjUwpSocket::SendTo(const void *buf, pj_ssize_t *len,
  465. const pj_sockaddr_t *to)
  466. {
  467. if (sock_type != SOCKTYPE_DATAGRAM || sock_state < SOCKSTATE_INITIALIZED
  468. || sock_state >= SOCKSTATE_DISCONNECTED)
  469. {
  470. return PJ_EINVALIDOP;
  471. }
  472. if (has_pending_send)
  473. return PJ_RETURN_OS_ERROR(PJ_BLOCKING_ERROR_VAL);
  474. if (*len > (pj_ssize_t)send_buffer->Capacity)
  475. return PJ_ETOOBIG;
  476. HostName ^hostname;
  477. int port;
  478. sockaddr_to_hostname_port(to, hostname, &port);
  479. concurrency::cancellation_token_source cts;
  480. auto cts_token = cts.get_token();
  481. auto t = concurrency::create_task(datagram_sock->GetOutputStreamAsync(
  482. hostname, port.ToString()), cts_token);
  483. pj_status_t status = PJ_SUCCESS;
  484. cancel_after_timeout(t, cts, (unsigned int)WRITE_TIMEOUT).
  485. then([this, cts_token, &status](concurrency::task<IOutputStream^> t_)
  486. {
  487. try {
  488. if (cts_token.is_canceled()) {
  489. status = PJ_ETIMEDOUT;
  490. } else {
  491. IOutputStream^ outstream = t_.get();
  492. socket_writer = ref new DataWriter(outstream);
  493. }
  494. } catch (Exception^ e) {
  495. status = PJ_RETURN_OS_ERROR(e->HResult);
  496. }
  497. }).get();
  498. if (status != PJ_SUCCESS)
  499. return status;
  500. status = SendImp(buf, len);
  501. if ((status == PJ_SUCCESS || status == PJ_EPENDING) &&
  502. sock_state < SOCKSTATE_CONNECTED)
  503. {
  504. sock_state = SOCKSTATE_CONNECTED;
  505. }
  506. return status;
  507. }
  508. int PjUwpSocket::ConsumeReadBuffer(void *buf, int max_len)
  509. {
  510. if (socket_reader->UnconsumedBufferLength == 0)
  511. return 0;
  512. int read_len = PJ_MIN((int)socket_reader->UnconsumedBufferLength,max_len);
  513. IBuffer^ buffer = socket_reader->ReadBuffer(read_len);
  514. read_len = buffer->Length;
  515. CopyFromIBuffer((unsigned char*)buf, read_len, buffer);
  516. return read_len;
  517. }
  518. pj_status_t PjUwpSocket::Recv(void *buf, pj_ssize_t *len)
  519. {
  520. /* Only for TCP, at least for now! */
  521. if (sock_type == SOCKTYPE_DATAGRAM)
  522. return PJ_ENOTSUP;
  523. if (sock_type != SOCKTYPE_STREAM || sock_state != SOCKSTATE_CONNECTED)
  524. return PJ_EINVALIDOP;
  525. if (has_pending_recv)
  526. return PJ_RETURN_OS_ERROR(PJ_BLOCKING_ERROR_VAL);
  527. /* First check if there is already some data in the read buffer */
  528. if (buf) {
  529. int avail_len = ConsumeReadBuffer(buf, *len);
  530. if (avail_len > 0) {
  531. *len = avail_len;
  532. return PJ_SUCCESS;
  533. }
  534. }
  535. /* Blocking version */
  536. if (is_blocking) {
  537. pj_status_t status = PJ_SUCCESS;
  538. concurrency::cancellation_token_source cts;
  539. auto cts_token = cts.get_token();
  540. auto t = concurrency::create_task(socket_reader->LoadAsync(*len),
  541. cts_token);
  542. *len = cancel_after_timeout(t, cts, READ_TIMEOUT)
  543. .then([this, len, buf, cts_token, &status]
  544. (concurrency::task<unsigned int> t_)
  545. {
  546. try {
  547. if (cts_token.is_canceled()) {
  548. status = PJ_ETIMEDOUT;
  549. return 0;
  550. }
  551. t_.get();
  552. } catch (Exception^) {
  553. status = PJ_ETIMEDOUT;
  554. return 0;
  555. }
  556. *len = ConsumeReadBuffer(buf, *len);
  557. return (int)*len;
  558. }).get();
  559. return status;
  560. }
  561. /* Non-blocking version */
  562. concurrency::cancellation_token_source cts;
  563. auto cts_token = cts.get_token();
  564. has_pending_recv = PJ_TRUE;
  565. concurrency::create_task(socket_reader->LoadAsync(*len), cts_token)
  566. .then([this, cts_token](concurrency::task<unsigned int> t_)
  567. {
  568. try {
  569. if (cts_token.is_canceled()) {
  570. has_pending_recv = PJ_FALSE;
  571. // invoke callback
  572. if (cb.on_read) {
  573. (*cb.on_read)(this, -PJ_EUNKNOWN);
  574. }
  575. return;
  576. }
  577. t_.get();
  578. has_pending_recv = PJ_FALSE;
  579. // invoke callback
  580. int read_len = socket_reader->UnconsumedBufferLength;
  581. if (read_len > 0 && cb.on_read) {
  582. (*cb.on_read)(this, read_len);
  583. }
  584. } catch (...) {
  585. has_pending_recv = PJ_FALSE;
  586. // invoke callback
  587. if (cb.on_read) {
  588. (*cb.on_read)(this, -PJ_EUNKNOWN);
  589. }
  590. }
  591. });
  592. return PJ_RETURN_OS_ERROR(PJ_BLOCKING_ERROR_VAL);
  593. }
  594. pj_status_t PjUwpSocket::RecvFrom(void *buf, pj_ssize_t *len,
  595. pj_sockaddr_t *from)
  596. {
  597. if (sock_type != SOCKTYPE_DATAGRAM || sock_state < SOCKSTATE_INITIALIZED
  598. || sock_state >= SOCKSTATE_DISCONNECTED)
  599. {
  600. return PJ_EINVALIDOP;
  601. }
  602. /* Start receive, if not yet */
  603. if (dgram_recv_helper == nullptr) {
  604. dgram_recv_helper = ref new PjUwpSocketDatagramRecvHelper(this);
  605. }
  606. /* Try to read any available data first */
  607. if (buf || is_blocking) {
  608. pj_status_t status;
  609. status = dgram_recv_helper->ReadDataIfAvailable(buf, len, from);
  610. if (status != PJ_ENOTFOUND)
  611. return status;
  612. }
  613. /* Blocking version */
  614. if (is_blocking) {
  615. int max_loop = 0;
  616. pj_status_t status = PJ_ENOTFOUND;
  617. while (status == PJ_ENOTFOUND && sock_state <= SOCKSTATE_CONNECTED)
  618. {
  619. status = dgram_recv_helper->ReadDataIfAvailable(buf, len, from);
  620. if (status != PJ_SUCCESS)
  621. pj_thread_sleep(100);
  622. if (++max_loop > 10)
  623. return PJ_ETIMEDOUT;
  624. }
  625. return status;
  626. }
  627. /* For non-blocking version, just return PJ_EPENDING */
  628. return PJ_RETURN_OS_ERROR(PJ_BLOCKING_ERROR_VAL);
  629. }
  630. pj_status_t PjUwpSocket::Connect(const pj_sockaddr_t *addr)
  631. {
  632. pj_status_t status;
  633. PJ_ASSERT_RETURN((sock_type == SOCKTYPE_UNKNOWN && sock_state == SOCKSTATE_NULL) ||
  634. (sock_type == SOCKTYPE_DATAGRAM && sock_state == SOCKSTATE_INITIALIZED),
  635. PJ_EINVALIDOP);
  636. if (sock_type == SOCKTYPE_UNKNOWN) {
  637. InitSocket(SOCKTYPE_STREAM);
  638. // No need to check pending bind, no bind for TCP client socket
  639. }
  640. pj_sockaddr_cp(&remote_addr, addr);
  641. auto t = concurrency::create_task([this, addr]()
  642. {
  643. HostName ^hostname;
  644. int port;
  645. sockaddr_to_hostname_port(&remote_addr, hostname, &port);
  646. if (sock_type == SOCKTYPE_STREAM)
  647. return stream_sock->ConnectAsync(hostname, port.ToString(),
  648. SocketProtectionLevel::PlainSocket);
  649. else
  650. return datagram_sock->ConnectAsync(hostname, port.ToString());
  651. }).then([=](concurrency::task<void> t_)
  652. {
  653. try {
  654. t_.get();
  655. sock_state = SOCKSTATE_CONNECTED;
  656. // Update local & remote address
  657. HostName^ local_address;
  658. String^ local_port;
  659. if (sock_type == SOCKTYPE_STREAM) {
  660. local_address = stream_sock->Information->LocalAddress;
  661. local_port = stream_sock->Information->LocalPort;
  662. socket_reader = ref new DataReader(stream_sock->InputStream);
  663. socket_writer = ref new DataWriter(stream_sock->OutputStream);
  664. socket_reader->InputStreamOptions = InputStreamOptions::Partial;
  665. } else {
  666. local_address = datagram_sock->Information->LocalAddress;
  667. local_port = datagram_sock->Information->LocalPort;
  668. }
  669. if (local_address && local_port) {
  670. wstr_addr_to_sockaddr(local_address->CanonicalName->Data(),
  671. local_port->Data(),
  672. &local_addr);
  673. }
  674. if (!is_blocking && cb.on_connect) {
  675. (*cb.on_connect)(this, PJ_SUCCESS);
  676. }
  677. return (pj_status_t)PJ_SUCCESS;
  678. } catch (Exception^ ex) {
  679. SocketErrorStatus status = SocketError::GetStatus(ex->HResult);
  680. switch (status)
  681. {
  682. case SocketErrorStatus::UnreachableHost:
  683. break;
  684. case SocketErrorStatus::ConnectionTimedOut:
  685. break;
  686. case SocketErrorStatus::ConnectionRefused:
  687. break;
  688. default:
  689. break;
  690. }
  691. if (!is_blocking && cb.on_connect) {
  692. (*cb.on_connect)(this, PJ_EUNKNOWN);
  693. }
  694. return (pj_status_t)PJ_EUNKNOWN;
  695. }
  696. });
  697. if (!is_blocking)
  698. return PJ_RETURN_OS_ERROR(PJ_BLOCKING_CONNECT_ERROR_VAL);
  699. try {
  700. status = t.get();
  701. } catch (Exception^) {
  702. return PJ_EUNKNOWN;
  703. }
  704. return status;
  705. }
  706. pj_status_t PjUwpSocket::Listen()
  707. {
  708. PJ_ASSERT_RETURN((sock_type == SOCKTYPE_UNKNOWN) ||
  709. (sock_type == SOCKTYPE_LISTENER &&
  710. sock_state == SOCKSTATE_INITIALIZED),
  711. PJ_EINVALIDOP);
  712. if (sock_type == SOCKTYPE_UNKNOWN)
  713. InitSocket(SOCKTYPE_LISTENER);
  714. if (has_pending_bind)
  715. Bind();
  716. /* Start listen */
  717. if (listener_helper == nullptr) {
  718. listener_helper = ref new PjUwpSocketListenerHelper(this);
  719. }
  720. return PJ_SUCCESS;
  721. }
  722. pj_status_t PjUwpSocket::Accept(PjUwpSocket **new_sock)
  723. {
  724. if (sock_type != SOCKTYPE_LISTENER || sock_state != SOCKSTATE_INITIALIZED)
  725. return PJ_EINVALIDOP;
  726. StreamSocket^ accepted_sock;
  727. pj_status_t status = listener_helper->GetAcceptedSocket(accepted_sock);
  728. if (status == PJ_ENOTFOUND)
  729. return PJ_RETURN_OS_ERROR(PJ_BLOCKING_ERROR_VAL);
  730. if (status != PJ_SUCCESS)
  731. return status;
  732. *new_sock = CreateAcceptSocket(accepted_sock);
  733. return PJ_SUCCESS;
  734. }
  735. /////////////////////////////////////////////////////////////////////////////
  736. //
  737. // PJLIB's sock.h implementation
  738. //
  739. /*
  740. * Convert 16-bit value from network byte order to host byte order.
  741. */
  742. PJ_DEF(pj_uint16_t) pj_ntohs(pj_uint16_t netshort)
  743. {
  744. return ntohs(netshort);
  745. }
  746. /*
  747. * Convert 16-bit value from host byte order to network byte order.
  748. */
  749. PJ_DEF(pj_uint16_t) pj_htons(pj_uint16_t hostshort)
  750. {
  751. return htons(hostshort);
  752. }
  753. /*
  754. * Convert 32-bit value from network byte order to host byte order.
  755. */
  756. PJ_DEF(pj_uint32_t) pj_ntohl(pj_uint32_t netlong)
  757. {
  758. return ntohl(netlong);
  759. }
  760. /*
  761. * Convert 32-bit value from host byte order to network byte order.
  762. */
  763. PJ_DEF(pj_uint32_t) pj_htonl(pj_uint32_t hostlong)
  764. {
  765. return htonl(hostlong);
  766. }
  767. /*
  768. * Convert an Internet host address given in network byte order
  769. * to string in standard numbers and dots notation.
  770. */
  771. PJ_DEF(char*) pj_inet_ntoa(pj_in_addr inaddr)
  772. {
  773. return inet_ntoa(*(struct in_addr*)&inaddr);
  774. }
  775. /*
  776. * This function converts the Internet host address cp from the standard
  777. * numbers-and-dots notation into binary data and stores it in the structure
  778. * that inp points to.
  779. */
  780. PJ_DEF(int) pj_inet_aton(const pj_str_t *cp, pj_in_addr *inp)
  781. {
  782. char tempaddr[PJ_INET_ADDRSTRLEN];
  783. /* Initialize output with PJ_INADDR_NONE.
  784. * Some apps relies on this instead of the return value
  785. * (and anyway the return value is quite confusing!)
  786. */
  787. inp->s_addr = PJ_INADDR_NONE;
  788. /* Caution:
  789. * this function might be called with cp->slen >= 16
  790. * (i.e. when called with hostname to check if it's an IP addr).
  791. */
  792. PJ_ASSERT_RETURN(cp && cp->slen && inp, 0);
  793. if (cp->slen >= PJ_INET_ADDRSTRLEN) {
  794. return 0;
  795. }
  796. pj_memcpy(tempaddr, cp->ptr, cp->slen);
  797. tempaddr[cp->slen] = '\0';
  798. #if defined(PJ_SOCK_HAS_INET_ATON) && PJ_SOCK_HAS_INET_ATON != 0
  799. return inet_aton(tempaddr, (struct in_addr*)inp);
  800. #else
  801. inp->s_addr = inet_addr(tempaddr);
  802. return inp->s_addr == PJ_INADDR_NONE ? 0 : 1;
  803. #endif
  804. }
  805. /*
  806. * Convert text to IPv4/IPv6 address.
  807. */
  808. PJ_DEF(pj_status_t) pj_inet_pton(int af, const pj_str_t *src, void *dst)
  809. {
  810. char tempaddr[PJ_INET6_ADDRSTRLEN];
  811. PJ_ASSERT_RETURN(af == PJ_AF_INET || af == PJ_AF_INET6, PJ_EAFNOTSUP);
  812. PJ_ASSERT_RETURN(src && src->slen && dst, PJ_EINVAL);
  813. /* Initialize output with PJ_IN_ADDR_NONE for IPv4 (to be
  814. * compatible with pj_inet_aton()
  815. */
  816. if (af == PJ_AF_INET) {
  817. ((pj_in_addr*)dst)->s_addr = PJ_INADDR_NONE;
  818. }
  819. /* Caution:
  820. * this function might be called with cp->slen >= 46
  821. * (i.e. when called with hostname to check if it's an IP addr).
  822. */
  823. if (src->slen >= PJ_INET6_ADDRSTRLEN) {
  824. return PJ_ENAMETOOLONG;
  825. }
  826. pj_memcpy(tempaddr, src->ptr, src->slen);
  827. tempaddr[src->slen] = '\0';
  828. #if defined(PJ_SOCK_HAS_INET_PTON) && PJ_SOCK_HAS_INET_PTON != 0
  829. /*
  830. * Implementation using inet_pton()
  831. */
  832. if (inet_pton(af, tempaddr, dst) != 1) {
  833. pj_status_t status = pj_get_netos_error();
  834. if (status == PJ_SUCCESS)
  835. status = PJ_EUNKNOWN;
  836. return status;
  837. }
  838. return PJ_SUCCESS;
  839. #elif defined(PJ_WIN32) || defined(PJ_WIN64) || defined(PJ_WIN32_WINCE)
  840. /*
  841. * Implementation on Windows, using WSAStringToAddress().
  842. * Should also work on Unicode systems.
  843. */
  844. {
  845. PJ_DECL_UNICODE_TEMP_BUF(wtempaddr, PJ_INET6_ADDRSTRLEN)
  846. pj_sockaddr sock_addr;
  847. int addr_len = sizeof(sock_addr);
  848. int rc;
  849. sock_addr.addr.sa_family = (pj_uint16_t)af;
  850. rc = WSAStringToAddress(
  851. PJ_STRING_TO_NATIVE(tempaddr, wtempaddr, sizeof(wtempaddr)),
  852. af, NULL, (LPSOCKADDR)&sock_addr, &addr_len);
  853. if (rc != 0) {
  854. /* If you get rc 130022 Invalid argument (WSAEINVAL) with IPv6,
  855. * check that you have IPv6 enabled (install it in the network
  856. * adapter).
  857. */
  858. pj_status_t status = pj_get_netos_error();
  859. if (status == PJ_SUCCESS)
  860. status = PJ_EUNKNOWN;
  861. return status;
  862. }
  863. if (sock_addr.addr.sa_family == PJ_AF_INET) {
  864. pj_memcpy(dst, &sock_addr.ipv4.sin_addr, 4);
  865. return PJ_SUCCESS;
  866. }
  867. else if (sock_addr.addr.sa_family == PJ_AF_INET6) {
  868. pj_memcpy(dst, &sock_addr.ipv6.sin6_addr, 16);
  869. return PJ_SUCCESS;
  870. }
  871. else {
  872. pj_assert(!"Shouldn't happen");
  873. return PJ_EBUG;
  874. }
  875. }
  876. #elif !defined(PJ_HAS_IPV6) || PJ_HAS_IPV6==0
  877. /* IPv6 support is disabled, just return error without raising assertion */
  878. return PJ_EIPV6NOTSUP;
  879. #else
  880. pj_assert(!"Not supported");
  881. return PJ_EIPV6NOTSUP;
  882. #endif
  883. }
  884. /*
  885. * Convert IPv4/IPv6 address to text.
  886. */
  887. PJ_DEF(pj_status_t) pj_inet_ntop(int af, const void *src,
  888. char *dst, int size)
  889. {
  890. PJ_ASSERT_RETURN(src && dst && size, PJ_EINVAL);
  891. PJ_ASSERT_RETURN(af == PJ_AF_INET || af == PJ_AF_INET6, PJ_EAFNOTSUP);
  892. *dst = '\0';
  893. #if defined(PJ_SOCK_HAS_INET_NTOP) && PJ_SOCK_HAS_INET_NTOP != 0
  894. /*
  895. * Implementation using inet_ntop()
  896. */
  897. if (inet_ntop(af, src, dst, size) == NULL) {
  898. pj_status_t status = pj_get_netos_error();
  899. if (status == PJ_SUCCESS)
  900. status = PJ_EUNKNOWN;
  901. return status;
  902. }
  903. return PJ_SUCCESS;
  904. #elif defined(PJ_WIN32) || defined(PJ_WIN64) || defined(PJ_WIN32_WINCE)
  905. /*
  906. * Implementation on Windows, using WSAAddressToString().
  907. * Should also work on Unicode systems.
  908. */
  909. {
  910. PJ_DECL_UNICODE_TEMP_BUF(wtempaddr, PJ_INET6_ADDRSTRLEN)
  911. pj_sockaddr sock_addr;
  912. DWORD addr_len, addr_str_len;
  913. int rc;
  914. pj_bzero(&sock_addr, sizeof(sock_addr));
  915. sock_addr.addr.sa_family = (pj_uint16_t)af;
  916. if (af == PJ_AF_INET) {
  917. if (size < PJ_INET_ADDRSTRLEN)
  918. return PJ_ETOOSMALL;
  919. pj_memcpy(&sock_addr.ipv4.sin_addr, src, 4);
  920. addr_len = sizeof(pj_sockaddr_in);
  921. addr_str_len = PJ_INET_ADDRSTRLEN;
  922. }
  923. else if (af == PJ_AF_INET6) {
  924. if (size < PJ_INET6_ADDRSTRLEN)
  925. return PJ_ETOOSMALL;
  926. pj_memcpy(&sock_addr.ipv6.sin6_addr, src, 16);
  927. addr_len = sizeof(pj_sockaddr_in6);
  928. addr_str_len = PJ_INET6_ADDRSTRLEN;
  929. }
  930. else {
  931. pj_assert(!"Unsupported address family");
  932. return PJ_EAFNOTSUP;
  933. }
  934. #if PJ_NATIVE_STRING_IS_UNICODE
  935. rc = WSAAddressToString((LPSOCKADDR)&sock_addr, addr_len,
  936. NULL, wtempaddr, &addr_str_len);
  937. if (rc == 0) {
  938. pj_unicode_to_ansi(wtempaddr, wcslen(wtempaddr), dst, size);
  939. }
  940. #else
  941. rc = WSAAddressToString((LPSOCKADDR)&sock_addr, addr_len,
  942. NULL, dst, &addr_str_len);
  943. #endif
  944. if (rc != 0) {
  945. pj_status_t status = pj_get_netos_error();
  946. if (status == PJ_SUCCESS)
  947. status = PJ_EUNKNOWN;
  948. return status;
  949. }
  950. return PJ_SUCCESS;
  951. }
  952. #elif !defined(PJ_HAS_IPV6) || PJ_HAS_IPV6==0
  953. /* IPv6 support is disabled, just return error without raising assertion */
  954. return PJ_EIPV6NOTSUP;
  955. #else
  956. pj_assert(!"Not supported");
  957. return PJ_EIPV6NOTSUP;
  958. #endif
  959. }
  960. /*
  961. * Get hostname.
  962. */
  963. PJ_DEF(const pj_str_t*) pj_gethostname(void)
  964. {
  965. static char buf[PJ_MAX_HOSTNAME];
  966. static pj_str_t hostname;
  967. PJ_CHECK_STACK();
  968. if (hostname.ptr == NULL) {
  969. hostname.ptr = buf;
  970. if (gethostname(buf, sizeof(buf)) != 0) {
  971. hostname.ptr[0] = '\0';
  972. hostname.slen = 0;
  973. }
  974. else {
  975. hostname.slen = strlen(buf);
  976. }
  977. }
  978. return &hostname;
  979. }
  980. /*
  981. * Create new socket/endpoint for communication and returns a descriptor.
  982. */
  983. PJ_DEF(pj_status_t) pj_sock_socket(int af,
  984. int type,
  985. int proto,
  986. pj_sock_t *p_sock)
  987. {
  988. PJ_CHECK_STACK();
  989. PJ_ASSERT_RETURN(p_sock!=NULL, PJ_EINVAL);
  990. PjUwpSocket *s = new PjUwpSocket(af, type, proto);
  991. /* Init UDP socket here */
  992. if (type == pj_SOCK_DGRAM()) {
  993. s->InitSocket(SOCKTYPE_DATAGRAM);
  994. }
  995. *p_sock = (pj_sock_t)s;
  996. return PJ_SUCCESS;
  997. }
  998. /*
  999. * Bind socket.
  1000. */
  1001. PJ_DEF(pj_status_t) pj_sock_bind( pj_sock_t sock,
  1002. const pj_sockaddr_t *addr,
  1003. int len)
  1004. {
  1005. PJ_CHECK_STACK();
  1006. PJ_ASSERT_RETURN(sock, PJ_EINVAL);
  1007. PJ_ASSERT_RETURN(addr && len>=(int)sizeof(pj_sockaddr_in), PJ_EINVAL);
  1008. PjUwpSocket *s = (PjUwpSocket*)sock;
  1009. return s->Bind(addr);
  1010. }
  1011. /*
  1012. * Bind socket.
  1013. */
  1014. PJ_DEF(pj_status_t) pj_sock_bind_in( pj_sock_t sock,
  1015. pj_uint32_t addr32,
  1016. pj_uint16_t port)
  1017. {
  1018. pj_sockaddr_in addr;
  1019. PJ_CHECK_STACK();
  1020. pj_bzero(&addr, sizeof(addr));
  1021. addr.sin_family = PJ_AF_INET;
  1022. addr.sin_addr.s_addr = pj_htonl(addr32);
  1023. addr.sin_port = pj_htons(port);
  1024. return pj_sock_bind(sock, &addr, sizeof(pj_sockaddr_in));
  1025. }
  1026. /*
  1027. * Close socket.
  1028. */
  1029. PJ_DEF(pj_status_t) pj_sock_close(pj_sock_t sock)
  1030. {
  1031. PJ_CHECK_STACK();
  1032. PJ_ASSERT_RETURN(sock, PJ_EINVAL);
  1033. if (sock == PJ_INVALID_SOCKET)
  1034. return PJ_SUCCESS;
  1035. PjUwpSocket *s = (PjUwpSocket*)sock;
  1036. delete s;
  1037. return PJ_SUCCESS;
  1038. }
  1039. /*
  1040. * Get remote's name.
  1041. */
  1042. PJ_DEF(pj_status_t) pj_sock_getpeername( pj_sock_t sock,
  1043. pj_sockaddr_t *addr,
  1044. int *namelen)
  1045. {
  1046. PJ_CHECK_STACK();
  1047. PJ_ASSERT_RETURN(sock && addr && namelen &&
  1048. *namelen>=(int)sizeof(pj_sockaddr_in), PJ_EINVAL);
  1049. PjUwpSocket *s = (PjUwpSocket*)sock;
  1050. pj_sockaddr_cp(addr, s->GetRemoteAddr());
  1051. *namelen = pj_sockaddr_get_len(addr);
  1052. return PJ_SUCCESS;
  1053. }
  1054. /*
  1055. * Get socket name.
  1056. */
  1057. PJ_DEF(pj_status_t) pj_sock_getsockname( pj_sock_t sock,
  1058. pj_sockaddr_t *addr,
  1059. int *namelen)
  1060. {
  1061. PJ_CHECK_STACK();
  1062. PJ_ASSERT_RETURN(sock && addr && namelen &&
  1063. *namelen>=(int)sizeof(pj_sockaddr_in), PJ_EINVAL);
  1064. PjUwpSocket *s = (PjUwpSocket*)sock;
  1065. pj_sockaddr_cp(addr, s->GetLocalAddr());
  1066. *namelen = pj_sockaddr_get_len(addr);
  1067. return PJ_SUCCESS;
  1068. }
  1069. /*
  1070. * Send data
  1071. */
  1072. PJ_DEF(pj_status_t) pj_sock_send(pj_sock_t sock,
  1073. const void *buf,
  1074. pj_ssize_t *len,
  1075. unsigned flags)
  1076. {
  1077. PJ_CHECK_STACK();
  1078. PJ_ASSERT_RETURN(sock && buf && len, PJ_EINVAL);
  1079. PJ_UNUSED_ARG(flags);
  1080. PjUwpSocket *s = (PjUwpSocket*)sock;
  1081. return s->Send(buf, len);
  1082. }
  1083. /*
  1084. * Send data.
  1085. */
  1086. PJ_DEF(pj_status_t) pj_sock_sendto(pj_sock_t sock,
  1087. const void *buf,
  1088. pj_ssize_t *len,
  1089. unsigned flags,
  1090. const pj_sockaddr_t *to,
  1091. int tolen)
  1092. {
  1093. PJ_CHECK_STACK();
  1094. PJ_ASSERT_RETURN(sock && buf && len, PJ_EINVAL);
  1095. PJ_UNUSED_ARG(flags);
  1096. PJ_UNUSED_ARG(tolen);
  1097. PjUwpSocket *s = (PjUwpSocket*)sock;
  1098. return s->SendTo(buf, len, to);
  1099. }
  1100. /*
  1101. * Receive data.
  1102. */
  1103. PJ_DEF(pj_status_t) pj_sock_recv(pj_sock_t sock,
  1104. void *buf,
  1105. pj_ssize_t *len,
  1106. unsigned flags)
  1107. {
  1108. PJ_CHECK_STACK();
  1109. PJ_ASSERT_RETURN(sock && len && *len > 0, PJ_EINVAL);
  1110. PJ_UNUSED_ARG(flags);
  1111. PjUwpSocket *s = (PjUwpSocket*)sock;
  1112. return s->Recv(buf, len);
  1113. }
  1114. /*
  1115. * Receive data.
  1116. */
  1117. PJ_DEF(pj_status_t) pj_sock_recvfrom(pj_sock_t sock,
  1118. void *buf,
  1119. pj_ssize_t *len,
  1120. unsigned flags,
  1121. pj_sockaddr_t *from,
  1122. int *fromlen)
  1123. {
  1124. PJ_CHECK_STACK();
  1125. PJ_ASSERT_RETURN(sock && buf && len && from && fromlen, PJ_EINVAL);
  1126. PJ_ASSERT_RETURN(*len > 0, PJ_EINVAL);
  1127. PJ_ASSERT_RETURN(*fromlen >= (int)sizeof(pj_sockaddr_in), PJ_EINVAL);
  1128. PJ_UNUSED_ARG(flags);
  1129. PjUwpSocket *s = (PjUwpSocket*)sock;
  1130. pj_status_t status = s->RecvFrom(buf, len, from);
  1131. if (status == PJ_SUCCESS)
  1132. *fromlen = pj_sockaddr_get_len(from);
  1133. return status;
  1134. }
  1135. /*
  1136. * Get socket option.
  1137. */
  1138. PJ_DEF(pj_status_t) pj_sock_getsockopt( pj_sock_t sock,
  1139. pj_uint16_t level,
  1140. pj_uint16_t optname,
  1141. void *optval,
  1142. int *optlen)
  1143. {
  1144. // Not supported for now.
  1145. PJ_UNUSED_ARG(sock);
  1146. PJ_UNUSED_ARG(level);
  1147. PJ_UNUSED_ARG(optname);
  1148. PJ_UNUSED_ARG(optval);
  1149. PJ_UNUSED_ARG(optlen);
  1150. return PJ_ENOTSUP;
  1151. }
  1152. /*
  1153. * Set socket option.
  1154. */
  1155. PJ_DEF(pj_status_t) pj_sock_setsockopt( pj_sock_t sock,
  1156. pj_uint16_t level,
  1157. pj_uint16_t optname,
  1158. const void *optval,
  1159. int optlen)
  1160. {
  1161. // Not supported for now.
  1162. PJ_UNUSED_ARG(sock);
  1163. PJ_UNUSED_ARG(level);
  1164. PJ_UNUSED_ARG(optname);
  1165. PJ_UNUSED_ARG(optval);
  1166. PJ_UNUSED_ARG(optlen);
  1167. return PJ_ENOTSUP;
  1168. }
  1169. /*
  1170. * Set socket option.
  1171. */
  1172. PJ_DEF(pj_status_t) pj_sock_setsockopt_params( pj_sock_t sockfd,
  1173. const pj_sockopt_params *params)
  1174. {
  1175. unsigned int i = 0;
  1176. pj_status_t retval = PJ_SUCCESS;
  1177. PJ_CHECK_STACK();
  1178. PJ_ASSERT_RETURN(params, PJ_EINVAL);
  1179. for (;i<params->cnt && i<PJ_MAX_SOCKOPT_PARAMS;++i) {
  1180. pj_status_t status = pj_sock_setsockopt(sockfd,
  1181. (pj_uint16_t)params->options[i].level,
  1182. (pj_uint16_t)params->options[i].optname,
  1183. params->options[i].optval,
  1184. params->options[i].optlen);
  1185. if (status != PJ_SUCCESS) {
  1186. retval = status;
  1187. PJ_PERROR(4,(THIS_FILE, status,
  1188. "Warning: error applying sock opt %d",
  1189. params->options[i].optname));
  1190. }
  1191. }
  1192. return retval;
  1193. }
  1194. /*
  1195. * Connect socket.
  1196. */
  1197. PJ_DEF(pj_status_t) pj_sock_connect( pj_sock_t sock,
  1198. const pj_sockaddr_t *addr,
  1199. int namelen)
  1200. {
  1201. PJ_CHECK_STACK();
  1202. PJ_ASSERT_RETURN(sock && addr, PJ_EINVAL);
  1203. PJ_UNUSED_ARG(namelen);
  1204. PjUwpSocket *s = (PjUwpSocket*)sock;
  1205. return s->Connect(addr);
  1206. }
  1207. /*
  1208. * Shutdown socket.
  1209. */
  1210. #if PJ_HAS_TCP
  1211. PJ_DEF(pj_status_t) pj_sock_shutdown( pj_sock_t sock,
  1212. int how)
  1213. {
  1214. PJ_CHECK_STACK();
  1215. PJ_ASSERT_RETURN(sock, PJ_EINVAL);
  1216. PJ_UNUSED_ARG(how);
  1217. return pj_sock_close(sock);
  1218. }
  1219. /*
  1220. * Start listening to incoming connections.
  1221. */
  1222. PJ_DEF(pj_status_t) pj_sock_listen( pj_sock_t sock,
  1223. int backlog)
  1224. {
  1225. PJ_CHECK_STACK();
  1226. PJ_UNUSED_ARG(backlog);
  1227. PJ_ASSERT_RETURN(sock, PJ_EINVAL);
  1228. PjUwpSocket *s = (PjUwpSocket*)sock;
  1229. return s->Listen();
  1230. }
  1231. /*
  1232. * Accept incoming connections
  1233. */
  1234. PJ_DEF(pj_status_t) pj_sock_accept( pj_sock_t serverfd,
  1235. pj_sock_t *newsock,
  1236. pj_sockaddr_t *addr,
  1237. int *addrlen)
  1238. {
  1239. pj_status_t status;
  1240. PJ_CHECK_STACK();
  1241. PJ_ASSERT_RETURN(serverfd && newsock, PJ_EINVAL);
  1242. PjUwpSocket *s = (PjUwpSocket*)serverfd;
  1243. PjUwpSocket *new_uwp_sock;
  1244. status = s->Accept(&new_uwp_sock);
  1245. if (status != PJ_SUCCESS)
  1246. return status;
  1247. if (newsock == NULL)
  1248. return PJ_ENOTFOUND;
  1249. *newsock = (pj_sock_t)new_uwp_sock;
  1250. if (addr)
  1251. pj_sockaddr_cp(addr, new_uwp_sock->GetRemoteAddr());
  1252. if (addrlen)
  1253. *addrlen = pj_sockaddr_get_len(addr);
  1254. return PJ_SUCCESS;
  1255. }
  1256. #endif /* PJ_HAS_TCP */