├── .gitattributes
├── .github
└── workflows
│ ├── build.yml
│ ├── gosec.yml
│ └── qodana.yml
├── LICENSE
├── Makefile
├── README.MD
├── client.go
├── docs
└── CHANGELOG.MD
├── example
└── main.go
├── go.mod
├── go.sum
├── qodana.yaml
├── utils.go
└── winhttp.go
/.gitattributes:
--------------------------------------------------------------------------------
1 | *.go linguist-language=Go
--------------------------------------------------------------------------------
/.github/workflows/build.yml:
--------------------------------------------------------------------------------
1 | # This workflow will build a golang project
2 | # For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-go
3 |
4 | name: "Build & Test"
5 |
6 | on:
7 | workflow_dispatch:
8 | push:
9 | paths-ignore:
10 | - '.github/**'
11 | - 'docs/**'
12 | - '.gitattributes'
13 | - '.gitignore'
14 | - 'LICENSE'
15 | - 'README.MD'
16 | pull_request:
17 | paths-ignore:
18 | - '.github/**'
19 | - 'docs/**'
20 | - '.gitattributes'
21 | - '.gitignore'
22 | - 'LICENSE'
23 | - 'README.MD'
24 |
25 | jobs:
26 | build:
27 | name: 'Build Job'
28 | runs-on: windows-latest
29 | steps:
30 | - name: Checkout Repository
31 | id: checkout
32 | uses: actions/checkout@v3
33 |
34 | - name: Set up Go
35 | uses: actions/setup-go@v4
36 | with:
37 | go-version: '1.21'
38 | check-latest: true
39 |
40 | - name: GoVulnCheck
41 | id: govulncheck
42 | uses: golang/govulncheck-action@v1
43 | with:
44 | go-version-input: '1.21'
45 | go-package: '.'
46 |
47 | - name: 'Build winhttp example'
48 | id: build
49 | run: go build -o winhttp.exe ./example/main.go
50 |
--------------------------------------------------------------------------------
/.github/workflows/gosec.yml:
--------------------------------------------------------------------------------
1 | # This workflow will build a golang project
2 | # For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-go
3 |
4 | name: "gosec"
5 |
6 | on:
7 | workflow_dispatch:
8 | push:
9 | paths-ignore:
10 | - '.github/**'
11 | - 'docs/**'
12 | - '.gitattributes'
13 | - '.gitignore'
14 | - 'LICENSE'
15 | - 'README.MD'
16 | pull_request:
17 | paths-ignore:
18 | - '.github/**'
19 | - 'docs/**'
20 | - '.gitattributes'
21 | - '.gitignore'
22 | - 'LICENSE'
23 | - 'README.MD'
24 |
25 | jobs:
26 | build:
27 | name: 'gosec Job'
28 | runs-on: ubuntu-latest
29 | steps:
30 | - name: Checkout Repository
31 | id: checkout
32 | uses: actions/checkout@v3
33 |
34 | - name: Set up Go
35 | uses: actions/setup-go@v4
36 | with:
37 | go-version: '1.21'
38 | check-latest: true
39 |
40 | - name: Run Gosec Security Scanner
41 | id: gosec
42 | run: |
43 | export PATH=$PATH:$(go env GOPATH)/bin
44 | go install github.com/securego/gosec/v2/cmd/gosec@latest
45 | export GOOS=windows
46 | gosec -exclude=G103 ./...
47 |
48 | - name: Go Report Card - Install
49 | id: goreportcard_install
50 | working-directory: /tmp
51 | run: |
52 | git clone https://github.com/gojp/goreportcard.git
53 | cd goreportcard
54 | make install
55 | go install ./cmd/goreportcard-cli
56 |
57 | - name: Go Report Card - Run
58 | id: goreportcard_run
59 | run: 'goreportcard-cli -v' # This renames the files in the ./rpc directory to *.grc.bak causing builds to fail
--------------------------------------------------------------------------------
/.github/workflows/qodana.yml:
--------------------------------------------------------------------------------
1 | name: "Qodana: Push"
2 |
3 | on:
4 | workflow_dispatch:
5 | push:
6 | paths-ignore:
7 | - '.github/**'
8 | - 'docs/**'
9 | - '.gitattributes'
10 | - '.gitignore'
11 | - '.gitmodules'
12 | - 'qodana.yaml'
13 | - 'qodana.sarif.json'
14 | - 'LICENSE'
15 | - 'README.MD'
16 |
17 |
18 | jobs:
19 | qodana:
20 | name: 'Qodana Job'
21 | runs-on: ubuntu-latest
22 | permissions:
23 | contents: write
24 | pull-requests: write
25 | checks: write
26 | steps:
27 | - uses: actions/checkout@v3
28 | with:
29 | ref: ${{ github.event.pull_request.head.sha }} # to check out the actual pull request commit, not the merge commit
30 | fetch-depth: 0 # a full history is required for pull request analysis
31 | - name: 'Qodana Scan'
32 | uses: JetBrains/qodana-action@v2023.3
33 | with:
34 | args: --baseline,.qodana/qodana.sarif.json
35 | env:
36 | QODANA_TOKEN: ${{ secrets.QODANA_TOKEN }}
37 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/Makefile:
--------------------------------------------------------------------------------
1 | default:
2 | export GOOS=windows && go build -o winhttp-example.exe example/main.go
3 |
--------------------------------------------------------------------------------
/README.MD:
--------------------------------------------------------------------------------
1 | [](https://goreportcard.com/report/github.com/Ne0nd0g/winhttp)
2 | [](https://www.gnu.org/licenses/gpl-3.0)
3 | [](https://github.com/Ne0nd0g/winhttp/releases/latest)
4 | [](https://pkg.go.dev/github.com/Ne0nd0g/winhttp)
5 |
6 | # winhttp
7 |
8 | `winhttp` is a library used to interact with the Windows [winhttp](https://learn.microsoft.com/en-us/windows/win32/winhttp/about-winhttp) API.
9 |
10 | It is designed take in a [http.Request](https://pkg.go.dev/net/http#Request) and return a [http.Response](https://pkg.go.dev/net/http#Response) from the go `http` standard library.
11 | This library returns a custom `Client` that mimics the [http.Client](https://pkg.go.dev/net/http#Client) so that it can be a drop in replacement for the `http.Client`.
12 | This package's custom client also takes an [http.Transport](https://pkg.go.dev/net/http#Transport) structure in the `Transport` field to configure how the winhttp client is used.
13 |
14 | ## Logging
15 |
16 | This package uses the [log/slog](https://pkg.go.dev/log/slog) package for logging.
17 | To retrieve the log output, create a new logger and call the [slog.SetDefault()](https://pkg.go.dev/log/slog#SetDefault) function.
18 | All logging calls in this package are only for the `DEBUG` logging level which are not output by default.
19 |
20 | ## Example
21 |
22 | There is an example implementation in the [example](./example) directory.
23 | Run the example code with:
24 |
25 | ```text
26 | PS C:\> go run .\examples\main.go
27 | {"time":"2024-02-04T10:00:19.6010954-08:00","level":"INFO","msg":"building the HTTP request"}
28 | {"time":"2024-02-04T10:00:19.60164-08:00","level":"INFO","msg":"building the HTTP client"}
29 | {"time":"2024-02-04T10:00:19.60164-08:00","level":"INFO","msg":"sending the HTTP request","method":"GET","url":"https://httpbin.org/get"}
30 | {"time":"2024-02-04T10:00:19.7671138-08:00","level":"INFO","msg":"recieved HTTP response","response":{"Status":"200 OK","StatusCode":200,"Proto":"HTTP/1.1","ProtoMajor":1,"ProtoMinor":1,"Header":{"Access-Control-Allow-Credentials":["true"],"Access-Control-Allow-Origin":["*"],"Connection":["keep-alive"],"Content-Length":["364"],"Content-Type":["application/json"],"Date":["Sun, 04 Feb 2024 18:00:19 GMT"],"Server":["gunicorn/19.9.0"]},"Body":{"Reader":{}},"ContentLength":364,"TransferEncoding":null,"Close":false,"Uncompressed":false,"Trailer":null,"Request":null,"TLS":null}}
31 | {"time":"2024-02-04T10:00:19.7683439-08:00","level":"INFO","msg":"received HTTP payload data","data length":364}
32 | {"time":"2024-02-04T10:00:19.7683439-08:00","level":"INFO","msg":"program finished running succesfully"}
33 | ```
34 |
35 | The program's command line flags are:
36 |
37 | ```text
38 | -data string
39 | data to send with the request
40 | -debug
41 | enable debug output
42 | -method string
43 | the HTTP METHOD for the request (default "GET")
44 | -trace
45 | enable SourceKey for debug output
46 | -url string
47 | the full URL for the request (default "https://httpbin.org/get")
48 | ```
--------------------------------------------------------------------------------
/client.go:
--------------------------------------------------------------------------------
1 | //go:build windows
2 |
3 | /*
4 | Copyright (C) 2024 Russel Van Tuyl
5 |
6 | winhttp is free software: you can redistribute it and/or modify
7 | it under the terms of the GNU General Public License as published by
8 | the Free Software Foundation, either version 3 of the License, or
9 | any later version.
10 |
11 | winhttp is distributed in the hope that it will be useful,
12 | but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | GNU General Public License for more details.
15 |
16 | You should have received a copy of the GNU General Public License
17 | along with winhttp. If not, see .
18 | */
19 |
20 | // Package winhttp provides an HTTP client using the Windows WinHttp API
21 | package winhttp
22 |
23 | import (
24 | "bytes"
25 | "crypto/tls"
26 | "encoding/binary"
27 | "fmt"
28 | "io"
29 | "log/slog"
30 | "net/http"
31 | "reflect"
32 | "strconv"
33 | "strings"
34 | "time"
35 | "unsafe"
36 |
37 | "golang.org/x/sys/windows"
38 | )
39 |
40 | // Client is an HTTP client used for making HTTP requests using the Windows winhttp API
41 | // This type mimics the Golang http.Client type at https://pkg.go.dev/net/http#Client
42 | // The Transport is optional and the http.DefaultTransport will be used if one is not provided
43 | type Client struct {
44 | Transport http.RoundTripper
45 | Timeout time.Duration
46 | }
47 |
48 | // NewHTTPClient returns an HTTP/1.1 client using the Windows WinHTTP API
49 | func NewHTTPClient() (*Client, error) {
50 | slog.Debug("entering into NewHTTPClient function")
51 | client := Client{}
52 | return &client, nil
53 | }
54 |
55 | // Do send an HTTP request and returns an HTTP response using the Windows winhttp API.
56 | // The high-level API call flow to send data is:
57 | // WinHttpOpen -> WinHttpConnect -> WinHttpOpenRequest -> WinHttpSendRequest.
58 | // The high-level API call flow to receive data is:
59 | // WinHttpReceiveResponse -> WinHttpQueryDataAvailable -> WinHttpReadData.
60 | func (c *Client) Do(req *http.Request) (*http.Response, error) {
61 | slog.Debug("entering into *Client.Do function", "http.Request", fmt.Sprintf("%+v", req))
62 | resp := http.Response{}
63 |
64 | // Create the Windows HTTP session
65 | hSession, err := WinHttpOpen(req.UserAgent(), WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY, "", "", WINHTTP_FLAG_NONE)
66 | if err != nil {
67 | return nil, err
68 | }
69 | defer WinHttpCloseHandle(hSession)
70 |
71 | // See if the Client's transport type exists, if not, set it to the http package's DefaultTransport
72 | if c.Transport == nil {
73 | c.Transport = http.DefaultTransport
74 | }
75 | // Client only works with *http.Transport type
76 | if reflect.TypeOf(c.Transport) != reflect.TypeOf(&http.Transport{}) {
77 | return nil, fmt.Errorf("winhttp expect HTTP Client Transport of type *http.Transport but received: %T", c.Transport)
78 | }
79 | transport := c.Transport.(*http.Transport)
80 |
81 | // Apply TLS configurations if any
82 | if transport.TLSClientConfig != nil {
83 | // Check to see if a TLS minimum or maximum version was set
84 | vTLS := 0x00000000
85 | // Check to see if the TLS minimum version is set
86 | if transport.TLSClientConfig.MinVersion > 0 {
87 | switch transport.TLSClientConfig.MinVersion {
88 | case tls.VersionTLS10:
89 | vTLS = WINHTTP_FLAG_SECURE_PROTOCOL_TLS1 | WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_1 | WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_2 | WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_3
90 | case tls.VersionTLS11:
91 | vTLS = WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_1 | WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_2 | WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_3
92 | case tls.VersionTLS12:
93 | vTLS = WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_2 | WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_3
94 | case tls.VersionTLS13:
95 | vTLS = WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_3
96 | }
97 | }
98 |
99 | // Check to see if the TLS maximum version is set
100 | if transport.TLSClientConfig.MaxVersion > 0 {
101 | switch transport.TLSClientConfig.MaxVersion {
102 | case tls.VersionTLS10:
103 | vTLS = vTLS &^ (WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_1 | WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_2 | WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_3)
104 | case tls.VersionTLS11:
105 | vTLS = vTLS &^ (WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_2 | WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_3)
106 | case tls.VersionTLS12:
107 | vTLS = vTLS &^ WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_3
108 | }
109 | }
110 |
111 | // If a TLS min/max version was set, configure the winhttp client
112 | if vTLS > 0 {
113 | slog.Debug("set winhttp option", "option", "WINHTTP_OPTION_SECURE_PROTOCOLS", "flags", fmt.Sprintf("%08b", uint32(vTLS)))
114 | buffer := make([]byte, 4)
115 | binary.LittleEndian.PutUint32(buffer, uint32(vTLS))
116 | err = WinHttpSetOption(hSession, WINHTTP_OPTION_SECURE_PROTOCOLS, buffer)
117 | if err != nil {
118 | return nil, err
119 | }
120 | }
121 | }
122 |
123 | // Determine the request server port
124 | var port int
125 | if req.URL.Port() == "" {
126 | port = INTERNET_DEFAULT_PORT
127 | } else {
128 | port, err = strconv.Atoi(req.URL.Port())
129 | if err != nil {
130 | return nil, fmt.Errorf("winhttp there was an error converting '%s' to an integer: %s", req.URL.Port(), err)
131 | }
132 | }
133 |
134 | // Determine the request server name and remove the port if it exists
135 | serverName := req.URL.Hostname()
136 | if strings.Contains(serverName, ":") {
137 | serverName = strings.Split(serverName, ":")[0]
138 | }
139 |
140 | // Create the Windows HTTP connection to the target
141 | var hConnect windows.Handle
142 | hConnect, err = WinHttpConnect(hSession, serverName, uint32(port))
143 | if err != nil {
144 | return nil, err
145 | }
146 | defer WinHttpCloseHandle(hConnect)
147 |
148 | // Set HTTP Access Types
149 | accessTypes := []string{WINHTTP_DEFAULT_ACCEPT_TYPES}
150 | //accessTypes := []string{"text/html", "application/octet-stream", "application/xhtml+xml", "", "application/xml;q=0.9", "image/webp", "*/*;q=0.8"}
151 | _, OK := req.Header["Accept"]
152 | if OK {
153 | accessTypes = req.Header["Accept"]
154 | }
155 |
156 | // Set HTTP Request Flags
157 | reqFlags := WINHTTP_FLAG_NONE
158 | if req.URL.Scheme == "https" {
159 | reqFlags = reqFlags | WINHTTP_FLAG_SECURE
160 | }
161 |
162 | // Open the HTTP Request
163 | var hRequest windows.Handle
164 | hRequest, err = WinHttpOpenRequest(hConnect, req.Method, req.URL.Path, "", WINHTTP_NO_REFERER, accessTypes, uint32(reqFlags))
165 | if err != nil {
166 | return nil, err
167 | }
168 | defer WinHttpCloseHandle(hRequest)
169 |
170 | // If a TLS client configuration was provided, use it to configure the winhttp client
171 | if transport.TLSClientConfig != nil {
172 | // Check to see if InsecureSkipVerify was set to true
173 | if transport.TLSClientConfig.InsecureSkipVerify {
174 | flags := SECURITY_FLAG_IGNORE_UNKNOWN_CA | SECURITY_FLAG_IGNORE_CERT_CN_INVALID | SECURITY_FLAG_IGNORE_CERT_DATE_INVALID | SECURITY_FLAG_IGNORE_CERT_WRONG_USAGE
175 | buffer := make([]byte, 4)
176 | binary.LittleEndian.PutUint32(buffer, uint32(flags))
177 | err = WinHttpSetOption(hRequest, WINHTTP_OPTION_SECURITY_FLAGS, buffer)
178 | if err != nil {
179 | return nil, err
180 | }
181 | slog.Debug("set winhttp option", "option", "WINHTTP_OPTION_SECURITY_FLAGS", "flags", fmt.Sprintf("%08b", uint32(flags)))
182 | }
183 |
184 | // Check to see if TLS next protocols were set
185 | if len(transport.TLSClientConfig.NextProtos) > 0 {
186 | var flags int
187 | for _, proto := range transport.TLSClientConfig.NextProtos {
188 | switch strings.ToLower(proto) {
189 | case "h2":
190 | flags = flags | WINHTTP_PROTOCOL_FLAG_HTTP2
191 | case "h3":
192 | flags = flags | WINHTTP_PROTOCOL_FLAG_HTTP3
193 | }
194 | }
195 | buffer := make([]byte, 4)
196 | binary.LittleEndian.PutUint32(buffer, uint32(flags))
197 | err = WinHttpSetOption(hRequest, WINHTTP_OPTION_ENABLE_HTTP_PROTOCOL, buffer)
198 | if err != nil {
199 | return nil, err
200 | }
201 | slog.Debug("set winhttp option", "option", "WINHTTP_OPTION_ENABLE_HTTP_PROTOCOL", "flags", fmt.Sprintf("%08b", uint32(flags)))
202 | }
203 | }
204 |
205 | // See if the Client's timeout value has been set
206 | // Windows winhttp default connection timeout is 60 seconds, use 0xFFFFFFFF for infinite
207 | if c.Timeout.Milliseconds() > 0 {
208 | buffer := make([]byte, 4)
209 | binary.LittleEndian.PutUint32(buffer, uint32(c.Timeout.Milliseconds()))
210 | err = WinHttpSetOption(hRequest, WINHTTP_OPTION_CONNECT_TIMEOUT, buffer)
211 | if err != nil {
212 | return nil, err
213 | }
214 | slog.Debug("set winhttp option", "option", "WINHTTP_OPTION_CONNECT_TIMEOUT", "time", uint32(c.Timeout.Milliseconds()))
215 | }
216 |
217 | // See if the response header timeout value has been set
218 | // Windows winhttp default timeout is 90 seconds
219 | if transport.ResponseHeaderTimeout.Milliseconds() > 0 {
220 | buffer := make([]byte, 4)
221 | binary.LittleEndian.PutUint32(buffer, uint32(transport.ResponseHeaderTimeout.Milliseconds()))
222 | err = WinHttpSetOption(hRequest, WINHTTP_OPTION_RECEIVE_RESPONSE_TIMEOUT, buffer)
223 | if err != nil {
224 | return nil, err
225 | }
226 | slog.Debug("set winhttp option", "option", "WINHTTP_OPTION_RECEIVE_RESPONSE_TIMEOUT", "time", uint32(transport.ResponseHeaderTimeout.Milliseconds()))
227 | }
228 |
229 | // See if the response maximum header length value has been set
230 | // Windows winhttp default maximum header size is 64kb
231 | if transport.MaxResponseHeaderBytes > 0 {
232 | buffer := make([]byte, 4)
233 | binary.LittleEndian.PutUint32(buffer, uint32(transport.MaxResponseHeaderBytes))
234 | err = WinHttpSetOption(hRequest, WINHTTP_OPTION_MAX_RESPONSE_HEADER_SIZE, buffer)
235 | if err != nil {
236 | return nil, err
237 | }
238 | slog.Debug("set winhttp option", "option", "WINHTTP_OPTION_MAX_RESPONSE_HEADER_SIZE", "time", uint32(transport.MaxResponseHeaderBytes))
239 | }
240 |
241 | // See if the request has any headers to be added
242 | if len(req.Header) > 0 {
243 | var headers string
244 | for k, v := range req.Header {
245 | // Each header except the last must be terminated by a carriage return/line feed (CR/LF)
246 | headers += fmt.Sprintf("%s: %s", k, strings.Join(v, ", "))
247 | headers = strings.TrimSuffix(headers, ", ")
248 | headers += "\r\n"
249 | }
250 | headers = strings.TrimSuffix(headers, "\r\n")
251 | err = WinHttpAddRequestHeaders(hRequest, headers, WINHTTP_ADDREQ_FLAG_ADD)
252 | if err != nil {
253 | return nil, err
254 | }
255 | }
256 |
257 | // See if there is any data to send
258 | reqBody, err := io.ReadAll(req.Body)
259 | if err != nil {
260 | return nil, err
261 | }
262 | optionalDataLength := len(reqBody)
263 |
264 | optionalData := uintptr(WINHTTP_NO_REQUEST_DATA)
265 | if optionalDataLength > 0 {
266 | optionalData = uintptr(unsafe.Pointer(&reqBody[0]))
267 | }
268 |
269 | context := unsafe.Pointer(uintptr(0))
270 |
271 | // Send the HTTP Request
272 | err = WinHttpSendRequest(hRequest, WINHTTP_NO_ADDITIONAL_HEADERS, 0, optionalData, uint32(optionalDataLength), uint32(optionalDataLength), uintptr(context))
273 | if err != nil {
274 | return nil, err
275 | }
276 |
277 | // Receive the HTTP Response
278 | err = WinHttpReceiveResponse(hRequest)
279 | if err != nil {
280 | return nil, err
281 | }
282 |
283 | // Get the HTTP Status Code e.g. 200
284 | var data []byte
285 | data, err = WinHttpQueryHeaders(hRequest, WINHTTP_QUERY_STATUS_CODE, "", 0)
286 | if err != nil {
287 | return nil, err
288 | }
289 |
290 | // Convert the status code to an integer and store it in the response
291 | var statusCode string
292 | statusCode, err = decodeUTF8(data)
293 | if err != nil {
294 | return nil, err
295 | }
296 | resp.StatusCode, err = strconv.Atoi(statusCode)
297 | if err != nil {
298 | return nil, fmt.Errorf("winhttp there was an error parsing '%s' to an integer: %s", statusCode, err)
299 | }
300 | slog.Debug("retrieved HTTP status code", "status code", resp.StatusCode)
301 |
302 | // Get the HTTP Status e.g. "200 OK"
303 | data, err = WinHttpQueryHeaders(hRequest, WINHTTP_QUERY_STATUS_TEXT, "", 0)
304 | if err != nil {
305 | return nil, err
306 | }
307 | var statusText string
308 | statusText, err = decodeUTF8(data)
309 | if err != nil {
310 | return nil, err
311 | }
312 | resp.Status = fmt.Sprintf("%s %s", statusCode, statusText)
313 | slog.Debug("retrieved HTTP status code text", "status code text", resp.Status)
314 |
315 | // Get the HTTP Protocol e.g. "HTTP/1.0"
316 | data, err = WinHttpQueryHeaders(hRequest, WINHTTP_QUERY_VERSION, "", 0)
317 | if err != nil {
318 | return nil, err
319 | }
320 | resp.Proto, err = decodeUTF8(data)
321 | if err != nil {
322 | return nil, err
323 | }
324 | slog.Debug("retrieved HTTP version", "version", resp.Proto)
325 |
326 | // Parse the HTTP Protocol Major e.g., 1 in HTTP/1.1
327 | index := strings.Index(resp.Proto, ".")
328 | resp.ProtoMajor, err = strconv.Atoi(resp.Proto[index-1 : index])
329 | if err != nil {
330 | return nil, fmt.Errorf("there was an error converting '%s' to an integer: %s", resp.Proto[index-1:index], err)
331 | }
332 |
333 | // Parse the HTTP Protocol Minor e.g., 0 in HTTP/1.0
334 | resp.ProtoMinor, err = strconv.Atoi(resp.Proto[index+1 : index+2])
335 | if err != nil {
336 | return nil, fmt.Errorf("there was an error converting '%s' to an integer: %s", resp.Proto[index+1:index+2], err)
337 | }
338 |
339 | // Get the HTTP Headers
340 | data, err = WinHttpQueryHeaders(hRequest, WINHTTP_QUERY_RAW_HEADERS_CRLF, "", 0)
341 | if err != nil {
342 | return nil, err
343 | }
344 | var headers string
345 | headers, err = decodeUTF8(data)
346 | if err != nil {
347 | return nil, err
348 | }
349 | slog.Debug("called WinHTTPQueryHeaders", "headers", headers)
350 |
351 | // Parse the headers
352 | resp.Header = http.Header{}
353 | for _, header := range strings.SplitAfter(headers, "\r\n") {
354 | i := strings.Index(header, ":")
355 | // Ignore headers that do not contain a colon (e.g., HTTP/1.1 200 OK)
356 | if i != -1 {
357 | // The 2 is to account for the space after the colon
358 | resp.Header.Add(header[:i], strings.Trim(header[i+2:], "\r\n"))
359 | }
360 | }
361 |
362 | // Loop over available data until completed
363 | var body []byte
364 | var i int
365 | for {
366 | // Do not use the return value of WinHttpQueryDataAvailable to determine whether the end of a response has been reached,
367 | // because not all servers terminate responses properly, and an improperly terminated response causes
368 | // WinHttpQueryDataAvailable to anticipate more data.
369 |
370 | // Get the size of the HTTP Response
371 | var n uint32
372 | n, err = WinHttpQueryDataAvailable(hRequest)
373 | if err != nil {
374 | return nil, err
375 | }
376 | slog.Debug("called WinHttpQueryDataAvailable", "data size", n, "loop count", i)
377 |
378 | // Read the HTTP Response data
379 | var respData []byte
380 | respData, err = WinHttpReadData(hRequest, n)
381 | if err != nil {
382 | return nil, err
383 | }
384 | slog.Debug("called WinHttpReadData", "data length", len(respData), "data", string(respData), "loop count", i)
385 |
386 | // When there is no more data, exit the loop
387 | if len(respData) <= 0 {
388 | break
389 | }
390 |
391 | // Add the data chunk to the response body
392 | body = append(body, respData...)
393 | i++
394 | }
395 |
396 | // Set the Content-Length
397 | cl, ok := resp.Header["Content-Length"]
398 | if ok {
399 | resp.ContentLength, err = strconv.ParseInt(strings.Join(cl, ""), 10, 64)
400 | if err != nil {
401 | return nil, fmt.Errorf("there was an error parsing '%s' to a string: %s", strings.Join(cl, ""), err)
402 | }
403 | } else {
404 | resp.ContentLength = int64(len(body))
405 | }
406 |
407 | // Set the response body
408 | resp.Body = io.NopCloser(bytes.NewReader(body))
409 |
410 | return &resp, nil
411 | }
412 |
413 | // Get issues an HTTP GET request to the specified URL and returns an HTTP response
414 | func (c *Client) Get(url string) (*http.Response, error) {
415 | slog.Debug("entering into *Client.Get function", "url", url)
416 | req, err := http.NewRequest("GET", url, nil)
417 | if err != nil {
418 | return nil, err
419 | }
420 | return c.Do(req)
421 | }
422 |
423 | // Head issues an HTTP HEAD request to the specified URL and returns an HTTP response
424 | func (c *Client) Head(url string) (resp *http.Response, err error) {
425 | slog.Debug("entering into *Client.Head function", "url", url)
426 | req, err := http.NewRequest("HEAD", url, nil)
427 | if err != nil {
428 | return nil, err
429 | }
430 | return c.Do(req)
431 | }
432 |
433 | // Post issues an HTTP POST request to specified URL and returns an HTTP response
434 | func (c *Client) Post(url, contentType string, body io.Reader) (resp *http.Response, err error) {
435 | slog.Debug("entering into *Client.Post function", "url", url, "contentType", contentType, "body", fmt.Sprintf("%T: %+v", body, body))
436 | req, err := http.NewRequest("POST", url, body)
437 | if err != nil {
438 | return nil, err
439 | }
440 |
441 | // Set up the content-type
442 | req.Header.Set("Content-Type", contentType)
443 |
444 | return c.Do(req)
445 | }
446 |
--------------------------------------------------------------------------------
/docs/CHANGELOG.MD:
--------------------------------------------------------------------------------
1 | # Changelog
2 | All notable changes to this project will be documented in this file.
3 |
4 | The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/)
5 | and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html).
6 |
7 | ## 1.0.0 - 2024-02-07
8 |
9 | - Initial release of the `winhttp` library
--------------------------------------------------------------------------------
/example/main.go:
--------------------------------------------------------------------------------
1 | //go:build windows
2 |
3 | package main
4 |
5 | import (
6 | // Standard
7 | "bytes"
8 | "crypto/tls"
9 | "flag"
10 | "fmt"
11 | "io"
12 | "log"
13 | "log/slog"
14 | "net/http"
15 | "os"
16 | "strings"
17 | "time"
18 |
19 | // Internal
20 | "github.com/Ne0nd0g/winhttp"
21 | )
22 |
23 | func main() {
24 | debug := flag.Bool("debug", false, "enable debug output")
25 | trace := flag.Bool("trace", false, "enable SourceKey for debug output")
26 | method := flag.String("method", "GET", "the HTTP METHOD for the request")
27 | url := flag.String("url", "https://httpbin.org/get", "the full URL for the request")
28 | httpData := flag.String("data", "", "data to send with the request")
29 | flag.Parse()
30 |
31 | // Setup logger
32 | opts := slog.HandlerOptions{}
33 | if *debug {
34 | opts.Level = slog.LevelDebug
35 | }
36 | if *trace {
37 | opts.AddSource = true
38 | }
39 | logger := slog.New(slog.NewJSONHandler(os.Stdout, &opts))
40 | slog.SetDefault(logger)
41 |
42 | // Build the HTTP
43 | slog.Info("building the HTTP request")
44 | req, err := http.NewRequest(strings.ToUpper(*method), *url, bytes.NewReader([]byte(*httpData)))
45 | if err != nil {
46 | log.Fatal(err)
47 | }
48 | req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36 Edg/121.0.0.0")
49 |
50 | // Get the HTTP client
51 | slog.Info("building the HTTP client")
52 | client, err := winhttp.NewHTTPClient()
53 | if err != nil {
54 | log.Fatal(err)
55 | }
56 |
57 | // Build TLS Client Config and add it to the client
58 | tlsConfig := tls.Config{
59 | InsecureSkipVerify: true, // #nosec G402 - InsecureSkipVerify is set to true on purpose
60 | NextProtos: []string{},
61 | MinVersion: tls.VersionTLS10,
62 | MaxVersion: tls.VersionTLS13,
63 | }
64 | transport := http.Transport{
65 | TLSClientConfig: &tlsConfig,
66 | TLSHandshakeTimeout: 240 * time.Second,
67 | MaxResponseHeaderBytes: 0,
68 | }
69 | client.Transport = &transport
70 |
71 | // Send the request
72 | slog.Info("sending the HTTP request", "method", *method, "url", *url)
73 | resp, err := client.Do(req)
74 | if err != nil {
75 | log.Fatal(err)
76 | }
77 | slog.Info("received HTTP response", "response", resp)
78 |
79 | n := int64(0)
80 | body := new(strings.Builder)
81 | if resp.Body != nil {
82 | n, err = io.Copy(body, resp.Body)
83 | if err != nil {
84 | log.Fatal(err)
85 | }
86 | }
87 |
88 | if n > 0 {
89 | slog.Info("received HTTP payload data", "data length", n)
90 | if *debug {
91 | fmt.Printf("[+] HTTP Data:\n%s\n", body)
92 | }
93 | }
94 | slog.Info("program finished running successfully and is exiting...")
95 | }
96 |
--------------------------------------------------------------------------------
/go.mod:
--------------------------------------------------------------------------------
1 | module github.com/Ne0nd0g/winhttp
2 |
3 | go 1.21
4 |
5 | require golang.org/x/sys v0.17.0
6 |
--------------------------------------------------------------------------------
/go.sum:
--------------------------------------------------------------------------------
1 | golang.org/x/sys v0.17.0 h1:25cE3gD+tdBA7lp7QfhuV+rJiE9YXTcS3VG1SqssI/Y=
2 | golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
3 |
--------------------------------------------------------------------------------
/qodana.yaml:
--------------------------------------------------------------------------------
1 | #-------------------------------------------------------------------------------#
2 | # Qodana analysis is configured by qodana.yaml file #
3 | # https://www.jetbrains.com/help/qodana/qodana-yaml.html #
4 | #-------------------------------------------------------------------------------#
5 | version: "1.0"
6 |
7 | #Specify inspection profile for code analysis
8 | profile:
9 | name: qodana.starter
10 |
11 | #Enable inspections
12 | #include:
13 | # - name:
14 |
15 | #Disable inspections
16 | #exclude:
17 | # - name:
18 | # paths:
19 | # -
20 |
21 | #Execute shell command before Qodana execution (Applied in CI/CD pipeline)
22 | #bootstrap: sh ./prepare-qodana.sh
23 |
24 | #Install IDE plugins before Qodana execution (Applied in CI/CD pipeline)
25 | #plugins:
26 | # - id: #(plugin id can be found at https://plugins.jetbrains.com)
27 |
28 | #Specify Qodana linter for analysis (Applied in CI/CD pipeline)
29 | linter: jetbrains/qodana-go:latest
30 |
--------------------------------------------------------------------------------
/utils.go:
--------------------------------------------------------------------------------
1 | //go:build windows
2 |
3 | /*
4 | Copyright (C) 2024 Russel Van Tuyl
5 |
6 | winhttp is free software: you can redistribute it and/or modify
7 | it under the terms of the GNU General Public License as published by
8 | the Free Software Foundation, either version 3 of the License, or
9 | any later version.
10 |
11 | winhttp is distributed in the hope that it will be useful,
12 | but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | GNU General Public License for more details.
15 |
16 | You should have received a copy of the GNU General Public License
17 | along with winhttp. If not, see .
18 | */
19 |
20 | // Package winhttp provides an HTTP client using the Windows WinHttp API
21 | package winhttp
22 |
23 | import (
24 | "fmt"
25 | "unicode/utf8"
26 | )
27 |
28 | // decodeUTF8 decodes a UTF8 string and returns it, removing null characters
29 | func decodeUTF8(b []byte) (string, error) {
30 | if !utf8.Valid(b) {
31 | return "", fmt.Errorf("invalid UTF8: '0x%x'", b)
32 | }
33 |
34 | var s string
35 |
36 | for len(b) > 0 {
37 | r, size := utf8.DecodeRune(b)
38 | // Exclude null bytes
39 | // For example U+3400 = '4' but is returned as two runes: '34' and '00'
40 | if r != rune(00) {
41 | s += string(r)
42 | }
43 | // Update the byte slice to start after this rune
44 | b = b[size:]
45 | }
46 | return s, nil
47 | }
48 |
--------------------------------------------------------------------------------
/winhttp.go:
--------------------------------------------------------------------------------
1 | //go:build windows
2 |
3 | /*
4 | Copyright (C) 2024 Russel Van Tuyl
5 |
6 | winhttp is free software: you can redistribute it and/or modify
7 | it under the terms of the GNU General Public License as published by
8 | the Free Software Foundation, either version 3 of the License, or
9 | any later version.
10 |
11 | winhttp is distributed in the hope that it will be useful,
12 | but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | GNU General Public License for more details.
15 |
16 | You should have received a copy of the GNU General Public License
17 | along with winhttp. If not, see .
18 | */
19 |
20 | // Package winhttp provides an HTTP client using the Windows WinHttp API
21 | package winhttp
22 |
23 | import (
24 | "errors"
25 | "fmt"
26 | "log/slog"
27 | "strings"
28 | "unsafe"
29 |
30 | "golang.org/x/sys/windows"
31 | )
32 |
33 | const (
34 | // WinHTTP!WinHttpOpen dwAccessType
35 | // https://learn.microsoft.com/en-us/windows/win32/api/winhttp/nf-winhttp-winhttpopen
36 | WINHTTP_ACCESS_TYPE_DEFAULT_PROXY = 0
37 | WINHTTP_ACCESS_TYPE_NO_PROXY = 1
38 | WINHTTP_ACCESS_TYPE_NAMED_PROXY = 3
39 | WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY = 4
40 |
41 | // WinHTTP pszProxyW
42 | WINHTTP_NO_PROXY_NAME = 0
43 |
44 | // WinHTTP pszProxyBypassW
45 | WINHTTP_NO_PROXY_BYPASS = 0
46 |
47 | // WinHTTP dwFlags
48 | WINHTTP_FLAG_NONE = 0x00000000
49 | WINHTTP_FLAG_ASYNC = 0x10000000
50 | WINHTTP_FLAG_SECURE_DEFAULTS = 0x30000000
51 | WINHTTP_FLAG_SECURE = 0x00800000
52 | WINHTTP_FLAG_ESCAPE_PERCENT = 0x00000004
53 | WINHTTP_FLAG_NULL_CODEPAGE = 0x00000008
54 | WINHTTP_FLAG_ESCAPE_DISABLE = 0x00000040
55 | WINHTTP_FLAG_ESCAPE_DISABLE_QUERY = 0x00000080
56 | WINHTTP_FLAG_BYPASS_PROXY_CACHE = 0x00000100
57 | WINHTTP_FLAG_REFRESH = WINHTTP_FLAG_BYPASS_PROXY_CACHE
58 | WINHTTP_FLAG_AUTOMATIC_CHUNKING = 0x00000200
59 |
60 | // INTERNET_PORT https://learn.microsoft.com/en-us/windows/win32/winhttp/internet-port
61 | INTERNET_DEFAULT_PORT = 0
62 | INTERNET_DEFAULT_HTTP_PORT = 80
63 | INTERNET_DEFAULT_HTTPS_PORT = 443
64 |
65 | WINHTTP_NO_ADDITIONAL_HEADERS = ""
66 |
67 | // HTTP Query Flags
68 | WINHTTP_QUERY_MIME_VERSION = 0
69 | WINHTTP_QUERY_CONTENT_TYPE = 1
70 | WINHTTP_QUERY_CONTENT_TRANSFER_ENCODING = 2
71 | WINHTTP_QUERY_CONTENT_ID = 3
72 | WINHTTP_QUERY_CONTENT_DESCRIPTION = 4
73 | WINHTTP_QUERY_CONTENT_LENGTH = 5
74 | WINHTTP_QUERY_CONTENT_LANGUAGE = 6
75 | WINHTTP_QUERY_ALLOW = 7
76 | WINHTTP_QUERY_PUBLIC = 8
77 | WINHTTP_QUERY_DATE = 9
78 | WINHTTP_QUERY_EXPIRES = 10
79 | WINHTTP_QUERY_LAST_MODIFIED = 11
80 | WINHTTP_QUERY_MESSAGE_ID = 12
81 | WINHTTP_QUERY_URI = 13
82 | WINHTTP_QUERY_DERIVED_FROM = 14
83 | WINHTTP_QUERY_COST = 15
84 | WINHTTP_QUERY_LINK = 16
85 | WINHTTP_QUERY_PRAGMA = 17
86 | WINHTTP_QUERY_VERSION = 18
87 | WINHTTP_QUERY_STATUS_CODE = 19
88 | WINHTTP_QUERY_STATUS_TEXT = 20
89 | WINHTTP_QUERY_RAW_HEADERS = 21
90 | WINHTTP_QUERY_RAW_HEADERS_CRLF = 22
91 | WINHTTP_QUERY_CONNECTION = 23
92 | WINHTTP_QUERY_ACCEPT = 24
93 | WINHTTP_QUERY_ACCEPT_CHARSET = 25
94 | WINHTTP_QUERY_ACCEPT_ENCODING = 26
95 | WINHTTP_QUERY_ACCEPT_LANGUAGE = 27
96 | WINHTTP_QUERY_AUTHORIZATION = 28
97 | WINHTTP_QUERY_CONTENT_ENCODING = 29
98 | WINHTTP_QUERY_FORWARDED = 30
99 | WINHTTP_QUERY_FROM = 31
100 | WINHTTP_QUERY_IF_MODIFIED_SINCE = 32
101 | WINHTTP_QUERY_LOCATION = 33
102 | WINHTTP_QUERY_ORIG_URI = 34
103 | WINHTTP_QUERY_REFERER = 35
104 | WINHTTP_QUERY_RETRY_AFTER = 36
105 | WINHTTP_QUERY_SERVER = 37
106 | WINHTTP_QUERY_TITLE = 38
107 | WINHTTP_QUERY_USER_AGENT = 39
108 | WINHTTP_QUERY_WWW_AUTHENTICATE = 40
109 | WINHTTP_QUERY_PROXY_AUTHENTICATE = 41
110 | WINHTTP_QUERY_ACCEPT_RANGES = 42
111 | WINHTTP_QUERY_SET_COOKIE = 43
112 | WINHTTP_QUERY_COOKIE = 44
113 | WINHTTP_QUERY_REQUEST_METHOD = 45
114 | WINHTTP_QUERY_REFRESH = 46
115 | WINHTTP_QUERY_CONTENT_DISPOSITION = 47
116 | WINHTTP_QUERY_AGE = 48
117 | WINHTTP_QUERY_CACHE_CONTROL = 49
118 | WINHTTP_QUERY_CONTENT_BASE = 50
119 | WINHTTP_QUERY_CONTENT_LOCATION = 51
120 | WINHTTP_QUERY_CONTENT_MD5 = 52
121 | WINHTTP_QUERY_CONTENT_RANGE = 53
122 | WINHTTP_QUERY_ETAG = 54
123 | WINHTTP_QUERY_HOST = 55
124 | WINHTTP_QUERY_IF_MATCH = 56
125 | WINHTTP_QUERY_IF_NONE_MATCH = 57
126 | WINHTTP_QUERY_IF_RANGE = 58
127 | WINHTTP_QUERY_IF_UNMODIFIED_SINCE = 59
128 | WINHTTP_QUERY_MAX_FORWARDS = 60
129 | WINHTTP_QUERY_PROXY_AUTHORIZATION = 61
130 | WINHTTP_QUERY_RANGE = 62
131 | WINHTTP_QUERY_TRANSFER_ENCODING = 63
132 | WINHTTP_QUERY_UPGRADE = 64
133 | WINHTTP_QUERY_VARY = 65
134 | WINHTTP_QUERY_VIA = 66
135 | WINHTTP_QUERY_WARNING = 67
136 | WINHTTP_QUERY_EXPECT = 68
137 | WINHTTP_QUERY_PROXY_CONNECTION = 69
138 | WINHTTP_QUERY_UNLESS_MODIFIED_SINCE = 70
139 | WINHTTP_QUERY_PROXY_SUPPORT = 75
140 | WINHTTP_QUERY_AUTHENTICATION_INFO = 76
141 | WINHTTP_QUERY_PASSPORT_URLS = 77
142 | WINHTTP_QUERY_PASSPORT_CONFIG = 78
143 | WINHTTP_QUERY_MAX = 78
144 | WINHTTP_QUERY_CUSTOM = 65535
145 | WINHTTP_QUERY_FLAG_REQUEST_HEADERS = 0x80000000
146 | WINHTTP_QUERY_FLAG_SYSTEMTIME = 0x40000000
147 | WINHTTP_QUERY_FLAG_NUMBER = 0x20000000
148 |
149 | WINHTTP_NO_OUTPUT_BUFFER = 0
150 |
151 | WINHTTP_NO_REFERER = ""
152 |
153 | WINHTTP_DEFAULT_ACCEPT_TYPES = ""
154 |
155 | WINHTTP_NO_REQUEST_DATA = 0
156 |
157 | WINHTTP_HEADER_NAME_BY_INDEX = ""
158 |
159 | WINHTTP_NO_HEADER_INDEX = 0
160 |
161 | // flags for WinHttp{Set/Query}Options
162 | WINHTTP_FIRST_OPTION = WINHTTP_OPTION_CALLBACK
163 | WINHTTP_OPTION_CALLBACK = 1
164 | WINHTTP_OPTION_RESOLVE_TIMEOUT = 2
165 | WINHTTP_OPTION_CONNECT_TIMEOUT = 3
166 | WINHTTP_OPTION_CONNECT_RETRIES = 4
167 | WINHTTP_OPTION_SEND_TIMEOUT = 5
168 | WINHTTP_OPTION_RECEIVE_TIMEOUT = 6
169 | WINHTTP_OPTION_RECEIVE_RESPONSE_TIMEOUT = 7
170 | WINHTTP_OPTION_HANDLE_TYPE = 9
171 | WINHTTP_OPTION_READ_BUFFER_SIZE = 12
172 | WINHTTP_OPTION_WRITE_BUFFER_SIZE = 13
173 | WINHTTP_OPTION_PARENT_HANDLE = 21
174 | WINHTTP_OPTION_EXTENDED_ERROR = 24
175 | WINHTTP_OPTION_SECURITY_FLAGS = 31
176 | WINHTTP_OPTION_SECURITY_CERTIFICATE_STRUCT = 32
177 | WINHTTP_OPTION_URL = 34
178 | WINHTTP_OPTION_SECURITY_KEY_BITNESS = 36
179 | WINHTTP_OPTION_PROXY = 38
180 | WINHTTP_OPTION_PROXY_RESULT_ENTRY = 39
181 | WINHTTP_OPTION_USER_AGENT = 41
182 | WINHTTP_OPTION_CONTEXT_VALUE = 45
183 | WINHTTP_OPTION_CLIENT_CERT_CONTEXT = 47
184 | WINHTTP_OPTION_REQUEST_PRIORITY = 58
185 | WINHTTP_OPTION_HTTP_VERSION = 59
186 | WINHTTP_OPTION_DISABLE_FEATURE = 63
187 | WINHTTP_OPTION_CODEPAGE = 68
188 | WINHTTP_OPTION_MAX_CONNS_PER_SERVER = 73
189 | WINHTTP_OPTION_MAX_CONNS_PER_1_0_SERVER = 74
190 | WINHTTP_OPTION_AUTOLOGON_POLICY = 77
191 | WINHTTP_OPTION_SERVER_CERT_CONTEXT = 78
192 | WINHTTP_OPTION_ENABLE_FEATURE = 79
193 | WINHTTP_OPTION_WORKER_THREAD_COUNT = 80
194 | WINHTTP_OPTION_PASSPORT_COBRANDING_TEXT = 81
195 | WINHTTP_OPTION_PASSPORT_COBRANDING_URL = 82
196 | WINHTTP_OPTION_CONFIGURE_PASSPORT_AUTH = 83
197 | WINHTTP_OPTION_SECURE_PROTOCOLS = 84
198 | WINHTTP_OPTION_ENABLETRACING = 85
199 | WINHTTP_OPTION_PASSPORT_SIGN_OUT = 86
200 | WINHTTP_OPTION_PASSPORT_RETURN_URL = 87
201 | WINHTTP_OPTION_REDIRECT_POLICY = 88
202 | WINHTTP_OPTION_MAX_HTTP_AUTOMATIC_REDIRECTS = 89
203 | WINHTTP_OPTION_MAX_HTTP_STATUS_CONTINUE = 90
204 | WINHTTP_OPTION_MAX_RESPONSE_HEADER_SIZE = 91
205 | WINHTTP_OPTION_MAX_RESPONSE_DRAIN_SIZE = 92
206 | WINHTTP_OPTION_CONNECTION_INFO = 93
207 | WINHTTP_OPTION_CLIENT_CERT_ISSUER_LIST = 94
208 | WINHTTP_OPTION_SPN = 96
209 | WINHTTP_OPTION_GLOBAL_PROXY_CREDS = 97
210 | WINHTTP_OPTION_GLOBAL_SERVER_CREDS = 98
211 | WINHTTP_OPTION_UNLOAD_NOTIFY_EVENT = 99
212 | WINHTTP_OPTION_REJECT_USERPWD_IN_URL = 100
213 | WINHTTP_OPTION_USE_GLOBAL_SERVER_CREDENTIALS = 101
214 | WINHTTP_OPTION_RECEIVE_PROXY_CONNECT_RESPONSE = 103
215 | WINHTTP_OPTION_IS_PROXY_CONNECT_RESPONSE = 104
216 | WINHTTP_OPTION_SERVER_SPN_USED = 106
217 | WINHTTP_OPTION_PROXY_SPN_USED = 107
218 | WINHTTP_OPTION_SERVER_CBT = 108
219 | WINHTTP_OPTION_UNSAFE_HEADER_PARSING = 110
220 | WINHTTP_OPTION_ASSURED_NON_BLOCKING_CALLBACKS = 111
221 | WINHTTP_OPTION_UPGRADE_TO_WEB_SOCKET = 114
222 | WINHTTP_OPTION_WEB_SOCKET_CLOSE_TIMEOUT = 115
223 | WINHTTP_OPTION_WEB_SOCKET_KEEPALIVE_INTERVAL = 116
224 | WINHTTP_OPTION_DECOMPRESSION = 118
225 | WINHTTP_OPTION_WEB_SOCKET_RECEIVE_BUFFER_SIZE = 122
226 | WINHTTP_OPTION_WEB_SOCKET_SEND_BUFFER_SIZE = 123
227 | WINHTTP_OPTION_TCP_PRIORITY_HINT = 128
228 | WINHTTP_OPTION_CONNECTION_FILTER = 131
229 | WINHTTP_OPTION_ENABLE_HTTP_PROTOCOL = 133
230 | WINHTTP_OPTION_HTTP_PROTOCOL_USED = 134
231 | WINHTTP_OPTION_KDC_PROXY_SETTINGS = 136
232 | WINHTTP_OPTION_ENCODE_EXTRA = 138
233 | WINHTTP_OPTION_DISABLE_STREAM_QUEUE = 139
234 | WINHTTP_OPTION_IPV6_FAST_FALLBACK = 140
235 | WINHTTP_OPTION_CONNECTION_STATS_V0 = 141
236 | WINHTTP_OPTION_REQUEST_TIMES = 142
237 | WINHTTP_OPTION_EXPIRE_CONNECTION = 143
238 | WINHTTP_OPTION_DISABLE_SECURE_PROTOCOL_FALLBACK = 144
239 | WINHTTP_OPTION_HTTP_PROTOCOL_REQUIRED = 145
240 | WINHTTP_OPTION_REQUEST_STATS = 146
241 | WINHTTP_OPTION_SERVER_CERT_CHAIN_CONTEXT = 147
242 | WINHTTP_LAST_OPTION = WINHTTP_OPTION_SERVER_CERT_CHAIN_CONTEXT
243 | WINHTTP_OPTION_USERNAME = 0x1000
244 | WINHTTP_OPTION_PASSWORD = 0x1001
245 | WINHTTP_OPTION_PROXY_USERNAME = 0x1002
246 | WINHTTP_OPTION_PROXY_PASSWORD = 0x1003
247 |
248 | SECURITY_FLAG_IGNORE_UNKNOWN_CA = 0x00000100
249 | SECURITY_FLAG_IGNORE_CERT_DATE_INVALID = 0x00002000
250 | SECURITY_FLAG_IGNORE_CERT_CN_INVALID = 0x00001000
251 | SECURITY_FLAG_IGNORE_CERT_WRONG_USAGE = 0x00000200
252 | SECURITY_FLAG_SECURE = 0x00000001
253 | SECURITY_FLAG_STRENGTH_WEAK = 0x10000000
254 | SECURITY_FLAG_STRENGTH_MEDIUM = 0x40000000
255 | SECURITY_FLAG_STRENGTH_STRONG = 0x20000000
256 |
257 | WINHTTP_PROTOCOL_FLAG_HTTP1 = 0x0
258 | WINHTTP_PROTOCOL_FLAG_HTTP2 = 0x1
259 | WINHTTP_PROTOCOL_FLAG_HTTP3 = 0x2
260 |
261 | WINHTTP_FLAG_SECURE_PROTOCOL_SSL2 = 0x00000008
262 | WINHTTP_FLAG_SECURE_PROTOCOL_SSL3 = 0x00000020
263 | WINHTTP_FLAG_SECURE_PROTOCOL_TLS1 = 0x00000080
264 | WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_1 = 0x00000200
265 | WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_2 = 0x00000800
266 | WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_3 = 0x00002000
267 | WINHTTP_FLAG_SECURE_PROTOCOL_ALL = WINHTTP_FLAG_SECURE_PROTOCOL_SSL2 | WINHTTP_FLAG_SECURE_PROTOCOL_SSL3 | WINHTTP_FLAG_SECURE_PROTOCOL_TLS1
268 |
269 | WINHTTP_ADDREQ_FLAG_ADD_IF_NEW = 0x10000000
270 | WINHTTP_ADDREQ_FLAG_ADD = 0x20000000
271 | WINHTTP_ADDREQ_FLAG_COALESCE_WITH_COMMA = 0x40000000
272 | WINHTTP_ADDREQ_FLAG_COALESCE_WITH_SEMICOLON = 0x01000000
273 | WINHTTP_ADDREQ_FLAG_COALESCE = WINHTTP_ADDREQ_FLAG_COALESCE_WITH_COMMA
274 | WINHTTP_ADDREQ_FLAG_REPLACE = 0x80000000
275 | )
276 |
277 | var winhttp = windows.NewLazySystemDLL("winhttp.dll")
278 |
279 | // WinHttpOpen initializes, for an application, the use of WinHTTP functions and returns a WinHTTP-session handle.
280 | //
281 | // https://learn.microsoft.com/en-us/windows/win32/api/winhttp/nf-winhttp-winhttpopen
282 | //
283 | // userAgent is a string that contains the name of the application or entity calling the WinHTTP functions.
284 | // This name is used as the user agent in the HTTP protocol.
285 | //
286 | // accessType is the type of access required. This can be one of the following values:
287 | //
288 | // WINHTTP_ACCESS_TYPE_NO_PROXY - Resolves all host names directly without a proxy
289 | // WINHTTP_ACCESS_TYPE_DEFAULT_PROXY - Important Use of this option is deprecated on Windows 8.1 and newer.
290 | // Use WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY instead.
291 | // WINHTTP_ACCESS_TYPE_NAMED_PROXY - Passes requests to the proxy unless a proxy bypass list is supplied and the name
292 | // to be resolved bypasses the proxy. In this case, this function uses the values passed for pwszProxyName and pwszProxyBypass.
293 | // WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY - Uses system and per-user proxy settings (including the Internet Explorer proxy configuration)
294 | // to determine which proxy/proxies to use. Automatically attempts to handle failover between multiple proxies, different proxy
295 | // configurations per interface, and authentication. Supported in Windows 8.1 and newer.
296 | //
297 | // proxy is a string variable that contains the name of the proxy server to use when proxy access is specified by setting
298 | //
299 | // dwAccessType to WINHTTP_ACCESS_TYPE_NAMED_PROXY. The WinHTTP functions recognize only CERN type proxies for HTTP.
300 | // If dwAccessType is not set to WINHTTP_ACCESS_TYPE_NAMED_PROXY, this parameter must be set to WINHTTP_NO_PROXY_NAME.
301 | //
302 | // proxyBypass is a string variable that contains an optional semicolon delimited list of host names or IP addresses, or both,
303 | //
304 | // that should not be routed through the proxy when dwAccessType is set to WINHTTP_ACCESS_TYPE_NAMED_PROXY.
305 | // The list can contain wildcard characters. Do not use an empty string, because the WinHttpOpen function uses it as the proxy bypass list.
306 | // If this parameter specifies the "" macro in the list as the only entry, this function bypasses any host name that does not contain
307 | // a period. If dwAccessType is not set to WINHTTP_ACCESS_TYPE_NAMED_PROXY, this parameter must be set to WINHTTP_NO_PROXY_BYPASS.
308 | //
309 | // flags contains the flags that indicate various options affecting the behavior of this function.
310 | //
311 | // This parameter can have the following value:
312 | // WINHTTP_FLAG_ASYNC - Use the WinHTTP functions asynchronously.
313 | // By default, all WinHTTP functions that use the returned HINTERNET handle are performed synchronously.
314 | // When this flag is set, the caller needs to specify a callback function through WinHttpSetStatusCallback.
315 | // WINHTTP_FLAG_SECURE_DEFAULTS - When this flag is set, WinHttp will require use of TLS 1.2 or newer.
316 | // If the caller attempts to enable older TLS versions by setting WINHTTP_OPTION_SECURE_PROTOCOLS, it will fail with ERROR_ACCESS_DENIED.
317 | // Additionally, TLS fallback will be disabled. Note that setting this flag also sets flag WINHTTP_FLAG_ASYNC.
318 | func WinHttpOpen(userAgent string, accessType int, proxy string, proxyBypass string, flags uint32) (windows.Handle, error) {
319 | slog.Debug("entering into WinHttpOpen function", "user-agent", userAgent, "accessType", accessType, "proxy", proxy, "proxyBypass", proxyBypass, "flags", flags)
320 |
321 | // Convert useragent to a wide string
322 | pszAgentW, err := windows.UTF16PtrFromString(userAgent)
323 | if err != nil {
324 | slog.Error("there was an error converting userAgent to a UTF16 pointer", "userAgent", userAgent, "error", err)
325 | return 0, fmt.Errorf("winhttp WinHttpOpen(): there was an error converting the userAgent value '%s' to a UTF16 pointer: %s", userAgent, err)
326 | }
327 |
328 | dwAccessType := uint32(accessType)
329 |
330 | // Convert proxy and proxyBypass to a wide string
331 | var pszProxyW *uint16
332 | var pszProxyBypassW *uint16
333 | if accessType != WINHTTP_ACCESS_TYPE_NAMED_PROXY {
334 | p := uint16(WINHTTP_NO_PROXY_NAME)
335 | pszProxyW = &p
336 | slog.Debug("the access type was NOT set to WINHTTP_ACCESS_TYPE_NAMED_PROXY forcing proxy to be set to WINHTTP_NO_PROXY_NAME", "access type", accessType, "proxy", proxy)
337 |
338 | b := uint16(WINHTTP_NO_PROXY_BYPASS)
339 | pszProxyBypassW = &b
340 | slog.Debug("the access type was NOT set to WINHTTP_ACCESS_TYPE_NAMED_PROXY forcing proxyBypass to be set to WINHTTP_NO_PROXY_BYPASS", "access type", accessType, "proxyBypass", proxyBypass)
341 | } else {
342 | pszProxyW, err = windows.UTF16PtrFromString(proxy)
343 | if err != nil {
344 | slog.Error("there was an error converting proxy to a UTF16 pointer", "proxy", proxy, "error", err)
345 | return 0, fmt.Errorf("winhttp WinHttpOpen(): there was an error converting the proxy value '%s' to a UTF16 pointer: %s", proxy, err)
346 | }
347 |
348 | if proxyBypass != "" {
349 | pszProxyBypassW, err = windows.UTF16PtrFromString(proxyBypass)
350 | if err != nil {
351 | slog.Error("there was an error converting proxyBypass to a UTF16 pointer", "proxyBypass", proxyBypass, "error", err)
352 | return 0, fmt.Errorf("winhttp WinHttpOpen(): there was an error converting the proxyBypass value '%s' to a UTF16 pointer: %s", proxyBypass, err)
353 | }
354 | } else {
355 | b := uint16(WINHTTP_NO_PROXY_BYPASS)
356 | pszProxyBypassW = &b
357 | }
358 | }
359 |
360 | dwFlags := flags
361 |
362 | proc := winhttp.NewProc("WinHttpOpen")
363 | // WINHTTPAPI HINTERNET WinHttpOpen(
364 | // [in, optional] LPCWSTR pszAgentW,
365 | // [in] DWORD dwAccessType,
366 | // [in] LPCWSTR pszProxyW,
367 | // [in] LPCWSTR pszProxyBypassW,
368 | // [in] DWORD dwFlags
369 | // );
370 | r, _, err := proc.Call(
371 | uintptr(unsafe.Pointer(pszAgentW)),
372 | uintptr(dwAccessType),
373 | uintptr(unsafe.Pointer(pszProxyW)),
374 | uintptr(unsafe.Pointer(pszProxyBypassW)),
375 | uintptr(dwFlags),
376 | )
377 | if !errors.Is(err, windows.ERROR_SUCCESS) {
378 | slog.Error("there was an error calling winhttp!WinHttpOpen", "error", err)
379 | return 0, fmt.Errorf("winhttp WinHttpOpen(): there was an error calling winhttp!WinHttpOpen: %s", err)
380 | }
381 | if r == 0 {
382 | return 0, fmt.Errorf("the winhttp!WinHttpOpen function returned 0")
383 | }
384 | return windows.Handle(r), nil
385 | }
386 |
387 | // WinHttpConnect specifies the initial target server of an HTTP request and returns an
388 | // HINTERNET connection handle to an HTTP session for that initial target.
389 | //
390 | // https://learn.microsoft.com/en-us/windows/win32/api/winhttp/nf-winhttp-winhttpconnect
391 | //
392 | // hSession is a valid HINTERNET WinHTTP session handle returned by a previous call to WinHttpOpen.
393 | //
394 | // serverName is a string that contains the host name of an HTTP server.
395 | //
396 | // Alternately, the string can contain the IP address of the site in ASCII, for example, 10.0.1.45.
397 | // Note that WinHttp does not accept international host names without converting them first to Punycode
398 | //
399 | // serverPort is an unsigned integer that specifies the TCP/IP port on the server to which a connection is made.
400 | //
401 | // This parameter can be any valid TCP/IP port number, or one of the following values:
402 | // INTERNET_DEFAULT_HTTP_PORT - INTERNET_DEFAULT_HTTP_PORT
403 | // INTERNET_DEFAULT_HTTPS_PORT - Uses the default port for HTTPS servers (port 443).
404 | // Selecting this port does not automatically establish a secure connection.
405 | // You must still specify the use of secure transaction semantics by using the WINHTTP_FLAG_SECURE flag with WinHttpOpenRequest.
406 | // INTERNET_DEFAULT_PORT - Uses port 80 for HTTP and port 443 for Secure Hypertext Transfer Protocol (HTTPS).
407 | func WinHttpConnect(hSession windows.Handle, serverName string, serverPort uint32) (windows.Handle, error) {
408 | slog.Debug("entering into WinHttpConnect function", "session", hSession, "serverName", serverName, "serverPort", serverPort)
409 |
410 | // Convert server name to a LPCWSTR (uint16 pointer)
411 | pswzServerName, err := windows.UTF16PtrFromString(serverName)
412 | if err != nil {
413 | slog.Error("there was an error converting serverName to a UTF16 pointer", "serverName", serverName, "error", err)
414 | return 0, fmt.Errorf("winhttp WinHttpConnect(): there was an error converting the server name '%s' to a UTF16 pointer: %s", serverName, err)
415 | }
416 |
417 | nServerPort := serverPort
418 |
419 | proc := winhttp.NewProc("WinHttpConnect")
420 | // WINHTTPAPI HINTERNET WinHttpConnect(
421 | // [in] HINTERNET hSession,
422 | // [in] LPCWSTR pswzServerName,
423 | // [in] INTERNET_PORT nServerPort,
424 | // [in] DWORD dwReserved
425 | // );
426 | r, _, err := proc.Call(
427 | uintptr(hSession),
428 | uintptr(unsafe.Pointer(pswzServerName)),
429 | uintptr(nServerPort),
430 | 0,
431 | )
432 |
433 | if !errors.Is(err, windows.ERROR_SUCCESS) {
434 | slog.Error("there was an error calling winhttp!WinHttpConnect", "error", err)
435 | return 0, fmt.Errorf("there was an error calling winhttp!WinHttpConnect: %s", err)
436 | }
437 | if r == 0 {
438 | return 0, fmt.Errorf("the winhttp!WinHttpConnect function returned 0")
439 | }
440 | return windows.Handle(r), nil
441 | }
442 |
443 | // WinHttpOpenRequest creates an HTTP request handle
444 | //
445 | // https://learn.microsoft.com/en-us/windows/win32/api/winhttp/nf-winhttp-winhttpopenrequest
446 | //
447 | // hConnect is a connection handle to an HTTP session returned by WinHttpConnect
448 | //
449 | // method is a string that contains the HTTP verb to use in the request. If this parameter is empty, the function uses GET as the HTTP verb
450 | //
451 | // path is a string that contains the name of the target resource of the specified HTTP verb. This is generally a file name, an executable module, or a search specifier.
452 | //
453 | // version is a string that contains the HTTP version. If this parameter is empty, the function uses HTTP/1.1.
454 | //
455 | // referrer a string that specifies the URL of the document from which the URL in the request pwszObjectName was obtained.
456 | //
457 | // If this parameter is set to WINHTTP_NO_REFERER, no referring document is specified
458 | //
459 | // acceptTypes an array of strings that specifies media types accepted by the client.
460 | //
461 | // If this parameter is set to WINHTTP_DEFAULT_ACCEPT_TYPES, no types are accepted by the client.
462 | // Typically, servers handle a lack of accepted types as indication that the client accepts only documents of type "text/*";
463 | // that is, only text documents—no pictures or other binary files. For a list of valid media types, see Media Types defined
464 | // by IANA at http://www.iana.org/assignments/media-types/
465 | //
466 | // flags contains the Internet flag values. This can be one or more of the following values:
467 | //
468 | // WINHTTP_FLAG_BYPASS_PROXY_CACHE - This flag provides the same behavior as WINHTTP_FLAG_REFRESH.
469 | // WINHTTP_FLAG_ESCAPE_DISABLE - Unsafe characters in the URL passed in for pwszObjectName are not converted to escape sequences.
470 | // WINHTTP_FLAG_ESCAPE_DISABLE_QUERY - Unsafe characters in the query component of the URL passed in for pwszObjectName are not converted to escape sequences.
471 | // WINHTTP_FLAG_ESCAPE_PERCENT - The string passed in for pwszObjectName is converted from an LPCWSTR to an LPSTR. All unsafe characters are converted to an
472 | // escape sequence including the percent symbol. By default, all unsafe characters except the percent symbol are converted to an escape sequence.
473 | // WINHTTP_FLAG_NULL_CODEPAGE - The string passed in for pwszObjectName is assumed to consist of valid ANSI characters represented by WCHAR.
474 | // No check are done for unsafe characters.
475 | // Windows 7: This option is obsolete.
476 | // WINHTTP_FLAG_REFRESH - Indicates that the request should be forwarded to the originating server rather than sending a cached version of a resource from a proxy server.
477 | // When this flag is used, a "Pragma: no-cache" header is added to the request handle. When creating an HTTP/1.1 request header, a "Cache-Control: no-cache" is also added.
478 | // WINHTTP_FLAG_SECURE - Uses secure transaction semantics. This translates to using Secure Sockets Layer (SSL)/Transport Layer Security (TLS).
479 | func WinHttpOpenRequest(hConnect windows.Handle, method string, path string, version string, referrer string, accessTypes []string, flags uint32) (windows.Handle, error) {
480 | slog.Debug("entering into WinHttpOpenRequest function", "hConnect", hConnect, "method", method, "path", path, "version", version, "referrer", referrer, "accessTypes", accessTypes, "flags", flags)
481 |
482 | // Convert HTTP method to LPCWSTR
483 | pwszVerb, err := windows.UTF16PtrFromString(strings.ToUpper(method))
484 | if err != nil {
485 | slog.Error("there was an error converting method to a UTF16 pointer", "method", method, "error", err)
486 | return 0, fmt.Errorf("winhttp WinHttpOpenRequest(): there was an error converting the HTTP method '%s' to a UTF16 pointer: %s", method, err)
487 | }
488 |
489 | // Convert the URI to LPCWSTR
490 | pwszObjectName, err := windows.UTF16PtrFromString(path)
491 | if err != nil {
492 | slog.Error("there was an error converting path to a UTF16 pointer", "path", path, "error", err)
493 | return 0, fmt.Errorf("winhttp WinHttpOpenRequest(): there was an error converting the path '%s' to a UTF16 pointer: %s", path, err)
494 | }
495 |
496 | // Convert the version to LPCWSTR
497 | var pwszVersion *uint16
498 | if version == "" {
499 | NULL := uint16(0)
500 | pwszVersion = &NULL
501 | } else {
502 | pwszVersion, err = windows.UTF16PtrFromString(version)
503 | if err != nil {
504 | slog.Error("there was an error converting version to a UTF16 pointer", "version", version, "error", err)
505 | return 0, fmt.Errorf("winhttp WinHttpOpenRequest(): there was an error converting the version '%s' to a UTF16 pointer: %s", version, err)
506 | }
507 | }
508 |
509 | // Convert the version to LPCWSTR
510 | pwszReferrer, err := windows.UTF16PtrFromString(referrer)
511 | if err != nil {
512 | slog.Error("there was an error converting referrer to a UTF16 pointer", "referrer", referrer, "error", err)
513 | return 0, fmt.Errorf("winhttp WinHttpOpenRequest(): there was an error converting the referrer '%s' to a UTF16 pointer: %s", referrer, err)
514 | }
515 |
516 | // convert acceptTypes to LPCWSTR
517 | // Pointer to a null-terminated array of string pointers that specifies media types accepted by the client
518 | var ppwszAcceptTypes []*uint16
519 | if len(accessTypes) > 0 {
520 | for i, acceptType := range accessTypes {
521 | var pwszAcceptType *uint16
522 | // An empty string will cause the Accept header to be added to the request with no value
523 | if acceptType == "" {
524 | if i == 0 {
525 | ppwszAcceptTypes = []*uint16{nil}
526 | continue
527 | }
528 | // Adding an empty string to the array causes it to be null-terminated in that spot
529 | // and the rest of the array is ignored. So we just break out of the loop here.
530 | continue
531 | }
532 | pwszAcceptType, err = windows.UTF16PtrFromString(acceptType)
533 | if err != nil {
534 | slog.Error("there was an error converting acceptType to a UTF16 pointer", "acceptType", acceptType, "error", err)
535 | return 0, fmt.Errorf("winhttp WinHttpOpenRequest(): there was an error converting the acceptType '%s' to a UTF16 pointer: %s", acceptType, err)
536 | }
537 | ppwszAcceptTypes = append(ppwszAcceptTypes, pwszAcceptType)
538 | }
539 | } else {
540 | ppwszAcceptTypes = []*uint16{nil}
541 | }
542 |
543 | dwFlags := flags
544 |
545 | winhttpopenrequest := winhttp.NewProc("WinHttpOpenRequest")
546 | // WINHTTPAPI HINTERNET WinHttpOpenRequest(
547 | // [in] HINTERNET hConnect,
548 | // [in] LPCWSTR pwszVerb,
549 | // [in] LPCWSTR pwszObjectName,
550 | // [in] LPCWSTR pwszVersion,
551 | // [in] LPCWSTR pwszReferrer,
552 | // [in] LPCWSTR *ppwszAcceptTypes,
553 | // [in] DWORD dwFlags
554 | // );
555 | r, _, err := winhttpopenrequest.Call(
556 | uintptr(hConnect),
557 | uintptr(unsafe.Pointer(pwszVerb)),
558 | uintptr(unsafe.Pointer(pwszObjectName)),
559 | uintptr(unsafe.Pointer(pwszVersion)),
560 | uintptr(unsafe.Pointer(pwszReferrer)),
561 | uintptr(unsafe.Pointer(&ppwszAcceptTypes[0])),
562 | uintptr(dwFlags),
563 | )
564 |
565 | if !errors.Is(err, windows.ERROR_SUCCESS) {
566 | slog.Error("there was an error calling winhttp!WinHttpOpenRequest", "error", err)
567 | return 0, fmt.Errorf("there was an error calling winhttp!WinHttpOpenRequest: %s", err)
568 | }
569 | if r == 0 {
570 | return 0, fmt.Errorf("the winhttp!WinHttpOpenRequest function returned 0")
571 | }
572 |
573 | return windows.Handle(r), nil
574 | }
575 |
576 | // WinHttpSendRequest sends the specified request to the HTTP server
577 | //
578 | // https://learn.microsoft.com/en-us/windows/win32/api/winhttp/nf-winhttp-winhttpsendrequest
579 | //
580 | // hRequest is an HINTERNET handle returned by WinHttpOpenRequest.
581 | //
582 | // headers an string that contains the additional headers to append to the request.
583 | //
584 | // This parameter can be WINHTTP_NO_ADDITIONAL_HEADERS if there are no additional headers to append.
585 | //
586 | // headersLength contains the length, in characters, of the additional headers.
587 | //
588 | // If this parameter is -1L and pwszHeaders is not NULL, this function assumes that pwszHeaders is null-terminated, and the length is calculated.
589 | //
590 | // optionalData is a pointer a buffer that contains any optional data to send immediately after the request headers.
591 | //
592 | // This parameter is generally used for POST and PUT operations.
593 | // The optional data can be the resource or data posted to the server.
594 | // This parameter can be WINHTTP_NO_REQUEST_DATA if there is no optional data to send.
595 | // If the dwOptionalLength parameter is 0, this parameter is ignored and set to NULL.
596 | // This buffer must remain available until the request handle is closed or the call to WinHttpReceiveResponse has completed.
597 | //
598 | // optionalDataLen is an unsigned long integer value that contains the length, in bytes, of the optional data.
599 | //
600 | // This parameter can be zero if there is no optional data to send.
601 | // This parameter must contain a valid length when the lpOptional parameter is not NULL. Otherwise, lpOptional is ignored and set to NULL.
602 | //
603 | // totalLen is an unsigned long integer value that contains the length, in bytes, of the total data sent.
604 | //
605 | // This parameter specifies the Content-Length header of the request.
606 | // If the value of this parameter is greater than the length specified by dwOptionalLength, then WinHttpWriteData can be used to send additional data.
607 | // dwTotalLength must not change between calls to WinHttpSendRequest for the same request.
608 | // If dwTotalLength needs to be changed, the caller should create a new request.
609 | //
610 | // context A pointer to a pointer-sized variable that contains an application-defined value that is passed, with the request handle, to any callback functions.
611 | func WinHttpSendRequest(hRequest windows.Handle, headers string, headersLength uint32, optionalData uintptr, optionalDataLen uint32, totalLen uint32, context uintptr) error {
612 | slog.Debug("entering into WinHttpSendRequest function", "hRequest", hRequest, "headers", headers, "optioanlData", optionalData, "optionalDataLen", optionalDataLen, "totalLen", totalLen, "context", context)
613 |
614 | // Convert headers to LPCWSTR
615 | lpszHeaders, err := windows.UTF16PtrFromString(headers)
616 | if err != nil {
617 | slog.Error("there was an error converting headers to a UTF16 pointer", "headers", headers, "error", err)
618 | return fmt.Errorf("winhttp WinHttpSendRequest(): there was an error converting the headers '%s' to a UTF16 pointer: %s", headers, err)
619 | }
620 |
621 | dwHeadersLength := headersLength
622 |
623 | lpOptional := optionalData
624 | dwOptionalLength := optionalDataLen
625 | dwTotalLength := totalLen
626 | dwContext := context
627 |
628 | proc := winhttp.NewProc("WinHttpSendRequest")
629 | // WINHTTPAPI BOOL WinHttpSendRequest(
630 | // [in] HINTERNET hRequest,
631 | // [in, optional] LPCWSTR lpszHeaders,
632 | // [in] DWORD dwHeadersLength,
633 | // [in, optional] LPVOID lpOptional,
634 | // [in] DWORD dwOptionalLength,
635 | // [in] DWORD dwTotalLength,
636 | // [in] DWORD_PTR dwContext
637 | // );
638 | r, _, err := proc.Call(
639 | uintptr(hRequest),
640 | uintptr(unsafe.Pointer(lpszHeaders)),
641 | uintptr(dwHeadersLength),
642 | lpOptional,
643 | uintptr(dwOptionalLength),
644 | uintptr(dwTotalLength),
645 | dwContext,
646 | )
647 |
648 | if !errors.Is(err, windows.ERROR_SUCCESS) {
649 | slog.Error("there was an error calling winhttp!WinHttpSendRequest", "error", err)
650 | return fmt.Errorf("winhttp there was an error calling winhttp!WinHttpSendRequest: %s", err)
651 | }
652 | // Returns TRUE if successful, or FALSE otherwise
653 | if r == 0 {
654 | return fmt.Errorf("the winhttp!WinHttpSendRequest function returned 0")
655 | }
656 | return nil
657 | }
658 |
659 | // WinHttpReceiveResponse waits to receive the response to an HTTP request initiated by WinHttpSendRequest.
660 | // When WinHttpReceiveResponse completes successfully, the status code and response headers have been received and are available for
661 | // the application to inspect using WinHttpQueryHeaders.
662 | // An application must call WinHttpReceiveResponse before it can use WinHttpQueryDataAvailable and WinHttpReadData to access the
663 | // response entity body (if any).
664 | //
665 | // https://learn.microsoft.com/en-us/windows/win32/api/winhttp/nf-winhttp-winhttpreceiveresponse
666 | //
667 | // hRequest an HINTERNET handle returned by WinHttpOpenRequest and sent by WinHttpSendRequest.
668 | //
669 | // Wait until WinHttpSendRequest has completed for this handle before calling WinHttpReceiveResponse.
670 | func WinHttpReceiveResponse(hRequest windows.Handle) error {
671 | slog.Debug("entering into WinHttpReceiveResponse function", "hRequest", hRequest)
672 | proc := winhttp.NewProc("WinHttpReceiveResponse")
673 | // WINHTTPAPI BOOL WinHttpReceiveResponse(
674 | // [in] HINTERNET hRequest,
675 | // [in] LPVOID lpReserved
676 | // );
677 | r, _, err := proc.Call(uintptr(hRequest), 0)
678 | if !errors.Is(err, windows.ERROR_SUCCESS) {
679 | slog.Error("there was an error calling winhttp!WinHttpReceiveResponse", "error", err)
680 | return fmt.Errorf("winhttp there was an error calling winhttp!WinHttpReceiveResponse: %s", err)
681 | }
682 | // Returns TRUE if successful, or FALSE otherwise
683 | if r == 0 {
684 | return fmt.Errorf("the winhttp!WinHttpReceiveResponse function returned 0")
685 | }
686 | return nil
687 | }
688 |
689 | // WinHttpReadData reads data from a handle opened by the WinHttpOpenRequest function.
690 | //
691 | // https://learn.microsoft.com/en-us/windows/win32/api/winhttp/nf-winhttp-winhttpreaddata
692 | //
693 | // hRequest is a valid HINTERNET handle returned from a previous call to WinHttpOpenRequest.
694 | // WinHttpReceiveResponse or WinHttpQueryDataAvailable must have been called for this handle
695 | // and must have completed before WinHttpReadData is called.
696 | // Although calling WinHttpReadData immediately after completion of WinHttpReceiveResponse avoids the expense
697 | // of a buffer copy, doing so requires that the application use a fixed-length buffer for reading.
698 | //
699 | // size is the number of bytes to read
700 | func WinHttpReadData(hRequest windows.Handle, size uint32) ([]byte, error) {
701 | slog.Debug("entering into WinHttpReadData function", "hRequest", hRequest, "size", size)
702 | // WinHttpQueryDataAvailable returns 0 when there is nothing left to read, but this function must be called to determine if finished
703 | // Size 0 buffer causes error
704 | if size == 0 {
705 | size = 1
706 | }
707 |
708 | lpBuffer := make([]byte, size)
709 | dwNumberOfBytesToRead := size
710 | lpdwNumberOfBytesRead := uint32(0)
711 |
712 | proc := winhttp.NewProc("WinHttpReadData")
713 | // WINHTTPAPI BOOL WinHttpReadData(
714 | // [in] HINTERNET hRequest,
715 | // [out] LPVOID lpBuffer,
716 | // [in] DWORD dwNumberOfBytesToRead,
717 | // [out] LPDWORD lpdwNumberOfBytesRead
718 | // );
719 | r, _, err := proc.Call(
720 | uintptr(hRequest),
721 | uintptr(unsafe.Pointer(&lpBuffer[0])),
722 | uintptr(dwNumberOfBytesToRead),
723 | uintptr(unsafe.Pointer(&lpdwNumberOfBytesRead)),
724 | )
725 | if !errors.Is(err, windows.ERROR_SUCCESS) {
726 | slog.Error("there was an error calling winhttp!WinHttpReadData", "error", err)
727 | return []byte{}, fmt.Errorf("there was an error calling winhttp!WinHttpReadData: %s", err)
728 | }
729 | // Returns TRUE if successful, or FALSE otherwise
730 | if r == 0 {
731 | return []byte{}, fmt.Errorf("the winhttp!WinHttpReadData function returned 0")
732 | }
733 |
734 | // If you are using WinHttpReadData synchronously, and the return value is TRUE and the number of bytes read is zero,
735 | // the transfer has been completed and there are no more bytes to read on the handle.
736 | if lpdwNumberOfBytesRead == 0 {
737 | return []byte{}, nil
738 | }
739 |
740 | return lpBuffer, nil
741 | }
742 |
743 | // WinHttpQueryDataAvailable returns the amount of data, in bytes, available to be read with WinHttpReadData.
744 | //
745 | // https://learn.microsoft.com/en-us/windows/win32/api/winhttp/nf-winhttp-winhttpquerydataavailable
746 | //
747 | // hRequest a valid HINTERNET handle returned by WinHttpOpenRequest.
748 | // WinHttpReceiveResponse must have been called for this handle and have completed before WinHttpQueryDataAvailable is called.
749 | func WinHttpQueryDataAvailable(hRequest windows.Handle) (uint32, error) {
750 | slog.Debug("entering into WinHttpQueryDataAvailable function", "hRequest", hRequest)
751 | lpdwNumberOfBytesAvailable := uint32(0)
752 |
753 | proc := winhttp.NewProc("WinHttpQueryDataAvailable")
754 | // WINHTTPAPI BOOL WinHttpQueryDataAvailable(
755 | // [in] HINTERNET hRequest,
756 | // [out] LPDWORD lpdwNumberOfBytesAvailable
757 | // );
758 | r, _, err := proc.Call(
759 | uintptr(hRequest),
760 | uintptr(unsafe.Pointer(&lpdwNumberOfBytesAvailable)),
761 | )
762 | if !errors.Is(err, windows.ERROR_SUCCESS) {
763 | slog.Error("there was an error calling winhttp!WinHttpQueryDataAvailable", "error", err)
764 | return lpdwNumberOfBytesAvailable, fmt.Errorf("there was an error calling winhttp!WinHttpQueryDataAvailable: %s", err)
765 | }
766 | // Returns TRUE if successful, or FALSE otherwise
767 | if r == 0 {
768 | return lpdwNumberOfBytesAvailable, fmt.Errorf("the winhttp!WinHttpQueryDataAvailable function returned 0")
769 | }
770 | return lpdwNumberOfBytesAvailable, nil
771 | }
772 |
773 | // WinHttpQueryHeaders retrieves header information associated with an HTTP request.
774 | //
775 | // https://learn.microsoft.com/en-us/windows/win32/api/winhttp/nf-winhttp-winhttpqueryheaders
776 | //
777 | // hRequest is an HINTERNET request handle returned by WinHttpOpenRequest.
778 | //
779 | // WinHttpReceiveResponse must have been called for this handle and have completed before WinHttpQueryHeaders is called.
780 | //
781 | // infoLevel specifies a combination of attribute and modifier flags listed on the Query Info Flags page.
782 | // These attribute and modifier flags indicate that the information is being requested and how it is to be formatted.
783 | // https://learn.microsoft.com/en-us/windows/win32/winhttp/query-info-flags
784 | //
785 | // header a string that contains the header name.
786 | // If the flag in dwInfoLevel is not WINHTTP_QUERY_CUSTOM, set this parameter to WINHTTP_HEADER_NAME_BY_INDEX.
787 | //
788 | // index used to enumerate multiple headers with the same name.
789 | // When calling the function, this parameter is the index of the specified header to return.
790 | // When the function returns, this parameter is the index of the next header.
791 | // If the next index cannot be found, ERROR_WINHTTP_HEADER_NOT_FOUND is returned.
792 | // Set this parameter to WINHTTP_NO_HEADER_INDEX to specify that only the first occurrence of a header should be returned.
793 | func WinHttpQueryHeaders(hRequest windows.Handle, infoLevel uint32, header string, index uint32) ([]byte, error) {
794 | slog.Debug("entering into WinHttpQueryHeaders function", "hRequest", hRequest, "info level", infoLevel, "header", header, "index", index)
795 | dwInfoLevel := infoLevel
796 |
797 | // lpBuffer is a pointer to the buffer that receives the information.
798 | // Setting this parameter to WINHTTP_NO_OUTPUT_BUFFER causes this function to return FALSE.
799 | // Calling GetLastError then returns ERROR_INSUFFICIENT_BUFFER and lpdwBufferLength contains the number of bytes required to hold the requested information.
800 | var lpBuffer []byte
801 |
802 | // lpdwBufferLength Pointer to a value of type DWORD that specifies the length of the data buffer, in bytes.
803 | // When the function returns, this parameter contains the pointer to a value that specifies the length of the information written to the buffer.
804 | // When the function returns strings, the following rules apply.
805 | // If the function succeeds, lpdwBufferLength specifies the length of the string, in bytes, minus 2 for the terminating null.
806 | // If the function fails and ERROR_INSUFFICIENT_BUFFER is returned, lpdwBufferLength specifies the number of bytes that the application must allocate to receive the string.
807 | var lpdwBufferLength int64
808 |
809 | // pwszName - Pointer to a string that contains the header name.
810 | // If the flag in dwInfoLevel is not WINHTTP_QUERY_CUSTOM, set this parameter to WINHTTP_HEADER_NAME_BY_INDEX.
811 | var pwszName *uint16
812 | var err error
813 | if header != "" {
814 | pwszName, err = windows.UTF16PtrFromString(header)
815 | if err != nil {
816 | slog.Error("there was an error converting the header string to a UTF16 pointer", "header", header, "error", err)
817 | return lpBuffer, fmt.Errorf("WinHttpQueryHeader there was an error converting '%s' to a LPCWSTR: %s", header, err)
818 | }
819 | }
820 |
821 | proc := winhttp.NewProc("WinHttpQueryHeaders")
822 | // WINHTTPAPI BOOL WinHttpQueryHeaders(
823 | // [in] HINTERNET hRequest,
824 | // [in] DWORD dwInfoLevel,
825 | // [in, optional] LPCWSTR pwszName,
826 | // [out] LPVOID lpBuffer,
827 | // [in, out] LPDWORD lpdwBufferLength,
828 | // [in, out] LPDWORD lpdwIndex
829 | // );
830 |
831 | // Call first time get the buffer size
832 | r, _, err := proc.Call(
833 | uintptr(hRequest),
834 | uintptr(dwInfoLevel),
835 | uintptr(unsafe.Pointer(pwszName)),
836 | WINHTTP_NO_OUTPUT_BUFFER,
837 | uintptr(unsafe.Pointer(&lpdwBufferLength)),
838 | uintptr(unsafe.Pointer(&index)),
839 | )
840 | // First run returns ERROR_INSUFFICIENT_BUFFER and lpdwBufferLength contains the number of bytes required to hold the requested information.
841 | if !errors.Is(err, windows.ERROR_INSUFFICIENT_BUFFER) {
842 | slog.Error("there was an error calling winhttp!WinHttpQueryHeaders with WINHTTP_NO_OUTPUT_BUFFER to determine the data size", "error", err)
843 | return lpBuffer, fmt.Errorf("winhttp there was an error calling winhttp!WinHttpQueryHeaders 1: %s", err)
844 | }
845 | // Returns TRUE (0) if successful, or FALSE (1) otherwise.
846 | // This one should return false with ERROR_INSUFFICIENT_BUFFER error and the lpdwBufferLength set
847 | if r == 1 {
848 | return lpBuffer, fmt.Errorf("the winhttp!WinHttpQueryHeaders function returned 1")
849 | }
850 |
851 | // Adjust the buffer size
852 | lpBuffer = make([]byte, lpdwBufferLength)
853 |
854 | // Call second time to get actual data
855 | r, _, err = proc.Call(
856 | uintptr(hRequest),
857 | uintptr(dwInfoLevel),
858 | uintptr(unsafe.Pointer(pwszName)),
859 | uintptr(unsafe.Pointer(&lpBuffer[0])),
860 | uintptr(unsafe.Pointer(&lpdwBufferLength)),
861 | uintptr(unsafe.Pointer(&index)),
862 | )
863 | if !errors.Is(err, windows.ERROR_SUCCESS) {
864 | slog.Error("there was an error calling winHttpQueryHeaders to receive the data", "error", err)
865 | return lpBuffer, fmt.Errorf("winhttp there was an error calling winhttp!WinHttpQueryHeaders 2: %s", err)
866 | }
867 | if r == 0 {
868 | return lpBuffer, fmt.Errorf("the winhttp!WinHttpQueryHeaders function returned 0")
869 | }
870 | return lpBuffer, nil
871 | }
872 |
873 | // WinHttpCloseHandle closes a single HINTERNET handle
874 | //
875 | // https://learn.microsoft.com/en-us/windows/win32/api/winhttp/nf-winhttp-winhttpclosehandle
876 | //
877 | // hInternet is a valid HINTERNET handle (see HINTERNET Handles in WinHTTP) to be closed.
878 | // https://learn.microsoft.com/en-us/windows/win32/winhttp/hinternet-handles-in-winhttp
879 | func WinHttpCloseHandle(hInternet windows.Handle) {
880 | slog.Debug("entering into WinHttpCloseHandle function", "hInternet", hInternet)
881 | proc := winhttp.NewProc("WinHttpCloseHandle")
882 | // // WINHTTPAPI BOOL WinHttpCloseHandle(
883 | // [in] HINTERNET hInternet
884 | // );
885 | r, _, err := proc.Call(uintptr(hInternet))
886 | if !errors.Is(err, windows.ERROR_SUCCESS) {
887 | slog.Error("there was an error calling winhttp!WinHttpCloseHandle", "error", err)
888 | return
889 | }
890 | // Returns TRUE if the handle is successfully closed, otherwise FALSE
891 | if r != 1 {
892 | slog.Error("winhttp!WinHttpCloseHandle returned something other than TRUE", "return", r)
893 | }
894 | }
895 |
896 | // WinHttpSetOption set an internal option
897 | //
898 | // https://learn.microsoft.com/en-us/windows/win32/api/winhttp/nf-winhttp-winhttpsetoption
899 | //
900 | // hInternet is the HINTERNET handle on which to set data.
901 | // Be aware that this can be either a Session handle or a Request handle, depending on what option is being set.
902 | // For more information about how to determine which handle is appropriate to use in setting a particular option, see the Option Flags.
903 | //
904 | // option contains the Internet option to set. This can be one of the Option Flags values.
905 | // https://learn.microsoft.com/en-us/windows/win32/winhttp/option-flags
906 | //
907 | // buffer a pointer to a buffer that contains the option setting.
908 | //
909 | // size contains the length of the buffer.
910 | // The length of the buffer is specified in characters for the following options;
911 | // for all other options, the length is specified in bytes.
912 | func WinHttpSetOption(hInternet windows.Handle, option uint32, buffer []byte) error {
913 | slog.Debug("entering into WinHttpSetOption function", "hInternet", hInternet, "option", option, "buffer", fmt.Sprintf("(%d) 0x%X", len(buffer), buffer))
914 | dwOption := option
915 | lpBuffer := buffer
916 | dwBufferLength := uint32(len(buffer))
917 |
918 | proc := winhttp.NewProc("WinHttpSetOption")
919 | // WINHTTPAPI BOOL WinHttpSetOption(
920 | // [in] HINTERNET hInternet,
921 | // [in] DWORD dwOption,
922 | // [in] LPVOID lpBuffer,
923 | // [in] DWORD dwBufferLength
924 | // );
925 | r, _, err := proc.Call(
926 | uintptr(hInternet),
927 | uintptr(dwOption),
928 | uintptr(unsafe.Pointer(&lpBuffer[0])),
929 | uintptr(dwBufferLength),
930 | )
931 | if !errors.Is(err, windows.ERROR_SUCCESS) {
932 | slog.Error("there was an error calling winhttp!WinHttpSetOption", "option", option, "buffer", fmt.Sprintf("0x%X", buffer), "error", err)
933 | return fmt.Errorf("winhttp there was an error calling winhttp!WinHttpSetOption: %s", err)
934 | }
935 | // Returns TRUE if the handle is successfully closed, otherwise FALSE
936 | if r == 0 {
937 | return fmt.Errorf("the winhttp!WinHttpSetOption function returned 0")
938 | }
939 | return nil
940 | }
941 |
942 | // WinHttpAddRequestHeaders adds one or more HTTP request headers to the HTTP request handle.
943 | //
944 | // https://learn.microsoft.com/en-us/windows/win32/api/winhttp/nf-winhttp-winhttpaddrequestheaders
945 | //
946 | // hRequest is a valid HINTERNET request handle returned by WinHttpOpenRequest.
947 | //
948 | // headers a string that contains the headers to add to the request.
949 | // Each header except the last must be terminated by a carriage return/line feed (CR/LF).
950 | //
951 | // modifiers the flags used to modify the semantics of this function.
952 | // Can be one or more of the following flags:
953 | // WINHTTP_ADDREQ_FLAG_ADD - Adds the header if it does not exist. Used with WINHTTP_ADDREQ_FLAG_REPLACE.
954 | // WINHTTP_ADDREQ_FLAG_ADD_IF_NEW - Adds the header only if it does not already exist; otherwise, an error is returned.
955 | // WINHTTP_ADDREQ_FLAG_COALESCE - Merges headers of the same name.
956 | // WINHTTP_ADDREQ_FLAG_COALESCE_WITH_COMMA - Merges headers of the same name using a comma. For example, adding "Accept: text/*" followed by "Accept: audio/*" with this flag results in a single header "Accept: text/*, audio/*". This causes the first header found to be merged. The calling application must to ensure a cohesive scheme with respect to merged and separate headers.
957 | // WINHTTP_ADDREQ_FLAG_COALESCE_WITH_SEMICOLON - Merges headers of the same name using a semicolon.
958 | // WINHTTP_ADDREQ_FLAG_REPLACE - Replaces or removes a header. If the header value is empty and the header is found, it is removed. If the value is not empty, it is replaced.
959 | func WinHttpAddRequestHeaders(hRequest windows.Handle, headers string, modifiers uint32) error {
960 | slog.Debug("entering into WinHttpAddRequestHeaders function", "hRequest", hRequest, "headers", headers, "modifiers", fmt.Sprintf("%08b", modifiers))
961 |
962 | var lpszHeaders *uint16
963 | var err error
964 | // Convert the headers string to a UTF16 pointer
965 | if headers != "" {
966 | lpszHeaders, err = windows.UTF16PtrFromString(headers)
967 | if err != nil {
968 | slog.Error("there was an error converting the header string to a UTF16 pointer", "headers", headers, "error", err)
969 | return fmt.Errorf("WinHttpAddRequestHeaders there was an error converting '%s' to a LPCWSTR: %s", headers, err)
970 | }
971 | }
972 |
973 | dwHeadersLength := uint32(len(headers))
974 | dwModifiers := modifiers
975 |
976 | proc := winhttp.NewProc("WinHttpAddRequestHeaders")
977 | // WINHTTPAPI BOOL WinHttpAddRequestHeaders(
978 | // [in] HINTERNET hRequest,
979 | // [in] LPCWSTR lpszHeaders,
980 | // [in] DWORD dwHeadersLength,
981 | // [in] DWORD dwModifiers
982 | // );
983 | r, _, err := proc.Call(
984 | uintptr(hRequest),
985 | uintptr(unsafe.Pointer(lpszHeaders)),
986 | uintptr(dwHeadersLength),
987 | uintptr(dwModifiers),
988 | )
989 | if !errors.Is(err, windows.ERROR_SUCCESS) {
990 | slog.Error("there was an error calling winhttp!WinHttpAddRequestHeaders", "headers", headers, "modifiers", fmt.Sprintf("%08b", modifiers), "error", err)
991 | return fmt.Errorf("winhttp there was an error calling winhttp!WinHttpAddRequestHeaders: %s", err)
992 | }
993 | // Returns TRUE if the handle is successfully closed, otherwise FALSE
994 | if r == 0 {
995 | return fmt.Errorf("the winhttp!WinHttpAddRequestHeaders function returned 0")
996 | }
997 | return nil
998 | }
999 |
--------------------------------------------------------------------------------