summaryrefslogtreecommitdiff
path: root/network/trans/WFPSampler/lib/HelperFunctions_WinSock.cpp
blob: 2ff097377b5adf37a095b68ce6361239dbccf48b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
////////////////////////////////////////////////////////////////////////////////////////////////////
//
//   Copyright (c) 2012 Microsoft Corporation. All Rights Reserved.
//
//   Module Name:
//      HelperFunctions_WinSock.cpp
//
//   Abstract:
//      This module contains functions for assisting in operations pertaining to Windows Sockets.
//
//   Author:
//      Dusty Harper      (DHarper)
//
//   Revision History:
//
//      [ Month ][Day] [Year] - [Revision]-[ Comments ]
//      May       01,   2010  -     1.0   -  Creation
//
////////////////////////////////////////////////////////////////////////////////////////////////////

#include "HelperFunctions_Include.h" /// .

/**
 @helper_function="HlprWinSockCleanup"
 
   Purpose:  Terminates use of the Winsock DLL for the process's use.                           <br>
                                                                                                <br>
   Notes:                                                                                       <br>
                                                                                                <br>
   MSDN_Ref: HTTP://MSDN.Microsoft.com/En-US/Library/Windows/Desktop/MS741549.aspx              <br>
*/
_Success_(return == NO_ERROR)
UINT32 HlprWinSockCleanup()
{
   UINT32 status = NO_ERROR;

   status = WSACleanup();
   if(status != NO_ERROR)
   {
      status = WSAGetLastError();

      HlprLogError(L"HlprWinSockCleanup : WSACleanup() [status: %#x]",
                   status);
   }

   return status;
}

/**
 @helper_function="HlprWinSockInitialize"
 
   Purpose:  Initializes use of the Winsock DLL for the process's use.                          <br>
                                                                                                <br>
   Notes:                                                                                       <br>
                                                                                                <br>
   MSDN_Ref: HTTP://MSDN.Microsoft.com/En-US/Library/Windows/Desktop/MS742213.aspx              <br>
*/
_Success_(return == NO_ERROR)
UINT32 HlprWinSockInitialize()
{
   UINT32  status           = NO_ERROR;
   UINT16  versionRequested = MAKEWORD(2,
                                       2);
   WSADATA wsaData          = {0};

   status = WSAStartup(versionRequested,
                       &wsaData);
   if(status != NO_ERROR)
      HlprLogError(L"HlprWinSockInitialize : WSAStartup() [status: %#x]",
                   status);

   return status;
}

/**
 @helper_function="HlprWinSockDestroyWSAEvent"
 
   Purpose:  Free a WSAEvent.                                                                   <br>
                                                                                                <br>
   Notes:                                                                                       <br>
                                                                                                <br>
   MSDN_Ref: HTTP://MSDN.Microsoft.com/En-US/Library/Windows/Desktop/MS741551.aspx              <br>
*/
_Success_(return == NO_ERROR)
UINT32 HlprWinSockDestroyWSAEvent(_Inout_ WSAEVENT* pWSAEvent)
{
   ASSERT(pWSAEvent);

   UINT32 status = NO_ERROR;

   if(!WSACloseEvent(*pWSAEvent))
   {
      status = WSAGetLastError();

      HlprLogError(L"HlprWinSockDestroyWSAEvent : WSACloseEvent() [status: %#x]",
                   status);
   }
   else
      *pWSAEvent = WSA_INVALID_EVENT;

   return status;
}

/**
 @helper_function="HlprWinSockSetWSAEvent"
 
   Purpose:  Set a WSAEvent to signaled.                                                        <br>
                                                                                                <br>
   Notes:                                                                                       <br>
                                                                                                <br>
   MSDN_Ref: HTTP://MSDN.Microsoft.com/En-US/Library/Windows/Desktop/MS742208.aspx              <br>
*/
_Success_(return == NO_ERROR)
UINT32 HlprWinSockSetWSAEvent(_In_ WSAEVENT wsaEvent)
{
   UINT32 status = NO_ERROR;

   if(!WSASetEvent(wsaEvent))
   {
      status = WSAGetLastError();

      HlprLogError(L"HlprWinSockSetWSAEvent : WSASetEvent() [status: %#x]",
                   status);
   }

   return status;
}

/**
 @helper_function="HlprWinSockCreateWSAEvent"
 
   Purpose:  Create a WSAEvent.                                                                 <br>
                                                                                                <br>
   Notes:                                                                                       <br>
                                                                                                <br>
   MSDN_Ref: HTTP://MSDN.Microsoft.com/En-US/Library/Windows/Desktop/MS741561.aspx              <br>
*/
_Success_(return == NO_ERROR)
UINT32 HlprWinSockCreateWSAEvent(_Inout_ WSAEVENT* pWSAEvent)
{
   ASSERT(pWSAEvent);

   UINT32 status = NO_ERROR;

   *pWSAEvent = WSACreateEvent();
   if(*pWSAEvent == WSA_INVALID_EVENT)
   {
      status = WSAGetLastError();

      HlprLogError(L"HlprWinSockCreateWSAEvent : WSACreateEvent() [status: %#x]",
                   status);
   }

   return status;
}

/**
 @helper_function="HlprWinSockDestroySocket"
 
   Purpose:  Destroy a socket gracefully.                                                       <br>
                                                                                                <br>
   Notes:                                                                                       <br>
                                                                                                <br>
   MSDN_Ref: HTTP://MSDN.Microsoft.com/En-US/Library/Windows/Desktop/MS740481.aspx              <br>
             HTTP://MSDN.Microsoft.com/En-US/Library/Windows/Desktop/MS737582.aspx              <br>
*/
_Success_(return == NO_ERROR)
UINT32 HlprWinSockDestroySocket(_Inout_ SOCKET* pSocket)
{
   ASSERT(pSocket);

   UINT32 status = NO_ERROR;

   if(*pSocket != INVALID_SOCKET)
   {
      status = shutdown(*pSocket,
                        SD_BOTH);
      if(status != NO_ERROR)
      {
         status = WSAGetLastError();

         HlprLogError(L"HlprWinSockDestroySocket : shutdown() [status: %#x]",
                      status);

         HLPR_BAIL;
      }

      status = closesocket(*pSocket);
      if(status != NO_ERROR)
      {
         status = WSAGetLastError();

         HlprLogError(L"HlprWinSockDestroySocket : shutdown() [status: %#x]",
                      status);

         HLPR_BAIL;
      }

      *pSocket = INVALID_SOCKET;
   }

   HLPR_BAIL_LABEL:

   return status;
}

/**
 @helper_function="HlprWinSockCreateSocket"
 
   Purpose:  Create a new socket.                                                               <br>
                                                                                                <br>
   Notes:                                                                                       <br>
                                                                                                <br>
   MSDN_Ref: HTTP://MSDN.Microsoft.com/En-US/Library/Windows/Desktop/MS742212.aspx              <br>
*/
_Success_(return == NO_ERROR)
UINT32 HlprWinSockCreateSocket(_In_ SOCKADDR_STORAGE* pSockAddrStorage,
                               _In_ UINT8 protocol,
                               _Inout_ SOCKET* pSocket)
{
   ASSERT(pSockAddrStorage);
   ASSERT(pSocket);

   UINT32 status = NO_ERROR;
   UINT32 type   = SOCK_RAW;

   if(protocol == IPPROTO_TCP)
      type = SOCK_STREAM;
   else if(protocol == IPPROTO_UDP)
      type = SOCK_DGRAM;

   *pSocket = WSASocket(pSockAddrStorage->ss_family,
                        type,
                        protocol,
                        0,
                        0,
                        WSA_FLAG_OVERLAPPED);
   if(*pSocket == INVALID_SOCKET)
   {
      status = WSAGetLastError();

      HlprLogError(L"HlprWinSockCreateSocket : WSASocket() [status:%#x]",
                   status);
   }

   return status;
}

/**
 @helper_function="HlprWinSockSetAbortiveDisconnect"
 
   Purpose:  Set the linger socket option to FALSE.                                             <br>
                                                                                                <br>
   Notes:    This function needs to be called prior to HlprWinSockDestroySocket for stream 
             sockets that get a WSAECONNRESET.                                                  <br>
                                                                                                <br>
   MSDN_Ref: HTTP://MSDN.Microsoft.com/En-US/Library/Windows/Desktop/MS740476.aspx              <br>
*/
_Success_(return == NO_ERROR)
UINT32 HlprWinSockSetAbortiveDisconnect(_In_ SOCKET abortedSocket)
{
   ASSERT(abortedSocket != INVALID_SOCKET);

   UINT32 status = NO_ERROR;
   LINGER linger = {0};

   linger.l_onoff  = TRUE;
   linger.l_linger = 0;

   status = setsockopt(abortedSocket,
                       SOL_SOCKET,
                       SO_LINGER,
                       (char*)&linger,
                       sizeof(LINGER));
   if(status != NO_ERROR)
   {
      status = WSAGetLastError();

      HlprLogError(L"HlprWinSockSetAbortiveDisconnect : setsockopt() [status: %#x]",
                   status);
   }

   return status;
}

/**
 @helper_function="HlprWinSockSetSocketReceiveTimeout"
 
   Purpose:  Specify a timeout for blocking receive calls.                                      <br>
                                                                                                <br>
   Notes:    This function needs to be called prior to binding the socket.                      <br>
                                                                                                <br>
   MSDN_Ref: HTTP://MSDN.Microsoft.com/En-US/Library/Windows/Desktop/MS740476.aspx              <br>
*/
_Success_(return == NO_ERROR)
UINT32 HlprWinSockSetSocketReceiveTimeout(_In_ SOCKET receivingSocket,
                                          _In_ UINT32 timeout)         /* 5000 */
{
   ASSERT(receivingSocket != INVALID_SOCKET);

   UINT32 status = NO_ERROR;

   status = setsockopt(receivingSocket,
                       SOL_SOCKET,
                       SO_RCVTIMEO,
                       (char*)&timeout,
                       sizeof(UINT32));
   if(status != NO_ERROR)
   {
      status = WSAGetLastError();

      HlprLogError(L"HlprWinSockSetSocketReceiveTimeout : setsockopt() [status: %#x]",
                   status);
   }

   return status;
}

/**
 @helper_function="HlprWinSockSetSocketSendTimeout"
 
   Purpose:  Specify a timeout for blocking send calls.                                         <br>
                                                                                                <br>
   Notes:    This function needs to be called prior to binding the socket.                      <br>
                                                                                                <br>
   MSDN_Ref: HTTP://MSDN.Microsoft.com/En-US/Library/Windows/Desktop/MS740476.aspx              <br>
*/
_Success_(return == NO_ERROR)
UINT32 HlprWinSockSetSocketSendTimeout(_In_ SOCKET sendingSocket,
                                       _In_ UINT32 timeout)       /* 5000 */
{
   ASSERT(sendingSocket != INVALID_SOCKET);

   UINT32 status = NO_ERROR;

   status = setsockopt(sendingSocket,
                       SOL_SOCKET,
                       SO_SNDTIMEO,
                       (char*)&timeout,
                       sizeof(UINT32));
   if(status != NO_ERROR)
   {
      status = WSAGetLastError();

      HlprLogError(L"HlprWinSockSetSocketSendTimeout : setsockopt() [status: %#x]",
                   status);
   }

   return status;
}


/**
 @helper_function="HlprWinSockSetSocketNonBlocking"
 
   Purpose:  Enable non-blocking mode on the socket.                                            <br>
                                                                                                <br>
   Notes:    This function needs to be called prior to binding the socket.                      <br>
                                                                                                <br>
   MSDN_Ref: HTTP://MSDN.Microsoft.com/En-US/Library/Windows/Desktop/MS741621.aspx              <br>
*/
_Success_(return == NO_ERROR)
UINT32 HlprWinSockSetSocketNonBlocking(_In_ SOCKET unboundSocket)
{
   ASSERT(unboundSocket != INVALID_SOCKET);

   UINT32 status              = NO_ERROR;
   UINT32 isNonBlockingSocket = TRUE;
   UINT32 bytesReturned       = 0;

   status = WSAIoctl(unboundSocket,
                     FIONBIO,
                     &isNonBlockingSocket,
                     sizeof(UINT32),
                     0,
                     0,
                     (LPDWORD)&bytesReturned,
                     0,
                     0);
   if(status != NO_ERROR)
   {
      status = WSAGetLastError();

      HlprLogError(L"HlprWinSockSetSocketNonBlocking : WSAIoctl() [status: %#x]",
                   status);
   }

   return status;
}

/**
 @helper_function="HlprWinSockAcquirePortReservationForSocket"
 
   Purpose:  Request a runtime reservation for the provided ports.                              <br>
                                                                                                <br>
   Notes:                                                                                       <br>
                                                                                                <br>
   MSDN_Ref: HTTP://MSDN.Microsoft.com/En-US/Library/Windows/Desktop/GG699720.aspx              <br>
             HTTP://MSDN.Microsoft.com/En-US/Library/Windows/Desktop/MS741621.aspx              <br>
*/
_Success_(return == NO_ERROR)
UINT32 HlprWinSockAcquirePortReservationForSocket(_In_ SOCKET unboundSocket,
                                                  _In_ INET_PORT_RANGE* pPortRange,
                                                  _Inout_ UINT64* pReservationToken)
{
   ASSERT(unboundSocket != INVALID_SOCKET);
   ASSERT(pPortRange);
   ASSERT(pReservationToken);

   UINT32                         status        = NO_ERROR;
   UINT32                         bytesReturned = 0;
   INET_PORT_RESERVATION_INSTANCE reservation   = {0};

   status = WSAIoctl(unboundSocket,
                     SIO_ACQUIRE_PORT_RESERVATION,
                     pPortRange,
                     sizeof(INET_PORT_RANGE),
                     &reservation,
                     sizeof(INET_PORT_RESERVATION_INSTANCE),
                     (LPDWORD)&bytesReturned,
                     0,
                     0);
   if(status != NO_ERROR)
   {
      status = WSAGetLastError();

      HlprLogError(L"HlprWinSockAssociatePortReservationWithSocket : WSAIoctl() [status: %#x]",
                   status);
   }
   else
      *pReservationToken = reservation.Token.Token;

   return status;
}

/**
 @helper_function="HlprWinSockAssociatePortReservationWithSocket"
 
   Purpose:  Associate the socket with the persistent port(s) that were reserved previously.    <br>
                                                                                                <br>
   Notes:                                                                                       <br>
                                                                                                <br>
   MSDN_Ref: HTTP://MSDN.Microsoft.com/En-US/Library/Windows/Desktop/GG699721.aspx              <br>
             HTTP://MSDN.Microsoft.com/En-US/Library/Windows/Desktop/MS741621.aspx              <br>
*/
_Success_(return == NO_ERROR)
UINT32 HlprWinSockAssociatePortReservationWithSocket(_In_ SOCKET unboundSocket,
                                                     _In_ UINT64 reservationToken)
{
   ASSERT(unboundSocket != INVALID_SOCKET);

   UINT32 status        = NO_ERROR;
   UINT32 bytesReturned = 0;

   status = WSAIoctl(unboundSocket,
                     SIO_ASSOCIATE_PORT_RESERVATION,
                     &reservationToken,
                     sizeof(UINT64),
                     0,
                     0,
                     (LPDWORD)&bytesReturned,
                     0,
                     0);
   if(status != NO_ERROR)
   {
      status = WSAGetLastError();

      HlprLogError(L"HlprWinSockAssociatePortReservationWithSocket : WSAIoctl() [status: %#x]",
                   status);
   }

   return status;
}

/**
 @private_function="HlprWinSockQueryPortReservation"
 
   Purpose:  Find the token for the previously created port reservations.                       <br>
                                                                                                <br>
   Notes:                                                                                       <br>
                                                                                                <br>
   MSDN_Ref: HTTP://MSDN.Microsoft.com/En-US/Library/Windows/Desktop/GG696072.aspx              <br>
             HTTP://MSDN.Microsoft.com/En-US/Library/Windows/Desktop/GG696063.aspx              <br>
*/
_Success_(return == NO_ERROR)
UINT32 HlprWinSockQueryPortReservation(_In_ UINT8 ipProtocol,
                                       _In_ INET_PORT_RANGE* pPortRange,
                                       _Inout_ UINT64* pReservationToken)
{
   ASSERT(ipProtocol != IPPROTO_TCP &&
          ipProtocol != IPPROTO_UDP);
   ASSERT(pPortRange);
   ASSERT(pReservationToken);

   UINT32 status = NO_ERROR;

   if(ipProtocol == IPPROTO_TCP)
      status = LookupPersistentTcpPortReservation(htons(pPortRange->StartPort),
                                                  pPortRange->NumberOfPorts,
                                                  pReservationToken);
   else
      status = LookupPersistentUdpPortReservation(htons(pPortRange->StartPort),
                                                  pPortRange->NumberOfPorts,
                                                  pReservationToken);

   if(status != NO_ERROR)
   {
      if(status == ERROR_NOT_FOUND)
         HlprLogInfo(L"HlprWinSockQueryPortReservation : LookupPersistent%sPortReservation() [status: %#x]",
                     ipProtocol == IPPROTO_TCP ? L"Tcp" : L"Udp",
                     status);
      else
         HlprLogError(L"HlprWinSockQueryPortReservation : LookupPersistent%sPortReservation() [status: %#x]",
                      ipProtocol == IPPROTO_TCP ? L"Tcp" : L"Udp",
                      status);

      *pReservationToken = 0;
   }

   return status;
}

/**
 @private_function="HlprWinSockDestroyPortReservation"
 
   Purpose:  Removes the reservation of specific ports for the Proxy service's use.             <br>
                                                                                                <br>
   Notes:                                                                                       <br>
                                                                                                <br>
   MSDN_Ref: HTTP://MSDN.Microsoft.com/En-US/Library/Windows/Desktop/GG696070.aspx              <br>
             HTTP://MSDN.Microsoft.com/En-US/Library/Windows/Desktop/GG696071.aspx              <br>
*/
_Success_(return == NO_ERROR)
UINT32 HlprWinSockDestroyPortReservation(_In_ UINT8 ipProtocol,
                                         _In_ INET_PORT_RANGE* pPortRange,
                                         _Inout_opt_ UINT64* pReservationToken) /* 0 */
{
   ASSERT(ipProtocol != IPPROTO_TCP &&
          ipProtocol != IPPROTO_UDP);
   ASSERT(pPortRange);

   UINT32 status = NO_ERROR;

   if(ipProtocol == IPPROTO_TCP)
      status = DeletePersistentTcpPortReservation(htons(pPortRange->StartPort),
                                                  pPortRange->NumberOfPorts);
   else
      status = DeletePersistentUdpPortReservation(htons(pPortRange->StartPort),
                                                  pPortRange->NumberOfPorts);

   if(status == NO_ERROR)
   {
      if(pReservationToken)
         *pReservationToken = 0;
   }
   else if(status == ERROR_NOT_FOUND)
   {
      status = NO_ERROR;

      if(pReservationToken)
         *pReservationToken = 0;
   }
   else
      HlprLogError(L"HlprWinSockDestroyPortReservation : DeletePersistent%sPortReservation() [status: %#x]",
                   ipProtocol == IPPROTO_TCP ? L"Tcp" : L"Udp",
                   status);

   return status;
}

/**
 @private_function="HlprWinSockCreatePortReservation"
 
   Purpose:  Reserves specific ports for the Proxy service's use.                               <br>
                                                                                                <br>
   Notes:                                                                                       <br>
                                                                                                <br>
   MSDN_Ref: HTTP://MSDN.Microsoft.com/En-US/Library/Windows/Desktop/GG696068.aspx              <br>
             HTTP://MSDN.Microsoft.com/En-US/Library/Windows/Desktop/GG696069.aspx              <br>
*/
_Success_(return == NO_ERROR)
UINT32 HlprWinSockCreatePortReservation(_In_ UINT8 ipProtocol,
                                        _In_ INET_PORT_RANGE* pPortRange,
                                        _Inout_ UINT64* pReservationToken)
{
   ASSERT(ipProtocol != IPPROTO_TCP &&
          ipProtocol != IPPROTO_UDP);
   ASSERT(pPortRange);
   ASSERT(pReservationToken);

   UINT32 status = NO_ERROR;

   if(ipProtocol == IPPROTO_TCP)
      status = CreatePersistentTcpPortReservation(htons(pPortRange->StartPort),
                                                  pPortRange->NumberOfPorts,
                                                  pReservationToken);
   else
      status = CreatePersistentUdpPortReservation(htons(pPortRange->StartPort),
                                                  pPortRange->NumberOfPorts,
                                                  pReservationToken);

   if(status != NO_ERROR)
   {
      HlprLogError(L"HlprWinSockCreatePortReservation : CreatePersistent%sPortReservation() [status: %#x]",
                   ipProtocol == IPPROTO_TCP ? L"Tcp" : L"Udp",
                   status);

      *pReservationToken = 0;
   }

   return status;
}

#if(NTDDI_VERSION >= NTDDI_WIN8)

/**
 @helper_function="HlprWinSockAssociateConnectionRedirectRecordsAndContextWithProxySocket"
 
   Purpose:  Retrieve the original REDIRECT_RECORDS from the original socket and associate them 
             with the new (proxy) socket.                                                       <br>
                                                                                                <br>
   Notes:    This function needs to be called prior to binding the proxied socket.              <br>
                                                                                                <br>
   MSDN_Ref: HTTP://MSDN.Microsoft.com/En-US/Library/Windows/Desktop/MS741621.aspx              <br>
             HTTP://MSDN.Microsoft.com/En-US/Library/Windows/Hardware/HH802472.aspx             <br>
             HTTP://MSDN.Microsoft.com/En-US/Library/Windows/Hardware/HH802473.aspx             <br>
             HTTP://MSDN.Microsoft.com/En-US/Library/Windows/Hardware/HH802474.aspx             <br>

*/
_Success_(return == NO_ERROR)
UINT32 HlprWinSockAssociateConnectionRedirectRecordsAndContextWithProxySocket(_In_ SOCKET originalSocket,
                                                                              _Inout_ SOCKET proxySocket,
                                                                              _Inout_ SOCKADDR_STORAGE* pProxyPeerSockAddrStorage,
                                                                              _Inout_opt_ SOCKADDR_STORAGE* pOriginSockAddrStorage) /* 0 */
{
   ASSERT(originalSocket != INVALID_SOCKET);
   ASSERT(proxySocket != INVALID_SOCKET);
   ASSERT(pProxyPeerSockAddrStorage);

   UINT32       status                = NO_ERROR;
   const SIZE_T REDIRECT_RECORDS_SIZE = 8192;
   const SIZE_T REDIRECT_CONTEXT_SIZE = sizeof(SOCKADDR_STORAGE) * 2;
   BYTE*        pRedirectRecords      = 0;
   BYTE*        pRedirectContext      = 0;
   SIZE_T       redirectRecordsSize   = 0;
   SIZE_T       redirectContextSize   = 0;
   SIZE_T       outputSize            = 0;

   HLPR_NEW_ARRAY(pRedirectRecords,
                  BYTE,
                  REDIRECT_RECORDS_SIZE);
   HLPR_BAIL_ON_ALLOC_FAILURE(pRedirectRecords,
                              status);

   HLPR_NEW_ARRAY(pRedirectContext,
                  BYTE,
                  REDIRECT_CONTEXT_SIZE);
   HLPR_BAIL_ON_ALLOC_FAILURE(pRedirectContext,
                              status);

   /// Retrieve the REDIRECT_RECORDS from the client socket.
   status = WSAIoctl(originalSocket,
                     SIO_QUERY_WFP_CONNECTION_REDIRECT_RECORDS,
                     0,
                     0,
                     pRedirectRecords,
                     REDIRECT_RECORDS_SIZE,
                     (LPDWORD)&redirectRecordsSize,
                     0,
                     0);
   if(status != NO_ERROR)
   {
      status = WSAGetLastError();

      HlprLogError(L"HlprWinSockAssociateConnectionRedirectRecordsAndContextWithProxySocket : WSAIoctl() [status: %#x]",
                   status);

      HLPR_BAIL;
   }

   /// Retrieve the REDIRECT_CONTEXT from the client socket.
   status = WSAIoctl(originalSocket,
                     SIO_QUERY_WFP_CONNECTION_REDIRECT_CONTEXT,
                     0,
                     0,
                     pRedirectContext,
                     REDIRECT_CONTEXT_SIZE,
                     (LPDWORD)&redirectContextSize,
                     0,
                     0);
   if(status != NO_ERROR)
   {
      status = WSAGetLastError();

      if(status != FWP_E_NOT_FOUND)
      {
         HlprLogError(L"HlprWinSockAssociateConnectionRedirectRecordsAndContextWithProxySocket : WSAIoctl() [status: %#x]",
                      status);

         HLPR_BAIL;
      }
   }
   else
   {
      ASSERT(redirectContextSize == REDIRECT_CONTEXT_SIZE);

      /// The context passed in WFPSamplerCalloutDriver.sys is the SOCKADDR_STORAGE info of the 
      /// classified peer endpoint ...
      RtlCopyMemory(pProxyPeerSockAddrStorage,
                    pRedirectContext,
                    sizeof(SOCKADDR_STORAGE));

      /// ... and the SOCK_ADDR_STORAGE of the classified origin endpoint.
      if(pOriginSockAddrStorage)
      {
         UINT32 contextOriginOffset = sizeof(SOCKADDR_STORAGE);

         RtlCopyMemory(pOriginSockAddrStorage,
                       &(pRedirectContext[contextOriginOffset]),
                       sizeof(SOCKADDR_STORAGE));
      }
   }

   /// Attach the REDIRECT_RECORDS to the proxied socket
   status = WSAIoctl(proxySocket,
                     SIO_SET_WFP_CONNECTION_REDIRECT_RECORDS,
                     pRedirectRecords,
                     (DWORD)redirectRecordsSize,
                     0,
                     0,
                     (LPDWORD)&outputSize,
                     0,
                     0);
   if(status != NO_ERROR)
   {
      status = WSAGetLastError();

      HlprLogError(L"HlprWinSockAssociateConnectionRedirectRecordsAndContextWithProxySocket : WSAIoctl() [status: %#x]",
                   status);

      HLPR_BAIL;
   }

   HLPR_BAIL_LABEL:

   HLPR_DELETE_ARRAY(pRedirectContext);

   HLPR_DELETE_ARRAY(pRedirectRecords);

   return status;
}

#endif /// (NTDDI_VERSION >= NTDDI_WIN8)

/**
 @helper_function="HlprWinSockBindToSocket"
 
   Purpose:  Bind a socket to a protocol, port, and network address.                            <br>
                                                                                                <br>
   Notes:                                                                                       <br>
                                                                                                <br>
   MSDN_Ref: HTTP://MSDN.Microsoft.com/En-US/Library/Windows/Desktop/MS737550.aspx              <br>
*/
_Success_(return == NO_ERROR)
UINT32 HlprWinSockBindToSocket(_In_ SOCKET unboundSocket,
                               _In_ SOCKADDR_STORAGE* pSockAddrStorage)
{
   ASSERT(unboundSocket != INVALID_SOCKET);
   ASSERT(pSockAddrStorage);

   UINT32 status = NO_ERROR;

   status = bind(unboundSocket,
                 (SOCKADDR*)pSockAddrStorage,
                 sizeof(SOCKADDR_STORAGE));
   if(status != NO_ERROR)
   {
      status = WSAGetLastError();

      HlprLogError(L"HlprWinSockBindToSocket : bind() [status: %#x]",
                   status);
   }

   return status;
}

/**
 @helper_function="HlprWinSockListenOnSocket"
 
   Purpose:  Place the socket in a state in which it listens for incoming connections.          <br>
                                                                                                <br>
   Notes:                                                                                       <br>
                                                                                                <br>
   MSDN_Ref: HTTP://MSDN.Microsoft.com/En-US/Library/Windows/Desktop/MS739168.aspx              <br>
*/
_Success_(return == NO_ERROR)
UINT32 HlprWinSockListenOnSocket(_In_ SOCKET boundSocket)
{
   ASSERT(boundSocket != INVALID_SOCKET);

   UINT32 status = NO_ERROR;

   status = listen(boundSocket,
                   SOMAXCONN);
   if(status != NO_ERROR)
   {
      status = WSAGetLastError();

      HlprLogError(L"HlprWinSockListenOnSocket : listen() [status: %#x]",
                   status);
   }

   return status;
}

/**
 @helper_function="HlprWinSockAcceptConnection"
 
   Purpose:  Place the socket in a state in which it listens for incoming connections.          <br>
                                                                                                <br>
   Notes:                                                                                       <br>
                                                                                                <br>
   MSDN_Ref: HTTP://MSDN.Microsoft.com/En-US/Library/Windows/Desktop/MS741513.aspx              <br>
*/
_Success_(return == NO_ERROR)
UINT32 HlprWinSockAcceptConnection(_In_ SOCKET listeningSocket,
                                   _Inout_ SOCKET* pConnectedSocket,
                                   _Inout_ SOCKADDR_STORAGE* pPeerSockAddrStorage)
{
   ASSERT(listeningSocket != INVALID_SOCKET);
   ASSERT(pConnectedSocket);
   ASSERT(pPeerSockAddrStorage);

   UINT32 status        = NO_ERROR;
   UINT32 addressLength = sizeof(SOCKADDR_STORAGE);

   *pConnectedSocket = WSAAccept(listeningSocket,
                                 (SOCKADDR*)pPeerSockAddrStorage,
                                 (LPINT)&addressLength,
                                 0,
                                 0);
   if(*pConnectedSocket == INVALID_SOCKET)
   {
      status = WSAGetLastError();

      HlprLogError(L"HlprWinSockAcceptConnection : WSAAccept() [status: %#x]",
                   status);
   }

   return status;
}

/**
 @helper_function="HlprWinSockConnectSocket"
 
   Purpose:  Establish the TCP handshake with the remote peer.                                  <br>
                                                                                                <br>
   Notes:                                                                                       <br>
                                                                                                <br>
   MSDN_Ref: HTTP://MSDN.Microsoft.com/En-US/Library/Windows/Desktop/MS741559.aspx              <br>
*/
_Success_(return == NO_ERROR)
UINT32 HlprWinSockConnectSocket(_In_ SOCKET unconnectedSocket,
                                _In_ SOCKADDR_STORAGE* pPeerSockAddrStorage)
{
   ASSERT(unconnectedSocket != INVALID_SOCKET);
   ASSERT(pPeerSockAddrStorage);

   UINT32 status = NO_ERROR;

   status = WSAConnect(unconnectedSocket,
                       (SOCKADDR*)pPeerSockAddrStorage,
                       sizeof(SOCKADDR_STORAGE),
                       0,
                       0,
                       0,
                       0);
   if(status != NO_ERROR)
   {
      status = WSAGetLastError();

      HlprLogError(L"HlprWinSockConnectSocket : WSAConnect() [status: %#x]",
                   status);
   }

   return status;
}

/**
 @helper_function="HlprWinSockReceiveTCPData"
 
   Purpose:  Receive TCP data from the peer.                                                    <br>
                                                                                                <br>
   Notes:    For use with TCP only.                                                             <br>
                                                                                                <br>
   MSDN_Ref: HTTP://MSDN.Microsoft.com/En-US/Library/Windows/Desktop/MS741688.aspx              <br>
*/
_Success_(return == NO_ERROR)
UINT32 HlprWinSockReceiveTCPData(_In_ SOCKET receivingSocket,
                                 _Inout_updates_(numDataBuffers) WSABUF* pDataBuffers,
                                 _Inout_ UINT32* pNumBytesReceived,
                                 _In_opt_ LPWSAOVERLAPPED pOverlapped,                      /* 0 */
                                 _In_opt_ LPWSAOVERLAPPED_COMPLETION_ROUTINE pCompletionFn, /* 0 */
                                 _In_ UINT32 numDataBuffers,                                /* 1 */
                                 _In_ UINT32 msgFlags)                                      /* 0 */
{
   ASSERT(receivingSocket != INVALID_SOCKET);
   ASSERT(pDataBuffers);
   ASSERT(pDataBuffers->len);
   ASSERT(pDataBuffers->buf);
   ASSERT(pNumBytesReceived);
   ASSERT(numDataBuffers);
   ASSERT((pNumBytesReceived &&
           pOverlapped == 0 &&
           pCompletionFn == 0) ||
           (pNumBytesReceived &&
           pOverlapped &&
           pCompletionFn));


   UINT32 status = NO_ERROR;
   UINT32 flags  = msgFlags;

   status = WSARecv(receivingSocket,
                    pDataBuffers,
                    numDataBuffers,
                    (LPDWORD)pNumBytesReceived,
                    (LPDWORD)&flags,
                    pOverlapped,
                    pCompletionFn);
   if(status != NO_ERROR)
   {
      status = WSAGetLastError();

      if(status == WSA_IO_PENDING &&
         pOverlapped &&
         pCompletionFn)
         status = NO_ERROR;
      else if(status != WSAEDISCON)
         HlprLogError(L"HlprWinSockReceiveData : WSARecv() [status: %#x]",
                      status);
   }

   return status;
}

/**
 @helper_function="HlprWinSockSendTCPData"
 
   Purpose:  Transmit TCP data to the peer.                                                     <br>
                                                                                                <br>
   Notes:    For use with TCP only.                                                             <br>
                                                                                                <br>
   MSDN_Ref: HTTP://MSDN.Microsoft.com/En-US/Library/Windows/Desktop/MS742203.aspx              <br>
*/
_Success_(return == NO_ERROR)
UINT32 HlprWinSockSendTCPData(_In_ SOCKET sendingSocket,
                              _In_reads_(numDataBuffers) WSABUF* pDataBuffers,
                              _Inout_opt_ UINT32* pNumBytesTransmitted,
                              _In_opt_ LPWSAOVERLAPPED pOverlapped,                      /* 0 */
                              _In_opt_ LPWSAOVERLAPPED_COMPLETION_ROUTINE pCompletionFn, /* 0 */
                              _In_ UINT32 numDataBuffers)                                /* 1 */
{
   ASSERT(sendingSocket != INVALID_SOCKET);
   ASSERT(pDataBuffers);
   ASSERT(pDataBuffers->len);
   ASSERT(pDataBuffers->buf);
   ASSERT(numDataBuffers);
   ASSERT((pNumBytesTransmitted &&
           pOverlapped == 0 &&
           pCompletionFn == 0) ||
           (pNumBytesTransmitted &&
           pOverlapped &&
           pCompletionFn));

   UINT32 status = NO_ERROR;

   status = WSASend(sendingSocket,
                    pDataBuffers,
                    numDataBuffers,
                    (LPDWORD)pNumBytesTransmitted,
                    0,
                    pOverlapped,
                    pCompletionFn);
   if(status != NO_ERROR)
   {
      status = WSAGetLastError();

      if(status == WSA_IO_PENDING &&
         pOverlapped &&
         pCompletionFn)
         status = NO_ERROR;
      else
         HlprLogError(L"HlprWinSockSendTCPData : WSASend() [status: %#x]",
                      status);
   }

   return status;
}